From 9bd7d4f223e6e51dd3e6556a9bc73bf6f8240de8 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 23 Nov 2026 15:53:12 -0500 Subject: [PATCH 01/19] Test PyPI and RubyGems vendored mode beside a Bazel hub on real Bazel Tests only. rules_python's `pip.parse` and rules_ruby's `ruby.bundle_fetch` hand a lock of the checkout to Bazel. The real-Bazel flows ran hosted mode beside both hubs, and vendored mode beside the Python one (pypi::vendored_pip_parse, which holds `vex` to saying that the build is not the patched one). No flow ran vendored mode for a gem, and the PyPI flow did not build between its undo and its hosted scan. ruby::vendored_bundle_fetch records what the command does today, in the fixture of the hosted flow (rules_ruby 1.0.0-rc2; the call names the `Gemfile` and the `Gemfile.lock` of the root). `scan --mode vendored --yes` exits 0 with status `success` and one package applied. It commits the unpacked gem with its specification and the ledger under `.socket/vendor/gem/`, gives the gem's declaration in `Gemfile` a `path:`, and moves the gem's entry of `Gemfile.lock` into a `PATH` section. The next `bazel build` fails in the `bundle install` action of the hub. rules_ruby copies the two files into a repository of Bazel's and runs Bundler there, which stops with The path `/external//.socket/vendor/gem//sp-victim-1.0.0` does not exist. `vex` attests the gem as patched meanwhile: it reads the committed copy, and what rules_ruby builds from one is not judged. `vendor --revert` puts every file back, and the build with them. pypi::vendored_pip_parse now names the failure it asserts. rules_python makes the name of a repository from the path of the vendored line, and Bazel stops with `invalid user-provided repo name 'pip_311__/_socket/vendor/pypi//spvictim_1_0_0_py2_py3_none_any_whl'`. The flow also builds right after `vendor --revert`: the unpatched build is back before hosted mode pins the patch. Both flows pass on Bazel 9.3.2 with the product code as it is. Each compares the tool's message without white space: Bundler breaks its message at the width of the console it runs in, which differs from one machine to the next. The two Ruby flows share their stand-in. `Served::to` builds the gems of a run, serves them, grants the patch and routes Bazel's downloads, as the hosted flow did inline. The grant now holds what the patch service grants for a gem: the patched gem with a sha512, and its specification. Vendored mode downloads both, and hosted mode neither. The record of the patch holds the hashes of the gem's one file, in place of the placeholders of the shared stand-in. bazel-ruby.yml says in its header that the legs run both modes, and a pull request that changes vendor/gem.rs now starts them: the file was in the list of the pushes to main alone. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-ruby.yml | 43 +- .../tests/e2e_bazel_build/pypi.rs | 65 +-- .../tests/e2e_bazel_build/ruby.rs | 373 ++++++++++++++---- 3 files changed, 353 insertions(+), 128 deletions(-) diff --git a/.github/workflows/bazel-ruby.yml b/.github/workflows/bazel-ruby.yml index 1615b3a12..b6e1e3352 100644 --- a/.github/workflows/bazel-ruby.yml +++ b/.github/workflows/bazel-ruby.yml @@ -1,8 +1,8 @@ name: Bazel patch compatibility (RubyGems) -# The RubyGems flow of the real-Bazel tests (`ruby::` in `e2e_bazel_build`): -# hosted mode for a gem that rules_ruby's `ruby.bundle_fetch` reads from -# `Gemfile` and `Gemfile.lock`, on each Bazel release below. +# The RubyGems flows of the real-Bazel tests (`ruby::` in `e2e_bazel_build`): +# hosted and vendored mode for a gem that rules_ruby's `ruby.bundle_fetch` +# reads from `Gemfile` and `Gemfile.lock`, on each Bazel release below. # bazel-compatibility.yml holds the legs and what every ecosystem shares; # this file says when the Ruby legs run and on which releases. # @@ -22,14 +22,16 @@ name: Bazel patch compatibility (RubyGems) on: pull_request: types: [opened, synchronize, reopened, ready_for_review] - # What a pull request run covers: the RubyGems flow and its fixture, the - # harness and the workflows that run it, the Bazel installer and its - # pins, and the RubyGems files that `scan --mode hosted` and `rollback` - # run through in the fixture, each by its own path: the readers of a - # Bundler lock and a Gemfile with the lock half of the hosted rewrite - # (formats/gem), lock discovery, the lock inventory, the Ruby crawler - # (it says which lock Bundler loads), the upstream restore of - # `rollback`, and the stale-install guard that both commands end with. + # What a pull request run covers: the RubyGems flows and their fixture, + # the harness and the workflows that run it, the Bazel installer and its + # pins, and the RubyGems files that `scan --mode hosted`, `rollback`, + # `scan --mode vendored` and `vendor --revert` run through in the + # fixture, each by its own path: the readers of a Bundler lock and a + # Gemfile with the lock half of the hosted rewrite (formats/gem), lock + # discovery, the lock inventory, the Ruby crawler (it says which lock + # Bundler loads), the upstream restore of `rollback`, the stale-install + # guard that those commands end with, and the vendored backend + # (vendor/gem.rs). # Last, the VEX code: `vex/` of the core, the files of the `vex` # command, and `bazel/` of the core, which reads the workspace files and # decides whether Bazel builds what was patched. Every flow holds the @@ -43,13 +45,13 @@ on: # hosted rewrite is there (`rewrite_gem` and its planner in # patch/redirect/mod.rs, the file of every ecosystem's rewriter), and # so are patch/redirect/grant.rs, hosted/engine.rs and - # commands/scan/hosted.rs, the shared test helpers and the toolchain - # files. vendor/gem.rs is the vendored backend, which the flow only - # borrows two readers of a `gem` line from. A change to one of those + # commands/scan/hosted.rs, the rest of vendored mode (the download from + # the patch service, the ledger, the `vendor` command), the shared test + # helpers and the toolchain files. A change to one of those # gets its run on the push to main (when the file is in the list below) # or in the nightly run, not on the pull request: that is the price of - # not running every ecosystem's legs on every shared change. The flow - # does not run the native extension rebuild of agent mode + # not running every ecosystem's legs on every shared change. No flow + # runs the native extension rebuild of agent mode # (patch/gem_ext.rs, patch/gem_source.rs), which is in neither list. On # demand, workflow_dispatch runs the legs on any branch. paths: @@ -66,6 +68,7 @@ on: - 'crates/socket-patch-core/src/crawlers/ruby_crawler.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' + - 'crates/socket-patch-core/src/vendor/gem.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/src/commands/vex*.rs' @@ -74,9 +77,9 @@ on: # The pull request paths, and what only a push to main covers: the # root of the test target (it changes when an ecosystem's module is # added; ci.yml builds the target and runs its hermetic tests on every - # pull request), the vendored backend, the shared engine code and test - # helpers the flow runs through, and the toolchain files. A main push - # outside this list waits for the nightly run below. + # pull request), the shared engine code and test helpers the flows run + # through, and the toolchain files. A main push outside this list waits + # for the nightly run below. paths: - '.github/workflows/bazel-ruby.yml' - '.github/workflows/bazel-compatibility.yml' @@ -91,11 +94,11 @@ on: - 'crates/socket-patch-core/src/crawlers/ruby_crawler.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' + - 'crates/socket-patch-core/src/vendor/gem.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/src/commands/vex*.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - - 'crates/socket-patch-core/src/vendor/gem.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' - 'crates/socket-patch-cli/src/commands/**' diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs index 336469dea..06f8bb082 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs @@ -48,8 +48,9 @@ //! `vendor --revert` has put the pin back. The flow asserts that; that //! every form of `vex` meanwhile writes a document that says the package //! is affected, and names the call of `MODULE.bazel` that reads the file; -//! and that the revert and hosted mode, which the document names, end in -//! the patched build and in a document that says not affected. +//! that the revert brings the unpatched build back; and that hosted mode, +//! which the document names, ends in the patched build and in a document +//! that says not affected. //! //! One loopback server stands in for four hosts. The Socket API and the //! patch host answer at their own paths; `pypi.org` (the project pages of @@ -710,20 +711,13 @@ fn vendors_the_wheel(cell: &Cell, with: &Vendoring) -> Tree { vendored } -/// What the document of an affected package tells the user to do, in the -/// checkout of `cell` that vendored mode patched: `vendor --revert` puts -/// every file back as it was in `before`, and `scan --mode hosted --yes` -/// then pins the patch of `with` in `requirements.txt`. Its document and -/// the one of `vex` attest the package, through the pin. -fn reverts_and_pins(cell: &Cell, with: &Vendoring, before: &Tree) { - let test = &cell.test; +/// The second thing the document of an affected package tells the user to +/// do, in the checkout of `cell` whose files `vendor --revert` has put back +/// as they were in `before`: `scan --mode hosted --yes` pins the patch of +/// `with` in `requirements.txt`. Its document and the one of `vex` attest +/// the package, through the pin. +fn pins(cell: &Cell, with: &Vendoring, before: &Tree) { let run = |cell: &Cell, args: &[&str]| with.run(cell, args); - let undo = run(cell, &["vendor", "--revert", "--yes"]); - let said = &undo.dump; - assert_eq!(undo.code, 0, "{test}: {said}"); - assert_eq!(undo.envelope["summary"]["removed"], 1, "{test}: {said}"); - assert_eq!(changed(before, &cell.tree()), NOTHING, "{test}: {said}"); - let claim = Claim::new(PURL, &with.uuid, How::Hosted); let document = cell.document("hosted"); let hosted = ["scan", "--mode", "hosted", "--yes"]; @@ -747,11 +741,11 @@ fn reverts_and_pins(cell: &Cell, with: &Vendoring, before: &Tree) { /// rules_python takes the path of that line for the name of a project /// and leaves the hub without a repository it can name. No build holds /// the patched wheel, and `vex` says affected again. -/// - (d) What the document says to do ([`reverts_and_pins`]): -/// `vendor --revert` puts every file back, `scan --mode hosted --yes` -/// pins the patch in `requirements.txt`, the same two Bazel commands -/// print the patched marker, and `vex` attests the package as not -/// affected. +/// - (d) What the document says to do: `vendor --revert` puts every file +/// back, and the same two Bazel commands print the unpatched marker +/// again. `scan --mode hosted --yes` then pins the patch in +/// `requirements.txt` ([`pins`]), the two commands print the patched +/// marker, and `vex` attests the package as not affected. #[test] #[ignore = "real Bazel; run with --ignored"] fn vendored_pip_parse() { @@ -772,11 +766,18 @@ fn vendored_pip_parse() { let vendored = vendors_the_wheel(&cell, &with); // (c) The build fails on the line that names the committed wheel, and - // changes no file of the checkout. + // changes no file of the checkout: rules_python makes the name of a + // repository from the path, and Bazel takes no such name. A console + // may break the message, so it is compared without white space. let build = cell.bazel("build", &[CONSUMER]); - let named = with.patched.filename().replace(['-', '.'], "_"); + let named = format!( + "invalid user-provided repo name 'pip_311__/_socket/vendor/pypi/{}/{}'", + with.uuid.replace('-', "_"), + with.patched.filename().replace(['-', '.'], "_") + ); + let squeezed = |text: &str| text.split_whitespace().collect::(); assert!( - !build.ok() && build.stderr().contains(&named), + !build.ok() && squeezed(&build.stderr()).contains(&squeezed(&named)), "{test}: the build did not fail on the vendored line ({named}):\n{}", build.dump() ); @@ -785,8 +786,11 @@ fn vendored_pip_parse() { let names = names(&cell); cell.stands_alone(run, &Claim::unbuilt(PURL, &with.uuid, &names), true); - // (d) The way out: the undo, then hosted mode, whose pin Bazel builds. - reverts_and_pins(&cell, &with, &before); + // (d) The way out: the undo, which brings the files and the build + // back, then hosted mode, whose pin Bazel builds. + let undo = run(&cell, &["vendor", "--revert", "--yes"]); + cell.undone(&undo, "removed", &before, UNPATCHED); + pins(&cell, &with, &before); let marker = format!("OUT: PATCHED {}", with.uuid); cell.builds(&marker); let claim = Claim::new(PURL, &with.uuid, How::Hosted); @@ -794,9 +798,9 @@ fn vendored_pip_parse() { println!( "{test}: Bazel {release} built {UNPATCHED:?}, and failed to build after `scan --mode \ - vendored`, while every form of `vex` said the package is affected; after `vendor \ - --revert` and `scan --mode hosted` it built {marker:?}, and `vex` said it is not \ - affected; {:?}", + vendored` ({named}), while every form of `vex` said the package is affected; after \ + `vendor --revert` it built {UNPATCHED:?} again, and after `scan --mode hosted` \ + {marker:?}, and `vex` said it is not affected; {:?}", started.elapsed() ); } @@ -851,7 +855,10 @@ fn a_vendored_wheel_is_affected_beside_a_hub_that_reads_the_requirements() { } assert_eq!(changed(&vendored, &cell.tree()), NOTHING); - reverts_and_pins(&cell, &with, &before); + let undo = with.run(&cell, &["vendor", "--revert", "--yes"]); + assert_eq!(undo.envelope["summary"]["removed"], 1, "{}", undo.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); + pins(&cell, &with, &before); // `vendor` in a checkout of hosted pins commits a copy of each: the // line of `requirements.txt` points at the wheel again. diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs index 1e1eb046a..60de2e0a9 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -1,10 +1,10 @@ -//! Hosted mode for a gem that comes through rules_ruby's +//! Hosted and vendored mode for a gem that comes through rules_ruby's //! `ruby.bundle_fetch(gemfile = "//:Gemfile", gemfile_lock = "//:Gemfile.lock")` //! under Bzlmod, where `MODULE.bazel` gives no `gem_checksums` and //! `Gemfile.lock` has a `CHECKSUMS` section. //! -//! One flow, on the Bazel the run is given ([`FIXTURE`] says which ruleset -//! goes with its release), in a fresh output base: +//! The hosted flow, on the Bazel the run is given ([`FIXTURE`] says which +//! ruleset goes with its release), in a fresh output base: //! //! - (a) `bazel build` and `bazel run //:consumer` print the unpatched //! marker, and Bazel fetched the upstream gem from the stand-in. @@ -26,6 +26,13 @@ //! //! The flow asserts the VEX document of its patch as `main.rs` says. //! +//! The vendored flow ([`vendored_bundle_fetch`]) commits the unpacked +//! patched gem under `.socket/vendor/gem` and makes `Gemfile` and +//! `Gemfile.lock` name it by its path from the project. rules_ruby runs +//! `bundle install` in a repository of Bazel's that holds the two files and +//! not the copy: the build fails until `vendor --revert` has put the two +//! files back. +//! //! Both markers are read from what Bazel built, and each holds an id made //! for the run, so no cache of an earlier run can supply either gem. The //! fixture's lock therefore holds no sha256 of a gem: it has a placeholder @@ -60,18 +67,24 @@ //! sends the two gems and the patch host to the stand-in. It is there from //! the first build on, and step (c) changes no flag. Bundler itself (the //! `bundler` gem the lock's `BUNDLED WITH` names) is not rewritten and comes -//! from rubygems.org. +//! from rubygems.org. Vendored mode downloads the patched gem itself, from +//! the patch host: the commands of that mode are told that the stand-in is +//! that host (`SOCKET_PATCH_SERVER_URL`). use std::io::Write as _; use std::time::Instant; +use base64::Engine as _; use serde_json::json; -use sha2::{Digest, Sha256}; +use sha2::{Digest, Sha256, Sha512}; + +use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; use crate::harness::{ - fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, StandIn, CONSUMER, + changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, StandIn, CONSUMER, + NOTHING, }; -use crate::hosted_memory_common::Patch; +use crate::hosted_memory_common::{Patch, ORG}; /// The sha256 of `bytes` in lowercase hex, as a `Gemfile.lock` and the gem /// index spell a sum. @@ -158,11 +171,34 @@ fn gem(name: &str, source: &str) -> Vec { ]) } +/// The one file of the fixture's gem. +const LIB: &str = "lib/sp_victim.rb"; + +/// What that file holds in the gem whose consumer prints `status` after +/// `OUT: `. +fn source(status: &str) -> String { + format!("module SpVictim\n STATUS = \"{status}\"\nend\n") +} + /// The fixture's gem, with the text its consumer prints after `OUT: `. fn victim(status: &str) -> Vec { - gem( - NAME, - &format!("module SpVictim\n STATUS = \"{status}\"\nend\n"), + gem(NAME, &source(status)) +} + +/// The specification the patch service serves beside a patched gem, which +/// vendored mode keeps in the copy: what RubyGems prints for the one of +/// [`gem`] (`Gem::Specification#to_ruby`). +fn stub() -> String { + format!( + "# -*- encoding: utf-8 -*-\n# stub: {NAME} {VERSION} ruby lib\n\n\ + Gem::Specification.new do |s|\n\ + \x20 s.name = \"{NAME}\".freeze\n\ + \x20 s.version = \"{VERSION}\".freeze\n\ + \x20 s.require_paths = [\"lib\".freeze]\n\ + \x20 s.authors = [\"socket-patch\".freeze]\n\ + \x20 s.files = [\"{LIB}\".freeze]\n\ + \x20 s.summary = \"a test fixture\".freeze\n\ + end\n" ) } @@ -198,28 +234,143 @@ fn gem_route(base: &str, name: &str) -> String { format!("/{base}/gems/{name}-{VERSION}.gem") } -/// The Socket API on `standin`: one free patch of the fixture's gem, granted -/// as the gem `patched`, with the artifact `url` (which hosted mode does not -/// fetch) and the patch registry `index`. -fn grant(standin: &StandIn, uuid: &str, url: &str, index: &str, patched: &[u8]) { - let sum = sha256_hex(patched); - let reference = json!({ - "status": "granted", - "url": url, - "purl": PURL, - "artifacts": [{ "kind": "tarball", "url": url, "integrity": { "sha256": sum } }], - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": index, - "identifiers": { "name": NAME, "version": VERSION, "gemChecksumSha256": sum }, - }, - }); - let patch = Patch { - purl: PURL.to_string(), - uuid: uuid.to_string(), - reference, - }; - standin.api(&[patch]); +/// A sum of `bytes` as a grant spells the one vendored mode holds a +/// download to. +fn sha512_sri(bytes: &[u8]) -> String { + let digest = base64::engine::general_purpose::STANDARD.encode(Sha512::digest(bytes)); + format!("sha512-{digest}") +} + +/// What a flow builds from and patches with: the fixture's two gems as one +/// run has them, and one patch of [`NAME`], on a stand-in. Each gem of +/// [`NAME`] holds an id that is new for every run. +struct Served { + standin: StandIn, + /// The id of the patch. + uuid: String, + /// The line the consumer prints for the upstream gem, and for the + /// patched one. + unpatched: String, + patched: String, + upstream_gem: Vec, + patched_gem: Vec, + /// The patch registry of the grant. + index: String, + /// The routes of the stand-in for the upstream gem and for the patched + /// one, as Bazel fetches them. + upstream_route: String, + patched_route: String, +} + +impl Served { + /// The stand-in of a flow in `cell`, whose lock then pins the two + /// upstream gems of this run, which only the stand-in has. + /// + /// The grant names the patch host as production does, with a token and + /// the patch id in the paths of its artifacts and of the patch + /// registry: the patched gem and its specification, which vendored + /// mode downloads, and the registry hosted mode writes into the lock. + /// The record of the patch holds the hashes of the file it changes. + /// + /// Bazel's downloads of the fixture's two gems on rubygems.org and of + /// anything on the patch host go to the stand-in, under the route + /// prefix of the host. A URL of the patch host that no rule rewrote is + /// refused, so no download of Bazel's reaches the real one. + fn to(cell: &mut Cell) -> Served { + let [run, uuid, token] = [(); 3].map(|()| uuid::Uuid::new_v4().to_string()); + let (pristine, fixed) = (format!("PRISTINE {run}"), format!("PATCHED {uuid}")); + let (upstream_gem, patched_gem) = (victim(&pristine), victim(&fixed)); + let neighbour_gem = neighbour(); + let registry = format!("{PATCH_HOST}/patch-registry/gem/{token}/{uuid}"); + let index = format!("https://{registry}/"); + let artifacts = format!("/patch/gem/{NAME}/{VERSION}/{token}/{uuid}/{NAME}-{VERSION}"); + let (upstream_route, patched_route) = + (gem_route(RUBYGEMS, NAME), gem_route(®istry, NAME)); + + let standin = StandIn::start(); + let origin = standin.origin(); + standin.serve(5, &upstream_route, &upstream_gem); + standin.serve(5, &gem_route(RUBYGEMS, NEIGHBOUR), &neighbour_gem); + standin.serve(5, &patched_route, &patched_gem); + // What `rollback` reads to restore the upstream `CHECKSUMS` line: + // the gem's file of the compact index, one line per version. + let info = format!("---\n{VERSION} |checksum:{}\n", sha256_hex(&upstream_gem)); + standin.serve(5, &format!("/{RUBYGEMS}/info/{NAME}"), info.as_bytes()); + + let sum = sha256_hex(&patched_gem); + let url = |file: &str| format!("https://{PATCH_HOST}{artifacts}.{file}"); + let stub = stub(); + standin.serve(5, &format!("{artifacts}.gem"), &patched_gem); + standin.serve(5, &format!("{artifacts}.gemspec"), stub.as_bytes()); + let reference = json!({ + "status": "granted", + "url": url("gem"), + "purl": PURL, + "artifacts": [{ + "kind": "tarball", + "url": url("gem"), + "integrity": { "sha256": sum, "sha512": sha512_sri(&patched_gem) }, + }, { + "kind": "gem-stub-gemspec", + "url": url("gemspec"), + "integrity": { "sha512": sha512_sri(stub.as_bytes()) }, + }], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": index, + "identifiers": { "name": NAME, "version": VERSION, "gemChecksumSha256": sum }, + }, + }); + standin.api(&[Patch { + purl: PURL.to_string(), + uuid: uuid.clone(), + reference, + }]); + let hash = |status: &str| compute_git_sha256_from_bytes(source(status).as_bytes()); + let record = json!({ + "uuid": uuid, + "purl": PURL, + "publishedAt": "2026-01-01T00:00:00Z", + "files": { LIB: { "beforeHash": hash(&pristine), "afterHash": hash(&fixed) } }, + "vulnerabilities": { "GHSA-test-aaaa-bbbb": { + "cves": ["CVE-2024-0001"], "summary": "s", "severity": "high", "description": "d", + }}, + "description": "fixture", + "license": "MIT", + "tier": "free", + }); + let record_route = format!("/v0/orgs/{ORG}/patches/view/{uuid}"); + standin.serve(1, &record_route, record.to_string().as_bytes()); + + let gems = |name: &str| rewrite(&format!("{RUBYGEMS}/gems/{name}-"), &origin); + cell.route_downloads(&[ + gems(NAME), + gems(NEIGHBOUR), + rewrite(&format!("{PATCH_HOST}/"), &origin), + format!("block {PATCH_HOST}"), + ]); + cell.write("Gemfile.lock", lock_pinning(&neighbour_gem, &upstream_gem)); + Served { + standin, + uuid, + unpatched: format!("OUT: {pristine}"), + patched: format!("OUT: {fixed}"), + upstream_gem, + patched_gem, + index, + upstream_route, + patched_route, + } + } +} + +/// `socket-patch ` in `cell`, with `standin` as the Socket API and as +/// rubygems.org, and with the variables `env` as well. +fn run(standin: &StandIn, cell: &Cell, args: &[&str], env: &[(&str, &str)]) -> Ran { + let origin = standin.origin(); + let rubygems = format!("{origin}/{RUBYGEMS}"); + let env = [&[("SOCKET_RUBYGEMS_URL", rubygems.as_str())], env].concat(); + cell.socket_patch(&origin, args, &env) } /// The flow of the module docs. @@ -233,54 +384,21 @@ fn hosted_bundle_fetch() { }; let release = cell.release().to_string(); - // The upstream gem and the patched gem: one gem with two texts in its - // one file, each with an id that is new for every run. The grant names - // the patch host as production does, with a token and the patch id in - // the paths of the artifact and of the patch registry. - let run = uuid::Uuid::new_v4().to_string(); - let uuid = uuid::Uuid::new_v4().to_string(); - let token = uuid::Uuid::new_v4().to_string(); - let unpatched = format!("OUT: PRISTINE {run}"); - let patched = format!("OUT: PATCHED {uuid}"); - let patched_gem = victim(&format!("PATCHED {uuid}")); - let upstream_gem = victim(&format!("PRISTINE {run}")); - let neighbour_gem = neighbour(); - let registry = format!("{PATCH_HOST}/patch-registry/gem/{token}/{uuid}"); - let index = format!("https://{registry}/"); - let artifact = format!( - "https://{PATCH_HOST}/patch/gem/{NAME}/{VERSION}/{token}/{uuid}/{NAME}-{VERSION}.gem" - ); - let (upstream_route, patched_route) = (gem_route(RUBYGEMS, NAME), gem_route(®istry, NAME)); - - let standin = StandIn::start(); + let Served { + standin, + uuid, + unpatched, + patched, + upstream_gem, + patched_gem, + index, + upstream_route, + patched_route, + } = Served::to(&mut cell); let origin = standin.origin(); - standin.serve(5, &upstream_route, &upstream_gem); - standin.serve(5, &gem_route(RUBYGEMS, NEIGHBOUR), &neighbour_gem); - standin.serve(5, &patched_route, &patched_gem); - // What `rollback` reads to restore the upstream `CHECKSUMS` line: the - // gem's file of the compact index, one line per version. - let info = format!("---\n{VERSION} |checksum:{}\n", sha256_hex(&upstream_gem)); - standin.serve(5, &format!("/{RUBYGEMS}/info/{NAME}"), info.as_bytes()); - grant(&standin, &uuid, &artifact, &index, &patched_gem); - let rubygems = format!("{origin}/{RUBYGEMS}"); - let socket_patch = |cell: &Cell, args: &[&str]| { - cell.socket_patch(&origin, args, &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())]) - }; - // Bazel's downloads of the fixture's two gems on rubygems.org and of - // anything on the patch host go to the stand-in, under the route prefix - // of the host. A URL of the patch host that no rule rewrote is refused, - // so no download of Bazel's reaches the real one. - let gems = |name: &str| rewrite(&format!("{RUBYGEMS}/gems/{name}-"), &origin); - cell.route_downloads(&[ - gems(NAME), - gems(NEIGHBOUR), - rewrite(&format!("{PATCH_HOST}/"), &origin), - format!("block {PATCH_HOST}"), - ]); - - // (a) The unpatched build. The lock of the checkout pins the two - // upstream gems of this run, which only the stand-in has. - cell.write("Gemfile.lock", lock_pinning(&neighbour_gem, &upstream_gem)); + let socket_patch = |cell: &Cell, args: &[&str]| run(&standin, cell, args, &[]); + + // (a) The unpatched build, from the upstream gem of this run. let before = cell.builds_unpatched(&unpatched); let upstream_fetches = standin.asked(&upstream_route); assert!( @@ -398,6 +516,103 @@ fn hosted_bundle_fetch() { ); } +/// Vendored mode beside a hub that reads the Gemfile and its lock. +/// +/// - (a) `bazel build` and `bazel run //:consumer` print the unpatched +/// marker. +/// - (b) `socket-patch scan --mode vendored --yes` passes and reports the +/// gem vendored. It commits the unpacked patched gem, with its +/// specification and its ledger, under `.socket/vendor`, and makes the +/// declaration of `Gemfile` and a `PATH` section of `Gemfile.lock` name +/// that copy by its path from the project. +/// - (c) The same `bazel build` fails: rules_ruby copies `Gemfile` and +/// `Gemfile.lock` into a repository of Bazel's and runs `bundle install` +/// there, where the path names nothing. `vex` attests the gem as patched +/// all the same: it reads the committed copy, and what rules_ruby builds +/// from one is not judged. +/// - (d) `socket-patch vendor --revert`: every file of the checkout is the +/// one of before, and the build prints the unpatched marker again. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn vendored_bundle_fetch() { + let test = "ruby::vendored_bundle_fetch"; + let started = Instant::now(); + let Some(mut cell) = Cell::open(test, &FIXTURE) else { + return; + }; + let release = cell.release().to_string(); + let served = Served::to(&mut cell); + let (standin, uuid) = (&served.standin, served.uuid.as_str()); + let origin = standin.origin(); + let patch_host = [("SOCKET_PATCH_SERVER_URL", origin.as_str())]; + + // (a) The unpatched build. + let before = cell.builds_unpatched(&served.unpatched); + + // (b) The one command of vendored mode: the copy, its ledger, and the + // two files that name it. + let vendoring = ["scan", "--mode", "vendored", "--yes"]; + let scan = run(standin, &cell, &vendoring, &patch_host); + let said = &scan.dump; + assert_eq!(scan.code, 0, "{test}: {said}"); + assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{test}: {said}"); + let vendored = cell.tree(); + let kept = format!(".socket/vendor/gem/{uuid}"); + let copy = format!("{kept}/{NAME}-{VERSION}"); + let mut written = vec![ + format!("{kept}/socket-patch.vendor.json"), + format!("{copy}/{LIB}"), + format!("{copy}/{NAME}.gemspec"), + ".socket/vendor/state.json".to_string(), + "Gemfile".to_string(), + "Gemfile.lock".to_string(), + ]; + written.sort(); + assert_eq!(changed(&before, &vendored), written, "{test}: {said}"); + let patched_source = source(&format!("PATCHED {uuid}")); + let lib = &vendored[&format!("{copy}/{LIB}")]; + assert_eq!(*lib, patched_source.as_bytes(), "{test}"); + let text = |rel: &str| String::from_utf8(vendored[rel].clone()).expect("a text file"); + let (gemfile, lock) = (text("Gemfile"), text("Gemfile.lock")); + let declaration = format!("gem \"{NAME}\", \"{VERSION}\", path: \"{copy}\""); + let declared = gemfile.lines().filter(|line| *line == declaration).count(); + assert_eq!(declared, 1, "{test}: Gemfile:\n{gemfile}"); + let section = format!("PATH\n remote: {copy}\n specs:\n {NAME} ({VERSION})\n\n"); + assert!(lock.starts_with(§ion), "{test}: Gemfile.lock:\n{lock}"); + + // (c) The same build fails where rules_ruby runs Bundler, on the path + // of the copy, and changes no file of the checkout. Bundler breaks the + // message at the width of its console, so it is compared without white + // space. + let build = cell.bazel("build", &[CONSUMER]); + let squeezed = |text: &str| text.split_whitespace().collect::(); + let stderr = squeezed(&build.stderr()); + let missing = squeezed(&format!("{copy}` does not exist.")); + assert!( + !build.ok() && stderr.contains("Runningbundleinstall") && stderr.contains(&missing), + "{test}: the build did not fail on the path of the copy ({missing:?}):\n{}", + build.dump() + ); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}"); + let attests = |cell: &Cell, args: &[&str]| run(standin, cell, args, &[]); + cell.stands_alone(attests, &Claim::new(PURL, uuid, How::Vendored), true); + + // (d) The undo: every file is the one of before, and so is the build. + let undo = run(standin, &cell, &["vendor", "--revert", "--yes"], &[]); + cell.undone(&undo, "removed", &before, &served.unpatched); + + println!( + "{test}: Bazel {release} built {:?}; `scan --mode vendored` passed, wrote {copy} and \ + pointed Gemfile and Gemfile.lock at it, and the next build failed (Bundler: The path \ + ... does not exist) while `vex` attested the gem; `vendor --revert` restored all {} \ + files and the build; {:?}", + served.unpatched, + before.len(), + started.elapsed() + ); +} + /// Without a Bazel, what stays fixed now that no sum is committed: the /// fixture's directories and the legs of its workflow are those of its /// table, and the `CHECKSUMS` section of the fixture's lock is one line per From 9c9f202702ec6111d13615049667db3962167abe Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 23 Nov 2026 15:53:12 -0500 Subject: [PATCH 02/19] Decline PyPI and RubyGems vendored mode where a Bazel hub reads the lock rules_python's `pip.parse` and rules_ruby's `ruby.bundle_fetch` build the packages of a lock in repositories of Bazel's own. Vendored mode makes that lock name the patched copy by a path under `.socket/vendor`, and neither ruleset builds from such a lock. The command exited 0 with status `success`, and the next `bazel build` failed for everything the hub serves (Bazel 9.3.2, 8.8.2 and 7.7.2, the flows of the previous commit): - PyPI: rules_python 2.5.0-rc4 makes the name of a repository from the path of the vendored line, `invalid user-provided repo name 'pip_311__/_socket/vendor/pypi//'`. - RubyGems: rules_ruby 1.0.0-rc2 runs `bundle install` in a repository that holds the Gemfile and its lock and not the copy, `The path .../.socket/vendor/gem//- does not exist.` Vendored mode now declines such a package before it downloads or writes anything, with `vendor_pypi_bazel_hub` or `vendor_gem_bazel_hub`. The refusal rests on what the files of the workspace say and on what the run would write, so it is for a run that would write a file a hub reads, and for no other. When it declines. The project is in a Bazel workspace (`bazel::bazel_root`), and a call of its files names, by a label written out as a string, a file of the project that the run for the package would point at a copy: - a `pip.parse` whose `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` or `uv_lock` names a requirements file of the project that the run would write (`requirements.txt` or a file it includes with `-r`), or the `uv.lock` of a uv project; - a `ruby.bundle_fetch` whose `gemfile` or `gemfile_lock` names the project's `Gemfile` or `Gemfile.lock`; - a call of a `WORKSPACE` file that passes one of those attributes, which is how the older form of either ruleset is called there (`pip_parse`, `rb_bundle_fetch`). Which files a PyPI run writes is asked of the backend's own router (`vendor::pypi::hub_files`). A project with no tool lock is wired through its requirements files, so they count. A uv, Pipenv or PEP 751 lock is wired together with a pin of the package in the requirements files beside it, so they count for a package they name (a pin, a hosted pin that a takeover restores first, or the vendored line of an earlier patch) and not for one they do not name. A Poetry or PDM lock is wired alone: such a project is not declined beside a hub that reads the requirements file exported from its lock, and is vendored as it is without Bazel. Every such call counts, also one that may not run (in a comprehension). Every package whose run would write a file the call names is declined, since the lock is the project's, but one that is already vendored (below). What an uncertain reading does. Where the files of the workspace cannot be read with certainty and a call of the hub may be behind that, every package whose run would write such a file is declined, in every project of the workspace: - a call of the hub whose file is not a plain string, or that passes `*` or `**`, and a hub proxy handed to anything but `use_repo` or `inject_repo`; - a module file that is missing or cannot be read, or a statement of one that cannot be read, where the workspace calls the hub or a file that was read names its ruleset (a `bazel_dep` on it, or a `use_extension` of the hub's `.bzl` file under any repository name); - a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all. The last two matter because Bazel builds files that are not read here: one byte that is not UTF-8 is enough, in a comment too, and so is a file over 1 MiB. Without them the call in such a file was not seen and the run went on. Going on there can leave a broken build behind a command that exited 0, and declining costs a vendored run that the switch brings back. A workspace whose root `MODULE.bazel` and `WORKSPACE` file were read or are not there, and in which no file that was read calls the hub or names its ruleset, is never declined for it, whatever else cannot be read. Where nothing changes. Outside a Bazel workspace, in a workspace that calls neither hub, and for a package whose run writes no file that a call names (a project beside the one a hub reads, one whose `requirements.txt` is not the file the hub is given, a Poetry or PDM project whose exported requirements the hub reads), vendored mode prints what it printed and writes what it wrote. Other ecosystems, hosted mode and agent mode are not touched. Where it is asked. `bazel::built` already says for `vex` which hub reads which lock; `reader` there answers this question from the same table and the same reader of workspace files, and takes `uv_lock` as one more attribute. `vendor::bazel_hub::refusals` asks it about the files the run of each package would write and words the refusal. `vendor::refusals::bazel_workspace_refusals`, the one answer every vendored entry point takes for a refusal that rests on the Bazel workspace, returns it beside the Composer refusal. So it reaches `scan --mode vendored`, `get --mode vendored`, `vendor` for a patch the manifest records, the takeover of a hosted pin by a vendored scan, and the eject of one by `vendor`, which asks once and before it fetches a record. No command's own code changes. The package is a `failed` event and the run exits 1 (`partialFailure`; for the eject `eject_refused`, detail `kept hosted: ...`). A dry run of `scan` or `get` lists the package as one the run would refuse and exits 0; `vendor --dry-run` reports the refusal and exits 1, as it does for any package it could not vendor. Nothing is written, no patch is downloaded, and a hosted pin stays. These are the exit codes of the Composer refusal. The detail names the call with its file and line, the lock, the Bazel root and hosted mode: `pip.parse` (MODULE.bazel:15) of the Bazel workspace at /repo names requirements.txt; vendored mode makes the lock name the patched copy by a path under .socket/vendor, and rules_python fails the build on such a lock; use `--mode hosted`, which names the patched package by a URL that rules_python fetches, or pass `--allow-vendored-in-bazel` if no build takes the packages of this project from rules_python For a doubt it names the file, the line and the reason in the place of the call. Hosted mode pins the patch in the same file, and both rulesets build it: the two flows end with that build. For a gem the detail adds the condition under which rules_ruby builds a hosted pin, "where its call passes no `gem_checksums`": with an entry for the gem there the hosted build fails, which the docs list as a known problem. `--allow-vendored-in-bazel` (SOCKET_ALLOW_VENDORED_IN_BAZEL) lifts the refusal, as it lifts the Composer one: for a hub that no build uses, a `WORKSPACE` file that the Bazel in use does not read, or a `ruby.bundle_fetch` that is given the files of the copy as `srcs`. Its help text, its row in CLI_CONTRACT.md and the sentence of docs/ecosystems.md that named Composer as the one refusal it lifts now name the three. `vendor --revert` is not refused. Neither is a package that is already vendored, as for Composer. What is declined is the write of the path into the lock the hub reads, so a package that the file the call names already names by the copy of the same patch (`.socket/vendor/pypi//`, `.socket/vendor/gem//`, outside a comment) is let through: the run adds nothing to what the hub reads. A project vendored with the switch, or by an earlier release, keeps passing its in-sync runs without the switch, a `scan` or `get` that names no mode included, which runs in vendored mode there. A new patch for that package, and any other package, is declined as before. It is the named file that decides, not any file of the project: a uv project whose lock names the copy while the hub reads a requirements file that still pins the registry's release would have that file rewritten by the run, and is declined. That file is read as a lock of the workspace is (`built::lock_text`): up to 64 MiB, and not through a link that leads out of the Bazel root, so such a link lets nothing through. Where the reading is in doubt no file is known to be the hub's, so nothing is let through there. Such a run passing does not make the build the patched one: for PyPI `vex` says `affected` of that state. No line a person reads is new: the refusal prints where every refused vendored package does. Tests: - pypi::vendored_pip_parse and ruby::vendored_bundle_fetch (real Bazel) now hold the command to the refusal: exit 1, the code, a detail that names the call, the lock, `--mode hosted` and the switch, no file changed and no request for the patched wheel or gem. The same build passes on the upstream package. With the switch the expectations of the previous commit are back: the package is vendored, the build fails with the ruleset's message, and `vendor --revert` restores the build. Hosted mode then builds the patched package. - Hermetic tests of both files, on steps the harness now holds for both: every command that would vendor declines and writes nothing, the dry runs and the eject among them; vendored mode goes on with the switch and with its variable, a later run without them passes and writes nothing, a scan that names no mode included, and `vendor --revert` needs neither; it goes on with no switch in a workspace whose hub reads another file, in a project beside the one it reads, and in no workspace; a hub whose file is not written out declines. For PyPI also: a Poetry project beside a hub that reads its exported `requirements.txt` is vendored with no switch, that file stays as it is and the later runs pass; and a `MODULE.bazel` with one byte that is not UTF-8 declines. - Unit tests of `built::reads` (each attribute, a call that may not run, `uv_lock`, another project, another repository, a doubt of the call, of the proxy and of the workspace, a hub that is not called, the `WORKSPACE` file; a root module file, an included file and a `WORKSPACE` file that cannot be read, with a root that names the ruleset as a dependency, by its extension, or not at all), of the refusal (codes, words, the switch, a file brought in with `-r`, the `Gemfile` alone, no workspace; a package the named lock already names by the patch's copy, and the same copy named in a comment, in another file, behind a link out of the root or under a doubt; a Poetry and a PDM lock, and a uv and a Pipenv lock beside a requirements file that names the package or does not) and of its dispatch. Four tests of pypi.rs vendored a wheel beside the hub that reads the requirements, to hold `vex` to what it says of that state. The command that writes the line now has the switch there, and they assert what they asserted; the in-sync runs after it have none, as before. Docs: docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode", the two rows of the matrix, and what "Bazel workspaces: VEX" says of a vendored gem, which a build has now shown; the rows of the two codes, of the switch and of the vendored table in CLI_CONTRACT.md. In "Bazel workspaces: what is supported" the two vendored cells stay "Not supported", and the note on that word now says that the command declines there. The entry of the known problems for vendored mode listed commands that exit 0 and leave a failing build: PyPI and RubyGems leave it, and so does Composer, which declines since the change before this one; NuGet stays. bazel-pypi.yml and bazel-ruby.yml start their legs for a change to vendor/bazel_hub.rs and vendor/refusals.rs, and bazel-pypi.yml for one to vendor/pypi.rs. The `bazel` group of scripts/loc-budget.json follows the 69 lines added to built.rs. Not covered: a hub call in a `.bzl` file that a `WORKSPACE` file loads, a hub of another Bazel module, another tag or ruleset that reads the same file under Bzlmod, a `WORKSPACE` call that hides its arguments behind `**`, a Bazel root above the git checkout, and a hub whose call and whose `bazel_dep` are both in an included file that cannot be read while the files that were read name neither: vendored mode goes on there as before. A package of a uv, Pipenv or PEP 751 project that the hub's requirements file names in a form that is not wired with the lock (a range, extras) is declined although the run would leave that file alone. `vex` still attests a gem that was vendored with the switch as patched, while its build fails. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-pypi.yml | 11 +- .github/workflows/bazel-ruby.yml | 10 +- crates/socket-patch-cli/CLI_CONTRACT.md | 9 +- crates/socket-patch-cli/src/args.rs | 11 +- .../tests/e2e_bazel_build/harness.rs | 134 ++++++ .../tests/e2e_bazel_build/pypi.rs | 300 +++++++++--- .../tests/e2e_bazel_build/ruby.rs | 215 +++++++-- crates/socket-patch-core/src/bazel/built.rs | 353 +++++++++++++- .../socket-patch-core/src/vendor/bazel_hub.rs | 439 ++++++++++++++++++ crates/socket-patch-core/src/vendor/mod.rs | 1 + crates/socket-patch-core/src/vendor/pypi.rs | 34 ++ .../src/vendor/pypi_requirements.rs | 14 + .../socket-patch-core/src/vendor/refusals.rs | 55 ++- docs/ecosystems.md | 189 +++++++- scripts/loc-budget.json | 2 +- 15 files changed, 1635 insertions(+), 142 deletions(-) create mode 100644 crates/socket-patch-core/src/vendor/bazel_hub.rs diff --git a/.github/workflows/bazel-pypi.yml b/.github/workflows/bazel-pypi.yml index cd5198576..381838cab 100644 --- a/.github/workflows/bazel-pypi.yml +++ b/.github/workflows/bazel-pypi.yml @@ -41,7 +41,10 @@ on: # files and decides whether Bazel builds what was patched. Every flow # holds the exact document socket-patch writes about its build, patched # or not, so a change to how a document is built or worded - # starts the legs of every ecosystem. Nothing else that + # starts the legs of every ecosystem. `bazel/` also says which lock a + # hub reads, for the refusal of vendored mode beside such a hub + # (vendor/bazel_hub.rs), which vendor/refusals.rs hands to every + # command. Nothing else that # another ecosystem's flow owns is here, so any other change to one # ecosystem starts that ecosystem's legs only. # @@ -71,9 +74,12 @@ on: - 'crates/socket-patch-core/src/utils/python_lock.rs' - 'crates/socket-patch-core/src/utils/requirements.rs' - 'crates/socket-patch-core/src/vendor/lock_inventory/pypi.rs' + - 'crates/socket-patch-core/src/vendor/pypi.rs' - 'crates/socket-patch-core/src/vendor/pypi_distribution.rs' - 'crates/socket-patch-core/src/vendor/pypi_requirements.rs' - 'crates/socket-patch-core/src/vendor/pypi_wheel.rs' + - 'crates/socket-patch-core/src/vendor/bazel_hub.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/vex/discover/pypi_other.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/vex/**' @@ -105,9 +111,12 @@ on: - 'crates/socket-patch-core/src/utils/python_lock.rs' - 'crates/socket-patch-core/src/utils/requirements.rs' - 'crates/socket-patch-core/src/vendor/lock_inventory/pypi.rs' + - 'crates/socket-patch-core/src/vendor/pypi.rs' - 'crates/socket-patch-core/src/vendor/pypi_distribution.rs' - 'crates/socket-patch-core/src/vendor/pypi_requirements.rs' - 'crates/socket-patch-core/src/vendor/pypi_wheel.rs' + - 'crates/socket-patch-core/src/vendor/bazel_hub.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/vex/discover/pypi_other.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/vex/**' diff --git a/.github/workflows/bazel-ruby.yml b/.github/workflows/bazel-ruby.yml index b6e1e3352..0c4b1cfd6 100644 --- a/.github/workflows/bazel-ruby.yml +++ b/.github/workflows/bazel-ruby.yml @@ -30,8 +30,10 @@ on: # Gemfile with the lock half of the hosted rewrite (formats/gem), lock # discovery, the lock inventory, the Ruby crawler (it says which lock # Bundler loads), the upstream restore of `rollback`, the stale-install - # guard that those commands end with, and the vendored backend - # (vendor/gem.rs). + # guard that those commands end with, the vendored backend + # (vendor/gem.rs), and the refusal of vendored mode beside a hub that + # reads the lock (vendor/bazel_hub.rs), which vendor/refusals.rs hands + # to every command. # Last, the VEX code: `vex/` of the core, the files of the `vex` # command, and `bazel/` of the core, which reads the workspace files and # decides whether Bazel builds what was patched. Every flow holds the @@ -69,6 +71,8 @@ on: - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' - 'crates/socket-patch-core/src/vendor/gem.rs' + - 'crates/socket-patch-core/src/vendor/bazel_hub.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/src/commands/vex*.rs' @@ -95,6 +99,8 @@ on: - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' - 'crates/socket-patch-core/src/vendor/gem.rs' + - 'crates/socket-patch-core/src/vendor/bazel_hub.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/src/commands/vex*.rs' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index a1d543d5e..9e2a1ce9b 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -122,7 +122,7 @@ Every subcommand accepts the same set of "global" flags via a single shared `Glo | `--no-vlt-install-cleanup` | — | `SOCKET_NO_VLT_INSTALL_CLEANUP` | `false` | bool | Opt out of hosted mode's warm-tree heal for vlt: stale installed copies (`node_modules/.vlt-lock.json` and the stale `node_modules/.vlt/` entries) are left in place after `vlt-lock.json` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`), and the `redirect_vlt_reinstall_required` advisory tells you to run `vlt ci` instead. Stale copies of optional dependencies are always left in place (see `redirect_vlt_reinstall_required`). Other subcommands accept it silently | | `--no-gem-install-refresh` | — | `SOCKET_NO_GEM_INSTALL_REFRESH` | `false` | bool | Opt out of hosted mode's gem stale-install refresh: the gems Bundler already holds for the project (an installed gem under the project and its cached `.gem`, an archive in `vendor/cache`) are left as they are after `Gemfile.lock` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`, of a hosted pin or of a vendored gem; `vendor --revert`), and the `redirect_gem_stale_install` / `upstream_gem_stale_install` warning names the files to remove by hand instead (see the "Gem stale-install guard" section). Other subcommands accept it silently | | `--gem-refresh-shared` | — | `SOCKET_GEM_REFRESH_SHARED` | `false` | bool | Extend the gem stale-install refresh to gem homes OUTSIDE the project (the system gems, `~/.gem`, an rbenv or asdf home) and to project bundle or cache paths that resolve outside the project directory. Off by default: another project on the machine may pin the other build of the same gem version, and its `bundle pristine` then fails on the replaced archive's checksum (see the "Gem stale-install guard" section). Other subcommands accept it silently | -| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default; the one refusal it lifts today is `vendor_composer_bazel_workspace`: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. The switch is not specific to Composer: any refusal of vendored mode that rests on the Bazel workspace reads this one. For a project whose build does find the copy. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" | +| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default, and the switch lifts each of those refusals. `vendor_composer_bazel_workspace`: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. `vendor_pypi_bazel_hub` and `vendor_gem_bazel_hub`: a rules_python or rules_ruby hub of the workspace reads the lock, which then names the patched copy by a path under `.socket/vendor`, and neither ruleset builds from that. For a project whose build does find the copy, or does not take its packages from that lock. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" and "Bazel workspaces: PyPI and RubyGems vendored mode" | **`--download-mode` removed (v5.0, MAJOR).** The global `--download-mode` flag and its `SOCKET_DOWNLOAD_MODE` binding are gone, with no alias: passing the flag is a usage error (exit 2) and the env var is ignored. Patch content is always fetched as per-file blobs (`.socket/blobs/`); `.socket/diffs/` archives are obsolete, never read, and removed by the cleanup sweeps. @@ -1688,12 +1688,12 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` unless the run has `--allow-vendored-in-bazel` | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked prebuilt platform gem per locked platform, `-//`, each with its gemspec, plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patch's prebuilt platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a prebuild: while the patch service lists none for one of them the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair | -| pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock) | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked prebuilt platform gem per locked platform, `-//`, each with its gemspec, plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patch's prebuilt platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a prebuild: while the patch service lists none for one of them the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the project is refused `vendor_gem_bazel_hub` unless the run has `--allow-vendored-in-bazel` | +| pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | | pypi / pipenv (Pipfile.lock) | (rebuilt wheel) | lock-only: the `default`/`develop` entry → `{file, hashes:[sha256-of-our-wheel]}`. Pipfile + `_meta.hash` untouched. Emits `vendor_integrity_unverified` — pipenv does not hash-check file entries; the committed wheel bytes are the protection — and, when another entry is hashed, `pypi_pipenv_hash_export_unsupported` (`pipenv requirements --hash` drops the vendored wheel's hash) | `pipenv install --deploy` (+ `pipenv verify`), cold cache | -| pypi / requirements.txt (pip / `uv pip`) | (rebuilt wheel) | pin line → `./` (markers carried over; transitive deps appended), plus `--hash=sha256:` only when the requirements tree is already in pip's hash-checking mode (any `--hash` or `--require-hashes`) | `pip install -r` / `uv pip install -r` **run from the project root** (both resolve bare paths against the CWD) | +| pypi / requirements.txt (pip / `uv pip`) | (rebuilt wheel) | pin line → `./` (markers carried over; transitive deps appended), plus `--hash=sha256:` only when the requirements tree is already in pip's hash-checking mode (any `--hash` or `--require-hashes`) | `pip install -r` / `uv pip install -r` **run from the project root** (both resolve bare paths against the CWD). Where a rules_python hub of the project's Bazel workspace reads `requirements.txt` or a file it includes with `-r`, the project is refused `vendor_pypi_bazel_hub` unless the run has `--allow-vendored-in-bazel` | | nuget | deterministically rebuilt `.nupkg` at `..nupkg` (the uuid dir IS a NuGet folder feed; the stale embedded signature is dropped — unsigned is accepted under NuGet's default validation), plus `/.gitignore` (`!*`: re-includes the nupkg against the project's ignores, such as VisualStudio.gitignore's `*.nupkg`); refuses `vendor_artifact_gitignored` when git would still drop it | `nuget.config` source + `packageSourceMapping` for the id (creating the mapping from scratch ALSO fans a `` out to every pre-existing source, including the ones NuGet inherits from the user config and parent directories' configs (v5.0 #354), none at all when an inherited config already maps packages — mapping is exclusive, NU1100 otherwise; another source's exact pattern for the id is set aside in a comment while vendored, `vendor_nuget_mapping_set_aside`, #462) **+** `packages.lock.json` `contentHash` → `base64(sha512(nupkg))` for the entries at the patched version in every lock a project under the root restores into — the root `packages.lock.json`, member projects' locks, `packages..lock.json`, a literal `NuGetLockFilePath` (v5.0 #353/#514; an unevaluable `NuGetLockFilePath` is refused with `vendor_nuget_lock_path_unresolved`) — (`vendor_nuget_no_lockfile` warning when there is none; a lock that also resolves the id at another version is refused with `vendor_nuget_lock_other_version`, nothing written) | `dotnet restore --locked-mode`, cold cache, `--network none` (tampered nupkg fails NU1403) | | maven | the patched `.jar` + the upstream pom (its `` suffixed, and what it inherits from its parents through `${project.version}` declared at the base version between `socket-patch:inherited` markers, so it resolves what the upstream pom does; transitives survive) + `.sha1` sidecars + an ownership marker under `.socket/vendor/maven2///-socket./`; every JVM tree root (`.socket/vendor/maven2`, Gradle's `.socket/vendor/gradle`, Coursier's `.socket/vendor/coursier`) owns a `.gitignore` (`!*`) that re-includes the jars against the project's ignores, such as Java.gitignore's `*.jar`, plus a `.gitattributes` (`-text`); a tree root git ignores itself refuses `vendor_artifact_gitignored` | every pom root, single-module (a reactor of one) or multi-module: the pinned `` + `` pin, `.mvn/maven.config` (`maven.repo.local.tail`) and the `socket-patch-vendor` fallback file repository (`checksumPolicy=fail`); Gradle, sbt and scala-cli roots go to the same JVM backend (ledger ecosystem `jvm`). Pre-v5 `maven_pom_repository` entries (`` to `.socket/vendor/maven/`) are revert-only: vendoring their root is refused (`vendor_jvm_shape_unsupported`, `legacy_maven_root`) | `mvn` build on a fresh checkout with a warm local repository and behind `mirrorOf external:*` (host capstone `e2e_vendor_maven_build` across the Maven matrix) | @@ -2492,6 +2492,7 @@ command's integration tests check its output. | `vendor_bun_lockb_invalid` | `failed` | vendor / scan / get `--mode vendored`: the binary lock is malformed, unreadable, unsupported or cannot be rewritten safely. The detail names the parser, hash or filesystem error. Refused before patch downloads and before hosted takeover; the package's `failed` event carries `errorCode` and `error`, while `get ` also carries top-level `error.code`. Dry-run predicts the same refusal. | | `vendor_bun_workspace_unsupported` | `failed` | vendor / scan / get `--mode vendored` (bun): the text lock holds `workspace:` packages and its `lockfileVersion` is below 2 — Bun 1.2–1.3 resolve a workspace member's local-tarball path relative to the member; a committed version-2 lock is the proof every consumer runs Bun ≥ 1.4 (deliberate over-approximation: root-only declared packages would install on version 1 too). Detail names the version integer and a version-specific remedy: delete `bun.lock` and re-lock with Bun ≥ 1.4 (an in-place `bun install` keeps the existing version) — then, for a version-1 lock, "or use `--mode hosted`, which accepts version-1 workspace locks"; for a version-0 lock, "or delete `bun.lock`, re-lock with Bun ≥ 1.2 (which writes lockfileVersion 1) and use `--mode hosted`" (hosted refuses version-0 workspace locks, so a bare hosted pointer would send the user into a second refusal). Refused before any write — in the pre-download preflight on `get`/`scan` (see `vendor_bun_lockb_invalid` for the placements); in the shared preflight that `vendor` and the vendor step run BEFORE a hosted → vendored takeover's revert (a hosted-redirected purl stays hosted-wired, ledger and lock untouched; `vendor --dry-run` previews the same `failed` code); and in the engine when the run would write a NEW local tuple. Exempt: purls the vendor ledger wires at the selected uuid, purls whose every `bun.lock` instance is already a `.socket/vendor/npm/` tuple (any uuid), in-sync re-runs and `repair` redownloads. | | `vendor_composer_bazel_workspace` | `failed` | vendor / scan / get `--mode vendored` (composer): the project is in a Bazel workspace (its directory, or one above it up to the root of its git checkout, holds `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`). Vendored mode makes `composer.lock` name the patched copy by a path relative to the directory Composer runs in; a Bazel repository rule or build action that runs `composer install` from the lock anywhere else fails with Composer's `Source path "…" is not found for package …`, and the build with it (Bazel 9.3.2, 8.8.2, 7.7.2). Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the Bazel root and the mode that writes no such path, `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel`, `vendor --revert`, and a package whose `composer.lock` entry already names the copy of the same patch (the run leaves the lock as it is, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included; a new patch for it is refused). A project that commits its `vendor/` tree is refused like any other: the tree shows that Composer has run in the project's directory, not that no rule of the workspace runs it elsewhere as well. See docs/ecosystems.md "Bazel workspaces: Composer". | +| `vendor_pypi_bazel_hub` / `vendor_gem_bazel_hub` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): a hub of the project's Bazel workspace reads a file of the project that the run would point at the copy under `.socket/vendor`. That is a rules_python `pip.parse` whose `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` or `uv_lock` names a requirements file of the project that the run would write (`requirements.txt` or a file it includes with `-r`: in a project with no tool lock, and for a package they name beside a uv, Pipenv or PEP 751 lock) or the `uv.lock` of a uv project; a rules_ruby `ruby.bundle_fetch` whose `gemfile` or `gemfile_lock` names the project's `Gemfile` or `Gemfile.lock`; and a call of a `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`). Neither ruleset builds from such a file: rules_python 2.5.0-rc4 fails with `invalid user-provided repo name '___/_socket/vendor/pypi/…'`, and the `bundle install` action of rules_ruby 1.0.0-rc2 with `The path … does not exist.`, after a command that exited 0 (Bazel 9.3.2, 8.8.2, 7.7.2). Also refused, for every package whose run would write such a file: a workspace whose files cannot be read with certainty where a call of the hub may be behind that (a call of the hub whose file is not a plain string label or that passes `*` or `**`; a hub proxy handed on; a module file or a statement of one that cannot be read, while the workspace calls the hub or a file that was read names its ruleset; a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all, for which one byte that is not UTF-8 is enough), because a call may then read the project's lock. Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the call with its file and line, the lock (or the place and the reason of the doubt), the Bazel root, and the mode whose pin both rulesets build, `--mode hosted` (rules_ruby where its call passes no `gem_checksums`, which the detail for a gem says). Not refused: a package whose run writes no file that such a call names, in a Bazel workspace or outside one (a Poetry or PDM project, whose lock is wired alone, beside a hub that reads its exported `requirements.txt`); a workspace whose files were read and neither call the hub nor name its ruleset; a run with `--allow-vendored-in-bazel`; `vendor --revert`; and a package that the file the call names already names by the copy of the same patch (`.socket/vendor/pypi//`, `.socket/vendor/gem//`): the run adds nothing to what the hub reads, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included, while a new patch for the package is refused. Where the reading is in doubt no file is known to be the hub's, and every run without the switch is refused. See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" | | `vendor_lockfile_missing` / `vendor_lockfile_version_unsupported` (bun preflight placement) | `failed` | scan / get `--mode vendored` (bun): the pre-download preflight found `bun.lock` unreadable / at a `lockfileVersion` other than 0 to 3 (a newer version: update socket-patch; no integer: re-lock with Bun ≥ 1.2 — the same text as hosted's `redirect_bun_lock_unsupported`) or outside bun's single-line `packages` grammar. Same placements as `vendor_bun_lockb_invalid`; nothing fetched, no patch record. An unreadable `.socket/vendor/state.json` met by the same preflight is `vendor_state_unreadable` (see that row), never one of these. | | `bun_lockb_invalid` | scan `warnings[]` (run-level) | scan (every mode): the native binary inventory could not parse or read `bun.lockb`; detail names the format or filesystem error. Also printed as `Warning: …` on stderr. Exit and status remain unchanged. The warning is retained on empty and non-empty scans; valid binary locks are inventoried normally without a runtime or install. | | `bun_lock_unsupported` | scan `warnings[]` (run-level) | scan (every mode): the text `bun.lock` is there but the lock reader refuses it — a `lockfileVersion` newer than 3, no integer version, or a `packages` section outside bun's single-line grammar (a comment line, a re-indent) — so the packages it lists were not read from the lockfile. Detail is the shared version gate's text or `bun.lock: line : …`, followed by `, so the packages it lists were NOT read from the lockfile: a package that is locked but not installed was not scanned`. Also printed as `Warning: …` on stderr, and a scan that then finds no package at all ends `No packages found (see the warning).` instead of advising an install. Status and exit are unchanged (0): before, a checkout without `node_modules` scanned as an empty project and the lock was not mentioned. Installed packages are still crawled, and hosted / vendored runs keep their own refusal (`redirect_bun_lock_unsupported` / `vendor_lockfile_version_unsupported`). The hosted in-memory engine reports the same code among its warnings. | diff --git a/crates/socket-patch-cli/src/args.rs b/crates/socket-patch-cli/src/args.rs index bebd4ba9a..136f2e57c 100644 --- a/crates/socket-patch-cli/src/args.rs +++ b/crates/socket-patch-cli/src/args.rs @@ -425,11 +425,16 @@ pub struct GlobalArgs { /// Vendored mode (`vendor`, `scan`/`get --mode vendored`): write for a /// package although the project is in a Bazel workspace, where the /// build may not find the vendored copy. Vendored mode declines such - /// a package by default; today that is a Composer package + /// a package by default: a Composer package /// (`vendor_composer_bazel_workspace`), whose lock names the copy by a /// path that a Bazel rule running `composer install` in another - /// directory does not find. Pass it when the build does find the - /// copy. Other subcommands accept it silently. + /// directory does not find, and a PyPI or RubyGems package whose lock + /// a rules_python or rules_ruby hub of the workspace reads + /// (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), which builds + /// nothing from a lock that names a copy under `.socket/vendor`. Pass + /// it when the build does find the copy, or does not take the + /// project's packages from that lock. Other subcommands accept it + /// silently. #[arg( help_heading = GLOBAL_OPTIONS, long = "allow-vendored-in-bazel", diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs index d0fdc9917..595498e2d 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -158,6 +158,26 @@ const ADVISORY: &str = "GHSA-test-aaaa-bbbb"; /// package is affected. pub const NOT_IN_BUILD: &str = "vex_bazel_not_in_build"; +/// The one command of vendored mode. +pub const VENDORED: [&str; 4] = ["scan", "--mode", "vendored", "--yes"]; + +/// The switch that lets vendored mode write for a package it declines +/// because of the project's Bazel workspace, and the variable of the same +/// meaning. +pub const ALLOW: &str = "--allow-vendored-in-bazel"; +pub const ALLOW_ENV: &str = "SOCKET_ALLOW_VENDORED_IN_BAZEL"; + +/// A package that vendored mode declines in a checkout, because a hub of +/// the workspace reads a lock the run would rewrite. +pub struct Declined<'a> { + pub purl: &'a str, + /// The error code of the refusal. + pub code: &'a str, + /// What the refusal has to name beside hosted mode and the switch: the + /// call with its file and line, and the lock. + pub names: &'a [&'a str], +} + /// The mode a flow patched its package in, which a document says after the /// patch id. Or [`How::Unbuilt`]: the patch is in a copy that Bazel does /// not build, and a document says the package is affected. @@ -1085,6 +1105,120 @@ impl Cell { assert_eq!(changed(before, &self.tree()), NOTHING, "{test}"); } + /// For a finished command of vendored mode where it declines + /// `package`: it ended with `exit` and reports the package as its one + /// event, `action` under the code of the refusal, in words that name + /// the call, the lock, hosted mode and the switch. No file of the + /// checkout differs from `before`. + pub fn declined(&self, ran: &Ran, package: &Declined, exit: i32, action: &str, before: &Tree) { + let (test, said) = (&self.test, &ran.dump); + assert_eq!(ran.code, exit, "{test}: {said}"); + let [event] = events(&ran.envelope) else { + panic!("{test}: not one event: {said}"); + }; + let reported = [&event["purl"], &event["action"], &event["errorCode"]]; + let expected = [package.purl, action, package.code]; + assert_eq!(reported, expected, "{test}: {said}"); + let why = event["error"].as_str().or(event["reason"].as_str()); + let why = why.unwrap_or_default(); + let switch = format!("`{ALLOW}`"); + for name in package.names.iter().chain(&["`--mode hosted`", &switch]) { + assert!(why.contains(name), "{test}: no {name:?} in {why:?}"); + } + assert_eq!(changed(before, &self.tree()), NOTHING, "{test}: {said}"); + } + + /// Without a Bazel, in this checkout where a hub reads the lock of + /// `package`: every command that would vendor the package declines it + /// and writes nothing. That is the scan, `get`, `vendor` for a patch + /// the manifest records and, where the package is pinned hosted, the + /// scan that would take the pin over and the `vendor` that would eject + /// it, so the pin stays. A dry run of the scan names the refusal and + /// passes; one of `vendor` fails as its run does. `run` runs + /// `socket-patch` here, with the variables it is given. + pub fn declines_every_vendoring( + &self, + run: impl Fn(&Cell, &[&str], &[(&str, &str)]) -> Ran, + package: &Declined, + ) { + let declines = |args: &[&str], exit: i32, action: &str, before: &Tree| { + let ran = run(self, args, &[]); + self.declined(&ran, package, exit, action, before); + ran + }; + let before = self.tree(); + let get = ["get", package.purl, "--mode", "vendored", "--yes"]; + declines(&VENDORED, 1, "failed", &before); + declines(&get, 1, "failed", &before); + declines( + &[&VENDORED[..], &["--dry-run"]].concat(), + 0, + "skipped", + &before, + ); + + let saved = run(self, &["get", package.purl, "--save-only", "--yes"], &[]); + assert_eq!(saved.code, 0, "{}", saved.dump); + let vendor = [["vendor", "--yes"], ["vendor", "--dry-run"]]; + for vendor in &vendor { + declines(vendor, 1, "failed", &self.tree()); + } + std::fs::remove_dir_all(self.path(".socket")).expect("remove .socket"); + + // The eject is refused whole, before it restores a pin, and so is + // its dry run. + let hosted = run(self, &["scan", "--mode", "hosted", "--yes"], &[]); + assert_eq!(hosted.envelope["summary"]["applied"], 1, "{}", hosted.dump); + let pinned = self.tree(); + assert_ne!(changed(&before, &pinned), NOTHING, "{}", hosted.dump); + declines(&VENDORED, 1, "failed", &pinned); + for eject in &vendor { + let eject = declines(eject, 1, "failed", &pinned); + let refused = &eject.envelope["error"]["code"]; + assert_eq!(*refused, "eject_refused", "{}", eject.dump); + let why = event_for(&eject.envelope, package.purl)["error"].as_str(); + let kept = why.is_some_and(|why| why.starts_with("kept hosted: ")); + assert!(kept, "{}", eject.dump); + } + } + + /// Without a Bazel, in such a checkout: vendored mode goes on when the + /// user says so, with the switch or its variable. A later run without + /// either passes and writes nothing: the lock the hub reads already + /// names the copy of that patch, so the run is in sync, and so is a + /// scan that names no mode, which runs in vendored mode in a vendored + /// project. `vendor --revert` takes no switch: it puts every file back. + pub fn vendors_on_the_users_word( + &self, + run: impl Fn(&Cell, &[&str], &[(&str, &str)]) -> Ran, + package: &Declined, + ) { + let before = self.tree(); + let reverts = |why: &str| { + let undo = run(self, &["vendor", "--revert", "--yes"], &[]); + assert_eq!(undo.code, 0, "{why}: {}", undo.dump); + assert_eq!(changed(&before, &self.tree()), NOTHING, "{why}"); + }; + let vendors = |args: &[&str], env: &[(&str, &str)]| { + let ran = run(self, args, env); + assert_eq!(ran.code, 0, "{}", ran.dump); + assert_eq!(ran.envelope["summary"]["applied"], 1, "{}", ran.dump); + }; + vendors(&VENDORED, &[(ALLOW_ENV, "1")]); + reverts(ALLOW_ENV); + vendors(&[&VENDORED[..], &[ALLOW]].concat(), &[]); + let vendored = self.tree(); + for in_sync in [&VENDORED[..], &["scan", "--yes"]] { + let again = run(self, in_sync, &[]); + let said = &again.dump; + assert_eq!(again.code, 0, "{in_sync:?}: {said}"); + assert_eq!(again.envelope["status"], "success", "{in_sync:?}: {said}"); + assert!(!said.contains(package.code), "{in_sync:?}: {said}"); + assert_eq!(changed(&vendored, &self.tree()), NOTHING, "{in_sync:?}"); + } + reverts(ALLOW); + } + /// `socket-patch ` in the workspace copy, as a user in that /// directory runs it, against the Socket API at `api`. Its home and /// temp directory are the cell's, and every proxy is a closed port, so diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs index 06f8bb082..357c8e54d 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs @@ -42,15 +42,18 @@ //! id made for the run, so no cache of an earlier run can supply it. The //! flow asserts the VEX document of its patch as `main.rs` says. //! -//! The vendored flow ([`vendored_pip_parse`]) commits the patched wheel and -//! points the package's line of `requirements.txt` at it. rules_python -//! builds no wheel from such a line: the build fails until -//! `vendor --revert` has put the pin back. The flow asserts that; that -//! every form of `vex` meanwhile writes a document that says the package -//! is affected, and names the call of `MODULE.bazel` that reads the file; -//! that the revert brings the unpatched build back; and that hosted mode, -//! which the document names, ends in the patched build and in a document -//! that says not affected. +//! Vendored mode would commit the patched wheel and point the package's +//! line of `requirements.txt` at it, and rules_python builds no wheel from +//! such a line. So in this checkout, where the hub reads that file, the +//! command declines the package and writes nothing +//! ([`vendored_pip_parse`]): the build stays the unpatched one. With +//! `--allow-vendored-in-bazel` it does what it did before it declined, and +//! the build fails until `vendor --revert` has put the pin back. The flow +//! asserts that; that every form of `vex` meanwhile writes a document that +//! says the package is affected, and names the call of `MODULE.bazel` that +//! reads the file; that the revert brings the unpatched build back; and +//! that hosted mode, which the refusal and the document name, ends in the +//! patched build and in a document that says not affected. //! //! One loopback server stands in for four hosts. The Socket API and the //! patch host answer at their own paths; `pypi.org` (the project pages of @@ -95,8 +98,8 @@ use sha2::{Digest, Sha512}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; use crate::harness::{ - cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, - StandIn, Tree, CONSUMER, NOTHING, + cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Declined, Fixture, + How, Ran, StandIn, Tree, ALLOW, CONSUMER, NOTHING, VENDORED, }; use crate::hosted_memory_common::{read_tree, Patch, ORG}; @@ -572,6 +575,8 @@ struct Vendoring { uuid: String, wheels: [Wheel; 2], patched: Wheel, + /// The route of the patched wheel on the stand-in's patch host. + route: String, /// The record of the patch, as the API serves it. record: Value, } @@ -623,6 +628,7 @@ impl Vendoring { uuid, wheels, patched, + route, record, } } @@ -630,34 +636,56 @@ impl Vendoring { /// `socket-patch ` in `cell`, with the stand-in as the Socket /// API, the patch server and the index's JSON API. fn run(&self, cell: &Cell, args: &[&str]) -> Ran { + self.run_with(cell, args, &[]) + } + + /// [`Vendoring::run`] with the variables `more` as well. + fn run_with(&self, cell: &Cell, args: &[&str], more: &[(&str, &str)]) -> Ran { let origin = self.standin.origin(); let json_api = format!("{origin}/{INDEX}/pypi"); let env = [ ("SOCKET_PATCH_SERVER_URL", origin.as_str()), ("SOCKET_PYPI_JSON_API", json_api.as_str()), ]; - cell.socket_patch(&origin, args, &env) + cell.socket_patch(&origin, args, &[&env[..], more].concat()) } } +/// The code under which vendored mode declines a package whose +/// requirements a hub of the workspace reads. +const DECLINED: &str = "vendor_pypi_bazel_hub"; + +/// The line of the `MODULE.bazel` of `cell` that calls the hub. +fn hub_line(cell: &Cell) -> usize { + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + let above = module.lines().take_while(|line| *line != "pip.parse("); + above.count() + 1 +} + +/// What a refusal of vendored mode has to name in the checkout of `cell`: +/// the hub's call with its line in `MODULE.bazel`, and the file it reads. +fn refusal_names(cell: &Cell) -> [String; 2] { + let call = format!("`pip.parse` (MODULE.bazel:{})", hub_line(cell)); + [call, format!("names {REQUIREMENTS}; ")] +} + /// What `socket-patch` has to name when it says that the package is /// affected: the file that points at the committed wheel, the hub's call /// with its line in the `MODULE.bazel` of `cell`, and the two commands /// that patch what Bazel builds. fn names(cell: &Cell) -> Vec { - let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); - let above = module.lines().take_while(|line| *line != "pip.parse("); vec![ format!("the line of {REQUIREMENTS} that points at"), - format!("(`pip.parse`, MODULE.bazel:{})", above.count() + 1), + format!("(`pip.parse`, MODULE.bazel:{})", hub_line(cell)), "`socket-patch vendor --revert`, then `socket-patch scan --mode hosted`".to_string(), ] } -/// Vendored mode in the checkout of `cell`, whose `requirements.txt` pins -/// the wheels of `with`: `scan --mode vendored --yes` commits the patched -/// wheel under `.socket/vendor/pypi` and points the package's line of -/// `requirements.txt` at it. The command passes, and with `--vex` it +/// Vendored mode on the user's word in the checkout of `cell`, whose +/// `requirements.txt` pins the wheels of `with` and is read by the hub: +/// `scan --mode vendored --yes --allow-vendored-in-bazel` commits the +/// patched wheel under `.socket/vendor/pypi` and points the package's line +/// of `requirements.txt` at it. The command passes, and with `--vex` it /// writes a document that says the package is affected; so do /// `apply --vex` and `vendor --vex`, and `vex` and `vex --no-verify`. Each /// names the call of `MODULE.bazel` that hands `requirements.txt` to @@ -668,8 +696,10 @@ fn vendors_the_wheel(cell: &Cell, with: &Vendoring) -> Tree { let run = |cell: &Cell, args: &[&str]| with.run(cell, args); let in_run = cell.document("in-run"); - let vendoring = ["scan", "--mode", "vendored", "--yes"]; - let scan = run(cell, &[&vendoring[..], &with_vex(&in_run)].concat()); + let scan = run( + cell, + &[&VENDORED[..], &[ALLOW], &with_vex(&in_run)].concat(), + ); let said = &scan.dump; assert_eq!(scan.code, 0, "{test}: {said}"); assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); @@ -727,20 +757,38 @@ fn pins(cell: &Cell, with: &Vendoring, before: &Tree) { cell.stands_alone(run, &claim, true); } +/// Vendored mode where it declines: `socket-patch ` in `cell` ends +/// with `exit` and reports the package under [`DECLINED`], as the one event +/// `action`, in words that name the hub's call, the file it reads, hosted +/// mode and the switch. No file of the checkout differs from `before`. +fn declines(cell: &Cell, with: &Vendoring, args: &[&str], exit: i32, action: &str, before: &Tree) { + let names = refusal_names(cell); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &names.each_ref().map(String::as_str), + }; + cell.declined(&with.run(cell, args), &package, exit, action, before); +} + /// Vendored mode beside a hub that reads `requirements.txt`. /// /// - (a) `bazel build` and `bazel run //:consumer` print the unpatched /// marker. -/// - (b) `scan --mode vendored --yes` commits the patched wheel and points -/// the package's line of `requirements.txt` at it -/// ([`vendors_the_wheel`]). The command passes, and it and every other -/// form of `vex` write a document that says the package is affected: -/// each names the call of `MODULE.bazel` that reads the file, and the -/// way out. -/// - (c) The same `bazel build` fails, as the document said it may: -/// rules_python takes the path of that line for the name of a project -/// and leaves the hub without a repository it can name. No build holds -/// the patched wheel, and `vex` says affected again. +/// - (b) `scan --mode vendored --yes` declines the package: it exits 1, +/// names the call of `MODULE.bazel` that reads the file, hosted mode and +/// the switch, writes nothing and downloads no wheel. The same two Bazel +/// commands print the unpatched marker, and change no file. +/// - (c) With `--allow-vendored-in-bazel` the command does what it did +/// before it declined ([`vendors_the_wheel`]): it commits the patched +/// wheel and points the package's line of `requirements.txt` at it. It +/// passes, and it and every other form of `vex` write a document that +/// says the package is affected: each names the call of `MODULE.bazel` +/// that reads the file, and the way out. The same `bazel build` fails, +/// as the document said it may: rules_python takes the path of that +/// line for the name of a project and leaves the hub without a +/// repository it can name. No build holds the patched wheel, and `vex` +/// says affected again. /// - (d) What the document says to do: `vendor --revert` puts every file /// back, and the same two Bazel commands print the unpatched marker /// again. `scan --mode hosted --yes` then pins the patch in @@ -762,13 +810,19 @@ fn vendored_pip_parse() { // (a) The unpatched build. let before = cell.builds_unpatched(UNPATCHED); - // (b) Vendored mode commits the wheel, and says it is affected. - let vendored = vendors_the_wheel(&cell, &with); + // (b) The one command of vendored mode: declined, with nothing written + // and nothing of the patch fetched. The same build passes, on the + // upstream package. + declines(&cell, &with, &VENDORED, 1, "failed", &before); + assert_eq!(with.standin.asked(&with.route), 0, "{test}"); + cell.builds_patched(&before, UNPATCHED); - // (c) The build fails on the line that names the committed wheel, and - // changes no file of the checkout: rules_python makes the name of a - // repository from the path, and Bazel takes no such name. A console - // may break the message, so it is compared without white space. + // (c) On the user's word vendored mode commits the wheel, and says it + // is affected. The build fails on the line that names the committed + // wheel, and changes no file of the checkout: rules_python makes the + // name of a repository from the path, and Bazel takes no such name. A + // console may break the message, so it is compared without white space. + let vendored = vendors_the_wheel(&cell, &with); let build = cell.bazel("build", &[CONSUMER]); let named = format!( "invalid user-provided repo name 'pip_311__/_socket/vendor/pypi/{}/{}'", @@ -797,10 +851,11 @@ fn vendored_pip_parse() { cell.stands_alone(run, &claim, true); println!( - "{test}: Bazel {release} built {UNPATCHED:?}, and failed to build after `scan --mode \ - vendored` ({named}), while every form of `vex` said the package is affected; after \ - `vendor --revert` it built {UNPATCHED:?} again, and after `scan --mode hosted` \ - {marker:?}, and `vex` said it is not affected; {:?}", + "{test}: Bazel {release} built {UNPATCHED:?}; `scan --mode vendored` declined \ + ({DECLINED}), wrote nothing, and the build stayed {UNPATCHED:?}; with {ALLOW} it \ + vendored the wheel and the build failed ({named}), while every form of `vex` said the \ + package is affected; after `vendor --revert` it built {UNPATCHED:?} again, and after \ + `scan --mode hosted` {marker:?}, and `vex` said it is not affected; {:?}", started.elapsed() ); } @@ -819,14 +874,16 @@ fn checkout(with: &Vendoring) -> Cell { cell } -/// Without a Bazel: steps (b) and (d) of [`vendored_pip_parse`] in the +/// Without a Bazel: steps (c) and (d) of [`vendored_pip_parse`] in the /// fixture's checkout, where `MODULE.bazel` hands `requirements.txt` to -/// rules_python. Between them, `scan --mode vendored --vex`, `vendor --vex` -/// and `apply --vex` as a person runs them: each passes and writes the -/// document, with the warning on stderr, the line that it wrote a document -/// on stdout, and no error; with `--silent` each passes, writes the -/// document and prints nothing. After them, `vendor --vex` moves the -/// hosted pin into a committed copy again, and says affected again. +/// rules_python, so a vendored run that writes the line has the switch. +/// Between them, `scan --mode vendored --vex`, `vendor --vex` and +/// `apply --vex` as a person runs them, with no switch, since the file +/// already names the copy: each passes and writes the document, with the +/// warning on stderr, the line that it wrote a document on stdout, and no +/// error; with `--silent` each passes, writes the document and prints +/// nothing. After them, `vendor --vex` moves the hosted pin into a +/// committed copy again, and says affected again. #[test] fn a_vendored_wheel_is_affected_beside_a_hub_that_reads_the_requirements() { let with = Vendoring::new(); @@ -846,8 +903,7 @@ fn a_vendored_wheel_is_affected_beside_a_hub_that_reads_the_requirements() { names[0], with.uuid, names[1], names[2] ); let claim = Claim::unbuilt(PURL, &with.uuid, &names); - let scan = ["scan", "--mode", "vendored", "--yes"]; - for command in [&scan[..], &["vendor"], &["apply"]] { + for command in [&VENDORED[..], &["vendor"], &["apply"]] { let loud = [command, &with_vex(&document)].concat(); cell.tells_a_person(&origin, &loud, &env, &document, &claim, &warned); let silent = [&loud[..], &["--silent"]].concat(); @@ -863,7 +919,7 @@ fn a_vendored_wheel_is_affected_beside_a_hub_that_reads_the_requirements() { // `vendor` in a checkout of hosted pins commits a copy of each: the // line of `requirements.txt` points at the wheel again. let ejected = cell.document("eject"); - let eject = [&["vendor", "--yes"][..], &with_vex(&ejected)].concat(); + let eject = [&["vendor", "--yes", ALLOW][..], &with_vex(&ejected)].concat(); let eject = with.run(&cell, &eject); assert_eq!(eject.envelope["status"], "success", "{}", eject.dump); cell.wrote_in_run(&eject, &ejected, &claim); @@ -871,11 +927,11 @@ fn a_vendored_wheel_is_affected_beside_a_hub_that_reads_the_requirements() { assert!(line.contains(".socket/vendor/pypi/"), "{line}"); } -/// Without a Bazel: `vendor --vex` in a checkout whose manifest records -/// the patch, as agent mode leaves one. It commits the wheel, points -/// `requirements.txt` at it, and passes; its document says the package is -/// affected and names the call that reads the file, as the scan of -/// [`vendors_the_wheel`] does. +/// Without a Bazel: `vendor --vex` on the user's word in a checkout whose +/// manifest records the patch, as agent mode leaves one. It commits the +/// wheel, points `requirements.txt` at it, and passes; its document says +/// the package is affected and names the call that reads the file, as the +/// scan of [`vendors_the_wheel`] does. #[test] fn a_wheel_vendored_from_a_manifest_is_affected_beside_the_hub() { let with = Vendoring::new(); @@ -886,7 +942,7 @@ fn a_wheel_vendored_from_a_manifest_is_affected_beside_the_hub() { cell.write(".socket/manifest.json", manifest.to_string()); let document = cell.document("vendor"); - let vendor = [&["vendor", "--yes"][..], &with_vex(&document)].concat(); + let vendor = [&["vendor", "--yes", ALLOW][..], &with_vex(&document)].concat(); let vendor = with.run(&cell, &vendor); let line = String::from_utf8_lossy(&cell.tree()[REQUIREMENTS]).into_owned(); assert!( @@ -906,7 +962,8 @@ fn a_wheel_vendored_from_a_manifest_is_affected_beside_the_hub() { /// Without a Bazel: `vex` with a `--manifest-path` in another project /// attests that project, and asks the workspace about the files of that /// project. The checkout holds `svc`, where vendored mode pointed -/// `requirements.txt` at the wheel, and `app`, where the command is run. +/// `requirements.txt` at the wheel on the user's word, and `app`, where the +/// command is run. /// While the hub reads the file of `svc`, the document says the package /// is affected and names that file. While it reads the file of `app`, /// which pins the same release, the wheel of `svc` is attested as @@ -930,7 +987,7 @@ fn a_vendored_wheel_is_judged_by_the_files_of_the_manifest_s_project() { cell.write("MODULE.bazel", module.replace(&own, &label)); }; reads("svc"); - let vendoring = ["scan", "--mode", "vendored", "--yes", "--cwd", "svc"]; + let vendoring = [&VENDORED[..], &[ALLOW, "--cwd", "svc"]].concat(); let scan = with.run(&cell, &vendoring); assert_eq!(scan.envelope["summary"]["applied"], 1, "{}", scan.dump); @@ -950,6 +1007,131 @@ fn a_vendored_wheel_is_judged_by_the_files_of_the_manifest_s_project() { cell.stands_alone(run, &claim, true); } +/// Without a Bazel: in the fixture's checkout, where the hub reads +/// `requirements.txt`, every command that would vendor the package declines +/// it, writes nothing and fetches no wheel. On the user's word vendored +/// mode goes on, and a later run without it passes and writes nothing: the +/// file the hub reads already names the copy. +#[test] +fn every_command_that_would_vendor_declines_beside_a_hub_that_reads_the_requirements() { + let with = Vendoring::new(); + let cell = checkout(&with); + let names = refusal_names(&cell); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &names.each_ref().map(String::as_str), + }; + let run = |cell: &Cell, args: &[&str], env: &[(&str, &str)]| with.run_with(cell, args, env); + let before = cell.tree(); + cell.declines_every_vendoring(run, &package); + assert_eq!(with.standin.asked(&with.route), 0); + let undo = with.run(&cell, &["rollback", "--yes"]); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); + cell.vendors_on_the_users_word(run, &package); +} + +/// Without a Bazel: the refusal is for a run that would write a file a hub +/// reads, and for no other. In a workspace whose hub reads another file, in +/// a project beside the one whose file it reads, and in no workspace at +/// all, vendored mode vendors the package as it did, with no switch. So it +/// does in a Poetry project beside a hub that reads the requirements file +/// exported from its lock: the lock is wired alone, the file the hub reads +/// stays as it is, and a later run passes. Where the file the hub is given +/// is not written out in `MODULE.bazel`, and where `MODULE.bazel` has a +/// byte that is not UTF-8 (Bazel takes such a file, and the call in it is +/// not seen here), the package is declined, and the refusal names the +/// place and the reason. +#[test] +fn vendored_mode_goes_on_where_no_hub_reads_the_requirements() { + let with = Vendoring::new(); + let own = format!("\"//:{REQUIREMENTS}\""); + let module = |cell: &Cell| String::from_utf8(cell.tree()["MODULE.bazel"].clone()).unwrap(); + let vendors = |cell: &Cell, args: &[&str]| { + let scan = with.run(cell, &[&VENDORED[..], args].concat()); + assert_eq!(scan.code, 0, "{}", scan.dump); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{}", scan.dump); + }; + // Another file of the same project. + let cell = checkout(&with); + cell.write( + "MODULE.bazel", + module(&cell).replace(&own, "\"//:requirements_lock.txt\""), + ); + vendors(&cell, &[]); + // The file of another project, and no workspace file at all. + let cell = checkout(&with); + cell.write(&format!("svc/{REQUIREMENTS}"), requirements(&with.wheels)); + vendors(&cell, &["--cwd", "svc"]); + std::fs::remove_file(cell.path("MODULE.bazel")).expect("MODULE.bazel"); + let undo = with.run(&cell, &["vendor", "--revert", "--yes", "--cwd", "svc"]); + assert_eq!(undo.code, 0, "{}", undo.dump); + vendors(&cell, &[]); + // A Poetry project, whose lock is the one file a run points at the + // copy. The hub reads the requirements file exported from it. + let cell = checkout(&with); + let [_, upstream] = &with.wheels; + let poetry = format!( + "[[package]]\nname = \"{NAME}\"\nversion = \"{VERSION}\"\ndescription = \"\"\n\ + optional = false\npython-versions = \">=3.9\"\ngroups = [\"main\"]\nfiles = [\n \ + {{file = \"{}\", hash = \"sha256:{}\"}},\n]\n\n[metadata]\nlock-version = \"2.1\"\n\ + python-versions = \">=3.9\"\ncontent-hash = \"{}\"\n", + upstream.filename(), + upstream.sha256, + upstream.sha256 + ); + cell.write("poetry.lock", poetry); + let project = format!( + "[tool.poetry]\nname = \"demo\"\nversion = \"0.1.0\"\ndescription = \"\"\n\ + authors = []\npackage-mode = false\n\n[tool.poetry.dependencies]\n\ + python = \">=3.9\"\n{NAME} = \"{VERSION}\"\n" + ); + cell.write("pyproject.toml", project); + let before = cell.tree(); + vendors(&cell, &[]); + let vendored = cell.tree(); + assert!(vendored[REQUIREMENTS] == before[REQUIREMENTS]); + let lock = String::from_utf8_lossy(&vendored["poetry.lock"]); + assert!(lock.contains(".socket/vendor/pypi/"), "{lock}"); + for later in [&VENDORED[..], &["scan", "--yes"]] { + let scan = with.run(&cell, later); + assert_eq!(scan.code, 0, "{}", scan.dump); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{}", scan.dump); + } + + // A file that is not written out: the hub may read any. + let cell = checkout(&with); + cell.write("MODULE.bazel", module(&cell).replace(&own, "LOCK")); + let unread = format!( + "(MODULE.bazel:{}: the files `pip.parse` names", + hub_line(&cell) + ); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &[&unread, "cannot be read with certainty"], + }; + let before = cell.tree(); + cell.declined(&with.run(&cell, &VENDORED), &package, 1, "failed", &before); + + // A file that cannot be read here: it may hold a call that reads any. + let cell = checkout(&with); + cell.write( + "MODULE.bazel", + [module(&cell).as_bytes(), b"# caf\xe9\n"].concat(), + ); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &[ + "(MODULE.bazel: it cannot be read: it is not UTF-8)", + "cannot be read with certainty", + ], + }; + let before = cell.tree(); + cell.declined(&with.run(&cell, &VENDORED), &package, 1, "failed", &before); +} + /// Without a Bazel: the fixture's directories are those of its table, and /// the workflow runs each release on its era. The fixture holds no /// `requirements.txt`: every era names the one the test writes, which pins diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs index 60de2e0a9..a5f2b8dd6 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -26,12 +26,16 @@ //! //! The flow asserts the VEX document of its patch as `main.rs` says. //! -//! The vendored flow ([`vendored_bundle_fetch`]) commits the unpacked -//! patched gem under `.socket/vendor/gem` and makes `Gemfile` and -//! `Gemfile.lock` name it by its path from the project. rules_ruby runs -//! `bundle install` in a repository of Bazel's that holds the two files and -//! not the copy: the build fails until `vendor --revert` has put the two -//! files back. +//! Vendored mode would commit the unpacked patched gem under +//! `.socket/vendor/gem` and make `Gemfile` and `Gemfile.lock` name it by +//! its path from the project, and rules_ruby runs `bundle install` in a +//! repository of Bazel's that holds the two files and not the copy. So in +//! this checkout, where the hub reads both files, the command declines the +//! gem and writes nothing ([`vendored_bundle_fetch`]): the build stays the +//! unpatched one. With `--allow-vendored-in-bazel` it does what it did +//! before it declined, and the build fails until `vendor --revert` has put +//! the two files back. Hosted mode, which the refusal names, then patches +//! the build. //! //! Both markers are read from what Bazel built, and each holds an id made //! for the run, so no cache of an earlier run can supply either gem. The @@ -81,10 +85,10 @@ use sha2::{Digest, Sha256, Sha512}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; use crate::harness::{ - changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, StandIn, CONSUMER, - NOTHING, + cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Declined, Fixture, + How, Ran, StandIn, ALLOW, CONSUMER, NOTHING, VENDORED, }; -use crate::hosted_memory_common::{Patch, ORG}; +use crate::hosted_memory_common::{read_tree, Patch, ORG}; /// The sha256 of `bytes` in lowercase hex, as a `Gemfile.lock` and the gem /// index spell a sum. @@ -260,6 +264,8 @@ struct Served { /// one, as Bazel fetches them. upstream_route: String, patched_route: String, + /// The route of the patched gem as vendored mode downloads it. + artifact_route: String, } impl Served { @@ -360,6 +366,7 @@ impl Served { index, upstream_route, patched_route, + artifact_route: format!("{artifacts}.gem"), } } } @@ -394,6 +401,7 @@ fn hosted_bundle_fetch() { index, upstream_route, patched_route, + .. } = Served::to(&mut cell); let origin = standin.origin(); let socket_patch = |cell: &Cell, args: &[&str]| run(&standin, cell, args, &[]); @@ -516,22 +524,48 @@ fn hosted_bundle_fetch() { ); } +/// The code under which vendored mode declines a gem whose Gemfile or lock +/// a hub of the workspace reads, and what a refusal has to name in the +/// fixture's checkout: the hub's call with its line in `MODULE.bazel`, and +/// the file it reads. +const DECLINED: Declined = Declined { + purl: PURL, + code: "vendor_gem_bazel_hub", + names: &[ + "`ruby.bundle_fetch` (MODULE.bazel:15)", + "names Gemfile.lock; ", + ], +}; + +/// The variables of a command of vendored mode, which downloads the +/// patched gem from the patch host: the stand-in at `origin` is that host. +fn patch_host(origin: &str) -> [(&str, &str); 1] { + [("SOCKET_PATCH_SERVER_URL", origin)] +} + /// Vendored mode beside a hub that reads the Gemfile and its lock. /// /// - (a) `bazel build` and `bazel run //:consumer` print the unpatched /// marker. -/// - (b) `socket-patch scan --mode vendored --yes` passes and reports the -/// gem vendored. It commits the unpacked patched gem, with its -/// specification and its ledger, under `.socket/vendor`, and makes the -/// declaration of `Gemfile` and a `PATH` section of `Gemfile.lock` name -/// that copy by its path from the project. -/// - (c) The same `bazel build` fails: rules_ruby copies `Gemfile` and -/// `Gemfile.lock` into a repository of Bazel's and runs `bundle install` -/// there, where the path names nothing. `vex` attests the gem as patched -/// all the same: it reads the committed copy, and what rules_ruby builds -/// from one is not judged. -/// - (d) `socket-patch vendor --revert`: every file of the checkout is the -/// one of before, and the build prints the unpatched marker again. +/// - (b) `socket-patch scan --mode vendored --yes` declines the gem: it +/// exits 1, names the call of `MODULE.bazel` that reads the lock, hosted +/// mode and the switch, writes nothing and downloads no gem. The same +/// two Bazel commands print the unpatched marker, and change no file. +/// - (c) With `--allow-vendored-in-bazel` the command does what it did +/// before it declined: it passes and reports the gem vendored. It +/// commits the unpacked patched gem, with its specification and its +/// ledger, under `.socket/vendor`, and makes the declaration of +/// `Gemfile` and a `PATH` section of `Gemfile.lock` name that copy by +/// its path from the project. The same `bazel build` fails: rules_ruby +/// copies `Gemfile` and `Gemfile.lock` into a repository of Bazel's and +/// runs `bundle install` there, where the path names nothing. `vex` +/// attests the gem as patched all the same: it reads the committed +/// copy, and what rules_ruby builds from one is not judged. +/// - (d) `socket-patch vendor --revert`, which takes no switch: every file +/// of the checkout is the one of before, and the build prints the +/// unpatched marker again. +/// - (e) Hosted mode, which the refusal names: the same two Bazel commands +/// print the patched marker. #[test] #[ignore = "real Bazel; run with --ignored"] fn vendored_bundle_fetch() { @@ -544,15 +578,21 @@ fn vendored_bundle_fetch() { let served = Served::to(&mut cell); let (standin, uuid) = (&served.standin, served.uuid.as_str()); let origin = standin.origin(); - let patch_host = [("SOCKET_PATCH_SERVER_URL", origin.as_str())]; + let vendoring = |args: &[&str]| run(standin, &cell, args, &patch_host(&origin)); // (a) The unpatched build. let before = cell.builds_unpatched(&served.unpatched); - // (b) The one command of vendored mode: the copy, its ledger, and the - // two files that name it. - let vendoring = ["scan", "--mode", "vendored", "--yes"]; - let scan = run(standin, &cell, &vendoring, &patch_host); + // (b) The one command of vendored mode: declined, with nothing written + // and nothing of the patch fetched. The same build passes, on the + // upstream gem. + cell.declined(&vendoring(&VENDORED), &DECLINED, 1, "failed", &before); + assert_eq!(standin.asked(&served.artifact_route), 0, "{test}"); + cell.builds_patched(&before, &served.unpatched); + + // (c) On the user's word: the copy, its ledger, and the two files that + // name it. + let scan = vendoring(&[&VENDORED[..], &[ALLOW]].concat()); let said = &scan.dump; assert_eq!(scan.code, 0, "{test}: {said}"); assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); @@ -581,8 +621,8 @@ fn vendored_bundle_fetch() { let section = format!("PATH\n remote: {copy}\n specs:\n {NAME} ({VERSION})\n\n"); assert!(lock.starts_with(§ion), "{test}: Gemfile.lock:\n{lock}"); - // (c) The same build fails where rules_ruby runs Bundler, on the path - // of the copy, and changes no file of the checkout. Bundler breaks the + // The same build fails where rules_ruby runs Bundler, on the path of + // the copy, and changes no file of the checkout. Bundler breaks the // message at the width of its console, so it is compared without white // space. let build = cell.bazel("build", &[CONSUMER]); @@ -595,24 +635,129 @@ fn vendored_bundle_fetch() { build.dump() ); assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}"); - let attests = |cell: &Cell, args: &[&str]| run(standin, cell, args, &[]); - cell.stands_alone(attests, &Claim::new(PURL, uuid, How::Vendored), true); + let socket_patch = |cell: &Cell, args: &[&str]| run(standin, cell, args, &[]); + cell.stands_alone(socket_patch, &Claim::new(PURL, uuid, How::Vendored), true); // (d) The undo: every file is the one of before, and so is the build. - let undo = run(standin, &cell, &["vendor", "--revert", "--yes"], &[]); + let undo = socket_patch(&cell, &["vendor", "--revert", "--yes"]); cell.undone(&undo, "removed", &before, &served.unpatched); + // (e) The remedy the refusal names: hosted mode patches the build. + let scan = socket_patch(&cell, &["scan", "--mode", "hosted", "--yes"]); + let pinned = cell.pinned_by(&scan, PURL, uuid, &before, &["Gemfile", "Gemfile.lock"]); + cell.builds_patched(&pinned, &served.patched); + println!( - "{test}: Bazel {release} built {:?}; `scan --mode vendored` passed, wrote {copy} and \ - pointed Gemfile and Gemfile.lock at it, and the next build failed (Bundler: The path \ - ... does not exist) while `vex` attested the gem; `vendor --revert` restored all {} \ - files and the build; {:?}", + "{test}: Bazel {release} built {:?}; `scan --mode vendored` declined ({}), wrote \ + nothing, and the build stayed the same; with {ALLOW} it wrote {copy} and pointed \ + Gemfile and Gemfile.lock at it, and the next build failed (Bundler: The path ... does \ + not exist) while `vex` attested the gem; `vendor --revert` restored all {} files and \ + the build; `scan --mode hosted` built {:?}; {:?}", served.unpatched, + DECLINED.code, before.len(), + served.patched, started.elapsed() ); } +/// Without a Bazel: the fixture in a checkout of its own, whose lock pins +/// the gems of the stand-in that comes with it. +fn checkout() -> (Cell, Served) { + 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 served = Served::to(&mut cell); + (cell, served) +} + +/// Without a Bazel: in the fixture's checkout, where the hub reads the +/// Gemfile and its lock, every command that would vendor the gem declines +/// it, writes nothing and fetches no gem. On the user's word vendored mode +/// goes on, and a later run without it passes and writes nothing: the lock +/// the hub reads already names the copy. +#[test] +fn every_command_that_would_vendor_declines_beside_a_hub_that_reads_the_lock() { + let (cell, served) = checkout(); + let standin = &served.standin; + let origin = standin.origin(); + let run = |cell: &Cell, args: &[&str], env: &[(&str, &str)]| { + run( + standin, + cell, + args, + &[&patch_host(&origin)[..], env].concat(), + ) + }; + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + let called = module.lines().nth(14); + assert_eq!(called, Some("ruby.bundle_fetch("), "{}", DECLINED.names[0]); + let before = cell.tree(); + cell.declines_every_vendoring(run, &DECLINED); + assert_eq!(standin.asked(&served.artifact_route), 0); + let undo = run(&cell, &["rollback", "--yes"], &[]); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); + cell.vendors_on_the_users_word(run, &DECLINED); +} + +/// Without a Bazel: the refusal is the project's whose files a hub reads, +/// and no other's. In a workspace whose hub reads the files of another +/// project, and in no workspace at all, vendored mode vendors the gem as +/// it did, with no switch. Where the files the hub is given are not +/// written out in `MODULE.bazel`, the gem is declined, and the refusal +/// names the call and the reason. +#[test] +fn vendored_mode_goes_on_where_no_hub_reads_the_lock() { + let own = [ + "gemfile = \"//:Gemfile\"", + "gemfile_lock = \"//:Gemfile.lock\"", + ]; + let reads = |cell: &Cell, files: [&str; 2]| { + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + let other = module.replace(own[0], files[0]).replace(own[1], files[1]); + assert_ne!(other, module); + cell.write("MODULE.bazel", other); + }; + let scan = |cell: &Cell, served: &Served| { + let origin = served.standin.origin(); + run(&served.standin, cell, &VENDORED, &patch_host(&origin)) + }; + let vendors = |cell: &Cell, served: &Served| { + let scan = scan(cell, served); + assert_eq!(scan.code, 0, "{}", scan.dump); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{}", scan.dump); + }; + let (cell, served) = checkout(); + reads( + &cell, + [ + "gemfile = \"//svc:Gemfile\"", + "gemfile_lock = \"//svc:Gemfile.lock\"", + ], + ); + vendors(&cell, &served); + let (cell, served) = checkout(); + std::fs::remove_file(cell.path("MODULE.bazel")).expect("MODULE.bazel"); + vendors(&cell, &served); + + // Files that are not written out: the hub may read any. + let (cell, served) = checkout(); + reads(&cell, ["gemfile = GEMFILE", "gemfile_lock = LOCK"]); + let package = Declined { + names: &[ + "(MODULE.bazel:15: the files `ruby.bundle_fetch` names", + "cannot be read with certainty", + ], + ..DECLINED + }; + let before = cell.tree(); + cell.declined(&scan(&cell, &served), &package, 1, "failed", &before); +} + /// Without a Bazel, what stays fixed now that no sum is committed: the /// fixture's directories and the legs of its workflow are those of its /// table, and the `CHECKSUMS` section of the fixture's lock is one line per diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index 6c86baad8..465463b1b 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -13,8 +13,10 @@ //! points at a copy committed under `.socket/vendor`: 2.5.0-rc4 takes the //! path for the name of a project and fails the build of everything the //! hub serves (Bazel 9.3.2, 8.8.2 and 7.7.2). rules_js does build a -//! vendored tarball. What rules_ruby does with a vendored gem no build has -//! shown, so a vendored gem is not judged. +//! vendored tarball. rules_ruby 1.0.0-rc2 fails the build on a vendored +//! gem (same three releases) unless the call lists every file of the copy +//! among its `srcs`, which it copies beside the Gemfile: `srcs` is not +//! read here, so a vendored gem is not judged. //! //! [`unbuilt`] names, for a patched package, the call that builds it from a //! file without its patch. It says so only when the files of the workspace @@ -50,8 +52,23 @@ //! rules_js links nothing of the document pnpm 11 keeps for its own //! configuration. //! +//! [`reader`] answers the question vendored mode asks before it writes: +//! does a call of the hub name a file that the run would make point at a +//! copy under `.socket/vendor`? Where [`unbuilt`] says nothing when it is +//! in doubt, this one says so, because there a wrong "no" breaks a build. +//! Every call of the hub counts, also one that may not run, and so does a +//! call of a `WORKSPACE` file that passes one of the hub's files, which is +//! how the older form of the ruleset is called there (`pip_parse`, +//! `rb_bundle_fetch`). And where something of the workspace cannot be read +//! with certainty and a call of the hub may be behind it, the answer is +//! that doubt: the workspace calls the hub, or a file that was read names +//! its ruleset, or the root module file or the `WORKSPACE` file could not +//! be read at all. A file with one byte that is not UTF-8 is such a file, +//! and Bazel builds it. +//! //! Not looked at: what a `--override_repository` or an rc file changes, -//! BUILD files, and hubs of other rulesets. +//! BUILD files, the `.bzl` files a `WORKSPACE` file loads, and hubs of +//! other rulesets. //! //! [`Tags::doubts`]: super::workspace::Tags::doubts @@ -61,8 +78,9 @@ use std::path::{Component, Path}; use aho_corasick::AhoCorasick; -use super::starlark::{Call, Value}; -use super::workspace::{disk, Extension, Repo, Workspace}; +use super::starlark::{Call, File, Value}; +use super::workspace::{disk, Doubt, Extension, Repo, Workspace}; +use super::BazelRoot; use crate::formats::gem::locked_specs; use crate::formats::pnpm::grammar::documents; use crate::formats::pnpm::workspace::lock_text_member_importers; @@ -110,7 +128,8 @@ struct Hub { extension: Extension<'static>, tag: &'static str, /// The attributes that name such a file: a label, or a dict with a - /// label as each key. + /// label as each key. `uv_lock` is one for [`reader`] alone: [`judge`] + /// passes over a call that has it. files: &'static [&'static str], /// The packages a file lists plainly, each as its name and version. lists: fn(&str) -> Vec<(String, String)>, @@ -118,8 +137,8 @@ struct Hub { /// each from that directory: the members of a pnpm workspace. members: fn(&str) -> Vec, /// Whether a call of the tag may build a package from a line that - /// points at a copy under `.socket/vendor`: rules_js does, and of - /// rules_ruby no build has shown that it does not. + /// points at a copy under `.socket/vendor`: rules_js does, and + /// rules_ruby does when the call lists the files of the copy. builds_vendored: bool, } @@ -158,6 +177,7 @@ const HUBS: [Hub; 3] = [ "requirements_darwin", "requirements_linux", "requirements_windows", + "uv_lock", ], lists: |text| { let lines = logical_lines(text); @@ -218,16 +238,108 @@ pub async fn unbuilt(project: &Path, packages: Vec) -> Vec = parts - .map(|part| part.as_os_str().to_string_lossy()) - .collect(); - judge(&workspace, &parts.join("/"), &read, &packages) + judge(&workspace, &slashed(&root.project), &read, &packages) }) .await } +/// `path` with `/` between its parts, as Bazel has it on every system. +fn slashed(path: &Path) -> String { + let parts = path.components(); + let parts: Vec<_> = parts + .map(|part| part.as_os_str().to_string_lossy()) + .collect(); + parts.join("/") +} + +/// What stands between vendored mode and the locks of a project +/// ([`reader`]). `Ok`: this call of the hub names one of them, `lock`. +/// `Err`: this is why the files of the workspace are not read with +/// certainty, where a call of the hub that names such a lock may be behind +/// that. +pub type Reader = Result; + +/// The call of the workspace `root` that hands Bazel one of `locks`: files +/// of the project in that workspace, each by its path from the project, +/// which vendored mode would rewrite for a package of `ecosystem` (the type +/// of its purls). Or the doubt that leaves that open. `None` when the +/// calls of the hub are read with certainty and name other files, and when +/// nothing shows that the workspace may call it: no call of the hub and no +/// file that names its ruleset, with a root module file and a `WORKSPACE` +/// file that were read or are not there. +pub async fn reader( + root: &BazelRoot, + ecosystem: &'static str, + locks: Vec, +) -> Option { + let (dir, project) = (root.dir.clone(), slashed(&root.project)); + run_blocking(move || reads(&Workspace::read(&disk(&dir)), &project, ecosystem, &locks)).await +} + +/// [`reader`] for the workspace `workspace` and the project in its +/// directory `project` (empty: the root itself). +fn reads( + workspace: &Workspace, + project: &str, + ecosystem: &str, + locks: &[String], +) -> Option { + let hub = HUBS.iter().find(|hub| hub.ecosystem == ecosystem)?; + let tags = workspace.tags(&hub.extension, hub.tag); + let tag = format!("{}.{}", hub.extension.name, hub.tag); + let tagged = tags.calls.iter().map(|at| (at.file, at.call, tag.as_str())); + // In a `WORKSPACE` file, the calls that pass one of the hub's files. + let legacy = workspace + .legacy + .as_ref() + .and_then(|read| read.as_ref().ok()); + let passes = |call: &&Call| hub.files.iter().any(|file| call.arg(file).is_some()); + let legacy = legacy.into_iter().flat_map(|(name, file)| { + let calls = file.calls.iter().filter(passes); + calls.map(move |call| (name.as_str(), call, call.callee.as_str())) + }); + let mut doubt = tags.doubts.first().cloned(); + let mut called = doubt.is_some(); + for (file, call, name) in tagged.chain(legacy) { + called = true; + let own = |lock: &String| locks.iter().any(|own| below(project, own) == *lock); + if let Some(lock) = files(workspace, call, hub.files).into_iter().find(own) { + return Some(Ok(Unbuilt { + call: name.to_string(), + file: file.to_string(), + line: call.line, + lock, + })); + } + let written = |file: &&str| { + let value = call.arg(file); + matches!(value, None | Some(Value::Str(_) | Value::Dict(_))) + }; + if doubt.is_none() && (call.unpacks() || !hub.files.iter().all(written)) { + doubt = Some(Doubt { + file: file.to_string(), + line: call.line, + why: format!("the files `{name}` names are not all written out"), + }); + } + } + // What could not be read of the workspace may hide a call of the hub + // where the hub is seen to be called, where a file that was read names + // its ruleset (as a dependency, or by the file of its extension under + // any name of the repository), and where the root module file was not + // read at all. So may a `WORKSPACE` file that could not be read. + let names = |call: &Call| match (call.callee.as_str(), call.arg("name"), call.positional(0)) { + ("bazel_dep", Some(Value::Str(name)), _) => name == hub.extension.module, + ("use_extension", _, Some(Value::Str(file))) => file.ends_with(hub.extension.file), + _ => false, + }; + let named = |(_, file): &(String, File)| file.calls.iter().any(names); + let may = || called || workspace.files.is_empty() || workspace.files.iter().any(named); + let hidden = || workspace.doubts.first().filter(|_| may()); + let unread = || workspace.legacy.as_ref()?.as_ref().err(); + doubt.or_else(|| hidden().or_else(unread).cloned()).map(Err) +} + /// The most of a lock that is read: the lock of a large pnpm workspace has /// some tens of MiB. A larger file decides nothing. const MAX_LOCK: u64 = 64 << 20; @@ -239,7 +351,7 @@ const MAX_LOCK: u64 = 64 << 20; /// workspace. `None` for that, for what is no file (a directory, which /// Windows does not even open, like any other) or not UTF-8, and for a /// file over [`MAX_LOCK`]. -fn lock_text(root: &Path, file: &str) -> Option { +pub(crate) fn lock_text(root: &Path, file: &str) -> Option { let path = root.join(file); let mut bytes = Vec::new(); let plain = |part| matches!(part, Component::Normal(_)); @@ -862,6 +974,217 @@ use_repo(ruby, "bundle") } } + /// What [`reads`] says of the locks `locks` of the project in + /// `project`, in the workspace of `files`: `call file:line lock`, or + /// `? file:line why` for a doubt. A file whose text starts with + /// [`UNREADABLE`] is one that cannot be read, for the reason after it. + fn reader_of(files: &[(&str, &str)], project: &str, ecosystem: &str, locks: &[&str]) -> String { + let text = |path: &str| files.iter().find(|(name, _)| *name == path); + let workspace = Workspace::read(&|path| match text(path) { + Some((_, text)) => match text.strip_prefix(UNREADABLE) { + Some(why) => Entry::Unreadable(why.to_string()), + None => Entry::Text(text.to_string()), + }, + None => Entry::Absent, + }); + let locks: Vec = locks.iter().map(|lock| lock.to_string()).collect(); + match reads(&workspace, project, ecosystem, &locks) { + Some(Ok(by)) => format!("{} {}:{} {}", by.call, by.file, by.line, by.lock), + Some(Err(doubt)) => format!("? {}:{} {}", doubt.file, doubt.line, doubt.why), + None => String::new(), + } + } + + /// The shop with `new` in the place of `old` in its root module. + fn shop_with(old: &str, new: &str) -> Vec<(&'static str, &'static str)> { + let root = ROOT.replace(old, new); + assert_ne!(root, ROOT, "{old}"); + with("MODULE.bazel", Box::leak(root.into_boxed_str())) + } + + const UNREADABLE: &str = "unreadable: "; + const PIP: &str = " requirements_lock = \"//api:requirements.txt\",\n"; + const UNWRITTEN: &str = "the files `pip.parse` names are not all written out"; + + /// A call of the hub that names a file vendored mode would rewrite is + /// found, under each attribute, and a project whose files no call + /// names has none. + #[test] + fn the_call_that_reads_a_lock_of_the_project_is_found() { + let pypi = |project, locks: &[&str]| reader_of(&SHOP, project, "pypi", locks); + let api = "pip.parse MODULE.bazel:15 api/requirements.txt"; + assert_eq!(pypi("api", &["requirements.txt"]), api); + assert_eq!(pypi("api", &["base.txt", "./requirements.txt"]), api); + let darwin = "pip.parse MODULE.bazel:20 tools/requirements_darwin.txt"; + assert_eq!( + pypi("tools", &["uv.lock", "requirements_darwin.txt"]), + darwin + ); + let gem = |project, locks: &[&str]| reader_of(&SHOP, project, "gem", locks); + let lock = "ruby.bundle_fetch billing/ruby.MODULE.bazel:2 billing/Gemfile.lock"; + assert_eq!(gem("billing", &["Gemfile", "Gemfile.lock"]), lock); + let gemfile = "ruby.bundle_fetch billing/ruby.MODULE.bazel:2 billing/Gemfile"; + assert_eq!(gem("billing", &["Gemfile"]), gemfile); + // A call that may not run counts, and so does a `uv_lock`. + let looped = "[pip.parse(requirements_lock = \"//api:requirements.txt\") for v in V]\n"; + let files = shop_with( + "pip.parse(\n hub_name = \"pypi\",", + &format!("{looped}pip.parse("), + ); + let looped = "pip.parse MODULE.bazel:15 api/requirements.txt"; + assert_eq!( + reader_of(&files, "api", "pypi", &["requirements.txt"]), + looped + ); + let files = shop_with(PIP, " uv_lock = \"//api:uv.lock\",\n"); + let uv = "pip.parse MODULE.bazel:15 api/uv.lock"; + assert_eq!(reader_of(&files, "api", "pypi", &["uv.lock"]), uv); + + // Other files of the project, another project, a file of another + // repository, another ecosystem, and one without a hub. + assert_eq!(pypi("api", &["requirements-dev.txt", "uv.lock"]), ""); + assert_eq!(pypi("mobile", &["requirements.txt"]), ""); + assert_eq!(pypi("", &["requirements.txt"]), ""); + assert_eq!(pypi("api/worker", &["requirements.txt"]), ""); + let files = shop_with( + "\"//api:requirements.txt\"", + "\"@other//api:requirements.txt\"", + ); + assert_eq!(reader_of(&files, "api", "pypi", &["requirements.txt"]), ""); + assert_eq!(gem("api", &["requirements.txt"]), ""); + assert_eq!(reader_of(&SHOP, "api", "cargo", &["requirements.txt"]), ""); + } + + /// Where the workspace calls the hub and what a call names cannot be + /// read, the answer is the doubt, for every project. A doubt of a + /// workspace that does not call the hub is none. + #[test] + fn a_hub_that_is_not_read_with_certainty_is_a_doubt() { + let pypi = |files: &[(&str, &str)], project| { + reader_of(files, project, "pypi", &["requirements.txt"]) + }; + let unwritten = format!("? MODULE.bazel:15 {UNWRITTEN}"); + for argument in [" requirements_lock = LOCK,\n", " **COMMON\n"] { + let files = shop_with(PIP, argument); + assert_eq!(pypi(&files, "api"), unwritten, "{argument}"); + assert_eq!(pypi(&files, "mobile"), unwritten, "{argument}"); + // A call that names a lock of the project is the answer all + // the same. + let darwin = "pip.parse MODULE.bazel:20 tools/requirements_darwin.txt"; + let named = reader_of(&files, "tools", "pypi", &["requirements_darwin.txt"]); + assert_eq!(named, darwin, "{argument}"); + } + // The proxy is handed on: other calls of the hub may be made. + let handed = with( + "MODULE.bazel", + Box::leak(format!("{ROOT}print(pip)\n").into_boxed_str()), + ); + let said = "? MODULE.bazel:31 `pip` is used other than to call a tag"; + assert_eq!(pypi(&handed, "mobile"), said); + assert_eq!( + pypi(&handed, "api"), + "pip.parse MODULE.bazel:15 api/requirements.txt" + ); + assert_eq!(reader_of(&handed, "mobile", "gem", &["Gemfile"]), ""); + + // A file of the workspace is missing: it may hold a call of the + // Python hub, which is called, and one of the Ruby hub, which is + // not seen while the root names its ruleset. + let missing: Vec<_> = SHOP + .into_iter() + .filter(|(name, _)| !name.ends_with("ruby.MODULE.bazel")) + .collect(); + let hidden = "? billing/ruby.MODULE.bazel:0 it does not exist; MODULE.bazel:30 includes it"; + assert_eq!(pypi(&missing, "mobile"), hidden); + let gem = reader_of(&missing, "billing", "gem", &["Gemfile", "Gemfile.lock"]); + assert_eq!(gem, hidden); + } + + /// A file that cannot be read may hold a call of a hub that no file + /// shows. Bazel builds one with a byte that is not UTF-8, so the answer + /// is a doubt where the root module file or the `WORKSPACE` file is + /// such a file, and where another is while a file that was read names + /// the ruleset. A doubt of a workspace that names neither ruleset is + /// none. + #[test] + fn a_file_that_cannot_be_read_may_hold_a_call_of_the_hub() { + let asked = |files: &[(&str, &str)], ecosystem| { + reader_of(files, "svc", ecosystem, &["requirements.txt", "Gemfile"]) + }; + let unread = "unreadable: it is not UTF-8"; + let why = "it cannot be read: it is not UTF-8"; + let root = [("MODULE.bazel", unread)]; + for ecosystem in ["pypi", "gem"] { + assert_eq!(asked(&root, ecosystem), format!("? MODULE.bazel:0 {why}")); + } + // An included file, under a root that names the Python ruleset: as + // a dependency, or by the file of its extension under a name that + // the unread file gives the repository. + let include = "include(\"//py:deps.MODULE.bazel\")\n"; + let said = format!("? py/deps.MODULE.bazel:0 {why}; MODULE.bazel:2 includes it"); + for names in [ + "bazel_dep(name = \"rules_python\", version = \"2.5.0-rc4\")\n", + "pip = use_extension(\"@py//python/extensions:pip.bzl\", \"pip\")\n", + ] { + let root = format!("{names}{include}"); + let files = [ + ("MODULE.bazel", root.as_str()), + ("py/deps.MODULE.bazel", unread), + ]; + assert_eq!(asked(&files, "pypi"), said, "{names}"); + assert_eq!(asked(&files, "gem"), "", "{names}"); + } + let neither = "bazel_dep(name = \"rules_go\", version = \"0.65.0\")\n"; + let root = format!("{neither}{include}"); + let files = [ + ("MODULE.bazel", root.as_str()), + ("py/deps.MODULE.bazel", unread), + ]; + assert_eq!( + (asked(&files, "pypi"), asked(&files, "gem")), + Default::default() + ); + // The `WORKSPACE` file, beside a `MODULE.bazel` that is read or + // alone. + let module = ("MODULE.bazel", "module(name = \"shop\")\n"); + for files in [ + vec![module, ("WORKSPACE.bazel", unread)], + vec![("WORKSPACE", unread)], + ] { + let said = format!("? {}:0 {why}", files.last().unwrap().0); + for ecosystem in ["pypi", "gem"] { + assert_eq!(asked(&files, ecosystem), said); + } + } + } + + /// A call of a `WORKSPACE` file that passes one of the hub's files is + /// a call of the ruleset's older form, with or without a `MODULE.bazel`. + #[test] + fn a_workspace_file_that_names_the_lock_counts() { + let legacy = "load(\"@rules_python//python:pip.bzl\", \"pip_parse\")\n\ + pip_parse(\n name = \"pypi\",\n requirements_lock = \"//svc:requirements.txt\",\n)\n\ + rb_bundle_fetch(name = \"bundle\", gemfile = \"//svc:Gemfile\", gemfile_lock = LOCK)\n\ + http_archive(name = \"x\", requirements = \"//other:requirements.txt\")\n"; + for files in [with("WORKSPACE", legacy), vec![("WORKSPACE.bazel", legacy)]] { + let name = files.last().unwrap().0; + let asked = + |project, ecosystem, locks: &[&str]| reader_of(&files, project, ecosystem, locks); + let pip = format!("pip_parse {name}:2 svc/requirements.txt"); + assert_eq!(asked("svc", "pypi", &["requirements.txt"]), pip); + assert_eq!(asked("other", "pypi", &["requirements.txt"]), ""); + let gemfile = format!("rb_bundle_fetch {name}:6 svc/Gemfile"); + assert_eq!(asked("svc", "gem", &["Gemfile", "Gemfile.lock"]), gemfile); + let doubt = + format!("? {name}:6 the files `rb_bundle_fetch` names are not all written out"); + assert_eq!(asked("other", "gem", &["Gemfile", "Gemfile.lock"]), doubt); + } + // A file that calls neither says nothing of them. + let rule = "http_archive(name = \"x\", urls = [LOCK])\n"; + let files = [("WORKSPACE", rule)]; + assert_eq!(reader_of(&files, "svc", "pypi", &["requirements.txt"]), ""); + } + #[test] fn a_project_is_in_the_directory_of_a_lock_or_below_it_or_neither() { for (project, lock, from) in [ diff --git a/crates/socket-patch-core/src/vendor/bazel_hub.rs b/crates/socket-patch-core/src/vendor/bazel_hub.rs new file mode 100644 index 000000000..682f8bc52 --- /dev/null +++ b/crates/socket-patch-core/src/vendor/bazel_hub.rs @@ -0,0 +1,439 @@ +//! PyPI and RubyGems vendored mode for a project whose lock a Bazel hub +//! reads: declined unless the user allows it. +//! +//! rules_python's `pip.parse` and rules_ruby's `ruby.bundle_fetch` build +//! the packages of a lock in repositories of Bazel's own. Vendored mode +//! makes the lock name the patched copy by a path under `.socket/vendor`, +//! and neither ruleset builds from that. rules_python 2.5.0-rc4 makes the +//! name of a repository from the path of a requirements line (`invalid +//! user-provided repo name 'pip_311__/_socket/vendor/pypi/...'`). +//! rules_ruby 1.0.0-rc2 runs `bundle install` in a repository that holds +//! the Gemfile and its lock and not the copy (`The path ... does not +//! exist.`). Either fails the build of everything the hub serves, after a +//! command that exited 0 (Bazel 9.3.2, 8.8.2 and 7.7.2). +//! +//! Which lock a hub reads is in the files of the workspace +//! ([`crate::bazel::built::reader`]), so the refusal is for a package whose +//! run would write a file that one reads and for no other. A project +//! beside a workspace whose calls name other files is vendored as it is +//! without Bazel, and so is a package whose run leaves the file the hub +//! reads alone: one of a Poetry or PDM project, whose lock is wired alone, +//! beside a hub that reads the requirements file exported from it +//! ([`super::pypi::hub_files`]). Where the files of the workspace cannot be +//! read with certainty and a call of the hub may be behind that, the +//! package is declined as well. Going on there can break a build; +//! declining costs a vendored run that the user's word brings back. +//! +//! What is declined is the write of that path into the lock the hub reads. +//! A package that this lock already names by the copy of the same patch is +//! let through: the run adds nothing to what the hub reads, so a project +//! that was vendored before (by an earlier release, or with the flag) keeps +//! passing its in-sync runs. Where the reading is in doubt no lock is known +//! to be the hub's, and nothing is let through. + +use std::path::Path; + +use crate::bazel::built::{lock_text, reader, Unbuilt}; +use crate::bazel::workspace::Doubt; +use crate::bazel::BazelRoot; +use crate::crawlers::Ecosystem; +use crate::utils::env_compat::env_flag; +use crate::utils::fs::run_blocking; +use crate::utils::pnpm_workspace::without_verbatim_prefix; +use crate::vendor::path::vendor_uuid_dir_rel; +use crate::vendor::refusals::ALLOW_IN_BAZEL_ENV; + +/// The codes of [`refusals`], one per ecosystem. +pub const PYPI_CODE: &str = "vendor_pypi_bazel_hub"; +pub const GEM_CODE: &str = "vendor_gem_bazel_hub"; + +/// The PyPI and RubyGems `candidates` (`(purl, uuid)` pairs) that vendored +/// mode declines in the project at `project`, each with its code and the +/// detail. It declines a package whose hub may read a file of the project +/// that the run would rewrite, unless the user allowed it +/// ([`ALLOW_IN_BAZEL_ENV`]), and lets through a package the hub's lock +/// already names by the copy of that patch. Nothing is declined outside a +/// Bazel workspace ([`crate::bazel::bazel_root`]). Read-only, and it starts +/// no program. +pub async fn refusals<'a>( + project: &Path, + candidates: &[(&'a str, &str)], +) -> Vec<(&'a str, &'static str, String)> { + refusals_unless(project, candidates, env_flag(ALLOW_IN_BAZEL_ENV)).await +} + +/// What stands between vendored mode and a list of files of a project +/// ([`standing`]): the words of the refusal, and the text of the lock the +/// hub reads where a call names one. `None` where nothing does. +type Standing = Option<(String, Option)>; + +/// What rules_ruby builds of a hosted pin: the `sha256` of a gem that the +/// call lists holds the build to the registry's gem. +const GEM_HOSTED: &str = " where its call passes no `gem_checksums`"; + +/// [`refusals`] for a user who `allowed` it or did not. +async fn refusals_unless<'a>( + project: &Path, + candidates: &[(&'a str, &str)], + allowed: bool, +) -> Vec<(&'a str, &'static str, String)> { + let mut refused = Vec::new(); + // The code, the type of the purls, the ruleset, and what its hosted + // pin takes. + let hub = |purl: &str| match Ecosystem::from_purl(purl)? { + Ecosystem::Pypi => Some((PYPI_CODE, "pypi", "rules_python", "")), + Ecosystem::Gem => Some((GEM_CODE, "gem", "rules_ruby", GEM_HOSTED)), + _ => None, + }; + if allowed || !candidates.iter().any(|(purl, _)| hub(purl).is_some()) { + return refused; + } + let dir = project.to_path_buf(); + let Some(root) = run_blocking(move || crate::bazel::bazel_root(&dir)).await else { + return refused; + }; + // What stands in the way of each list of files, asked once per list. + let mut asked: Vec<(_, Standing)> = Vec::new(); + for (purl, uuid) in candidates { + let Some((code, purls, ruleset, hosted)) = hub(purl) else { + continue; + }; + // The files a hub can be given that the run for this package would + // point at a copy. With none, no hub stands in its way. + let locks = match purls { + "pypi" => super::pypi::hub_files(project, purl).await, + _ => ["Gemfile", "Gemfile.lock"].map(String::from).to_vec(), + }; + if locks.is_empty() { + continue; + } + let list = (purls, locks); + let at = match asked.iter().position(|(of, _)| *of == list) { + Some(at) => at, + None => { + let stands = standing(&root, purls, ruleset, hosted, list.1.clone()).await; + asked.push((list, stands)); + asked.len() - 1 + } + }; + let Some((detail, lock)) = &asked[at].1 else { + continue; + }; + // A lock names the copy of a patch by the copy's directory, outside + // a comment (`#` starts one in each of these files). + let copy = vendor_uuid_dir_rel(purls, uuid).map(|dir| format!("{dir}/")); + let wired = match (lock, copy) { + (Some(lock), Some(copy)) => { + let names = |line: &str| line.split('#').next().is_some_and(|l| l.contains(©)); + lock.lines().any(names) + } + _ => false, + }; + if !wired { + refused.push((*purl, code, detail.clone())); + } + } + refused +} + +/// The [`Standing`] of the files `locks` of the project of `root`, for the +/// packages of `ruleset` (purls of the type `purls`), whose hosted pin is +/// built `hosted`. +async fn standing( + root: &BazelRoot, + purls: &'static str, + ruleset: &str, + hosted: &str, + locks: Vec, +) -> Standing { + // The root is canonical: on Windows that spelling has a prefix no user + // types and no tool prints. + let at = without_verbatim_prefix(root.dir.clone()); + let at = at.display(); + let (reads, lock) = match reader(root, purls, locks).await? { + Ok(Unbuilt { + call, + file, + line, + lock, + }) => { + let reads = + format!("`{call}` ({file}:{line}) of the Bazel workspace at {at} names {lock}"); + // Read as a lock of the workspace is: within its bound, and + // not through a link that leads out of the Bazel root. + let dir = root.dir.clone(); + (reads, run_blocking(move || lock_text(&dir, &lock)).await) + } + Err(Doubt { file, line, why }) => { + let line = match line { + 0 => String::new(), + line => format!(":{line}"), + }; + let reads = format!( + "the files of the Bazel workspace at {at} cannot be read with certainty, so a \ + call of {ruleset} may name a lock of this project ({file}{line}: {why})" + ); + (reads, None) + } + }; + let detail = format!( + "{reads}; vendored mode makes the lock name the patched copy by a path under \ + .socket/vendor, and {ruleset} fails the build on such a lock; use `--mode hosted`, \ + which names the patched package by a URL that {ruleset} fetches{hosted}, or pass \ + `--allow-vendored-in-bazel` if no build takes the packages of this project from \ + {ruleset}" + ); + Some((detail, lock)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + const UUID: &str = "11111111-1111-4111-8111-111111111111"; + const OTHER_UUID: &str = "33333333-3333-4333-8333-333333333333"; + + /// A checkout whose root `MODULE.bazel` is `module`, canonical, with + /// the files `files`. + fn checkout(module: &str, files: &[(&str, &str)]) -> (tempfile::TempDir, std::path::PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let root = fs::canonicalize(tmp.path()).unwrap(); + let all = [ + (".git/HEAD", "ref: refs/heads/main\n"), + ("MODULE.bazel", module), + ]; + for (path, text) in all.iter().chain(files) { + let path = root.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + (tmp, root) + } + + const HUBS: &str = r#"pip = use_extension("@rules_python//python/extensions:pip.bzl", "pip") +pip.parse(hub_name = "pypi", python_version = "3.11", requirements_lock = "//api:base.txt") +ruby = use_extension("@rules_ruby//ruby:extensions.bzl", "ruby") +ruby.bundle_fetch(name = "bundle", gemfile = "//api:Gemfile", gemfile_lock = "//api:Gemfile.lock") +"#; + + /// The refusal of one package of `ecosystem` in `project`, for a user + /// who `allowed` it or did not: its code and detail. + async fn asked( + project: &Path, + ecosystem: Ecosystem, + allowed: bool, + ) -> Option<(&'static str, String)> { + let purl = format!("pkg:{}/x@1.0.0", ecosystem.cli_name()); + let refused = refusals_unless(project, &[(&purl, UUID)], allowed).await; + refused.into_iter().map(|(_, code, why)| (code, why)).next() + } + + async fn declined(project: &Path, ecosystem: Ecosystem) -> (&'static str, String) { + asked(project, ecosystem, false).await.unwrap_or_default() + } + + #[tokio::test] + async fn a_project_whose_lock_a_hub_reads_is_declined_and_no_other() { + let requirements = ("api/requirements.txt", "-r base.txt\nidna==3.7\n"); + let (_tmp, root) = checkout(HUBS, &[requirements, ("web/requirements.txt", "")]); + let (api, web) = (root.join("api"), root.join("web")); + let shown = without_verbatim_prefix(root.clone()); + let at = format!("of the Bazel workspace at {} names", shown.display()); + // The requirements file the hub is given is one the project's own + // brings in; the Gemfile and its lock are the project's. + for (ecosystem, code, names) in [ + ( + Ecosystem::Pypi, + PYPI_CODE, + [ + "`pip.parse` (MODULE.bazel:2)", + "names api/base.txt; ", + "and rules_python fails the build", + ], + ), + ( + Ecosystem::Gem, + GEM_CODE, + [ + "`ruby.bundle_fetch` (MODULE.bazel:4)", + "names api/Gemfile.lock; ", + "and rules_ruby fails the build", + ], + ), + ] { + let (declined, detail) = declined(&api, ecosystem).await; + assert_eq!(declined, code); + let named = [&at, "`--mode hosted`", "`--allow-vendored-in-bazel`"]; + let mut named = named.iter().chain(&names); + assert!(named.all(|part| detail.contains(part)), "{detail}"); + // The user's word lifts it, and a project whose files no call + // names is not declined: one beside it, and the root. + assert_eq!(asked(&api, ecosystem, true).await, None); + assert_eq!(asked(&web, ecosystem, false).await, None); + assert_eq!(asked(&root, ecosystem, false).await, None); + } + // No other ecosystem has such a hub. + for other in [Ecosystem::Npm, Ecosystem::Composer, Ecosystem::Cargo] { + assert_eq!(asked(&api, other, false).await, None, "{other:?}"); + } + // The Gemfile alone is a file the run rewrites, and hosted mode is + // named with what rules_ruby builds of it. + let alone = HUBS.replace(", gemfile_lock = \"//api:Gemfile.lock\"", ""); + fs::write(root.join("MODULE.bazel"), alone).unwrap(); + let (code, detail) = declined(&api, Ecosystem::Gem).await; + assert_eq!(code, GEM_CODE); + let named = [ + "names api/Gemfile; ", + "that rules_ruby fetches where its call passes no `gem_checksums`, or pass", + ]; + assert!(named.iter().all(|part| detail.contains(part)), "{detail}"); + let (_, detail) = declined(&api, Ecosystem::Pypi).await; + assert!( + detail.contains("that rules_python fetches, or pass"), + "{detail}" + ); + // Without the workspace file nothing is declined. + fs::remove_file(root.join("MODULE.bazel")).unwrap(); + assert_eq!(asked(&api, Ecosystem::Pypi, false).await, None); + assert_eq!(asked(&api, Ecosystem::Gem, false).await, None); + } + + /// A package that the lock the hub reads already names by the copy of + /// the same patch is let through: the run adds nothing to what the hub + /// reads. A package whose patch that lock does not name is declined, + /// and so is one whose copy is named only in a comment or only in + /// another file than the one the call names, and every package of a + /// hub that is in doubt. + #[tokio::test] + async fn a_package_the_hub_s_lock_already_names_by_the_patch_s_copy_is_let_through() { + let (_tmp, root) = checkout(HUBS, &[("api/requirements.txt", "-r base.txt\n")]); + let api = root.join("api"); + let (wheel, other, gem) = ("pkg:pypi/a@1.0.0", "pkg:pypi/c@2.0.0", "pkg:gem/b@1.0.0"); + let candidates = [(wheel, UUID), (other, OTHER_UUID), (gem, UUID)]; + let declined = || async { + let refused = refusals_unless(&api, &candidates, false).await; + refused + .into_iter() + .map(|(purl, _, _)| purl) + .collect::>() + }; + let line = format!("./.socket/vendor/pypi/{UUID}/a-1.0.0-py3-none-any.whl # a==1.0.0\n"); + let path = format!("PATH\n remote: .socket/vendor/gem/{UUID}/b-1.0.0\n"); + fs::write(api.join("base.txt"), &line).unwrap(); + fs::write(api.join("Gemfile.lock"), &path).unwrap(); + assert_eq!(declined().await, [other]); + // The lock is read as a file of the workspace is: one that is a + // link out of the Bazel root lets nothing through. + #[cfg(unix)] + { + let outside = tempfile::tempdir().unwrap(); + let named = outside.path().join("base.txt"); + fs::write(&named, &line).unwrap(); + fs::remove_file(api.join("base.txt")).unwrap(); + std::os::unix::fs::symlink(&named, api.join("base.txt")).unwrap(); + assert_eq!(declined().await, [wheel, other]); + fs::remove_file(api.join("base.txt")).unwrap(); + } + // Named in a comment, the copy is not what the lock installs. + fs::write(api.join("base.txt"), format!("a==1.0.0 # was {line}")).unwrap(); + assert_eq!(declined().await, [wheel, other]); + // Named by the Gemfile alone: the lock is the file the call names + // first, and it still holds the registry's gem. + fs::write( + api.join("Gemfile"), + path.replace("remote:", "gem 'b', path:"), + ) + .unwrap(); + fs::write(api.join("Gemfile.lock"), "GEM\n specs:\n b (1.0.0)\n").unwrap(); + assert_eq!(declined().await, [wheel, other, gem]); + // A hub whose file is not written out: no lock is known to be its. + fs::write(api.join("base.txt"), &line).unwrap(); + let unwritten = HUBS.replace("\"//api:base.txt\"", "LOCK"); + fs::write(root.join("MODULE.bazel"), unwritten).unwrap(); + assert_eq!(declined().await, [wheel, other, gem]); + } + + /// The uv lock of the project is a file a hub can be given, and a hub + /// whose files are not written out declines every project of its + /// ecosystem that a run would write, with the place and the reason. + #[tokio::test] + async fn a_uv_lock_counts_and_a_hub_that_cannot_be_read_declines() { + let uv = HUBS.replace( + "requirements_lock = \"//api:base.txt\"", + "uv_lock = \"//api:uv.lock\"", + ); + let (_tmp, root) = checkout(&uv, &[("api/uv.lock", "")]); + let (code, detail) = declined(&root.join("api"), Ecosystem::Pypi).await; + assert_eq!(code, PYPI_CODE); + assert!(detail.contains("names api/uv.lock; "), "{detail}"); + + let unwritten = HUBS.replace("\"//api:base.txt\"", "LOCK"); + let web = ("web/requirements.txt", ""); + let (_tmp, root) = checkout(&unwritten, &[web]); + let (code, detail) = declined(&root.join("web"), Ecosystem::Pypi).await; + assert_eq!(code, PYPI_CODE); + let named = [ + "cannot be read with certainty, so a call of rules_python may name a lock of this \ + project (MODULE.bazel:2: the files `pip.parse` names are not all written out); ", + "`--mode hosted`", + "`--allow-vendored-in-bazel`", + ]; + assert!(named.iter().all(|part| detail.contains(part)), "{detail}"); + // The doubt is about the Python hub alone. + assert_eq!(asked(&root.join("web"), Ecosystem::Gem, false).await, None); + // A file the root includes is missing: the doubt is about a file. + let included = format!("{HUBS}include(\"//api:more.MODULE.bazel\")\n"); + let (_tmp, root) = checkout(&included, &[]); + let (_, detail) = declined(&root.join("web"), Ecosystem::Gem).await; + assert!( + detail.contains("(api/more.MODULE.bazel: it does not exist"), + "{detail}" + ); + } + + /// The requirements file a hub reads is one the run writes where it is + /// what is wired, and where it names the package beside a uv, Pipenv or + /// Python lock. A Poetry or PDM lock is wired alone: the package of + /// such a project is not declined beside a hub that reads the + /// requirements file exported from the lock, whatever the hub's files + /// leave open. Nor is a package the requirements file beside a uv lock + /// does not name. + #[tokio::test] + async fn a_package_whose_run_leaves_the_hub_s_file_alone_is_not_declined() { + let hub = HUBS.replace("//api:base.txt", "//api:requirements.txt"); + let (_tmp, root) = checkout(&hub, &[("api/requirements.txt", "x==1.0.0\n")]); + let api = root.join("api"); + let pypi = || async { + let asked = asked(&api, Ecosystem::Pypi, false).await; + asked.map(|(code, _)| code) + }; + assert_eq!(pypi().await, Some(PYPI_CODE)); + let unwritten = hub.replace("\"//api:requirements.txt\"", "LOCK"); + for lock in ["poetry.lock", "pdm.lock"] { + fs::write(api.join(lock), "").unwrap(); + assert_eq!(pypi().await, None, "{lock}"); + fs::write(root.join("MODULE.bazel"), &unwritten).unwrap(); + assert_eq!(pypi().await, None, "{lock}, a hub in doubt"); + fs::write(root.join("MODULE.bazel"), &hub).unwrap(); + fs::remove_file(api.join(lock)).unwrap(); + } + // A uv or Pipenv lock is wired with the pin of the requirements + // file, also one that hosted mode made or an earlier patch. + for lock in ["uv.lock", "Pipfile.lock"] { + fs::write(api.join(lock), "").unwrap(); + let vendored = format!("./.socket/vendor/pypi/{OTHER_UUID}/x-1.0.0-py3-none-any.whl\n"); + for names in [ + "x==1.0.0\n", + "x @ https://h/x-1.0.0-py3-none-any.whl\n", + &vendored, + ] { + fs::write(api.join("requirements.txt"), names).unwrap(); + assert_eq!(pypi().await, Some(PYPI_CODE), "{lock}: {names}"); + } + fs::write(api.join("requirements.txt"), "y==1.0.0\n").unwrap(); + assert_eq!(pypi().await, None, "{lock}"); + fs::remove_file(api.join(lock)).unwrap(); + } + } +} diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 2243aa74d..5977a0eeb 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -48,6 +48,7 @@ pub mod path; pub mod state; +pub mod bazel_hub; #[cfg(any(test, feature = "test-fixtures"))] pub(crate) mod berry_zip; mod bun_binary; diff --git a/crates/socket-patch-core/src/vendor/pypi.rs b/crates/socket-patch-core/src/vendor/pypi.rs index 4010f649f..a2e7958a2 100644 --- a/crates/socket-patch-core/src/vendor/pypi.rs +++ b/crates/socket-patch-core/src/vendor/pypi.rs @@ -1609,6 +1609,40 @@ fn sibling_lock(flavor: PypiFlavor) -> Option<(&'static str, &'static str)> { } } +/// The files of the project that a vendored run for `purl` may point at the +/// patched copy and that a hub of a Bazel workspace can be given +/// ([`super::bazel_hub`]), each by its path from the project. `uv.lock` +/// where it governs. The requirements files where they are what is wired, +/// and where they name the package beside a uv, Pipenv or Python lock, +/// which is wired together with a pin of theirs +/// ([`super::pypi_requirements::sibling_names_package`]). None for a +/// Poetry or PDM lock, which is wired alone, and for a project the router +/// refuses, where nothing is written. +pub(super) async fn hub_files(project_root: &Path, purl: &str) -> Vec { + let mut files = Vec::new(); + let Some((name, version)) = parse_pypi_purl(purl) else { + return files; + }; + let name = canonicalize_pypi_name(&name); + let Ok((flavor, _)) = detect_pypi_flavor(project_root, Some((&name, &version))).await else { + return files; + }; + let requirements = match flavor { + PypiFlavor::Requirements => true, + _ if sibling_lock(flavor).is_none() => false, + _ => super::pypi_requirements::sibling_names_package(project_root, &name).await, + }; + if requirements { + let included = super::requirements_include_names(project_root).await; + files = included.unwrap_or_default(); + files.push(crate::formats::governing_locks::PYPI_REQUIREMENTS.to_string()); + } + if flavor == PypiFlavor::UvProject { + files.push("uv.lock".to_string()); + } + files +} + /// How the sibling notes name the requirements file wired with `flavor`'s /// lock: an export of a Pipenv or uv lock, but the file a `pip lock` /// pylock was locked from (#1758). diff --git a/crates/socket-patch-core/src/vendor/pypi_requirements.rs b/crates/socket-patch-core/src/vendor/pypi_requirements.rs index 79f436fa1..3b6ae5fe3 100644 --- a/crates/socket-patch-core/src/vendor/pypi_requirements.rs +++ b/crates/socket-patch-core/src/vendor/pypi_requirements.rs @@ -483,6 +483,20 @@ pub(super) async fn sibling_pin_wirable(root: &Path, canon_name: &str, version: && refuse_symlinked(root, &rels).await.is_ok() } +/// Whether a vendored run that wires a Pipenv, uv or Python lock for +/// `canon_name` may write the requirements set beside it as well: a file of +/// the set names the package. A pin of the release is wired with the lock +/// ([`sibling_pin_wirable`]), a hosted pin is such a pin once a takeover +/// has restored it, and a vendor line is re-wired by a later patch of the +/// package. A set that does not name the package is never written. +pub(super) async fn sibling_names_package(root: &Path, canon_name: &str) -> bool { + let names = |file: &ReqFile| { + names_package(&file.content, canon_name) || has_vendor_line(&file.content, canon_name) + }; + let files = collect_requirements_files(root).await; + files.is_ok_and(|files| files.iter().any(names)) +} + /// #1873: refuse a requirements line naming `canon_name` through a /// `${NAME}` pip expands where it runs (`six==${SIXV}`). What it installs /// is unknowable here, so the vendor neither rewrites it nor names the file diff --git a/crates/socket-patch-core/src/vendor/refusals.rs b/crates/socket-patch-core/src/vendor/refusals.rs index 87e710769..7db1b4b2b 100644 --- a/crates/socket-patch-core/src/vendor/refusals.rs +++ b/crates/socket-patch-core/src/vendor/refusals.rs @@ -23,10 +23,12 @@ //! as a skip); //! 6. a Maven version no module of the build selects //! (`vendor_maven_version_not_selected`, a skip too); -//! 7. a Composer project in a Bazel workspace -//! (`vendor_composer_bazel_workspace`), unless the user allowed it -//! ([`ALLOW_IN_BAZEL_ENV`]) or the lock already names the patch's copy -//! ([`bazel_workspace_refusals`]). +//! 7. a project in a Bazel workspace whose build would not find the +//! vendored copy ([`bazel_workspace_refusals`]), unless the user allowed +//! it ([`ALLOW_IN_BAZEL_ENV`]) or the lock already names the patch's +//! copy: any Composer project (`vendor_composer_bazel_workspace`), and a +//! PyPI or RubyGems project whose lock a hub of the workspace reads +//! (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`). //! //! Each check lives in its backend's module; this one only dispatches and //! scopes them. @@ -40,7 +42,9 @@ use crate::crawlers::Ecosystem; use crate::patch::redirect::upstream::HostedPin; use crate::utils::purl_key::PurlKey; use crate::vendor::state::{lookup_entry, VendorEntry}; -use crate::vendor::{bun_lock, composer_lock, gem, lock_inventory, npm_flavor, npm_lock, vlt_lock}; +use crate::vendor::{ + bazel_hub, bun_lock, composer_lock, gem, lock_inventory, npm_flavor, npm_lock, vlt_lock, +}; /// The vendor ledger as the refusals consume it: the caller's own load /// outcome, so an UNREADABLE ledger is a refusal the run can report @@ -113,7 +117,9 @@ fn is_composer(purl: &str) -> bool { /// vendored entry point takes this one answer: [`vendor_refusals`] hands it /// to a scan, a `get` and a `vendor`, and the eject of hosted pins asks it /// before it fetches or restores anything. A refusal of this kind for -/// another ecosystem belongs here; Composer's is the only one today. +/// another ecosystem belongs here. Today: any Composer project +/// ([`composer_lock::bazel::refusals`]), and a PyPI or RubyGems project +/// whose lock a hub of the workspace reads ([`bazel_hub::refusals`]). pub async fn bazel_workspace_refusals<'a>( project_root: &Path, candidates: &[(&'a str, &str)], @@ -123,7 +129,9 @@ pub async fn bazel_workspace_refusals<'a>( .filter(|(purl, _)| is_composer(purl)) .copied() .collect(); - composer_lock::bazel::refusals(project_root, &composer).await + let mut refused = composer_lock::bazel::refusals(project_root, &composer).await; + refused.extend(bazel_hub::refusals(project_root, candidates).await); + refused } /// Every refusal the vendor engine can decide for `candidates` (`(purl, @@ -480,6 +488,39 @@ mod tests { assert!(!refusal_is_benign(got[one].code)); } + /// A project whose requirements a hub of its Bazel workspace reads: + /// every PyPI candidate is refused with the one answer of the project, + /// and no candidate of an ecosystem whose hub the workspace does not + /// call. The switch is read from the environment, so the test holds it + /// unset. + #[tokio::test] + #[serial_test::serial] + async fn the_candidates_of_a_lock_that_a_bazel_hub_reads_are_refused() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let tmp = tempfile::tempdir().unwrap(); + let (one, other) = ("pkg:pypi/a@1.0.0", "pkg:pypi/b@2.0.0"); + let pairs = [(one, UUID), (other, OTHER_UUID), ("pkg:gem/x@1.0.0", UUID)]; + let empty = HashMap::new(); + let module = "pip = use_extension(\"@rules_python//python/extensions:pip.bzl\", \"pip\")\n\ + pip.parse(requirements_lock = \"//:requirements.txt\")\n"; + std::fs::write(tmp.path().join("MODULE.bazel"), module).unwrap(); + // The file a run for either package would write. + std::fs::write(tmp.path().join("requirements.txt"), "").unwrap(); + let got = run(tmp.path(), &pairs, Ok(&empty)).await; + assert_eq!(got.keys().collect::>(), [one, other]); + assert_eq!(got[one].code, "vendor_pypi_bazel_hub"); + assert_eq!(got[one], got[other]); + assert!(!refusal_is_benign(got[one].code)); + // The same answer is the eject's, and a hub that reads another + // file refuses nothing. + let asked = bazel_workspace_refusals(tmp.path(), &pairs).await; + let asked: Vec<_> = asked.iter().map(|(purl, code, _)| (*purl, *code)).collect(); + assert_eq!(asked, [(one, got[one].code), (other, got[one].code)]); + let elsewhere = module.replace("//:requirements.txt", "//:requirements_lock.txt"); + std::fs::write(tmp.path().join("MODULE.bazel"), elsewhere).unwrap(); + assert!(run(tmp.path(), &pairs, Ok(&empty)).await.is_empty()); + } + mod gem { use super::*; diff --git a/docs/ecosystems.md b/docs/ecosystems.md index ab1b93d10..72c9d7d7b 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -19,10 +19,10 @@ below is about what a package manager installs and builds. | Ecosystem | agent (`--mode agent`) | vendored (`--mode vendored`) | hosted (`--mode hosted`) | |-----------|------------------------|------------------------------|--------------------------| | npm (`npm`) — pnpm / yarn / berry / bun / vlt | ✅ any install layout, vlt's `node_modules/.vlt` store included (every store copy, copy-on-write) | ✅ seven lockfile flavors: package-lock, yarn classic, yarn berry (node-modules linker; PnP refused), pnpm v9, pnpm legacy v5.4/v6.0 (`pnpm 7/8` — frozen installs are path-bound because those majors absolutize `file:` override specifiers; moved checkouts run one `pnpm install --offline --no-frozen-lockfile`, surfaced as `vendor_pnpm_legacy_absolute_specifier`), bun text `bun.lock` lockfileVersion 0/1/2/3 and native binary `bun.lockb` revisions 1/2/3 (binary locks stay binary; text workspace vendoring requires lockfileVersion 2 — see [Bun compatibility](testing/bun-compatibility.md)), vlt `vlt-lock.json` lockfileVersion 0/1 (patched package directories for direct dependencies of the root or a workspace member; transitive targets refused — see [vlt notes](#npm-vlt-notes)). Rush monorepos on pnpm 9 and newer are wired through `pnpm-config.json` and each directly-depending project's `package.json` — see [Rush notes](#npm-rush-monorepos) | ✅ package-lock / npm-shrinkwrap, pnpm-lock.yaml and legacy shrinkwrap.yaml (pnpm majors 1–12; block and flow resolutions), yarn classic, yarn berry, bun, vlt (`vlt-lock.json` without `lockfileVersion`, 0 or 1) — pnpm, berry, bun and vlt carry constraints, see [npm hosted-mode notes](#npm-hosted-mode-notes) and [vlt notes](#npm-vlt-notes) | -| PyPI (`pypi`) — uv / poetry / pdm / pipenv / pip | ✅ in place | ✅ uv project/script locks, PEP 751 `pylock.toml` / `pylock..toml`, poetry, pdm, pipenv (Pipenv 2018 or later — every `Pipfile.lock` category is rewired, lock-only checkouts included; Pipenv 2023+ does not hash-check local wheels — `vendor_integrity_unverified`; Pipenv 2023.7.9+ exports the vendored wheel without a hash, so `pipenv requirements --hash` output fails pip's hash-checking mode — `pypi_pipenv_hash_export_unsupported`; a venv still holding the upstream release is reported as `pypi_pipenv_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)), and requirements.txt. Native uv vendoring requires uv ≥ 0.2.35 (the `[[package]]` lock grammar); hosted mode covers native `uv.lock` from uv 0.1.45 (the first release whose `uv lock` writes one) and requirements from uv 0.0.5; see [uv compatibility](testing/uv-compatibility.md). | ✅ requirements.txt including hash continuations, uv project/script locks, and PEP 751 locks. Version/source ambiguity is refused; see [uv compatibility](testing/uv-compatibility.md). Poetry 1.x and 2.x locks are supported; Poetry 0.x ignores URL sources and is refused. See [Poetry compatibility](testing/poetry-compatibility.md). Pipenv `Pipfile.lock` (pipfile-spec 6 — Pipenv 7 and later; `path` references for 7–11, `file` from 2018; lock-only checkouts and Pipenv's out-of-tree venv are discovered; a warm venv that Pipenv will not reinstall over warns `redirect_pypi_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)). `pdm.lock` is supported for the lock formats PDM 0.12–1.4 and 2.8.1+ write (`lock_version` 2 / 4.3–4.5.1); the identity-losing 3.1 / 4.0–4.2 formats (PDM 1.8–2.7) are refused. PDM 2.8.0 writes an indistinguishable `4.3` lock but shares that identity-loss bug, so a rewritten 2.8.0 lock crashes `pdm sync` — upgrade to ≥ 2.8.1. See [PDM compatibility](testing/pdm-compatibility.md). | +| PyPI (`pypi`) — uv / poetry / pdm / pipenv / pip | ✅ in place | ✅ uv project/script locks, PEP 751 `pylock.toml` / `pylock..toml`, poetry, pdm, pipenv (Pipenv 2018 or later — every `Pipfile.lock` category is rewired, lock-only checkouts included; Pipenv 2023+ does not hash-check local wheels — `vendor_integrity_unverified`; Pipenv 2023.7.9+ exports the vendored wheel without a hash, so `pipenv requirements --hash` output fails pip's hash-checking mode — `pypi_pipenv_hash_export_unsupported`; a venv still holding the upstream release is reported as `pypi_pipenv_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)), and requirements.txt. Native uv vendoring requires uv ≥ 0.2.35 (the `[[package]]` lock grammar); hosted mode covers native `uv.lock` from uv 0.1.45 (the first release whose `uv lock` writes one) and requirements from uv 0.0.5; see [uv compatibility](testing/uv-compatibility.md). Declined where a rules_python hub of a Bazel workspace reads the file, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ requirements.txt including hash continuations, uv project/script locks, and PEP 751 locks. Version/source ambiguity is refused; see [uv compatibility](testing/uv-compatibility.md). Poetry 1.x and 2.x locks are supported; Poetry 0.x ignores URL sources and is refused. See [Poetry compatibility](testing/poetry-compatibility.md). Pipenv `Pipfile.lock` (pipfile-spec 6 — Pipenv 7 and later; `path` references for 7–11, `file` from 2018; lock-only checkouts and Pipenv's out-of-tree venv are discovered; a warm venv that Pipenv will not reinstall over warns `redirect_pypi_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)). `pdm.lock` is supported for the lock formats PDM 0.12–1.4 and 2.8.1+ write (`lock_version` 2 / 4.3–4.5.1); the identity-losing 3.1 / 4.0–4.2 formats (PDM 1.8–2.7) are refused. PDM 2.8.0 writes an indistinguishable `4.3` lock but shares that identity-loss bug, so a rewritten 2.8.0 lock crashes `pdm sync` — upgrade to ≥ 2.8.1. See [PDM compatibility](testing/pdm-compatibility.md). | | pixi (`pypi`) — the Python packages of a pixi project, from conda channels or PyPI | ✅ in place, in every environment under `.pixi/envs`: PyPI wheels and pure-Python conda packages (compiled conda packages are not supported yet and are skipped) — see [PyPI: pixi projects](#pypi-pixi-projects) | ❌ refused (`pypi_no_requirements` / `pypi_pyproject_only`, which name agent mode) | ❌ nothing rewritten (`redirect_pypi_pixi_project` names agent mode) | | Cargo (`cargo`) | ✅ in-place + `.cargo-checksum.json` rewrite (shared registry-cache caveat — see [Cargo: shared registry cache](#cargo-shared-registry-cache)) | ✅ `[patch.crates-io]` path entry in the root `Cargo.toml` (v5; per-version Socket keys; pre-v5 `.cargo/config*` wiring migrates on re-run) | ✅ per-patch sparse registry (`[registries.socket-patch-]` + Cargo.lock source/checksum); needs cargo 1.68+ (sparse registries) — a project whose `rust-version` or `rust-toolchain[.toml]` declares an older cargo is refused (`redirect_cargo_old_cargo`), use `--mode vendored`; direct dependencies only — a crate another dependency also pulls in is refused, use `--mode vendored`; a crate the user overrides with `[patch]` (path, git or another registry) is refused too, the override is left alone; a `cargo vendor` or `cargo local-registry` project (crates.io replaced by an on-disk source in the project's, a parent directory's or `$CARGO_HOME`'s `.cargo/config*`) is refused, use agent mode; with no `Cargo.lock` the graph is unknown, so only a project whose sole dependency is the patched crate is redirected | -| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from prebuilt patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard") | +| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from prebuilt patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write); declined where a rules_ruby hub of a Bazel workspace reads the pair, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard") | | Go (`golang`) | ✅ `go.mod` `replace` → `.socket/go-patches/` — see [Go: directory replaces and go.sum](#go-directory-replaces-and-gosum) | ✅ `replace` → the committed vendor tree | ✅ (free tier) fork-style `replace` → `patch.socket.dev/gopatch/` + committed `go.sum` pin; see [Go notes](#go-directory-replaces-and-gosum). Paid hosted patches are unsupported; `redirect_golang_unsupported` names the vendored remedy | | Maven (`maven`) — Maven and Gradle | ✅ in place in every copy the build consumes: each `~/.m2` copy it reads and each Gradle `files-2.1` copy; `~/.m2` `.sha1`/`.md5` sidecars are rewritten, Gradle copies get advisories; jar-member records swap in the patch service's whole jar — prefer vendored / hosted, see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | ✅ suffixed Maven repository (`-socket.` pin + `.mvn/maven.config` + fallback file repository) for every pom root, single-module or reactor, or Gradle 6.8+ same-GAV repository with settings wiring and SHA-256 checks (a root with both `pom.xml` and a Gradle build wires both); see [JVM vendoring](design/maven-vendoring.md) and [Gradle](#gradle) | ✅ fail-closed by a Socket-only `-socket.` suffix: pom projects get a pinned `` (`${property}` versions are refused); Gradle 6.8+ builds get an owned settings script, lock-entry rewrites and a resolution tripwire — see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | | sbt / Mill / scala-cli (`maven`) | ✅ Coursier caches (sbt 1.3+, sbt 2, Mill, scala-cli) and Ivy caches (sbt 0.13–1.2, `useCoursier := false`) patched in place, Coursier checksum sidecars resynced — see [Scala build tools](#scala-build-tools-sbt-mill-scala-cli) | ✅ sbt 0.13.18+: generated `socket-patch-vendor.sbt` over the committed suffixed `.socket/vendor/maven2` tree; scala-cli directory builds: owned `socket-patch.scala` + same-GAV `.socket/vendor/coursier` tree (Linux / macOS); Mill: not wired (agent or hosted guidance) | ✅ sbt 0.13.18+: one generated `socket-patch.sbt`, gated on sbt's own `sbt update` records; Mill / scala-cli: paste-able snippets only (`redirect_mill_manual_snippet`, `redirect_scala_cli_manual_snippet`) | @@ -1891,6 +1891,11 @@ exits 0 and leaves a build that fails (the known problems below). What a cell sa - **Not supported**: socket-patch promises nothing about what a Bazel build holds after the mode ran, so do not use it for a package that Bazel builds. In most of these cells the patch does not reach the build, or the build breaks (see the known problems below). + Vendored mode for PyPI, RubyGems and Composer declines instead: the command exits 1 and + writes nothing. For PyPI and RubyGems that is where the call of the row reads a file the + run would rewrite + ([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)), + for Composer in every Bazel workspace ([Bazel workspaces: Composer](#bazel-workspaces-composer)). - **Supported**, for VEX: `socket-patch vex` and `--vex` say `not_affected` of a package the Bazel build takes patched, and `affected` of one whose patch Bazel does not build. [Bazel workspaces: VEX](#bazel-workspaces-vex) has the cases and the limits; a vendored gem @@ -1958,13 +1963,10 @@ patch. Known problems. In each of these a command exits 0 today and the next Bazel build fails: -- **Vendored mode for PyPI, RubyGems, NuGet and Composer.** The path of the committed copy - means nothing where Bazel runs: rules_python takes it for a package name, rules_ruby's - `bundle install` does not find it (`The path ... does not exist`), rules_csharp reads it as - a URL (`Bad URL`, or a crash of Bazel 9.3.2), and a Composer that Bazel runs elsewhere - reports `Source path ... is not found`. Run `socket-patch vendor --revert`, then - `socket-patch scan --mode hosted`. Of these builds a test of this repository runs the PyPI - one; the others were measured by hand on the three Bazel releases. +- **Vendored mode for NuGet.** The path of the committed copy means nothing where Bazel + runs: rules_csharp reads it as a URL (`Bad URL`, or a crash of Bazel 9.3.2). Run + `socket-patch vendor --revert`, then `socket-patch scan --mode hosted`. Measured by hand on + the three Bazel releases; no test of this repository runs that build. - **Hosted Cargo on a hub without `cargo_config`**, which is the hub as the rules_rust README shows it: the hub's cargo does not see the patch registry that `.cargo/config.toml` defines (`registry index was not found in any configuration`). Add @@ -2832,7 +2834,9 @@ project's directory, or where the build finds the copy all the same: socket-patch checks none of these. The switch is not Composer's alone: it lets vendored mode write for any package it would decline because the project is in a Bazel workspace, where the -build may not find the vendored copy. The Composer refusal is the only such refusal today. +build may not find the vendored copy. PyPI and RubyGems have such a refusal too, for a project +whose lock a hub of the workspace reads: see +[Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode). `vendor --revert` is never declined. Neither is a package that is already vendored: where `composer.lock` already names the copy of the same patch, a vendored run leaves the lock as it @@ -2859,6 +2863,156 @@ Limits: [`e2e_bazel_build/composer.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/composer.rs) runs these flows on a real Bazel. +## Bazel workspaces: PyPI and RubyGems vendored mode + +Two rulesets hand a lock of the checkout to Bazel through one call, a hub: rules_python's +`pip.parse` reads requirements files, and rules_ruby's `ruby.bundle_fetch` reads a `Gemfile` and +its lock. Each fetches what the file names into repositories of Bazel's own and builds from +there. Vendored mode makes that file name the patched copy by a path under `.socket/vendor`, +and neither ruleset builds from such a file: + +- **PyPI.** The package's line of `requirements.txt` becomes + `./.socket/vendor/pypi// --hash=sha256:...`. rules_python 2.5.0-rc4 makes the + name of a repository from that path, and the build of everything the hub serves fails with + `invalid user-provided repo name 'pip_311__/_socket/vendor/pypi//'`. +- **RubyGems.** The gem's declaration in `Gemfile` gets a `path:` and its entry of + `Gemfile.lock` moves into a `PATH` section. rules_ruby 1.0.0-rc2 copies the two files into a + repository of Bazel's and runs `bundle install` there, which fails with + `The path .../.socket/vendor/gem//- does not exist.` + +Both were measured on Bazel 9.3.2, 8.8.2 and 7.7.2, after a `scan --mode vendored` that exited +0 and reported the package vendored. So vendored mode now declines such a package, where the +files of the workspace show that a hub reads the file it would rewrite. + +**What is read.** The project is in a Bazel workspace by the lookup of +[Bazel workspaces: `.bazelignore`](#bazel-workspaces-bazelignore). There socket-patch reads +`MODULE.bazel` and the files it includes, and the `WORKSPACE` file, as +[Bazel workspaces: VEX](#bazel-workspaces-vex) describes; nothing is evaluated and no Bazel is +run. A package is declined when one of these calls names, by a label written out as a string, +a file of the package's project that the vendored run for that package would point at a copy: + +| Call | Attributes | Files of the project that count | +|---|---|---| +| rules_python `pip.parse` | `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows`, `uv_lock` | `requirements.txt` and each file it includes with `-r` (in the project), where the run would write them; `uv.lock` in a uv project | +| rules_ruby `ruby.bundle_fetch` | `gemfile_lock`, `gemfile` | `Gemfile`, `Gemfile.lock` | +| any call of the `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`) | the same | the same | + +Which files a run writes depends on the tool that locks the Python project, as in the matrix +at the top: + +- A project with no tool lock is wired through its requirements files. They count. +- A uv, Pipenv or PEP 751 lock is wired together with a pin of the same package in the + requirements files beside it. So those files count for a package they name, and not for + one they do not name. +- A Poetry or PDM lock is wired alone. A hub that reads the requirements file exported from + it stands in no run's way, and the package is vendored as it is without Bazel. Bazel goes on + building the registry's package from that file; `socket-patch vex` does not say so yet (see + the limits of [Bazel workspaces: VEX](#bazel-workspaces-vex)). + +Every such call counts, also one that may not run (in a comprehension, behind an `and`). The +refusal is for every package whose run would write a file the call names, since the lock is +the project's, with one exception: a package that is already vendored (see below). + +**What an uncertain reading does.** Where something of the workspace's files cannot be read +with certainty, and a call of the hub may be behind that, every package whose run would write +one of the files above is declined, in every project of the workspace, because the call may +read its lock. That is: + +- a call of the hub whose file is not a plain string (a constant, a concatenation), or one + that passes `*` or `**`; +- a hub proxy that is handed to anything but `use_repo` or `inject_repo`; +- a module file that is missing or cannot be read, or a statement of one that cannot be + read, where the workspace calls the hub or a file that was read names its ruleset (a + `bazel_dep` on rules_python or rules_ruby, or a `use_extension` of the hub's `.bzl` file); +- a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all. + +A file cannot be read here when one byte of it is not UTF-8 (a name in a comment is enough), +or when it is larger than 1 MiB; Bazel builds both. Going on there can leave a broken build +behind a command that exited 0; declining costs a vendored run, which the switch below brings +back. A workspace whose root `MODULE.bazel` and `WORKSPACE` file were read (or are not +there), and in which no file that was read calls the hub or names its ruleset, is never +declined for it, whatever else cannot be read. + +**What you see.** Every command that would vendor the package reports it `failed` with +`vendor_pypi_bazel_hub` or `vendor_gem_bazel_hub` and exits 1: `scan --mode vendored`, +`get --mode vendored` and `vendor`. It writes nothing and downloads no patch, and a +package that is pinned hosted stays pinned (`vendor` reports `eject_refused`). With +`--dry-run`, `scan` and `get` list the package as one the run would refuse and exit 0; +`vendor --dry-run` reports the refusal and exits 1. The message names the call with its file +and line, the lock, and the mode to use instead: + +``` +`pip.parse` (MODULE.bazel:15) of the Bazel workspace at /repo names requirements.txt; vendored mode makes the lock name the patched copy by a path under .socket/vendor, and rules_python fails the build on such a lock; use `--mode hosted`, which names the patched package by a URL that rules_python fetches, or pass `--allow-vendored-in-bazel` if no build takes the packages of this project from rules_python +``` + +For an uncertain reading the message names the file, the line and the reason where the +call stands. Hosted mode pins the patch in the same file, as a wheel URL with its sha256 or +as a gem source, and both rulesets build it: that is tested on the three Bazel releases, in +the checkout where vendored mode was declined. For a gem that holds for a +`ruby.bundle_fetch` without `gem_checksums`, as the message for a gem says: with a +`gem_checksums` entry for the gem the hosted build fails, which is one of the known problems +of [Bazel workspaces: what is supported](#bazel-workspaces-what-is-supported). + +**Where nothing changes.** A project in no Bazel workspace, a workspace that calls neither +hub, and a package whose run writes no file that a call names are vendored as before, with +the same output and the same files: a Python or Ruby project beside the one whose lock the +hub reads, a Poetry or PDM project whose exported requirements file the hub reads, or a +project that keeps a `requirements.txt` for pip while the hub reads a `requirements_lock.txt` +that socket-patch does not rewrite. In the last two cases Bazel goes on building the +unpatched package from its own file, as before. + +Vendored mode goes on when you say so, with `--allow-vendored-in-bazel` or +`SOCKET_ALLOW_VENDORED_IN_BAZEL=1`: for a hub that no build of yours uses, for a `WORKSPACE` +file that your Bazel no longer reads (Bazel 9 never reads it, Bazel 8 only with +`--enable_workspace`), or for a `ruby.bundle_fetch` to which you add every file of the +vendored gem as `srcs`, which rules_ruby copies beside the Gemfile (no test here builds +that). socket-patch checks none of these. It is the switch of +[Bazel workspaces: Composer](#bazel-workspaces-composer). + +`vendor --revert` is never declined. Neither is a package that is already vendored: where +the file that the call names already names the copy of the same patch +(`.socket/vendor/pypi//`, `.socket/vendor/gem//`), a vendored run adds nothing to +what the hub reads. So a project that was vendored with the switch, or by an earlier release, +keeps passing its runs without the switch, a `scan` or `get` with no `--mode` included, which +runs in vendored mode there. A new patch for that package, or another package, is declined +until the run has the switch. Where the reading is uncertain no file is known to be the +hub's, so nothing is let through: every vendored run there needs the switch. + +Passing such a run does not mean that the build is the patched one. A build that takes the +project's packages from the hub fails on a vendored PyPI package, and on a vendored gem +unless the call lists the copy's files. For a PyPI package `vex` says of that state that the +package is `affected` ([Bazel workspaces: VEX](#bazel-workspaces-vex)); the way out is +`vendor --revert`, then `scan --mode hosted`. + +Limits: + +- Not seen, so vendored mode goes on as before and the build can break: a hub call in a + `.bzl` file that a `WORKSPACE` file loads, a hub that another Bazel module declares, + another tag or another ruleset that reads the same file under Bzlmod (rules_ruby's older + `ruby.bundle`, rules_pycross, aspect_rules_py), a `WORKSPACE` call that hides its + arguments behind `**`, a Bazel root that the lookup does not reach, and a hub whose call + and whose `bazel_dep` are both in an included file that cannot be read, while the files + that were read name neither. +- Declined although the build would pass: a `WORKSPACE` file that names the lock while the + Bazel in use does not read that file, a hub call that never runs, and a workspace that + does not use the ruleset while its root `MODULE.bazel` or its `WORKSPACE` file cannot be + read here, or while a file that was read names the ruleset and another cannot be read. +- Declined although the run would write nothing to the file the call names: a package that + is already vendored where the file that names its copy is not the one the call names (a + requirements file that the named one includes with `-r`; the `Gemfile` when the call names + the lock too and the lock does not name the copy), any already vendored package where the + reading is uncertain, and a package of a uv, Pipenv or PEP 751 project that the + requirements file names in a form that is not wired with the lock (a range, extras). +- Only the `Gemfile` spelling is looked for, as vendored mode wires no `gems.rb` project. +- A `pip.parse` that names a `uv.lock` is declined by the rule above, not by a measurement: + no build was run on a vendored `uv.lock`. +- `repair` is not gated: it replaces a damaged copy of a package that is vendored already, + and leaves the lock as it is. + +[`e2e_bazel_build/pypi.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs) and +[`ruby.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs) run the refusal, the +switch and hosted mode on a real Bazel. + ## Ruby gems: hosted mode `scan --mode hosted` makes Bundler install a patched gem from that patch's own gem source on @@ -3305,8 +3459,12 @@ is patched: the file that points at the copy. rules_python 2.5.0-rc4 takes the path of the line for the name of a project, and the build of everything the hub serves fails (same three releases). A vendored npm tarball is built by rules_js and keeps its statement. So does a - vendored gem, for another reason: no test here runs the build of one yet, so nothing is - said of it. + vendored gem, for another reason: rules_ruby builds one only when the call lists every + file of the copy among its `srcs`, which is not read, so nothing is said of it. + Vendored mode declines both by default where the hub reads the file + ([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)), + so this is the state of a project vendored with `--allow-vendored-in-bazel` or by an + earlier release. Each advisory of such a patch gets a statement of the package's own with the status `affected`. It names that package alone under the product, and its `action_statement` says @@ -3442,9 +3600,10 @@ the build is broken): `-r`. Measured for PyPI, where the build fails. - **Vendored mode for RubyGems** beside `ruby.bundle_fetch`. rules_ruby 1.0.0-rc2 runs `bundle install` in a repository that holds the Gemfile, its lock and the files the call - lists as `srcs`, so the path of the copy does not exist there. Read from its source and - measured by hand, where the build fails; no test runs it yet, so the statement is left as - it is. + lists as `srcs`, so the path of the copy does not exist there unless every file of the copy + is listed. Measured on the three releases: the build fails, and the statement still says + `not_affected`. Vendored mode declines such a gem by default, so this is the state of a + project vendored with `--allow-vendored-in-bazel` or by an earlier release. - **A vendored package whose own files the hub does not read**, while the lock the hub does read still lists the registry's package: a uv or Poetry project vendored through `pyproject.toml` and its lock while `pip.parse` reads a requirements file exported before; diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 6729c125c..7cf4927da 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 2486 + "max": 2555 }, "lock-readers": { "paths": [ From 2d652c5fcb78c285c02c229420beeb6a0faebecf Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 23 Nov 2026 16:55:38 -0500 Subject: [PATCH 03/19] Close three ways a vendored run could still write a file a Bazel hub reads A review of the PyPI and RubyGems vendored declines found three states in which the run was let through and would write a file that a hub of the Bazel workspace reads: - A Poetry or PDM project whose exported requirements file holds the package by a URL, which is what a hosted pin is. The lock of such a project is wired alone, so its requirements files did not count, but a vendored run that takes a hosted pin over restores that line. The files now count for a package they hold by a URL. A package they pin from the registry is vendored as before. - A `WORKSPACE` call that names the lock through the name the file gives the main repository (`@shop//api:requirements.txt` beside `workspace(name = "shop")`). The label was taken for another repository's. It is the main repository now, for the calls of that file. - A package that is already vendored, where the calls name more than one file of the project. Only the first file a call names was read, so a `uv.lock` locked again beside a vendored requirements file let the package pass, and the run rewrote the lock. Each file a call names that holds the package now has to name the copy; one that cannot be read may hold it. Also from the review: the requirements file is no longer listed twice, the gem's two files are the gem backend's own constants, and the files of a package are chosen by its ecosystem and not by the text of its purl type. The docs and the contract row say what was imprecise: the requirements files of a project with no tool lock count as one set, also for a package a file of the set does not pin, because a file the hub reads can bring in the rewritten one with `-r`; and the `pip_install(requirements = ...)` of an older rules_python is not seen. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- crates/socket-patch-core/src/bazel/built.rs | 60 +++++++++++--- .../socket-patch-core/src/vendor/bazel_hub.rs | 82 ++++++++++++++++--- crates/socket-patch-core/src/vendor/gem.rs | 4 +- crates/socket-patch-core/src/vendor/pypi.rs | 23 ++++-- .../src/vendor/pypi_requirements.rs | 16 ++++ docs/ecosystems.md | 29 +++++-- scripts/loc-budget.json | 2 +- 8 files changed, 176 insertions(+), 42 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 9e2a1ce9b..57cdcb712 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2492,7 +2492,7 @@ command's integration tests check its output. | `vendor_bun_lockb_invalid` | `failed` | vendor / scan / get `--mode vendored`: the binary lock is malformed, unreadable, unsupported or cannot be rewritten safely. The detail names the parser, hash or filesystem error. Refused before patch downloads and before hosted takeover; the package's `failed` event carries `errorCode` and `error`, while `get ` also carries top-level `error.code`. Dry-run predicts the same refusal. | | `vendor_bun_workspace_unsupported` | `failed` | vendor / scan / get `--mode vendored` (bun): the text lock holds `workspace:` packages and its `lockfileVersion` is below 2 — Bun 1.2–1.3 resolve a workspace member's local-tarball path relative to the member; a committed version-2 lock is the proof every consumer runs Bun ≥ 1.4 (deliberate over-approximation: root-only declared packages would install on version 1 too). Detail names the version integer and a version-specific remedy: delete `bun.lock` and re-lock with Bun ≥ 1.4 (an in-place `bun install` keeps the existing version) — then, for a version-1 lock, "or use `--mode hosted`, which accepts version-1 workspace locks"; for a version-0 lock, "or delete `bun.lock`, re-lock with Bun ≥ 1.2 (which writes lockfileVersion 1) and use `--mode hosted`" (hosted refuses version-0 workspace locks, so a bare hosted pointer would send the user into a second refusal). Refused before any write — in the pre-download preflight on `get`/`scan` (see `vendor_bun_lockb_invalid` for the placements); in the shared preflight that `vendor` and the vendor step run BEFORE a hosted → vendored takeover's revert (a hosted-redirected purl stays hosted-wired, ledger and lock untouched; `vendor --dry-run` previews the same `failed` code); and in the engine when the run would write a NEW local tuple. Exempt: purls the vendor ledger wires at the selected uuid, purls whose every `bun.lock` instance is already a `.socket/vendor/npm/` tuple (any uuid), in-sync re-runs and `repair` redownloads. | | `vendor_composer_bazel_workspace` | `failed` | vendor / scan / get `--mode vendored` (composer): the project is in a Bazel workspace (its directory, or one above it up to the root of its git checkout, holds `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`). Vendored mode makes `composer.lock` name the patched copy by a path relative to the directory Composer runs in; a Bazel repository rule or build action that runs `composer install` from the lock anywhere else fails with Composer's `Source path "…" is not found for package …`, and the build with it (Bazel 9.3.2, 8.8.2, 7.7.2). Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the Bazel root and the mode that writes no such path, `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel`, `vendor --revert`, and a package whose `composer.lock` entry already names the copy of the same patch (the run leaves the lock as it is, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included; a new patch for it is refused). A project that commits its `vendor/` tree is refused like any other: the tree shows that Composer has run in the project's directory, not that no rule of the workspace runs it elsewhere as well. See docs/ecosystems.md "Bazel workspaces: Composer". | -| `vendor_pypi_bazel_hub` / `vendor_gem_bazel_hub` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): a hub of the project's Bazel workspace reads a file of the project that the run would point at the copy under `.socket/vendor`. That is a rules_python `pip.parse` whose `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` or `uv_lock` names a requirements file of the project that the run would write (`requirements.txt` or a file it includes with `-r`: in a project with no tool lock, and for a package they name beside a uv, Pipenv or PEP 751 lock) or the `uv.lock` of a uv project; a rules_ruby `ruby.bundle_fetch` whose `gemfile` or `gemfile_lock` names the project's `Gemfile` or `Gemfile.lock`; and a call of a `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`). Neither ruleset builds from such a file: rules_python 2.5.0-rc4 fails with `invalid user-provided repo name '___/_socket/vendor/pypi/…'`, and the `bundle install` action of rules_ruby 1.0.0-rc2 with `The path … does not exist.`, after a command that exited 0 (Bazel 9.3.2, 8.8.2, 7.7.2). Also refused, for every package whose run would write such a file: a workspace whose files cannot be read with certainty where a call of the hub may be behind that (a call of the hub whose file is not a plain string label or that passes `*` or `**`; a hub proxy handed on; a module file or a statement of one that cannot be read, while the workspace calls the hub or a file that was read names its ruleset; a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all, for which one byte that is not UTF-8 is enough), because a call may then read the project's lock. Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the call with its file and line, the lock (or the place and the reason of the doubt), the Bazel root, and the mode whose pin both rulesets build, `--mode hosted` (rules_ruby where its call passes no `gem_checksums`, which the detail for a gem says). Not refused: a package whose run writes no file that such a call names, in a Bazel workspace or outside one (a Poetry or PDM project, whose lock is wired alone, beside a hub that reads its exported `requirements.txt`); a workspace whose files were read and neither call the hub nor name its ruleset; a run with `--allow-vendored-in-bazel`; `vendor --revert`; and a package that the file the call names already names by the copy of the same patch (`.socket/vendor/pypi//`, `.socket/vendor/gem//`): the run adds nothing to what the hub reads, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included, while a new patch for the package is refused. Where the reading is in doubt no file is known to be the hub's, and every run without the switch is refused. See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" | +| `vendor_pypi_bazel_hub` / `vendor_gem_bazel_hub` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): a hub of the project's Bazel workspace reads a file of the project that the run would point at the copy under `.socket/vendor`. That is a rules_python `pip.parse` whose `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` or `uv_lock` names a requirements file of the project that the run may write (`requirements.txt` or a file it includes with `-r`, as one set: in a project with no tool lock, for a package they name beside a uv, Pipenv or PEP 751 lock, and for a package they hold by a URL, which is a hosted pin, beside a Poetry or PDM lock) or the `uv.lock` of a uv project; a rules_ruby `ruby.bundle_fetch` whose `gemfile` or `gemfile_lock` names the project's `Gemfile` or `Gemfile.lock`; and a call of a `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`), where `@//` is the main repository when the file says `workspace(name = "")`. Neither ruleset builds from such a file: rules_python 2.5.0-rc4 fails with `invalid user-provided repo name '___/_socket/vendor/pypi/…'`, and the `bundle install` action of rules_ruby 1.0.0-rc2 with `The path … does not exist.`, after a command that exited 0 (Bazel 9.3.2, 8.8.2, 7.7.2). Also refused, for every package whose run would write such a file: a workspace whose files cannot be read with certainty where a call of the hub may be behind that (a call of the hub whose file is not a plain string label or that passes `*` or `**`; a hub proxy handed on; a module file or a statement of one that cannot be read, while the workspace calls the hub or a file that was read names its ruleset; a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all, for which one byte that is not UTF-8 is enough), because a call may then read the project's lock. Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the call with its file and line, the lock (or the place and the reason of the doubt), the Bazel root, and the mode whose pin both rulesets build, `--mode hosted` (rules_ruby where its call passes no `gem_checksums`, which the detail for a gem says). Not refused: a package whose run writes no file that such a call names, in a Bazel workspace or outside one (a Poetry or PDM project, whose lock is wired alone, beside a hub that reads its exported `requirements.txt`, unless that file holds the package by a URL); a workspace whose files were read and neither call the hub nor name its ruleset; a run with `--allow-vendored-in-bazel`; `vendor --revert`; and a package that the file the call names already names by the copy of the same patch (`.socket/vendor/pypi//`, `.socket/vendor/gem//`): the run adds nothing to what the hub reads, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included, while a new patch for the package is refused; where the calls name more than one file of the project, each of them that holds the package has to name the copy. Where the reading is in doubt no file is known to be the hub's, and every run without the switch is refused. See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" | | `vendor_lockfile_missing` / `vendor_lockfile_version_unsupported` (bun preflight placement) | `failed` | scan / get `--mode vendored` (bun): the pre-download preflight found `bun.lock` unreadable / at a `lockfileVersion` other than 0 to 3 (a newer version: update socket-patch; no integer: re-lock with Bun ≥ 1.2 — the same text as hosted's `redirect_bun_lock_unsupported`) or outside bun's single-line `packages` grammar. Same placements as `vendor_bun_lockb_invalid`; nothing fetched, no patch record. An unreadable `.socket/vendor/state.json` met by the same preflight is `vendor_state_unreadable` (see that row), never one of these. | | `bun_lockb_invalid` | scan `warnings[]` (run-level) | scan (every mode): the native binary inventory could not parse or read `bun.lockb`; detail names the format or filesystem error. Also printed as `Warning: …` on stderr. Exit and status remain unchanged. The warning is retained on empty and non-empty scans; valid binary locks are inventoried normally without a runtime or install. | | `bun_lock_unsupported` | scan `warnings[]` (run-level) | scan (every mode): the text `bun.lock` is there but the lock reader refuses it — a `lockfileVersion` newer than 3, no integer version, or a `packages` section outside bun's single-line grammar (a comment line, a re-indent) — so the packages it lists were not read from the lockfile. Detail is the shared version gate's text or `bun.lock: line : …`, followed by `, so the packages it lists were NOT read from the lockfile: a package that is locked but not installed was not scanned`. Also printed as `Warning: …` on stderr, and a scan that then finds no package at all ends `No packages found (see the warning).` instead of advising an install. Status and exit are unchanged (0): before, a checkout without `node_modules` scanned as an empty project and the lock was not mentioned. Installed packages are still crawled, and hosted / vendored runs keep their own refusal (`redirect_bun_lock_unsupported` / `vendor_lockfile_version_unsupported`). The hosted in-memory engine reports the same code among its warnings. | diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index 465463b1b..d507581ae 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -295,15 +295,22 @@ fn reads( .and_then(|read| read.as_ref().ok()); let passes = |call: &&Call| hub.files.iter().any(|file| call.arg(file).is_some()); let legacy = legacy.into_iter().flat_map(|(name, file)| { + // `workspace(name = "shop")` makes `@shop//` the main repository + // for the labels of that file. + let main = file.calls.iter().find_map(workspace_name); let calls = file.calls.iter().filter(passes); - calls.map(move |call| (name.as_str(), call, call.callee.as_str())) + calls.map(move |call| (name.as_str(), call, call.callee.as_str(), main)) }); + let tagged = tagged.map(|(file, call, name)| (file, call, name, None)); let mut doubt = tags.doubts.first().cloned(); let mut called = doubt.is_some(); - for (file, call, name) in tagged.chain(legacy) { + for (file, call, name, main) in tagged.chain(legacy) { called = true; let own = |lock: &String| locks.iter().any(|own| below(project, own) == *lock); - if let Some(lock) = files(workspace, call, hub.files).into_iter().find(own) { + if let Some(lock) = files(workspace, call, hub.files, main) + .into_iter() + .find(own) + { return Some(Ok(Unbuilt { call: name.to_string(), file: file.to_string(), @@ -340,6 +347,14 @@ fn reads( doubt.or_else(|| hidden().or_else(unread).cloned()).map(Err) } +/// The name a `workspace(name = ...)` call gives the main repository. +fn workspace_name(call: &Call) -> Option<&str> { + match (call.callee.as_str(), call.arg("name")) { + ("workspace", Some(Value::Str(name))) => Some(name.as_str()), + _ => None, + } +} + /// The most of a lock that is read: the lock of a large pnpm workspace has /// some tens of MiB. A larger file decides nothing. const MAX_LOCK: u64 = 64 << 20; @@ -399,7 +414,7 @@ fn judge( let mut listed = HashMap::new(); let elsewhere = |call: &Call| call.unpacks() || call.arg("uv_lock").is_some(); for tag in (tags.calls.iter()).filter(|tag| tag.call.whole && !elsewhere(tag.call)) { - for lock in files(workspace, tag.call, hub.files) { + for lock in files(workspace, tag.call, hub.files, None) { for &at in &ours { let package = &packages[at]; let unpatched = match &package.pins { @@ -452,8 +467,15 @@ fn judge( /// The files of the main repository that `call` names under `attributes`, /// each by its path from the Bazel root. An attribute that is not written -/// out as a string, or as a dict with strings as keys, names none. -fn files(workspace: &Workspace, call: &Call, attributes: &[&str]) -> Vec { +/// out as a string, or as a dict with strings as keys, names none. `main` +/// is the name a `WORKSPACE` file gives the main repository, for a call of +/// that file: `@
//` is then the main repository too. +fn files( + workspace: &Workspace, + call: &Call, + attributes: &[&str], + main: Option<&str>, +) -> Vec { let mut labels: Vec<&str> = Vec::new(); for attribute in attributes { match call.arg(attribute) { @@ -464,13 +486,16 @@ fn files(workspace: &Workspace, call: &Call, attributes: &[&str]) -> Vec _ => {} } } - let main = |label: &&str| { - let label = workspace - .label(label) - .filter(|label| label.repo == Repo::Main); - label.map(|label| label.path()) + let ours = |label: &&str| { + let label = workspace.label(label)?; + let ours = match &label.repo { + Repo::Main => true, + Repo::Apparent(repo) => main == Some(repo.as_str()), + Repo::Canonical(_) => false, + }; + ours.then(|| label.path()) }; - labels.iter().filter_map(main).collect() + labels.iter().filter_map(ours).collect() } /// The path from the Bazel root of `file`, a path from the project in the @@ -1183,6 +1208,17 @@ use_repo(ruby, "bundle") let rule = "http_archive(name = \"x\", urls = [LOCK])\n"; let files = [("WORKSPACE", rule)]; assert_eq!(reader_of(&files, "svc", "pypi", &["requirements.txt"]), ""); + // The name the file gives the main repository names it in a label + // of that file; without that call the label is another + // repository's. + let call = + "pip_parse(name = \"pypi\", requirements_lock = \"@shop//svc:requirements.txt\")\n"; + let named = format!("workspace(name = \"shop\")\n{call}"); + let files = [("WORKSPACE", named.as_str())]; + let pip = "pip_parse WORKSPACE:2 svc/requirements.txt"; + assert_eq!(reader_of(&files, "svc", "pypi", &["requirements.txt"]), pip); + let files = [("WORKSPACE", call)]; + assert_eq!(reader_of(&files, "svc", "pypi", &["requirements.txt"]), ""); } #[test] diff --git a/crates/socket-patch-core/src/vendor/bazel_hub.rs b/crates/socket-patch-core/src/vendor/bazel_hub.rs index 682f8bc52..6f316895e 100644 --- a/crates/socket-patch-core/src/vendor/bazel_hub.rs +++ b/crates/socket-patch-core/src/vendor/bazel_hub.rs @@ -14,7 +14,9 @@ //! //! Which lock a hub reads is in the files of the workspace //! ([`crate::bazel::built::reader`]), so the refusal is for a package whose -//! run would write a file that one reads and for no other. A project +//! run may write a file that one reads and for no other. The requirements +//! files of a project count as one set there, since a file the hub reads +//! can bring in the rewritten one with `-r`. A project //! beside a workspace whose calls name other files is vendored as it is //! without Bazel, and so is a package whose run leaves the file the hub //! reads alone: one of a Poetry or PDM project, whose lock is wired alone, @@ -100,9 +102,12 @@ async fn refusals_unless<'a>( }; // The files a hub can be given that the run for this package would // point at a copy. With none, no hub stands in its way. - let locks = match purls { - "pypi" => super::pypi::hub_files(project, purl).await, - _ => ["Gemfile", "Gemfile.lock"].map(String::from).to_vec(), + let locks = match Ecosystem::from_purl(purl) { + Some(Ecosystem::Pypi) => super::pypi::hub_files(project, purl).await, + Some(Ecosystem::Gem) => [super::gem::GEMFILE, super::gem::GEMFILE_LOCK] + .map(String::from) + .to_vec(), + _ => continue, }; if locks.is_empty() { continue; @@ -122,13 +127,41 @@ async fn refusals_unless<'a>( // A lock names the copy of a patch by the copy's directory, outside // a comment (`#` starts one in each of these files). let copy = vendor_uuid_dir_rel(purls, uuid).map(|dir| format!("{dir}/")); - let wired = match (lock, copy) { + let names = |lock: &Option| match (lock, ©) { (Some(lock), Some(copy)) => { - let names = |line: &str| line.split('#').next().is_some_and(|l| l.contains(©)); + let names = |line: &str| line.split('#').next().is_some_and(|l| l.contains(copy)); lock.lines().any(names) } _ => false, }; + let mut wired = names(lock); + // The first file a call names says nothing of a second one. Another + // file of the list that a call names stands in the way when it + // holds the package and not by the copy (a `uv.lock` locked again + // beside a vendored requirements file): the run would rewrite it. + // One that cannot be read may hold it. + let name = purl + .rsplit('/') + .next() + .and_then(|rest| rest.split('@').next()); + let squash = |text: &str| text.to_ascii_lowercase().replace(['_', '.'], "-"); + let name = squash(name.unwrap_or_default()); + let holds = |text: &Option| match text { + Some(text) => squash(text).contains(&name), + None => true, + }; + let files = &asked[at].0 .1; + let several = wired && files.len() > 1; + for file in files.iter().filter(|_| several) { + if !wired { + break; + } + if let Some(Ok(named)) = reader(&root, purls, vec![file.clone()]).await { + let dir = root.dir.clone(); + let text = run_blocking(move || lock_text(&dir, &named.lock)).await; + wired = names(&text) || !holds(&text); + } + } if !wired { refused.push((*purl, code, detail.clone())); } @@ -320,9 +353,16 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//api:Gemfile", gemfile_lock = "// }; let line = format!("./.socket/vendor/pypi/{UUID}/a-1.0.0-py3-none-any.whl # a==1.0.0\n"); let path = format!("PATH\n remote: .socket/vendor/gem/{UUID}/b-1.0.0\n"); + let gemfile = path.replace("remote:", "gem 'b', path:"); fs::write(api.join("base.txt"), &line).unwrap(); + fs::write(api.join("Gemfile"), &gemfile).unwrap(); fs::write(api.join("Gemfile.lock"), &path).unwrap(); assert_eq!(declined().await, [other]); + // The other file the call names is read too: a Gemfile that cannot + // be read may hold the gem by the registry. + fs::remove_file(api.join("Gemfile")).unwrap(); + assert_eq!(declined().await, [other, gem]); + fs::write(api.join("Gemfile"), &gemfile).unwrap(); // The lock is read as a file of the workspace is: one that is a // link out of the Bazel root lets nothing through. #[cfg(unix)] @@ -340,11 +380,6 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//api:Gemfile", gemfile_lock = "// assert_eq!(declined().await, [wheel, other]); // Named by the Gemfile alone: the lock is the file the call names // first, and it still holds the registry's gem. - fs::write( - api.join("Gemfile"), - path.replace("remote:", "gem 'b', path:"), - ) - .unwrap(); fs::write(api.join("Gemfile.lock"), "GEM\n specs:\n b (1.0.0)\n").unwrap(); assert_eq!(declined().await, [wheel, other, gem]); // A hub whose file is not written out: no lock is known to be its. @@ -352,6 +387,25 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//api:Gemfile", gemfile_lock = "// let unwritten = HUBS.replace("\"//api:base.txt\"", "LOCK"); fs::write(root.join("MODULE.bazel"), unwritten).unwrap(); assert_eq!(declined().await, [wheel, other, gem]); + // A second file that the hub reads: the uv lock, locked again + // beside the vendored requirements file. It holds the package by + // the registry's wheel, so the run would rewrite it. + let both = "\"//api:base.txt\", uv_lock = \"//api:uv.lock\""; + fs::write( + root.join("MODULE.bazel"), + HUBS.replace("\"//api:base.txt\"", both), + ) + .unwrap(); + let entry = + |source: &str| format!("[[package]]\nname = \"a\"\nversion = \"1.0.0\"\n{source}"); + fs::write(api.join("uv.lock"), entry("")).unwrap(); + assert_eq!(declined().await, [wheel, other, gem]); + // Held by the copy there too, or not held at all: let through. + let copy = format!("source = {{ path = \".socket/vendor/pypi/{UUID}/a.whl\" }}\n"); + fs::write(api.join("uv.lock"), entry(©)).unwrap(); + assert_eq!(declined().await, [other, gem]); + fs::write(api.join("uv.lock"), "").unwrap(); + assert_eq!(declined().await, [other, gem]); } /// The uv lock of the project is a file a hub can be given, and a hub @@ -416,6 +470,12 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//api:Gemfile", gemfile_lock = "// fs::write(root.join("MODULE.bazel"), &unwritten).unwrap(); assert_eq!(pypi().await, None, "{lock}, a hub in doubt"); fs::write(root.join("MODULE.bazel"), &hub).unwrap(); + // But for a hosted pin of the requirements file: a run that + // takes it over restores the line the hub reads. + let hosted = "x @ https://h/x-1.0.0-py3-none-any.whl\n"; + fs::write(api.join("requirements.txt"), hosted).unwrap(); + assert_eq!(pypi().await, Some(PYPI_CODE), "{lock}, a hosted pin"); + fs::write(api.join("requirements.txt"), "x==1.0.0\n").unwrap(); fs::remove_file(api.join(lock)).unwrap(); } // A uv or Pipenv lock is wired with the pin of the requirements diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 2948d5da0..0151109a7 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -138,8 +138,8 @@ use crate::formats::gem::{ is_plain_gem_token, listed_specs, split_checksum_entry, split_entry, GemfileLock, }; -const GEMFILE: &str = "Gemfile"; -const GEMFILE_LOCK: &str = "Gemfile.lock"; +pub(super) const GEMFILE: &str = "Gemfile"; +pub(super) const GEMFILE_LOCK: &str = "Gemfile.lock"; /// Wiring-record discriminators (`key` is the gem name for all three). /// diff --git a/crates/socket-patch-core/src/vendor/pypi.rs b/crates/socket-patch-core/src/vendor/pypi.rs index a2e7958a2..e0adf56e9 100644 --- a/crates/socket-patch-core/src/vendor/pypi.rs +++ b/crates/socket-patch-core/src/vendor/pypi.rs @@ -1615,9 +1615,16 @@ fn sibling_lock(flavor: PypiFlavor) -> Option<(&'static str, &'static str)> { /// where it governs. The requirements files where they are what is wired, /// and where they name the package beside a uv, Pipenv or Python lock, /// which is wired together with a pin of theirs -/// ([`super::pypi_requirements::sibling_names_package`]). None for a -/// Poetry or PDM lock, which is wired alone, and for a project the router -/// refuses, where nothing is written. +/// ([`super::pypi_requirements::sibling_names_package`]). Beside a Poetry +/// or PDM lock, which is wired alone, only where they hold the package by a +/// URL: that is a hosted pin, which a run that takes it over restores +/// ([`super::pypi_requirements::sibling_names_package_by_url`]). None for a +/// project the router refuses, where nothing is written. +/// +/// The requirements files are counted as one set, the file a hub names and +/// the files it brings in with `-r` alike, and not only the files that pin +/// the package: a file the hub reads can reach the rewritten one through an +/// include. pub(super) async fn hub_files(project_root: &Path, purl: &str) -> Vec { let mut files = Vec::new(); let Some((name, version)) = parse_pypi_purl(purl) else { @@ -1629,13 +1636,17 @@ pub(super) async fn hub_files(project_root: &Path, purl: &str) -> Vec { }; let requirements = match flavor { PypiFlavor::Requirements => true, - _ if sibling_lock(flavor).is_none() => false, + _ if sibling_lock(flavor).is_none() => { + super::pypi_requirements::sibling_names_package_by_url(project_root, &name).await + } _ => super::pypi_requirements::sibling_names_package(project_root, &name).await, }; if requirements { + // The walk names `requirements.txt` first; where it fails, that file + // alone stands for the set. + let root = || vec![crate::formats::governing_locks::PYPI_REQUIREMENTS.to_string()]; let included = super::requirements_include_names(project_root).await; - files = included.unwrap_or_default(); - files.push(crate::formats::governing_locks::PYPI_REQUIREMENTS.to_string()); + files = included.unwrap_or_else(|_| root()); } if flavor == PypiFlavor::UvProject { files.push("uv.lock".to_string()); diff --git a/crates/socket-patch-core/src/vendor/pypi_requirements.rs b/crates/socket-patch-core/src/vendor/pypi_requirements.rs index 3b6ae5fe3..d0e860d89 100644 --- a/crates/socket-patch-core/src/vendor/pypi_requirements.rs +++ b/crates/socket-patch-core/src/vendor/pypi_requirements.rs @@ -497,6 +497,22 @@ pub(super) async fn sibling_names_package(root: &Path, canon_name: &str) -> bool files.is_ok_and(|files| files.iter().any(names)) } +/// Whether a requirements file of the project names the package by a URL +/// (`name @ https://...`), which is the form of a hosted pin. A lock that +/// is wired alone leaves the requirements files as they are, but a run +/// that takes a hosted pin over restores the line that holds it. +pub(super) async fn sibling_names_package_by_url(root: &Path, canon_name: &str) -> bool { + let by_url = |file: &ReqFile| { + logical_lines(&file.content).into_iter().any(|ll| { + let text = strip_comment(&ll.text); + let named = requirement_name(text).map(canonicalize_pypi_name); + text.contains("://") && named.as_deref() == Some(canon_name) + }) + }; + let files = collect_requirements_files(root).await; + files.is_ok_and(|files| files.iter().any(by_url)) +} + /// #1873: refuse a requirements line naming `canon_name` through a /// `${NAME}` pip expands where it runs (`six==${SIXV}`). What it installs /// is unknowable here, so the vendor neither rewrites it nor names the file diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 72c9d7d7b..bcb8db4b3 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2893,21 +2893,26 @@ a file of the package's project that the vendored run for that package would poi | Call | Attributes | Files of the project that count | |---|---|---| -| rules_python `pip.parse` | `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows`, `uv_lock` | `requirements.txt` and each file it includes with `-r` (in the project), where the run would write them; `uv.lock` in a uv project | +| rules_python `pip.parse` | `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows`, `uv_lock` | `requirements.txt` and each file it includes with `-r` (in the project), as one set, where the run writes a requirements file; `uv.lock` in a uv project | | rules_ruby `ruby.bundle_fetch` | `gemfile_lock`, `gemfile` | `Gemfile`, `Gemfile.lock` | -| any call of the `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`) | the same | the same | +| any call of the `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`) | the same; a label `@//...` names the main repository where the file says `workspace(name = "")` | the same | Which files a run writes depends on the tool that locks the Python project, as in the matrix at the top: -- A project with no tool lock is wired through its requirements files. They count. +- A project with no tool lock is wired through its requirements files. They count as one + set: a package is declined when the hub reads any file of the set, also one that does not + pin it, because that file can bring in the rewritten one with `-r`. - A uv, Pipenv or PEP 751 lock is wired together with a pin of the same package in the requirements files beside it. So those files count for a package they name, and not for one they do not name. - A Poetry or PDM lock is wired alone. A hub that reads the requirements file exported from it stands in no run's way, and the package is vendored as it is without Bazel. Bazel goes on building the registry's package from that file; `socket-patch vex` does not say so yet (see - the limits of [Bazel workspaces: VEX](#bazel-workspaces-vex)). + the limits of [Bazel workspaces: VEX](#bazel-workspaces-vex)). The one exception is a + requirements file that holds the package by a URL, which is what a hosted pin is: a + vendored run that takes the pin over restores that line, so the files count and the + package is declined. Every such call counts, also one that may not run (in a comprehension, behind an `and`). The refusal is for every package whose run would write a file the call names, since the lock is @@ -2975,8 +2980,11 @@ the file that the call names already names the copy of the same patch what the hub reads. So a project that was vendored with the switch, or by an earlier release, keeps passing its runs without the switch, a `scan` or `get` with no `--mode` included, which runs in vendored mode there. A new patch for that package, or another package, is declined -until the run has the switch. Where the reading is uncertain no file is known to be the -hub's, so nothing is let through: every vendored run there needs the switch. +until the run has the switch. Where the calls name more than one file of the project, each +of them that holds the package has to name the copy: a `uv.lock` that was locked again +beside a vendored requirements file does not, and the package is declined. Where the reading +is uncertain no file is known to be the hub's, so nothing is let through: every vendored run +there needs the switch. Passing such a run does not mean that the build is the patched one. A build that takes the project's packages from the hub fails on a vendored PyPI package, and on a vendored gem @@ -2990,7 +2998,8 @@ Limits: `.bzl` file that a `WORKSPACE` file loads, a hub that another Bazel module declares, another tag or another ruleset that reads the same file under Bzlmod (rules_ruby's older `ruby.bundle`, rules_pycross, aspect_rules_py), a `WORKSPACE` call that hides its - arguments behind `**`, a Bazel root that the lookup does not reach, and a hub whose call + arguments behind `**`, the `pip_install(requirements = ...)` of an older rules_python in a + `WORKSPACE` file, a Bazel root that the lookup does not reach, and a hub whose call and whose `bazel_dep` are both in an included file that cannot be read, while the files that were read name neither. - Declined although the build would pass: a `WORKSPACE` file that names the lock while the @@ -3001,8 +3010,10 @@ Limits: is already vendored where the file that names its copy is not the one the call names (a requirements file that the named one includes with `-r`; the `Gemfile` when the call names the lock too and the lock does not name the copy), any already vendored package where the - reading is uncertain, and a package of a uv, Pipenv or PEP 751 project that the - requirements file names in a form that is not wired with the lock (a range, extras). + reading is uncertain, a package of a uv, Pipenv or PEP 751 project that the + requirements file names in a form that is not wired with the lock (a range, extras), and a + package of a project with no tool lock where the hub reads a file of the requirements set + that neither pins the package nor brings in the file that does. - Only the `Gemfile` spelling is looked for, as vendored mode wires no `gems.rb` project. - A `pip.parse` that names a `uv.lock` is declined by the rule above, not by a measurement: no build was run on a vendored `uv.lock`. diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 7cf4927da..142c5444e 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 2555 + "max": 2574 }, "lock-readers": { "paths": [ From 9a022a861618b83ccf631e769f7bc3b1eab39bf9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:42:17 +0000 Subject: [PATCH 04/19] Decline a vendored run where a hub reads a parent file or is in doubt Two states in which a vendored PyPI run was still let through and would write a file a Bazel hub reads: - A hub that names a requirements file which brings the project's own in with `-r` (`all.txt` with `-r requirements.txt`). The files a run writes are walked down from `requirements.txt`, so the file the hub named was not among them and nothing was declined. A requirements file a call names now counts as naming each file its `-r` includes reach, read inside the Bazel root as any lock is, and the refusal names it. - An already-vendored package whose other files a call may name where the reading is in doubt: a second attribute that is not written out, or a call that may be behind a file that could not be read. Only a certain answer had that file read; a doubt was dropped and the package let through. A doubt now has the file read as well, so the package is declined where that file holds it and not by the copy. The `bazel` line budget goes from 2574 to 2611. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011f9aeQFeU3sKRPzawaNLsm Assisted-by: Claude Code:claude-opus-5-5 --- crates/socket-patch-core/src/bazel/built.rs | 88 +++++++++++++++++-- .../socket-patch-core/src/vendor/bazel_hub.rs | 49 +++++++++-- scripts/loc-budget.json | 2 +- 3 files changed, 121 insertions(+), 18 deletions(-) diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index d507581ae..60cefae56 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -262,7 +262,9 @@ pub type Reader = Result; /// The call of the workspace `root` that hands Bazel one of `locks`: files /// of the project in that workspace, each by its path from the project, /// which vendored mode would rewrite for a package of `ecosystem` (the type -/// of its purls). Or the doubt that leaves that open. `None` when the +/// of its purls), or the doubt that leaves that open. A requirements file +/// that a call names hands Bazel each file its `-r` includes reach as +/// well, and is then the file returned. `None` when the /// calls of the hub are read with certainty and name other files, and when /// nothing shows that the workspace may call it: no call of the hub and no /// file that names its ruleset, with a root module file and a `WORKSPACE` @@ -273,16 +275,33 @@ pub async fn reader( locks: Vec, ) -> Option { let (dir, project) = (root.dir.clone(), slashed(&root.project)); - run_blocking(move || reads(&Workspace::read(&disk(&dir)), &project, ecosystem, &locks)).await + run_blocking(move || { + let read = |file: &str| lock_text(&dir, file); + reads( + &Workspace::read(&disk(&dir)), + &project, + ecosystem, + &locks, + &read, + ) + }) + .await +} + +/// The path from the Bazel root `root` of `file`, a path from its project. +pub(crate) fn from_root(root: &BazelRoot, file: &str) -> String { + below(&slashed(&root.project), file) } /// [`reader`] for the workspace `workspace` and the project in its -/// directory `project` (empty: the root itself). +/// directory `project` (empty: the root itself), with `read` for the text +/// of a file of the workspace. fn reads( workspace: &Workspace, project: &str, ecosystem: &str, locks: &[String], + read: &dyn Fn(&str) -> Option, ) -> Option { let hub = HUBS.iter().find(|hub| hub.ecosystem == ecosystem)?; let tags = workspace.tags(&hub.extension, hub.tag); @@ -307,15 +326,17 @@ fn reads( for (file, call, name, main) in tagged.chain(legacy) { called = true; let own = |lock: &String| locks.iter().any(|own| below(project, own) == *lock); - if let Some(lock) = files(workspace, call, hub.files, main) - .into_iter() - .find(own) - { + let named = files(workspace, call, hub.files, main); + // A requirements file that brings one of the locks in with `-r` + // hands the hub that lock as well. + let includes = |lock: &&String| ecosystem == "pypi" && includes_one(lock, &own, read); + let found = named.iter().find(|lock| own(lock)); + if let Some(lock) = found.or_else(|| named.iter().find(includes)) { return Some(Ok(Unbuilt { call: name.to_string(), file: file.to_string(), line: call.line, - lock, + lock: lock.clone(), })); } let written = |file: &&str| { @@ -347,6 +368,34 @@ fn reads( doubt.or_else(|| hidden().or_else(unread).cloned()).map(Err) } +/// Whether the requirements file `start` (a path from the Bazel root) +/// brings in a file for which `own` holds, through its `-r` includes and +/// theirs, each read with `read`. An include that cannot be read brings in +/// nothing that can be seen. +fn includes_one( + start: &str, + own: &dyn Fn(&String) -> bool, + read: &dyn Fn(&str) -> Option, +) -> bool { + let mut seen = HashSet::new(); + let mut stack = vec![start.to_string()]; + while let Some(file) = stack.pop() { + if !seen.insert(file.clone()) { + continue; + } + let Some(text) = read(&file) else { + continue; + }; + for include in crate::vendor::pypi_requirements::requirements_includes(&file, &text) { + if own(&include) { + return true; + } + stack.push(include); + } + } + false +} + /// The name a `workspace(name = ...)` call gives the main repository. fn workspace_name(call: &Call) -> Option<&str> { match (call.callee.as_str(), call.arg("name")) { @@ -1013,7 +1062,8 @@ use_repo(ruby, "bundle") None => Entry::Absent, }); let locks: Vec = locks.iter().map(|lock| lock.to_string()).collect(); - match reads(&workspace, project, ecosystem, &locks) { + let read = |path: &str| text(path).map(|(_, text)| text.to_string()); + match reads(&workspace, project, ecosystem, &locks, &read) { Some(Ok(by)) => format!("{} {}:{} {}", by.call, by.file, by.line, by.lock), Some(Err(doubt)) => format!("? {}:{} {}", doubt.file, doubt.line, doubt.why), None => String::new(), @@ -1080,6 +1130,26 @@ use_repo(ruby, "bundle") assert_eq!(reader_of(&SHOP, "api", "cargo", &["requirements.txt"]), ""); } + /// A requirements file a call names that brings a lock of the project + /// in with `-r`, directly or through another include, hands the hub + /// that lock: the call is found, with the file it names. An include + /// that reaches no lock of the project, or a Gemfile, is not. + #[test] + fn a_hub_file_that_includes_a_lock_of_the_project_is_found() { + let parent = "api/requirements.txt"; + let mut files = with(parent, "-r requirements/all.txt\n"); + files.push(("api/requirements/all.txt", "-r ../base.txt\n-r dev.txt\n")); + files.push(("api/requirements/dev.txt", "-r all.txt\n")); + let api = "pip.parse MODULE.bazel:15 api/requirements.txt"; + assert_eq!(reader_of(&files, "api", "pypi", &["base.txt"]), api); + let all = ["requirements/all.txt"]; + assert_eq!(reader_of(&files, "api", "pypi", &all), api); + assert_eq!(reader_of(&files, "api", "pypi", &["other.txt"]), ""); + let mut files = with("billing/Gemfile.lock", "-r Gemfile.other\n"); + files.push(("billing/Gemfile", "-r Gemfile.other\n")); + assert_eq!(reader_of(&files, "billing", "gem", &["Gemfile.other"]), ""); + } + /// Where the workspace calls the hub and what a call names cannot be /// read, the answer is the doubt, for every project. A doubt of a /// workspace that does not call the hub is none. diff --git a/crates/socket-patch-core/src/vendor/bazel_hub.rs b/crates/socket-patch-core/src/vendor/bazel_hub.rs index 6f316895e..cde62bcc7 100644 --- a/crates/socket-patch-core/src/vendor/bazel_hub.rs +++ b/crates/socket-patch-core/src/vendor/bazel_hub.rs @@ -35,7 +35,7 @@ use std::path::Path; -use crate::bazel::built::{lock_text, reader, Unbuilt}; +use crate::bazel::built::{from_root, lock_text, reader, Unbuilt}; use crate::bazel::workspace::Doubt; use crate::bazel::BazelRoot; use crate::crawlers::Ecosystem; @@ -136,10 +136,11 @@ async fn refusals_unless<'a>( }; let mut wired = names(lock); // The first file a call names says nothing of a second one. Another - // file of the list that a call names stands in the way when it - // holds the package and not by the copy (a `uv.lock` locked again - // beside a vendored requirements file): the run would rewrite it. - // One that cannot be read may hold it. + // file of the list that a call names, or may name where the reading + // is in doubt, stands in the way when it holds the package and not + // by the copy (a `uv.lock` locked again beside a vendored + // requirements file): the run would rewrite it. One that cannot be + // read may hold it. let name = purl .rsplit('/') .next() @@ -156,9 +157,9 @@ async fn refusals_unless<'a>( if !wired { break; } - if let Some(Ok(named)) = reader(&root, purls, vec![file.clone()]).await { - let dir = root.dir.clone(); - let text = run_blocking(move || lock_text(&dir, &named.lock)).await; + if reader(&root, purls, vec![file.clone()]).await.is_some() { + let (dir, file) = (root.dir.clone(), from_root(&root, file)); + let text = run_blocking(move || lock_text(&dir, &file)).await; wired = names(&text) || !holds(&text); } } @@ -406,6 +407,38 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//api:Gemfile", gemfile_lock = "// assert_eq!(declined().await, [other, gem]); fs::write(api.join("uv.lock"), "").unwrap(); assert_eq!(declined().await, [other, gem]); + // A second attribute that is not written out may name the uv lock: + // it is read as one the call names. (The hub names the vendored + // requirements file itself here: `-r base.txt` would hold `a`.) + fs::write(api.join("requirements.txt"), &line).unwrap(); + let unwritten = "\"//api:requirements.txt\", requirements_by_platform = PLATFORMS"; + fs::write( + root.join("MODULE.bazel"), + HUBS.replace("\"//api:base.txt\"", unwritten), + ) + .unwrap(); + fs::write(api.join("uv.lock"), entry("")).unwrap(); + assert_eq!(declined().await, [wheel, other, gem]); + fs::write(api.join("uv.lock"), entry(©)).unwrap(); + assert_eq!(declined().await, [other, gem]); + } + + /// A requirements file the hub reads that brings the project's own in + /// with `-r` hands the hub every file the run would write: declined. + #[tokio::test] + async fn a_hub_file_that_includes_the_project_s_requirements_is_declined() { + let hub = HUBS.replace("//api:base.txt", "//api:all.txt"); + let files = [ + ("api/all.txt", "-r requirements.txt\n"), + ("api/requirements.txt", "x==1.0.0\n"), + ]; + let (_tmp, root) = checkout(&hub, &files); + let (code, detail) = declined(&root.join("api"), Ecosystem::Pypi).await; + assert_eq!(code, PYPI_CODE); + assert!(detail.contains("names api/all.txt; "), "{detail}"); + // Without the include, the hub reads a file the run leaves alone. + fs::write(root.join("api/all.txt"), "y==1.0.0\n").unwrap(); + assert_eq!(asked(&root.join("api"), Ecosystem::Pypi, false).await, None); } /// The uv lock of the project is a file a hub can be given, and a hub diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 142c5444e..929fdf942 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 2574 + "max": 2611 }, "lock-readers": { "paths": [ From 224f39d477072687bff575d4e1e1024affecdc59 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 15:08:20 -0500 Subject: [PATCH 05/19] Test agent mode for Cargo and NuGet beside a Bazel hub that builds from the lock Two flows on real Bazel, tests only, that record what socket-patch does today in a workspace where a ruleset builds a package from the project's lock and agent mode patches the copy a package manager unpacked outside the checkout: - `cargo::agent_from_cargo_with_config`: rules_rust's `crate.from_cargo(cargo_lockfile = "//:Cargo.lock", ...)`, and the crate in `$CARGO_HOME/registry/src`, as after `cargo fetch`. - `nuget::agent_from_lock`: rules_csharp's `nuget.from_lock(packages_lock_json = "//:packages.lock.json", ...)`, and the package in NuGet's global packages folder, as after `dotnet restore`. In both, `scan --mode agent --yes` exits 0 with the patch applied to that copy and writes nothing into the checkout but `.socket/`, and `apply` passes. `bazel build` and `bazel run //:consumer` print the unpatched marker before the command and after it: each hub has Bazel download the package the lock pins, and no build reads a cargo home or NuGet's folder. The build right after the command is a warm one, which looks at nothing outside the checkout again, so each flow ends with a build on a second machine: a copy of the checkout without `MODULE.bazel.lock` and with an empty output base, whose Bazel has the patched cargo home or NuGet folder in its environment and evaluates the hub anew. It prints the unpatched marker too. Meanwhile `scan --mode agent --vex`, `apply --vex`, `vex` and `vex --no-verify` each write an OpenVEX document whose one statement says the package is `not_affected`, "Patched via Socket patch ". That document is false for what Bazel builds. The flows assert it as it is today and mark it KNOWN GAP, with what a fix changes in the test. The copy in the cargo home is the one the hub's own cargo unpacked there where the ruleset runs that cargo with the home of the environment (rules_rust 0.56.0), and is laid out by the test where it does not (0.75.0); NuGet's folder is laid out as the hosted flow already does. No cargo and no dotnet runs. The Bazel commands of the NuGet flow get the two variables of the .NET home that `socket-patch` gets (`NUGET_PACKAGES`, `DOTNET_CLI_HOME`), so a build that read the folder would find it. What the flows share is in the harness: `Cell::patches_outside`, and `Cell::builds_anew` for the second machine, which removes the first workspace copy before it builds where the repository cache outlives that copy. The grant helpers of the two modules are split so that a patch record can carry the file contents agent mode patches from, and in the Cargo module the helper that names the hosts of a child takes its cargo home as well; the hosted and vendored flows call them as before and assert what they asserted. The two workflows say that their legs now run agent mode, and start on a pull request that changes the VEX code (`vex/` of the core, the `vex` command) or, for NuGet, agent mode's own file. Both flows pass on Bazel 9.3.2 (macOS arm64) with no change to the product: NuGet in 14 s, Cargo in 92 s with an empty repository cache. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-cargo.yml | 43 ++-- .github/workflows/bazel-nuget.yml | 61 +++--- .../tests/e2e_bazel_build/cargo.rs | 206 +++++++++++++++--- .../tests/e2e_bazel_build/harness.rs | 58 +++++ .../tests/e2e_bazel_build/nuget.rs | 203 +++++++++++++++-- 5 files changed, 475 insertions(+), 96 deletions(-) diff --git a/.github/workflows/bazel-cargo.yml b/.github/workflows/bazel-cargo.yml index 931c7dbac..ed82c851f 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,27 @@ 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 and the files of the `vex` command. 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 +80,8 @@ 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/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 +101,8 @@ 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/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..01b9ebf5d 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,39 @@ 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 + # 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 and the files of the `vex` command. 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' @@ -74,14 +80,17 @@ on: - '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' @@ -101,10 +110,12 @@ on: - '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/tests/e2e_bazel_build/cargo.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs index d77fb6975..1413021cd 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,14 @@ //! 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 what every form of `vex` says of the crate meanwhile +//! (see "Known gaps"). +//! //! 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 @@ -192,19 +201,30 @@ //! without a Bazel //! ([`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; +//! +//! # Known gaps +//! +//! One assertion of the agent flow holds what is wrong today, with every +//! ruleset, and is marked `KNOWN GAP` there with what a fix changes in this +//! test: `scan --mode agent --vex`, `apply --vex`, `vex` and +//! `vex --no-verify` each write a document that says the crate is not +//! affected, through the patch, while Bazel builds the unpatched crate. +//! `vex` reads the copy in the cargo home and not what the hub builds from. +//! A fix makes the document say that the crate is affected, and name the +//! call of `MODULE.bazel` that builds it from the lock. + +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, Cell, Claim, Fixture, How, Ran, Release, StandIn, + Tree, CONSUMER, NOTHING, REPO_CACHE, }; use crate::hosted_memory_common::{Patch, ORG}; @@ -521,6 +541,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 +608,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 +717,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 +741,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), ] } @@ -1675,6 +1724,103 @@ 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 +} + +/// 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`]). KNOWN GAP: both, `vex` and +/// `vex --no-verify` write a document that says the crate is not +/// affected, through the patch. +/// - (c) The same two Bazel commands print the unpatched marker again, and +/// change no file: the hub has Bazel download the crate file the lock +/// pins, and no build reads a cargo home. So the documents of (b) are +/// false for what Bazel builds. +/// - (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. KNOWN GAP: every + // document says the crate is not affected. Once `vex` reads the hub, + // the claim is `Claim::unbuilt`, with the call and the lock it names. + let library = fetched(home.path(), &upstream); + let run = |cell: &Cell, args: &[&str]| socket_patch_at(cell, &standin, home.path(), args); + let claim = Claim::new(PURL, &patch.uuid, How::Agent); + 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. + cell.builds(&upstream.marker); + 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; (KNOWN GAP) every form of `vex` said the crate is not \ + affected; {:?}", + upstream.marker, + library.display(), + started.elapsed() + ); +} + /// 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 d0fdc9917..e54295fdd 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -1024,6 +1024,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 { @@ -1409,6 +1424,49 @@ 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 + } + /// 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..7cdd872fa 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,13 @@ //! 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 what every form of `vex` says of the package meanwhile +//! (see "Known gaps"). +//! //! 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 +137,7 @@ //! //! # Known gaps //! -//! Three outcomes the flow asserts are gaps of the product, not its +//! Four 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: //! @@ -142,6 +149,11 @@ //! while Bazel builds the patched package (c). //! - Bazel prints the access token of the grant, in a warning for each //! package of the lock that the Socket source does not hold (c). +//! - After agent mode, `scan --mode agent --vex`, `apply --vex`, `vex` and +//! `vex --no-verify` each write a document that says the package is not +//! affected, through the patch, while Bazel builds the unpatched package: +//! `vex` reads the copy in NuGet's folder and not what the hub builds +//! from (the agent flow). use std::io::Write as _; use std::path::{Path, PathBuf}; @@ -154,8 +166,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, Cell, Claim, Fixture, How, Ran, StandIn, + Tree, CONSUMER, NOTHING, }; use crate::hosted_memory_common::{read_tree, Patch, ORG}; @@ -440,6 +452,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 +522,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 +1005,128 @@ 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)) + } +} + +/// 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`]). KNOWN GAP: both, `vex` and +/// `vex --no-verify` write a document that says the package is not +/// affected, through the patch. +/// - (c) The same two Bazel commands print the unpatched marker again, and +/// change no file: the hub has Bazel download the package the lock pins, +/// and no build reads NuGet's folder. So the documents of (b) are false +/// for what Bazel builds. +/// - (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. KNOWN GAP: every + // document says the package is not affected. Once `vex` reads the hub, + // the claim is `Claim::unbuilt`, with the call and the lock it names. + let assembly = machine.assembly(); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, standin, machine.home.path(), args); + let claim = Claim::new(&purl, &patch.uuid, How::Agent); + 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. + cell.builds(&unpatched); + 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; (KNOWN GAP) every form of `vex` said the package \ + is not affected; {:?}", + 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 From a60599c7064f6a52328f9c9a720f33f0e51c82fc Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 15:09:13 -0500 Subject: [PATCH 06/19] Attest a Cargo or NuGet patch as affected in VEX where a Bazel hub builds the package from the lock Agent mode patches a crate in the cargo home (`$CARGO_HOME/registry/src`) and a NuGet package in NuGet's global packages folder. In a Bazel workspace neither copy is built: rules_rust's `crate.from_cargo(cargo_lockfile = ...)` and rules_csharp's `nuget.from_lock(packages_lock_json = ...)` have Bazel download what the project's lock pins. The flows of the commit before this one measured it on Bazel 9.3.2: `scan --mode agent` exits 0 with the patch applied, `bazel build` prints the upstream marker before and after, also on a second machine that evaluates the hub anew, and `scan --vex`, `apply --vex`, `vex` and `vex --no-verify` each attest the package as `not_affected`. That document is false for what Bazel builds. Cargo and NuGet join the table of hubs in `bazel/built.rs`, so what main does for npm, PyPI and RubyGems holds for them too. When a call that is a statement of its own names the project's own `Cargo.lock` or `packages.lock.json` in a plain string, and that lock lists the package at the patched version without the patch, the document says `affected` of the package, with an action statement that names the lock, the call and its line, and what to run. `vex --json` reports a `skipped` event with `vex_bazel_not_in_build` and `details.status: "affected"`, the envelope is `partialFailure` and the exit code is 0, as on main. `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL` leaves Bazel out of it. What the table holds for the two: - rules_rust: the extension by both files that define it at 0.56.0 and 0.75.0 (the constant of `bazel/cargo.rs`), the tag `from_cargo`, the attribute `cargo_lockfile`. Of the lock, the crates of a registry that no `[replace]` swaps out: those are the ones Bazel downloads. A call with a cargo-bazel lock (`lockfile`) is passed over, because the hub renders its crates from that file until a repin. So is one without `cargo_lockfile`, which names no lock. - rules_csharp: the extension as `bazel/nuget.rs` names it, the tag `from_lock`, the attribute `packages_lock_json`. A `packages.lock.json` never names a patch (a hosted pin there is a hash), and rules_csharp 0.5.0 makes one hub of all the `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 a project patched in agent mode can be built patched through the hosted pin of another project of the workspace (measured on Bazel 9.3.2 with two calls). The `nuget_config` of every call is therefore searched for the id of the patch together with the lock. Where one names it, or is not a plain label, or cannot be read, or a call passes `*` or `**`, nothing is said of the hub. The locks are still read one call at a time, and `feeds` and `local_package_dirs` are not read. The action statement names the modes that a flow of this repository builds patched on real Bazel under that hub, so a hub carries its own sentence: hosted mode with the attribute it needs of the call (`cargo_config`, `nuget_config`), and for a crate vendored mode as well. The sentence of the three hubs on main is the same bytes as before, and their calls are judged one at a time as before. Left as main has them: a hosted pin (the caller hands none over, and whether a hub takes one is for `bazel/cargo.rs` and `bazel/nuget.rs` to say), a vendored crate (rules_rust builds it), a vendored NuGet package (no test builds one under its hub), a project whose lock no call names, a workspace that is not read with certainty, and a project in no Bazel workspace. Tests: unit tests of the table (what a lock lists, which calls are passed over, the hub of several `nuget.from_lock` calls, a doubt on the hub by either file of the rules_rust extension, the sentence of each hub). Two tests without Bazel per ecosystem run the binary in a checkout of the fixture: one runs the scans the action statement names and holds the document after each to `not_affected`; the other holds `vex`, wherever the hub decides nothing and with `--no-bazel`, to what it gives in the same checkout without its `MODULE.bazel` (exit code, both streams, the document), through `Cell::keeps_its_statement` of the harness. For NuGet one of those hubs has a second call whose `nuget_config` names the patch. The two agent flows now expect `affected` from the run, from `apply`, from `vex` and from `vex --no-verify`, and `not_affected` from `vex --no-bazel`, while the build still prints the upstream marker, on the second machine too. No assertion of the hosted and vendored flows is edited. One existing unit test took a Cargo purl for a package of no hub; it takes a Go module now. Docs: the VEX cells of Cargo and NuGet in "Bazel workspaces: what is supported", the section "Bazel workspaces: VEX" and the `vex_bazel_not_in_build` row of the CLI contract. The two workflows start their legs on a change to `bazel/built.rs` and to the reader of the workspace files, each by its path. The size budget of `bazel/` follows the code (3337 to 3403 lines). Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-cargo.yml | 23 +- .github/workflows/bazel-nuget.yml | 14 +- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- crates/socket-patch-cli/src/commands/vex.rs | 27 +- .../tests/e2e_bazel_build/cargo.rs | 150 ++++-- .../tests/e2e_bazel_build/harness.rs | 38 ++ .../tests/e2e_bazel_build/nuget.rs | 146 +++++- crates/socket-patch-core/src/bazel/built.rs | 465 ++++++++++++++++-- crates/socket-patch-core/src/bazel/cargo.rs | 2 +- docs/ecosystems.md | 88 +++- scripts/loc-budget.json | 2 +- 11 files changed, 813 insertions(+), 144 deletions(-) diff --git a/.github/workflows/bazel-cargo.yml b/.github/workflows/bazel-cargo.yml index ed82c851f..e19a1adcc 100644 --- a/.github/workflows/bazel-cargo.yml +++ b/.github/workflows/bazel-cargo.yml @@ -56,11 +56,14 @@ on: # 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. Last, the VEX code: - # `vex/` of the core and the files of the `vex` command. 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. + # `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/, the rest of commands/, the apply engine @@ -80,6 +83,11 @@ 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: @@ -101,6 +109,11 @@ 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' diff --git a/.github/workflows/bazel-nuget.yml b/.github/workflows/bazel-nuget.yml index 01b9ebf5d..135293751 100644 --- a/.github/workflows/bazel-nuget.yml +++ b/.github/workflows/bazel-nuget.yml @@ -46,11 +46,13 @@ on: # version and folder helpers that every one of those files calls. # 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 and the files of the `vex` command. 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. + # 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 @@ -76,6 +78,7 @@ 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' @@ -106,6 +109,7 @@ 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' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 42c5d4a95..f1afc9a5a 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -4130,7 +4130,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, 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, 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, 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 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 1413021cd..e2f952b09 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs @@ -89,8 +89,9 @@ //! 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 what every form of `vex` says of the crate meanwhile -//! (see "Known gaps"). +//! 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 @@ -201,17 +202,6 @@ //! without a Bazel //! ([`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`]). -//! -//! # Known gaps -//! -//! One assertion of the agent flow holds what is wrong today, with every -//! ruleset, and is marked `KNOWN GAP` there with what a fix changes in this -//! test: `scan --mode agent --vex`, `apply --vex`, `vex` and -//! `vex --no-verify` each write a document that says the crate is not -//! affected, through the patch, while Bazel builds the unpatched crate. -//! `vex` reads the copy in the cargo home and not what the hub builds from. -//! A fix makes the document say that the crate is affected, and name the -//! call of `MODULE.bazel` that builds it from the lock. use std::path::{Path, PathBuf}; use std::time::Instant; @@ -223,8 +213,8 @@ 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, Claim, Fixture, How, 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}; @@ -1762,6 +1752,26 @@ fn fetched(home: &Path, upstream: &Package) -> PathBuf { 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 @@ -1770,13 +1780,15 @@ fn fetched(home: &Path, upstream: &Package) -> PathBuf { /// `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`]). KNOWN GAP: both, `vex` and -/// `vex --no-verify` write a document that says the crate is not -/// affected, through the patch. -/// - (c) The same two Bazel commands print the unpatched marker again, and -/// change no file: the hub has Bazel download the crate file the lock -/// pins, and no build reads a cargo home. So the documents of (b) are -/// false for what Bazel builds. +/// ([`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 @@ -1796,16 +1808,19 @@ fn agent_from_cargo_with_config() { // (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. KNOWN GAP: every - // document says the crate is not affected. Once `vex` reads the hub, - // the claim is `Claim::unbuilt`, with the call and the lock it names. + // (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 claim = Claim::new(PURL, &patch.uuid, How::Agent); + 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. @@ -1813,14 +1828,93 @@ fn agent_from_cargo_with_config() { println!( "{test}: Bazel {release} built {:?} before and after `scan --mode agent` patched {}, \ - and on a second machine; (KNOWN GAP) every form of `vex` said the crate is not \ - affected; {:?}", + 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 e54295fdd..99d5a2d79 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -1467,6 +1467,44 @@ impl Cell { 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 7cdd872fa..846cce28a 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs @@ -74,8 +74,9 @@ //! 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 what every form of `vex` says of the package meanwhile -//! (see "Known gaps"). +//! 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 @@ -137,7 +138,7 @@ //! //! # Known gaps //! -//! Four outcomes the flows assert 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: //! @@ -149,11 +150,6 @@ //! while Bazel builds the patched package (c). //! - Bazel prints the access token of the grant, in a warning for each //! package of the lock that the Socket source does not hold (c). -//! - After agent mode, `scan --mode agent --vex`, `apply --vex`, `vex` and -//! `vex --no-verify` each write a document that says the package is not -//! affected, through the patch, while Bazel builds the unpatched package: -//! `vex` reads the copy in NuGet's folder and not what the hub builds -//! from (the agent flow). use std::io::Write as _; use std::path::{Path, PathBuf}; @@ -166,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, Claim, Fixture, How, 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}; @@ -1064,6 +1060,27 @@ impl Restored { } } +/// 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 @@ -1072,13 +1089,15 @@ impl Restored { /// `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`]). KNOWN GAP: both, `vex` and -/// `vex --no-verify` write a document that says the package is not -/// affected, through the patch. -/// - (c) The same two Bazel commands print the unpatched marker again, and -/// change no file: the hub has Bazel download the package the lock pins, -/// and no build reads NuGet's folder. So the documents of (b) are false -/// for what Bazel builds. +/// ([`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) @@ -1103,16 +1122,19 @@ fn agent_from_lock() { "{test}: the build did not fetch the upstream package from the stand-in" ); - // (b) Agent mode patches the copy in NuGet's folder. KNOWN GAP: every - // document says the package is not affected. Once `vex` reads the hub, - // the claim is `Claim::unbuilt`, with the call and the lock it names. + // (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 claim = Claim::new(&purl, &patch.uuid, How::Agent); + 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. @@ -1120,8 +1142,9 @@ fn agent_from_lock() { println!( "{test}: Bazel {release} built {unpatched:?} before and after `scan --mode agent` \ - patched {}, and on a second machine; (KNOWN GAP) every form of `vex` said the package \ - is not affected; {:?}", + 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() ); @@ -1412,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 +/// the lock of another directory, 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..47a568751 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 @@ -37,9 +40,11 @@ //! 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 ([`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,7 +53,20 @@ //! 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 named plainly 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. @@ -62,8 +80,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 +120,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,7 +130,8 @@ 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. @@ -118,19 +142,40 @@ struct Hub { /// each from that directory: the members of a pnpm workspace. members: fn(&str) -> Vec, /// Whether a call of the tag may build a package from a line that - /// points at a copy under `.socket/vendor`: rules_js does, and of - /// rules_ruby no build has shown that it does not. + /// points at a copy under `.socket/vendor`: rules_js 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."; + +/// The attributes with which a call can take its packages from a file that +/// is not read here, whatever its lock lists. `uv_lock` of `pip.parse`: +/// rules_python 2.2.0 and later. `lockfile` of `crate.from_cargo`: 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). +const ELSEWHERE: [&str; 2] = ["uv_lock", "lockfile"]; + +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"], lists: |text| { @@ -143,14 +188,16 @@ const HUBS: [Hub; 3] = [ }, members: lock_text_member_importers, 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", @@ -169,19 +216,60 @@ const HUBS: [Hub; 3] = [ }, members: |_| Vec::new(), 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"], lists: |text| owned(locked_specs(text).into_iter()), members: |_| Vec::new(), builds_vendored: true, + beside: &[], + remedy: HOSTED, + }, + Hub { + ecosystem: "cargo", + extensions: &super::cargo::EXTENSIONS, + tag: "from_cargo", + files: &["cargo_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(), + 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"], + 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(), + 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 +364,34 @@ 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 is not + // named plainly, or that a call may pass unseen, may name any. + let beside = |tag: &Tag| files(workspace, tag.call, hub.beside); + let beside: Vec = calls().flat_map(beside).collect(); + let given = |name: &&str| calls().filter(|tag| tag.call.arg(name).is_some()).count(); + let given: usize = hub.beside.iter().map(given).sum(); + let unseen = !hub.beside.is_empty() && calls().any(|tag| tag.call.unpacks()); + if beside.len() != given || unseen { continue; } // 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| 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]; @@ -298,12 +403,15 @@ fn judge( None => { let listed = listed.entry(lock.clone()).or_insert_with(|| { let member = from_lock(project, &lock)?; - let text = read(&lock)?; + 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(); + for file in &beside { + text.push_str(&read(file)?); + } let key = |(name, version)| { PurlKey::new(&format!("pkg:{}/{name}@{version}", hub.ecosystem)) }; @@ -325,10 +433,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, }); } } @@ -619,12 +728,281 @@ 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"] { + assert_eq!(installed(project, JSON), "", "{project:?}"); + } + // 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", + "**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 +1169,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 +1283,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 0d0353aca..085d48ff0 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1993,8 +1993,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 | 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 | Not supported | Not supported | Supported with a hosted patch | @@ -2015,7 +2015,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 Maven a test without Bazel). It does not say `affected` of a package whose patch @@ -3773,7 +3775,7 @@ restores the original sources and build. `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 | @@ -3781,24 +3783,36 @@ 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`. 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 @@ -3830,6 +3844,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): ``` @@ -3870,7 +3896,10 @@ read with certainty when a module file is missing, cannot be read or holds a sta 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. @@ -3909,8 +3938,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. @@ -3918,15 +3950,20 @@ 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 +- **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. 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 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 @@ -3937,6 +3974,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 25c6e29f0..ea65a0056 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 3337 + "max": 3403 }, "lock-readers": { "paths": [ From 5a5cdc450d2f7f79688b6eee4ab92ed94f2ba511 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 16:22:52 -0500 Subject: [PATCH 07/19] Read a NuGet lock below the run's directory as the project's own in the Bazel VEX answer A NuGet project is every project file below the directory a command runs in, each with a `packages.lock.json` beside it: agent mode patches what any of them restored, and hosted mode and `vex` read a pin in each of their locks. The hub table took only the lock in the run's own directory for the project's, as it does for the other ecosystems. So for a run at the root of a solution, where `nuget.from_lock` names `//src/App:packages.lock.json`, the document kept `not_affected` for a package that Bazel downloads unpatched. The NuGet hub now takes a lock at or below the directory of the run. The other hubs are as they were: a lock below the run is still the lock of another project there. Three smaller changes to the same function, none of which changes what is said of a workspace that Bazel can load: - Whether every `nuget_config` of the hub is a plain label was a comparison of two counts: the labels that resolve, and the calls that give the attribute. A dict counts once as given and once per key as resolved, so the counts could be equal while a config was not read. Each call is now asked on its own: no `nuget_config`, or one string that names a file of the main repository. - The attributes with which a call can take its packages from a file that is not read (`uv_lock`, `lockfile`) were one list for every hub. Each hub now has its own. - The configs of a rules_csharp hub were read again for every lock. They are read once for the hub, when the first lock asks. The docs and the contract row say which lock is the project's own for NuGet, and the list of statements that stay wrong names the member of a Cargo workspace, whose `Cargo.lock` lies above it. The `bazel` line budget is the new count, 3704. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../tests/e2e_bazel_build/nuget.rs | 2 +- crates/socket-patch-core/src/bazel/built.rs | 106 ++++++++++++------ docs/ecosystems.md | 15 ++- scripts/loc-budget.json | 2 +- 5 files changed, 87 insertions(+), 40 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index fd7f28079..97f7143a9 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -4133,7 +4133,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`, 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, 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, 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, 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 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_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/tests/e2e_bazel_build/nuget.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs index 846cce28a..b4df3ccca 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs @@ -1475,7 +1475,7 @@ fn an_installed_package_is_affected_beside_a_hub_that_reads_the_lock() { /// 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 -/// the lock of another directory, one whose `nuget_config` is not written +/// 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 diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index 47a568751..f569ec39d 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -34,14 +34,15 @@ //! 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 one that can take its packages from a file -//! that is not read here ([`ELSEWHERE`]). A `crate.from_cargo` without +//! 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. @@ -61,8 +62,8 @@ //! 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 named plainly or a call passes `*` or `**`. The -//! locks are still read one call at a time, and `feeds` and +//! 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 @@ -73,6 +74,7 @@ //! //! [`Tags::doubts`]: super::workspace::Tags::doubts +use std::cell::OnceCell; use std::collections::{HashMap, HashSet}; use std::io::Read; use std::path::{Component, Path}; @@ -136,11 +138,19 @@ struct Hub { /// 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 and rules_rust /// do, and of rules_ruby and rules_csharp no test here has shown @@ -161,13 +171,6 @@ struct Hub { const HOSTED: &str = "Run `socket-patch scan --mode hosted` in the directory of that lock to pin \ the patch there."; -/// The attributes with which a call can take its packages from a file that -/// is not read here, whatever its lock lists. `uv_lock` of `pip.parse`: -/// rules_python 2.2.0 and later. `lockfile` of `crate.from_cargo`: 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). -const ELSEWHERE: [&str; 2] = ["uv_lock", "lockfile"]; - const HUBS: [Hub; 5] = [ Hub { ecosystem: "npm", @@ -178,6 +181,7 @@ const HUBS: [Hub; 5] = [ }], tag: "npm_translate_lock", files: &["pnpm_lock"], + elsewhere: &[], lists: |text| { let project = documents(text).into_iter(); let project = project.filter(|(_, kind)| *kind == PnpmDocument::Project); @@ -187,6 +191,7 @@ const HUBS: [Hub; 5] = [ owned(keys.filter_map(|package| pnpm_registry_key(package.key))) }, members: lock_text_member_importers, + nested: false, builds_vendored: true, beside: &[], remedy: HOSTED, @@ -206,6 +211,8 @@ const HUBS: [Hub; 5] = [ "requirements_linux", "requirements_windows", ], + // rules_python 2.2.0 and later. + elsewhere: &["uv_lock"], lists: |text| { let lines = logical_lines(text); owned( @@ -215,6 +222,7 @@ const HUBS: [Hub; 5] = [ ) }, members: |_| Vec::new(), + nested: false, builds_vendored: false, beside: &[], remedy: HOSTED, @@ -228,8 +236,10 @@ const HUBS: [Hub; 5] = [ }], 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, @@ -239,6 +249,10 @@ const HUBS: [Hub; 5] = [ 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()); @@ -247,6 +261,7 @@ const HUBS: [Hub; 5] = [ 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 \ @@ -259,12 +274,14 @@ const HUBS: [Hub; 5] = [ 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 \ @@ -373,23 +390,33 @@ fn judge( // 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 is not - // named plainly, or that a call may pass unseen, may name any. - let beside = |tag: &Tag| files(workspace, tag.call, hub.beside); - let beside: Vec = calls().flat_map(beside).collect(); - let given = |name: &&str| calls().filter(|tag| tag.call.arg(name).is_some()).count(); - let given: usize = hub.beside.iter().map(given).sum(); + // 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()); - if beside.len() != given || unseen { + 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, 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 named = |call: &Call| ELSEWHERE.iter().any(|name| call.arg(name).is_some()); + 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) { @@ -402,16 +429,15 @@ fn judge( } None => { let listed = listed.entry(lock.clone()).or_insert_with(|| { - let member = from_lock(project, &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(); - for file in &beside { - text.push_str(&read(file)?); - } + text.push_str(configs.get_or_init(texts).as_deref()?); let key = |(name, version)| { PurlKey::new(&format!("pkg:{}/{name}@{version}", hub.ecosystem)) }; @@ -461,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 @@ -480,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 @@ -873,9 +909,14 @@ replace = "swapped 3.0.0" for (project, purl) in [("desk", SERDE), ("", SERDE), ("engine/cli", SERDE)] { assert_eq!(installed(project, purl), "", "{project:?}"); } - for project in ["engine", "", "desk/tests"] { + 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)), ""); @@ -991,6 +1032,7 @@ replace = "swapped 3.0.0" "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}"); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 338b3dfb1..a1edba31d 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -3970,7 +3970,9 @@ package that it is `affected`, not that it is patched: 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`. Of a `Cargo.lock` the crates of a registry count, which are the ones the hub + `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 @@ -4064,7 +4066,8 @@ 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 @@ -4132,9 +4135,11 @@ the build is broken): 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. 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 + 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, rules_rust and rules_csharp, which build from the lock and never read the diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index d418935f1..7453a62ae 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 3681 + "max": 3704 }, "lock-readers": { "paths": [ From 541644f7a69b23379e147914923ac65d7e56b1e5 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 16:42:10 -0500 Subject: [PATCH 08/19] Accept either unseen repository where a Cargo flow comments out the ignore line `cargo::vendored_from_cargo_with_config` comments out the line the scan wrote in `.bazelignore` and expects `bazel cquery //...` and `bazel query 'deps(//...)'` to fail on a repository that the main repository does not see. It looked for the hub's repository (`@crates__...`) alone. The build file that cargo-bazel writes into the committed copy names `@platforms` as well, and Bazel reports the first one it meets: on a Linux runner with Bazel 9.3.2 the query named `@platforms` and the flow failed on its own check. The flow now takes either name for that failure. Test only: nothing the command does changes. Co-Authored-By: Claude Fable 5.2 --- .../socket-patch-cli/tests/e2e_bazel_build/cargo.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) 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 e2f952b09..bcd9895c1 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs @@ -913,13 +913,18 @@ fn every_target(cell: &Cell) -> Vec { /// 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: one of the hub, or +/// `platforms`. Bazel names the first one it meets, and which one that is +/// differs from run to run. 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 stderr = run.stderr(); + let unseen = ["@crates__", "@platforms'"] + .iter() + .any(|repo| stderr.contains(&format!("No repository visible as '{repo}"))); assert_ne!(run.ok(), unseen, "{}: {}", cell.test, run.dump()); } assert_eq!(runs[0].ok(), runs[1].ok(), "{}", cell.test); From 23398b6b1135e399e549359d5731ff1b3d881079 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 16:42:10 -0500 Subject: [PATCH 09/19] Accept either unseen repository where a Cargo flow comments out the ignore line `cargo::vendored_from_cargo_with_config` comments out the line the scan wrote in `.bazelignore` and expects `bazel cquery //...` and `bazel query 'deps(//...)'` to fail on a repository that the main repository does not see. It looked for the hub's repository (`@crates__...`) alone. The build file that cargo-bazel writes into the committed copy names `@platforms` as well, and Bazel reports the first one it meets: on a Linux runner with Bazel 9.3.2 the query named `@platforms` and the flow failed on its own check. The flow now takes either name for that failure. Test only: nothing the command does changes. Co-Authored-By: Claude Fable 5.2 --- .../socket-patch-cli/tests/e2e_bazel_build/cargo.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) 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..1ee8c374c 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs @@ -874,13 +874,18 @@ fn every_target(cell: &Cell) -> Vec { /// 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: one of the hub, or +/// `platforms`. Bazel names the first one it meets, and which one that is +/// differs from run to run. 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 stderr = run.stderr(); + let unseen = ["@crates__", "@platforms'"] + .iter() + .any(|repo| stderr.contains(&format!("No repository visible as '{repo}"))); assert_ne!(run.ok(), unseen, "{}: {}", cell.test, run.dump()); } assert_eq!(runs[0].ok(), runs[1].ok(), "{}", cell.test); From 46eacb8ae234e0da2bc40c788c3ee71a014a7567 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 17:55:54 -0500 Subject: [PATCH 10/19] Hold the unseen repository to Bazel's own words, and say so in the docs The check of the commands that fail once the ignore line is commented out now reads the name out of Bazel's message and takes it only when the message is about the main repository's view: `platforms`, or a repository of the crate hub. The same words about another repository's view, or about another name, are a different failure and no longer pass for the expected one. A test without Bazel holds the check to the two messages that were seen and to three it must not take. The module docs, the comment at the call and the section on the build file in a vendored crate said the commands end on the dependency's repository alone. They now name `platforms` as well, which is what a user who comments the line out can see. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_bazel_build/cargo.rs | 51 ++++++++++++++----- docs/ecosystems.md | 5 +- 2 files changed, 41 insertions(+), 15 deletions(-) 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 bcd9895c1..2aa5d7ab9 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs @@ -182,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 @@ -911,20 +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 that the build file in the -/// copy names and the main repository does not see: one of the hub, or -/// `platforms`. Bazel names the first one it meets, and which one that is -/// differs from run to run. +/// 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 stderr = run.stderr(); - let unseen = ["@crates__", "@platforms'"] - .iter() - .any(|repo| stderr.contains(&format!("No repository visible as '{repo}"))); + let unseen = unseen(&run.stderr()); assert_ne!(run.ok(), unseen, "{}: {}", cell.test, run.dump()); } assert_eq!(runs[0].ok(), runs[1].ok(), "{}", cell.test); @@ -1238,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); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index a1edba31d..9cb55b19e 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2910,8 +2910,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` From f3e56238f5acc7e83023166de977e90aec4adf15 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 17:55:54 -0500 Subject: [PATCH 11/19] Hold the unseen repository to Bazel's own words, and say so in the docs The check of the commands that fail once the ignore line is commented out now reads the name out of Bazel's message and takes it only when the message is about the main repository's view: `platforms`, or a repository of the crate hub. The same words about another repository's view, or about another name, are a different failure and no longer pass for the expected one. A test without Bazel holds the check to the two messages that were seen and to three it must not take. The module docs, the comment at the call and the section on the build file in a vendored crate said the commands end on the dependency's repository alone. They now name `platforms` as well, which is what a user who comments the line out can see. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_bazel_build/cargo.rs | 51 ++++++++++++++----- docs/ecosystems.md | 5 +- 2 files changed, 41 insertions(+), 15 deletions(-) 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 1ee8c374c..a8f49e0a5 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs @@ -172,10 +172,12 @@ //! the same. //! - Bazel would read that file as a package of the user's workspace. The //! crate has a dependency ([`DEP`]), so the file names a repository of -//! the hub, which the main repository does not see, and the commands -//! that analyse every target fail on it: `bazel cquery //...` and -//! `bazel query 'deps(//...)'` ([`analyses`]). The line that the scan -//! wrote into `.bazelignore` keeps the copies out of Bazel's packages: +//! the hub, which the main repository does not see, as it does not see +//! `platforms`, which the file names too. The commands that analyse +//! every target fail on the first of the two that Bazel meets: +//! `bazel cquery //...` and `bazel query 'deps(//...)'` ([`analyses`]). +//! The line that the scan wrote into `.bazelignore` keeps the copies out +//! of Bazel's packages: //! `//...` is the user's own target ([`every_target`]), both commands //! pass, and the build is the patched one, because the hub reads the //! copy by its path, not as a package. A user who comments the line out @@ -872,20 +874,42 @@ fn every_target(cell: &Cell) -> Vec { targets } +/// Whether `stderr` says that the main repository does not see a +/// repository that the build file in the copy names: one of the hub, or +/// `platforms`. Bazel names the first one it meets, and which one that is +/// differs from run to run. The same words about another repository's view +/// are another failure. +fn unseen(stderr: &str) -> bool { + (stderr.split("No repository visible as '@").skip(1)) + .filter_map(|rest| rest.split_once("' from main repository")) + .any(|(repo, _)| { + !repo.contains('\'') && (repo == "platforms" || repo.starts_with("crates__")) + }) +} + +/// [`unseen`] takes the two messages Bazel was seen to print, and neither +/// another repository's name nor another repository's view. +#[test] +fn an_unseen_repository_is_one_the_copy_names_and_the_main_repository_misses() { + let said = |repo: &str, from: &str| { + format!("ERROR: no such package: No repository visible as '@{repo}' from {from}\n") + }; + assert!(unseen(&said("platforms", "main repository"))); + assert!(unseen(&said("crates__dep-1.0.0", "main repository"))); + assert!(!unseen(&said("rules_cc", "main repository"))); + assert!(!unseen(&said("platforms", "repository '@@rules_rust+'"))); + assert!(!unseen("Loading: 0 packages loaded\n")); +} + /// Whether the commands that analyse every target of the checkout of /// `cell` pass: `bazel cquery //...` and `bazel query 'deps(//...)'`, which /// agree. One that fails has met a repository that the build file in the -/// copy names and the main repository does not see: one of the hub, or -/// `platforms`. Bazel names the first one it meets, and which one that is -/// differs from run to run. +/// 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 stderr = run.stderr(); - let unseen = ["@crates__", "@platforms'"] - .iter() - .any(|repo| stderr.contains(&format!("No repository visible as '{repo}"))); + let unseen = unseen(&run.stderr()); assert_ne!(run.ok(), unseen, "{}: {}", cell.test, run.dump()); } assert_eq!(runs[0].ok(), runs[1].ok(), "{}", cell.test); @@ -1199,8 +1223,9 @@ fn vendored_from_cargo_with_config() { // package: `//...` is the consumer alone, and the commands that analyse // every target pass. A user who comments the line out has the package // back, where the ruleset writes the build file: `//...` names targets - // there, those commands fail on the repository of the dependency, and - // the file Bazel now reads is a change of the copy again. + // there, those commands fail on a repository that the file names and + // the main repository does not see, and the file Bazel now reads is a + // change of the copy again. assert_eq!(every_target(&cell), [CONSUMER], "{test}"); assert!(analyses(&cell), "{test}: under the line of the scan"); cell.write(".bazelignore", DECLINED); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 12a1d016c..20264f90b 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -3113,8 +3113,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` From 6e78f046b5d018eef3d9286dff429854a05d154d Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 01:04:04 -0500 Subject: [PATCH 12/19] Test agent mode for Maven beside a Bazel hub that fetches the jar from its lock Two tests, no product change, that record what socket-patch does today in a workspace where a pinned rules_jvm_external hub (`maven.install(lock_file = "//:maven_install.json", ...)`) fetches an artifact and agent mode patches the jar of that artifact in the Maven local repository: - `maven::an_agent_patch_beside_a_pinned_hub`, on real Bazel: the checkout has a `pom.xml` that declares the artifact, and the jar is in the Maven local repository as a Maven build leaves it. `scan --mode agent --yes` exits 0, puts the patch service's jar in its place and writes nothing into the checkout but `.socket/`; `apply` passes and warns `maven_bazel_hub_unpatched`. `bazel build` and `bazel run //:consumer` print the upstream marker before the command and after it: the hub fetches the jar its lock pins, at the lock's sha256, and no build reads the Maven local repository. - `maven::an_installed_jar_is_attested_beside_a_hub_that_fetches_its_own`, without Bazel: the same step in a checkout whose lock is written by the test, in the format rules_jvm_external 7.2 writes. In both, `scan --mode agent --vex`, `apply --vex`, `vex` and `vex --no-verify` each write an OpenVEX document whose one statement says the artifact is `not_affected`, "Patched via Socket patch ". That document is false for what Bazel builds. The tests assert it as it is today and mark it KNOWN GAP, with what a fix changes. What the tests share is in the Maven module: step 0 of a flow is split into the layout of the checkout and the ruleset's pin, so that a checkout no Bazel builds in can have the same stand-in, grants and local repository; `Pinned::patches_the_installed_jar` runs the agent step. `Cell::patches_outside` of the harness compares the installed file as bytes, since a jar is no text; the Cargo and NuGet flows call it as before. The real-Bazel flow passes on Bazel 9.3.2 and 7.7.2 (macOS arm64) with no change to the product, in about 20 s each. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_bazel_build/harness.rs | 9 +- .../tests/e2e_bazel_build/maven.rs | 228 ++++++++++++++---- 2 files changed, 189 insertions(+), 48 deletions(-) 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 f8f76acce..666062854 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -1452,7 +1452,7 @@ impl Cell { /// 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 + /// file of that copy: `scan --mode agent --yes` gives the file the bytes /// `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 @@ -1462,7 +1462,7 @@ impl Cell { &self, run: impl Fn(&Cell, &[&str]) -> Ran, installed: &Path, - patched: &str, + patched: impl AsRef<[u8]>, claim: &Claim, ) -> Tree { let test = &self.test; @@ -1478,8 +1478,9 @@ impl Cell { 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 holds = std::fs::read(installed).unwrap_or_default(); + let (at, shown) = (installed.display(), String::from_utf8_lossy(&holds)); + assert!(holds == patched.as_ref(), "{test}: {at} holds:\n{shown}"); let again = self.document("apply"); let apply = run(self, &[&["apply"][..], &with_vex(&again)].concat()); diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs index c1ab67684..727c6b89e 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs @@ -71,6 +71,12 @@ //! hosted command then takes the vendored entry, its directory and its //! ledger entry out again, and the checkout is the one the first hosted //! command left; `rollback` undoes a vendored patch to the byte. +//! - [`an_agent_patch_beside_a_pinned_hub`]: agent mode in a checkout that +//! Maven builds too. `scan --mode agent --yes` puts the patched jar in +//! the Maven local repository and patches no hub: the build prints the +//! upstream marker before and after. The document of the run, of +//! `apply`, of `vex` and of `vex --no-verify` says that the artifact is +//! not affected, which is false for what Bazel builds (KNOWN GAP). //! //! A command that writes the block gives no warning. One that does not //! gives one, in the place of "no pom.xml", with the reason and the words @@ -127,9 +133,10 @@ use sha2::{Digest, Sha256, Sha512}; use socket_patch_core::bazel::maven::{Lock, Pinned as Jar}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes as git_sha256; -use crate::envelope::{event_for, event_triples}; +use crate::envelope::{codes_in, event_for, event_triples}; use crate::harness::{ - changed, rewrite, Cell, Claim, Fixture, How, Ran, StandIn, Tree, CONSUMER, NOTHING, + cell_without_bazel, changed, fixture_path, rewrite, Cell, Claim, Fixture, How, Ran, StandIn, + Tree, CONSUMER, NOTHING, }; use crate::hosted_memory_common::{Patch, ORG}; @@ -431,15 +438,68 @@ struct Pinned { } impl Pinned { - /// Step 0 of every flow: the fixture's checkout for `test`, with a + /// Step 0 of every flow: the fixture's checkout for `test` + /// ([`Pinned::laid_out`]), pinned by the ruleset against its stand-in. + /// `None` when no Bazel runs here. + fn open(test: &str, maven: bool, prepare: &dyn Fn(&Cell, &mut String)) -> Option { + let flow = Pinned::laid_out(Cell::open(test, &FIXTURE)?, maven, prepare); + let (cell, repository) = (&flow.cell, flow.repository()); + + // The ruleset's own relock. The lock it writes holds the victim, + // which `MODULE.bazel` does not name, at the sha256 of this run's + // jar, in the format of the era. + let pin = cell.bazel_env("run", &[&format!("@{HUB}//:pin")], &[("REPIN", "1")]); + assert!(pin.ok(), "{test}: {}", pin.dump()); + let lock = std::fs::read_to_string(cell.path("maven_install.json")).expect("the lock"); + let raw: Value = serde_json::from_str(&lock).expect("the lock is JSON"); + // Nothing else is in it: no other Bazel module added to the hub, + // and its one repository is the stand-in. + let keys = |of: &str| { + let map = raw[of].as_object().expect("a map of the lock"); + map.keys().map(String::as_str).collect::>().join(" ") + }; + assert_eq!( + (keys("artifacts"), keys("repositories")), + ( + format!("{GROUP}:consumer {GROUP}:{VICTIM}"), + format!("{repository}/") + ), + "{test}: {raw:#}" + ); + let lock = Lock::parse(&lock).unwrap_or_else(|why| panic!("{test}: {why}:\n{lock}")); + let format = if cell.numbers() >= (9, 0, 0) { 3 } else { 2 }; + let jar = Jar { + version: VERSION.to_string(), + jar_sha256: Some(sha256_hex(&flow.upstream_jar())), + fetched: true, + }; + assert_eq!( + (lock.format, lock.plain_jar(GROUP, VICTIM)), + (format, Some(&jar)), + "{test}: {lock:?}" + ); + Some(flow) + } + + /// The repository of the hub: the stand-in's. + fn repository(&self) -> String { + format!("{}/{UPSTREAM}", self.standin.origin()) + } + + /// The upstream jar of the victim that the stand-in serves. + fn upstream_jar(&self) -> Vec { + victim(&format!("PRISTINE {}", self.run)) + } + + /// The checkout `cell` of the fixture before its hub is pinned, with a /// `pom.xml` that declares the victim when `maven` is set and with /// what `prepare` adds to its files and to the text of `MODULE.bazel`, - /// pinned by the ruleset against a stand-in that has the two - /// artifacts, the patched jar and the grant of its patch. `None` when - /// no Bazel runs here. - fn open(test: &str, maven: bool, prepare: &dyn Fn(&Cell, &mut String)) -> Option { + /// against a stand-in that has the two artifacts, the patched jar and + /// the grant of its patch. The lock is the empty file the ruleset's + /// documentation starts from. + fn laid_out(mut cell: Cell, maven: bool, prepare: &dyn Fn(&Cell, &mut String)) -> Pinned { let started = Instant::now(); - let mut cell = Cell::open(test, &FIXTURE)?; + let test = cell.test.clone(); // The cache of the Coursier that pins. Before 7.2 the ruleset // leaves the choice to Coursier, which without this takes the home // directory from the system, whatever `HOME` says. @@ -493,41 +553,8 @@ impl Pinned { std::fs::write(&file, bytes).expect("write the local repository"); } - // The ruleset's own relock. The lock it writes holds the victim, - // which `MODULE.bazel` does not name, at the sha256 of this run's - // jar, in the format of the era. - let pin = cell.bazel_env("run", &[&format!("@{HUB}//:pin")], &[("REPIN", "1")]); - assert!(pin.ok(), "{test}: {}", pin.dump()); - let lock = std::fs::read_to_string(cell.path("maven_install.json")).expect("the lock"); - let raw: Value = serde_json::from_str(&lock).expect("the lock is JSON"); - // Nothing else is in it: no other Bazel module added to the hub, - // and its one repository is the stand-in. - let keys = |of: &str| { - let map = raw[of].as_object().expect("a map of the lock"); - map.keys().map(String::as_str).collect::>().join(" ") - }; - assert_eq!( - (keys("artifacts"), keys("repositories")), - ( - format!("{GROUP}:consumer {GROUP}:{VICTIM}"), - format!("{repository}/") - ), - "{test}: {raw:#}" - ); - let lock = Lock::parse(&lock).unwrap_or_else(|why| panic!("{test}: {why}:\n{lock}")); - let format = if cell.numbers() >= (9, 0, 0) { 3 } else { 2 }; - let jar = Jar { - version: VERSION.to_string(), - jar_sha256: Some(sha256_hex(&upstream_jar)), - fetched: true, - }; - assert_eq!( - (lock.format, lock.plain_jar(GROUP, VICTIM)), - (format, Some(&jar)), - "{test}: {lock:?}" - ); let upstream = format!("OUT: PRISTINE {run}"); - Some(Pinned { + Pinned { cell, standin, tools, @@ -537,7 +564,7 @@ impl Pinned { upstream, upstream_route: format!("/{UPSTREAM}/{}", repo_path(VICTIM, VERSION, "jar")), started, - }) + } } /// Step 1: the build prints the upstream marker, from a jar Bazel @@ -574,8 +601,18 @@ impl Pinned { /// the patched jar from the URL the grant has for it on the patch host: /// that host is the stand-in here. fn vendored(&self, args: &[&str]) -> Ran { + self.serviced(&self.cell, args) + } + + /// [`Pinned::vendored`] in the checkout `cell`. Agent mode takes the + /// patched jar from that URL as well. + fn serviced(&self, cell: &Cell, args: &[&str]) -> Ran { let origin = self.standin.origin(); - self.socket_patch(&[args, &["--patch-server-url", &origin]].concat()) + self.socket_patch_in( + cell, + &self.standin, + &[args, &["--patch-server-url", &origin]].concat(), + ) } /// The command where it writes no entry for the hub, in a tree without @@ -1352,6 +1389,109 @@ fn the_users_own_override_of_the_artifact() { ); } +/// The warning of an agent run for an artifact that a pinned hub fetches: +/// the command patches no hub. +const HUB_UNPATCHED: &str = "maven_bazel_hub_unpatched"; + +impl Pinned { + /// Without a Bazel: the checkout of [`Pinned::open`] beside a `pom.xml`, + /// in a workspace copy that no Bazel has built in. No ruleset pins it, + /// so the lock is written here: the two artifacts under the stand-in's + /// repository, in the format the ruleset of Bazel 9.3.2 writes. + fn unbuilt() -> Pinned { + let cell = cell_without_bazel("9.3.2"); + let module = fixture_path(FIXTURE.dir).join("e9").join(MODULE); + cell.write(MODULE, std::fs::read(module).expect(MODULE)); + cell.write(".git/HEAD", "ref: refs/heads/main\n"); + let flow = Pinned::laid_out(cell, true, &|_, _| {}); + let sums = |jar: &[u8]| json!({ "jar": sha256_hex(jar) }); + let keys = [format!("{GROUP}:consumer"), format!("{GROUP}:{VICTIM}")]; + let lock = json!({ + "artifacts": { + &keys[0]: { "shasums": sums(&jar(&[])), "version": "2.0" }, + &keys[1]: { "shasums": sums(&flow.upstream_jar()), "version": VERSION }, + }, + "repositories": { format!("{}/", flow.repository()): keys }, + "version": "3", + }); + flow.cell.write("maven_install.json", format!("{lock:#}\n")); + flow + } + + /// Agent mode in the checkout ([`Cell::patches_outside`]). The victim's + /// jar is in the Maven local repository, as a Maven build of the + /// checkout's `pom.xml` leaves it: `scan --mode agent --yes` puts the + /// jar of the patch service in its place and writes nothing into the + /// checkout but its `.socket` directory, and each of the four + /// documents says `claim`. A later `apply` warns that it patches no hub + /// ([`HUB_UNPATCHED`]). Gives the files of the checkout. + fn patches_the_installed_jar(&self, claim: &Claim) -> Tree { + let test = &self.cell.test; + let installed = self.tools.path().join("m2"); + let installed = installed.join(repo_path(VICTIM, VERSION, "jar")); + let patched = victim(&format!("PATCHED {}", self.patch.uuid)); + let run = |cell: &Cell, args: &[&str]| self.serviced(cell, args); + let left = self.cell.patches_outside(run, &installed, &patched, claim); + let apply = self.serviced(&self.cell, &["apply"]); + let warned = codes_in(&apply.envelope["warnings"]); + assert_eq!(warned, [HUB_UNPATCHED], "{test}: {}", apply.dump); + left + } +} + +/// Agent mode beside a pinned hub that fetches the artifact. +/// +/// - (a) `bazel build` and `bazel run //:consumer` print the upstream +/// marker. +/// - (b) `scan --mode agent --yes` patches the jar in the Maven local +/// repository and warns that it patches no hub, and `apply` passes +/// ([`Pinned::patches_the_installed_jar`]). Both, `vex` and +/// `vex --no-verify` exit 0 and write a document that says the artifact +/// is not affected, through the patch. +/// - (c) The same two Bazel commands print the upstream marker again and +/// change no file: the hub fetches the jar its lock pins, at the lock's +/// sha256, and no build reads the Maven local repository. +/// +/// KNOWN GAP: the documents of (b) are false for what Bazel builds. A fix +/// makes each say that the artifact is affected, with what Bazel builds it +/// from and the command that patches the hub. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn an_agent_patch_beside_a_pinned_hub() { + let test = "maven::an_agent_patch_beside_a_pinned_hub"; + let Some(flow) = Pinned::open(test, true, &|_, _| {}) else { + return; + }; + // (a) The upstream build, with the jar from the stand-in. + flow.builds_upstream(); + + // (b) Agent mode patches the installed jar. KNOWN GAP: every document + // says not affected. + let claim = Claim::new(PURL, &flow.patch.uuid, How::Agent); + let patched = flow.patches_the_installed_jar(&claim); + + // (c) The build is the one of (a): Bazel never reads the patched jar. + flow.cell.builds(&flow.upstream); + assert_eq!(changed(&patched, &flow.cell.tree()), NOTHING, "{test}"); + println!( + "{test}: Bazel {} built {:?} before and after `scan --mode agent` patched {VICTIM}-\ + {VERSION}.jar in the Maven local repository; every form of `vex` said the artifact is \ + not affected (KNOWN GAP); {:?}", + flow.cell.release(), + flow.upstream, + flow.started.elapsed() + ); +} + +/// Without a Bazel: step (b) of [`an_agent_patch_beside_a_pinned_hub`] in a +/// checkout whose hub is pinned ([`Pinned::unbuilt`]). KNOWN GAP, as there. +#[test] +fn an_installed_jar_is_attested_beside_a_hub_that_fetches_its_own() { + let flow = Pinned::unbuilt(); + let claim = Claim::new(PURL, &flow.patch.uuid, How::Agent); + flow.patches_the_installed_jar(&claim); +} + /// Without a Bazel: the fixture's directories and the legs of its workflow /// are those of the table, each era's `MODULE.bazel` has a hub of its own /// name with the one repository a flow replaces, and a jar made here holds From 7e630622711c401a0e25af2e4de388ab8178020b Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 02:52:32 -0500 Subject: [PATCH 13/19] Attest a Maven patch as affected in VEX where a pinned Bazel hub fetches the jar from its lock Agent mode patches the jar of a Maven artifact where a build tool installed it (the Maven local repository, a Gradle or Coursier cache). In a Bazel workspace a pinned rules_jvm_external hub does not build that jar: it takes the one its lock (`maven_install.json`) pins, at the lock's sha256. `apply` already warns of it (`maven_bazel_hub_unpatched`). The tests of the commit before this one measured the rest on Bazel 9.3.2 and 7.7.2: `bazel build` prints the upstream marker before and after `scan --mode agent`, and `scan --vex`, `apply --vex`, `vex` and `vex --no-verify` each attest the artifact as `not_affected`. That document is false for what Bazel builds. The document now says `affected` of such an artifact, as it does for npm, PyPI, RubyGems, Cargo and NuGet: one statement of the package's own, whose action statement names the lock of the hub, the `maven.install` with its file and line, and the command that patches a pinned hub, `socket-patch get --mode hosted` at the Bazel root, or with `--mode vendored`. It ends with the `--no-bazel` sentence. The warning is `vex_bazel_not_in_build`, `vex --json` reports a `skipped` event with `details.status: "affected"`, the envelope is `partialFailure`, the exit code is 0, and `--no-bazel`, `--vex-no-bazel` and `SOCKET_VEX_NO_BAZEL` leave Bazel out of the document, all through the code those ecosystems already run. The command comes with a condition, in brackets: "a `maven_bazel_*` warning of that run means that the Bazel build keeps the upstream jar". Hosted and vendored mode write no entry for a hub where they cannot show from the checkout that one works (Bazel before 7.4.0, an unknown release of the ruleset, an rc file, a jar the lock lists under no repository, an isolated `use_extension`). The command then exits 0 with such a warning, and beside a `pom.xml` it has still pinned or vendored the patch for the Maven build, which `vex` attests as `not_affected`. That statement is wrong for the Bazel build. It is the one hosted mode leaves there without an agent patch before it, so it is not new; it is in the docs' list of where the document is still wrong, and the action statement must not send a reader there without a word. Where the answer comes from. The table of hubs in `bazel/built.rs` decides by the project's own lock: where it lies from the project, what it lists, and whether its text names the patch. None of that fits a Maven hub. Its lock is no project's own and never names a patch (the patch of a hub is an entry of the block in the root `MODULE.bazel`), and whether a hub fetches a jar takes what `bazel/maven.rs` already reads for hosted and vendored mode: the tags that make a hub of one name, the lock in format 2 or 3 with its skipped and local artifacts, a `maven.override`, a `maven_install` of a `WORKSPACE` file, the block. A second reader could disagree with that one. So `built::unbuilt` asks `maven::upstream`, new, which reads the hubs once with `Hubs::read` and says for each jar what `Hubs::sure` and the block say: - a pinned hub fetches the plain jar at that version, every hub of the workspace was read, and the block holds no entry for the jar: the hub, for a statement that says `affected`; - anything else: nothing, and the statement stays the one of a project without Bazel. That is a jar no hub fetches, a jar the block patches, and every case in which something was not read: a hub without a `lock_file`, a tag or a lock that cannot be read, a `maven.override` of the artifact, a `maven_install` of a `WORKSPACE` file that Bazel may read, a block that was changed by hand. `Hubs::sure`, not `Hubs::built`, because a block that was changed by hand may still patch the jar, and its entries are not read. So `apply` can warn `maven_bazel_hub_unpatched` (it asks `Hubs::built`) where the document keeps `not_affected`: beside a hub that was not read. The docs say so. The warning and the statement share the check of the block (`Hubs::patches`). Two things follow from taking that reader, and the docs say both: - A `WORKSPACE` file. For the hubs of the table any such file that defines a repository leaves the statement as without Bazel. The Maven reader takes one for a doubt only when it calls `maven_install` or cannot be read, and only while the checkout names no Bazel 9 or later, which is the rule hosted mode writes its entries by. So beside a `WORKSPACE` file that defines other repositories a Maven jar is `affected`. - `m2local`. A lock with it takes a jar that no repository lists from the Maven local repository, at the lock's sha256. Such a jar counts as fetched, and its statement says `affected`: the patched jar does not have that sha256 (read from the ruleset's source at 7.2 and 6.5, not built here). The lock's sha256 is not compared with the patch. `Unbuilt::remedy` is a `String` now, since the Maven command names the package. A hosted or vendored entry of the block keeps its statement: the caller hands over no hosted pin, and a committed copy is not asked about. Nothing is read without a Maven jar among the patched packages, and nothing outside a Bazel workspace. Tests. Unit tests of `maven::upstream` (each case above; another version, a classifier and another packaging of the jar; a block's entry for another version of the artifact; a `WORKSPACE` file without `maven_install`; a jar under `m2local`) and of `built::unbuilt` on disk (the sentence, a project below the Bazel root, a committed copy, the block's entry). The two tests of the commit before now expect `affected` with the action statement. Without Bazel, each of the two modes the statement names is run after agent mode in a checkout of its own: where the command writes its entry it gives no `maven_bazel_*` warning and `vex` then says `not_affected`; in a checkout that names Bazel 7.3.0 it writes none and warns `maven_bazel_release`, and the `not_affected` that `vex` then writes is held as the known limit it is. A second test holds `vex`, with `--no-bazel` and beside four hubs of which nothing is said, to what it gives in the same checkout without `MODULE.bazel` (exit code, both streams, the document), and `apply --vex` to the line a person reads. On real Bazel the flow goes on after the documents: the hosted command pins the Maven build and the hub, the same build prints the marker of the patched jar, and `vex` says `not_affected`. Docs: the Maven cell of "Bazel workspaces: what is supported", the agent paragraph and the last limit of "Bazel workspaces: Maven", the section "Bazel workspaces: VEX" (the table of calls, the kinds of patch, the action statement and its condition, what changes nothing, what is tested, what is still wrong) and the rows `vex_bazel_not_in_build` and `maven_bazel_hub_unpatched` of the CLI contract. Two things that held before are now said. `--vex-no-bazel` is about the document, and what `scan`, `apply` and `vendor` themselves say in a Bazel workspace stays, such as `maven_bazel_hub_unpatched`: a sentence of the docs and of the contract's paragraph on the installed tree is narrowed to that. And a patch is judged only where the run found it in place, so `vex` on a machine whose installed jar is not the patched one ends as it does without Bazel. The Maven workflow names the agent flow and starts its legs on a change to the VEX code and to the two files agent mode patches a jar with. The size budget of `bazel/` follows the code (4006 to 4051 lines). Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-maven.yml | 20 +- crates/socket-patch-cli/CLI_CONTRACT.md | 6 +- crates/socket-patch-cli/src/commands/vex.rs | 13 +- .../tests/e2e_bazel_build/maven.rs | 187 +++++++++++++++--- crates/socket-patch-core/src/bazel/built.rs | 100 +++++++++- crates/socket-patch-core/src/bazel/maven.rs | 106 +++++++++- docs/ecosystems.md | 122 ++++++++++-- scripts/loc-budget.json | 2 +- 8 files changed, 494 insertions(+), 62 deletions(-) diff --git a/.github/workflows/bazel-maven.yml b/.github/workflows/bazel-maven.yml index c28b174c8..e0cef8460 100644 --- a/.github/workflows/bazel-maven.yml +++ b/.github/workflows/bazel-maven.yml @@ -12,7 +12,11 @@ name: Bazel patch compatibility (Maven) # mode that repository is a directory of the checkout with the committed # jar: the flows hold the build from the checkout alone with no host to # ask, the audit of the committed jar, the undo, and the way from hosted -# to vendored and back. bazel-compatibility.yml holds the legs and what +# to vendored and back. Agent mode patches the jar in the Maven local +# repository and no hub: its flow holds the build to the upstream jar, +# every VEX document to `affected` with the command that patches the hub, +# and after that command the build and the document to the patched jar. +# bazel-compatibility.yml holds the legs and what # every ecosystem # shares; this file says when the Maven legs run and on which releases. # @@ -70,7 +74,11 @@ on: # hubs of MODULE.bazel, their locks and the block). Nothing another # ecosystem's flow owns is here but that dispatch, which the Composer # legs watch too, so a change to one ecosystem starts that ecosystem's - # legs only. + # legs only. Last, what the agent flow runs through: the two files + # with which agent mode patches a jar, and the VEX code (`vex/` of the + # core, the files of the `vex` command). That 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. # # What it does not cover: shared engine code (`rewrite_maven_pom` is in # patch/redirect/mod.rs, the file of every ecosystem's rewriter; hosted/, @@ -99,6 +107,10 @@ on: - 'crates/socket-patch-core/src/vendor/maven_repo.rs' - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' + - 'crates/socket-patch-core/src/patch/jvm_jar.rs' + - 'crates/socket-patch-core/src/patch/jar_members.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 @@ -127,6 +139,10 @@ on: - 'crates/socket-patch-core/src/vendor/maven_repo.rs' - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' + - 'crates/socket-patch-core/src/patch/jvm_jar.rs' + - 'crates/socket-patch-core/src/patch/jar_members.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/**' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 346a92ba3..f38e2fcb0 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -746,7 +746,7 @@ Every VEX statement's impact string records which patch-application mode persist **Unverified statements (`--no-verify`).** `--no-verify` / `--vex-no-verify` (and an ambient `SOCKET_VEX_NO_VERIFY`) skip every on-disk hash check, so a statement emitted under it rests on the patch records and the wiring gates alone — for an agent-mode patch on nothing but the manifest, even when the installed files are unpatched or absent. Such a run is never silent. Each purl it attests ends its impact-statement part with `; not verified on disk`, appended AFTER the marker, so the three marker strings above stay intact as prefixes (`Patched via Socket patch (vendored); not verified on disk`), and the run raises the `vex_not_verified` warning (stderr in human mode, `warnings[]` / `vex.warnings` under `--json`) naming how many statements carry the suffix. The purls an in-run `scan --mode hosted --vex` confirmed are attested from that run's own evidence in either mode and never carry it. A default (verifying) run's document is unchanged: it never contains the suffix. -**The installed tree (`--no-bazel`).** `--no-bazel` / `--vex-no-bazel` (and an ambient `SOCKET_VEX_NO_BAZEL`, read like `SOCKET_VEX_NO_VERIFY`: `1` or `true` sets it, an empty value does not) say that the document describes what the package manager installed, for a repository that ships that tree while a Bazel hub reads the same lock for something else, such as its tests. The Bazel workspace is then not read: no package is attested as `affected` for `vex_bazel_not_in_build`, and the document, the events, the warnings, the exit code and every printed line are those of the same checkout without its Bazel files. Without the option nothing changes, and outside a Bazel workspace the option changes nothing and is accepted silently. `--vex-no-bazel` is inert unless `--vex` is set. +**The installed tree (`--no-bazel`).** `--no-bazel` / `--vex-no-bazel` (and an ambient `SOCKET_VEX_NO_BAZEL`, read like `SOCKET_VEX_NO_VERIFY`: `1` or `true` sets it, an empty value does not) say that the document describes what the package manager installed, for a repository that ships that tree while a Bazel hub reads the same lock for something else, such as its tests. The Bazel workspace is then not read for the document: no package is attested as `affected` for `vex_bazel_not_in_build`, and the document, the events and warnings about it, the exit code and every line `vex` prints are those of the same checkout without its Bazel files. The option is about the document alone: what the host command itself does and says in a Bazel workspace stays (`apply` and an agent `scan` beside a pinned rules_jvm_external hub still warn `maven_bazel_hub_unpatched`). Without the option nothing changes, and outside a Bazel workspace the option changes nothing and is accepted silently. `--vex-no-bazel` is inert unless `--vex` is set. **Identifier overrides.** `--product` / `--vex-product` and `--doc-id` / `--vex-doc-id` are emitted with surrounding whitespace trimmed (a blank value means unset). @@ -2712,7 +2712,7 @@ command's integration tests check its output. | `vendor_prebuilt_stub_invalid` | `failed` | RubyGems: the server stub lacks required attributes or is otherwise invalid; no local stub fallback is permitted. | | `bazelignore_not_updated` | run-level `warnings[]` | Go vendored and agent mode, Cargo vendored mode under a rules_rust crate hub, and Maven vendored mode, in a Bazel workspace (additive): the `.bazelignore` at the Bazel root, which keeps Bazel and gazelle out of the module copies under `.socket/vendor/golang` and `.socket/go-patches` out of the crates under `.socket/vendor/cargo`, and out of the jars vendored for a rules_jvm_external hub under `.socket/vendor/maven`, was not updated. It could not be read or written (a symbolic link or a directory in its place, a read-only directory, a read-only file). The detail names the line to add, or says that the lines of a copy that is gone can be deleted; the command's patch or undo stands and its exit code is unchanged. See docs/ecosystems.md "Bazel workspaces: `.bazelignore`". | | `redirect_cargo_bazel_config_unread` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_rust crate_universe hub (`crate.from_cargo` in `MODULE.bazel` or a file it includes, or `crates_repository` in the `WORKSPACE` file) reads the project's `Cargo.lock` or one of its `Cargo.toml` files, or may read them (its `cargo_lockfile` or `manifests` is not written out as strings, or a use of the extension may hide a call), and its `cargo_config` is not one string that is the label of the cargo config hosted mode writes (`.cargo/config.toml`, or the project's `.cargo/config`). cargo-bazel runs cargo with the config its hub names and no other, so the registry of a pin would be unknown to it and `bazel build` would fail (`registry index was not found in any configuration`). The crate is not pinned: nothing is written for it, its event is `skipped` / `redirect_unconfirmed` (a vendored crate that the scan would take over stays vendored: `skipped` with this code, and `redirect_takeover_kept_vendored`), and status and exit code are unchanged. One warning per crate; the detail names the hub's file and line, the config to commit (created with a comment line in it where the project has none), the attribute to give the hub (`cargo_config = "//:.cargo/config.toml"`; the label is written in the package of the hub's own labels), after which the same command pins the crate, and `--mode vendored`. A hub that names that config is still in the way while the file is there and holds nothing: `rollback` deletes a cargo config it leaves empty, and the hub fails on the missing file; the detail asks for a comment line in it. For a use of the extension that may hide a call the detail names that line to rewrite and no attribute: the next run pins the crate or names the hub that is in the way. A `WORKSPACE` call (`crates_repository`, also under the name a `load` of that file gives it) counts only when no hub of the module files reads the project's Cargo files and the checkout names no Bazel 9 or later. The rewriter's own refusals answer first and keep their codes. A pin that is in place already stays `applied`, and no warning is given for it. Nothing is read or changed in no Bazel workspace, or where no such hub is seen to read the project's Cargo files. See docs/ecosystems.md "Bazel workspaces: Cargo". | -| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace, agent and vendored mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch of this run, and the block that hosted and vendored mode keep in `MODULE.bazel` holds no entry for that jar after it. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build. Agent mode (`apply`, and `get` / `scan` in that mode; only for a package it found installed; never under `--global`) patches no hub: one warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub; the events, the exit code and every written file are those of the same run without the workspace. Vendored mode (`vendor`, and `get` / `scan` in that mode) patches a pinned hub (below), and gives this code only for a jar it could have written an entry for and vendored nothing for, because the package failed or was skipped for another reason (never in a dry run); a jar it cannot write an entry for gets the `maven_bazel_*` code of the reason instead. A `vendor` whose `--ecosystems` leaves Maven out gives none. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace, agent and vendored mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch of this run, and the block that hosted and vendored mode keep in `MODULE.bazel` holds no entry for that jar after it. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build. Agent mode (`apply`, and `get` / `scan` in that mode; only for a package it found installed; never under `--global`) patches no hub: one warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub; the events, the exit code and every written file are those of the same run without the workspace. A VEX document says `affected` of such a jar when every hub was read (`vex_bazel_not_in_build`). Vendored mode (`vendor`, and `get` / `scan` in that mode) patches a pinned hub (below), and gives this code only for a jar it could have written an entry for and vendored nothing for, because the package failed or was skipped for another reason (never in a dry run); a jar it cannot write an entry for gets the `maven_bazel_*` code of the reason instead. A `vendor` whose `--ecosystems` leaves Maven out gives none. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | | `maven_bazel_unreadable` | agent: run-level `warnings[]` (human: `Warning: …`); scan/get `--mode hosted`: `warnings[]` (warning); vendored: as `maven_bazel_not_at_root` | Maven in a Bazel workspace (additive): whether a rules_jvm_external hub builds the jar of a Maven patch could not be told, because something could not be read with certainty: a hub without `lock_file` in agent mode (hosted and vendored mode give `maven_bazel_not_pinned`), a `maven.artifact` or `maven.from_toml` tag that cannot be read, a lock that is missing, empty, not format 2 or 3, larger than 16 MiB (or past the 64 MiB of locks that are read for one workspace) or no JSON, a `WORKSPACE` file that calls `maven_install` or cannot be read while `.bazeliskrc` or `.bazelversion` at the Bazel root names no release of Bazel 9 or later, a `maven.install` whose `name` or `lock_file` is not a plain string, a construct of `MODULE.bazel` the reader does not follow, and, in agent mode, a `maven.override` of the artifact (hosted and vendored mode give `maven_bazel_no_effect`). Hosted and vendored mode also give it for a hub on an isolated `use_extension`, an rc file that cannot be read (also one that an import takes from outside the workspace by a relative path, and one with a line whose reading Bazel's own source calls an oversight: a quote that is never closed, a `\` with nothing after it), a `MODULE.bazel` that is a symbolic link, and a block of `MODULE.bazel` that was changed by hand (also in its first line alone), and then writes no entry for the hub. One warning per purl; the detail names the file, the line and the reason. | | `maven_bazel_hub_not_read` | scan run-level `warnings[]` (human: `Warning: …`); `get --mode hosted`: `warnings[]` | scan `--mode hosted` at the root of a Bazel workspace, with Maven in scope (additive): the scan takes the jars that the pinned rules_jvm_external hubs fetch for packages of the project (the lockfile supplement above), and something of the hubs could not be read with certainty, so it does not know every Maven artifact that Bazel builds through a hub. Given once per run, for the first thing that was not read, whatever the packages: a hub without `lock_file` (the detail then ends with how to pin it), or one of the reasons of `maven_bazel_unreadable` that concern reading the hubs (a tag or a lock that cannot be read, a `maven_install` of a `WORKSPACE` file that Bazel may read, a construct of `MODULE.bazel` the reader does not follow, a block that was changed by hand). `[:]: , so socket-patch does not know every Maven artifact that Bazel builds here through a rules_jvm_external hub: it looks for patches of the ones in the hub locks it read, and of no other`. No jar is guessed for what was not read; the jars of the hubs that were read are scanned, and a patch found for one of them gets no entry while the doubt stands (`maven_bazel_not_pinned` / `maven_bazel_unreadable` below). With no package at all a person reads `No packages found (see the warning).`. Exit code and `status` unchanged. A hosted `get` by advisory, which keeps the releases the project has by the same supplement, gives it too when the advisory has a patch of a Maven artifact. Only in a workspace that has to do with the ruleset: a call in `MODULE.bazel` or a file it includes names `rules_jvm_external`, the `WORKSPACE` file calls `maven_install`, or a `maven_install.json` lies at the Bazel root. In another Bazel workspace a file that cannot be read gives no such warning, and the run is the one without the workspace. | | `maven_bazel_not_at_root` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_jvm_external hub builds the jar of a Maven patch, and the project is below the root of its Bazel workspace, in whose `MODULE.bazel` the patch of a hub is written. Like the five codes below and `maven_bazel_unreadable` in hosted mode, it means that the run wrote no entry for the jar in the block of the root `MODULE.bazel`, because it could not show from the checkout that the entry works. One warning per purl, in the place of `redirect_maven_no_pom` for that purl; the detail says why and ends with what the block of the root holds for the jar, which is read for a project below the root too (the detail then names the file as "the MODULE.bazel at the root"). Nothing: "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps the upstream jar". The event is the one of the same run without the hub: `skipped` / `redirect_unconfirmed` in a tree only Bazel builds, `applied` beside a `pom.xml` or Gradle pin that landed. The entry of the patch, from an earlier run: that entry stays, the event is `applied`, and the detail ends "socket-patch left the entry that MODULE.bazel holds for it as it is". The entry of another patch of the same jar: it stays too, the event is the one without the hub, and the detail ends "socket-patch wrote nothing to MODULE.bazel for it: the entry of patch remains there, and where the block is in effect the Bazel build takes that patch's jar". Exit code unchanged. With none of these codes the run writes the block: `redirect.rewrittenFiles` holds `MODULE.bazel`, the event is `applied`, and `rollback` / `remove` take the entry out. **Vendored mode** (`vendor`, and `scan` / `get --mode vendored`; additive) gives the same codes, but for `maven_bazel_download`, with the same detail, for a jar whose entry it does not write. In a project with no Maven, Gradle, sbt or scala-cli build the hub is the patch's only target: the event is `failed` with the code as its `errorCode` and the detail, without the purl in front, as its `error`, nothing is written and the run exits 1, as for any vendored refusal (before, such a project failed with `vendor_jvm_shape_unsupported`, which a jar that no hub builds still does). Beside such a build that was vendored, the code is a run-level `warnings[]` entry (human: `Warning: …`), the event is `applied` and the exit code is unchanged. With none of these codes vendored mode commits the patched jar under `.socket/vendor/maven//` (`REPO.bazel`, `file/BUILD.bazel`, `file/-.jar`, `.gitignore`), writes the entry that names that directory into the block, in the place of a hosted entry for the same jar, adds the directory's line to `.bazelignore`, and records the patch in the vendor ledger (in a project with no other JVM build: `ecosystem` `maven`, `flavor` `bazel`, the committed jar as `artifact`, no `wiring`); the event is `applied`. `vendor --check` then also fails (`vendor_check_failed`) when that jar is not, byte for byte, the vendored jar the ledger records (beside a Maven or Gradle build the hub's jar is a copy of it), when `REPO.bazel` / `file/BUILD.bazel` is not the file that was written, when the block no longer names the directory or was changed by hand, and when no pinned hub takes the jar at that version any more (the reason names `socket-patch rollback `) or an rc file switches the entry off. `vendor --revert` / `rollback` / `remove` take the entry, the directory and the line out, and a hosted run that puts its entry in the place of the vendored one removes the directory and the line. See docs/ecosystems.md "Bazel workspaces: Maven". | @@ -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`, 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_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`, rules_jvm_external `maven.install`), 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 in an installed jar of a Maven artifact while a pinned hub fetches the plain jar of that artifact at that version and the block that hosted and vendored mode keep in the root `MODULE.bazel` holds no entry for it (the lock of a hub is no project's own: the same from every project of the workspace; a jar that the hub takes from the Maven local repository under `m2local` counts as fetched, and the lock's sha256 is not compared with the patch), 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 Maven jar `get --mode hosted` at the Bazel root, or with `--mode vendored`, and that a `maven_bazel_*` warning of that run means that the Bazel build keeps the upstream jar: the command writes no entry for the hub where it cannot show that one works, and the pin it then leaves in a `pom.xml` or a Gradle build is attested as `not_affected`; 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), for a Maven jar when the block holds an entry for it or when any rules_jvm_external hub of the workspace is not read with certainty (a hub without `lock_file`, a `maven.override` of the artifact and the other reasons of `maven_bazel_unreadable` that concern reading the hubs, also where `apply` warns `maven_bazel_hub_unpatched` beside such a hub), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, which for a Maven jar counts only when it calls `maven_install` or cannot be read while the checkout names no Bazel 9 or later, 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 74a908d22..1dae29e2e 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -1909,10 +1909,12 @@ const INSTALLED_TREE_SHIPS: &str = "If what you ship is the installed tree and n builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor)."; /// 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 +/// rules_ruby, rules_rust, rules_csharp or rules_jvm_external builds a +/// package from the lock a workspace file names, never from the copy a +/// package manager installed (a jar of the Maven local repository only at +/// the lock's sha256), 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` @@ -1979,7 +1981,8 @@ async fn unbuilt_by_bazel( /// what `call` builds the package from, and what to run so that the build /// 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. +/// they run in, so it names the directory of the lock, and for a Maven jar +/// the Bazel root, where the patch of a hub is written. /// /// 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 diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs index 727c6b89e..b3fedee4c 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs @@ -74,9 +74,12 @@ //! - [`an_agent_patch_beside_a_pinned_hub`]: agent mode in a checkout that //! Maven builds too. `scan --mode agent --yes` puts the patched jar in //! the Maven local repository and patches no hub: the build prints the -//! upstream marker before and after. The document of the run, of +//! upstream marker before and after, and the document of the run, of //! `apply`, of `vex` and of `vex --no-verify` says that the artifact is -//! not affected, which is false for what Bazel builds (KNOWN GAP). +//! affected, with the lock and the `maven.install` Bazel builds it from +//! and the command that patches the hub. After that command, the hosted +//! one, the build prints the marker of the patched jar and `vex` says +//! not affected. //! //! A command that writes the block gives no warning. One that does not //! gives one, in the place of "no pom.xml", with the reason and the words @@ -123,6 +126,7 @@ //! Java embedded in Bazel. use std::io::Write as _; +use std::path::Path; use std::time::Instant; use base64::Engine as _; @@ -135,8 +139,8 @@ use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes as git_sh use crate::envelope::{codes_in, event_for, event_triples}; use crate::harness::{ - cell_without_bazel, changed, fixture_path, rewrite, Cell, Claim, Fixture, How, 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::{Patch, ORG}; @@ -587,16 +591,22 @@ impl Pinned { /// `standin`, with the directories of [`Pinned::tools`] in the place of /// the machine's. fn socket_patch_in(&self, cell: &Cell, standin: &StandIn, args: &[&str]) -> Ran { - let dir = |name: &str| self.tools.path().join(name).to_string_lossy().into_owned(); - let (m2, gradle, coursier) = (dir("m2"), dir("gradle"), dir("coursier")); - let env = [ - ("MAVEN_REPO_LOCAL", m2.as_str()), - ("GRADLE_USER_HOME", &gradle), - ("COURSIER_CACHE", &coursier), - ]; + let tools = self.tools_env(); + let env = tools.each_ref().map(|(name, dir)| (*name, dir.as_str())); cell.socket_patch(&standin.origin(), args, &env) } + /// The directories of [`Pinned::tools`], each as the variable that + /// puts it in the place of the machine's. + fn tools_env(&self) -> [(&'static str, String); 3] { + let dir = |name: &str| self.tools.path().join(name).to_string_lossy().into_owned(); + [ + ("MAVEN_REPO_LOCAL", dir("m2")), + ("GRADLE_USER_HOME", dir("gradle")), + ("COURSIER_CACHE", dir("coursier")), + ] + } + /// `socket-patch ` for a command of vendored mode, which downloads /// the patched jar from the URL the grant has for it on the patch host: /// that host is the stand-in here. @@ -1397,7 +1407,10 @@ impl Pinned { /// Without a Bazel: the checkout of [`Pinned::open`] beside a `pom.xml`, /// in a workspace copy that no Bazel has built in. No ruleset pins it, /// so the lock is written here: the two artifacts under the stand-in's - /// repository, in the format the ruleset of Bazel 9.3.2 writes. + /// repository, in the format the ruleset of Bazel 9.3.2 writes. And no + /// Bazel leaves its own lock, so what hosted and vendored mode read + /// before they write an entry is written here too: the Bazel release, + /// and the release of the ruleset that Bazel selected. fn unbuilt() -> Pinned { let cell = cell_without_bazel("9.3.2"); let module = fixture_path(FIXTURE.dir).join("e9").join(MODULE); @@ -1415,9 +1428,34 @@ impl Pinned { "version": "3", }); flow.cell.write("maven_install.json", format!("{lock:#}\n")); + let selected = "https://bcr.bazel.build/modules/rules_jvm_external/7.2/source.json"; + let lock = json!({ "lockFileVersion": 13, "registryFileHashes": { selected: "0" } }); + flow.cell.write("MODULE.bazel.lock", format!("{lock:#}\n")); + flow.cell.write(".bazelversion", "9.3.2\n"); flow } + /// What every document of a patch that is only in the installed jar + /// says, as its action statement and in the warning of its run: the + /// lock of the hub, the call and its line, the command of the two modes + /// that patch a pinned hub with what tells that it wrote no entry, and + /// the option for a repository that ships the installed tree. + fn affected(&self) -> Vec { + let module = std::fs::read_to_string(self.cell.path(MODULE)).expect(MODULE); + let call = module.lines().position(|line| line == "maven.install("); + vec![format!( + "Bazel builds this package from maven_install.json (`maven.install`, {MODULE}:{}), \ + which does not name Socket patch {}: the patch is only in the installed copy. Run \ + `socket-patch get {PURL} --mode hosted` at the Bazel root to patch the hub, or with \ + `--mode vendored` to commit the patched jar (a `maven_bazel_*` warning of that run \ + means that the Bazel build keeps the upstream jar). 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("the hub") + 1, + self.patch.uuid + )] + } + /// Agent mode in the checkout ([`Cell::patches_outside`]). The victim's /// jar is in the Maven local repository, as a Maven build of the /// checkout's `pom.xml` leaves it: `scan --mode agent --yes` puts the @@ -1447,14 +1485,14 @@ impl Pinned { /// repository and warns that it patches no hub, and `apply` passes /// ([`Pinned::patches_the_installed_jar`]). Both, `vex` and /// `vex --no-verify` exit 0 and write a document that says the artifact -/// is not affected, through the patch. -/// - (c) The same two Bazel commands print the upstream marker again and -/// change no file: the hub fetches the jar its lock pins, at the lock's -/// sha256, and no build reads the Maven local repository. -/// -/// KNOWN GAP: the documents of (b) are false for what Bazel builds. A fix -/// makes each say that the artifact is affected, with what Bazel builds it -/// from and the command that patches the hub. +/// is affected, with what to do about it ([`Pinned::affected`]). +/// - (c) The same two Bazel commands print the upstream marker again, as +/// the documents said, and change no file: the hub fetches the jar its +/// lock pins, at the lock's sha256, and no build reads the Maven local +/// repository. +/// - (d) The hosted command the documents name pins the Maven build and +/// the hub. The same build prints the marker of the patched jar, and +/// `vex` says not affected, through the hosted patch. #[test] #[ignore = "real Bazel; run with --ignored"] fn an_agent_patch_beside_a_pinned_hub() { @@ -1464,32 +1502,125 @@ fn an_agent_patch_beside_a_pinned_hub() { }; // (a) The upstream build, with the jar from the stand-in. flow.builds_upstream(); + flow.names_its_bazel(); - // (b) Agent mode patches the installed jar. KNOWN GAP: every document - // says not affected. - let claim = Claim::new(PURL, &flow.patch.uuid, How::Agent); + // (b) Agent mode patches the installed jar, and every document says + // the artifact is affected. + let names = flow.affected(); + let claim = Claim::unbuilt(PURL, &flow.patch.uuid, &names); let patched = flow.patches_the_installed_jar(&claim); // (c) The build is the one of (a): Bazel never reads the patched jar. flow.cell.builds(&flow.upstream); assert_eq!(changed(&patched, &flow.cell.tree()), NOTHING, "{test}"); + + // (d) What the documents say to run: the build is patched, and the + // document says so. + let pinned = flow.pins(&patched, &PINNED); + flow.builds_patched(&pinned); + let run = |cell: &Cell, args: &[&str]| flow.socket_patch_in(cell, &flow.standin, args); + let hosted = Claim::new(PURL, &flow.patch.uuid, How::Hosted); + flow.cell.stands_alone(run, &hosted, true); println!( "{test}: Bazel {} built {:?} before and after `scan --mode agent` patched {VICTIM}-\ - {VERSION}.jar in the Maven local repository; every form of `vex` said the artifact is \ - not affected (KNOWN GAP); {:?}", + {VERSION}.jar in the Maven local repository, and every form of `vex` said the artifact \ + is affected, in the words {names:?}; after `get --mode hosted` it built {:?} and `vex` \ + said not affected; {:?}", flow.cell.release(), flow.upstream, + flow.patch.marker, flow.started.elapsed() ); } /// Without a Bazel: step (b) of [`an_agent_patch_beside_a_pinned_hub`] in a -/// checkout whose hub is pinned ([`Pinned::unbuilt`]). KNOWN GAP, as there. +/// checkout whose hub is pinned ([`Pinned::unbuilt`]). Then each of the two +/// modes the document names, in a checkout of its own: the command pins or +/// vendors the artifact for the Maven build and for the hub, with no +/// warning about the hub, and `vex` says not affected, through that mode. +/// +/// And each where the command writes no entry, in a checkout that names a +/// Bazel without `override_repo`: the documents of agent mode are the +/// same, and the command pins or vendors for the Maven build alone and +/// warns `maven_bazel_release`, which is what the action statement says to +/// look for. KNOWN LIMIT: `vex` then attests the Maven build's patch as +/// not affected although the hub still fetches the upstream jar, as it +/// does without the agent patch before it (the list of what is still wrong +/// in docs/ecosystems.md, "Bazel workspaces: VEX"). +#[test] +fn an_installed_jar_is_affected_beside_a_hub_that_fetches_its_own() { + let modes = [("hosted", How::Hosted), ("vendored", How::Vendored)]; + let releases: [(&str, &[&str]); 2] = [("9.3.2", &[]), ("7.3.0", &["maven_bazel_release"])]; + let each = |(mode, how)| releases.map(|(bazel, declined)| (mode, how, bazel, declined)); + for (mode, how, bazel, declined) in modes.into_iter().flat_map(each) { + let flow = Pinned::unbuilt(); + flow.cell.write(".bazelversion", format!("{bazel}\n")); + let names = flow.affected(); + let claim = Claim::unbuilt(PURL, &flow.patch.uuid, &names); + flow.patches_the_installed_jar(&claim); + + let get = flow.vendored(&["get", PURL, "--mode", mode, "--yes"]); + assert_eq!(get.envelope["summary"]["applied"], 1, "{}", get.dump); + let mut warned = codes_in(&get.envelope["warnings"]); + warned.retain(|code| code.starts_with("maven_bazel_")); + let module = std::fs::read_to_string(flow.cell.path(MODULE)).expect(MODULE); + let entry = module.contains(&format!("Socket patch {}", flow.patch.uuid)); + let expected = (declined.join(" "), declined.is_empty()); + assert_eq!((warned.join(" "), entry), expected, "{}", get.dump); + let run = |cell: &Cell, args: &[&str]| flow.socket_patch_in(cell, &flow.standin, args); + flow.cell + .stands_alone(run, &Claim::new(PURL, &flow.patch.uuid, how), true); + } +} + +/// Without a Bazel: what stays the statement of a project without Bazel +/// while the patch is in the installed jar alone +/// ([`Cell::keeps_its_statement`]). The hubs of which nothing is said: one +/// that has no lock, a pinned one beside one that has none, one with a +/// `maven.override` of the artifact, and one whose call may not run. And +/// what a person reads of an `apply` beside the hub that fetches the jar: +/// the warning and the count of the statement, and nothing under +/// `--silent`. #[test] -fn an_installed_jar_is_attested_beside_a_hub_that_fetches_its_own() { +fn an_installed_jar_is_attested_where_no_hub_is_shown_to_fetch_its_own() { let flow = Pinned::unbuilt(); - let claim = Claim::new(PURL, &flow.patch.uuid, How::Agent); + let names = flow.affected(); + let claim = Claim::unbuilt(PURL, &flow.patch.uuid, &names); flow.patches_the_installed_jar(&claim); + + let (origin, tools) = (flow.standin.origin(), flow.tools_env()); + let told = tools.each_ref().map(|(name, dir)| (*name, dir.as_str())); + let document = flow.cell.document("person"); + let warned = format!( + "Warning: {PURL}: the VEX document says affected. {}", + names[0] + ); + let loud = [&["apply"][..], &with_vex(&document)].concat(); + let silent = [&loud[..], &["--silent"]].concat(); + for apply in [loud, silent] { + flow.cell + .tells_a_person(&origin, &apply, &told, &document, &claim, &warned); + } + + let module = std::fs::read_to_string(flow.cell.path(MODULE)).expect(MODULE); + let lock = " lock_file = \"//:maven_install.json\",\n"; + let more = "maven.artifact(\n name = \"more\",\n artifact = \"gson\",\n group = \ + \"com.google.code.gson\",\n version = \"2.8.9\",\n)\n"; + let own = format!( + "maven.override(\n name = \"{HUB}\",\n coordinates = \"{GROUP}:{VICTIM}\",\n \ + target = \"//own:victim\",\n)\n" + ); + let undecided = [ + module.replace(lock, ""), + format!("{module}{more}"), + format!("{module}{own}"), + module.replace("maven.install(", "ENABLED and maven.install("), + ]; + let run = |cell: &Cell, args: &[&str]| flow.socket_patch_in(cell, &flow.standin, args); + let gives = |args: &[&str], document: &Path| flow.cell.gives(&origin, args, &told, document); + let installed = Claim::new(PURL, &flow.patch.uuid, How::Agent); + flow.cell + .keeps_its_statement(run, gives, &installed, &undecided); } /// Without a Bazel: the fixture's directories and the legs of its workflow diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index f569ec39d..6b854082f 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -19,6 +19,20 @@ //! rules_ruby does with a vendored gem and rules_csharp with a vendored //! package no test here builds, so neither is judged. //! +//! A sixth, rules_jvm_external, takes each jar that the lock of a hub pins +//! (`maven.install`) at the lock's sha256: from a repository of the lock, +//! or under `m2local` from the Maven local repository, where a jar that +//! agent mode patched no longer has that sha256. Its hubs are not in the +//! table below: [`super::maven`] reads them for hosted and vendored mode, +//! which patch a hub through a block of the root `MODULE.bazel` and not +//! through its lock, and the same reader answers here +//! ([`super::maven::upstream`]): for a jar patched in the installed copy, +//! whatever project of the workspace it was patched from, when every hub +//! was read and the block holds no entry for it. What counts as read is +//! that reader's to say, and the next paragraph is about the table alone: +//! a `WORKSPACE` file puts a Maven hub in doubt only by a `maven_install` +//! call that Bazel may read. +//! //! [`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 //! show it: the reader's answer is certain ([`Workspace::doubts`] and the @@ -123,8 +137,8 @@ pub struct Unbuilt { /// 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, + /// ([`Hub::remedy`]; for a Maven jar the command names the package). + pub remedy: String, } /// The tag of a module extension that names the files a ruleset builds the @@ -311,7 +325,8 @@ fn ecosystem(purl: &str) -> Option { pub async fn unbuilt(project: &Path, packages: Vec) -> Vec> { let hub = |package: &Patched| { let of = ecosystem(&package.purl); - HUBS.iter().any(|hub| of.as_deref() == Some(hub.ecosystem)) + let known = |hub: &Hub| of.as_deref() == Some(hub.ecosystem); + of.as_deref() == Some("maven") || HUBS.iter().any(known) }; if !packages.iter().any(hub) { return vec![None; packages.len()]; @@ -328,11 +343,44 @@ pub async fn unbuilt(project: &Path, packages: Vec) -> Vec = parts .map(|part| part.as_os_str().to_string_lossy()) .collect(); - judge(&workspace, &parts.join("/"), &read, &packages) + let mut found = judge(&workspace, &parts.join("/"), &read, &packages); + jars(&root.dir, &packages, &mut found); + found }) .await } +/// [`unbuilt`] for the Maven jars among `packages` that are patched in an +/// installed copy, in the workspace at `root`: into `found`, the +/// `maven.install` of the pinned hub that fetches the upstream jar +/// ([`super::maven::upstream`]), with the command that patches such a hub. +/// A flow builds it patched on real Bazel in hosted and in vendored mode. +/// That command writes no entry where it cannot show that one works (an +/// older Bazel, an rc file, a jar of the Maven local repository) and then +/// warns with a code of [`super::maven`]. The remedy says so, because the +/// pin such a run leaves in a `pom.xml` is attested all the same. +fn jars(root: &Path, packages: &[Patched], found: &mut [Option]) { + let installed = |at: &usize| packages[*at].pins.is_none(); + let installed: Vec = (0..packages.len()).filter(installed).collect(); + let purls: Vec<&str> = installed.iter().map(|at| &*packages[*at].purl).collect(); + let hubs = super::maven::upstream(root, &purls); + for (at, hub) in installed.into_iter().zip(hubs) { + let Some(hub) = hub else { continue }; + let purl = &packages[at].purl; + found[at] = Some(Unbuilt { + call: "maven.install".to_string(), + file: hub.file, + line: hub.line, + lock: hub.lock.unwrap_or_default(), + remedy: format!( + "Run `socket-patch get {purl} --mode hosted` at the Bazel root to patch the \ + hub, or with `--mode vendored` to commit the patched jar (a `maven_bazel_*` \ + warning of that run means that the Bazel build keeps the upstream jar)." + ), + }); + } +} + /// The most of a lock that is read: the lock of a large pnpm workspace has /// some tens of MiB. A larger file decides nothing. const MAX_LOCK: u64 = 64 << 20; @@ -463,7 +511,7 @@ fn judge( file: tag.file.to_string(), line: tag.call.line, lock: lock.clone(), - remedy: hub.remedy, + remedy: hub.remedy.to_string(), }); } } @@ -1358,6 +1406,48 @@ replace = "swapped 3.0.0" assert_eq!(unbuilt(&root.join("api"), vendored).await, [None]); } + /// A Maven jar that is patched in the installed copy, in a project of a + /// workspace whose pinned hub fetches that jar: the `maven.install` and + /// the lock of the hub, with the command of the two modes that patch + /// it, which names the package, and what tells that the command wrote + /// no entry. Nothing for a committed copy, which + /// vendored mode gives the hub, nor once the block holds the jar's + /// entry. + #[tokio::test] + async fn an_installed_jar_is_not_what_a_pinned_hub_fetches() { + let [module, lock, patched] = super::super::maven::tests::sample(UUID); + let tmp = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(tmp.path()).unwrap(); + std::fs::create_dir_all(root.join(".git")).unwrap(); + std::fs::create_dir_all(root.join("services/billing")).unwrap(); + std::fs::write(root.join("MODULE.bazel"), module).unwrap(); + std::fs::write(root.join("maven_install.json"), lock).unwrap(); + let netty = "pkg:maven/io.netty/netty-tcnative-classes@2.0.61.Final"; + let package = |pins: Option>| Patched { + purl: netty.to_string(), + uuid: UUID.to_string(), + pins, + }; + let packages = vec![package(None), package(Some(vec!["pom.xml".to_string()]))]; + let fetched = Unbuilt { + call: "maven.install".to_string(), + file: "MODULE.bazel".to_string(), + line: 4, + lock: "maven_install.json".to_string(), + remedy: format!( + "Run `socket-patch get {netty} --mode hosted` at the Bazel root to patch the \ + hub, or with `--mode vendored` to commit the patched jar (a `maven_bazel_*` \ + warning of that run means that the Bazel build keeps the upstream jar)." + ), + }; + for project in ["", "services/billing"] { + let found = unbuilt(&root.join(project), packages.clone()).await; + assert_eq!(found, [Some(fetched.clone()), None], "{project}"); + } + std::fs::write(root.join("MODULE.bazel"), patched).unwrap(); + assert_eq!(unbuilt(&root, packages).await, [None, None]); + } + /// On disk a lock is read as a file of the workspace is: through a /// link that stays inside the Bazel root and not through one that /// leads out of it, not past its bound, and as the run left a file it diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 73eb1d69d..3b4cb09ee 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -674,6 +674,15 @@ impl Hubs { (built, _) => built, } } + + /// Whether the block holds an entry for the jar of `group:artifact` at + /// `version`: Bazel takes that entry's jar in the place of a hub's. + fn patches(&self, group: &str, artifact: &str, version: &str) -> bool { + let jar = |patch: &Patch| { + (&*patch.group, &*patch.artifact, &*patch.version) == (group, artifact, version) + }; + self.block.iter().any(jar) + } } /// One patch in the block: the jar that takes the place of the one a hub @@ -1673,13 +1682,10 @@ fn notices_blocking( let hubs = Hubs::read(&disk(&root.dir), &disk_up_to(&root.dir, MAX_LOCK)); let mut said = Vec::new(); for (purl, (group, artifact, version)) in jars { - let in_block = |patch: &Patch| { - (&*patch.group, &*patch.artifact, &*patch.version) == (&*group, &*artifact, &*version) - }; let (code, detail) = match hubs.built(&group, &artifact, &version) { Built::No => continue, // Bazel takes the jar of the block's entry. - Built::Yes(_) if hubs.block.iter().any(in_block) => continue, + Built::Yes(_) if hubs.patches(&group, &artifact, &version) => continue, Built::Yes(by) => { let from = |(hub, _): &(&Hub, &Pinned)| { let (lock, name) = (hub.lock.as_deref().unwrap_or_default(), &hub.name); @@ -1711,6 +1717,37 @@ fn notices_blocking( said } +/// For each of `purls`, patched in the copy a build tool installed: the +/// pinned hub of the workspace at the Bazel root `root` that fetches the +/// plain jar of that artifact at that version, the first of them. Bazel +/// then takes the jar at the sha256 the lock of that hub pins: from a +/// repository, or under `m2local` from the Maven local repository, where +/// the patched jar is not one of that sha256. The lock's sha256 is not +/// compared with the patch: a lock that pins the patched jar's bytes is +/// read as any other. It is said only when it is certain: every hub was +/// read ([`Hubs::sure`]), and the block holds no entry for the jar, which +/// Bazel would take in its place. `None` otherwise, and for what is no +/// plain jar of a Maven artifact; without one among `purls` nothing is +/// read. +pub fn upstream(root: &Path, purls: &[&str]) -> Vec> { + let jar = |purl| parse_maven_purl(purl).filter(|_| plain(purl)); + let jars: Vec<_> = purls.iter().copied().map(jar).collect(); + if jars.iter().all(Option::is_none) { + return vec![None; purls.len()]; + } + let hubs = Hubs::read(&disk(root), &disk_up_to(root, MAX_LOCK)); + let fetched = jars.into_iter().map(|jar| { + let (group, artifact, version) = jar?; + let Built::Yes(by) = hubs.sure(&group, &artifact, &version) else { + return None; + }; + let patched = hubs.patches(&group, &artifact, &version); + let hub = by.first().filter(|_| !patched); + hub.map(|(hub, _)| (*hub).clone()) + }); + fetched.collect() +} + #[cfg(test)] pub(crate) mod tests { use super::*; @@ -2545,6 +2582,67 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") assert_eq!(notices_blocking(broken.path(), Vec::new()), []); } + /// [`upstream`] names the hub of an installed jar only where that is + /// certain: a pinned hub fetches the plain jar at that version, every + /// hub was read, and the block holds no entry for the jar. + #[test] + fn an_installed_jar_is_upstream_where_a_pinned_hub_surely_fetches_it() { + let [_, lock, patched] = sample("7a11e000-0000-4000-8000-0000000000b1"); + let said = |module: &str, more: &[(&str, &str)], purl: &str| { + let pinned = [("MODULE.bazel", module), ("maven_install.json", &lock)]; + let dir = project(&[&pinned[..], more].concat()); + let hub = |hub: Hub| { + let lock = hub.lock.unwrap_or_default(); + format!("{} {}:{} {lock}", hub.name, hub.file, hub.line) + }; + let found = upstream(dir.path(), &["pkg:npm/left-pad@1.3.0", purl]); + assert_eq!((found.len(), &found[0]), (2, &None), "{purl}"); + found[1].clone().map(hub).unwrap_or_default() + }; + let fetched = "maven MODULE.bazel:4 maven_install.json"; + assert_eq!(said(PINNED, &[], NETTY_PURL), fetched); + // Also a jar that no repository of the lock lists: under `m2local` + // the hub takes it from the Maven local repository, at that sha256. + let local = lock.replace("\"repositories\"", "\"m2local\": true, \"mirrors\""); + let local = [("maven_install.json", local.as_str())]; + assert_eq!(said(PINNED, &local, NETTY_PURL), fetched); + // Not another version, a classifier or a packaging of the jar. + let others = [ + NETTY_PURL.replace("61", "62"), + format!("{NETTY_PURL}?classifier=sources"), + format!("{NETTY_PURL}?type=aar"), + ]; + for purl in others { + assert_eq!(said(PINNED, &[], &purl), "", "{purl}"); + } + // The block's entry is the jar Bazel takes, and a block that was + // changed by hand may hold one. An entry for another version of + // the artifact is the entry of another jar. + assert_eq!(said(&patched, &[], NETTY_PURL), ""); + let by_hand = patched.replace("# Do not change", "# Do change"); + assert_eq!(said(&by_hand, &[], NETTY_PURL), ""); + let mut earlier = patch("netty-tcnative-classes", OTHER_UUID); + earlier.version = "2.0.60.Final".to_string(); + let earlier = with_patch(PINNED, LABEL, earlier).expect("a block"); + assert_eq!(said(&earlier, &[], NETTY_PURL), fetched); + // Beside the hub that fetches the jar: a hub without a lock, an + // override of the jar, and a `WORKSPACE` file that Bazel may read. + let lockless = "maven.artifact(name = 'more', artifact = 'a', group = 'g', version = '1')"; + let over = "maven.override(coordinates = 'io.netty:netty-tcnative-classes', target = ':a')"; + for more in [lockless, over] { + let module = format!("{PINNED}{more}\n"); + assert_eq!(said(&module, &[], NETTY_PURL), "", "{more}"); + } + let legacy = ("WORKSPACE", "maven_install(artifacts = [])\n"); + assert_eq!(said(PINNED, &[legacy], NETTY_PURL), ""); + let bazel_9 = [legacy, (".bazelversion", "9.3.2\n")]; + assert_eq!(said(PINNED, &bazel_9, NETTY_PURL), fetched); + // A `WORKSPACE` file that defines another repository is about no + // hub, whatever Bazel reads it. + let other = ("WORKSPACE", "http_archive(name = 'zlib', urls = [])\n"); + assert_eq!(said(PINNED, &[other], NETTY_PURL), fetched); + } + /// What the warning for a hub that was not read says after where and /// why. const NOT_READ: &str = "so socket-patch does not know every Maven artifact that Bazel builds \ diff --git a/docs/ecosystems.md b/docs/ecosystems.md index fc0ed2637..8979ef1f0 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2157,7 +2157,7 @@ workspace and that Bazel does not build keeps the matrix at the top. | 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 | +| 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 | These words are the table's own, not the [v5 support tiers](#v5-support-tiers). In particular "Not supported" does not mean that the command refuses: in several cells it runs, @@ -2178,14 +2178,15 @@ exits 0 and leaves a build that fails (the known problems below). What a cell sa [Bazel workspaces: VEX](#bazel-workspaces-vex) has the cases and the limits; a vendored gem 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). + below). For Maven, + [Bazel workspaces: Maven](#bazel-workspaces-maven) says what `vex` checks of the hub before + it attests an entry, and that it attests a patch that only the Maven or Gradle build + holds. - **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 + that. It does not say `affected` of a package whose patch is in no build of Bazel's, one that is only in an installed copy, say: - of that package it still says `not_affected`. Do not publish that document. For Maven, - [Bazel workspaces: Maven](#bazel-workspaces-maven) says what `vex` checks of the hub before - it attests an entry. + of that package it still says `not_affected`. Do not publish that document. **Agent mode is not supported for Bazel builds, in any ecosystem.** Agent mode is made for the copies a package manager installed: `socket-patch apply` patches them after each install. @@ -2783,6 +2784,16 @@ artifact: - Nothing is said for a jar the block patches, under `--global`, and by a `vendor` whose `--ecosystems` leaves Maven out. +`socket-patch vex` and `--vex` say `affected` of an artifact that agent mode patched in an +installed jar while a pinned hub fetches the jar at that version and the block holds no +entry for it: the statement names the lock, the `maven.install` and its line, and the +command of hosted and of vendored mode that patches the hub +([Bazel workspaces: VEX](#bazel-workspaces-vex)). It says so only when every hub was read. +Where one was not, the statement stays `not_affected`, as without Bazel, also beside the +first warning above. The command it names patches the hub only where it writes an entry: +where it gives a code of the table above instead, the hub stays as it is, and the statement +of the pin that the command left in the `pom.xml` is `not_affected` (the last limit below). + The Bazel release is the one that `.bazeliskrc` (`USE_BAZEL_VERSION`) or else `.bazelversion` at the Bazel root names, read as bazelisk reads them: the last `USE_BAZEL_VERSION` line counts, without the blanks around the name and the value, and an empty one leaves it to the first line @@ -2836,8 +2847,10 @@ Limits: that only Bazel builds that is `package_not_installed`. A vendored `get` of a jar that no hub builds there fails with `vendor_jvm_shape_unsupported`, as before. So does a `vendor` that is refused before it vendors anything (a ledger that cannot be read, or one that git ignores). -- `socket-patch vex` looks at the hub only for the block's entries: a patch that only the - `pom.xml` pin or a patched jar attests is attested, although the Bazel build does not have it. +- `socket-patch vex` looks at the hub for the block's entries and for a jar that agent mode + patched (above): a patch that only a `pom.xml` or Gradle pin, or the vendored tree of + such a build, attests is attested, although the Bazel build does not have it. That is the + state a hosted or vendored command leaves where it writes no entry for the hub. ## Bazel workspaces: Cargo @@ -4279,7 +4292,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 five rulesets that hand +also read `MODULE.bazel` and the files it includes, for the calls of six rulesets that hand a lock to Bazel: | Call | Files it names | @@ -4289,11 +4302,15 @@ a lock to Bazel: | rules_ruby `ruby.bundle_fetch` | `gemfile_lock`, `gemfile` | | rules_rust `crate.from_cargo` | `cargo_lockfile` | | rules_csharp `nuget.from_lock` | `packages_lock_json` | +| rules_jvm_external `maven.install` | `lock_file` | 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, 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: +folder. A rules_jvm_external hub takes a jar from the Maven local repository only when its +lock has `m2local` and lists the jar under no repository, and then at the lock's sha256 +too, so not the jar as agent mode patched it. So three 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 @@ -4313,6 +4330,25 @@ package that it is `affected`, not that it is patched: 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 patch in an installed jar** (agent mode) of a Maven artifact, when a pinned hub (the + `maven.install` tags of one name, with a `lock_file`) fetches the plain jar of that + artifact at that version, and the block that hosted and vendored mode keep in the root + `MODULE.bazel` holds no entry for the jar. The lock of a hub is no project's own, and no + `pom.xml` or Gradle file decides what a hub fetches: the statement is the same from every + project of the workspace, whichever build tool installed the jar. The hubs are read as + [Bazel workspaces: Maven](#bazel-workspaces-maven) says, and every hub has to be read: + beside a hub without a `lock_file`, a tag or a lock that cannot be read, a + `maven.override` of the artifact, a `maven_install` of a `WORKSPACE` file that Bazel may + read or a block that was changed by hand, the statement stays `not_affected`, also where + `apply` warns `maven_bazel_hub_unpatched`. + A jar that a hub takes from the Maven local repository under `m2local` counts as fetched: + the hub holds that file to the lock's sha256, which the patched jar does not have (read + from the ruleset's source at 7.2 and 6.5; no test builds it). The sha256 of the lock is + not compared with the patch: a lock that pins the very bytes of the patched jar would + still read as `affected`. + Measured on Bazel 9.3.2 and 7.7.2 for rules_jvm_external 7.2 and 6.5, with a lock that + lists the jar under a repository: the build prints the upstream jar before + `scan --mode agent` and after it. - **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 @@ -4362,6 +4398,30 @@ A test without Bazel runs each of those scans after agent mode, and the document `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. +For a Maven artifact the action statement names the command of the two modes that patch a +pinned hub. It names the package, and it runs at the Bazel root, where the patch of a hub is +written: + +``` +Run `socket-patch get pkg:maven//@ --mode hosted` at the Bazel root to patch the hub, or with `--mode vendored` to commit the patched jar (a `maven_bazel_*` warning of that run means that the Bazel build keeps the upstream jar). +``` + +The words in brackets are a condition of the command. It writes its entry for the hub only +where it can show from the checkout that the entry works: Bazel 7.4.0 or later, a known +release of the ruleset, no rc file that switches the entry off, a jar that a repository of +the lock lists, a hub on a `use_extension` that is not isolated (the table of codes in +[Bazel workspaces: Maven](#bazel-workspaces-maven)). Where it cannot, it gives a +`maven_bazel_*` warning, and beside a `pom.xml` or a Gradle build it exits 0 and has still +pinned or vendored the patch for that build. `vex` then attests that patch and says +`not_affected`, which is wrong for the Bazel build: the hub fetches the upstream jar as +before (the list at the end of this section). Read the warnings of the command before you +trust the next document. + +A test without Bazel runs each of the two after agent mode. Where the command writes its +entry it gives no such warning, and `vex` then says `not_affected`. In a checkout that names +Bazel 7.3.0 it writes none and warns `maven_bazel_release`. The hosted one is run on real +Bazel after agent mode as well: the build prints the patched jar. + A run tells a person the same in a warning (`vex_bazel_not_in_build`, one per package): ``` @@ -4386,9 +4446,12 @@ lock. A repository that ships what its package manager installed (a container im with `pnpm install` and `socket-patch apply`, say) and keeps the hub for something else, such as its tests, says so with `--no-bazel` on `vex`, with `--vex-no-bazel` on `scan`, `apply` and `vendor`, or with `SOCKET_VEX_NO_BAZEL=1` in the environment. The Bazel workspace is then not -read: the document describes the installed tree, and it, the warnings, the exit code and -every line of the run are those of the same checkout without its Bazel files. The option -changes nothing outside a Bazel workspace. +read for the document: it describes the installed tree, and it, the warnings about it, the +exit code and every line that `vex` prints are those of the same checkout without its Bazel +files. The option is about the document alone. What `scan`, `apply` and `vendor` themselves +do and say in a Bazel workspace stays: an agent run beside a pinned rules_jvm_external hub +still warns `maven_bazel_hub_unpatched`. The option changes nothing outside a Bazel +workspace. Nothing changes where the files do not show such a call: outside a Bazel workspace, in a `--global` run, for a hosted pin, for a project whose own lock no call names, and wherever @@ -4417,6 +4480,16 @@ is not read at all. In each of these the document is the one of a project without Bazel. Flags outside the committed files (`--override_repository`, an rc file) and BUILD files are not read either. +A Maven jar differs in one of these, the `WORKSPACE` file. Its hubs are read as +[Bazel workspaces: Maven](#bazel-workspaces-maven) says: there such a file counts only when +it calls `maven_install` or cannot be read, and only while `.bazeliskrc` or `.bazelversion` +names no Bazel 9 or later. So beside a `WORKSPACE` file that defines other repositories, +and on Bazel 9 beside any, a jar that a pinned hub fetches is `affected`. In the other cases +the document of a Maven jar is the one of a project without Bazel as well (a lock of a hub +is read up to 16 MiB), and also when no pinned hub fetches the jar at that version, when +the block holds an entry for it, and when any hub of the workspace is not read with +certainty (the list of the jar above). + Three more things change no statement. A call counts only when it is a statement of its own, which Bazel runs once: one in a comprehension, behind an `and`, in a conditional or in the arguments of another call may never run. Of a pnpm lock the project documents are read: a @@ -4424,6 +4497,12 @@ package that only the document pnpm 11 keeps for its own configuration lists is rules_js links. And a patch whose record names no advisory gets no statement from any run, so it is not looked at here: a run over such a patch alone ends as it does without Bazel. +Only a patch that the run found in place is looked at. Where the installed copy on the +machine is missing or is not the patched one, `vex` ends as it does without Bazel: no +statement for that package, and exit 1 (`no_applicable_patches`) when it was the only one, +although the hub builds the upstream package all the same. `vex --no-verify`, which attests +the record, says `affected` there. Measured by hand, without Bazel, for a Maven jar. + The document and the build are tested to agree on real Bazel 9.3.2, 8.8.2 and 7.7.2 for four shapes, all under Bzlmod: Go through gazelle's `go_deps.from_file(go_mod = "//:go.mod")` with @@ -4453,6 +4532,12 @@ NuGet a flow of agent mode holds the documents to the unpatched build as well: t [Bazel workspaces: what is supported](#bazel-workspaces-what-is-supported) says what the document does not show. +For Maven, through rules_jvm_external's `maven.install` with a `lock_file`, a flow of agent +mode beside a `pom.xml` holds the documents to the unpatched build on Bazel 9.3.2 and 7.7.2: +the run (`--vex`), `apply --vex`, `vex` and `vex --no-verify` each write one `affected` +statement. After the hosted command the build is the patched one, and `vex` writes one +`not_affected` statement. `vex --no-bazel` is tested without Bazel. + For no other Bazel shape do these pages say that the document and the build agree, and in these the document is still wrong (`not_affected` while Bazel builds the unpatched package, or while the build is broken): @@ -4473,6 +4558,15 @@ the build is broken): file at the root defines something, or the workspace has no `MODULE.bazel`. Measured for rules_js, rules_rust and rules_csharp, which build from the lock and never read the patched copy. +- **Agent mode beside rules_jvm_external**, wherever the statement does not say `affected` + above: a hub of the workspace is not read with certainty, or the jar reaches Bazel in a + way that [Bazel workspaces: Maven](#bazel-workspaces-maven) lists as not seen (a hub of + another Bazel module, a `maven_install` inside a function of a `.bzl` file). +- **Hosted and vendored mode for Maven, where the run wrote no entry for the hub** (the + `maven_bazel_*` warnings) and pinned or vendored the patch for a `pom.xml` or a Gradle + build: the hub builds the upstream jar. The command that an `affected` statement names + ends here where it declines. A test without Bazel holds both modes to it, in a checkout + that names Bazel 7.3.0. - **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 diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index ea94cfb34..987353ea3 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 4006 + "max": 4051 }, "lock-readers": { "paths": [ From 1aad23cc47d9cee2cae4824122c5016fe6f26dd5 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 04:14:50 -0500 Subject: [PATCH 14/19] Hold every Maven patch to the Bazel hub in VEX, whichever mode holds it `vex` and `--vex` say `affected` of a Maven artifact that agent mode patched in an installed jar while a pinned rules_jvm_external hub fetches that jar from its lock. This change makes the statement hold in the cases around it where the document was still false, or said less than socket-patch knows. A patch in any mode. A hub reads no `pom.xml`, no Gradle file and no vendored tree, so a hosted pin or a vendored copy of a Maven or Gradle build is in the Bazel build only through an entry of the block in the root `MODULE.bazel`. Hosted and vendored mode write no entry where they cannot show that one works: they exit 0 with a `maven_bazel_*` warning and pin or vendor for the other build. `vex` then attested that patch as `not_affected` while the hub fetched the upstream jar, and the action statement of an agent patch sent a reader into that state. The Bazel step of `vex` now asks about every Maven patch, also one with a hosted pin or a committed copy, so the document after a command that declined still says `affected`. The statement is one for every mode: "the patch is only in what Maven or Gradle builds from", and "If what you ship is what Maven or Gradle builds and not what Bazel builds, pass `--no-bazel`". The statements of the other ecosystems are word for word what they were, and a hosted pin of another ecosystem is left alone as before. The hub that fetches the jar, not every hub. `maven::upstream` asked `Hubs::sure`, which is the rule for writing an entry: any doubt, also one about another hub, gave nothing. So beside a second hub without a lock `apply` warned that the Bazel build stays unpatched while the document of the same run said `not_affected`. It now asks `Hubs::built`: a pinned hub that was read fetches the jar, and no `maven.override` names the artifact. A block that was changed by hand may hold an entry, so it still gives nothing. An entry of this patch. Any entry of the block for the jar counted as "Bazel builds the patch". The entry of another patch than the one the document attests does not: the statement is `affected`, and names that entry first. Whether Bazel reads `MODULE.bazel`. Nothing is said where the checkout does not show that it does: `.bazeliskrc` or `.bazelversion` names a Bazel before 7.0; neither names a release while a `WORKSPACE` file defines a repository; or an rc file names an option that switches Bzlmod off or drops tags of the root, or cannot be read. Such an option is found on whatever line, so it may hold for one `--config` alone: with it neither the hub nor an entry of the block is certain, which is why an entry of hosted mode is not attested there either. Before, a checkout that switched Bzlmod off got `affected` from a file that Bazel does not read. While a release from 7.0 on is named, Maven keeps its finer rule for a `WORKSPACE` file: a `maven_install` there is another hub, and changes nothing for the hub that was read. What to do. The action statement named `get --mode hosted` whether or not that command would write an entry. `upstream` now gives the remedy with the hub. Where hosted or vendored mode writes the entry (`Hubs::label` and `settings`, as for a run) it is the command. Where they do not, it is "Hosted and vendored mode write no entry for this hub (``): .", with the code and the reason of the warning that the command gives. One helper builds the command for the statement and for the `maven_bazel_hub_unpatched` warning, from the coordinates of the jar: a purl with qualifiers (`?type=jar&...`) no longer puts `?` and `&` into a command for a shell. `"maven.install"` and the sentence moved from `bazel/built.rs` to `bazel/maven.rs` with it. `built::unbuilt` no longer parses the workspace for its table of hubs in a run that has only Maven packages. The hubs and their locks are still read once more than lock discovery reads them for the block: the two are different layers of a run, and a read is one `MODULE.bazel` with the locks it names. Tests. `maven::upstream` has one unit test with a line per case above. Without Bazel, `e2e_bazel_build` runs agent mode and then the hosted and the vendored command in three checkouts: where the command writes its entry (`not_affected` after it), and under Bazel 7.3.0 and beside a second hub without a lock (`affected` before and after, with the code and the reason in the place of the command). It holds the statement of a project without Bazel beside an rc file that names `--noenable_bzlmod` for one config, beside a `WORKSPACE` file with no release named, and under Bazel 6. No existing test expected `not_affected` for a hosted or vendored Maven patch whose hub got no entry: each of them writes the entry, and passes as it was. docs/ecosystems.md, the CLI contract and the line budget of `bazel/` (4051 to 4084 implementation lines) follow. The contract's row of `vex_bazel_not_in_build` no longer says that a `--no-bazel` run reads no Bazel file: the option is about the document, and `apply` still reads the workspace for its own warning. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 4 +- crates/socket-patch-cli/src/commands/vex.rs | 41 ++- .../tests/e2e_bazel_build/maven.rs | 138 +++++--- crates/socket-patch-core/src/bazel/built.rs | 135 ++++---- crates/socket-patch-core/src/bazel/maven.rs | 297 +++++++++++++----- docs/ecosystems.md | 171 ++++++---- scripts/loc-budget.json | 2 +- 7 files changed, 529 insertions(+), 259 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index f38e2fcb0..dd79caf70 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2712,7 +2712,7 @@ command's integration tests check its output. | `vendor_prebuilt_stub_invalid` | `failed` | RubyGems: the server stub lacks required attributes or is otherwise invalid; no local stub fallback is permitted. | | `bazelignore_not_updated` | run-level `warnings[]` | Go vendored and agent mode, Cargo vendored mode under a rules_rust crate hub, and Maven vendored mode, in a Bazel workspace (additive): the `.bazelignore` at the Bazel root, which keeps Bazel and gazelle out of the module copies under `.socket/vendor/golang` and `.socket/go-patches` out of the crates under `.socket/vendor/cargo`, and out of the jars vendored for a rules_jvm_external hub under `.socket/vendor/maven`, was not updated. It could not be read or written (a symbolic link or a directory in its place, a read-only directory, a read-only file). The detail names the line to add, or says that the lines of a copy that is gone can be deleted; the command's patch or undo stands and its exit code is unchanged. See docs/ecosystems.md "Bazel workspaces: `.bazelignore`". | | `redirect_cargo_bazel_config_unread` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_rust crate_universe hub (`crate.from_cargo` in `MODULE.bazel` or a file it includes, or `crates_repository` in the `WORKSPACE` file) reads the project's `Cargo.lock` or one of its `Cargo.toml` files, or may read them (its `cargo_lockfile` or `manifests` is not written out as strings, or a use of the extension may hide a call), and its `cargo_config` is not one string that is the label of the cargo config hosted mode writes (`.cargo/config.toml`, or the project's `.cargo/config`). cargo-bazel runs cargo with the config its hub names and no other, so the registry of a pin would be unknown to it and `bazel build` would fail (`registry index was not found in any configuration`). The crate is not pinned: nothing is written for it, its event is `skipped` / `redirect_unconfirmed` (a vendored crate that the scan would take over stays vendored: `skipped` with this code, and `redirect_takeover_kept_vendored`), and status and exit code are unchanged. One warning per crate; the detail names the hub's file and line, the config to commit (created with a comment line in it where the project has none), the attribute to give the hub (`cargo_config = "//:.cargo/config.toml"`; the label is written in the package of the hub's own labels), after which the same command pins the crate, and `--mode vendored`. A hub that names that config is still in the way while the file is there and holds nothing: `rollback` deletes a cargo config it leaves empty, and the hub fails on the missing file; the detail asks for a comment line in it. For a use of the extension that may hide a call the detail names that line to rewrite and no attribute: the next run pins the crate or names the hub that is in the way. A `WORKSPACE` call (`crates_repository`, also under the name a `load` of that file gives it) counts only when no hub of the module files reads the project's Cargo files and the checkout names no Bazel 9 or later. The rewriter's own refusals answer first and keep their codes. A pin that is in place already stays `applied`, and no warning is given for it. Nothing is read or changed in no Bazel workspace, or where no such hub is seen to read the project's Cargo files. See docs/ecosystems.md "Bazel workspaces: Cargo". | -| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace, agent and vendored mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch of this run, and the block that hosted and vendored mode keep in `MODULE.bazel` holds no entry for that jar after it. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build. Agent mode (`apply`, and `get` / `scan` in that mode; only for a package it found installed; never under `--global`) patches no hub: one warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub; the events, the exit code and every written file are those of the same run without the workspace. A VEX document says `affected` of such a jar when every hub was read (`vex_bazel_not_in_build`). Vendored mode (`vendor`, and `get` / `scan` in that mode) patches a pinned hub (below), and gives this code only for a jar it could have written an entry for and vendored nothing for, because the package failed or was skipped for another reason (never in a dry run); a jar it cannot write an entry for gets the `maven_bazel_*` code of the reason instead. A `vendor` whose `--ecosystems` leaves Maven out gives none. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace, agent and vendored mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch of this run, and the block that hosted and vendored mode keep in `MODULE.bazel` holds no entry for that jar after it. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build. Agent mode (`apply`, and `get` / `scan` in that mode; only for a package it found installed; never under `--global`) patches no hub: one warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub; the events, the exit code and every written file are those of the same run without the workspace. A VEX document says `affected` of such a jar (`vex_bazel_not_in_build`), but where the block was changed by hand or the checkout does not say that Bazel reads `MODULE.bazel` as it stands. Vendored mode (`vendor`, and `get` / `scan` in that mode) patches a pinned hub (below), and gives this code only for a jar it could have written an entry for and vendored nothing for, because the package failed or was skipped for another reason (never in a dry run); a jar it cannot write an entry for gets the `maven_bazel_*` code of the reason instead. A `vendor` whose `--ecosystems` leaves Maven out gives none. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | | `maven_bazel_unreadable` | agent: run-level `warnings[]` (human: `Warning: …`); scan/get `--mode hosted`: `warnings[]` (warning); vendored: as `maven_bazel_not_at_root` | Maven in a Bazel workspace (additive): whether a rules_jvm_external hub builds the jar of a Maven patch could not be told, because something could not be read with certainty: a hub without `lock_file` in agent mode (hosted and vendored mode give `maven_bazel_not_pinned`), a `maven.artifact` or `maven.from_toml` tag that cannot be read, a lock that is missing, empty, not format 2 or 3, larger than 16 MiB (or past the 64 MiB of locks that are read for one workspace) or no JSON, a `WORKSPACE` file that calls `maven_install` or cannot be read while `.bazeliskrc` or `.bazelversion` at the Bazel root names no release of Bazel 9 or later, a `maven.install` whose `name` or `lock_file` is not a plain string, a construct of `MODULE.bazel` the reader does not follow, and, in agent mode, a `maven.override` of the artifact (hosted and vendored mode give `maven_bazel_no_effect`). Hosted and vendored mode also give it for a hub on an isolated `use_extension`, an rc file that cannot be read (also one that an import takes from outside the workspace by a relative path, and one with a line whose reading Bazel's own source calls an oversight: a quote that is never closed, a `\` with nothing after it), a `MODULE.bazel` that is a symbolic link, and a block of `MODULE.bazel` that was changed by hand (also in its first line alone), and then writes no entry for the hub. One warning per purl; the detail names the file, the line and the reason. | | `maven_bazel_hub_not_read` | scan run-level `warnings[]` (human: `Warning: …`); `get --mode hosted`: `warnings[]` | scan `--mode hosted` at the root of a Bazel workspace, with Maven in scope (additive): the scan takes the jars that the pinned rules_jvm_external hubs fetch for packages of the project (the lockfile supplement above), and something of the hubs could not be read with certainty, so it does not know every Maven artifact that Bazel builds through a hub. Given once per run, for the first thing that was not read, whatever the packages: a hub without `lock_file` (the detail then ends with how to pin it), or one of the reasons of `maven_bazel_unreadable` that concern reading the hubs (a tag or a lock that cannot be read, a `maven_install` of a `WORKSPACE` file that Bazel may read, a construct of `MODULE.bazel` the reader does not follow, a block that was changed by hand). `[:]: , so socket-patch does not know every Maven artifact that Bazel builds here through a rules_jvm_external hub: it looks for patches of the ones in the hub locks it read, and of no other`. No jar is guessed for what was not read; the jars of the hubs that were read are scanned, and a patch found for one of them gets no entry while the doubt stands (`maven_bazel_not_pinned` / `maven_bazel_unreadable` below). With no package at all a person reads `No packages found (see the warning).`. Exit code and `status` unchanged. A hosted `get` by advisory, which keeps the releases the project has by the same supplement, gives it too when the advisory has a patch of a Maven artifact. Only in a workspace that has to do with the ruleset: a call in `MODULE.bazel` or a file it includes names `rules_jvm_external`, the `WORKSPACE` file calls `maven_install`, or a `maven_install.json` lies at the Bazel root. In another Bazel workspace a file that cannot be read gives no such warning, and the run is the one without the workspace. | | `maven_bazel_not_at_root` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_jvm_external hub builds the jar of a Maven patch, and the project is below the root of its Bazel workspace, in whose `MODULE.bazel` the patch of a hub is written. Like the five codes below and `maven_bazel_unreadable` in hosted mode, it means that the run wrote no entry for the jar in the block of the root `MODULE.bazel`, because it could not show from the checkout that the entry works. One warning per purl, in the place of `redirect_maven_no_pom` for that purl; the detail says why and ends with what the block of the root holds for the jar, which is read for a project below the root too (the detail then names the file as "the MODULE.bazel at the root"). Nothing: "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps the upstream jar". The event is the one of the same run without the hub: `skipped` / `redirect_unconfirmed` in a tree only Bazel builds, `applied` beside a `pom.xml` or Gradle pin that landed. The entry of the patch, from an earlier run: that entry stays, the event is `applied`, and the detail ends "socket-patch left the entry that MODULE.bazel holds for it as it is". The entry of another patch of the same jar: it stays too, the event is the one without the hub, and the detail ends "socket-patch wrote nothing to MODULE.bazel for it: the entry of patch remains there, and where the block is in effect the Bazel build takes that patch's jar". Exit code unchanged. With none of these codes the run writes the block: `redirect.rewrittenFiles` holds `MODULE.bazel`, the event is `applied`, and `rollback` / `remove` take the entry out. **Vendored mode** (`vendor`, and `scan` / `get --mode vendored`; additive) gives the same codes, but for `maven_bazel_download`, with the same detail, for a jar whose entry it does not write. In a project with no Maven, Gradle, sbt or scala-cli build the hub is the patch's only target: the event is `failed` with the code as its `errorCode` and the detail, without the purl in front, as its `error`, nothing is written and the run exits 1, as for any vendored refusal (before, such a project failed with `vendor_jvm_shape_unsupported`, which a jar that no hub builds still does). Beside such a build that was vendored, the code is a run-level `warnings[]` entry (human: `Warning: …`), the event is `applied` and the exit code is unchanged. With none of these codes vendored mode commits the patched jar under `.socket/vendor/maven//` (`REPO.bazel`, `file/BUILD.bazel`, `file/-.jar`, `.gitignore`), writes the entry that names that directory into the block, in the place of a hosted entry for the same jar, adds the directory's line to `.bazelignore`, and records the patch in the vendor ledger (in a project with no other JVM build: `ecosystem` `maven`, `flavor` `bazel`, the committed jar as `artifact`, no `wiring`); the event is `applied`. `vendor --check` then also fails (`vendor_check_failed`) when that jar is not, byte for byte, the vendored jar the ledger records (beside a Maven or Gradle build the hub's jar is a copy of it), when `REPO.bazel` / `file/BUILD.bazel` is not the file that was written, when the block no longer names the directory or was changed by hand, and when no pinned hub takes the jar at that version any more (the reason names `socket-patch rollback `) or an rc file switches the entry off. `vendor --revert` / `rollback` / `remove` take the entry, the directory and the line out, and a hosted run that puts its entry in the place of the vendored one removes the directory and the line. See docs/ecosystems.md "Bazel workspaces: Maven". | @@ -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`, rules_rust `crate.from_cargo`, rules_csharp `nuget.from_lock`, rules_jvm_external `maven.install`), 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 in an installed jar of a Maven artifact while a pinned hub fetches the plain jar of that artifact at that version and the block that hosted and vendored mode keep in the root `MODULE.bazel` holds no entry for it (the lock of a hub is no project's own: the same from every project of the workspace; a jar that the hub takes from the Maven local repository under `m2local` counts as fetched, and the lock's sha256 is not compared with the patch), 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 Maven jar `get --mode hosted` at the Bazel root, or with `--mode vendored`, and that a `maven_bazel_*` warning of that run means that the Bazel build keeps the upstream jar: the command writes no entry for the hub where it cannot show that one works, and the pin it then leaves in a `pom.xml` or a Gradle build is attested as `not_affected`; 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), for a Maven jar when the block holds an entry for it or when any rules_jvm_external hub of the workspace is not read with certainty (a hub without `lock_file`, a `maven.override` of the artifact and the other reasons of `maven_bazel_unreadable` that concern reading the hubs, also where `apply` warns `maven_bazel_hub_unpatched` beside such a hub), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, which for a Maven jar counts only when it calls `maven_install` or cannot be read while the checkout names no Bazel 9 or later, 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`, rules_jvm_external `maven.install`), 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 patch of a Maven artifact in any mode (in an installed jar, in a pin of a `pom.xml` or a Gradle file, in a copy vendored for such a build) while a pinned hub fetches the plain jar of that artifact at that version and the block that hosted and vendored mode keep in the root `MODULE.bazel` holds no entry of that patch for it (no file of a project decides what a hub fetches: the same from every project of the workspace, and the same after a hosted or vendored command that wrote no entry for the hub; a jar that the hub takes from the Maven local repository under `m2local` counts as fetched, and the lock's sha256 is not compared with the patch), 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 Maven jar `get pkg:maven//@ --mode hosted` at the Bazel root, or with `--mode vendored`, the package by its coordinates alone, without the qualifiers of its purl; where hosted and vendored mode write no entry for the hub, in the place of the command ``Hosted and vendored mode write no entry for this hub (``): .`` with the `maven_bazel_*` code and the reason of the warning that the command gives (those of vendored mode: an option about downloads does not count); before either, when the block holds the entry of another patch for the jar, ``MODULE.bazel holds the entry of patch for this jar, and where the block is in effect the Bazel build takes that patch's jar.``; for a vendored PyPI 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).``; a Maven statement, which is one for every mode, says ``the patch is only in what Maven or Gradle builds from`` where the others say ``the patch is only in the installed copy``, and ends ``If what you ship is what Maven or Gradle builds and not what Bazel builds, pass …``), 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`, under which the Bazel workspace is not read for the document (see "The installed tree" under "VEX provenance markers": what the host command itself does and says in a Bazel workspace stays), for a hosted pin of another ecosystem than Maven, 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), for a Maven jar when the block holds the entry of its patch or was changed by hand, when a `maven.override` names the artifact, when the hub that would fetch it or its lock cannot be read (what is not known of another hub, such as a second hub without `lock_file` or a `maven_install` of a `WORKSPACE` file, changes nothing), or when the checkout does not say that Bazel reads `MODULE.bazel` as it stands (`.bazeliskrc` or `.bazelversion` names a Bazel before 7.0, or neither names a release while a `WORKSPACE` file defines a repository; an rc file of the checkout names `enable_bzlmod` other than switched on while the checkout names no Bazel 9 or later, or `--ignore_dev_dependency` without switching it off, on whatever line, or cannot be read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, which for a Maven jar counts only while the checkout names no Bazel release, 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 1dae29e2e..436724d99 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -1902,12 +1902,6 @@ const BAZEL_NOT_IN_BUILD: &str = "vex_bazel_not_in_build"; const AFFECTED_REASON: &str = "attested as affected, not as patched: Bazel does not build the \ patched copy of this package; the run warning names what it builds from"; -/// The closing sentence of the action statement, and so of the run warning, -/// of a package that is affected because its patch is in the installed copy -/// alone. -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, /// rules_ruby, rules_rust, rules_csharp or rules_jvm_external builds a /// package from the lock a workspace file names, never from the copy a @@ -1929,6 +1923,10 @@ const INSTALLED_TREE_SHIPS: &str = "If what you ship is the installed tree and n /// be read with certainty: the statement stays the one of a project /// without Bazel. So is a patch whose record names no advisory: no run /// writes a statement for it, and it is left out for that reason alone. +/// A Maven patch is asked about whichever mode recorded it: no file of a +/// project decides what a rules_jvm_external hub fetches, so a pin of a +/// `pom.xml` or a Gradle file, and a copy vendored for such a build, are +/// in the Bazel build only through an entry of the root `MODULE.bazel`. /// /// With `--no-bazel` / `--vex-no-bazel` (`params.no_bazel`) the user has /// said that the document is about the installed tree, which is what the @@ -1952,7 +1950,8 @@ async fn unbuilt_by_bazel( } let patched = |purl: &String| { let record = plan.view.patches.get(purl)?; - let judged = !plan.hosted.contains_key(purl) && !record.vulnerabilities.is_empty(); + let pinned = plan.hosted.contains_key(purl) && !purl.starts_with(MAVEN); + let judged = !pinned && !record.vulnerabilities.is_empty(); judged.then(|| Patched { purl: purl.clone(), uuid: record.uuid.clone(), @@ -1977,21 +1976,28 @@ async fn unbuilt_by_bazel( affected } +/// The start of a Maven purl. +const MAVEN: &str = "pkg:maven/"; + /// 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. 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, and for a Maven jar -/// the Bazel root, where the patch of a hub is written. +/// the Bazel root, where the patch of a hub is written, or what keeps +/// those modes from writing it. /// /// 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 /// option, in both spellings, since the statement is the same whichever -/// command wrote the document. Not for a committed PyPI copy: there the +/// command wrote the document. A Maven patch has the same statement in +/// every mode, a committed copy included, in words that hold for each: +/// the patch is in what Maven or Gradle builds from, and that build is +/// what such a repository ships. Not for a committed PyPI copy: there the /// build is broken or takes the registry's package, and the installed tree /// is not the patched one either. fn bazel_build_action(package: &Patched, call: &Unbuilt) -> String { - let Patched { uuid, pins, .. } = package; + let Patched { purl, uuid, pins } = package; let Unbuilt { call: tag, file, @@ -1999,11 +2005,20 @@ fn bazel_build_action(package: &Patched, call: &Unbuilt) -> String { lock, remedy, } = call; - match pins { + let maven = purl.starts_with(MAVEN); + let (only, ships) = match maven { + true => ( + "what Maven or Gradle builds from", + "what Maven or Gradle builds", + ), + false => ("the installed copy", "the installed tree"), + }; + match pins.as_ref().filter(|_| !maven) { 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. {remedy} \ - {INSTALLED_TREE_SHIPS}" + name Socket patch {uuid}: the patch is only in {only}. {remedy} If what you ship \ + is {ships} and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, \ + apply and vendor)." ), 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/maven.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs index b3fedee4c..1f02fbe68 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs @@ -1402,6 +1402,14 @@ fn the_users_own_override_of_the_artifact() { /// The warning of an agent run for an artifact that a pinned hub fetches: /// the command patches no hub. const HUB_UNPATCHED: &str = "maven_bazel_hub_unpatched"; +/// What an action statement says to run where hosted and vendored mode +/// write an entry for the hub: the package by its coordinates. +const RUN: &str = "Run `socket-patch get pkg:maven/dev.socket.fixture/victim@1.10.0 --mode \ + hosted` at the Bazel root to patch the hub, or with `--mode vendored` to \ + commit the patched jar."; +/// And what it says where they write none, before the code of their +/// warning and its reason. +const NO_ENTRY: &str = "Hosted and vendored mode write no entry for this hub"; impl Pinned { /// Without a Bazel: the checkout of [`Pinned::open`] beside a `pom.xml`, @@ -1435,22 +1443,20 @@ impl Pinned { flow } - /// What every document of a patch that is only in the installed jar - /// says, as its action statement and in the warning of its run: the - /// lock of the hub, the call and its line, the command of the two modes - /// that patch a pinned hub with what tells that it wrote no entry, and - /// the option for a repository that ships the installed tree. - fn affected(&self) -> Vec { + /// What every document of a patch that the hub does not take says, as + /// its action statement and in the warning of its run: the lock of the + /// hub, the call and its line, `remedy`, which is the command of the + /// two modes that patch a pinned hub ([`RUN`]) or why they write no + /// entry for this one, and the option for a repository that ships what + /// Maven or Gradle builds. + fn affected(&self, remedy: &str) -> Vec { let module = std::fs::read_to_string(self.cell.path(MODULE)).expect(MODULE); let call = module.lines().position(|line| line == "maven.install("); vec![format!( "Bazel builds this package from maven_install.json (`maven.install`, {MODULE}:{}), \ - which does not name Socket patch {}: the patch is only in the installed copy. Run \ - `socket-patch get {PURL} --mode hosted` at the Bazel root to patch the hub, or with \ - `--mode vendored` to commit the patched jar (a `maven_bazel_*` warning of that run \ - means that the Bazel build keeps the upstream jar). If what you ship is the \ - installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on \ - scan, apply and vendor).", + which does not name Socket patch {}: the patch is only in what Maven or Gradle \ + builds from. {remedy} If what you ship is what Maven or Gradle builds and not what \ + Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).", call.expect("the hub") + 1, self.patch.uuid )] @@ -1506,7 +1512,7 @@ fn an_agent_patch_beside_a_pinned_hub() { // (b) Agent mode patches the installed jar, and every document says // the artifact is affected. - let names = flow.affected(); + let names = flow.affected(RUN); let claim = Claim::unbuilt(PURL, &flow.patch.uuid, &names); let patched = flow.patches_the_installed_jar(&claim); @@ -1533,29 +1539,60 @@ fn an_agent_patch_beside_a_pinned_hub() { ); } +/// A second hub, which has no lock: what is not known of it leaves the hub +/// that fetches the jar as it is. +const MORE: &str = "maven.artifact(\n name = \"more\",\n artifact = \"gson\",\n group = \ + \"com.google.code.gson\",\n version = \"2.8.9\",\n)\n"; + /// Without a Bazel: step (b) of [`an_agent_patch_beside_a_pinned_hub`] in a /// checkout whose hub is pinned ([`Pinned::unbuilt`]). Then each of the two /// modes the document names, in a checkout of its own: the command pins or /// vendors the artifact for the Maven build and for the hub, with no /// warning about the hub, and `vex` says not affected, through that mode. /// -/// And each where the command writes no entry, in a checkout that names a -/// Bazel without `override_repo`: the documents of agent mode are the -/// same, and the command pins or vendors for the Maven build alone and -/// warns `maven_bazel_release`, which is what the action statement says to -/// look for. KNOWN LIMIT: `vex` then attests the Maven build's patch as -/// not affected although the hub still fetches the upstream jar, as it -/// does without the agent patch before it (the list of what is still wrong -/// in docs/ecosystems.md, "Bazel workspaces: VEX"). +/// And each where the command writes no entry: in a checkout that names a +/// Bazel without `override_repo`, and beside a second hub without a lock, +/// where `apply` warns that the hub stays unpatched all the same. There +/// the documents of agent mode say affected too, and name the code and +/// the reason of the command's warning in the place of the command. The +/// command then pins or vendors for the Maven build alone and gives that +/// warning, and `vex` still says affected, in the same words: the hub +/// fetches the upstream jar as before, whichever mode holds the patch. #[test] fn an_installed_jar_is_affected_beside_a_hub_that_fetches_its_own() { let modes = [("hosted", How::Hosted), ("vendored", How::Vendored)]; - let releases: [(&str, &[&str]); 2] = [("9.3.2", &[]), ("7.3.0", &["maven_bazel_release"])]; - let each = |(mode, how)| releases.map(|(bazel, declined)| (mode, how, bazel, declined)); - for (mode, how, bazel, declined) in modes.into_iter().flat_map(each) { + let old = "the checkout names Bazel 7.3.0 (`.bazeliskrc` or `.bazelversion`), and an entry \ + needs `override_repo`, which Bazel has from 7.4.0"; + let lockless = "hub \"more\" has no `lock_file`, so Bazel resolves its jars when it builds \ + and none can be replaced: give the hub a `lock_file` and pin it (`REPIN=1 \ + bazel run @more//:pin`)"; + // The file that differs, with what is added to it or put in its place, + // and the code and the reason with which the command then declines. + let checkouts = [ + (MODULE, "", None), + ( + ".bazelversion", + "7.3.0\n", + Some(("maven_bazel_release", old)), + ), + (MODULE, MORE, Some(("maven_bazel_not_pinned", lockless))), + ]; + let each = + |(mode, how)| checkouts.map(|(file, text, declined)| (mode, how, file, text, declined)); + for (mode, how, file, text, declined) in modes.into_iter().flat_map(each) { let flow = Pinned::unbuilt(); - flow.cell.write(".bazelversion", format!("{bazel}\n")); - let names = flow.affected(); + let module = std::fs::read_to_string(flow.cell.path(MODULE)).expect(MODULE); + match file { + MODULE => flow.cell.write(MODULE, format!("{module}{text}")), + _ => flow.cell.write(file, text), + } + // The reason names the place of a tag: the one added last. + let at = format!("{MODULE}:{}: ", module.lines().count() + 1); + let remedy = declined.map(|(code, why)| { + let at = if why.starts_with("hub ") { &at } else { "" }; + format!("{NO_ENTRY} (`{code}`): {at}{why}.") + }); + let names = flow.affected(remedy.as_deref().unwrap_or(RUN)); let claim = Claim::unbuilt(PURL, &flow.patch.uuid, &names); flow.patches_the_installed_jar(&claim); @@ -1565,26 +1602,35 @@ fn an_installed_jar_is_affected_beside_a_hub_that_fetches_its_own() { warned.retain(|code| code.starts_with("maven_bazel_")); let module = std::fs::read_to_string(flow.cell.path(MODULE)).expect(MODULE); let entry = module.contains(&format!("Socket patch {}", flow.patch.uuid)); - let expected = (declined.join(" "), declined.is_empty()); - assert_eq!((warned.join(" "), entry), expected, "{}", get.dump); + let code = declined.map_or("", |(code, _)| code); + assert_eq!( + (warned.join(" "), entry), + (code.to_string(), declined.is_none()), + "{}", + get.dump + ); let run = |cell: &Cell, args: &[&str]| flow.socket_patch_in(cell, &flow.standin, args); - flow.cell - .stands_alone(run, &Claim::new(PURL, &flow.patch.uuid, how), true); + let patched = Claim::new(PURL, &flow.patch.uuid, how); + let says = if declined.is_some() { &claim } else { &patched }; + flow.cell.stands_alone(run, says, true); } } /// Without a Bazel: what stays the statement of a project without Bazel /// while the patch is in the installed jar alone /// ([`Cell::keeps_its_statement`]). The hubs of which nothing is said: one -/// that has no lock, a pinned one beside one that has none, one with a -/// `maven.override` of the artifact, and one whose call may not run. And -/// what a person reads of an `apply` beside the hub that fetches the jar: -/// the warning and the count of the statement, and nothing under -/// `--silent`. +/// that has no lock, one with a `maven.override` of the artifact, and one +/// whose call may not run. So is the checkout that does not say that Bazel +/// reads `MODULE.bazel` as it stands: an rc file names the option that +/// switches Bzlmod off, for one `--config`; no release is named beside a +/// `WORKSPACE` file that defines a repository; the release named is one +/// before 7.0. And what a person reads of an `apply` beside the hub that +/// fetches the jar: the warning and the count of the statement, and +/// nothing under `--silent`. #[test] fn an_installed_jar_is_attested_where_no_hub_is_shown_to_fetch_its_own() { let flow = Pinned::unbuilt(); - let names = flow.affected(); + let names = flow.affected(RUN); let claim = Claim::unbuilt(PURL, &flow.patch.uuid, &names); flow.patches_the_installed_jar(&claim); @@ -1602,23 +1648,33 @@ fn an_installed_jar_is_attested_where_no_hub_is_shown_to_fetch_its_own() { .tells_a_person(&origin, &apply, &told, &document, &claim, &warned); } + let run = |cell: &Cell, args: &[&str]| flow.socket_patch_in(cell, &flow.standin, args); + let installed = Claim::new(PURL, &flow.patch.uuid, How::Agent); + let repository = "http_archive(name = \"zlib\", urls = [])\n"; + for (file, text, bazel) in [ + (".bazelrc", "build:legacy --noenable_bzlmod\n", "7.7.2\n"), + ("WORKSPACE", repository, "latest\n"), + ("WORKSPACE", "", "6.5.0\n"), + ] { + flow.cell.write(file, text); + flow.cell.write(".bazelversion", bazel); + flow.cell.stands_alone(run, &installed, true); + std::fs::remove_file(flow.cell.path(file)).expect(file); + } + flow.cell.write(".bazelversion", "9.3.2\n"); + let module = std::fs::read_to_string(flow.cell.path(MODULE)).expect(MODULE); let lock = " lock_file = \"//:maven_install.json\",\n"; - let more = "maven.artifact(\n name = \"more\",\n artifact = \"gson\",\n group = \ - \"com.google.code.gson\",\n version = \"2.8.9\",\n)\n"; let own = format!( "maven.override(\n name = \"{HUB}\",\n coordinates = \"{GROUP}:{VICTIM}\",\n \ target = \"//own:victim\",\n)\n" ); let undecided = [ module.replace(lock, ""), - format!("{module}{more}"), format!("{module}{own}"), module.replace("maven.install(", "ENABLED and maven.install("), ]; - let run = |cell: &Cell, args: &[&str]| flow.socket_patch_in(cell, &flow.standin, args); let gives = |args: &[&str], document: &Path| flow.cell.gives(&origin, args, &told, document); - let installed = Claim::new(PURL, &flow.patch.uuid, How::Agent); flow.cell .keeps_its_statement(run, gives, &installed, &undecided); } diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index 6b854082f..c66f66927 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -22,16 +22,15 @@ //! A sixth, rules_jvm_external, takes each jar that the lock of a hub pins //! (`maven.install`) at the lock's sha256: from a repository of the lock, //! or under `m2local` from the Maven local repository, where a jar that -//! agent mode patched no longer has that sha256. Its hubs are not in the -//! table below: [`super::maven`] reads them for hosted and vendored mode, -//! which patch a hub through a block of the root `MODULE.bazel` and not -//! through its lock, and the same reader answers here -//! ([`super::maven::upstream`]): for a jar patched in the installed copy, -//! whatever project of the workspace it was patched from, when every hub -//! was read and the block holds no entry for it. What counts as read is -//! that reader's to say, and the next paragraph is about the table alone: -//! a `WORKSPACE` file puts a Maven hub in doubt only by a `maven_install` -//! call that Bazel may read. +//! agent mode patched no longer has that sha256. It reads no `pom.xml` +//! and no Gradle file either. Its hubs are not in the table below: +//! [`super::maven`] reads them for hosted and vendored mode, which patch a +//! hub through a block of the root `MODULE.bazel` and not through its +//! lock, and the same reader answers here ([`super::maven::upstream`]): +//! for a Maven patch of any mode, whatever project of the workspace it is +//! in, when a pinned hub that was read fetches the jar and the block holds +//! no entry of that patch for it. What makes that uncertain is that +//! reader's to say, and the next paragraph is about the table alone. //! //! [`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 @@ -81,7 +80,7 @@ //! `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. +//! package that has one, but a Maven jar. //! //! Not looked at: what a `--override_repository` or an rc file changes, //! BUILD files, and hubs of other rulesets. @@ -120,7 +119,9 @@ pub struct Patched { /// `None`: the patch is in the copy a package manager installed. /// `Some`: it is a copy committed under `.socket/vendor`, and these /// files of the project point at it, each by its path from the project - /// with `/` between its parts. + /// with `/` between its parts. They decide nothing for a Maven jar, + /// which is asked about in every mode: no file of a project says what + /// a rules_jvm_external hub fetches. pub pins: Option>, } @@ -137,7 +138,8 @@ pub struct Unbuilt { /// 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`]; for a Maven jar the command names the package). + /// ([`Hub::remedy`]). For a Maven jar, the command that patches the + /// hub, or why none does ([`super::maven::upstream`]). pub remedy: String, } @@ -323,60 +325,53 @@ fn ecosystem(purl: &str) -> Option { /// Nothing is read for packages no hub is known for, nor outside a Bazel /// workspace ([`super::bazel_root`], whose bounds these are). pub async fn unbuilt(project: &Path, packages: Vec) -> Vec> { - let hub = |package: &Patched| { - let of = ecosystem(&package.purl); - let known = |hub: &Hub| of.as_deref() == Some(hub.ecosystem); - of.as_deref() == Some("maven") || HUBS.iter().any(known) - }; - if !packages.iter().any(hub) { + let of = |package: &Patched| ecosystem(&package.purl); + let known = |of: Option| HUBS.iter().any(|hub| of.as_deref() == Some(hub.ecosystem)); + let maven = |package: &Patched| of(package).as_deref() == Some("maven"); + // The table's reader is not asked for a run of Maven jars alone. + let table = packages.iter().any(|package| known(of(package))); + if !table && !packages.iter().any(maven) { return vec![None; packages.len()]; } let project = project.to_path_buf(); run_blocking(move || { + let mut found = vec![None; packages.len()]; let Some(root) = super::bazel_root(&project) else { - return vec![None; packages.len()]; + return found; }; - let workspace = Workspace::read(&disk(&root.dir)); - let read = |file: &str| lock_text(&root.dir, file); - // Bazel has `/` between the parts of a path on every system. - let parts = root.project.components(); - let parts: Vec<_> = parts - .map(|part| part.as_os_str().to_string_lossy()) - .collect(); - let mut found = judge(&workspace, &parts.join("/"), &read, &packages); + if table { + let workspace = Workspace::read(&disk(&root.dir)); + let read = |file: &str| lock_text(&root.dir, file); + // Bazel has `/` between the parts of a path on every system. + let parts = root.project.components(); + let parts: Vec<_> = parts + .map(|part| part.as_os_str().to_string_lossy()) + .collect(); + found = judge(&workspace, &parts.join("/"), &read, &packages); + } jars(&root.dir, &packages, &mut found); found }) .await } -/// [`unbuilt`] for the Maven jars among `packages` that are patched in an -/// installed copy, in the workspace at `root`: into `found`, the -/// `maven.install` of the pinned hub that fetches the upstream jar -/// ([`super::maven::upstream`]), with the command that patches such a hub. -/// A flow builds it patched on real Bazel in hosted and in vendored mode. -/// That command writes no entry where it cannot show that one works (an -/// older Bazel, an rc file, a jar of the Maven local repository) and then -/// warns with a code of [`super::maven`]. The remedy says so, because the -/// pin such a run leaves in a `pom.xml` is attested all the same. +/// [`unbuilt`] for the Maven jars among `packages`, in the workspace at +/// `root`, whichever mode patched them: into `found`, the `maven.install` +/// of the pinned hub that fetches the upstream jar, and what +/// [`super::maven::upstream`] says to do about it. A flow builds the hub +/// patched on real Bazel after the command it names, in hosted and in +/// vendored mode. fn jars(root: &Path, packages: &[Patched], found: &mut [Option]) { - let installed = |at: &usize| packages[*at].pins.is_none(); - let installed: Vec = (0..packages.len()).filter(installed).collect(); - let purls: Vec<&str> = installed.iter().map(|at| &*packages[*at].purl).collect(); - let hubs = super::maven::upstream(root, &purls); - for (at, hub) in installed.into_iter().zip(hubs) { - let Some(hub) = hub else { continue }; - let purl = &packages[at].purl; - found[at] = Some(Unbuilt { - call: "maven.install".to_string(), + let patches: Vec<_> = packages.iter().map(|p| (&*p.purl, &*p.uuid)).collect(); + let hubs = super::maven::upstream(root, &patches); + for (found, hub) in found.iter_mut().zip(hubs) { + let Some((hub, remedy)) = hub else { continue }; + *found = Some(Unbuilt { + call: super::maven::INSTALL.to_string(), file: hub.file, line: hub.line, lock: hub.lock.unwrap_or_default(), - remedy: format!( - "Run `socket-patch get {purl} --mode hosted` at the Bazel root to patch the \ - hub, or with `--mode vendored` to commit the patched jar (a `maven_bazel_*` \ - warning of that run means that the Bazel build keeps the upstream jar)." - ), + remedy, }); } } @@ -1406,22 +1401,34 @@ replace = "swapped 3.0.0" assert_eq!(unbuilt(&root.join("api"), vendored).await, [None]); } - /// A Maven jar that is patched in the installed copy, in a project of a - /// workspace whose pinned hub fetches that jar: the `maven.install` and - /// the lock of the hub, with the command of the two modes that patch - /// it, which names the package, and what tells that the command wrote - /// no entry. Nothing for a committed copy, which - /// vendored mode gives the hub, nor once the block holds the jar's - /// entry. + /// A Maven jar in a project of a workspace whose pinned hub fetches + /// that jar, patched in the installed copy or in a copy committed for + /// a Maven build: the `maven.install` and the lock of the hub, with + /// the command of the two modes that patch it, which names the jar. + /// Nothing once the block holds the entry of the patch. A `WORKSPACE` + /// file that defines another repository, beside which nothing is said + /// of a package of the table, changes nothing for the jar while the + /// checkout names a Bazel that reads `MODULE.bazel`. #[tokio::test] - async fn an_installed_jar_is_not_what_a_pinned_hub_fetches() { + async fn a_maven_jar_is_not_what_a_pinned_hub_fetches() { let [module, lock, patched] = super::super::maven::tests::sample(UUID); let tmp = tempfile::tempdir().unwrap(); let root = std::fs::canonicalize(tmp.path()).unwrap(); std::fs::create_dir_all(root.join(".git")).unwrap(); std::fs::create_dir_all(root.join("services/billing")).unwrap(); - std::fs::write(root.join("MODULE.bazel"), module).unwrap(); - std::fs::write(root.join("maven_install.json"), lock).unwrap(); + let selected = "https://bcr.bazel.build/modules/rules_jvm_external/7.2/source.json"; + let selected = format!( + "{{\"lockFileVersion\": 13, \"registryFileHashes\": {{\"{selected}\": \"0\"}}}}" + ); + for (file, text) in [ + ("MODULE.bazel", module.as_str()), + ("maven_install.json", &lock), + ("MODULE.bazel.lock", &selected), + (".bazelversion", "7.7.2\n"), + ("WORKSPACE", "http_archive(name = \"zlib\", urls = [])\n"), + ] { + std::fs::write(root.join(file), text).unwrap(); + } let netty = "pkg:maven/io.netty/netty-tcnative-classes@2.0.61.Final"; let package = |pins: Option>| Patched { purl: netty.to_string(), @@ -1436,13 +1443,13 @@ replace = "swapped 3.0.0" lock: "maven_install.json".to_string(), remedy: format!( "Run `socket-patch get {netty} --mode hosted` at the Bazel root to patch the \ - hub, or with `--mode vendored` to commit the patched jar (a `maven_bazel_*` \ - warning of that run means that the Bazel build keeps the upstream jar)." + hub, or with `--mode vendored` to commit the patched jar." ), }; for project in ["", "services/billing"] { let found = unbuilt(&root.join(project), packages.clone()).await; - assert_eq!(found, [Some(fetched.clone()), None], "{project}"); + let jars = [Some(fetched.clone()), Some(fetched.clone())]; + assert_eq!(found, jars, "{project}"); } std::fs::write(root.join("MODULE.bazel"), patched).unwrap(); assert_eq!(unbuilt(&root, packages).await, [None, None]); diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 3b4cb09ee..12e49b88d 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -143,6 +143,9 @@ const MAX_LOCKS: usize = 4 * MAX_LOCK; /// `override` and `amend_artifact`, make no hub. const MAKE_A_HUB: [&str; 3] = ["install", "artifact", "from_toml"]; +/// The tag that pins a hub, as a warning and an action statement name it. +pub const INSTALL: &str = "maven.install"; + /// A hub of the root module. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Hub { @@ -487,6 +490,9 @@ pub struct Hubs { /// or a `maven_install.json` lies at the root. In another workspace a /// doubt is about no hub ([`hub_jars`]). ruleset: bool, + /// Whether a `WORKSPACE` file of the root defines anything + /// ([`Workspace::legacy`]), which is what a Bazel before 7.0 builds. + legacy: bool, } impl Hubs { @@ -600,7 +606,7 @@ impl Hubs { .files .iter() .any(|(_, file)| file.calls.iter().any(names)); - let calls = matches!(ws.legacy, Some(Ok(_))); + let (calls, defined) = (matches!(ws.legacy, Some(Ok(_))), ws.legacy.is_some()); let before_9 = || declared_release(view).is_none_or(|release| release < (9, 0, 0)); let legacy = match ws.legacy.filter(|_| before_9()) { Some(Ok((file, read))) => { @@ -634,6 +640,7 @@ impl Hubs { edited, asked, ruleset, + legacy: defined, } } @@ -675,13 +682,14 @@ impl Hubs { } } - /// Whether the block holds an entry for the jar of `group:artifact` at - /// `version`: Bazel takes that entry's jar in the place of a hub's. - fn patches(&self, group: &str, artifact: &str, version: &str) -> bool { - let jar = |patch: &Patch| { + /// The id of the patch whose entry the block holds for the jar of + /// `group:artifact` at `version`: where the block is in effect, Bazel + /// takes that entry's jar in the place of a hub's. + fn held(&self, group: &str, artifact: &str, version: &str) -> Option<&str> { + let jar = |patch: &&Patch| { (&*patch.group, &*patch.artifact, &*patch.version) == (group, artifact, version) }; - self.block.iter().any(jar) + self.block.iter().find(jar).map(|patch| &*patch.uuid) } } @@ -1373,10 +1381,7 @@ fn verdicts( all.clone().map(|()| label) }), }; - let jar = |patch: &&Patch| { - (&patch.group, &patch.artifact, &patch.version) == (group, artifact, version) - }; - let held = hubs.block.iter().find(jar).map(|patch| patch.uuid.clone()); + let held = hubs.held(group, artifact, version).map(str::to_string); site.push((uuid.clone(), entry, held)); } site @@ -1685,20 +1690,20 @@ fn notices_blocking( let (code, detail) = match hubs.built(&group, &artifact, &version) { Built::No => continue, // Bazel takes the jar of the block's entry. - Built::Yes(_) if hubs.patches(&group, &artifact, &version) => continue, + Built::Yes(_) if hubs.held(&group, &artifact, &version).is_some() => continue, Built::Yes(by) => { let from = |(hub, _): &(&Hub, &Pinned)| { let (lock, name) = (hub.lock.as_deref().unwrap_or_default(), &hub.name); let (file, line) = (&hub.file, hub.line); - format!("{lock} (hub \"{name}\", `maven.install` at {file}:{line})") + format!("{lock} (hub \"{name}\", `{INSTALL}` at {file}:{line})") }; let from = by.iter().map(from).collect::>().join(" and "); let detail = format!( "Bazel takes this artifact from {from}, which pins the upstream jar, and \ this command does not patch a rules_jvm_external hub: the Bazel build \ - stays unpatched whatever it did for another build of the checkout. \ - `socket-patch get {purl} --mode hosted` at the Bazel root patches a \ - pinned hub" + stays unpatched whatever it did for another build of the checkout. {} \ + patches a pinned hub", + command(&group, &artifact, &version) ); (HUB_UNPATCHED, detail) } @@ -1717,33 +1722,92 @@ fn notices_blocking( said } -/// For each of `purls`, patched in the copy a build tool installed: the -/// pinned hub of the workspace at the Bazel root `root` that fetches the -/// plain jar of that artifact at that version, the first of them. Bazel -/// then takes the jar at the sha256 the lock of that hub pins: from a -/// repository, or under `m2local` from the Maven local repository, where -/// the patched jar is not one of that sha256. The lock's sha256 is not +/// The command of hosted mode that patches a pinned hub, as a warning and +/// an action statement name it: by the coordinates of the jar, without +/// what a purl may carry after them (`?type=jar`), which a shell reads. +fn command(group: &str, artifact: &str, version: &str) -> String { + let purl = build_maven_purl(group, artifact, version); + format!("`socket-patch get {purl} --mode hosted` at the Bazel root") +} + +/// For each of `patches`, the purl of a Maven jar and the id of its patch, +/// whichever mode recorded it (the jar a build tool installed, a pin or a +/// vendored copy of a Maven or Gradle build): the pinned hub of the +/// workspace at the Bazel root `root` that fetches the plain jar of that +/// artifact at that version, the first of them, and what to do about it. +/// Bazel then takes the jar at the sha256 the lock of that hub pins: from +/// a repository, or under `m2local` from the Maven local repository, where +/// a patched jar is not one of that sha256. The lock's sha256 is not /// compared with the patch: a lock that pins the patched jar's bytes is -/// read as any other. It is said only when it is certain: every hub was -/// read ([`Hubs::sure`]), and the block holds no entry for the jar, which -/// Bazel would take in its place. `None` otherwise, and for what is no -/// plain jar of a Maven artifact; without one among `purls` nothing is -/// read. -pub fn upstream(root: &Path, purls: &[&str]) -> Vec> { +/// read as any other. +/// +/// It is said only when it is certain of that hub, whatever is not known +/// of another one: the hub and its lock were read and no `maven.override` +/// names the artifact ([`Hubs::built`]), the block was not changed by +/// hand, and it holds no entry of this patch for the jar. `None` +/// otherwise, and where the checkout does not say that Bazel reads +/// `MODULE.bazel` as it stands: it names a Bazel before 7.0, or none +/// while a `WORKSPACE` file defines something, or an rc file names an +/// option that switches Bzlmod off or drops tags of the root (on whatever +/// line: it may hold for one `--config` alone), or cannot be read. `None` +/// too for what is no plain jar of a Maven artifact; without one among +/// `patches` nothing is read. +/// +/// What to do is the command that writes an entry for the jar at the +/// root, or why hosted and vendored mode write none there, with the code +/// and in the words of their warning ([`verdicts`]). The entry of another +/// patch is named first: Bazel takes that one's jar until the command has +/// put this one's in its place. +pub fn upstream(root: &Path, patches: &[(&str, &str)]) -> Vec> { let jar = |purl| parse_maven_purl(purl).filter(|_| plain(purl)); - let jars: Vec<_> = purls.iter().copied().map(jar).collect(); + let jars: Vec<_> = patches.iter().map(|&(purl, _)| jar(purl)).collect(); + let none = || vec![None; patches.len()]; if jars.iter().all(Option::is_none) { - return vec![None; purls.len()]; + return none(); + } + let (view, locks) = (disk(root), disk_up_to(root, MAX_LOCK)); + let hubs = Hubs::read(&view, &locks); + let release = declared_release(&view); + let read = release.map_or(!hubs.legacy, |release| release >= (7, 0, 0)); + let off = || rc(&view, release).iter().any(|(code, _)| *code != DOWNLOAD); + if hubs.pinned.is_empty() || hubs.edited.is_some() || !read || off() { + return none(); } - let hubs = Hubs::read(&disk(root), &disk_up_to(root, MAX_LOCK)); - let fetched = jars.into_iter().map(|jar| { + // What holds for every jar is asked once, as for a run that writes. + let mut workspace = None; + let fetched = jars.into_iter().zip(patches).map(|(jar, (_, uuid))| { let (group, artifact, version) = jar?; - let Built::Yes(by) = hubs.sure(&group, &artifact, &version) else { + let Built::Yes(by) = hubs.built(&group, &artifact, &version) else { return None; }; - let patched = hubs.patches(&group, &artifact, &version); - let hub = by.first().filter(|_| !patched); - hub.map(|(hub, _)| (*hub).clone()) + let held = hubs.held(&group, &artifact, &version); + if held == Some(*uuid) { + return None; + } + let entry = match hubs.sure(&group, &artifact, &version) { + Built::Unknown(doubt, kind) => Err(unknown(doubt, kind)), + _ => hubs.label(&group, &artifact, &version).and_then(|_| { + let all = || settings(root, &view, &locks, &hubs.asked, true); + workspace.get_or_insert_with(all).clone() + }), + }; + let other = held.map_or_else(String::new, |held| { + format!( + "{FILE} holds the entry of patch {held} for this jar, and where the block is \ + in effect the Bazel build takes that patch's jar. " + ) + }); + let remedy = match entry { + Ok(()) => format!( + "{other}Run {} to patch the hub, or with `--mode vendored` to commit the \ + patched jar.", + command(&group, &artifact, &version) + ), + Err((code, why)) => format!( + "{other}Hosted and vendored mode write no entry for this hub (`{code}`): {why}." + ), + }; + Some((by[0].0.clone(), remedy)) }); fetched.collect() } @@ -2582,30 +2646,57 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") assert_eq!(notices_blocking(broken.path(), Vec::new()), []); } - /// [`upstream`] names the hub of an installed jar only where that is - /// certain: a pinned hub fetches the plain jar at that version, every - /// hub was read, and the block holds no entry for the jar. + /// [`upstream`] names the hub of a patched jar only where that is + /// certain of the hub: a pinned hub that was read fetches the plain jar + /// at that version, the block was not changed by hand and holds no + /// entry of the patch, and nothing of the checkout says that Bazel may + /// pass over `MODULE.bazel`. With the hub it says what to do: the + /// command that writes the entry, or why no mode writes one. #[test] fn an_installed_jar_is_upstream_where_a_pinned_hub_surely_fetches_it() { - let [_, lock, patched] = sample("7a11e000-0000-4000-8000-0000000000b1"); - let said = |module: &str, more: &[(&str, &str)], purl: &str| { - let pinned = [("MODULE.bazel", module), ("maven_install.json", &lock)]; - let dir = project(&[&pinned[..], more].concat()); - let hub = |hub: Hub| { + let uuid = "7a11e000-0000-4000-8000-0000000000b1"; + let [_, lock, patched] = sample(uuid); + // In a checkout where a run may write, with `files`: the hub of + // `purl`, patched by `uuid`, and what to do. + let said = |files: &[(&str, &str)], purl: &str| { + let dir = checkout(files); + let patches = [("pkg:npm/left-pad@1.3.0", uuid), (purl, uuid)]; + let mut found = upstream(dir.path(), &patches); + assert_eq!((found.len(), &found[0]), (2, &None), "{purl}"); + let (hub, remedy) = found.remove(1).unzip(); + let hub = hub.map(|hub: Hub| { let lock = hub.lock.unwrap_or_default(); format!("{} {}:{} {lock}", hub.name, hub.file, hub.line) - }; - let found = upstream(dir.path(), &["pkg:npm/left-pad@1.3.0", purl]); - assert_eq!((found.len(), &found[0]), (2, &None), "{purl}"); - found[1].clone().map(hub).unwrap_or_default() + }); + (hub.unwrap_or_default(), remedy.unwrap_or_default()) }; - let fetched = "maven MODULE.bazel:4 maven_install.json"; - assert_eq!(said(PINNED, &[], NETTY_PURL), fetched); - // Also a jar that no repository of the lock lists: under `m2local` - // the hub takes it from the Maven local repository, at that sha256. - let local = lock.replace("\"repositories\"", "\"m2local\": true, \"mirrors\""); - let local = [("maven_install.json", local.as_str())]; - assert_eq!(said(PINNED, &local, NETTY_PURL), fetched); + let hub = "maven MODULE.bazel:4 maven_install.json"; + let run = format!( + "Run `socket-patch get {NETTY_PURL} --mode hosted` at the Bazel root to patch the \ + hub, or with `--mode vendored` to commit the patched jar." + ); + let fetched = (hub.to_string(), run.clone()); + let nothing = (String::new(), String::new()); + // The hub, where hosted and vendored mode write no entry for it: + // the code of their warning, and how its reason ends. + let declined = |files: &[(&str, &str)], code: &str, ends: &str| { + let (found, remedy) = said(files, NETTY_PURL); + let begins = + format!("Hosted and vendored mode write no entry for this hub (`{code}`): "); + let whole = remedy.starts_with(&begins) && remedy.ends_with(&format!("{ends}.")); + assert!(found == hub && whole, "{files:?}: {found:?} {remedy:?}"); + }; + assert_eq!(said(&[], NETTY_PURL), fetched); + // The command names the jar by its coordinates: nothing of what a + // purl carries after them, which a shell would read, is in it. + let qualified = format!("{NETTY_PURL}?type=jar&repository_url=x"); + assert_eq!(said(&[], &qualified), fetched); + // The warning of an agent run names the same command. + let warned = notices_blocking(checkout(&[]).path(), vec![qualified.clone()]); + let command = run.split(" to patch").next().expect("the command"); + let command = command.trim_start_matches("Run "); + let names = |(_, detail): &(_, String)| detail.contains(&format!("{command} patches")); + assert!(warned.len() == 1 && names(&warned[0]), "{warned:?}"); // Not another version, a classifier or a packaging of the jar. let others = [ NETTY_PURL.replace("61", "62"), @@ -2613,34 +2704,92 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") format!("{NETTY_PURL}?type=aar"), ]; for purl in others { - assert_eq!(said(PINNED, &[], &purl), "", "{purl}"); + assert_eq!(said(&[], &purl), nothing, "{purl}"); + } + // Also a jar that no repository of the lock lists: under `m2local` + // the hub takes it from the Maven local repository, at that sha256, + // and no entry can take its place. + let local = lock.replace("\"repositories\"", "\"m2local\": true, \"mirrors\""); + let local = [("maven_install.json", local.as_str())]; + declined( + &local, + ARTIFACT, + "there is no repository for an entry to replace", + ); + // The block's entry of the patch is the jar Bazel takes, and a + // block that was changed by hand may hold one. The entry of another + // patch is not this one's: it is named, and the command replaces + // it. An entry for another version is the entry of another jar. + fn module(text: &str) -> [(&str, &str); 1] { + [("MODULE.bazel", text)] } - // The block's entry is the jar Bazel takes, and a block that was - // changed by hand may hold one. An entry for another version of - // the artifact is the entry of another jar. - assert_eq!(said(&patched, &[], NETTY_PURL), ""); + assert_eq!(said(&module(&patched), NETTY_PURL), nothing); let by_hand = patched.replace("# Do not change", "# Do change"); - assert_eq!(said(&by_hand, &[], NETTY_PURL), ""); - let mut earlier = patch("netty-tcnative-classes", OTHER_UUID); + assert_eq!(said(&module(&by_hand), NETTY_PURL), nothing); + let another = patch("netty-tcnative-classes", OTHER_UUID); + let another = with_patch(PINNED, LABEL, another).expect("a block"); + let names = format!( + "MODULE.bazel holds the entry of patch {OTHER_UUID} for this jar, and where the \ + block is in effect the Bazel build takes that patch's jar. {run}" + ); + let replaced = (hub.to_string(), names); + assert_eq!(said(&module(&another), NETTY_PURL), replaced); + let mut earlier = patch("netty-tcnative-classes", uuid); earlier.version = "2.0.60.Final".to_string(); let earlier = with_patch(PINNED, LABEL, earlier).expect("a block"); - assert_eq!(said(&earlier, &[], NETTY_PURL), fetched); - // Beside the hub that fetches the jar: a hub without a lock, an - // override of the jar, and a `WORKSPACE` file that Bazel may read. + assert_eq!(said(&module(&earlier), NETTY_PURL), fetched); + // What is not known of another hub leaves this one as it is, and + // says why no entry is written: a hub without a lock, and a + // `maven_install` of a `WORKSPACE` file that Bazel 7 reads. An + // override of the jar is about this hub. let lockless = "maven.artifact(name = 'more', artifact = 'a', group = 'g', version = '1')"; let over = "maven.override(coordinates = 'io.netty:netty-tcnative-classes', target = ':a')"; - for more in [lockless, over] { - let module = format!("{PINNED}{more}\n"); - assert_eq!(said(&module, &[], NETTY_PURL), "", "{more}"); - } + let [lockless, over] = [lockless, over].map(|more| format!("{PINNED}{more}\n")); + declined( + &module(&lockless), + NOT_PINNED, + "(`REPIN=1 bazel run @more//:pin`)", + ); + assert_eq!(said(&module(&over), NETTY_PURL), nothing); + let (bazel_6, bazel_7) = ((".bazelversion", "6.5.0\n"), (".bazelversion", "7.7.2\n")); + let bazel_9 = (".bazelversion", "9.3.2\n"); let legacy = ("WORKSPACE", "maven_install(artifacts = [])\n"); - assert_eq!(said(PINNED, &[legacy], NETTY_PURL), ""); - let bazel_9 = [legacy, (".bazelversion", "9.3.2\n")]; - assert_eq!(said(PINNED, &bazel_9, NETTY_PURL), fetched); - // A `WORKSPACE` file that defines another repository is about no - // hub, whatever Bazel reads it. + let not_read = "WORKSPACE:1: a `maven_install` of a WORKSPACE file is not read"; + declined(&[legacy, bazel_7], UNREADABLE, not_read); + assert_eq!(said(&[legacy, bazel_9], NETTY_PURL), fetched); + // Nothing where the checkout does not say that Bazel reads + // `MODULE.bazel`: it names a Bazel before 7.0, or none beside a + // `WORKSPACE` file that defines anything. let other = ("WORKSPACE", "http_archive(name = 'zlib', urls = [])\n"); - assert_eq!(said(PINNED, &[other], NETTY_PURL), fetched); + assert_eq!(said(&[bazel_6], NETTY_PURL), nothing); + for file in [legacy, other] { + assert_eq!(said(&[file], NETTY_PURL), nothing, "{file:?}"); + } + assert_eq!(said(&[other, bazel_7], NETTY_PURL), fetched); + // Nor where an rc file names an option that switches Bzlmod off or + // drops tags of the root, on whatever line, or cannot be read: + // with it the hub, and an entry of the block, may be out of the + // build. An option about downloads leaves the hub as it is. + let unread = [ + (".bazelrc", "import %workspace%/ci.bazelrc\n"), + ("ci.bazelrc/a", ""), + ]; + let rc = |text: &'static str| [(".bazelrc", text), bazel_7]; + for files in [ + &rc("build:legacy --noenable_bzlmod\n")[..], + &rc("common --ignore_dev_dependency\n"), + &unread, + ] { + assert_eq!(said(files, NETTY_PURL), nothing, "{files:?}"); + } + let offline = rc("build --repository_disable_download\n"); + assert_eq!(said(&offline, NETTY_PURL), fetched); + // A Bazel without `override_repo`, and a hub on a usage that no + // entry reaches: the hub fetches the jar, and no mode patches it. + let old = [(".bazelversion", "7.3.0\n")]; + declined(&old, RELEASE, "which Bazel has from 7.4.0"); + let isolated = PINNED.replace("\"maven\")", "\"maven\", isolate = True)"); + declined(&module(&isolated), UNREADABLE, "reaches"); } /// What the warning for a hub that was not read says after where and diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 8979ef1f0..1436d28de 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2180,8 +2180,8 @@ exits 0 and leaves a build that fails (the known problems below). What a cell sa document on a machine whose NuGet folder still holds the unpatched package (the last list below). For Maven, [Bazel workspaces: Maven](#bazel-workspaces-maven) says what `vex` checks of the hub before - it attests an entry, and that it attests a patch that only the Maven or Gradle build - holds. + it attests an entry, and that it says `affected` of a patch that only a Maven or Gradle + build holds while a pinned hub fetches the jar. - **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. It does not say `affected` of a @@ -2784,15 +2784,19 @@ artifact: - Nothing is said for a jar the block patches, under `--global`, and by a `vendor` whose `--ecosystems` leaves Maven out. -`socket-patch vex` and `--vex` say `affected` of an artifact that agent mode patched in an -installed jar while a pinned hub fetches the jar at that version and the block holds no -entry for it: the statement names the lock, the `maven.install` and its line, and the -command of hosted and of vendored mode that patches the hub -([Bazel workspaces: VEX](#bazel-workspaces-vex)). It says so only when every hub was read. -Where one was not, the statement stays `not_affected`, as without Bazel, also beside the -first warning above. The command it names patches the hub only where it writes an entry: -where it gives a code of the table above instead, the hub stays as it is, and the statement -of the pin that the command left in the `pom.xml` is `not_affected` (the last limit below). +`socket-patch vex` and `--vex` say `affected` of an artifact whose patch the hub does not +take, whichever mode holds it: an installed jar that agent mode patched, a pin of a +`pom.xml` or a Gradle file, a copy vendored for such a build, while a pinned hub fetches +the jar at that version and the block holds no entry of that patch for it. The statement +names the lock, the `maven.install` and its line, and the command of hosted and of vendored +mode that patches the hub or, where those modes write no entry, the code of the table above +with its reason ([Bazel workspaces: VEX](#bazel-workspaces-vex)). So the document after a +command that gave such a code still says `affected`. It is about the hub that fetches the +jar, also beside another hub that was not read, where the first warning above is given. +It stays `not_affected`, as without Bazel, where that hub is in doubt (an override of the +artifact, a block that was changed by hand) and where the checkout does not say that Bazel +reads `MODULE.bazel` as it stands (a Bazel before 7.0, a `WORKSPACE` file beside no named +release, an rc file that names `enable_bzlmod` or `--ignore_dev_dependency`). The Bazel release is the one that `.bazeliskrc` (`USE_BAZEL_VERSION`) or else `.bazelversion` at the Bazel root names, read as bazelisk reads them: the last `USE_BAZEL_VERSION` line counts, @@ -2847,10 +2851,10 @@ Limits: that only Bazel builds that is `package_not_installed`. A vendored `get` of a jar that no hub builds there fails with `vendor_jvm_shape_unsupported`, as before. So does a `vendor` that is refused before it vendors anything (a ledger that cannot be read, or one that git ignores). -- `socket-patch vex` looks at the hub for the block's entries and for a jar that agent mode - patched (above): a patch that only a `pom.xml` or Gradle pin, or the vendored tree of - such a build, attests is attested, although the Bazel build does not have it. That is the - state a hosted or vendored command leaves where it writes no entry for the hub. +- `socket-patch vex` holds every Maven patch to the hubs (above), and a `maven_install.json` + names no project. So a project of the workspace that Maven or Gradle builds and Bazel + does not gets `affected` too, beside a hub that pins the same artifact at the same + version. `--no-bazel` is for the repository that ships what Maven or Gradle builds. ## Bazel workspaces: Cargo @@ -4330,17 +4334,32 @@ patched: 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 patch in an installed jar** (agent mode) of a Maven artifact, when a pinned hub (the - `maven.install` tags of one name, with a `lock_file`) fetches the plain jar of that - artifact at that version, and the block that hosted and vendored mode keep in the root - `MODULE.bazel` holds no entry for the jar. The lock of a hub is no project's own, and no - `pom.xml` or Gradle file decides what a hub fetches: the statement is the same from every - project of the workspace, whichever build tool installed the jar. The hubs are read as - [Bazel workspaces: Maven](#bazel-workspaces-maven) says, and every hub has to be read: - beside a hub without a `lock_file`, a tag or a lock that cannot be read, a - `maven.override` of the artifact, a `maven_install` of a `WORKSPACE` file that Bazel may - read or a block that was changed by hand, the statement stays `not_affected`, also where - `apply` warns `maven_bazel_hub_unpatched`. +- **A patch of a Maven artifact, in any mode**, when a pinned hub (the `maven.install` tags + of one name, with a `lock_file`) fetches the plain jar of that artifact at that version, + and the block that hosted and vendored mode keep in the root `MODULE.bazel` holds no + entry of that patch for the jar. The patch is then in an installed jar (agent mode), in a + pin of a `pom.xml` or a Gradle file (hosted mode) or in a copy vendored for such a build, + and in none of them for Bazel: the lock of a hub is no project's own, and no `pom.xml` or + Gradle file decides what a hub fetches. So the statement is the same from every project + of the workspace, whichever build tool installed the jar and whichever mode holds the + patch, and it is still the statement after a hosted or vendored command that wrote no + entry for the hub (the `maven_bazel_*` warnings). + The hubs are read as [Bazel workspaces: Maven](#bazel-workspaces-maven) says, and the + statement is about the hub that fetches the jar, whatever is not known of another one: + beside a second hub without a `lock_file`, another hub's lock that cannot be read or a + `maven_install` of a `WORKSPACE` file, it is `affected`, as `apply` warns + `maven_bazel_hub_unpatched` there. It stays `not_affected` where that hub itself is in + doubt: its tags or its lock cannot be read, a `maven.override` names the artifact, or the + block was changed by hand and may hold an entry. It stays so too where the checkout does + not say that Bazel reads `MODULE.bazel` as it stands: `.bazeliskrc` or `.bazelversion` + names a Bazel before 7.0; neither names a release while a `WORKSPACE` file defines a + repository; or an rc file of the checkout names `enable_bzlmod` other than switched on + (while the checkout names no Bazel 9 or later) or `--ignore_dev_dependency` without + switching it off, or cannot be read. Such an option counts on whatever line, so it may + hold for one `--config` alone, and where it holds the hub, like an entry of the block, + may be out of the build: neither is certain. + The entry of another patch for the same jar is not this patch's: the statement is + `affected`, and names that entry. A jar that a hub takes from the Maven local repository under `m2local` counts as fetched: the hub holds that file to the lock's sha256, which the patched jar does not have (read from the ruleset's source at 7.2 and 6.5; no test builds it). The sha256 of the lock is @@ -4398,29 +4417,47 @@ A test without Bazel runs each of those scans after agent mode, and the document `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. -For a Maven artifact the action statement names the command of the two modes that patch a -pinned hub. It names the package, and it runs at the Bazel root, where the patch of a hub is -written: +For a Maven artifact the statement is one for every mode, so it says where the patch is and +what a repository beside the hub ships in words that hold for each: ``` -Run `socket-patch get pkg:maven//@ --mode hosted` at the Bazel root to patch the hub, or with `--mode vendored` to commit the patched jar (a `maven_bazel_*` warning of that run means that the Bazel build keeps the upstream jar). +Bazel builds this package from maven_install.json (`maven.install`, MODULE.bazel:22), which does not name Socket patch 7a11e000-...: the patch is only in what Maven or Gradle builds from. Run `socket-patch get pkg:maven//@ --mode hosted` at the Bazel root to patch the hub, or with `--mode vendored` to commit the patched jar. If what you ship is what Maven or Gradle builds and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor). ``` -The words in brackets are a condition of the command. It writes its entry for the hub only -where it can show from the checkout that the entry works: Bazel 7.4.0 or later, a known -release of the ruleset, no rc file that switches the entry off, a jar that a repository of -the lock lists, a hub on a `use_extension` that is not isolated (the table of codes in -[Bazel workspaces: Maven](#bazel-workspaces-maven)). Where it cannot, it gives a -`maven_bazel_*` warning, and beside a `pom.xml` or a Gradle build it exits 0 and has still -pinned or vendored the patch for that build. `vex` then attests that patch and says -`not_affected`, which is wrong for the Bazel build: the hub fetches the upstream jar as -before (the list at the end of this section). Read the warnings of the command before you -trust the next document. +The command is the one of the two modes that patch a pinned hub. It runs at the Bazel root, +where the patch of a hub is written, and it names the package by its group, artifact and +version alone: nothing of what a purl can carry after them (`?type=jar`), which a shell +would read. + +That command writes its entry only where it can show from the checkout that the entry +works: Bazel 7.4.0 or later, a known release of the ruleset, a jar that a repository of the +lock lists, a hub on a `use_extension` that is not isolated, no hub of the workspace that +was not read (the table of codes in [Bazel workspaces: Maven](#bazel-workspaces-maven)). +The statement is written by the same reader, so where the command would decline it names no +command. It says why, with the code and the reason of the warning that the command would +give: + +``` +Hosted and vendored mode write no entry for this hub (`maven_bazel_release`): the checkout names Bazel 7.3.0 (`.bazeliskrc` or `.bazelversion`), and an entry needs `override_repo`, which Bazel has from 7.4.0. +``` + +The reasons are those of vendored mode. Where only the hosted command declines, because an +rc file names an option about downloads (`maven_bazel_download`), the statement names the +command, which writes the entry with `--mode vendored`. When the block holds the entry of +another patch for the jar, the statement says so first, in the words of that warning +("MODULE.bazel holds the entry of patch for this jar, and where the block is in effect +the Bazel build takes that patch's jar"); the command puts its entry in that one's place. + +A command that declines still pins or vendors the patch for a `pom.xml` or a Gradle build +beside the hub, and exits 0. The next document says `affected` all the same: the patch is +judged against the hub whichever mode holds it. A test without Bazel runs each of the two after agent mode. Where the command writes its entry it gives no such warning, and `vex` then says `not_affected`. In a checkout that names -Bazel 7.3.0 it writes none and warns `maven_bazel_release`. The hosted one is run on real -Bazel after agent mode as well: the build prints the patched jar. +Bazel 7.3.0, and beside a second hub without a lock, the documents of agent mode name the +code and the reason in the place of the command, the command gives that warning, and `vex` +says `affected` after it in the same words. The hosted command is run on real Bazel after +agent mode as well: the build prints the patched jar. A run tells a person the same in a warning (`vex_bazel_not_in_build`, one per package): @@ -4454,9 +4491,9 @@ still warns `maven_bazel_hub_unpatched`. The option changes nothing outside a Ba workspace. Nothing changes where the files do not show such a call: outside a Bazel workspace, in a -`--global` run, for a hosted pin, for a project whose own lock no call names, and wherever -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 +`--global` run, for a hosted pin (but a Maven one, above), for a project whose own lock no +call names, and wherever 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 (but for a `packages.lock.json`, see above), or above it without naming it among the importers of a pnpm workspace (a pnpm app @@ -4480,15 +4517,21 @@ is not read at all. In each of these the document is the one of a project without Bazel. Flags outside the committed files (`--override_repository`, an rc file) and BUILD files are not read either. -A Maven jar differs in one of these, the `WORKSPACE` file. Its hubs are read as -[Bazel workspaces: Maven](#bazel-workspaces-maven) says: there such a file counts only when -it calls `maven_install` or cannot be read, and only while `.bazeliskrc` or `.bazelversion` -names no Bazel 9 or later. So beside a `WORKSPACE` file that defines other repositories, -and on Bazel 9 beside any, a jar that a pinned hub fetches is `affected`. In the other cases -the document of a Maven jar is the one of a project without Bazel as well (a lock of a hub -is read up to 16 MiB), and also when no pinned hub fetches the jar at that version, when -the block holds an entry for it, and when any hub of the workspace is not read with -certainty (the list of the jar above). +A Maven artifact differs in one of these, the `WORKSPACE` file. Its hubs are read as +[Bazel workspaces: Maven](#bazel-workspaces-maven) says, by the reader hosted mode writes +its entries by. While `.bazeliskrc` or `.bazelversion` names a Bazel release from 7.0 on, +such a file changes nothing for a jar that a pinned hub of `MODULE.bazel` fetches: that +Bazel reads `MODULE.bazel` whatever the file holds, and a `maven_install` there is another +hub, which no mode patches either. That is so for a `maven_install` that the file calls +through a function of a `.bzl` file as well, which is not seen at all: it cannot put the +patch into the hub that was read. Where only such a hub fetches the jar, nothing is said. +While neither file names a release (also `latest`, a range, a release candidate), a +`WORKSPACE` file that defines a repository leaves the statement as without Bazel, as for +the other ecosystems: an older Bazel builds from that file alone. In the other cases the +document of a Maven artifact is the one of a project without Bazel as well (a lock of a +hub is read up to 16 MiB): when no pinned hub that was read fetches the jar at that +version, when the block holds the entry of the patch, and in the doubts that the list of +the artifact above names. Three more things change no statement. A call counts only when it is a statement of its own, which Bazel runs once: one in a comprehension, behind an `and`, in a conditional or in the @@ -4536,7 +4579,9 @@ For Maven, through rules_jvm_external's `maven.install` with a `lock_file`, a fl mode beside a `pom.xml` holds the documents to the unpatched build on Bazel 9.3.2 and 7.7.2: the run (`--vex`), `apply --vex`, `vex` and `vex --no-verify` each write one `affected` statement. After the hosted command the build is the patched one, and `vex` writes one -`not_affected` statement. `vex --no-bazel` is tested without Bazel. +`not_affected` statement, as it does after the vendored command in a checkout that only +Bazel builds. `vex --no-bazel`, and the `affected` statement of a hosted pin and of a +vendored copy whose command wrote no entry for the hub, are tested without Bazel. For no other Bazel shape do these pages say that the document and the build agree, and in these the document is still wrong (`not_affected` while Bazel builds the unpatched package, or while @@ -4558,15 +4603,13 @@ the build is broken): file at the root defines something, or the workspace has no `MODULE.bazel`. Measured for rules_js, rules_rust and rules_csharp, which build from the lock and never read the patched copy. -- **Agent mode beside rules_jvm_external**, wherever the statement does not say `affected` - above: a hub of the workspace is not read with certainty, or the jar reaches Bazel in a - way that [Bazel workspaces: Maven](#bazel-workspaces-maven) lists as not seen (a hub of - another Bazel module, a `maven_install` inside a function of a `.bzl` file). -- **Hosted and vendored mode for Maven, where the run wrote no entry for the hub** (the - `maven_bazel_*` warnings) and pinned or vendored the patch for a `pom.xml` or a Gradle - build: the hub builds the upstream jar. The command that an `affected` statement names - ends here where it declines. A test without Bazel holds both modes to it, in a checkout - that names Bazel 7.3.0. +- **A Maven patch beside rules_jvm_external**, in any mode, wherever the statement does not + say `affected` above: the hub that fetches the jar is not read with certainty; the + checkout does not say that Bazel reads `MODULE.bazel` as it stands (an rc file that names + `enable_bzlmod` or `--ignore_dev_dependency`, a `WORKSPACE` file beside no named + release); or the jar reaches Bazel in a way that + [Bazel workspaces: Maven](#bazel-workspaces-maven) lists as not seen (a hub of another + Bazel module, a `maven_install` inside a function of a `.bzl` file). - **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 diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 987353ea3..305019eaa 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 4051 + "max": 4084 }, "lock-readers": { "paths": [ From 7f549ab8866b5aefa62f17b5598fa37a448b04da Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 04:14:55 -0500 Subject: [PATCH 15/19] Start the Maven Bazel legs for the jar manifest reader The path lists of the Maven real-Bazel workflow name the files agent mode patches a jar with, because one of its flows does that. They had `patch/jvm_jar.rs` and `patch/jar_members.rs`. The second calls `patch/jar_manifest.rs`, which was missing, so a change to how the manifest of a signed jar is rewritten did not start the legs. It is in both lists now. Two kinds of entry said nothing: `vex/**` covers `vex/discover/maven.rs` and `vex/discover/bazel_maven.rs`, and in the push list `commands/**` covers `commands/vex*.rs`. They are removed, and the comment says that lock discovery is under `vex/`. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-maven.yml | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/.github/workflows/bazel-maven.yml b/.github/workflows/bazel-maven.yml index e0cef8460..6d85d6a7f 100644 --- a/.github/workflows/bazel-maven.yml +++ b/.github/workflows/bazel-maven.yml @@ -66,7 +66,7 @@ on: # rewriter's index of a pom, the model of what Maven selects with the # pom walk under it (the hosted lane pins only where Maven selects the # patch's version), the crawler that says where the Maven local - # repository is, lock discovery and the upstream restore of `rollback` + # repository is, the upstream restore of `rollback` # (for a pom and for the block of MODULE.bazel), the vendored Maven # backend, which writes the hub's jar and its entry, the dispatch that # hands a vendored command the hub's declines (vendor/refusals.rs), and what @@ -74,9 +74,10 @@ on: # hubs of MODULE.bazel, their locks and the block). Nothing another # ecosystem's flow owns is here but that dispatch, which the Composer # legs watch too, so a change to one ecosystem starts that ecosystem's - # legs only. Last, what the agent flow runs through: the two files + # legs only. Last, what the agent flow runs through: the three files # with which agent mode patches a jar, and the VEX code (`vex/` of the - # core, the files of the `vex` command). That flow holds the exact + # core, where lock discovery is too, and the files of the `vex` + # command). That 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. # @@ -100,8 +101,6 @@ on: - 'crates/socket-patch-core/src/crawlers/maven_selection.rs' - 'crates/socket-patch-core/src/crawlers/maven_scope.rs' - 'crates/socket-patch-core/src/crawlers/maven_crawler.rs' - - 'crates/socket-patch-core/src/vex/discover/maven.rs' - - 'crates/socket-patch-core/src/vex/discover/bazel_maven.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/maven.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/bazel_maven.rs' - 'crates/socket-patch-core/src/vendor/maven_repo.rs' @@ -109,6 +108,7 @@ on: - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/patch/jvm_jar.rs' - 'crates/socket-patch-core/src/patch/jar_members.rs' + - 'crates/socket-patch-core/src/patch/jar_manifest.rs' - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/src/commands/vex*.rs' push: @@ -132,8 +132,6 @@ on: - 'crates/socket-patch-core/src/crawlers/maven_selection.rs' - 'crates/socket-patch-core/src/crawlers/maven_scope.rs' - 'crates/socket-patch-core/src/crawlers/maven_crawler.rs' - - 'crates/socket-patch-core/src/vex/discover/maven.rs' - - 'crates/socket-patch-core/src/vex/discover/bazel_maven.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/maven.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/bazel_maven.rs' - 'crates/socket-patch-core/src/vendor/maven_repo.rs' @@ -141,8 +139,8 @@ on: - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/patch/jvm_jar.rs' - 'crates/socket-patch-core/src/patch/jar_members.rs' + - 'crates/socket-patch-core/src/patch/jar_manifest.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/**' From 6016a3938b2ba825a8d237e8a06e56f43daee283 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 04:30:01 -0500 Subject: [PATCH 16/19] Say affected beside what is left of a block that overrides nothing `maven::upstream` gave nothing whenever the block of `MODULE.bazel` was changed by hand, because such a block may hold an entry. For a block that can hold one, that check decided nothing: an `override_repo` outside the block as socket-patch writes it is a call the workspace reader does not follow, so no hub is read beside it, and nothing is said of any jar. What the check did decide is a block that overrides nothing any more (its first and its last line, say). That one holds no entry and the hub fetches the upstream jar: `apply` warns `maven_bazel_hub_unpatched` there, and the document said `not_affected`. The check is removed. Such a checkout gets `affected`, and the statement says why no mode patches the hub, in the words of the hosted command's warning: the block was changed by hand (`maven_bazel_unreadable`). The unit test of `upstream` holds both blocks, and the docs and the CLI contract say which one keeps the statement of a project without Bazel. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 4 ++-- crates/socket-patch-core/src/bazel/maven.rs | 16 ++++++++++++---- docs/ecosystems.md | 11 +++++++---- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index dd79caf70..49c7f70b0 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2712,7 +2712,7 @@ command's integration tests check its output. | `vendor_prebuilt_stub_invalid` | `failed` | RubyGems: the server stub lacks required attributes or is otherwise invalid; no local stub fallback is permitted. | | `bazelignore_not_updated` | run-level `warnings[]` | Go vendored and agent mode, Cargo vendored mode under a rules_rust crate hub, and Maven vendored mode, in a Bazel workspace (additive): the `.bazelignore` at the Bazel root, which keeps Bazel and gazelle out of the module copies under `.socket/vendor/golang` and `.socket/go-patches` out of the crates under `.socket/vendor/cargo`, and out of the jars vendored for a rules_jvm_external hub under `.socket/vendor/maven`, was not updated. It could not be read or written (a symbolic link or a directory in its place, a read-only directory, a read-only file). The detail names the line to add, or says that the lines of a copy that is gone can be deleted; the command's patch or undo stands and its exit code is unchanged. See docs/ecosystems.md "Bazel workspaces: `.bazelignore`". | | `redirect_cargo_bazel_config_unread` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_rust crate_universe hub (`crate.from_cargo` in `MODULE.bazel` or a file it includes, or `crates_repository` in the `WORKSPACE` file) reads the project's `Cargo.lock` or one of its `Cargo.toml` files, or may read them (its `cargo_lockfile` or `manifests` is not written out as strings, or a use of the extension may hide a call), and its `cargo_config` is not one string that is the label of the cargo config hosted mode writes (`.cargo/config.toml`, or the project's `.cargo/config`). cargo-bazel runs cargo with the config its hub names and no other, so the registry of a pin would be unknown to it and `bazel build` would fail (`registry index was not found in any configuration`). The crate is not pinned: nothing is written for it, its event is `skipped` / `redirect_unconfirmed` (a vendored crate that the scan would take over stays vendored: `skipped` with this code, and `redirect_takeover_kept_vendored`), and status and exit code are unchanged. One warning per crate; the detail names the hub's file and line, the config to commit (created with a comment line in it where the project has none), the attribute to give the hub (`cargo_config = "//:.cargo/config.toml"`; the label is written in the package of the hub's own labels), after which the same command pins the crate, and `--mode vendored`. A hub that names that config is still in the way while the file is there and holds nothing: `rollback` deletes a cargo config it leaves empty, and the hub fails on the missing file; the detail asks for a comment line in it. For a use of the extension that may hide a call the detail names that line to rewrite and no attribute: the next run pins the crate or names the hub that is in the way. A `WORKSPACE` call (`crates_repository`, also under the name a `load` of that file gives it) counts only when no hub of the module files reads the project's Cargo files and the checkout names no Bazel 9 or later. The rewriter's own refusals answer first and keep their codes. A pin that is in place already stays `applied`, and no warning is given for it. Nothing is read or changed in no Bazel workspace, or where no such hub is seen to read the project's Cargo files. See docs/ecosystems.md "Bazel workspaces: Cargo". | -| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace, agent and vendored mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch of this run, and the block that hosted and vendored mode keep in `MODULE.bazel` holds no entry for that jar after it. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build. Agent mode (`apply`, and `get` / `scan` in that mode; only for a package it found installed; never under `--global`) patches no hub: one warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub; the events, the exit code and every written file are those of the same run without the workspace. A VEX document says `affected` of such a jar (`vex_bazel_not_in_build`), but where the block was changed by hand or the checkout does not say that Bazel reads `MODULE.bazel` as it stands. Vendored mode (`vendor`, and `get` / `scan` in that mode) patches a pinned hub (below), and gives this code only for a jar it could have written an entry for and vendored nothing for, because the package failed or was skipped for another reason (never in a dry run); a jar it cannot write an entry for gets the `maven_bazel_*` code of the reason instead. A `vendor` whose `--ecosystems` leaves Maven out gives none. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace, agent and vendored mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch of this run, and the block that hosted and vendored mode keep in `MODULE.bazel` holds no entry for that jar after it. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build. Agent mode (`apply`, and `get` / `scan` in that mode; only for a package it found installed; never under `--global`) patches no hub: one warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub; the events, the exit code and every written file are those of the same run without the workspace. A VEX document says `affected` of such a jar (`vex_bazel_not_in_build`), but where the checkout does not say that Bazel reads `MODULE.bazel` as it stands. Vendored mode (`vendor`, and `get` / `scan` in that mode) patches a pinned hub (below), and gives this code only for a jar it could have written an entry for and vendored nothing for, because the package failed or was skipped for another reason (never in a dry run); a jar it cannot write an entry for gets the `maven_bazel_*` code of the reason instead. A `vendor` whose `--ecosystems` leaves Maven out gives none. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | | `maven_bazel_unreadable` | agent: run-level `warnings[]` (human: `Warning: …`); scan/get `--mode hosted`: `warnings[]` (warning); vendored: as `maven_bazel_not_at_root` | Maven in a Bazel workspace (additive): whether a rules_jvm_external hub builds the jar of a Maven patch could not be told, because something could not be read with certainty: a hub without `lock_file` in agent mode (hosted and vendored mode give `maven_bazel_not_pinned`), a `maven.artifact` or `maven.from_toml` tag that cannot be read, a lock that is missing, empty, not format 2 or 3, larger than 16 MiB (or past the 64 MiB of locks that are read for one workspace) or no JSON, a `WORKSPACE` file that calls `maven_install` or cannot be read while `.bazeliskrc` or `.bazelversion` at the Bazel root names no release of Bazel 9 or later, a `maven.install` whose `name` or `lock_file` is not a plain string, a construct of `MODULE.bazel` the reader does not follow, and, in agent mode, a `maven.override` of the artifact (hosted and vendored mode give `maven_bazel_no_effect`). Hosted and vendored mode also give it for a hub on an isolated `use_extension`, an rc file that cannot be read (also one that an import takes from outside the workspace by a relative path, and one with a line whose reading Bazel's own source calls an oversight: a quote that is never closed, a `\` with nothing after it), a `MODULE.bazel` that is a symbolic link, and a block of `MODULE.bazel` that was changed by hand (also in its first line alone), and then writes no entry for the hub. One warning per purl; the detail names the file, the line and the reason. | | `maven_bazel_hub_not_read` | scan run-level `warnings[]` (human: `Warning: …`); `get --mode hosted`: `warnings[]` | scan `--mode hosted` at the root of a Bazel workspace, with Maven in scope (additive): the scan takes the jars that the pinned rules_jvm_external hubs fetch for packages of the project (the lockfile supplement above), and something of the hubs could not be read with certainty, so it does not know every Maven artifact that Bazel builds through a hub. Given once per run, for the first thing that was not read, whatever the packages: a hub without `lock_file` (the detail then ends with how to pin it), or one of the reasons of `maven_bazel_unreadable` that concern reading the hubs (a tag or a lock that cannot be read, a `maven_install` of a `WORKSPACE` file that Bazel may read, a construct of `MODULE.bazel` the reader does not follow, a block that was changed by hand). `[:]: , so socket-patch does not know every Maven artifact that Bazel builds here through a rules_jvm_external hub: it looks for patches of the ones in the hub locks it read, and of no other`. No jar is guessed for what was not read; the jars of the hubs that were read are scanned, and a patch found for one of them gets no entry while the doubt stands (`maven_bazel_not_pinned` / `maven_bazel_unreadable` below). With no package at all a person reads `No packages found (see the warning).`. Exit code and `status` unchanged. A hosted `get` by advisory, which keeps the releases the project has by the same supplement, gives it too when the advisory has a patch of a Maven artifact. Only in a workspace that has to do with the ruleset: a call in `MODULE.bazel` or a file it includes names `rules_jvm_external`, the `WORKSPACE` file calls `maven_install`, or a `maven_install.json` lies at the Bazel root. In another Bazel workspace a file that cannot be read gives no such warning, and the run is the one without the workspace. | | `maven_bazel_not_at_root` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_jvm_external hub builds the jar of a Maven patch, and the project is below the root of its Bazel workspace, in whose `MODULE.bazel` the patch of a hub is written. Like the five codes below and `maven_bazel_unreadable` in hosted mode, it means that the run wrote no entry for the jar in the block of the root `MODULE.bazel`, because it could not show from the checkout that the entry works. One warning per purl, in the place of `redirect_maven_no_pom` for that purl; the detail says why and ends with what the block of the root holds for the jar, which is read for a project below the root too (the detail then names the file as "the MODULE.bazel at the root"). Nothing: "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps the upstream jar". The event is the one of the same run without the hub: `skipped` / `redirect_unconfirmed` in a tree only Bazel builds, `applied` beside a `pom.xml` or Gradle pin that landed. The entry of the patch, from an earlier run: that entry stays, the event is `applied`, and the detail ends "socket-patch left the entry that MODULE.bazel holds for it as it is". The entry of another patch of the same jar: it stays too, the event is the one without the hub, and the detail ends "socket-patch wrote nothing to MODULE.bazel for it: the entry of patch remains there, and where the block is in effect the Bazel build takes that patch's jar". Exit code unchanged. With none of these codes the run writes the block: `redirect.rewrittenFiles` holds `MODULE.bazel`, the event is `applied`, and `rollback` / `remove` take the entry out. **Vendored mode** (`vendor`, and `scan` / `get --mode vendored`; additive) gives the same codes, but for `maven_bazel_download`, with the same detail, for a jar whose entry it does not write. In a project with no Maven, Gradle, sbt or scala-cli build the hub is the patch's only target: the event is `failed` with the code as its `errorCode` and the detail, without the purl in front, as its `error`, nothing is written and the run exits 1, as for any vendored refusal (before, such a project failed with `vendor_jvm_shape_unsupported`, which a jar that no hub builds still does). Beside such a build that was vendored, the code is a run-level `warnings[]` entry (human: `Warning: …`), the event is `applied` and the exit code is unchanged. With none of these codes vendored mode commits the patched jar under `.socket/vendor/maven//` (`REPO.bazel`, `file/BUILD.bazel`, `file/-.jar`, `.gitignore`), writes the entry that names that directory into the block, in the place of a hosted entry for the same jar, adds the directory's line to `.bazelignore`, and records the patch in the vendor ledger (in a project with no other JVM build: `ecosystem` `maven`, `flavor` `bazel`, the committed jar as `artifact`, no `wiring`); the event is `applied`. `vendor --check` then also fails (`vendor_check_failed`) when that jar is not, byte for byte, the vendored jar the ledger records (beside a Maven or Gradle build the hub's jar is a copy of it), when `REPO.bazel` / `file/BUILD.bazel` is not the file that was written, when the block no longer names the directory or was changed by hand, and when no pinned hub takes the jar at that version any more (the reason names `socket-patch rollback `) or an rc file switches the entry off. `vendor --revert` / `rollback` / `remove` take the entry, the directory and the line out, and a hosted run that puts its entry in the place of the vendored one removes the directory and the line. See docs/ecosystems.md "Bazel workspaces: Maven". | @@ -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`, rules_rust `crate.from_cargo`, rules_csharp `nuget.from_lock`, rules_jvm_external `maven.install`), 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 patch of a Maven artifact in any mode (in an installed jar, in a pin of a `pom.xml` or a Gradle file, in a copy vendored for such a build) while a pinned hub fetches the plain jar of that artifact at that version and the block that hosted and vendored mode keep in the root `MODULE.bazel` holds no entry of that patch for it (no file of a project decides what a hub fetches: the same from every project of the workspace, and the same after a hosted or vendored command that wrote no entry for the hub; a jar that the hub takes from the Maven local repository under `m2local` counts as fetched, and the lock's sha256 is not compared with the patch), 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 Maven jar `get pkg:maven//@ --mode hosted` at the Bazel root, or with `--mode vendored`, the package by its coordinates alone, without the qualifiers of its purl; where hosted and vendored mode write no entry for the hub, in the place of the command ``Hosted and vendored mode write no entry for this hub (``): .`` with the `maven_bazel_*` code and the reason of the warning that the command gives (those of vendored mode: an option about downloads does not count); before either, when the block holds the entry of another patch for the jar, ``MODULE.bazel holds the entry of patch for this jar, and where the block is in effect the Bazel build takes that patch's jar.``; for a vendored PyPI 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).``; a Maven statement, which is one for every mode, says ``the patch is only in what Maven or Gradle builds from`` where the others say ``the patch is only in the installed copy``, and ends ``If what you ship is what Maven or Gradle builds and not what Bazel builds, pass …``), 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`, under which the Bazel workspace is not read for the document (see "The installed tree" under "VEX provenance markers": what the host command itself does and says in a Bazel workspace stays), for a hosted pin of another ecosystem than Maven, 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), for a Maven jar when the block holds the entry of its patch or was changed by hand, when a `maven.override` names the artifact, when the hub that would fetch it or its lock cannot be read (what is not known of another hub, such as a second hub without `lock_file` or a `maven_install` of a `WORKSPACE` file, changes nothing), or when the checkout does not say that Bazel reads `MODULE.bazel` as it stands (`.bazeliskrc` or `.bazelversion` names a Bazel before 7.0, or neither names a release while a `WORKSPACE` file defines a repository; an rc file of the checkout names `enable_bzlmod` other than switched on while the checkout names no Bazel 9 or later, or `--ignore_dev_dependency` without switching it off, on whatever line, or cannot be read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, which for a Maven jar counts only while the checkout names no Bazel release, 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`, rules_jvm_external `maven.install`), 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 patch of a Maven artifact in any mode (in an installed jar, in a pin of a `pom.xml` or a Gradle file, in a copy vendored for such a build) while a pinned hub fetches the plain jar of that artifact at that version and the block that hosted and vendored mode keep in the root `MODULE.bazel` holds no entry of that patch for it (no file of a project decides what a hub fetches: the same from every project of the workspace, and the same after a hosted or vendored command that wrote no entry for the hub; a jar that the hub takes from the Maven local repository under `m2local` counts as fetched, and the lock's sha256 is not compared with the patch), 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 Maven jar `get pkg:maven//@ --mode hosted` at the Bazel root, or with `--mode vendored`, the package by its coordinates alone, without the qualifiers of its purl; where hosted and vendored mode write no entry for the hub, in the place of the command ``Hosted and vendored mode write no entry for this hub (``): .`` with the `maven_bazel_*` code and the reason of the warning that the command gives (those of vendored mode: an option about downloads does not count); before either, when the block holds the entry of another patch for the jar, ``MODULE.bazel holds the entry of patch for this jar, and where the block is in effect the Bazel build takes that patch's jar.``; for a vendored PyPI 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).``; a Maven statement, which is one for every mode, says ``the patch is only in what Maven or Gradle builds from`` where the others say ``the patch is only in the installed copy``, and ends ``If what you ship is what Maven or Gradle builds and not what Bazel builds, pass …``), 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`, under which the Bazel workspace is not read for the document (see "The installed tree" under "VEX provenance markers": what the host command itself does and says in a Bazel workspace stays), for a hosted pin of another ecosystem than Maven, 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), for a Maven jar when the block holds the entry of its patch, or was changed by hand and still calls `override_repo`, when a `maven.override` names the artifact, when the hub that would fetch it or its lock cannot be read (what is not known of another hub, such as a second hub without `lock_file` or a `maven_install` of a `WORKSPACE` file, changes nothing), or when the checkout does not say that Bazel reads `MODULE.bazel` as it stands (`.bazeliskrc` or `.bazelversion` names a Bazel before 7.0, or neither names a release while a `WORKSPACE` file defines a repository; an rc file of the checkout names `enable_bzlmod` other than switched on while the checkout names no Bazel 9 or later, or `--ignore_dev_dependency` without switching it off, on whatever line, or cannot be read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, which for a Maven jar counts only while the checkout names no Bazel release, 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-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 12e49b88d..6a26f4974 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -1743,8 +1743,11 @@ fn command(group: &str, artifact: &str, version: &str) -> String { /// /// It is said only when it is certain of that hub, whatever is not known /// of another one: the hub and its lock were read and no `maven.override` -/// names the artifact ([`Hubs::built`]), the block was not changed by -/// hand, and it holds no entry of this patch for the jar. `None` +/// names the artifact ([`Hubs::built`]), and the block holds no entry of +/// this patch for the jar. A block that was changed by hand and still +/// overrides a repository may hold one: the reader does not follow such +/// a call, so no hub is read beside it. One that overrides nothing holds +/// no entry, and no mode writes to it. `None` /// otherwise, and where the checkout does not say that Bazel reads /// `MODULE.bazel` as it stands: it names a Bazel before 7.0, or none /// while a `WORKSPACE` file defines something, or an rc file names an @@ -1770,7 +1773,7 @@ pub fn upstream(root: &Path, patches: &[(&str, &str)]) -> Vec= (7, 0, 0)); let off = || rc(&view, release).iter().any(|(code, _)| *code != DOWNLOAD); - if hubs.pinned.is_empty() || hubs.edited.is_some() || !read || off() { + if hubs.pinned.is_empty() || !read || off() { return none(); } // What holds for every jar is asked once, as for a run that writes. @@ -2717,7 +2720,9 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") "there is no repository for an entry to replace", ); // The block's entry of the patch is the jar Bazel takes, and a - // block that was changed by hand may hold one. The entry of another + // block that was changed by hand may hold one while it overrides + // a repository: what is left of one that overrides nothing holds + // none, and no mode writes to it. The entry of another // patch is not this one's: it is named, and the command replaces // it. An entry for another version is the entry of another jar. fn module(text: &str) -> [(&str, &str); 1] { @@ -2726,6 +2731,9 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") assert_eq!(said(&module(&patched), NETTY_PURL), nothing); let by_hand = patched.replace("# Do not change", "# Do change"); assert_eq!(said(&module(&by_hand), NETTY_PURL), nothing); + let emptied = format!("{PINNED}\n{BEGIN}\n{END}\n"); + let by_hand = "the block that socket-patch keeps there was changed by hand"; + declined(&module(&emptied), UNREADABLE, by_hand); let another = patch("netty-tcnative-classes", OTHER_UUID); let another = with_patch(PINNED, LABEL, another).expect("a block"); let names = format!( diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1436d28de..22b6b43e2 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2794,9 +2794,10 @@ with its reason ([Bazel workspaces: VEX](#bazel-workspaces-vex)). So the documen command that gave such a code still says `affected`. It is about the hub that fetches the jar, also beside another hub that was not read, where the first warning above is given. It stays `not_affected`, as without Bazel, where that hub is in doubt (an override of the -artifact, a block that was changed by hand) and where the checkout does not say that Bazel -reads `MODULE.bazel` as it stands (a Bazel before 7.0, a `WORKSPACE` file beside no named -release, an rc file that names `enable_bzlmod` or `--ignore_dev_dependency`). +artifact, a block that was changed by hand and still overrides a repository) and where the +checkout does not say that Bazel reads `MODULE.bazel` as it stands (a Bazel before 7.0, a +`WORKSPACE` file beside no named release, an rc file that names `enable_bzlmod` or +`--ignore_dev_dependency`). The Bazel release is the one that `.bazeliskrc` (`USE_BAZEL_VERSION`) or else `.bazelversion` at the Bazel root names, read as bazelisk reads them: the last `USE_BAZEL_VERSION` line counts, @@ -4350,7 +4351,9 @@ patched: `maven_install` of a `WORKSPACE` file, it is `affected`, as `apply` warns `maven_bazel_hub_unpatched` there. It stays `not_affected` where that hub itself is in doubt: its tags or its lock cannot be read, a `maven.override` names the artifact, or the - block was changed by hand and may hold an entry. It stays so too where the checkout does + block was changed by hand and still overrides a repository, so that it may hold an entry + (what is left of a block that overrides nothing holds none: the statement is `affected`, + and says that no mode writes to that block). It stays so too where the checkout does not say that Bazel reads `MODULE.bazel` as it stands: `.bazeliskrc` or `.bazelversion` names a Bazel before 7.0; neither names a release while a `WORKSPACE` file defines a repository; or an rc file of the checkout names `enable_bzlmod` other than switched on From 4fe3b14af543bcc39009df874c61a0d9863431b7 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 11:52:33 -0500 Subject: [PATCH 17/19] Pass over a WORKSPACE file where the checkout names Bazel 9 or later Vendored mode declines a PyPI or RubyGems package whose lock a Bazel hub reads, and it counted a call of a `WORKSPACE` file that names the lock as such a hub (`pip_parse`, `rb_bundle_fetch`). Bazel 9 never reads a `WORKSPACE` file. One that a move to Bzlmod left behind can still name `requirements.txt` or `Gemfile.lock`, so in a checkout that Bazel 9 builds, a vendored run that worked before exited 1 with `vendor_pypi_bazel_hub` or `vendor_gem_bazel_hub`, with no hub that takes the lock. Where the checkout names a Bazel release of 9 or later, a `WORKSPACE`, `WORKSPACE.bazel` or `WORKSPACE.bzlmod` file now counts for nothing in these two refusals: a call of it is no reader of the lock, a call of it that is not written out is no doubt, and neither is a file that cannot be read. The run does what it does without the file. The exception for a package that is already vendored asks the same reader, so it agrees. The release is read as the Maven reader reads it (`rc::declared_release`: `USE_BAZEL_VERSION` of `.bazeliskrc`, else `.bazelversion`, and only three numbers name one). One rule, `rc::reads_workspace_file`, holds "before 9, or not named", and the Maven reader now asks it in the place of its own closure. So a checkout that names 7.x or 8.x, `latest`, a release candidate or no release keeps the refusal: a Bazel 7 or 8 may build it. What `vex` says is not changed: `built::unbuilt` still says nothing beside a `WORKSPACE` file. Tests: unit rows in bazel/rc.rs and bazel/built.rs (the lock a call names, the call that is not written out and the file that cannot be read, under nine ways to name a release), and one test each in e2e_bazel_build/ruby.rs and pypi.rs that runs the built binary without Bazel. With `.bazelversion` 9.3.2, 9.0.0 or 10.0.0 beside a retained `WORKSPACE` that names the lock, `scan --mode vendored` vendors the package and writes the files it writes without that file; with 7.7.2, 8.8.2, no file or `latest` it is declined as before. With the rule switched off, the test of built.rs and both of those fail on their first 9.x row. docs/ecosystems.md and the contract row of the two codes say when the file counts. The `bazel` cap of scripts/loc-budget.json is the new count, 4047. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../tests/e2e_bazel_build/pypi.rs | 60 ++++++++++ .../tests/e2e_bazel_build/ruby.rs | 67 +++++++++++ crates/socket-patch-core/src/bazel/built.rs | 105 ++++++++++++++++-- crates/socket-patch-core/src/bazel/maven.rs | 5 +- crates/socket-patch-core/src/bazel/rc.rs | 37 ++++++ docs/ecosystems.md | 39 ++++--- scripts/loc-budget.json | 2 +- 8 files changed, 288 insertions(+), 29 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 45aed9c43..5f8f36ad2 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2537,7 +2537,7 @@ command's integration tests check its output. | `vendor_bun_lockb_invalid` | `failed` | vendor / scan / get `--mode vendored`: the binary lock is malformed, unreadable, unsupported or cannot be rewritten safely. The detail names the parser, hash or filesystem error. Refused before patch downloads and before hosted takeover; the package's `failed` event carries `errorCode` and `error`, while `get ` also carries top-level `error.code`. Dry-run predicts the same refusal. | | `vendor_bun_workspace_unsupported` | `failed` | vendor / scan / get `--mode vendored` (bun): the text lock holds `workspace:` packages and its `lockfileVersion` is below 2 — Bun 1.2–1.3 resolve a workspace member's local-tarball path relative to the member; a committed version-2 lock is the proof every consumer runs Bun ≥ 1.4 (deliberate over-approximation: root-only declared packages would install on version 1 too). Detail names the version integer and a version-specific remedy: delete `bun.lock` and re-lock with Bun ≥ 1.4 (an in-place `bun install` keeps the existing version) — then, for a version-1 lock, "or use `--mode hosted`, which accepts version-1 workspace locks"; for a version-0 lock, "or delete `bun.lock`, re-lock with Bun ≥ 1.2 (which writes lockfileVersion 1) and use `--mode hosted`" (hosted refuses version-0 workspace locks, so a bare hosted pointer would send the user into a second refusal). Refused before any write — in the pre-download preflight on `get`/`scan` (see `vendor_bun_lockb_invalid` for the placements); in the shared preflight that `vendor` and the vendor step run BEFORE a hosted → vendored takeover's revert (a hosted-redirected purl stays hosted-wired, ledger and lock untouched; `vendor --dry-run` previews the same `failed` code); and in the engine when the run would write a NEW local tuple. Exempt: purls the vendor ledger wires at the selected uuid, purls whose every `bun.lock` instance is already a `.socket/vendor/npm/` tuple (any uuid), in-sync re-runs and `repair` redownloads. | | `vendor_composer_bazel_workspace` | `failed` | vendor / scan / get `--mode vendored` (composer): the project is in a Bazel workspace (its directory, or one above it up to the root of its git checkout, holds `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`). Vendored mode makes `composer.lock` name the patched copy by a path relative to the directory Composer runs in; a Bazel repository rule or build action that runs `composer install` from the lock anywhere else fails with Composer's `Source path "…" is not found for package …`, and the build with it (Bazel 9.3.2, 8.8.2, 7.7.2). Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the Bazel root and the mode that writes no such path, `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel`, `vendor --revert`, and a package whose `composer.lock` entry already names the copy of the same patch (the run leaves the lock as it is, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included; a new patch for it is refused). A project that commits its `vendor/` tree is refused like any other: the tree shows that Composer has run in the project's directory, not that no rule of the workspace runs it elsewhere as well. See docs/ecosystems.md "Bazel workspaces: Composer". | -| `vendor_pypi_bazel_hub` / `vendor_gem_bazel_hub` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): a hub of the project's Bazel workspace reads a file of the project that the run would point at the copy under `.socket/vendor`. That is a rules_python `pip.parse` whose `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` or `uv_lock` names a requirements file of the project that the run may write (`requirements.txt` or a file it includes with `-r`, as one set: in a project with no tool lock, for a package they name beside a uv, Pipenv or PEP 751 lock, and for a package they hold by a URL, which is a hosted pin, beside a Poetry or PDM lock) or the `uv.lock` of a uv project; a rules_ruby `ruby.bundle_fetch` whose `gemfile` or `gemfile_lock` names the project's `Gemfile` or `Gemfile.lock`; and a call of a `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`), where `@//` is the main repository when the file says `workspace(name = "")`. Neither ruleset builds from such a file: rules_python 2.5.0-rc4 fails with `invalid user-provided repo name '___/_socket/vendor/pypi/…'`, and the `bundle install` action of rules_ruby 1.0.0-rc2 with `The path … does not exist.`, after a command that exited 0 (Bazel 9.3.2, 8.8.2, 7.7.2). Also refused, for every package whose run would write such a file: a workspace whose files cannot be read with certainty where a call of the hub may be behind that (a call of the hub whose file is not a plain string label or that passes `*` or `**`; a hub proxy handed on; a module file or a statement of one that cannot be read, while the workspace calls the hub or a file that was read names its ruleset; a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all, for which one byte that is not UTF-8 is enough), because a call may then read the project's lock. Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the call with its file and line, the lock (or the place and the reason of the doubt), the Bazel root, and the mode whose pin both rulesets build, `--mode hosted` (rules_ruby where its call passes no `gem_checksums`, which the detail for a gem says). Not refused: a package whose run writes no file that such a call names, in a Bazel workspace or outside one (a Poetry or PDM project, whose lock is wired alone, beside a hub that reads its exported `requirements.txt`, unless that file holds the package by a URL); a workspace whose files were read and neither call the hub nor name its ruleset; a run with `--allow-vendored-in-bazel`; `vendor --revert`; and a package that the file the call names already names by the copy of the same patch (`.socket/vendor/pypi//`, `.socket/vendor/gem//`): the run adds nothing to what the hub reads, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included, while a new patch for the package is refused; where the calls name more than one file of the project, each of them that holds the package has to name the copy. Where the reading is in doubt no file is known to be the hub's, and every run without the switch is refused. See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" | +| `vendor_pypi_bazel_hub` / `vendor_gem_bazel_hub` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): a hub of the project's Bazel workspace reads a file of the project that the run would point at the copy under `.socket/vendor`. That is a rules_python `pip.parse` whose `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` or `uv_lock` names a requirements file of the project that the run may write (`requirements.txt` or a file it includes with `-r`, as one set: in a project with no tool lock, for a package they name beside a uv, Pipenv or PEP 751 lock, and for a package they hold by a URL, which is a hosted pin, beside a Poetry or PDM lock) or the `uv.lock` of a uv project; a rules_ruby `ruby.bundle_fetch` whose `gemfile` or `gemfile_lock` names the project's `Gemfile` or `Gemfile.lock`; and a call of a `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`), where `@//` is the main repository when the file says `workspace(name = "")`. A `WORKSPACE` file counts unless the checkout names a Bazel release of 9 or later, which never reads one (`.bazelversion`, or `USE_BAZEL_VERSION` in `.bazeliskrc`, as three numbers; with an older release, `latest`, a release candidate or neither file it counts): there it is no reason to refuse and no doubt. Neither ruleset builds from such a file: rules_python 2.5.0-rc4 fails with `invalid user-provided repo name '___/_socket/vendor/pypi/…'`, and the `bundle install` action of rules_ruby 1.0.0-rc2 with `The path … does not exist.`, after a command that exited 0 (Bazel 9.3.2, 8.8.2, 7.7.2). Also refused, for every package whose run would write such a file: a workspace whose files cannot be read with certainty where a call of the hub may be behind that (a call of the hub whose file is not a plain string label or that passes `*` or `**`; a hub proxy handed on; a module file or a statement of one that cannot be read, while the workspace calls the hub or a file that was read names its ruleset; a root `MODULE.bazel` that cannot be read at all, or a `WORKSPACE` file that cannot be and counts, for which one byte that is not UTF-8 is enough), because a call may then read the project's lock. Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the call with its file and line, the lock (or the place and the reason of the doubt), the Bazel root, and the mode whose pin both rulesets build, `--mode hosted` (rules_ruby where its call passes no `gem_checksums`, which the detail for a gem says). Not refused: a package whose run writes no file that such a call names, in a Bazel workspace or outside one (a Poetry or PDM project, whose lock is wired alone, beside a hub that reads its exported `requirements.txt`, unless that file holds the package by a URL); a workspace whose files were read and neither call the hub nor name its ruleset; a run with `--allow-vendored-in-bazel`; `vendor --revert`; and a package that the file the call names already names by the copy of the same patch (`.socket/vendor/pypi//`, `.socket/vendor/gem//`): the run adds nothing to what the hub reads, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included, while a new patch for the package is refused; where the calls name more than one file of the project, each of them that holds the package has to name the copy. Where the reading is in doubt no file is known to be the hub's, and every run without the switch is refused. See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" | | `vendor_lockfile_missing` / `vendor_lockfile_version_unsupported` (bun preflight placement) | `failed` | scan / get `--mode vendored` (bun): the pre-download preflight found `bun.lock` unreadable / at a `lockfileVersion` other than 0 to 3 (a newer version: update socket-patch; no integer: re-lock with Bun ≥ 1.2 — the same text as hosted's `redirect_bun_lock_unsupported`) or outside bun's single-line `packages` grammar. Same placements as `vendor_bun_lockb_invalid`; nothing fetched, no patch record. An unreadable `.socket/vendor/state.json` met by the same preflight is `vendor_state_unreadable` (see that row), never one of these. | | `bun_lockb_invalid` | scan `warnings[]` (run-level) | scan (every mode): the native binary inventory could not parse or read `bun.lockb`; detail names the format or filesystem error. Also printed as `Warning: …` on stderr. Exit and status remain unchanged. The warning is retained on empty and non-empty scans; valid binary locks are inventoried normally without a runtime or install. | | `bun_lock_unsupported` | scan `warnings[]` (run-level) | scan (every mode): the text `bun.lock` is there but the lock reader refuses it — a `lockfileVersion` newer than 3, no integer version, or a `packages` section outside bun's single-line grammar (a comment line, a re-indent) — so the packages it lists were not read from the lockfile. Detail is the shared version gate's text or `bun.lock: line : …`, followed by `, so the packages it lists were NOT read from the lockfile: a package that is locked but not installed was not scanned`. Also printed as `Warning: …` on stderr, and a scan that then finds no package at all ends `No packages found (see the warning).` instead of advising an install. Status and exit are unchanged (0): before, a checkout without `node_modules` scanned as an empty project and the lock was not mentioned. Installed packages are still crawled, and hosted / vendored runs keep their own refusal (`redirect_bun_lock_unsupported` / `vendor_lockfile_version_unsupported`). The hosted in-memory engine reports the same code among its warnings. | diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs index 357c8e54d..16b6befe9 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs @@ -1132,6 +1132,66 @@ fn vendored_mode_goes_on_where_no_hub_reads_the_requirements() { cell.declined(&with.run(&cell, &VENDORED), &package, 1, "failed", &before); } +/// Without a Bazel: a `WORKSPACE` file that a migration left behind still +/// hands `requirements.txt` to the ruleset's older rule, beside a +/// `MODULE.bazel` whose hub reads another file. Bazel 9 never reads a +/// `WORKSPACE` file, so where the checkout names a release of 9 or later +/// the package is vendored as it is without that file. Where it names an +/// older release, none, or one that is no release, a Bazel that reads the +/// file may build the checkout: the package is declined, and the refusal +/// names the call of the `WORKSPACE` file. +#[test] +fn a_workspace_file_counts_unless_the_checkout_names_bazel_9_or_later() { + let with = Vendoring::new(); + let own = format!("\"//:{REQUIREMENTS}\""); + let legacy = format!("pip_parse(\n name = \"pypi\",\n requirements_lock = {own},\n)\n"); + // The fixture's checkout with a hub that reads another file, the + // `WORKSPACE` file where it is `kept`, and what names the Bazel + // release. + let retained = |release: Option<&str>, kept: bool| { + let cell = checkout(&with); + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + let other = module.replace(&own, "\"//:requirements_lock.txt\""); + assert_ne!(other, module); + cell.write("MODULE.bazel", other); + if kept { + cell.write("WORKSPACE", &legacy); + } + if let Some(release) = release { + cell.write(".bazelversion", format!("{release}\n")); + } + cell + }; + // A run that vendors the wheel: the files it writes, and the + // requirements it leaves. + let vendors = |cell: &Cell| { + let before = cell.tree(); + let scan = with.run(cell, &VENDORED); + assert_eq!(scan.code, 0, "{}", scan.dump); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{}", scan.dump); + let after = cell.tree(); + (changed(&before, &after), after[REQUIREMENTS].clone()) + }; + let written = vendors(&retained(Some("9.3.2"), false)); + let line = String::from_utf8_lossy(&written.1); + assert!(line.contains("./.socket/vendor/pypi/"), "{line}"); + for release in ["9.3.2", "9.0.0", "10.0.0"] { + let kept = vendors(&retained(Some(release), true)); + assert!(kept == written, "{release}"); + } + let names = format!("names {REQUIREMENTS}; "); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &["`pip_parse` (WORKSPACE:1)", &names], + }; + for release in [Some("7.7.2"), Some("8.8.2"), None, Some("latest")] { + let cell = retained(release, true); + let before = cell.tree(); + cell.declined(&with.run(&cell, &VENDORED), &package, 1, "failed", &before); + } +} + /// Without a Bazel: the fixture's directories are those of its table, and /// the workflow runs each release on its era. The fixture holds no /// `requirements.txt`: every era names the one the test writes, which pins diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs index adcae9388..5e34e9499 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -974,6 +974,73 @@ fn vendored_mode_goes_on_where_no_hub_reads_the_lock() { cell.declined(&scan(&cell, &served), &package, 1, "failed", &before); } +/// Without a Bazel: a `WORKSPACE` file that a migration left behind still +/// hands the Gemfile and its lock to the ruleset's older rule, beside a +/// `MODULE.bazel` whose hub reads the files of another project. Bazel 9 +/// never reads a `WORKSPACE` file, so where the checkout names a release of +/// 9 or later the gem is vendored as it is without that file. Where it +/// names an older release, none, or one that is no release, a Bazel that +/// reads the file may build the checkout: the gem is declined, and the +/// refusal names the call of the `WORKSPACE` file. +#[test] +fn a_workspace_file_counts_unless_the_checkout_names_bazel_9_or_later() { + let legacy = "rb_bundle_fetch(\n name = \"bundle\",\n gemfile = \"//:Gemfile\",\n \ + gemfile_lock = \"//:Gemfile.lock\",\n)\n"; + // The fixture's checkout with a hub that reads the files of another + // project, the `WORKSPACE` file where it is `kept`, and what names + // the Bazel release. + let retained = |release: Option<&str>, kept: bool| { + let (cell, served) = checkout(); + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + let other = module.replace("\"//:Gemfile", "\"//svc:Gemfile"); + assert_ne!(other, module); + cell.write("MODULE.bazel", other); + if kept { + cell.write("WORKSPACE", legacy); + } + if let Some(release) = release { + cell.write(".bazelversion", format!("{release}\n")); + } + (cell, served) + }; + let scan = |cell: &Cell, served: &Served| { + let origin = served.standin.origin(); + run(&served.standin, cell, &VENDORED, &patch_host(&origin)) + }; + // A run that vendors the gem by its path, and the files it writes, + // with the id of the patch left out of their names. + let vendors = |cell: &Cell, served: &Served| -> Vec { + let before = cell.tree(); + let ran = scan(cell, served); + assert_eq!(ran.code, 0, "{}", ran.dump); + assert_eq!(ran.envelope["summary"]["applied"], 1, "{}", ran.dump); + let after = cell.tree(); + let copy = format!(".socket/vendor/gem/{}/{NAME}-{VERSION}", served.uuid); + let lock = String::from_utf8_lossy(&after["Gemfile.lock"]); + let section = format!("PATH\n remote: {copy}\n"); + assert!(lock.starts_with(§ion), "{lock}"); + let written = changed(&before, &after).into_iter(); + written + .map(|path| path.replace(&served.uuid, "")) + .collect() + }; + let (cell, served) = retained(Some("9.3.2"), false); + let written = vendors(&cell, &served); + for release in ["9.3.2", "9.0.0", "10.0.0"] { + let (cell, served) = retained(Some(release), true); + assert_eq!(vendors(&cell, &served), written, "{release}"); + } + let package = Declined { + names: &["`rb_bundle_fetch` (WORKSPACE:1)", "names Gemfile.lock; "], + ..DECLINED + }; + for release in [Some("7.7.2"), Some("8.8.2"), None, Some("latest")] { + let (cell, served) = retained(release, true); + let before = cell.tree(); + cell.declined(&scan(&cell, &served), &package, 1, "failed", &before); + } +} + /// Without a Bazel: steps (b), (d) and (f) of /// [`hosted_bundle_fetch_gem_checksums`] in the fixture's checkout, with /// what a person reads of (b), and (b) again with `--dry-run` and with diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index 60cefae56..74b6a00f0 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -59,7 +59,10 @@ //! Every call of the hub counts, also one that may not run, and so does a //! call of a `WORKSPACE` file that passes one of the hub's files, which is //! how the older form of the ruleset is called there (`pip_parse`, -//! `rb_bundle_fetch`). And where something of the workspace cannot be read +//! `rb_bundle_fetch`). A `WORKSPACE` file counts unless the checkout names +//! a Bazel release of 9 or later, which never reads one +//! ([`workspace_as_built`]): there it holds no call and is no doubt, +//! whatever it says. And where something of the workspace cannot be read //! with certainty and a call of the hub may be behind it, the answer is //! that doubt: the workspace calls the hub, or a file that was read names //! its ruleset, or the root module file or the `WORKSPACE` file could not @@ -78,8 +81,9 @@ use std::path::{Component, Path}; use aho_corasick::AhoCorasick; +use super::rc::reads_workspace_file; use super::starlark::{Call, File, Value}; -use super::workspace::{disk, Doubt, Extension, Repo, Workspace}; +use super::workspace::{disk, Doubt, Entry, Extension, Repo, Workspace}; use super::BazelRoot; use crate::formats::gem::locked_specs; use crate::formats::pnpm::grammar::documents; @@ -268,7 +272,8 @@ pub type Reader = Result; /// calls of the hub are read with certainty and name other files, and when /// nothing shows that the workspace may call it: no call of the hub and no /// file that names its ruleset, with a root module file and a `WORKSPACE` -/// file that were read or are not there. +/// file that were read or are not there. A `WORKSPACE` file that the Bazel +/// of the checkout does not read is not there ([`workspace_as_built`]). pub async fn reader( root: &BazelRoot, ecosystem: &'static str, @@ -277,17 +282,29 @@ pub async fn reader( let (dir, project) = (root.dir.clone(), slashed(&root.project)); run_blocking(move || { let read = |file: &str| lock_text(&dir, file); - reads( - &Workspace::read(&disk(&dir)), - &project, - ecosystem, - &locks, - &read, - ) + let workspace = workspace_as_built(&disk(&dir)); + reads(&workspace, &project, ecosystem, &locks, &read) }) .await } +/// The workspace of `view` as the Bazel that the checkout names reads it: +/// without its `WORKSPACE` file ([`Workspace::legacy`]) where that Bazel +/// reads none, which is a release of 9 or later +/// ([`reads_workspace_file`]). A checkout that names an older release, or +/// none as three numbers, keeps the file: a Bazel 7 or 8 may build it. +/// +/// For a question whose wrong "yes" costs a run that worked: a +/// `WORKSPACE` file that a migration left behind can still name a lock, +/// and stands in no build's way. +pub(crate) fn workspace_as_built(view: &dyn Fn(&str) -> Entry) -> Workspace { + let mut workspace = Workspace::read(view); + if !reads_workspace_file(view) { + workspace.legacy = None; + } + workspace +} + /// The path from the Bazel root `root` of `file`, a path from its project. pub(crate) fn from_root(root: &BazelRoot, file: &str) -> String { below(&slashed(&root.project), file) @@ -1054,7 +1071,7 @@ use_repo(ruby, "bundle") /// [`UNREADABLE`] is one that cannot be read, for the reason after it. fn reader_of(files: &[(&str, &str)], project: &str, ecosystem: &str, locks: &[&str]) -> String { let text = |path: &str| files.iter().find(|(name, _)| *name == path); - let workspace = Workspace::read(&|path| match text(path) { + let workspace = workspace_as_built(&|path| match text(path) { Some((_, text)) => match text.strip_prefix(UNREADABLE) { Some(why) => Entry::Unreadable(why.to_string()), None => Entry::Text(text.to_string()), @@ -1291,6 +1308,72 @@ use_repo(ruby, "bundle") assert_eq!(reader_of(&files, "svc", "pypi", &["requirements.txt"]), ""); } + /// A `WORKSPACE` file is not read by a Bazel of 9 or later. Where the + /// checkout names such a release, a call of that file that names the + /// lock is no reader of it, one that is not written out is no doubt, + /// and neither is a file that cannot be read. A checkout that names an + /// older release, none, or something that is no release keeps all + /// three, and a call of a module file counts under every release. + #[test] + fn a_workspace_file_counts_unless_the_checkout_names_bazel_9_or_later() { + let module = ("MODULE.bazel", "module(name = \"shop\")\n"); + let legacy = "pip_parse(name = \"pypi\", requirements_lock = \"//svc:requirements.txt\")\n\ + rb_bundle_fetch(name = \"bundle\", gemfile = \"//svc:Gemfile\", gemfile_lock = LOCK)\n"; + let asked = |files: &[(&str, &str)], project, ecosystem| { + let locks: &[&str] = match ecosystem { + "pypi" => &["requirements.txt"], + _ => &["Gemfile", "Gemfile.lock"], + }; + reader_of(files, project, ecosystem, locks) + }; + let pip = "pip_parse WORKSPACE:1 svc/requirements.txt"; + let gemfile = "rb_bundle_fetch WORKSPACE:2 svc/Gemfile"; + let unwritten = "? WORKSPACE:2 the files `rb_bundle_fetch` names are not all written out"; + let unread = "? WORKSPACE:0 it cannot be read: it is not UTF-8"; + // What names the release, and whether the file then counts. + let rows: [(&[(&str, &str)], bool); 9] = [ + (&[], true), + (&[(".bazelversion", "7.7.2\n")], true), + (&[(".bazelversion", "8.8.2\n")], true), + (&[(".bazelversion", "latest\n")], true), + (&[(".bazelversion", "9.3.2rc1\n")], true), + (&[(".bazelversion", "9.0.0\n")], false), + (&[(".bazelversion", "9.3.2\n")], false), + (&[(".bazelversion", "10.0.0\n")], false), + ( + &[ + (".bazeliskrc", "USE_BAZEL_VERSION=8.8.2\n"), + (".bazelversion", "9.3.2\n"), + ], + true, + ), + ]; + for (release, counts) in rows { + let with = |workspace: &'static str| { + let mut files = vec![module, ("WORKSPACE", workspace)]; + files.extend_from_slice(release); + files + }; + let said = |yes: &str| counts.then_some(yes).unwrap_or_default().to_string(); + let files = with(legacy); + assert_eq!(asked(&files, "svc", "pypi"), said(pip), "{release:?}"); + assert_eq!(asked(&files, "svc", "gem"), said(gemfile), "{release:?}"); + let other = asked(&files, "other", "gem"); + assert_eq!(other, said(unwritten), "{release:?}"); + let files = with("unreadable: it is not UTF-8"); + for ecosystem in ["pypi", "gem"] { + assert_eq!(asked(&files, "svc", ecosystem), said(unread), "{release:?}"); + } + } + // A call of a module file is the hub's under Bazel 9 as under any. + let mut files = SHOP.to_vec(); + files.push(("WORKSPACE", legacy)); + files.push((".bazelversion", "9.3.2\n")); + let api = "pip.parse MODULE.bazel:15 api/requirements.txt"; + assert_eq!(asked(&files, "api", "pypi"), api); + assert_eq!(asked(&files, "svc", "pypi"), ""); + } + #[test] fn a_project_is_in_the_directory_of_a_lock_or_below_it_or_neither() { for (project, lock, from) in [ diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 73eb1d69d..299b9d325 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -54,7 +54,7 @@ use std::ops::Range; use std::path::Path; use std::rc::Rc; -use super::rc::{declared_release, mentions, ModuleLock}; +use super::rc::{declared_release, mentions, reads_workspace_file, ModuleLock}; use super::starlark::{Bound, Call, How, Value}; use super::workspace::{disk, disk_up_to, Doubt, Entry, Extension, Repo, Tag, Workspace}; use crate::formats::maven::is_variant; @@ -601,8 +601,7 @@ impl Hubs { .iter() .any(|(_, file)| file.calls.iter().any(names)); let calls = matches!(ws.legacy, Some(Ok(_))); - let before_9 = || declared_release(view).is_none_or(|release| release < (9, 0, 0)); - let legacy = match ws.legacy.filter(|_| before_9()) { + let legacy = match ws.legacy.filter(|_| reads_workspace_file(view)) { Some(Ok((file, read))) => { // By its own name, or by one that a `load` gives it. let symbol = Value::Str("maven_install".to_string()); diff --git a/crates/socket-patch-core/src/bazel/rc.rs b/crates/socket-patch-core/src/bazel/rc.rs index 47346de05..aca277e19 100644 --- a/crates/socket-patch-core/src/bazel/rc.rs +++ b/crates/socket-patch-core/src/bazel/rc.rs @@ -58,6 +58,17 @@ pub fn declared_release(view: &dyn Fn(&str) -> Entry) -> Option { } } +/// Whether the Bazel that builds the checkout may read a `WORKSPACE` file +/// ([`super::workspace::Workspace::legacy`]). Bazel 7 reads one beside +/// `MODULE.bazel`, Bazel 8 when it is told to, and Bazel 9 and later +/// never. So it does not where the checkout names a release of 9 or later +/// ([`declared_release`]), and it may where the checkout names an older +/// one or none: `latest`, a release candidate and a missing file name no +/// release. +pub fn reads_workspace_file(view: &dyn Fn(&str) -> Entry) -> bool { + declared_release(view).is_none_or(|release| release < (9, 0, 0)) +} + /// What `MODULE.bazel.lock` says of the Bazel that wrote it and of the /// modules it selected. Bazel writes the file at a build, so a checkout /// that was built has it whether it is committed or not. @@ -330,6 +341,32 @@ mod tests { assert_eq!(declared_release(&unreadable), None); } + /// A `WORKSPACE` file may be read unless the checkout names a Bazel of + /// 9 or later: one that names an older release, none, or something + /// that is no release may be built by a Bazel that reads it. + #[test] + fn a_workspace_file_may_be_read_unless_bazel_9_or_later_is_named() { + let reads = |files: &[(&str, &str)]| { + reads_workspace_file(&|path| match files.iter().find(|(name, _)| *name == path) { + Some((_, text)) => Entry::Text(text.to_string()), + None => Entry::Absent, + }) + }; + for named in ["9.0.0", "9.3.2\n", "10.0.0\n"] { + assert!(!reads(&[(".bazelversion", named)]), "{named:?}"); + } + let unnamed = ["8.8.2\n", "7.7.2\n", "", "latest\n", "9.x\n", "9.3.2rc1\n"]; + for named in unnamed { + assert!(reads(&[(".bazelversion", named)]), "{named:?}"); + } + assert!(reads(&[])); + // `.bazeliskrc` outranks `.bazelversion`, as for a launcher. + let rc = (".bazeliskrc", "USE_BAZEL_VERSION=9.3.2\n"); + assert!(!reads(&[rc, (".bazelversion", "7.7.2\n")])); + let rc = (".bazeliskrc", "USE_BAZEL_VERSION=7.7.2\n"); + assert!(reads(&[rc, (".bazelversion", "9.3.2\n")])); + } + /// The view of the files `files`, where a file whose text is `\0` /// cannot be read. fn view<'a>(files: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Entry + 'a { diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 949a0d26b..6f37e157f 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -3793,6 +3793,14 @@ a file of the package's project that the vendored run for that package would poi | rules_ruby `ruby.bundle_fetch` | `gemfile_lock`, `gemfile` | `Gemfile`, `Gemfile.lock` | | any call of the `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`) | the same; a label `@//...` names the main repository where the file says `workspace(name = "")` | the same | +The `WORKSPACE` file counts unless the checkout names a Bazel release of 9 or later, which +never reads one: a file that a move to Bzlmod left behind can still name the lock, and +stands in no build's way. The release is the one `.bazelversion` names, or +`USE_BAZEL_VERSION` in `.bazeliskrc`, and only three numbers name one (`9.3.2`). With an +older release, with `latest` or a release candidate, and with neither file, the +`WORKSPACE` file counts, because a Bazel 7 or 8 may build the checkout. Where it does not +count, it is no reason to decline and no doubt, whatever it holds. + Which files a run writes depends on the tool that locks the Python project, as in the matrix at the top: @@ -3825,14 +3833,15 @@ read its lock. That is: - a module file that is missing or cannot be read, or a statement of one that cannot be read, where the workspace calls the hub or a file that was read names its ruleset (a `bazel_dep` on rules_python or rules_ruby, or a `use_extension` of the hub's `.bzl` file); -- a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all. +- a root `MODULE.bazel` that cannot be read at all, or a `WORKSPACE` file that cannot be + and counts (see above). A file cannot be read here when one byte of it is not UTF-8 (a name in a comment is enough), or when it is larger than 1 MiB; Bazel builds both. Going on there can leave a broken build behind a command that exited 0; declining costs a vendored run, which the switch below brings back. A workspace whose root `MODULE.bazel` and `WORKSPACE` file were read (or are not -there), and in which no file that was read calls the hub or names its ruleset, is never -declined for it, whatever else cannot be read. +there, or the `WORKSPACE` file does not count), and in which no file that was read calls +the hub or names its ruleset, is never declined for it, whatever else cannot be read. **What you see.** Every command that would vendor the package reports it `failed` with `vendor_pypi_bazel_hub` or `vendor_gem_bazel_hub` and exits 1: `scan --mode vendored`, @@ -3865,10 +3874,11 @@ unpatched package from its own file, as before. Vendored mode goes on when you say so, with `--allow-vendored-in-bazel` or `SOCKET_ALLOW_VENDORED_IN_BAZEL=1`: for a hub that no build of yours uses, for a `WORKSPACE` -file that your Bazel no longer reads (Bazel 9 never reads it, Bazel 8 only with -`--enable_workspace`), or for a `ruby.bundle_fetch` to which you add every file of the -vendored gem as `srcs`, which rules_ruby copies beside the Gemfile (no test here builds -that). socket-patch checks none of these. It is the switch of +file that your Bazel does not read while the checkout does not say so (Bazel 8 reads it +only with `--enable_workspace`; for Bazel 9, naming the release in `.bazelversion` is +enough, and no switch is needed), or for a `ruby.bundle_fetch` to which you add every file +of the vendored gem as `srcs`, which rules_ruby copies beside the Gemfile (no test here +builds that). socket-patch checks none of these. It is the switch of [Bazel workspaces: Composer](#bazel-workspaces-composer). `vendor --revert` is never declined. Neither is a package that is already vendored: where @@ -3896,13 +3906,16 @@ Limits: another tag or another ruleset that reads the same file under Bzlmod (rules_ruby's older `ruby.bundle`, rules_pycross, aspect_rules_py), a `WORKSPACE` call that hides its arguments behind `**`, the `pip_install(requirements = ...)` of an older rules_python in a - `WORKSPACE` file, a Bazel root that the lookup does not reach, and a hub whose call - and whose `bazel_dep` are both in an included file that cannot be read, while the files - that were read name neither. + `WORKSPACE` file, a Bazel root that the lookup does not reach, a `WORKSPACE` file of a + checkout that names Bazel 9 or later while an older Bazel builds it (`USE_BAZEL_VERSION` + in the environment outranks both files and is not read), and a hub whose call and whose + `bazel_dep` are both in an included file that cannot be read, while the files that were + read name neither. - Declined although the build would pass: a `WORKSPACE` file that names the lock while the - Bazel in use does not read that file, a hub call that never runs, and a workspace that - does not use the ruleset while its root `MODULE.bazel` or its `WORKSPACE` file cannot be - read here, or while a file that was read names the ruleset and another cannot be read. + Bazel in use does not read that file and the checkout names no release of 9 or later, a + hub call that never runs, and a workspace that does not use the ruleset while its root + `MODULE.bazel` or its `WORKSPACE` file cannot be read here, or while a file that was read + names the ruleset and another cannot be read. - Declined although the run would write nothing to the file the call names: a package that is already vendored where the file that names its copy is not the one the call names (a requirements file that the named one includes with `-r`; the `Gemfile` when the call names diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 01494161d..3903abd1e 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 4042 + "max": 4047 }, "lock-readers": { "paths": [ From 752c70b6c1e1a35c01b8c838c0c5fa5b727b77fb Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 12:01:43 -0500 Subject: [PATCH 18/19] Count an entry of the block only where it reaches the hub that fetches the jar `maven::upstream` took an entry of the patch in the block of `MODULE.bazel` for "Bazel builds the patch" and said nothing of the jar, so `vex` attested `not_affected`. It did not ask whether the entry's `override_repo` reaches the hub. The block overrides a repository of the shared usage of the ruleset's extension, which reaches no hub whose `use_extension` is an isolated one (`isolate = True`). `Hubs::label`, by which hosted and vendored mode write an entry, declines such a hub, but it was asked only where the block holds no entry. Measured on Bazel 9.3.2 with a temporary flow: after the hosted command wrote its entry, the hub's `use_extension` was given `isolate = True`. Under `--experimental_isolated_extension_usages`, without which Bazel does not take `isolate` at all, the build passes with the entry in place and `//:consumer` prints the upstream jar. The document said `not_affected` of it. An entry of the patch now counts only where no pinned hub that fetches the jar is on an isolated usage. Otherwise the statement is `affected` for that hub, also where another hub does take the entry. It says first that "the entry that MODULE.bazel holds for this patch does not reach this hub", and then why hosted and vendored mode write none that does, with the code and the reason of their warning (`maven_bazel_unreadable`), as for the other declines. Only what is certain. `Hub::proxy` is `None` for a usage that is isolated and for one that cannot be read: an `isolate` that is neither `True` nor `False`, a label that is no plain string. The second kind may be a shared usage, which the entry reaches. So the reader keeps the two apart (`Hub::isolated`: each tag of the hub is on a usage with `isolate = True`), and beside a usage that cannot be read the entry stands and the statement stays `not_affected`. Without an entry nothing changes: the hub fetches the upstream jar whatever its usage is, and the statement was `affected` already. Tests. The unit test of `upstream` has the rows: an entry beside an isolated hub, beside a usage that cannot be read, beside two hubs of which one is isolated (that one is named), and a hub with tags on both kinds of usage. Without Bazel, `e2e_bazel_build` runs the hosted and the vendored command, sees `not_affected`, makes the hub's usage an isolated one and sees `affected` with those words. Every existing test of an entry that reaches its hub passes unchanged. The line budget of `bazel/` goes from 4084 to 4096. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../tests/e2e_bazel_build/maven.rs | 42 +++++++ crates/socket-patch-core/src/bazel/maven.rs | 117 ++++++++++++++---- docs/ecosystems.md | 19 ++- scripts/loc-budget.json | 2 +- 5 files changed, 152 insertions(+), 30 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 67c5bae4f..0b862d12a 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -4180,7 +4180,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`, rules_rust `crate.from_cargo`, rules_csharp `nuget.from_lock`, rules_jvm_external `maven.install`), 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 patch of a Maven artifact in any mode (in an installed jar, in a pin of a `pom.xml` or a Gradle file, in a copy vendored for such a build) while a pinned hub fetches the plain jar of that artifact at that version and the block that hosted and vendored mode keep in the root `MODULE.bazel` holds no entry of that patch for it (no file of a project decides what a hub fetches: the same from every project of the workspace, and the same after a hosted or vendored command that wrote no entry for the hub; a jar that the hub takes from the Maven local repository under `m2local` counts as fetched, and the lock's sha256 is not compared with the patch), 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 Maven jar `get pkg:maven//@ --mode hosted` at the Bazel root, or with `--mode vendored`, the package by its coordinates alone, without the qualifiers of its purl; where hosted and vendored mode write no entry for the hub, in the place of the command ``Hosted and vendored mode write no entry for this hub (``): .`` with the `maven_bazel_*` code and the reason of the warning that the command gives (those of vendored mode: an option about downloads does not count); before either, when the block holds the entry of another patch for the jar, ``MODULE.bazel holds the entry of patch for this jar, and where the block is in effect the Bazel build takes that patch's jar.``; for a vendored PyPI 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).``; a Maven statement, which is one for every mode, says ``the patch is only in what Maven or Gradle builds from`` where the others say ``the patch is only in the installed copy``, and ends ``If what you ship is what Maven or Gradle builds and not what Bazel builds, pass …``), 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`, under which the Bazel workspace is not read for the document (see "The installed tree" under "VEX provenance markers": what the host command itself does and says in a Bazel workspace stays), for a hosted pin of another ecosystem than Maven, 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), for a Maven jar when the block holds the entry of its patch, or was changed by hand and still calls `override_repo`, when a `maven.override` names the artifact, when the hub that would fetch it or its lock cannot be read (what is not known of another hub, such as a second hub without `lock_file` or a `maven_install` of a `WORKSPACE` file, changes nothing), or when the checkout does not say that Bazel reads `MODULE.bazel` as it stands (`.bazeliskrc` or `.bazelversion` names a Bazel before 7.0, or neither names a release while a `WORKSPACE` file defines a repository; an rc file of the checkout names `enable_bzlmod` other than switched on while the checkout names no Bazel 9 or later, or `--ignore_dev_dependency` without switching it off, on whatever line, or cannot be read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, which for a Maven jar counts only while the checkout names no Bazel release, 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`, rules_jvm_external `maven.install`), 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 patch of a Maven artifact in any mode (in an installed jar, in a pin of a `pom.xml` or a Gradle file, in a copy vendored for such a build) while a pinned hub fetches the plain jar of that artifact at that version and the block that hosted and vendored mode keep in the root `MODULE.bazel` holds no entry of that patch for it, or holds one that does not reach the hub because the hub's `use_extension` is isolated (`isolate = True`: no `override_repo` of the block reaches such a usage, and the hub keeps the jar of its lock) (no file of a project decides what a hub fetches: the same from every project of the workspace, and the same after a hosted or vendored command that wrote no entry for the hub; a jar that the hub takes from the Maven local repository under `m2local` counts as fetched, and the lock's sha256 is not compared with the patch), 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 Maven jar `get pkg:maven//@ --mode hosted` at the Bazel root, or with `--mode vendored`, the package by its coordinates alone, without the qualifiers of its purl; where hosted and vendored mode write no entry for the hub, in the place of the command ``Hosted and vendored mode write no entry for this hub (``): .`` with the `maven_bazel_*` code and the reason of the warning that the command gives (those of vendored mode: an option about downloads does not count); before either, when the block holds the entry of another patch for the jar, ``MODULE.bazel holds the entry of patch for this jar, and where the block is in effect the Bazel build takes that patch's jar.``, and when it holds the entry of the patch itself, which does not reach an isolated hub, ``The entry that MODULE.bazel holds for this patch does not reach this hub.``; for a vendored PyPI 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).``; a Maven statement, which is one for every mode, says ``the patch is only in what Maven or Gradle builds from`` where the others say ``the patch is only in the installed copy``, and ends ``If what you ship is what Maven or Gradle builds and not what Bazel builds, pass …``), 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`, under which the Bazel workspace is not read for the document (see "The installed tree" under "VEX provenance markers": what the host command itself does and says in a Bazel workspace stays), for a hosted pin of another ecosystem than Maven, 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), for a Maven jar when the block holds the entry of its patch and no hub that fetches the jar is on an isolated `use_extension` (a usage that cannot be read may be a shared one: the entry stands), or was changed by hand and still calls `override_repo`, when a `maven.override` names the artifact, when the hub that would fetch it or its lock cannot be read (what is not known of another hub, such as a second hub without `lock_file` or a `maven_install` of a `WORKSPACE` file, changes nothing), or when the checkout does not say that Bazel reads `MODULE.bazel` as it stands (`.bazeliskrc` or `.bazelversion` names a Bazel before 7.0, or neither names a release while a `WORKSPACE` file defines a repository; an rc file of the checkout names `enable_bzlmod` other than switched on while the checkout names no Bazel 9 or later, or `--ignore_dev_dependency` without switching it off, on whatever line, or cannot be read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, which for a Maven jar counts only while the checkout names no Bazel release, 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/tests/e2e_bazel_build/maven.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs index 1f02fbe68..bc1d142c2 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs @@ -1616,6 +1616,48 @@ fn an_installed_jar_is_affected_beside_a_hub_that_fetches_its_own() { } } +/// Without a Bazel: the entry of the patch in the block, and a hub that it +/// does not reach. The hosted and the vendored command each write their +/// entry for the hub, and `vex` says not affected. Then the hub's +/// `use_extension` becomes an isolated one, which no `override_repo` of +/// another usage reaches: `vex` says affected of the hub and its lock, +/// says that the entry does not reach the hub, and gives the code and the +/// reason of the warning with which each mode would decline now. +#[test] +fn an_entry_is_no_patch_of_a_hub_on_an_isolated_usage() { + for (mode, how) in [("hosted", How::Hosted), ("vendored", How::Vendored)] { + let flow = Pinned::unbuilt(); + // The installed jar is the patched one, as agent mode leaves it: no + // document has a word about an installed tree that differs. + let installed = flow.tools.path().join("m2"); + let installed = installed.join(repo_path(VICTIM, VERSION, "jar")); + let jar = victim(&format!("PATCHED {}", flow.patch.uuid)); + std::fs::write(installed, jar).expect("the installed jar"); + let get = flow.vendored(&["get", PURL, "--mode", mode, "--yes"]); + assert_eq!(get.envelope["summary"]["applied"], 1, "{}", get.dump); + let run = |cell: &Cell, args: &[&str]| flow.socket_patch_in(cell, &flow.standin, args); + let patched = Claim::new(PURL, &flow.patch.uuid, how); + flow.cell.stands_alone(run, &patched, true); + + let module = std::fs::read_to_string(flow.cell.path(MODULE)).expect(MODULE); + let usage = "\"maven\")\nmaven.install("; + assert_eq!(module.matches(usage).count(), 1, "{module}"); + let isolated = module.replace(usage, "\"maven\", isolate = True)\nmaven.install("); + flow.cell.write(MODULE, isolated); + let call = module.lines().position(|line| line == "maven.install("); + let remedy = format!( + "The entry that {MODULE} holds for this patch does not reach this hub. {NO_ENTRY} \ + (`maven_bazel_unreadable`): {MODULE}:{}: a tag of hub \"{HUB}\" is called on a \ + `use_extension` that is isolated or cannot be read, which no `override_repo` of \ + another usage reaches.", + call.expect("the hub") + 1 + ); + let names = flow.affected(&remedy); + let unreached = Claim::unbuilt(PURL, &flow.patch.uuid, &names); + flow.cell.stands_alone(run, &unreached, true); + } +} + /// Without a Bazel: what stays the statement of a project without Bazel /// while the patch is in the installed jar alone /// ([`Cell::keeps_its_statement`]). The hubs of which nothing is said: one diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 6a26f4974..c9bcb0330 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -162,27 +162,37 @@ pub struct Hub { /// usage that cannot be read or is isolated: an `override_repo` on /// another usage does not reach the repositories of that one. pub proxy: Option, + /// Whether that is certain: each of its tags is called on a + /// `use_extension` with `isolate = True`. + pub isolated: bool, } /// The label of the `use_extension` call behind the proxy that `tag` is /// called on, when that usage is shared with every other one of the /// extension (`isolate` is not given, or is `False`) and its label holds -/// nothing a string of the block would have to escape. -fn proxy(ws: &Workspace, tag: &Tag) -> Option { - let (_, file) = ws.files.iter().find(|(path, _)| path == tag.file)?; - let Bound::Call(made) = file.binds.get(tag.call.bind?)?.to else { - return None; +/// nothing a string of the block would have to escape. Otherwise, whether +/// the usage is isolated for certain (`isolate = True`): one that cannot +/// be read may be shared. +fn proxy(ws: &Workspace, tag: &Tag) -> Result { + let made = || { + let (_, file) = ws.files.iter().find(|(path, _)| path == tag.file)?; + let Bound::Call(made) = file.binds.get(tag.call.bind?)?.to else { + return None; + }; + file.calls.get(made) }; - let made = file.calls.get(made)?; - let shared = match made.arg("isolate") { - None => true, - Some(Value::Name(isolate)) => isolate == "False", - Some(_) => false, + let made = made().ok_or(false)?; + let isolate = match made.arg("isolate") { + None => "False", + Some(Value::Name(isolate)) => isolate, + Some(_) => "", }; let plain = |b: u8| b.is_ascii_alphanumeric() || b"@/:._-+~".contains(&b); match made.positional(0) { - Some(Value::Str(label)) if shared && label.bytes().all(plain) => Some(label.clone()), - _ => None, + Some(Value::Str(label)) if isolate == "False" && label.bytes().all(plain) => { + Ok(label.clone()) + } + _ => Err(isolate == "True"), } } @@ -245,17 +255,20 @@ pub fn hubs(ws: &Workspace) -> (Vec, Vec) { } }; let proxy = proxy(ws, tag); + let isolated = proxy == Err(true); let Some(hub) = hubs.iter_mut().find(|hub| hub.name == name) else { hubs.push(Hub { name, file, line, lock, - proxy, + proxy: proxy.ok(), + isolated, }); continue; }; - hub.proxy = hub.proxy.take().filter(|_| proxy.is_some()); + hub.proxy = hub.proxy.take().filter(|_| proxy.is_ok()); + hub.isolated &= isolated; if pins && hub.lock != lock { let (first, at) = (&hub.file, hub.line); let why = format!("this tag and the one at {first}:{at} name different locks"); @@ -1744,10 +1757,14 @@ fn command(group: &str, artifact: &str, version: &str) -> String { /// It is said only when it is certain of that hub, whatever is not known /// of another one: the hub and its lock were read and no `maven.override` /// names the artifact ([`Hubs::built`]), and the block holds no entry of -/// this patch for the jar. A block that was changed by hand and still -/// overrides a repository may hold one: the reader does not follow such -/// a call, so no hub is read beside it. One that overrides nothing holds -/// no entry, and no mode writes to it. `None` +/// this patch for the jar, or one that does not reach a hub that fetches +/// it. An `override_repo` of the block reaches no hub on an isolated +/// usage ([`Hub::isolated`]), which keeps the jar of its lock and is the +/// hub that is named then. Of a usage that cannot be read that is not +/// certain, and the entry stands. A block that was changed by hand and +/// still overrides a repository may hold an entry: the reader does not +/// follow such a call, so no hub is read beside it. One that overrides +/// nothing holds no entry, and no mode writes to it. `None` /// otherwise, and where the checkout does not say that Bazel reads /// `MODULE.bazel` as it stands: it names a Bazel before 7.0, or none /// while a `WORKSPACE` file defines something, or an rc file names an @@ -1760,7 +1777,8 @@ fn command(group: &str, artifact: &str, version: &str) -> String { /// root, or why hosted and vendored mode write none there, with the code /// and in the words of their warning ([`verdicts`]). The entry of another /// patch is named first: Bazel takes that one's jar until the command has -/// put this one's in its place. +/// put this one's in its place. So is the entry of this patch that does +/// not reach the hub. pub fn upstream(root: &Path, patches: &[(&str, &str)]) -> Vec> { let jar = |purl| parse_maven_purl(purl).filter(|_| plain(purl)); let jars: Vec<_> = patches.iter().map(|&(purl, _)| jar(purl)).collect(); @@ -1784,7 +1802,10 @@ pub fn upstream(root: &Path, patches: &[(&str, &str)]) -> Vec Vec format!("The entry that {FILE} holds for this patch does not reach this hub. "), + false => format!( "{FILE} holds the entry of patch {held} for this jar, and where the block is \ in effect the Bazel build takes that patch's jar. " - ) + ), }); let remedy = match entry { Ok(()) => format!( @@ -1810,7 +1832,8 @@ pub fn upstream(root: &Path, patches: &[(&str, &str)]) -> Vec for this jar, and where the block is in effect the Bazel build takes that patch's jar"); the command puts its entry in that one's place. +When it holds the entry of the patch itself and the hub is on an isolated `use_extension`, +the statement says first that "the entry that MODULE.bazel holds for this patch does not +reach this hub", and then why no mode writes one that does (`maven_bazel_unreadable`). A command that declines still pins or vendors the patch for a `pom.xml` or a Gradle build beside the hub, and exits 0. The next document says `affected` all the same: the patch is @@ -4665,7 +4679,8 @@ the build is broken): rules_js, rules_rust and rules_csharp, which build from the lock and never read the patched copy. - **A Maven patch beside rules_jvm_external**, in any mode, wherever the statement does not - say `affected` above: the hub that fetches the jar is not read with certainty; the + say `affected` above: the hub that fetches the jar is not read with certainty (also a + hub whose `use_extension` cannot be read, beside an entry of the patch); the checkout does not say that Bazel reads `MODULE.bazel` as it stands (an rc file that names `enable_bzlmod` or `--ignore_dev_dependency`, a `WORKSPACE` file beside no named release); or the jar reaches Bazel in a way that diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 305019eaa..32a176e67 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 4084 + "max": 4096 }, "lock-readers": { "paths": [ From 7bb34cc1ac750812487b224b111a4322ef822227 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 12:18:03 -0500 Subject: [PATCH 19/19] Hold the Maven statement to the switch for a project that Bazel does not build Main gained `SOCKET_NO_BAZEL`, which makes every command do what it does for a project in no Bazel workspace, and this branch gained a statement that a Maven patch gets from any project of the workspace: a `maven_install.json` names no project, so a Maven service that Bazel does not build is `affected` too, beside a hub that pins the same artifact. That is the project the switch is for. The judgement goes through the workspace lookup, so the switch already turns it off. A test now holds it: beside the hub that fetches the jar, `apply --vex` with `SOCKET_NO_BAZEL=1` is the run of the same checkout without its Bazel files, in exit code, output and files, and is not the run beside the hub. The docs say it in both places: the list of what a Bazel workspace changes for a project names the Maven statement, and the Maven limits name the switch beside `--no-bazel`. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_bazel_build/maven.rs | 16 +++++++++++++++- docs/ecosystems.md | 8 ++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs index bc1d142c2..40d0eaafa 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs @@ -1668,7 +1668,8 @@ fn an_entry_is_no_patch_of_a_hub_on_an_isolated_usage() { /// `WORKSPACE` file that defines a repository; the release named is one /// before 7.0. And what a person reads of an `apply` beside the hub that /// fetches the jar: the warning and the count of the statement, and -/// nothing under `--silent`. +/// nothing under `--silent`. With `SOCKET_NO_BAZEL=1` that `apply` and its +/// document are those of the checkout without its Bazel files. #[test] fn an_installed_jar_is_attested_where_no_hub_is_shown_to_fetch_its_own() { let flow = Pinned::unbuilt(); @@ -1690,6 +1691,19 @@ fn an_installed_jar_is_attested_where_no_hub_is_shown_to_fetch_its_own() { .tells_a_person(&origin, &apply, &told, &document, &claim, &warned); } + // The switch for a project that Bazel does not build: with it the run + // is the one of the checkout without its Bazel files, which is not + // the run beside the hub. + let bazel = [ + MODULE, + "MODULE.bazel.lock", + "maven_install.json", + ".bazelversion", + ]; + let apply = [&["apply"][..], &with_vex(&document)].concat(); + flow.cell + .off_is_without_bazel(&origin, &apply, &told, &bazel); + let run = |cell: &Cell, args: &[&str]| flow.socket_patch_in(cell, &flow.standin, args); let installed = Claim::new(PURL, &flow.patch.uuid, How::Agent); let repository = "http_archive(name = \"zlib\", urls = [])\n"; diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 0e0da309a..91ac1849c 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2405,7 +2405,9 @@ projects too. What the sections below then do for it: under `.socket/vendor/maven/`), and a run that does not patch such a hub says so, per patch, when the hub builds the artifact, or may ([Bazel workspaces: Maven](#bazel-workspaces-maven)). -- VEX: a package is attested `affected` when a hub call names the project's lock. +- VEX: a package is attested `affected` when a hub call names the project's lock, and a + Maven artifact when a pinned rules_jvm_external hub fetches its jar, whichever project of + the workspace holds the patch ([Bazel workspaces: VEX](#bazel-workspaces-vex)). `SOCKET_NO_BAZEL=1` in the environment switches all of it off (`1`, `true`, `yes`, `on`, `y` or `t`, in any case, as for the other switches that are read from the environment alone; an @@ -2983,7 +2985,9 @@ Limits: - `socket-patch vex` holds every Maven patch to the hubs (above), and a `maven_install.json` names no project. So a project of the workspace that Maven or Gradle builds and Bazel does not gets `affected` too, beside a hub that pins the same artifact at the same - version. `--no-bazel` is for the repository that ships what Maven or Gradle builds. + version. `--no-bazel` is for the repository that ships what Maven or Gradle builds, and + [`SOCKET_NO_BAZEL=1`](#bazel-workspaces-a-project-that-bazel-does-not-build) for the + project that Bazel does not build at all. ## Bazel workspaces: Cargo