From 9bd7d4f223e6e51dd3e6556a9bc73bf6f8240de8 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 23 Nov 2026 15:53:12 -0500 Subject: [PATCH 01/22] 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/22] 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/22] 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/22] 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 6005d87b6555f6a5ec5ec617b387f2e2103f304a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 23 Nov 2026 20:44:07 -0500 Subject: [PATCH 05/22] Test a gem committed for a Bazel hub and named by a relative file: URL Tests only. rules_ruby's `ruby.bundle_fetch` copies `Gemfile` and `Gemfile.lock` into a repository of Bazel's, has Bazel download `gems/-.gem` for every gem of a `GEM` section, and runs `bundle install --local` there. Vendored mode names its copy by a path, which that repository does not hold, so beside such a hub the command declines (ruby::vendored_bundle_fetch, which stays as it is). ruby::file_source_by_hand shows a vendored form that this hub does build, written by hand in the fixture of the two other flows (rules_ruby 1.0.0-rc2, a lock with a `CHECKSUMS` section, no `gem_checksums`). It is the pair hosted mode writes, with a relative `file:` URL of the checkout in the place of the patch registry's: gem "sp-victim", "1.0.0", source: "file:.socket/vendor/gem//" GEM remote: file:.socket/vendor/gem// specs: sp-victim (1.0.0) DEPENDENCIES sp-victim (= 1.0.0)! CHECKSUMS sp-victim (1.0.0) sha256= and the patched gem committed at `.socket/vendor/gem//gems/sp-victim-1.0.0.gem`, where rules_ruby asks that source for it. No file of Bazel's is written. Bazel's server runs in the root of the workspace and opens the URL from there, and Bundler holds the file to the lock's `CHECKSUMS` line. The flow builds the unpatched checkout, writes the three files, and builds them on a second machine: a new output base (on Bazel 9 a new contents cache too), a downloader config that sends nothing to a patch host and refuses its URLs, and a repository cache that holds no copy of the patched gem. `bazel build` and `bazel run //:consumer` print the patched marker, Bazel changes no file, a `--lockfile_mode=error` build passes, and the stand-in was asked for no patched gem and for no further upstream one. On a third machine the last byte of the committed gem is another one. That byte is padding of the tar, so RubyGems still reads the file, and the build fails in the `bundle install` action with "Bundler found mismatched checksums", which names the sha256 of the lock and the one of the file. rules_ruby installs the Bundler that the lock's `BUNDLED WITH` names in the hub and runs it there. The fixture's lock names 4.0.15, and most locks today name a Bundler of the 2 line, so a fourth and a fifth machine do both again with 2.6.9 in the lock: the hub holds `@bundle//:bundler-2.6.9`, the build prints the patched marker, and the changed byte fails it with the same message. Bazel downloads that Bundler from rubygems.org with the sha256 of rules_ruby's own table, as it does the 4.0.15 of the other flows. The flow passes on Bazel 9.3.2 with the product code as it is, and on 8.8.2 and 7.7.2 with the change that follows, which it does not use (macOS arm64). The downloader rules of a flow are now a function (`routes`), so that a machine without a patch host keeps the two rules for the gems of rubygems.org. Bundler's message is compared without white space in one place for both flows. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_bazel_build/ruby.rs | 237 +++++++++++++++++- 1 file changed, 228 insertions(+), 9 deletions(-) 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 a5f2b8dd6..4dadafb34 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -37,6 +37,17 @@ //! the two files back. Hosted mode, which the refusal names, then patches //! the build. //! +//! A vendored gem that this hub does build is one the lock names as hosted +//! mode names it, with the patch registry's URL replaced by a relative +//! `file:` URL of a directory of the checkout that holds the patched gem at +//! `gems/-.gem`. rules_ruby asks Bazel for that URL, Bazel +//! reads it from the root of the workspace, and Bundler holds the file to +//! the lock's `CHECKSUMS` line. [`file_source_by_hand`] writes those three +//! files by hand ([`by_hand`]) and builds them on a second machine that +//! reaches no patch host, and on a third one where one byte of the gem is +//! another. The hub runs the Bundler its lock names, so the flow does both +//! again with a lock that names Bundler 2.6.9 ([`OLDER_BUNDLER`]). +//! //! 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 @@ -76,6 +87,7 @@ //! that host (`SOCKET_PATCH_SERVER_URL`). use std::io::Write as _; +use std::path::PathBuf; use std::time::Instant; use base64::Engine as _; @@ -86,7 +98,7 @@ 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, Declined, Fixture, - How, Ran, StandIn, ALLOW, CONSUMER, NOTHING, VENDORED, + How, Ran, StandIn, Tree, ALLOW, CONSUMER, NOTHING, REPO_CACHE, VENDORED, }; use crate::hosted_memory_common::{read_tree, Patch, ORG}; @@ -348,13 +360,7 @@ impl Served { let record_route = format!("/v0/orgs/{ORG}/patches/view/{uuid}"); standin.serve(1, &record_route, record.to_string().as_bytes()); - let gems = |name: &str| rewrite(&format!("{RUBYGEMS}/gems/{name}-"), &origin); - cell.route_downloads(&[ - gems(NAME), - gems(NEIGHBOUR), - rewrite(&format!("{PATCH_HOST}/"), &origin), - format!("block {PATCH_HOST}"), - ]); + cell.route_downloads(&routes(&origin, true)); cell.write("Gemfile.lock", lock_pinning(&neighbour_gem, &upstream_gem)); Served { standin, @@ -371,6 +377,20 @@ impl Served { } } +/// The downloader config of a flow whose stand-in is at `origin`: the +/// fixture's two gems on rubygems.org go there, and so does everything on +/// the patch host where the machine reaches one (`patch_host`). A URL of the +/// patch host that no rule rewrote is refused, so on a machine that reaches +/// none a build that asks for it fails, and no download of Bazel's goes to +/// the real one. +fn routes(origin: &str, patch_host: bool) -> Vec { + let gems = |name: &str| rewrite(&format!("{RUBYGEMS}/gems/{name}-"), origin); + let mut rules = vec![gems(NAME), gems(NEIGHBOUR)]; + rules.extend(patch_host.then(|| rewrite(&format!("{PATCH_HOST}/"), origin))); + rules.push(format!("block {PATCH_HOST}")); + rules +} + /// `socket-patch ` in `cell`, with `standin` as the Socket API and as /// rubygems.org, and with the variables `env` as well. fn run(standin: &StandIn, cell: &Cell, args: &[&str], env: &[(&str, &str)]) -> Ran { @@ -524,6 +544,206 @@ fn hosted_bundle_fetch() { ); } +/// Where the patched gem of the patch `uuid` is committed for a hub: the +/// directory of the patch under `.socket/vendor`, which the lock names as +/// the gem's source, and in it the path rules_ruby asks a source for. +fn committed_gem(uuid: &str) -> String { + format!(".socket/vendor/gem/{uuid}/gems/{NAME}-{VERSION}.gem") +} + +/// The fixture's checkout with the patched gem `patched` of the patch +/// `uuid` vendored for the hub, written by hand: the files that differ from +/// the fixture's, each whole, by its path from the checkout. `Gemfile` and +/// `Gemfile.lock` are what hosted mode writes with the patch registry's URL +/// replaced by `file:.socket/vendor/gem//`, and the gem is committed +/// where rules_ruby asks that source for it. +fn by_hand(uuid: &str, patched: &[u8]) -> Tree { + let source = format!("file:.socket/vendor/gem/{uuid}/"); + let gemfile = format!( + "source \"https://rubygems.org/\"\n\n\ + gem \"{NAME}\", \"{VERSION}\", source: \"{source}\"\n\ + gem \"{NEIGHBOUR}\", \"{VERSION}\"\n" + ); + let lock = format!( + "GEM\n remote: {source}\n specs:\n {NAME} ({VERSION})\n\n\ + GEM\n remote: https://rubygems.org/\n specs:\n {NEIGHBOUR} ({VERSION})\n\n\ + PLATFORMS\n ruby\n\n\ + DEPENDENCIES\n {NEIGHBOUR} (= {VERSION})\n {NAME} (= {VERSION})!\n\n\ + CHECKSUMS\n{}{}\n\ + BUNDLED WITH\n 4.0.15\n", + checksum(NEIGHBOUR, &sha256_hex(&neighbour())), + checksum(NAME, &sha256_hex(patched)), + ); + Tree::from([ + (committed_gem(uuid), patched.to_vec()), + ("Gemfile".to_string(), gemfile.into_bytes()), + ("Gemfile.lock".to_string(), lock.into_bytes()), + ]) +} + +/// Whether the repository cache of `cell`, which its twins share, holds a +/// download of `gem`: Bazel keeps a file there under its sha256. +fn cached(cell: &Cell, gem: &[u8]) -> bool { + let cache = match std::env::var_os(REPO_CACHE) { + Some(shared) => PathBuf::from(shared), + None => cell.path("../cache"), + }; + let files = cache.join("content_addressable/sha256"); + assert!(files.is_dir(), "no repository cache at {}", cache.display()); + files.join(sha256_hex(gem)).join("file").exists() +} + +/// A second machine with the files of `cell` that reaches no patch host: a +/// new output base, and a downloader config that sends nothing there. +fn without_patch_host(cell: &Cell, origin: &str) -> Cell { + let mut twin = cell.twin(); + twin.route_downloads(&routes(origin, false)); + twin +} + +/// What `text` reads without its white space: Bundler breaks a message at +/// the width of the console it runs in. +fn squeezed(text: &str) -> String { + text.split_whitespace().collect() +} + +/// The build of `cell`, where one byte of the committed gem is not the one +/// the lock pins (`patched`), fails on the lock's checksum: Bundler names +/// the sha256 of the lock and the one of the file. +fn fails_on_the_checksum(cell: &Cell, patched: &[u8], changed: &[u8]) { + let build = cell.bazel("build", &[CONSUMER]); + let stderr = squeezed(&build.stderr()); + let sums = [patched, changed].map(|gem| format!("sha256={}", sha256_hex(gem))); + assert!( + !build.ok() + && stderr.contains("mismatchedchecksums") + && sums.iter().all(|sum| stderr.contains(sum)), + "{}: the build did not fail on the checksum of the committed gem:\n{}", + cell.test, + build.dump() + ); +} + +/// A Bundler of the 2 line, which most locks name today, in the place of +/// the fixture's 4.0.15: rules_ruby installs the Bundler of the lock's +/// `BUNDLED WITH` in the hub, and the hub's `bundle install` is that one's. +const OLDER_BUNDLER: &str = "2.6.9"; + +/// Makes the lock of `cell` name [`OLDER_BUNDLER`]. +fn names_the_older_bundler(cell: &Cell) { + let lock = String::from_utf8(cell.tree()["Gemfile.lock"].clone()).expect("a text file"); + let named = "\nBUNDLED WITH\n 4.0.15\n"; + assert!(lock.ends_with(named), "{}: {lock}", cell.test); + let older = format!("\nBUNDLED WITH\n {OLDER_BUNDLER}\n"); + cell.write("Gemfile.lock", lock.replace(named, &older)); +} + +/// `gem` with its last byte changed: one of the padding a tar ends with, so +/// the file is still a gem RubyGems reads, with another sha256. +fn one_byte_changed(gem: &[u8]) -> Vec { + let mut changed = gem.to_vec(); + *changed.last_mut().expect("a gem has bytes") ^= 1; + changed +} + +/// A vendored gem that the hub builds, written by hand. +/// +/// - (a) `bazel build` and `bazel run //:consumer` print the unpatched +/// marker. +/// - (b) By hand ([`by_hand`]): `Gemfile` gives the gem the source +/// `file:.socket/vendor/gem//`, `Gemfile.lock` resolves it from a +/// `GEM` section of that remote with the sha256 of the patched gem in +/// `CHECKSUMS`, and the patched gem is committed at +/// `.socket/vendor/gem//gems/-.gem`. No file of +/// Bazel's is touched. +/// - (c) On a second machine with those files (a new output base and, on +/// Bazel 9, a new contents cache), which reaches no patch host and whose +/// repository cache holds no copy of the patched gem, the same two Bazel +/// commands print the patched marker. Bazel changed no file, and a +/// `--lockfile_mode=error` build passes. The stand-in was asked for no +/// patched gem and for no further upstream one. +/// - (d) On a third machine, with one byte of the committed gem changed, +/// the build fails on the lock's checksum. +/// - (e) On a fourth machine, whose lock names Bundler 2.6.9, the hub holds +/// that Bundler and the same two Bazel commands print the patched marker; +/// on a fifth one, with the changed byte, the build fails on the lock's +/// checksum. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn file_source_by_hand() { + let test = "ruby::file_source_by_hand"; + let started = Instant::now(); + let Some(mut cell) = Cell::open(test, &FIXTURE) else { + return; + }; + let release = cell.release().to_string(); + let served = Served::to(&mut cell); + let (standin, uuid) = (&served.standin, served.uuid.as_str()); + let origin = standin.origin(); + + // (a) The unpatched build. + let before = cell.builds_unpatched(&served.unpatched); + let upstream_fetches = standin.asked(&served.upstream_route); + + // (b) The three files, by hand. + let files = by_hand(uuid, &served.patched_gem); + for (rel, bytes) in &files { + cell.write(rel, bytes); + } + let wired = cell.tree(); + let written: Vec = files.keys().cloned().collect(); + assert_eq!(changed(&before, &wired), written, "{test}"); + + // (c) A second machine: patched, from the committed gem and nothing + // else. + assert!(!cached(&cell, &served.patched_gem), "{test}"); + let second = without_patch_host(&cell, &origin); + second.builds_patched(&wired, &served.patched); + let patch_host = |path: &String| path.starts_with(&format!("/{PATCH_HOST}/")); + let asked: Vec = standin.requests().into_iter().filter(patch_host).collect(); + assert_eq!(asked, NOTHING, "{test}: the patch host was asked"); + assert_eq!( + standin.asked(&served.upstream_route), + upstream_fetches, + "{test}: the patched build fetched the upstream gem" + ); + + // (d) A third machine, where one byte of the committed gem is another. + let third = without_patch_host(&second, &origin); + let other = one_byte_changed(&served.patched_gem); + third.write(&committed_gem(uuid), &other); + fails_on_the_checksum(&third, &served.patched_gem, &other); + + // (e) The same two machines with the Bundler of most locks. + let fourth = without_patch_host(&third, &origin); + fourth.write(&committed_gem(uuid), &served.patched_gem); + names_the_older_bundler(&fourth); + fourth.builds_patched(&fourth.tree(), &served.patched); + let bundler = format!("@bundle//:bundler-{OLDER_BUNDLER}"); + let held = fourth.bazel("query", &[&bundler]); + assert!(held.ok(), "{test}: no {bundler}:\n{}", held.dump()); + let fifth = without_patch_host(&fourth, &origin); + fifth.write(&committed_gem(uuid), &other); + fails_on_the_checksum(&fifth, &served.patched_gem, &other); + assert_eq!( + standin.asked(&served.upstream_route), + upstream_fetches, + "{test}: the build went to the upstream gem" + ); + let asked: Vec = standin.requests().into_iter().filter(patch_host).collect(); + assert_eq!(asked, NOTHING, "{test}: the patch host was asked"); + + println!( + "{test}: Bazel {release} built {:?} on a second machine that reaches no patch host, \ + from {} and a `file:` source in Gemfile and Gemfile.lock written by hand; one changed \ + byte of that gem failed a third machine's build (Bundler: mismatched checksums); the \ + same with Bundler {OLDER_BUNDLER} in the lock and the hub, on a fourth and a fifth; {:?}", + served.patched, + committed_gem(uuid), + started.elapsed() + ); +} + /// The code under which vendored mode declines a gem whose Gemfile or lock /// a hub of the workspace reads, and what a refusal has to name in the /// fixture's checkout: the hub's call with its line in `MODULE.bazel`, and @@ -626,7 +846,6 @@ fn vendored_bundle_fetch() { // 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!( From 3cb76104c8cc09bdfa5625e5eee7687494316eb2 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 23 Nov 2026 20:44:16 -0500 Subject: [PATCH 06/22] Vendor a gem for a Bazel hub as its archive, named by a relative file: URL Vendored mode declined every gem whose `Gemfile` or lock a `ruby.bundle_fetch` call of the Bazel workspace reads (`vendor_gem_bazel_hub`): the copy it commits is named by a path, and rules_ruby runs `bundle install` in a repository of Bazel's that does not hold it. It now vendors such a gem in a form that the hub builds, where the files of the checkout show that it builds, and declines everywhere else as before. The form. The patched gem is committed as the archive the patch service serves, at `.socket/vendor/gem//gems/-.gem`, and the two files name it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` in the registry's place: a `source:` option on the gem's declaration (or the line hosted mode adds for a gem the Gemfile does not declare), a `GEM` section of the gem's own with that remote, a source-pinned `DEPENDENCIES` entry, and the sha256 of the patched gem in `CHECKSUMS`. These are the three files of ruby::file_source_by_hand, byte for byte. rules_ruby asks Bazel for `gems/-.gem`; Bazel's server runs in the root of the workspace and opens the URL from there; Bundler holds the file to the `CHECKSUMS` line. No file of Bazel's is written. Beside the gem the directory of the patch holds the marker and a `.gitignore` (`!*`) and `.gitattributes` of its own, because stock ignore templates name `*.gem`, and the ledger records the archive with its sha256 and size. The pair is not written by new code: it is the hosted planner's own edit (`plan_gem_source` hands `plan_gem_redirect` the URL and the sum), so it is what hosted mode writes for the same project, in the lock's own line endings. Where it is written (`vendor::gem::bazel::gate`). Only for a gem whose `Gemfile` or lock a call of the hub names, and only where each of these holds. All of them are read from the files of the checkout, through the readers of `bazel/`; no Bazel is run: - The checkout names a Bazel release of 7, 8 or 9 other than 9.1.0 (`bazel::rc::declared_release`: `.bazelversion`, or `USE_BAZEL_VERSION` in `.bazeliskrc`). Bazel's history says that `repository_ctx.download` fails on such a URL in 9.1.0 ("Migrate from URL to URI") and that 9.1.1 and 9.2.0 fixed it ("downloader: fix opaque file URI names"); that is read, not run. A checkout that names no release, or one that is not three numbers, is declined: 9.1.0 may build it, or a release to come. - The project is the root of the Bazel workspace: Bazel opens the URL from the root, and the gem lies under the project. - The module files are read with certainty, no `WORKSPACE` file defines a repository, every call of the hub writes out the files it reads, and a call that reads the `Gemfile` or the lock of the project reads both. - Something holds the gem to its bytes in the hub of every call that reads the two files: the lock has a `CHECKSUMS` section, or the `gem_checksums` of each such call (a dict of strings that is written out) have an entry for the gem. With neither, any bytes at that path would build in that hub. Two calls may read the same pair, each for a hub of its own, and the detail names the call without an entry. - The lock names a Bundler that a hub was built with (`BUNDLED WITH`): 2.6 or later of the 2 line, or one of the 4 line. rules_ruby installs the lock's Bundler in the hub and runs it; ruby::file_source_by_hand builds the form with 2.6.9 and 4.0.15, and both fail the build on a changed byte. An older Bundler, and a lock that names none, is declined; every lock that passes has one `GEM` section per source. - The lock holds the gem as its ruby-platform entry. One more condition is known only once the patched gem is downloaded: every `gem_checksums` entry for the gem, in any call that reads the two files, has to hold it to the patched gem, because rules_ruby hands that sha256 to Bazel. An entry for other bytes declines the gem after the download and before any write, with the same code, and the detail names the call, the entry and the sha256 to write there. socket-patch does not edit the call. A dry run downloads nothing and does not show this one. Before any of that the gem meets what vendored mode refuses for every gem, in the same order as outside Bazel: the refusals of the lock, of the declaration and of the stub gemspec (a native extension, a declaration in a `group` block, and the rest). What declines says so. The refusal keeps its code, its exit code and its place (before a download, a takeover or an eject), and the detail names the condition in the place of the sentence about the path: `ruby.bundle_fetch` (MODULE.bazel:15) of the Bazel workspace at /repo names Gemfile.lock; vendored mode commits the patched gem for such a call and names it by a relative `file:` URL, which is not known to build here: the checkout names no Bazel release as three numbers (`.bazelversion`, or `USE_BAZEL_VERSION` in `.bazeliskrc`), and not every release opens such a URL; use `--mode hosted`, ... A doubt of the reader declines as it did, in the words it had. What a run that works says. One warning per gem, `vendor_gem_bazel_file_source`, with what the form costs: Bundler by itself does not install from such a source (`bundle install` on a machine without the gem and `bundle lock --update` fail; on a machine that installed the gem before the patch, `bundle install` passes and the program runs that unpatched copy; measured with Bundler 4.0.15), so the checkout builds its gems through Bazel only, and hosted mode serves both; and Bazel does not watch the gem, so an output base that fetched the hub before keeps what it fetched. A person who ran the command is told to build with Bazel as the next step, where a run that vendored anything else is told to reinstall. Every entry point. The refusal layer (`vendor::bazel_hub::refusals`) asks the gate where it declined, so `scan`, `get` and `vendor`, their dry runs, the takeover of a hosted pin and the eject of one all go on where it holds. The backend (`vendor_gem`) asks it again and takes the gem in `vendor::gem::bazel::vendor`; the download plan asks for the archive and its stub gemspec and stages no tree. The undo. `vendor --revert`, `rollback` and `remove` take the source off the `Gemfile` (the option, or the added line, with the helpers the hosted unwind uses), move the lock's entry back into the section it came from, where Bundler sorts it, and put its `DEPENDENCIES` entry and its `CHECKSUMS` line back as the ledger recorded them, then delete the directory. Both files go back or neither, byte for byte where the lock's entries are in Bundler's own order: a pair whose `source:` or `GEM` section is no longer what the run wrote is left alone with the gem (`vendor_lock_entry_drifted`), and so is a ledger record that would put back a line that is not this gem's. A pair that names the source nowhere has been put back by hand, and only the directory goes. The undo does not edit the call either. Where a `gem_checksums` entry still holds the gem to the sha256 of the patched gem, which is the value the run asked for, Bazel fails the download of the upstream gem that the lock names again (`Checksum was ... but wanted ...`). The undo says so in a warning, `vendor_gem_bazel_checksum_left`, that names the call and the entry; the decline that asks for the value says that no undo puts the old one back. The other commands. A later run is in sync, with or without the switch. `vendor --check` holds the committed gem to the patch (the patched files in it) and to the sha256 of the ledger; `repair` downloads it again, and so does a run that finds the pair in place and the gem gone. A newer patch of the gem takes the source over in place. `list` shows the gem as vendored. Lock discovery reads a `GEM` section whose one remote is the patch's directory, spelled exactly as written, as a vendored reference to that archive where the manifest gives the gem the same source, so `vex` attests the gem as it attests every vendored one: `not_affected`, which ruby::vendored_bundle_fetch now holds to the patched build. `vex` holds the committed gem to its patched files, as it holds every vendored archive; `vendor --check` holds it to its bytes as well. What `vex` says of a gem vendored by its path is unchanged (nothing: its build is not judged). A ledger artifact counts as one committed file by its place, `/gems/.gem`, and not by the suffix alone: a copy vendored by its path is a directory named for its gem and version, and a version may end in `.gem`. The switch. `--allow-vendored-in-bazel` means what it meant: with it vendored mode writes the copy of every other project, named by its path, also where the archive would be written without it. Where nothing changes. Outside a Bazel workspace, and in a workspace whose hubs read none of the project's files, the gem backend takes the path it took: for 40 scenarios in four such places (scan, check, rescan, revert, dry runs, `get`, `vendor`, the eject and the takeover, as JSON and as a person reads them) a binary of this commit prints what a binary of its parent prints, exits as it does and leaves the same files, byte for byte. Tests: - ruby::vendored_bundle_fetch (real Bazel): the checkout names no release, the command declines and the build stays the upstream one; with the release in `.bazelversion` it writes the files of the flow written by hand, the next build prints the patched marker on a machine whose Bazel reaches no patch host, with no request for a patched or an upstream gem, `vendor --check` passes, one changed byte fails `vendor --check` and the build of a second machine, `vendor --revert` restores every file and the upstream build, and hosted mode still patches it. The documents of `--vex`, `vex` and `vex --no-verify` are held to that build. - Without a Bazel, through the binary: the run, the dry run, the in-sync runs, `vendor --check`, `repair`, the three undos, the switch, a hosted scan over the vendored gem and the takeover of a hosted pin; the next step a person is given; a lock that names Bundler 2.6.9; and each condition that declines, with nothing written and no gem fetched: an older Bundler, a second call without an entry, the entry for other bytes in the first call and in a second one. With the entry for the patched gem the gem is vendored with and without a `CHECKSUMS` section, and each of the three undos puts every file back and names the entry it leaves. - Unit tests of the gate, one case per condition; of the undo over the planner's own pairs (a declared gem with its requirement, options and comment, an undeclared one, CRLF, a lock with no `CHECKSUMS`), of a patch that follows another, of a pair that drifted and of a ledger record that names another gem's line; of the archive check; of the backend against a stand-in for the patch service; and of discovery. The three `ruby::` flows pass on Bazel 9.3.2, 8.8.2 and 7.7.2 at this commit (macOS arm64), and ruby::vendored_bundle_fetch fails on 9.3.2 against a binary of the parent; the legs of bazel-ruby.yml run them on the three releases. The test of the refusal in bazel_hub.rs asserted the sentence about the path for a gem below the Bazel root; it now asserts the condition that declines that gem. Docs: docs/ecosystems.md has "Bazel workspaces: RubyGems vendored mode", the vendored cell of the RubyGems row ("Supported with the Bazel release named in `.bazelversion`"), four entries among the known problems (the two costs, the entry an undo leaves in the call, and a hub that Bazel does not fetch again), and what "Bazel workspaces: VEX" says of a vendored gem; CLI_CONTRACT.md has the rows of the code, of the two warnings, of the switch and of the vendored table. bazel-ruby.yml starts its legs for vendor/gem/. The `bazel` group of scripts/loc-budget.json follows the 11 lines added to built.rs. Not covered: `rb_bundle_fetch` in a `WORKSPACE` file, a project below the Bazel root, a gem locked as platform gems and a lock of a Bundler older than 2.6 are declined. Not run: Windows, releases of rules_ruby other than 1.0.0-rc2, and a Bundler other than 4.0.15 and 2.6.9 inside the hub. A gem that the Gemfile does not declare was built by hand on Bazel 9.3.2; no test here builds one. A release that the environment of a machine names in place of the checkout's is not seen. Measured by hand on Bazel 9.3.2 and stated in the docs, with no test here: an output base that fetched a damaged gem keeps failing after `repair` until it fetches the hub again, and a hub that Bazel does not fetch again (pinned in a vendor directory, or built with `--nofetch`) keeps the gems it has. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-ruby.yml | 9 +- crates/socket-patch-cli/CLI_CONTRACT.md | 10 +- crates/socket-patch-cli/src/args.rs | 6 +- .../socket-patch-cli/src/commands/vendor.rs | 10 +- .../tests/e2e_bazel_build/ruby.rs | 557 +++++-- crates/socket-patch-core/src/bazel/built.rs | 34 +- .../src/patch/redirect/mod.rs | 29 +- .../socket-patch-core/src/vendor/bazel_hub.rs | 71 +- crates/socket-patch-core/src/vendor/gem.rs | 243 ++- .../socket-patch-core/src/vendor/gem/bazel.rs | 1438 +++++++++++++++++ .../src/vendor/redownload.rs | 9 +- .../socket-patch-core/src/vendor/refusals.rs | 3 +- crates/socket-patch-core/src/vendor/verify.rs | 7 +- .../socket-patch-core/src/vex/discover/gem.rs | 137 +- docs/ecosystems.md | 195 ++- scripts/loc-budget.json | 2 +- 16 files changed, 2576 insertions(+), 184 deletions(-) create mode 100644 crates/socket-patch-core/src/vendor/gem/bazel.rs diff --git a/.github/workflows/bazel-ruby.yml b/.github/workflows/bazel-ruby.yml index 0c4b1cfd6..0fc921e88 100644 --- a/.github/workflows/bazel-ruby.yml +++ b/.github/workflows/bazel-ruby.yml @@ -31,9 +31,10 @@ on: # discovery, the lock inventory, the Ruby crawler (it says which lock # Bundler loads), the upstream restore of `rollback`, the stale-install # guard that those commands end with, the vendored backend - # (vendor/gem.rs), and the refusal of vendored mode beside a hub that - # reads the lock (vendor/bazel_hub.rs), which vendor/refusals.rs hands - # to every command. + # (vendor/gem.rs, and vendor/gem/ for the gem it commits for a hub), + # and the refusal of vendored mode beside a hub that reads the lock + # (vendor/bazel_hub.rs), which vendor/refusals.rs hands to every + # command. # Last, the VEX code: `vex/` of the core, the files of the `vex` # command, and `bazel/` of the core, which reads the workspace files and # decides whether Bazel builds what was patched. Every flow holds the @@ -71,6 +72,7 @@ on: - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' - 'crates/socket-patch-core/src/vendor/gem.rs' + - 'crates/socket-patch-core/src/vendor/gem/**' - 'crates/socket-patch-core/src/vendor/bazel_hub.rs' - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' @@ -99,6 +101,7 @@ on: - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' - 'crates/socket-patch-core/src/vendor/gem.rs' + - 'crates/socket-patch-core/src/vendor/gem/**' - 'crates/socket-patch-core/src/vendor/bazel_hub.rs' - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 57cdcb712..817adae78 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -122,7 +122,7 @@ Every subcommand accepts the same set of "global" flags via a single shared `Glo | `--no-vlt-install-cleanup` | — | `SOCKET_NO_VLT_INSTALL_CLEANUP` | `false` | bool | Opt out of hosted mode's warm-tree heal for vlt: stale installed copies (`node_modules/.vlt-lock.json` and the stale `node_modules/.vlt/` entries) are left in place after `vlt-lock.json` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`), and the `redirect_vlt_reinstall_required` advisory tells you to run `vlt ci` instead. Stale copies of optional dependencies are always left in place (see `redirect_vlt_reinstall_required`). Other subcommands accept it silently | | `--no-gem-install-refresh` | — | `SOCKET_NO_GEM_INSTALL_REFRESH` | `false` | bool | Opt out of hosted mode's gem stale-install refresh: the gems Bundler already holds for the project (an installed gem under the project and its cached `.gem`, an archive in `vendor/cache`) are left as they are after `Gemfile.lock` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`, of a hosted pin or of a vendored gem; `vendor --revert`), and the `redirect_gem_stale_install` / `upstream_gem_stale_install` warning names the files to remove by hand instead (see the "Gem stale-install guard" section). Other subcommands accept it silently | | `--gem-refresh-shared` | — | `SOCKET_GEM_REFRESH_SHARED` | `false` | bool | Extend the gem stale-install refresh to gem homes OUTSIDE the project (the system gems, `~/.gem`, an rbenv or asdf home) and to project bundle or cache paths that resolve outside the project directory. Off by default: another project on the machine may pin the other build of the same gem version, and its `bundle pristine` then fails on the replaced archive's checksum (see the "Gem stale-install guard" section). Other subcommands accept it silently | -| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default, and the switch lifts each of those refusals. `vendor_composer_bazel_workspace`: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. `vendor_pypi_bazel_hub` and `vendor_gem_bazel_hub`: a rules_python or rules_ruby hub of the workspace reads the lock, which then names the patched copy by a path under `.socket/vendor`, and neither ruleset builds from that. For a project whose build does find the copy, or does not take its packages from that lock. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" and "Bazel workspaces: PyPI and RubyGems vendored mode" | +| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default, and the switch lifts each of those refusals. `vendor_composer_bazel_workspace`: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. `vendor_pypi_bazel_hub` and `vendor_gem_bazel_hub`: a rules_python or rules_ruby hub of the workspace reads the lock, which then names the patched copy by a path under `.socket/vendor`, and neither ruleset builds from that. For a project whose build does find the copy, or does not take its packages from that lock. A gem that vendored mode commits for a rules_ruby hub as an archive without the switch (`vendor_gem_bazel_file_source`) is vendored by its path with it, like every other gem. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" and "Bazel workspaces: PyPI and RubyGems vendored mode" | **`--download-mode` removed (v5.0, MAJOR).** The global `--download-mode` flag and its `SOCKET_DOWNLOAD_MODE` binding are gone, with no alias: passing the flag is a usage error (exit 2) and the env var is ignored. Patch content is always fetched as per-file blobs (`.socket/blobs/`); `.socket/diffs/` archives are obsolete, never read, and removed by the cleanup sweeps. @@ -1688,7 +1688,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` unless the run has `--allow-vendored-in-bazel` | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked prebuilt platform gem per locked platform, `-//`, each with its gemspec, plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patch's prebuilt platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a prebuild: while the patch service lists none for one of them the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the project is refused `vendor_gem_bazel_hub` unless the run has `--allow-vendored-in-bazel` | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked prebuilt platform gem per locked platform, `-//`, each with its gemspec, plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patch's prebuilt platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a prebuild: while the patch service lists none for one of them the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub`, and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -2492,7 +2492,9 @@ command's integration tests check its output. | `vendor_bun_lockb_invalid` | `failed` | vendor / scan / get `--mode vendored`: the binary lock is malformed, unreadable, unsupported or cannot be rewritten safely. The detail names the parser, hash or filesystem error. Refused before patch downloads and before hosted takeover; the package's `failed` event carries `errorCode` and `error`, while `get ` also carries top-level `error.code`. Dry-run predicts the same refusal. | | `vendor_bun_workspace_unsupported` | `failed` | vendor / scan / get `--mode vendored` (bun): the text lock holds `workspace:` packages and its `lockfileVersion` is below 2 — Bun 1.2–1.3 resolve a workspace member's local-tarball path relative to the member; a committed version-2 lock is the proof every consumer runs Bun ≥ 1.4 (deliberate over-approximation: root-only declared packages would install on version 1 too). Detail names the version integer and a version-specific remedy: delete `bun.lock` and re-lock with Bun ≥ 1.4 (an in-place `bun install` keeps the existing version) — then, for a version-1 lock, "or use `--mode hosted`, which accepts version-1 workspace locks"; for a version-0 lock, "or delete `bun.lock`, re-lock with Bun ≥ 1.2 (which writes lockfileVersion 1) and use `--mode hosted`" (hosted refuses version-0 workspace locks, so a bare hosted pointer would send the user into a second refusal). Refused before any write — in the pre-download preflight on `get`/`scan` (see `vendor_bun_lockb_invalid` for the placements); in the shared preflight that `vendor` and the vendor step run BEFORE a hosted → vendored takeover's revert (a hosted-redirected purl stays hosted-wired, ledger and lock untouched; `vendor --dry-run` previews the same `failed` code); and in the engine when the run would write a NEW local tuple. Exempt: purls the vendor ledger wires at the selected uuid, purls whose every `bun.lock` instance is already a `.socket/vendor/npm/` tuple (any uuid), in-sync re-runs and `repair` redownloads. | | `vendor_composer_bazel_workspace` | `failed` | vendor / scan / get `--mode vendored` (composer): the project is in a Bazel workspace (its directory, or one above it up to the root of its git checkout, holds `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`). Vendored mode makes `composer.lock` name the patched copy by a path relative to the directory Composer runs in; a Bazel repository rule or build action that runs `composer install` from the lock anywhere else fails with Composer's `Source path "…" is not found for package …`, and the build with it (Bazel 9.3.2, 8.8.2, 7.7.2). Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the Bazel root and the mode that writes no such path, `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel`, `vendor --revert`, and a package whose `composer.lock` entry already names the copy of the same patch (the run leaves the lock as it is, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included; a new patch for it is refused). A project that commits its `vendor/` tree is refused like any other: the tree shows that Composer has run in the project's directory, not that no rule of the workspace runs it elsewhere as well. See docs/ecosystems.md "Bazel workspaces: Composer". | -| `vendor_pypi_bazel_hub` / `vendor_gem_bazel_hub` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): a hub of the project's Bazel workspace reads a file of the project that the run would point at the copy under `.socket/vendor`. That is a rules_python `pip.parse` whose `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` or `uv_lock` names a requirements file of the project that the run may write (`requirements.txt` or a file it includes with `-r`, as one set: in a project with no tool lock, for a package they name beside a uv, Pipenv or PEP 751 lock, and for a package they hold by a URL, which is a hosted pin, beside a Poetry or PDM lock) or the `uv.lock` of a uv project; a rules_ruby `ruby.bundle_fetch` whose `gemfile` or `gemfile_lock` names the project's `Gemfile` or `Gemfile.lock`; and a call of a `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`), where `@//` is the main repository when the file says `workspace(name = "")`. Neither ruleset builds from such a file: rules_python 2.5.0-rc4 fails with `invalid user-provided repo name '___/_socket/vendor/pypi/…'`, and the `bundle install` action of rules_ruby 1.0.0-rc2 with `The path … does not exist.`, after a command that exited 0 (Bazel 9.3.2, 8.8.2, 7.7.2). Also refused, for every package whose run would write such a file: a workspace whose files cannot be read with certainty where a call of the hub may be behind that (a call of the hub whose file is not a plain string label or that passes `*` or `**`; a hub proxy handed on; a module file or a statement of one that cannot be read, while the workspace calls the hub or a file that was read names its ruleset; a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all, for which one byte that is not UTF-8 is enough), because a call may then read the project's lock. Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the call with its file and line, the lock (or the place and the reason of the doubt), the Bazel root, and the mode whose pin both rulesets build, `--mode hosted` (rules_ruby where its call passes no `gem_checksums`, which the detail for a gem says). Not refused: a package whose run writes no file that such a call names, in a Bazel workspace or outside one (a Poetry or PDM project, whose lock is wired alone, beside a hub that reads its exported `requirements.txt`, unless that file holds the package by a URL); a workspace whose files were read and neither call the hub nor name its ruleset; a run with `--allow-vendored-in-bazel`; `vendor --revert`; and a package that the file the call names already names by the copy of the same patch (`.socket/vendor/pypi//`, `.socket/vendor/gem//`): the run adds nothing to what the hub reads, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included, while a new patch for the package is refused; where the calls name more than one file of the project, each of them that holds the package has to name the copy. Where the reading is in doubt no file is known to be the hub's, and every run without the switch is refused. See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" | +| `vendor_pypi_bazel_hub` / `vendor_gem_bazel_hub` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): a hub of the project's Bazel workspace reads a file of the project that the run would point at the copy under `.socket/vendor`. That is a rules_python `pip.parse` whose `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` or `uv_lock` names a requirements file of the project that the run may write (`requirements.txt` or a file it includes with `-r`, as one set: in a project with no tool lock, for a package they name beside a uv, Pipenv or PEP 751 lock, and for a package they hold by a URL, which is a hosted pin, beside a Poetry or PDM lock) or the `uv.lock` of a uv project; a rules_ruby `ruby.bundle_fetch` whose `gemfile` or `gemfile_lock` names the project's `Gemfile` or `Gemfile.lock`; and a call of a `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`), where `@//` is the main repository when the file says `workspace(name = "")`. Neither ruleset builds from such a file: rules_python 2.5.0-rc4 fails with `invalid user-provided repo name '___/_socket/vendor/pypi/…'`, and the `bundle install` action of rules_ruby 1.0.0-rc2 with `The path … does not exist.`, after a command that exited 0 (Bazel 9.3.2, 8.8.2, 7.7.2). Also refused, for every package whose run would write such a file: a workspace whose files cannot be read with certainty where a call of the hub may be behind that (a call of the hub whose file is not a plain string label or that passes `*` or `**`; a hub proxy handed on; a module file or a statement of one that cannot be read, while the workspace calls the hub or a file that was read names its ruleset; a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all, for which one byte that is not UTF-8 is enough), because a call may then read the project's lock. Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the call with its file and line, the lock (or the place and the reason of the doubt), the Bazel root, and the mode whose pin both rulesets build, `--mode hosted` (rules_ruby where its call passes no `gem_checksums`, which the detail for a gem says). Not refused: a package whose run writes no file that such a call names, in a Bazel workspace or outside one (a Poetry or PDM project, whose lock is wired alone, beside a hub that reads its exported `requirements.txt`, unless that file holds the package by a URL); a workspace whose files were read and neither call the hub nor name its ruleset; a run with `--allow-vendored-in-bazel`; `vendor --revert`; and a package that the file the call names already names by the copy of the same patch (`.socket/vendor/pypi//`, `.socket/vendor/gem//`): the run adds nothing to what the hub reads, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included, while a new patch for the package is refused; where the calls name more than one file of the project, each of them that holds the package has to name the copy. Where the reading is in doubt no file is known to be the hub's, and every run without the switch is refused. For a gem the refusal is narrower: where a `ruby.bundle_fetch` call names the project's `Gemfile` or lock and the reading is certain, the gem is vendored as its committed archive (`vendor_gem_bazel_file_source`) and is refused only where that form is not known to build, which the detail names in the place of the path sentence: the checkout names no Bazel release as three numbers in `.bazelversion` or `.bazeliskrc` (none at all, or `latest` or a release candidate), or names 9.1.0 or one outside 7, 8 and 9; the project is not the root of the Bazel workspace; a `WORKSPACE` file defines repositories; a call of the hub does not write out the files it reads, or reads one of the two files alone; its `gem_checksums` are not written out; the lock has no `CHECKSUMS` section and a call that reads the two files has no `gem_checksums` entry for the gem (the detail names that call); the lock's `BUNDLED WITH` names no Bundler, or one that is neither 2.6 or later of the 2 line nor of the 4 line (the hub runs the lock's Bundler, and was built with 2.6.9 and 4.0.15); or the lock holds the gem as platform gems. One more condition is known only once the patched gem is downloaded, so it is refused by the backend, after the download and before any write, with the same code, and a dry run of `scan` or `get`, which downloads nothing, does not show it: a `gem_checksums` entry of any call that reads the two files that holds the gem to another sha256 than the patched gem's (the detail names the call, the entry and both sums, and says that no undo puts the old value back; no file is edited). See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" and "Bazel workspaces: RubyGems vendored mode" | +| `vendor_gem_bazel_file_source` | `skipped` (advisory; human: `Warning: …`) | vendor / scan / get `--mode vendored` (gem; additive): the gem was committed for a rules_ruby hub of the project's Bazel workspace as its archive, `.socket/vendor/gem//gems/-.gem`, which `Gemfile` and `Gemfile.lock` name by the relative URL `file:.socket/vendor/gem//`. The detail says what that form costs: Bundler by itself does not install from such a source (`bundle install` on a machine without the gem and `bundle lock --update` fail; on a machine that installed the gem before the patch, `bundle install` passes and keeps that unpatched copy), so the checkout builds its gems through Bazel only, and hosted mode serves both; and Bazel does not watch the gem, so an output base that fetched the hub before keeps what it fetched. A human run that vendored only such gems words the second of its `Next steps:` as ``Build with Bazel, which installs the committed gems, then run `socket-patch vex` to verify the installed patches.`` in the place of the reinstall. One event per gem vendored this way by the run; none on an in-sync run, and none with `--allow-vendored-in-bazel`. The ledger entry's artifact is the archive (`artifact.path` is `.socket/vendor/gem//gems/-.gem`, with its `sha256` and `size`), and its wiring records are `gemfile_file_source` and `gemfile_lock_file_source`. See docs/ecosystems.md "Bazel workspaces: RubyGems vendored mode" | +| `vendor_gem_bazel_checksum_left` | warning of the undo (human: `Warning: …`) | `vendor --revert` / `rollback` / `remove` (gem; additive): the undo put `Gemfile` and `Gemfile.lock` back for a gem that was committed for a rules_ruby hub (`vendor_gem_bazel_file_source`), and the `gem_checksums` of a `ruby.bundle_fetch` call of the workspace still hold the gem to the sha256 of the patched gem, which the vendoring run asked the user to write there. socket-patch does not edit the call, so the Bazel build fails on that entry (`Checksum was … but wanted …`) until it holds the upstream gem's sha256 again or is removed. The detail names the call with its file and line, the entry and the sha256. The undo itself is complete and its exit code is unchanged; also reported by its dry run. See docs/ecosystems.md "Bazel workspaces: RubyGems vendored mode" | | `vendor_lockfile_missing` / `vendor_lockfile_version_unsupported` (bun preflight placement) | `failed` | scan / get `--mode vendored` (bun): the pre-download preflight found `bun.lock` unreadable / at a `lockfileVersion` other than 0 to 3 (a newer version: update socket-patch; no integer: re-lock with Bun ≥ 1.2 — the same text as hosted's `redirect_bun_lock_unsupported`) or outside bun's single-line `packages` grammar. Same placements as `vendor_bun_lockb_invalid`; nothing fetched, no patch record. An unreadable `.socket/vendor/state.json` met by the same preflight is `vendor_state_unreadable` (see that row), never one of these. | | `bun_lockb_invalid` | scan `warnings[]` (run-level) | scan (every mode): the native binary inventory could not parse or read `bun.lockb`; detail names the format or filesystem error. Also printed as `Warning: …` on stderr. Exit and status remain unchanged. The warning is retained on empty and non-empty scans; valid binary locks are inventoried normally without a runtime or install. | | `bun_lock_unsupported` | scan `warnings[]` (run-level) | scan (every mode): the text `bun.lock` is there but the lock reader refuses it — a `lockfileVersion` newer than 3, no integer version, or a `packages` section outside bun's single-line grammar (a comment line, a re-indent) — so the packages it lists were not read from the lockfile. Detail is the shared version gate's text or `bun.lock: line : …`, followed by `, so the packages it lists were NOT read from the lockfile: a package that is locked but not installed was not scanned`. Also printed as `Warning: …` on stderr, and a scan that then finds no package at all ends `No packages found (see the warning).` instead of advising an install. Status and exit are unchanged (0): before, a checkout without `node_modules` scanned as an empty project and the lock was not mentioned. Installed packages are still crawled, and hosted / vendored runs keep their own refusal (`redirect_bun_lock_unsupported` / `vendor_lockfile_version_unsupported`). The hosted in-memory engine reports the same code among its warnings. | @@ -4044,7 +4046,7 @@ match it, withholds the statement: | `gradle_unpatched_copy` | `failed[].reason` | The purl the warning above (or `vex_gradle_derived_cache_check_failed`) withheld. | | `vex_gradle_derived_cache_check_failed` | run warning | The derived-cache check of an attested Gradle copy did not finish (it crashed), so a copy derived from the unpatched jar cannot be ruled out; no statement for that purl. | | `vex_gradle_lock_above_base` | run warning and `failed[].reason` | A hosted pin is wired, but a lock file records a release above its base, which that build resolves instead of the patch; no statement until it is re-locked or the patch is rolled back. | -| `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, or the lock of a pnpm workspace above it that names that directory among its importers), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock; for a vendored copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, which reads no Bazel file (see "The installed tree" under "VEX provenance markers"), for a hosted pin, for a vendored gem (no build has shown what rules_ruby does with one), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**` or a `pip.parse` with `uv_lock` (it may take its packages from a file that is not read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | +| `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, or the lock of a pnpm workspace above it that names that directory among its importers), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock; for a vendored copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, which reads no Bazel file (see "The installed tree" under "VEX provenance markers"), for a hosted pin, for a vendored gem (rules_ruby builds one that is committed as its archive, `vendor_gem_bazel_file_source`, and one vendored by its path only when the call lists the copy's files, which is not read), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**` or a `pip.parse` with `uv_lock` (it may take its packages from a file that is not read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | | `vex_pnpm_bundled_copy` | run warning and `failed[].reason` | An npm pin is wired, but its pnpm lock names a package whose `bundledDependencies` may ship an unpatched copy of it (the lock does not record that copy's version); no statement while that package bundles it. `vendor --check` and `scan` still treat the wiring as live. | | `vex_deno_lock_copy` | run warning and `failed[].reason` | An npm pin is wired, but `deno.lock` locks the same `name@version`, which `deno install` installs without the wiring; no statement while it does. `vendor --check` and `scan` still treat the wiring as live. | | `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven patch is wired in a reactor (`` / ``, a profile's included, or Maven 4 subproject discovery) one of whose modules may build the unpatched version: it resolves the patched version, or its selection cannot be told on the machine that runs `vex`, and no pin or declaration of the patch reaches it; or a declaration may still build the base version; or a pom of the reactor cannot be read. No statement; the note names the module (#261). `list`, `rollback` and `remove` still find the wiring. | diff --git a/crates/socket-patch-cli/src/args.rs b/crates/socket-patch-cli/src/args.rs index 136f2e57c..e16f103ae 100644 --- a/crates/socket-patch-cli/src/args.rs +++ b/crates/socket-patch-cli/src/args.rs @@ -433,8 +433,10 @@ pub struct GlobalArgs { /// (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), which builds /// nothing from a lock that names a copy under `.socket/vendor`. Pass /// it when the build does find the copy, or does not take the - /// project's packages from that lock. Other subcommands accept it - /// silently. + /// project's packages from that lock. Without it a gem is committed + /// for a rules_ruby hub as an archive that the hub builds, where + /// that is known to build; with it every gem is vendored by its + /// path. Other subcommands accept it silently. #[arg( help_heading = GLOBAL_OPTIONS, long = "allow-vendored-in-bazel", diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index d90e89e11..d0b3d481f 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -4759,7 +4759,15 @@ fn print_vendor_closing( .iter() .filter(|f| flavor_install_command(f).is_some()) .all(|f| JVM_TOOLS.contains(&f.as_str())); - let reinstall = if jvm_only { + // A gem committed for a rules_ruby hub is installed by the Bazel + // build alone: Bundler by itself fails on its source, which the + // warning of the run says. + let for_bazel = + |e: &&PatchEvent| e.error_code.as_deref() == Some("vendor_gem_bazel_file_source"); + let for_bazel = env.events.iter().filter(for_bazel).count(); + let reinstall = if for_bazel > 0 && for_bazel == env.summary.applied as usize { + "Build with Bazel, which installs the committed gems".to_string() + } else if jvm_only { let cmds: Vec = installs.iter().map(|c| format!("`{c}`")).collect(); format!( "Run {} so the build resolves the vendored artifacts (the generated root \ 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 4dadafb34..7df86e696 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -26,16 +26,11 @@ //! //! The flow asserts the VEX document of its patch as `main.rs` says. //! -//! Vendored mode would commit the unpacked patched gem under -//! `.socket/vendor/gem` and make `Gemfile` and `Gemfile.lock` name it by -//! its path from the project, and rules_ruby runs `bundle install` in a -//! repository of Bazel's that holds the two files and not the copy. So in -//! this checkout, where the hub reads both files, the command declines the -//! gem and writes nothing ([`vendored_bundle_fetch`]): the build stays the -//! unpatched one. With `--allow-vendored-in-bazel` it does what it did -//! before it declined, and the build fails until `vendor --revert` has put -//! the two files back. Hosted mode, which the refusal names, then patches -//! the build. +//! Outside a Bazel workspace vendored mode commits the unpacked patched gem +//! under `.socket/vendor/gem` and makes `Gemfile` and `Gemfile.lock` name +//! it by its path from the project. rules_ruby runs `bundle install` in a +//! repository of Bazel's that holds the two files and not the copy, so that +//! form fails the build of this checkout, where the hub reads both files. //! //! A vendored gem that this hub does build is one the lock names as hosted //! mode names it, with the patch registry's URL replaced by a relative @@ -48,6 +43,19 @@ //! another. The hub runs the Bundler its lock names, so the flow does both //! again with a lock that names Bundler 2.6.9 ([`OLDER_BUNDLER`]). //! +//! [`vendored_bundle_fetch`] holds `scan --mode vendored` to writing those +//! files, byte for byte, where the checkout names the Bazel release it is +//! built with, and to declining the gem where it names none: Bazel 9.1.0 +//! fails on such a URL, and nothing in the checkout says that another +//! release builds it. The tests without a Bazel hold it to every other +//! condition under which it declines +//! ([`a_gem_is_declined_where_the_committed_gem_is_not_known_to_build`]): +//! a Bundler in the lock that no hub here was built with, a second call +//! that reads the pair and holds the gem to other bytes or to none, and +//! the rest. +//! With `--allow-vendored-in-bazel` the command writes the copy of every +//! other project, as it did. +//! //! Both markers are read from what Bazel built, and each holds an id made //! for the run, so no cache of an earlier run can supply either gem. The //! fixture's lock therefore holds no sha256 of a gem: it has a placeholder @@ -96,6 +104,7 @@ use sha2::{Digest, Sha256, Sha512}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; +use crate::envelope::events; use crate::harness::{ cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Declined, Fixture, How, Ran, StandIn, Tree, ALLOW, CONSUMER, NOTHING, REPO_CACHE, VENDORED, @@ -629,13 +638,13 @@ fn fails_on_the_checksum(cell: &Cell, patched: &[u8], changed: &[u8]) { /// `BUNDLED WITH` in the hub, and the hub's `bundle install` is that one's. const OLDER_BUNDLER: &str = "2.6.9"; -/// Makes the lock of `cell` name [`OLDER_BUNDLER`]. -fn names_the_older_bundler(cell: &Cell) { +/// Makes the lock of `cell` name Bundler `version`. +fn names_bundler(cell: &Cell, version: &str) { let lock = String::from_utf8(cell.tree()["Gemfile.lock"].clone()).expect("a text file"); let named = "\nBUNDLED WITH\n 4.0.15\n"; assert!(lock.ends_with(named), "{}: {lock}", cell.test); - let older = format!("\nBUNDLED WITH\n {OLDER_BUNDLER}\n"); - cell.write("Gemfile.lock", lock.replace(named, &older)); + let other = format!("\nBUNDLED WITH\n {version}\n"); + cell.write("Gemfile.lock", lock.replace(named, &other)); } /// `gem` with its last byte changed: one of the padding a tar ends with, so @@ -717,7 +726,7 @@ fn file_source_by_hand() { // (e) The same two machines with the Bundler of most locks. let fourth = without_patch_host(&third, &origin); fourth.write(&committed_gem(uuid), &served.patched_gem); - names_the_older_bundler(&fourth); + names_bundler(&fourth, OLDER_BUNDLER); fourth.builds_patched(&fourth.tree(), &served.patched); let bundler = format!("@bundle//:bundler-{OLDER_BUNDLER}"); let held = fourth.bazel("query", &[&bundler]); @@ -746,46 +755,99 @@ fn file_source_by_hand() { /// The code under which vendored mode declines a gem whose Gemfile or lock /// a hub of the workspace reads, and what a refusal has to name in the -/// fixture's checkout: the hub's call with its line in `MODULE.bazel`, and -/// the file it reads. +/// fixture's checkout: the hub's call with its line in `MODULE.bazel`, the +/// file it reads, and why the committed gem is not known to build there. +/// The fixture names no Bazel release. const DECLINED: Declined = Declined { purl: PURL, code: "vendor_gem_bazel_hub", names: &[ "`ruby.bundle_fetch` (MODULE.bazel:15)", "names Gemfile.lock; ", + "the checkout names no Bazel release as three numbers (`.bazelversion`", ], }; +/// The advisory of a run that committed a gem for a hub. +const ADVISORY: &str = "vendor_gem_bazel_file_source"; +/// The warning of an undo that leaves a `gem_checksums` entry of the call +/// holding the gem to the patched one. +const ENTRY_LEFT: &str = "vendor_gem_bazel_checksum_left"; + /// The variables of a command of vendored mode, which downloads the /// patched gem from the patch host: the stand-in at `origin` is that host. fn patch_host(origin: &str) -> [(&str, &str); 1] { [("SOCKET_PATCH_SERVER_URL", origin)] } -/// Vendored mode beside a hub that reads the Gemfile and its lock. +/// For a finished `scan --mode vendored --yes` in the fixture's checkout +/// with the files `before`, where the hub reads the lock and the checkout +/// names its Bazel release: the command vendored the one gem and says what +/// that form costs. It wrote the three files of [`by_hand`], byte for +/// byte, and beside them only its own: the ledger, the marker of the +/// patch's directory, and the two files that keep git from ignoring or +/// converting the gem. Gives the files of the checkout. +fn committed_for_the_hub(cell: &Cell, scan: &Ran, served: &Served, before: &Tree) -> Tree { + let (test, said) = (&cell.test, &scan.dump); + assert_eq!(scan.code, 0, "{test}: {said}"); + assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{test}: {said}"); + let advised = |event: &&serde_json::Value| event["errorCode"] == ADVISORY; + let advisory = events(&scan.envelope).iter().find(advised); + let advisory = advisory.and_then(|event| event["reason"].as_str()); + let advisory = advisory.unwrap_or_default(); + let costs = [ + "through Bazel only", + "keeps that unpatched copy", + "`--mode hosted`", + "does not watch", + ]; + for cost in costs { + assert!(advisory.contains(cost), "{test}: no {cost:?} in {said}"); + } + let by_hand = by_hand(&served.uuid, &served.patched_gem); + let dir = format!(".socket/vendor/gem/{}", served.uuid); + let own = [".gitattributes", ".gitignore", "socket-patch.vendor.json"]; + let own = own.map(|file| format!("{dir}/{file}")); + let ledger = ".socket/vendor/state.json".to_string(); + let mut written: Vec = by_hand.keys().cloned().chain(own).chain([ledger]).collect(); + written.sort(); + let vendored = cell.tree(); + assert_eq!(changed(before, &vendored), written, "{test}: {said}"); + for (rel, bytes) in &by_hand { + let same = vendored[rel] == *bytes; + assert!(same, "{test}: {rel} is not the file written by hand"); + } + vendored +} + +/// Vendored mode beside a hub that reads the Gemfile and its lock, on a +/// machine whose Bazel reaches no patch host. /// /// - (a) `bazel build` and `bazel run //:consumer` print the unpatched /// marker. -/// - (b) `socket-patch scan --mode vendored --yes` declines the gem: it -/// exits 1, names the call of `MODULE.bazel` that reads the lock, hosted -/// mode and the switch, writes nothing and downloads no gem. The same -/// two Bazel commands print the unpatched marker, and change no file. -/// - (c) With `--allow-vendored-in-bazel` the command does what it did -/// before it declined: it passes and reports the gem vendored. It -/// commits the unpacked patched gem, with its specification and its -/// ledger, under `.socket/vendor`, and makes the declaration of -/// `Gemfile` and a `PATH` section of `Gemfile.lock` name that copy by -/// its path from the project. The same `bazel build` fails: rules_ruby -/// copies `Gemfile` and `Gemfile.lock` into a repository of Bazel's and -/// runs `bundle install` there, where the path names nothing. `vex` -/// attests the gem as patched all the same: it reads the committed -/// copy, and what rules_ruby builds from one is not judged. -/// - (d) `socket-patch vendor --revert`, which takes no switch: every file -/// of the checkout is the one of before, and the build prints the -/// unpatched marker again. -/// - (e) Hosted mode, which the refusal names: the same two Bazel commands -/// print the patched marker. +/// - (b) The checkout names no Bazel release, so `socket-patch scan --mode +/// vendored --yes` declines the gem: it exits 1, names the call of +/// `MODULE.bazel` that reads the lock, the missing release, hosted mode +/// and the switch, writes nothing and downloads no gem. The same two +/// Bazel commands print the unpatched marker, and change no file. +/// - (c) With the release of this Bazel in `.bazelversion`, the same +/// command vendors the gem: it writes the three files of +/// [`file_source_by_hand`], byte for byte, with its ledger, and says +/// what the form costs. +/// - (d) The same two Bazel commands, with no step in between, print the +/// patched marker. Bazel asked for no patched gem and no upstream one, +/// changed no file, and a `--lockfile_mode=error` build passes. +/// `vendor --check` passes. +/// - (e) On a second machine with those files, where one byte of the +/// committed gem is another, `vendor --check` fails on the sha256 of the +/// ledger and the build fails on the lock's checksum. +/// - (f) `socket-patch vendor --revert`: every file of the checkout is the +/// one of before, and the build prints the unpatched marker again. +/// - (g) Hosted mode, which the refusal names, on a machine that reaches +/// the patch host: the same two Bazel commands print the patched marker. +/// +/// The flow asserts the VEX document of its patch as `main.rs` says. #[test] #[ignore = "real Bazel; run with --ignored"] fn vendored_bundle_fetch() { @@ -798,82 +860,83 @@ fn vendored_bundle_fetch() { let served = Served::to(&mut cell); let (standin, uuid) = (&served.standin, served.uuid.as_str()); let origin = standin.origin(); - let vendoring = |args: &[&str]| run(standin, &cell, args, &patch_host(&origin)); + cell.route_downloads(&routes(&origin, false)); + let run = |cell: &Cell, args: &[&str]| run(standin, cell, args, &patch_host(&origin)); // (a) The unpatched build. let before = cell.builds_unpatched(&served.unpatched); + let upstream_fetches = standin.asked(&served.upstream_route); - // (b) The one command of vendored mode: declined, with nothing written - // and nothing of the patch fetched. The same build passes, on the - // upstream gem. - cell.declined(&vendoring(&VENDORED), &DECLINED, 1, "failed", &before); + // (b) No release is named: declined, with nothing written and nothing + // of the patch fetched. The same build passes, on the upstream gem. + cell.declined(&run(&cell, &VENDORED), &DECLINED, 1, "failed", &before); assert_eq!(standin.asked(&served.artifact_route), 0, "{test}"); cell.builds_patched(&before, &served.unpatched); - // (c) On the user's word: the copy, its ledger, and the two files that - // name it. - let scan = vendoring(&[&VENDORED[..], &[ALLOW]].concat()); - let said = &scan.dump; - assert_eq!(scan.code, 0, "{test}: {said}"); - assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); - assert_eq!(scan.envelope["summary"]["applied"], 1, "{test}: {said}"); - let vendored = cell.tree(); - let kept = format!(".socket/vendor/gem/{uuid}"); - let copy = format!("{kept}/{NAME}-{VERSION}"); - let mut written = vec![ - format!("{kept}/socket-patch.vendor.json"), - format!("{copy}/{LIB}"), - format!("{copy}/{NAME}.gemspec"), - ".socket/vendor/state.json".to_string(), - "Gemfile".to_string(), - "Gemfile.lock".to_string(), - ]; - written.sort(); - assert_eq!(changed(&before, &vendored), written, "{test}: {said}"); - let patched_source = source(&format!("PATCHED {uuid}")); - let lib = &vendored[&format!("{copy}/{LIB}")]; - assert_eq!(*lib, patched_source.as_bytes(), "{test}"); - let text = |rel: &str| String::from_utf8(vendored[rel].clone()).expect("a text file"); - let (gemfile, lock) = (text("Gemfile"), text("Gemfile.lock")); - let declaration = format!("gem \"{NAME}\", \"{VERSION}\", path: \"{copy}\""); - let declared = gemfile.lines().filter(|line| *line == declaration).count(); - assert_eq!(declared, 1, "{test}: Gemfile:\n{gemfile}"); - let section = format!("PATH\n remote: {copy}\n specs:\n {NAME} ({VERSION})\n\n"); - assert!(lock.starts_with(§ion), "{test}: Gemfile.lock:\n{lock}"); + // (c) The release is named: the gem, its ledger, and the two files + // that name it. The document of that run and the one of `vex` say so, + // before the patched build. + cell.write(".bazelversion", format!("{release}\n")); + let before = cell.tree(); + let claim = Claim::new(PURL, uuid, How::Vendored); + let in_run = cell.document("in-run"); + let scan = run(&cell, &[&VENDORED[..], &with_vex(&in_run)].concat()); + let vendored = committed_for_the_hub(&cell, &scan, &served, &before); + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(run, &claim, true); - // The same build fails where rules_ruby runs Bundler, on the path of - // the copy, and changes no file of the checkout. Bundler breaks the - // message at the width of its console, so it is compared without white - // space. - let build = cell.bazel("build", &[CONSUMER]); - let stderr = squeezed(&build.stderr()); - let missing = squeezed(&format!("{copy}` does not exist.")); - assert!( - !build.ok() && stderr.contains("Runningbundleinstall") && stderr.contains(&missing), - "{test}: the build did not fail on the path of the copy ({missing:?}):\n{}", - build.dump() + // (d) The same build, no step in between: patched, from the committed + // gem. + cell.builds_patched(&vendored, &served.patched); + assert_eq!(standin.asked(&served.patched_route), 0, "{test}"); + assert_eq!( + standin.asked(&served.upstream_route), + upstream_fetches, + "{test}: the patched build fetched the upstream gem" ); - assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}"); - let socket_patch = |cell: &Cell, args: &[&str]| run(standin, cell, args, &[]); - cell.stands_alone(socket_patch, &Claim::new(PURL, uuid, How::Vendored), true); + cell.stands_alone(run, &claim, true); + cell.stands_alone(run, &claim, false); + cell.detects_product(run, None); + let check = run(&cell, &["vendor", "--check"]); + assert_eq!(check.code, 0, "{test}: {}", check.dump); + + // (e) A second machine, where one byte of the committed gem is another. + { + let second = cell.twin(); + let other = one_byte_changed(&served.patched_gem); + second.write(&committed_gem(uuid), &other); + let check = run(&second, &["vendor", "--check"]); + let caught = check.dump.contains("vendor_sha256_mismatch"); + assert!(check.code == 1 && caught, "{test}: {}", check.dump); + fails_on_the_checksum(&second, &served.patched_gem, &other); + } - // (d) The undo: every file is the one of before, and so is the build. - let undo = socket_patch(&cell, &["vendor", "--revert", "--yes"]); + // (f) The undo: every file is the one of before, and so is the build, + // and `vex` has no document for it. The same two documents where no + // Bazel has built. + let undo = run(&cell, &["vendor", "--revert", "--yes"]); cell.undone(&undo, "removed", &before, &served.unpatched); + cell.attests_nothing(run, 2, "manifest_not_found"); + cell.attests_unbuilt(run, &VENDORED, &before, &vendored, &claim); - // (e) The remedy the refusal names: hosted mode patches the build. - let scan = socket_patch(&cell, &["scan", "--mode", "hosted", "--yes"]); + // (g) The remedy the refusal names, where Bazel reaches the patch host: + // hosted mode patches the build. + cell.route_downloads(&routes(&origin, true)); + let scan = run(&cell, &["scan", "--mode", "hosted", "--yes"]); let pinned = cell.pinned_by(&scan, PURL, uuid, &before, &["Gemfile", "Gemfile.lock"]); cell.builds_patched(&pinned, &served.patched); println!( - "{test}: Bazel {release} built {:?}; `scan --mode vendored` declined ({}), wrote \ - nothing, and the build stayed the same; with {ALLOW} it wrote {copy} and pointed \ - Gemfile and Gemfile.lock at it, and the next build failed (Bundler: The path ... does \ - not exist) while `vex` attested the gem; `vendor --revert` restored all {} files and \ - the build; `scan --mode hosted` built {:?}; {:?}", + "{test}: Bazel {release} built {:?}; `scan --mode vendored` declined ({}) in a checkout \ + that names no Bazel release, and the build stayed the same; with the release named it \ + wrote {} and a `file:` source in Gemfile and Gemfile.lock, the files written by hand, \ + and the next build printed {:?} with no patch host; one changed byte failed `vendor \ + --check` and a second machine's build (Bundler: mismatched checksums); `vendor \ + --revert` restored all {} files and the build; `scan --mode hosted` built {:?}; {:?}", served.unpatched, DECLINED.code, + committed_gem(uuid), + served.patched, before.len(), served.patched, started.elapsed() @@ -895,10 +958,11 @@ fn checkout() -> (Cell, Served) { } /// Without a Bazel: in the fixture's checkout, where the hub reads the -/// Gemfile and its lock, every command that would vendor the gem declines -/// it, writes nothing and fetches no gem. On the user's word vendored mode -/// goes on, and a later run without it passes and writes nothing: the lock -/// the hub reads already names the copy. +/// Gemfile and its lock and no file names a Bazel release, every command +/// that would vendor the gem declines it, writes nothing and fetches no +/// gem. On the user's word vendored mode goes on, with the copy of every +/// other project, and a later run without it passes and writes nothing: +/// the lock the hub reads already names the copy. #[test] fn every_command_that_would_vendor_declines_beside_a_hub_that_reads_the_lock() { let (cell, served) = checkout(); @@ -923,6 +987,301 @@ fn every_command_that_would_vendor_declines_beside_a_hub_that_reads_the_lock() { cell.vendors_on_the_users_word(run, &DECLINED); } +/// Without a Bazel: in the fixture's checkout with its Bazel release named +/// in `.bazelversion`, vendored mode commits the gem for the hub. +/// +/// - A dry run names no refusal and writes nothing. +/// - The run writes the three files of [`by_hand`], byte for byte, and +/// says what the form costs. +/// - A later run passes and writes nothing, also a scan that names no mode +/// and one with the switch: the pair names the committed gem. +/// - A hosted scan leaves the pair alone and names the undo. +/// - `vendor --check` passes, and fails on one changed byte of the gem, +/// which `repair` puts right. +/// - `vendor --revert`, `rollback` and `remove` each put every file back, +/// byte for byte, and the gem is vendored the same again after each. +/// - Run as a person runs it, the command names the Bazel build as the +/// next step, and no reinstall: Bundler by itself fails on the source. +/// - With Bundler 2.6.9 in the lock the gem is vendored the same way. +/// - With the switch the run writes the copy of every other project. +/// - A vendored scan takes over a hosted pin of the gem, and writes the +/// same three files. +#[test] +fn a_gem_is_committed_for_the_hub_and_put_back() { + let (cell, served) = checkout(); + cell.write(".bazelversion", "9.3.2\n"); + let (standin, uuid) = (&served.standin, served.uuid.as_str()); + let origin = standin.origin(); + let go = |args: &[&str]| run(standin, &cell, args, &patch_host(&origin)); + let before = cell.tree(); + let same = |ran: &Ran, tree: &Tree| { + assert_eq!(ran.code, 0, "{}", ran.dump); + assert_eq!(changed(tree, &cell.tree()), NOTHING, "{}", ran.dump); + }; + + let dry = go(&[&VENDORED[..], &["--dry-run"]].concat()); + same(&dry, &before); + assert!(!dry.dump.contains(DECLINED.code), "{}", dry.dump); + let vendored = committed_for_the_hub(&cell, &go(&VENDORED), &served, &before); + for in_sync in [ + &VENDORED[..], + &["scan", "--yes"], + &[&VENDORED[..], &[ALLOW]].concat(), + ] { + let again = go(in_sync); + same(&again, &vendored); + assert_eq!(again.envelope["status"], "success", "{}", again.dump); + assert!(!again.dump.contains(DECLINED.code), "{}", again.dump); + } + + // Hosted mode leaves a gem vendored this way alone, and says how to + // hand it over. + let hosted = go(&["scan", "--mode", "hosted", "--yes"]); + same(&hosted, &vendored); + let handed_over = hosted.dump.contains("socket-patch's own vendored wiring"); + assert!(handed_over, "{}", hosted.dump); + + same(&go(&["vendor", "--check"]), &vendored); + cell.write(&committed_gem(uuid), one_byte_changed(&served.patched_gem)); + let check = go(&["vendor", "--check"]); + let caught = check.dump.contains("vendor_sha256_mismatch"); + assert!(check.code == 1 && caught, "{}", check.dump); + same(&go(&["repair"]), &vendored); + + for undo in [ + &["vendor", "--revert", "--yes"][..], + &["rollback", "--yes"], + &["remove", PURL, "--yes"], + ] { + same(&go(undo), &before); + committed_for_the_hub(&cell, &go(&VENDORED), &served, &before); + } + same(&go(&["vendor", "--revert", "--yes"]), &before); + + // As a person runs it: the next step is the build, and no reinstall. + let rubygems = format!("{origin}/{RUBYGEMS}"); + let env = [ + ("SOCKET_RUBYGEMS_URL", rubygems.as_str()), + patch_host(&origin)[0], + ]; + let [stdout, stderr] = cell.socket_patch_person(&origin, &VENDORED, &env); + let said = format!("--- stdout\n{stdout}\n--- stderr\n{stderr}"); + let step = + "2. Build with Bazel, which installs the committed gems, then run `socket-patch vex`"; + let stepped = squeezed(&stdout).contains(&squeezed(step)); + assert!(stepped && !stdout.contains("Reinstall"), "{said}"); + assert!( + stderr.contains("Warning: ") && stderr.contains("through Bazel only"), + "{said}" + ); + same(&go(&["vendor", "--revert", "--yes"]), &before); + + // The Bundler of most locks, which a hub was built with too. + names_bundler(&cell, OLDER_BUNDLER); + let older = cell.tree(); + let ran = go(&VENDORED); + assert_eq!(ran.envelope["summary"]["applied"], 1, "{}", ran.dump); + assert!(ran.dump.contains(ADVISORY), "{}", ran.dump); + same(&go(&["vendor", "--revert", "--yes"]), &older); + cell.write("Gemfile.lock", &before["Gemfile.lock"]); + + // On the user's word: the copy of every other project, named by its + // path. + let allowed = go(&[&VENDORED[..], &[ALLOW]].concat()); + assert_eq!( + allowed.envelope["summary"]["applied"], 1, + "{}", + allowed.dump + ); + let lock = String::from_utf8(cell.tree()["Gemfile.lock"].clone()).expect("a text file"); + let copy = format!("PATH\n remote: .socket/vendor/gem/{uuid}/{NAME}-{VERSION}\n"); + assert!(lock.starts_with(©), "{lock}"); + same(&go(&["vendor", "--revert", "--yes"]), &before); + + let hosted = go(&["scan", "--mode", "hosted", "--yes"]); + assert_eq!(hosted.envelope["summary"]["applied"], 1, "{}", hosted.dump); + let taken_over = go(&VENDORED); + assert_eq!(taken_over.code, 0, "{}", taken_over.dump); + let tree = cell.tree(); + for (rel, bytes) in by_hand(uuid, &served.patched_gem) { + assert!(tree[&rel] == bytes, "{rel}: {}", taken_over.dump); + } + same(&go(&["vendor", "--revert", "--yes"]), &before); +} + +/// Without a Bazel: each condition under which the committed gem is not +/// known to build declines the gem, with nothing written and no gem +/// fetched, and names the call, the lock and the condition. The lock's +/// `CHECKSUMS` line or the `gem_checksums` entry of every call that reads +/// the pair is what holds the committed gem to its bytes: an entry that +/// holds the gem to other bytes declines it once the patched gem is known, +/// naming the call, the entry and both sums, also where it is a second +/// call's. With the sum of the patched gem written there the gem is +/// vendored, also in a lock with no `CHECKSUMS` section, and each undo +/// then puts every file back and says that the entry it leaves in the call +/// fails the build. +#[test] +fn a_gem_is_declined_where_the_committed_gem_is_not_known_to_build() { + let scan = |cell: &Cell, served: &Served| { + let origin = served.standin.origin(); + run(&served.standin, cell, &VENDORED, &patch_host(&origin)) + }; + let text = + |cell: &Cell, rel: &str| String::from_utf8(cell.tree()[rel].clone()).expect("a text file"); + // The lock without its `CHECKSUMS` section. + let unchecked = |cell: &Cell| { + let lock = text(cell, "Gemfile.lock"); + let (head, sums) = lock.split_once("CHECKSUMS\n").expect("a CHECKSUMS section"); + let (_, tail) = sums.split_once("\n\n").expect("a section after it"); + cell.write("Gemfile.lock", format!("{head}{tail}")); + }; + // The call with `gem_checksums = `. + let pins = |cell: &Cell, sums: &str| { + let lock = " gemfile_lock = \"//:Gemfile.lock\",\n"; + let module = text(cell, "MODULE.bazel"); + assert!(module.contains(lock), "{module}"); + let pinned = format!("{lock} gem_checksums = {sums},\n"); + cell.write("MODULE.bazel", module.replace(lock, &pinned)); + }; + // A second call that reads the same pair, for a hub of its own, with + // the arguments `more`: the line of `MODULE.bazel` it is on. + let second = |cell: &Cell, more: &str| { + let module = text(cell, "MODULE.bazel"); + let call = format!( + "ruby.bundle_fetch(name = \"tools\", gemfile = \"//:Gemfile\", gemfile_lock = \ + \"//:Gemfile.lock\"{more})\n" + ); + cell.write("MODULE.bazel", format!("{module}{call}")); + module.lines().count() + 1 + }; + let entry = |sum: &str| format!("{{\"{NAME}-{VERSION}\": \"{sum}\"}}"); + let unheld = |line: usize| { + format!( + "has no CHECKSUMS section and `ruby.bundle_fetch` (MODULE.bazel:{line}) has no \ + `gem_checksums` entry for {NAME}-{VERSION}" + ) + }; + let (first_unheld, second_unheld) = (unheld(15), unheld(28)); + type Edit<'a> = &'a dyn Fn(&Cell); + let cases: [(Edit, &str); 9] = [ + ( + &|cell| cell.write(".bazelversion", "9.1.0\n"), + "Bazel 9.1.0 fails on such a URL", + ), + ( + &|cell| cell.write(".bazelversion", "10.0.0\n"), + "not known to build on Bazel 10.0.0", + ), + ( + &|cell| cell.write(".bazelversion", "latest\n"), + DECLINED.names[2], + ), + (&unchecked, &first_unheld), + ( + // The first call holds the gem, and the second one does not. + &|cell| { + unchecked(cell); + pins(cell, &entry(PLACEHOLDER)); + assert_eq!(second(cell, ""), 28); + }, + &second_unheld, + ), + ( + &|cell| names_bundler(cell, "2.5.23"), + "not known to build with Bundler 2.5.23, which Gemfile.lock names", + ), + ( + &|cell| names_bundler(cell, "5.0.0"), + "not known to build with Bundler 5.0.0, which Gemfile.lock names", + ), + ( + &|cell| pins(cell, "SUMS"), + "the `gem_checksums` of `ruby.bundle_fetch` (MODULE.bazel:15) are not written out", + ), + ( + &|cell| { + cell.write( + "WORKSPACE", + "local_repository(name = \"x\", path = \"x\")\n", + ) + }, + "a `WORKSPACE` file of the workspace defines repositories", + ), + ]; + for (edit, why) in cases { + let (cell, served) = checkout(); + cell.write(".bazelversion", "9.3.2\n"); + edit(&cell); + let package = Declined { + names: &[DECLINED.names[0], DECLINED.names[1], why], + ..DECLINED + }; + let before = cell.tree(); + cell.declined(&scan(&cell, &served), &package, 1, "failed", &before); + assert_eq!(served.standin.asked(&served.artifact_route), 0, "{why}"); + } + + // An entry that holds the gem to the upstream bytes. + let (cell, served) = checkout(); + cell.write(".bazelversion", "9.3.2\n"); + let sums = [&served.upstream_gem, &served.patched_gem].map(|gem| sha256_hex(gem)); + let unpinned = text(&cell, "MODULE.bazel"); + pins(&cell, &entry(&sums[0])); + let before = cell.tree(); + let ran = scan(&cell, &served); + let said = squeezed(&ran.dump); + let named = [ + format!("hold {NAME}-{VERSION} to sha256 {}", sums[0]), + format!("the patched gem has {}", sums[1]), + DECLINED.code.to_string(), + ]; + let named = named.iter().all(|part| said.contains(&squeezed(part))); + assert!(ran.code == 1 && named, "{}", ran.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", ran.dump); + + // The sum of the patched gem there, and a second call that reads the + // pair and holds the gem to the upstream bytes: its hub would fail. + cell.write("MODULE.bazel", &unpinned); + pins(&cell, &entry(&sums[1])); + let pinned = text(&cell, "MODULE.bazel"); + let line = second(&cell, &format!(", gem_checksums = {}", entry(&sums[0]))); + let before = cell.tree(); + let ran = scan(&cell, &served); + let said = squeezed(&ran.dump); + let named = format!( + "`ruby.bundle_fetch` (MODULE.bazel:{line}) hold {NAME}-{VERSION} to sha256 {}", + sums[0] + ); + let named = said.contains(&squeezed(&named)) && said.contains(DECLINED.code); + assert!(ran.code == 1 && named, "{}", ran.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", ran.dump); + + // The one call, with the sum of the patched gem: vendored, with and + // without a `CHECKSUMS` section in the lock. Each undo puts every file + // back and names the entry it leaves in the call. + cell.write("MODULE.bazel", &pinned); + for (with_section, undo) in [ + (true, &["vendor", "--revert", "--yes"][..]), + (true, &["rollback", "--yes"]), + (false, &["remove", PURL, "--yes"]), + ] { + if !with_section { + unchecked(&cell); + } + let before = cell.tree(); + let ran = scan(&cell, &served); + assert_eq!(ran.envelope["summary"]["applied"], 1, "{}", ran.dump); + let pinned = text(&cell, "Gemfile.lock").contains(&checksum(NAME, &sums[1])); + assert_eq!(pinned, with_section, "{}", ran.dump); + let undo = run(&served.standin, &cell, undo, &[]); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); + let said = squeezed(&undo.dump); + let left = format!("`ruby.bundle_fetch` (MODULE.bazel:15) still hold {NAME}-{VERSION}"); + let left = said.contains(ENTRY_LEFT) && said.contains(&squeezed(&left)); + assert!(undo.code == 0 && left, "{}", undo.dump); + } +} + /// Without a Bazel: the refusal is the project's whose files a hub reads, /// and no other's. In a workspace whose hub reads the files of another /// project, and in no workspace at all, vendored mode vendors the gem as diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index d507581ae..a1ec2d365 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -13,10 +13,12 @@ //! points at a copy committed under `.socket/vendor`: 2.5.0-rc4 takes the //! path for the name of a project and fails the build of everything the //! hub serves (Bazel 9.3.2, 8.8.2 and 7.7.2). rules_js does build a -//! vendored tarball. rules_ruby 1.0.0-rc2 fails the build on a vendored -//! gem (same three releases) unless the call lists every file of the copy -//! among its `srcs`, which it copies beside the Gemfile: `srcs` is not -//! read here, so a vendored gem is not judged. +//! vendored tarball. rules_ruby 1.0.0-rc2 builds a gem that is committed +//! as its archive and named by a `file:` source +//! ([`crate::vendor::gem::bazel`]), and fails the build on one vendored by +//! its path (same three releases) unless the call lists every file of the +//! copy among its `srcs`, which it copies beside the Gemfile: `srcs` is +//! not read here, so a vendored gem is not judged. //! //! [`unbuilt`] names, for a patched package, the call that builds it from a //! file without its patch. It says so only when the files of the workspace @@ -79,7 +81,7 @@ use std::path::{Component, Path}; use aho_corasick::AhoCorasick; use super::starlark::{Call, File, Value}; -use super::workspace::{disk, Doubt, Extension, Repo, Workspace}; +use super::workspace::{disk, Doubt, Extension, Repo, Tag, Workspace}; use super::BazelRoot; use crate::formats::gem::locked_specs; use crate::formats::pnpm::grammar::documents; @@ -138,7 +140,8 @@ struct Hub { members: fn(&str) -> Vec, /// Whether a call of the tag may build a package from a line that /// points at a copy under `.socket/vendor`: rules_js does, and - /// rules_ruby does when the call lists the files of the copy. + /// rules_ruby does for a gem committed as its archive, or when the + /// call lists the files of the copy. builds_vendored: bool, } @@ -347,6 +350,25 @@ fn reads( doubt.or_else(|| hidden().or_else(unread).cloned()).map(Err) } +/// The calls of the hub of `ecosystem` in the module files of `workspace`, +/// each with the files of the main repository it names by a label that is +/// written out (their paths from the Bazel root), and what leaves open +/// whether these are all of them ([`Tags::doubts`]). No call of a +/// `WORKSPACE` file is among them. +/// +/// [`Tags::doubts`]: super::workspace::Tags::doubts +pub(crate) fn hub_calls<'w>( + workspace: &'w Workspace, + ecosystem: &str, +) -> (Vec<(Tag<'w>, Vec)>, Vec) { + let Some(hub) = HUBS.iter().find(|hub| hub.ecosystem == ecosystem) else { + return Default::default(); + }; + let tags = workspace.tags(&hub.extension, hub.tag); + let named = |tag: Tag<'w>| (tag, files(workspace, tag.call, hub.files, None)); + (tags.calls.into_iter().map(named).collect(), tags.doubts) +} + /// 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")) { diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 350328ccf..669d0ced3 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -8125,7 +8125,7 @@ fn gem_dependency_entry(lock: &str, line_no: usize) -> &str { /// and the lock resolves it from a `GEM` section naming that remote, with a /// source-pinned `DEPENDENCIES` entry. Bundler refuses any other pair under /// frozen / deployment mode, so a plan that fails this is never committed. -fn gem_pair_agrees( +pub(crate) fn gem_pair_agrees( manifest: &str, lock: &str, dep: &DepOverride, @@ -8312,12 +8312,14 @@ fn plan_gem_redirect( } // Bundler allows ONE source per gem: an option that already // picks one (`git:`, `path:`, another `source:`) cannot take - // the Socket source beside it. When the blocking `path:` is + // the Socket source beside it. When the blocking `path:` (or + // the `source:` of a gem committed for a Bazel hub) is // socket-patch's OWN vendored wiring, prescribe the eject path // instead of leaving the user to puzzle over their own Gemfile. if let Some(spelling) = decl.source_selecting() { let socket_vendored = decl.args.iter().any(|arg| { - matches!(&arg.kind, ArgKind::Option { key, .. } if key == "path") + let ours = |key: &str| key == "path" || key == "source"; + matches!(&arg.kind, ArgKind::Option { key, .. } if ours(key)) && gf[arg.start..arg.end].contains(".socket/vendor/") }); return Err(refuse( @@ -8757,6 +8759,27 @@ fn plan_gem_redirect( }) } +/// The pair edit of hosted mode for the gem `dep` with `source` in the place +/// of the patch registry's URL and `sha256` as the sum of the gem's archive: +/// `Gemfile` and `Gemfile.lock` as the edit leaves them, and its edits. +/// Vendored mode writes it for a gem whose lock a Bazel hub reads +/// ([`crate::vendor::gem::bazel`]), with a relative `file:` URL of the +/// checkout as `source`. +pub(crate) fn plan_gem_source( + gemfile: &str, + lock: &str, + dep: &DepOverride, + source: &str, + sha256: &str, +) -> Result<(String, String, Vec), RewriteWarning> { + let sums = [(dep.version.clone(), sha256.to_string())]; + let (files, names) = (BTreeMap::new(), ("Gemfile", "Gemfile.lock")); + let (gemfile, layout) = (Some(gemfile), lock_layout(lock)); + let layout = layout.as_ref(); + let plan = plan_gem_redirect(&files, dep, source, &sums, gemfile, lock, names, layout)?; + Ok((plan.gemfile, plan.lock, plan.staged.edits)) +} + fn rewrite_gem( files: &BTreeMap, overrides: &[DepOverride], diff --git a/crates/socket-patch-core/src/vendor/bazel_hub.rs b/crates/socket-patch-core/src/vendor/bazel_hub.rs index 6f316895e..e99940ede 100644 --- a/crates/socket-patch-core/src/vendor/bazel_hub.rs +++ b/crates/socket-patch-core/src/vendor/bazel_hub.rs @@ -1,5 +1,6 @@ //! PyPI and RubyGems vendored mode for a project whose lock a Bazel hub -//! reads: declined unless the user allows it. +//! reads: declined unless the user allows it, or the package is a gem that +//! can be committed for the hub as its archive ([`super::gem::bazel`]). //! //! rules_python's `pip.parse` and rules_ruby's `ruby.bundle_fetch` build //! the packages of a lock in repositories of Bazel's own. Vendored mode @@ -42,6 +43,8 @@ use crate::crawlers::Ecosystem; use crate::utils::env_compat::env_flag; use crate::utils::fs::run_blocking; use crate::utils::pnpm_workspace::without_verbatim_prefix; +use crate::utils::purl::parse_gem_purl; +use crate::vendor::gem::bazel as gem_hub; use crate::vendor::path::vendor_uuid_dir_rel; use crate::vendor::refusals::ALLOW_IN_BAZEL_ENV; @@ -65,9 +68,11 @@ pub async fn refusals<'a>( } /// What stands between vendored mode and a list of files of a project -/// ([`standing`]): the words of the refusal, and the text of the lock the -/// hub reads where a call names one. `None` where nothing does. -type Standing = Option<(String, Option)>; +/// ([`standing`]): what was read of the workspace, the text of the lock the +/// hub reads where a call names one, and for a call that names a gem's +/// files whether a gem can be committed for it as its archive +/// ([`gem_hub::gate`]). `None` where nothing stands in the way. +type Standing = Option<(String, Option, Option>)>; /// What rules_ruby builds of a hosted pin: the `sha256` of a gem that the /// call lists holds the build to the registry's gem. @@ -116,12 +121,12 @@ async fn refusals_unless<'a>( let at = match asked.iter().position(|(of, _)| *of == list) { Some(at) => at, None => { - let stands = standing(&root, purls, ruleset, hosted, list.1.clone()).await; + let stands = standing(&root, purls, ruleset, list.1.clone()).await; asked.push((list, stands)); asked.len() - 1 } }; - let Some((detail, lock)) = &asked[at].1 else { + let Some((reads, lock, gem)) = &asked[at].1 else { continue; }; // A lock names the copy of a patch by the copy's directory, outside @@ -162,28 +167,50 @@ async fn refusals_unless<'a>( wired = names(&text) || !holds(&text); } } - if !wired { - refused.push((*purl, code, detail.clone())); + if wired { + continue; } + // A gem is committed as its archive where the hub is known to + // build that: only where it is not is the gem declined. + let committed = gem.as_ref().map(|hub| { + let (name, version) = parse_gem_purl(purl).unwrap_or_default(); + let hub = hub.as_ref().map_err(String::clone)?; + hub.declines(&name, &version).map_or(Ok(()), Err) + }); + let fails = match committed { + Some(Ok(())) => continue, + Some(Err(why)) => format!( + "vendored mode commits the patched gem for such a call and names it by a \ + relative `file:` URL, which is not known to build here: {why}" + ), + None => format!( + "vendored mode makes the lock name the patched copy by a path under \ + .socket/vendor, and {ruleset} fails the build on such a lock" + ), + }; + let detail = format!( + "{reads}; {fails}; use `--mode hosted`, which names the patched package by a URL \ + that {ruleset} fetches{hosted}, or pass `--allow-vendored-in-bazel` if no build \ + takes the packages of this project from {ruleset}" + ); + refused.push((*purl, code, detail)); } refused } /// The [`Standing`] of the files `locks` of the project of `root`, for the -/// packages of `ruleset` (purls of the type `purls`), whose hosted pin is -/// built `hosted`. +/// packages of `ruleset` (purls of the type `purls`). async fn standing( root: &BazelRoot, purls: &'static str, ruleset: &str, - hosted: &str, locks: Vec, ) -> Standing { // The root is canonical: on Windows that spelling has a prefix no user // types and no tool prints. let at = without_verbatim_prefix(root.dir.clone()); let at = at.display(); - let (reads, lock) = match reader(root, purls, locks).await? { + let (reads, lock, gem) = match reader(root, purls, locks).await? { Ok(Unbuilt { call, file, @@ -195,7 +222,12 @@ async fn standing( // Read as a lock of the workspace is: within its bound, and // not through a link that leads out of the Bazel root. let dir = root.dir.clone(); - (reads, run_blocking(move || lock_text(&dir, &lock)).await) + let lock = run_blocking(move || lock_text(&dir, &lock)).await; + let gem = match purls { + "gem" => Some(gem_hub::gate(root).await), + _ => None, + }; + (reads, lock, gem) } Err(Doubt { file, line, why }) => { let line = match line { @@ -206,17 +238,10 @@ async fn standing( "the files of the Bazel workspace at {at} cannot be read with certainty, so a \ call of {ruleset} may name a lock of this project ({file}{line}: {why})" ); - (reads, None) + (reads, None, None) } }; - let detail = format!( - "{reads}; vendored mode makes the lock name the patched copy by a path under \ - .socket/vendor, and {ruleset} fails the build on such a lock; use `--mode hosted`, \ - which names the patched package by a URL that {ruleset} fetches{hosted}, or pass \ - `--allow-vendored-in-bazel` if no build takes the packages of this project from \ - {ruleset}" - ); - Some((detail, lock)) + Some((reads, lock, gem)) } #[cfg(test)] @@ -291,7 +316,7 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//api:Gemfile", gemfile_lock = "// [ "`ruby.bundle_fetch` (MODULE.bazel:4)", "names api/Gemfile.lock; ", - "and rules_ruby fails the build", + "which is not known to build here: the project is not the root", ], ), ] { diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 0151109a7..2654a88c1 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -138,6 +138,8 @@ use crate::formats::gem::{ is_plain_gem_token, listed_specs, split_checksum_entry, split_entry, GemfileLock, }; +pub(crate) mod bazel; + pub(super) const GEMFILE: &str = "Gemfile"; pub(super) const GEMFILE_LOCK: &str = "Gemfile.lock"; @@ -989,6 +991,9 @@ pub(crate) async fn service_preflight( let prelude = gem_prelude(purl, installed_path, project_root, record) .await .ok()?; + if let Some(planned) = bazel::preflight(purl, &prelude, project_root, record).await { + return planned; + } let asks = match prelude.lock_wired { true => !prelude.copy_ok, false => gem_edits(purl, &prelude).is_ok(), @@ -1025,6 +1030,19 @@ pub async fn vendor_gem<'a>( Ok(prelude) => prelude, Err(outcome) => return outcome, }; + // A gem whose lock a Bazel hub reads is committed as its archive. + let for_hub = bazel::vendor( + purl, + &prelude, + project_root, + record, + vendored_at, + dry_run, + service, + ); + if let Some(outcome) = for_hub.await { + return outcome; + } let GemPrelude { name, version, @@ -1428,17 +1446,13 @@ fn gem_entry( /// eval-able Ruby form a bundler path source loads. pub(crate) const GEM_STUB_ARTIFACT_KIND: &str = "gem-stub-gemspec"; -/// Download and verify the `.gem` and its stub gemspec, then atomically -/// replace the copy. Missing, invalid, or native-extension stubs are refused. -pub(super) async fn gem_service_copy( +/// Download and verify the `.gem` and its stub gemspec. Missing, invalid, or +/// native-extension stubs are refused. +async fn gem_service_archive( service: Option<&VendorServiceConfig>, record: &PatchRecord, name: &str, - copy_dir: &Path, - uuid_dir: &Path, - unwind_uuid_dir: bool, - warnings: &mut Vec, -) -> Result<(), Box> { +) -> Result<(super::service_fetch::VerifiedArchive, Vec), Box> { let cfg = service .filter(|cfg| cfg.service_enabled()) .ok_or_else(|| Box::new(super::service_fetch::required()))?; @@ -1446,7 +1460,7 @@ pub(super) async fn gem_service_copy( let fetched = fetch_verified_archive(cfg, &record.uuid).await; let subject = format!(".gem for {name}"); let policy = ServicePolicy::Refused; - let mut archive = policy.settle(fetched, ".gem", &subject)?; + let archive = policy.settle(fetched, ".gem", &subject)?; // Step 2: the stub gemspec the converter generated alongside the `.gem`. let stub = match fetch_verified_secondary(cfg, &archive, GEM_STUB_ARTIFACT_KIND).await { @@ -1472,6 +1486,22 @@ pub(super) async fn gem_service_copy( } }; refuse_unusable_stub(policy, name, name, &String::from_utf8_lossy(&stub))?; + Ok((archive, stub)) +} + +/// [`gem_service_archive`], then atomically replace the copy with the +/// unpacked gem and its stub gemspec. +pub(super) async fn gem_service_copy( + service: Option<&VendorServiceConfig>, + record: &PatchRecord, + name: &str, + copy_dir: &Path, + uuid_dir: &Path, + unwind_uuid_dir: bool, + warnings: &mut Vec, +) -> Result<(), Box> { + let (mut archive, stub) = gem_service_archive(service, record, name).await?; + let policy = ServicePolicy::Refused; // Extract the patched `.gem`'s data.tar.gz into a STAGE sibling, add the // stub as `.gemspec` (a `.gem`'s data.tar.gz never carries one — @@ -2100,6 +2130,11 @@ pub async fn revert_gem_opts( )); } + // A gem committed as its archive, for a Bazel hub. + if bazel::is_archive(entry) { + return bazel::revert(entry, project_root, &uuid_dir_rel, opts).await; + } + // Wiring is restored in reverse application order: lock first, Gemfile // last (the mirror image of vendor's Gemfile-then-lock). Every record is // planned against in-memory text first and nothing is written unless @@ -7672,7 +7707,7 @@ mod tests { /// Build a `.gem` (uncompressed outer tar holding `data.tar.gz` + /// `metadata.gz`). `data_files` are the inner data.tar.gz entries at the /// root (no prefix dir), as a real `.gem` carries them. - fn make_gem(data_files: &[(&str, &[u8])]) -> Vec { + pub(super) fn make_gem(data_files: &[(&str, &[u8])]) -> Vec { use std::io::Write as _; let mut data_tar = tar::Builder::new(Vec::new()); for (rel, content) in data_files { @@ -7715,16 +7750,27 @@ mod tests { gem_bytes: &[u8], gem_sha512: &str, stub: Option<(&[u8], &str)>, + ) { + mount_gem_granted_as(server, UUID, gem_bytes, gem_sha512, stub).await; + } + + /// [`mount_gem_granted`] for the patch `uuid`. + async fn mount_gem_granted_as( + server: &wiremock::MockServer, + uuid: &str, + gem_bytes: &[u8], + gem_sha512: &str, + stub: Option<(&[u8], &str)>, ) { use wiremock::matchers::{method, path}; use wiremock::{Mock, ResponseTemplate}; - let gem_path = format!("/patch/gem/rack/3.2.6/tok/{UUID}/rack-3.2.6.gem"); + let gem_path = format!("/patch/gem/rack/3.2.6/tok/{uuid}/rack-3.2.6.gem"); let gem_url = format!("{}{gem_path}", server.uri()); let mut artifacts = vec![serde_json::json!({ "kind": "tarball", "url": gem_url, "integrity": { "sha512": gem_sha512 } })]; - let stub_path = format!("/patch/gem/rack/3.2.6/tok/{UUID}/rack-3.2.6.gemspec"); + let stub_path = format!("/patch/gem/rack/3.2.6/tok/{uuid}/rack-3.2.6.gemspec"); if let Some((stub_bytes, stub_sha512)) = stub { let stub_url = format!("{}{stub_path}", server.uri()); artifacts.push(serde_json::json!({ @@ -7740,7 +7786,7 @@ mod tests { Mock::given(method("POST")) .and(path("/v0/orgs/acme/patches/package")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { UUID: { + "results": { uuid: { "status": "granted", "url": gem_url, "purl": PURL, @@ -7833,6 +7879,177 @@ mod tests { .any(|w| w.code == "vendor_prebuilt_downloaded")); } + /// A gem whose `Gemfile` and lock a Bazel hub reads is committed as its + /// archive ([`bazel`]): the pair names it by a `file:` source, a later + /// run is in sync, a gem that went missing is written again and held + /// to the lock, a newer patch takes the source over, and the revert + /// puts the pair back. A `gem_checksums` entry for other bytes declines + /// the gem once its bytes are known, with nothing written. + #[tokio::test] + #[serial_test::serial] + async fn a_gem_of_a_lock_a_bazel_hub_reads_is_committed_as_its_archive() { + let _unset = crate::test_env::EnvGuard::unset(super::super::refusals::ALLOW_IN_BAZEL_ENV); + let sums = "CHECKSUMS\n puma (6.4.2) sha256=aa\n rack (3.2.6) sha256=bb\n\nBUNDLED WITH"; + // A Bundler that a hub was built with. + let lock = LOCK_DIRECT.replace("BUNDLED WITH", sums); + let lock = lock.replace(" 2.5.22\n", " 2.6.9\n"); + assert!(lock.ends_with("BUNDLED WITH\n 2.6.9\n"), "{lock}"); + let (_tmp, root, _installed, blobs, record) = fixture(GEMFILE_DIRECT, &lock).await; + let module = "ruby = use_extension(\"@rules_ruby//ruby:extensions.bzl\", \"ruby\")\n\ + ruby.bundle_fetch(name = \"b\", gemfile = \"//:Gemfile\", gemfile_lock = \ + \"//:Gemfile.lock\"SUMS)\n"; + let write = |file: &str, text: &str| std::fs::write(root.join(file), text).unwrap(); + let read = |file: &str| std::fs::read_to_string(root.join(file)).unwrap(); + write("MODULE.bazel", &module.replace("SUMS", "")); + write(".bazelversion", "8.8.2\n"); + let gem = make_gem(&[("lib/rack.rb", PATCHED)]); + let sum = crate::utils::digest::sha256_hex_of(&gem); + let server = wiremock::MockServer::start().await; + let stub = Some((SERVICE_STUB, sri_sha512(SERVICE_STUB))); + let stub = stub.as_ref().map(|(bytes, sri)| (*bytes, sri.as_str())); + mount_gem_granted(&server, &gem, &sri_sha512(&gem), stub).await; + let sources = PatchSources::blobs_only(&blobs); + let cfg = gem_service_cfg(&server.uri(), VendorSource::Service, false); + let run = |record: &PatchRecord, dry_run: bool, cfg: &VendorServiceConfig| { + let (record, cfg) = (record.clone(), cfg.clone()); + let (root, sources) = (root.clone(), sources.clone()); + async move { + let at = "2026-06-09T00:00:00Z"; + let install = missing_install(&root); + crate::vendor::test_support::vendor_gem( + PURL, + &install, + &root, + &record, + &sources, + at, + dry_run, + false, + Some(&cfg), + ) + .await + } + }; + let archive = + |uuid: &str| root.join(format!(".socket/vendor/gem/{uuid}/gems/rack-3.2.6.gem")); + let source = |uuid: &str| format!("file:.socket/vendor/gem/{uuid}/"); + + // An entry of the call for the upstream gem: declined, nothing + // written. A dry run says the same. + let pinned = format!( + ", gem_checksums = {{\"rack-3.2.6\": \"{}\"}}", + "c".repeat(64) + ); + write("MODULE.bazel", &module.replace("SUMS", &pinned)); + for dry_run in [true, false] { + let (code, detail) = unwrap_refused(run(&record, dry_run, &cfg).await); + assert_eq!(code, "vendor_gem_bazel_hub"); + assert!( + detail.contains(&sum) && detail.contains("rack-3.2.6"), + "{detail}" + ); + assert_eq!([read(GEMFILE), read(GEMFILE_LOCK)], [GEMFILE_DIRECT, &lock]); + assert!(!root.join(".socket").exists()); + } + write("MODULE.bazel", &module.replace("SUMS", "")); + + // A gem that does not hold the patched file is not committed. + let other = wiremock::MockServer::start().await; + let unpatched = make_gem(&[("lib/rack.rb", PRISTINE)]); + mount_gem_granted(&other, &unpatched, &sri_sha512(&unpatched), stub).await; + let unpatched = gem_service_cfg(&other.uri(), VendorSource::Service, false); + let (code, _) = unwrap_refused(run(&record, false, &unpatched).await); + assert_eq!(code, "vendor_prebuilt_required"); + assert!(!root.join(".socket").exists() && read(GEMFILE_LOCK) == lock); + + // A dry run writes nothing; the run commits the gem and names it. + let (result, entry, _) = unwrap_done(run(&record, true, &cfg).await); + assert!(result.success && entry.is_none() && !root.join(".socket").exists()); + let (result, entry, warnings) = unwrap_done(run(&record, false, &cfg).await); + let first = entry.expect("an entry"); + assert!(result.success, "{:?}", result.error); + assert_eq!(std::fs::read(archive(UUID)).unwrap(), gem); + let rel = format!(".socket/vendor/gem/{UUID}/gems/rack-3.2.6.gem"); + assert_eq!( + (first.artifact.path.as_str(), first.artifact.sha256.as_str()), + (rel.as_str(), sum.as_str()) + ); + let declared = format!("gem \"rack\", \"~> 3.1\", source: \"{}\"\n", source(UUID)); + assert!(read(GEMFILE).ends_with(&declared), "{}", read(GEMFILE)); + let section = format!( + "GEM\n remote: {}\n specs:\n rack (3.2.6)\n base64 (>= 0.1.0)\n\n", + source(UUID) + ); + let wired = read(GEMFILE_LOCK); + assert!(wired.starts_with(§ion), "{wired}"); + assert!(wired.contains(&format!(" rack (~> 3.1)!\n\nCHECKSUMS\n puma (6.4.2) sha256=aa\n rack (3.2.6) sha256={sum}\n")), "{wired}"); + assert!( + warnings.iter().any(|w| w.code == bazel::ADVISORY), + "{warnings:?}" + ); + assert!(root + .join(format!(".socket/vendor/gem/{UUID}/.gitignore")) + .exists()); + + // In sync: nothing to record, nothing to say. + let (result, entry, warnings) = unwrap_done(run(&record, false, &cfg).await); + assert!( + result.success && entry.is_none() && warnings.is_empty(), + "{warnings:?}" + ); + + // The gem is gone: written again, with the pair as it is. One the + // lock does not pin is not written. + std::fs::remove_file(archive(UUID)).unwrap(); + let (_, entry, warnings) = unwrap_done(run(&record, false, &cfg).await); + assert!(entry.is_some_and(|entry| entry.wiring.is_empty())); + assert!( + warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), + "{warnings:?}" + ); + assert_eq!(std::fs::read(archive(UUID)).unwrap(), gem); + assert_eq!(read(GEMFILE_LOCK), wired); + std::fs::remove_file(archive(UUID)).unwrap(); + write(GEMFILE_LOCK, &wired.replace(&sum, &"d".repeat(64))); + let (code, detail) = unwrap_refused(run(&record, false, &cfg).await); + assert_eq!(code, "vendor_gem_bazel_hub"); + assert!( + detail.contains("Gemfile.lock holds rack 3.2.6 to sha256"), + "{detail}" + ); + assert!(!archive(UUID).exists()); + write(GEMFILE_LOCK, &wired); + unwrap_done(run(&record, false, &cfg).await); + + // A newer patch of the gem takes the source over, and its entry, + // with what the caller carries forward, reverts to the first pair. + let newer_gem = make_gem(&[("lib/rack.rb", PATCHED), ("lib/more.rb", b"more\n")]); + let newer = PatchRecord { + uuid: UUID2.to_string(), + ..record.clone() + }; + let second = wiremock::MockServer::start().await; + mount_gem_granted_as(&second, UUID2, &newer_gem, &sri_sha512(&newer_gem), stub).await; + let cfg2 = gem_service_cfg(&second.uri(), VendorSource::Service, false); + let (result, entry, _) = unwrap_done(run(&newer, false, &cfg2).await); + assert!(result.success, "{:?}", result.error); + let mut entry = entry.expect("an entry"); + assert_eq!(std::fs::read(archive(UUID2)).unwrap(), newer_gem); + let pair = read(GEMFILE) + &read(GEMFILE_LOCK); + assert!( + pair.contains(&source(UUID2)) && !pair.contains(&source(UUID)), + "{pair}" + ); + crate::vendor::state::carry_forward_wiring(&first, &mut entry); + let outcome = revert_gem(&entry, &root, false).await; + assert!( + outcome.success && outcome.warnings.is_empty(), + "{outcome:?}" + ); + assert_eq!([read(GEMFILE), read(GEMFILE_LOCK)], [GEMFILE_DIRECT, &lock]); + assert!(!archive(UUID2).exists()); + } + /// `service` mode + a `.gem` integrity mismatch hard-fails; nothing wired. #[tokio::test] async fn service_gem_integrity_mismatch_hard_fails() { diff --git a/crates/socket-patch-core/src/vendor/gem/bazel.rs b/crates/socket-patch-core/src/vendor/gem/bazel.rs new file mode 100644 index 000000000..c08b73947 --- /dev/null +++ b/crates/socket-patch-core/src/vendor/gem/bazel.rs @@ -0,0 +1,1438 @@ +//! RubyGems vendored mode for a gem whose `Gemfile` and lock a Bazel hub +//! reads. +//! +//! rules_ruby's `ruby.bundle_fetch` copies the two files into a repository +//! of Bazel's, has Bazel download `gems/-.gem` for +//! every gem of a `GEM` section, and runs `bundle install --local` there. +//! The unpacked copy that vendored mode commits everywhere else +//! ([`super`]: named by a `path:`) is not in that repository, and the build +//! fails on it. What the hub does build is the pair hosted mode writes, +//! with a relative `file:` URL of the checkout in the place of the patch +//! registry's, and the patched gem committed where the ruleset asks that +//! source for it: +//! +//! ```text +//! gem "", …, source: "file:.socket/vendor/gem//" # Gemfile +//! +//! GEM # Gemfile.lock +//! remote: file:.socket/vendor/gem// +//! specs: +//! () +//! DEPENDENCIES +//! (…)! +//! CHECKSUMS +//! () sha256= +//! +//! .socket/vendor/gem//gems/-.gem # the patched gem +//! ``` +//! +//! Bazel's server runs in the root of the workspace and opens the URL from +//! there, and Bundler holds the file to the lock's `CHECKSUMS` line. Built +//! on Bazel 9.3.2, 8.8.2 and 7.7.2 with rules_ruby 1.0.0-rc2 on a machine +//! that reaches no patch host; one changed byte of the gem fails the build +//! of a machine that fetches the hub anew (`ruby::` in the CLI's +//! `e2e_bazel_build`). No file of Bazel's is written. +//! +//! The pair is the hosted planner's own ([`plan_gem_source`]), and its undo +//! is that edit in reverse ([`revert`]). It is written only where [`gate`] +//! shows that it builds, and never on the user's word +//! ([`ALLOW_IN_BAZEL_ENV`]), which asks for the copy of every other +//! project. Anywhere else the gem is declined +//! ([`crate::vendor::bazel_hub`]). +//! +//! What the form costs, which the run says ([`ADVISORY`]): Bundler by +//! itself does not install from such a source (`bundle install` on a +//! machine without the gem and `bundle lock --update` fail, and on a +//! machine that installed the gem before the patch it passes and keeps +//! that unpatched copy), so the checkout builds its gems through Bazel +//! only; and Bazel does not watch the gem, so an output base that fetched +//! the hub before keeps what it fetched. + +use std::path::Path; + +use serde_json::{json, Value}; + +use super::{ + checksum_entry, dep_entry_name, gem_edits, gem_service_archive, is_one_line, + restore_uuid_metadata, GemPrelude, RevertFiles, GEMFILE, GEMFILE_LOCK, GEM_STUB_ARTIFACT_KIND, +}; +use crate::api::client::PlannedDownload; +use crate::bazel::built::{hub_calls, lock_text, reader}; +use crate::bazel::rc::{declared_release, Release}; +use crate::bazel::starlark::Value as Starlark; +use crate::bazel::workspace::{disk, Doubt, Tag, Workspace}; +use crate::bazel::BazelRoot; +use crate::formats::gem::declarations; +use crate::formats::gem::hosted::bundled_with_version; +use crate::formats::gem::{parse, parse_spec}; +use crate::manifest::schema::{PatchFileInfo, PatchRecord}; +use crate::patch::copy_tree::remove_tree; +use crate::patch::redirect::{gem_pair_agrees, plan_gem_source, DepOverride, FileEdit}; +use crate::utils::digest::sha256_hex_of; +use crate::utils::env_compat::env_flag; +use crate::utils::fs::{ + atomic_write_artifact, atomic_write_bytes_preserving_mode, read_regular_to_bytes, run_blocking, +}; +use crate::utils::purl::{build_gem_purl, parse_gem_purl}; +use crate::vendor::bazel_hub::GEM_CODE; +use crate::vendor::common::{ + already_patched_result, copy_matches_after_hashes, done, failed_result, preview_result, + prune_empty_vendor_levels, refused, service_offline_conflict, +}; +use crate::vendor::npm_dir::ignored_root_refusal; +use crate::vendor::path::vendor_uuid_dir_rel; +use crate::vendor::refusals::ALLOW_IN_BAZEL_ENV; +use crate::vendor::registry_fetch::{extract_gem_data, extract_on_blocking_pool}; +use crate::vendor::revert::{self, KeepPolicy}; +use crate::vendor::service_fetch::ServicePolicy; +use crate::vendor::state::{ + write_marker_or_warn, VendorArtifact, VendorEntry, VendorMarker, WiringAction, WiringRecord, +}; +use crate::vendor::{RevertOpts, RevertOutcome, VendorOutcome, VendorServiceConfig, VendorWarning}; + +/// The advisory of a run that vendored a gem this way: what the form costs +/// (see the module docs). +pub(crate) const ADVISORY: &str = "vendor_gem_bazel_file_source"; + +/// The warning of an undo ([`revert`]) after which a `gem_checksums` entry +/// still holds the gem to the patched one's sha256: the entry is the +/// user's own edit, which the run asked for and no undo takes back, and +/// Bazel fails the download of the upstream gem on it. +const ENTRY_LEFT: &str = "vendor_gem_bazel_checksum_left"; + +/// The wiring records of an entry: the source `Gemfile` gives the gem, and +/// what `Gemfile.lock` held before it followed (`original`: the `remote` of +/// the section the gem came from, its `dependency` entry and its `checksum` +/// line, each as the lock spelled it, the last two only where it had one). +const GEMFILE_KIND: &str = "gemfile_file_source"; +const LOCK_KIND: &str = "gemfile_lock_file_source"; + +/// The calls of the hub that read the `Gemfile` and the lock of a project +/// for which a gem committed as its archive is known to build ([`gate`]). +pub(crate) struct Hub { + /// The lock, as Bazel reads it. + lock: String, + /// Those calls, each as a message names it ([`named`]). Every one of + /// them fetches the gem for a hub of its own. + calls: Vec, + /// What the `gem_checksums` of those calls hold a gem to: its + /// `-`, the sha256, and the call, by its place among + /// them. + pins: Vec<(String, String, usize)>, +} + +/// A call of the hub, as a message names it. +fn named(tag: &Tag<'_>) -> String { + format!("`ruby.bundle_fetch` ({}:{})", tag.file, tag.call.line) +} + +/// Whether a gem of the project at the Bazel root `root`, whose `Gemfile` +/// or lock a call of the hub names, can be committed as its archive: the +/// calls that read the two files, or why that is not known to build here. +/// Read from the files of the checkout alone: +/// +/// - The workspace is read with certainty, and no `WORKSPACE` file defines +/// a repository: every call that reads the two files is among the ones +/// seen. +/// - The project is the root of the workspace, where Bazel opens the URL +/// from. +/// - Each call of the hub writes out the files it reads, and one that reads +/// the `Gemfile` or the lock of the project reads both, with +/// `gem_checksums` that are written out. +/// - The checkout names a Bazel release whose downloader opens such a URL +/// ([`opens_file_urls`]). +/// - The lock names a Bundler that the hub is known to build such a source +/// with ([`bundler_builds`]). +pub(crate) async fn gate(root: &BazelRoot) -> Result { + let (dir, project) = (root.dir.clone(), root.project.clone()); + run_blocking(move || read(&dir, &project)).await +} + +fn read(dir: &Path, project: &Path) -> Result { + let view = disk(dir); + let workspace = Workspace::read(&view); + let (calls, doubts) = hub_calls(&workspace, "gem"); + if let Some(doubt) = workspace.doubts.first().or(doubts.first()) { + return Err(uncertain(doubt)); + } + if workspace.legacy.is_some() { + return Err( + "a `WORKSPACE` file of the workspace defines repositories, which are not read".into(), + ); + } + if !project.as_os_str().is_empty() { + return Err( + "the project is not the root of the Bazel workspace, where Bazel opens such a URL \ + from" + .into(), + ); + } + let (mut reading, mut pins) = (Vec::new(), Vec::new()); + for (tag, files) in &calls { + let call = named(tag); + let plain = |name| matches!(tag.call.arg(name), None | Some(Starlark::Str(_))); + if tag.call.unpacks() || !plain("gemfile") || !plain("gemfile_lock") { + return Err(format!("{call} does not write out the files it reads")); + } + let reads = |file| files.iter().any(|path| path == file); + match (reads(GEMFILE), reads(GEMFILE_LOCK)) { + (false, false) => continue, + (true, true) => {} + _ => { + return Err(format!( + "{call} reads one of Gemfile and Gemfile.lock alone" + )) + } + } + let unwritten = || format!("the `gem_checksums` of {call} are not written out"); + match tag.call.arg("gem_checksums") { + None => {} + Some(Starlark::Dict(sums)) => { + for (gem, sum) in sums { + let Starlark::Str(sum) = sum else { + return Err(unwritten()); + }; + pins.push((gem.clone(), sum.clone(), reading.len())); + } + } + Some(_) => return Err(unwritten()), + } + reading.push(call); + } + if reading.is_empty() { + return Err("no `ruby.bundle_fetch` call is seen to read Gemfile and Gemfile.lock".into()); + } + opens_file_urls(declared_release(&view))?; + let unread = || "Gemfile.lock cannot be read".to_string(); + let lock = lock_text(dir, GEMFILE_LOCK).ok_or_else(unread)?; + bundler_builds(&lock)?; + let calls = reading; + Ok(Hub { lock, calls, pins }) +} + +/// Whether the hub is known to build a gem of such a source with the +/// Bundler the lock names (`BUNDLED WITH`), which rules_ruby installs in +/// the hub and runs there. Built with 2.6.9 and 4.0.15, which also hold +/// the gem to the lock's `CHECKSUMS` line; the later releases of the 2 +/// line and the ones of the 4 line are taken to do the same. Every such +/// lock has one `GEM` section per source, which the pair is written for. +fn bundler_builds(lock: &str) -> Result<(), String> { + match bundled_with_version(lock) { + Some(((2, 6..) | (4, _), _)) => Ok(()), + Some((_, version)) => Err(format!( + "it is not known to build with Bundler {version}, which Gemfile.lock names \ + (`BUNDLED WITH`) and the hub runs (it does with 2.6.9 and 4.0.15)" + )), + None => Err( + "Gemfile.lock names no Bundler (`BUNDLED WITH`) for the hub to run, and not every \ + Bundler is known to build such a source" + .into(), + ), + } +} + +/// What a doubt of the reader of the workspace's files says of them. +fn uncertain(Doubt { file, line, why }: &Doubt) -> String { + let line = match line { + 0 => String::new(), + line => format!(":{line}"), + }; + format!("the files of the Bazel workspace are not read with certainty ({file}{line}: {why})") +} + +/// Whether the downloader of the Bazel `release` a checkout names opens a +/// relative `file:` URL from the root of the workspace. Built on 7.7.2, +/// 8.8.2 and 9.3.2, and the other releases of those three lines are taken +/// to do the same but for 9.1.0: Bazel's own history says that +/// `repository_ctx.download` fails on such a URL there, and that 9.1.1 and +/// 9.2.0 fixed it. A checkout that names no release, or one that is not +/// three numbers (`latest`, a release candidate), may be built by that one, +/// and by any release to come. +fn opens_file_urls(release: Option) -> Result<(), String> { + match release { + None => Err( + "the checkout names no Bazel release as three numbers (`.bazelversion`, or \ + `USE_BAZEL_VERSION` in `.bazeliskrc`), and not every release opens such a URL" + .into(), + ), + Some((9, 1, 0)) => Err("Bazel 9.1.0 fails on such a URL (9.1.1 and later open it)".into()), + Some((7..=9, _, _)) => Ok(()), + Some((major, minor, patch)) => Err(format!( + "it is not known to build on Bazel {major}.{minor}.{patch} (it does on 7.7.2, 8.8.2 \ + and 9.3.2)" + )), + } +} + +impl Hub { + /// Why version `version` of the gem `name` is not committed for these + /// calls, before its bytes are known: the lock holds it as platform + /// gems, which no build has been run with, or in the hub of one of the + /// calls nothing would hold the committed gem to its bytes. Bundler + /// holds it to the lock's `CHECKSUMS` line and Bazel to the + /// `gem_checksums` entry of the call that fetches it, and to nothing + /// else. + pub(crate) fn declines(&self, name: &str, version: &str) -> Option { + let lock = parse(&self.lock); + if !lock.locked_builds(name, version).platforms.is_empty() { + return Some(format!( + "Gemfile.lock holds {name} {version} as platform gems" + )); + } + if lock.has_checksums() { + return None; + } + let key = format!("{name}-{version}"); + let held = |call: &usize| self.entries(&key).any(|(_, of)| of == *call); + let call = &self.calls[(0..self.calls.len()).find(|call| !held(call))?]; + Some(format!( + "Gemfile.lock has no CHECKSUMS section and {call} has no `gem_checksums` entry for \ + {key}, so nothing would hold the committed gem to its bytes there (`bundle lock \ + --add-checksums` writes the section)" + )) + } + + /// The `gem_checksums` entries of the gem `key` (`-`): + /// the sha256 and the call of each. + fn entries<'a>(&'a self, key: &'a str) -> impl Iterator { + let of = move |(gem, sum, call): &'a (String, String, usize)| { + (gem == key).then_some((sum.as_str(), *call)) + }; + self.pins.iter().filter_map(of) + } + + /// Why the patched gem, whose bytes hash to `sha256`, is not committed + /// for these calls: a `gem_checksums` entry of one of them holds the + /// gem to other bytes, and Bazel would fail that hub's download of the + /// committed ones. The call is the user's to edit. + fn pinned_to_other_bytes(&self, name: &str, version: &str, sha256: &str) -> Option { + let key = format!("{name}-{version}"); + let other = |(sum, _): &(&str, usize)| !sum.eq_ignore_ascii_case(sha256); + let (sum, call) = self.entries(&key).find(other)?; + let call = &self.calls[call]; + Some(format!( + "the `gem_checksums` of {call} hold {key} to sha256 {sum}, and the patched gem has \ + {sha256}: write that value there and run again (socket-patch does not edit the \ + call, and no undo puts the old value back)" + )) + } +} + +/// Where the gem of one patch is committed for a hub, and the lock it is +/// named in. +struct Site { + /// The directory of the patch, from the project. + dir: String, + /// The source the pair names: `file:.socket/vendor/gem//`. + source: String, + /// The patched gem, from the project: where rules_ruby asks that + /// source for it. + archive: String, + /// `Gemfile.lock`, as it was read. + lock: String, + /// The gem, as the hosted planner takes it. + dep: DepOverride, +} + +impl Site { + fn of(prelude: &GemPrelude, uuid: &str) -> Option { + let dir = vendor_uuid_dir_rel("gem", uuid)?; + let (name, version) = (&prelude.name, &prelude.version); + Some(Site { + source: format!("file:{dir}/"), + archive: format!("{dir}/gems/{name}-{version}.gem"), + dir, + lock: prelude.lock_eol.restore(&prelude.lock_text).into_owned(), + dep: DepOverride { + ecosystem: "gem".into(), + name: name.clone(), + namespace: None, + version: version.clone(), + token: String::new(), + patch_uuid: uuid.to_string(), + artifact_url: String::new(), + registry_override: None, + integrity: Default::default(), + }, + }) + } + + /// How the gem of `prelude` is vendored in the project at `project`. + /// `None`: as it is without Bazel. `Ok(None)`: the pair names the + /// source already. `Ok(Some)`: for these calls. `Err`: not at all, and + /// this is why. + async fn lane( + &self, + prelude: &GemPrelude, + project: &Path, + ) -> Option, String>> { + if prelude.lock_wired { + return None; + } + let gemfile = &prelude.gemfile_text; + if gemfile.contains(&self.source) + && gem_pair_agrees(gemfile, &self.lock, &self.dep, &self.source).is_ok() + { + return Some(Ok(None)); + } + if env_flag(ALLOW_IN_BAZEL_ENV) { + return None; + } + let dir = project.to_path_buf(); + let root = run_blocking(move || crate::bazel::bazel_root(&dir)).await?; + let files = [GEMFILE, GEMFILE_LOCK].map(String::from).to_vec(); + Some(match reader(&root, "gem", files).await? { + Err(doubt) => Err(uncertain(&doubt)), + Ok(_) => gate(&root).await.and_then(|hub| { + let declined = hub.declines(&prelude.name, &prelude.version); + declined.map_or(Ok(Some(hub)), Err) + }), + }) + } + + /// Whether the committed gem is the one the pair names: it holds every + /// file of `record` as patched, and hashes to what the lock pins. + async fn intact(&self, project: &Path, record: &PatchRecord) -> bool { + let Ok(bytes) = read_regular_to_bytes(&project.join(&self.archive)).await else { + return false; + }; + self.pinned().is_none_or(|sum| sum == sha256_hex_of(&bytes)) + && carries(bytes, &record.files).await + } + + /// The sha256 the lock's `CHECKSUMS` holds the gem to. + fn pinned(&self) -> Option { + let lock = parse(&self.lock); + let sum = lock.checksum(&self.dep.name, &self.dep.version)?; + Some(sum.to_ascii_lowercase()) + } + + /// Whether the `Gemfile` gives the gem the source of an earlier patch: + /// the new one takes its place, as the hosted planner follows a patch + /// that supersedes one. + fn follows(&self, gemfile: &str) -> bool { + let decls = declarations::declarations(gemfile); + let ours = |url: &str| crate::origin::vendor_uuid_dir(url).is_some(); + let mut sources = decls.of(&self.dep.name).filter_map(|decl| decl.source()?.1); + sources.any(ours) + } +} + +/// Whether the gem archive `bytes` holds every file of a patch as patched. +pub(crate) async fn carries( + bytes: Vec, + files: &std::collections::HashMap, +) -> bool { + let Ok(stage) = tempfile::tempdir() else { + return false; + }; + let unpacked = extract_on_blocking_pool(bytes, stage.path(), extract_gem_data).await; + unpacked.is_ok() && copy_matches_after_hashes(stage.path(), files).await +} + +/// Whether the artifact of a ledger entry is a gem committed as its +/// archive. +pub(crate) fn is_archive(entry: &VendorEntry) -> bool { + entry.ecosystem == "gem" && archive_path(&entry.artifact.path) +} + +/// Whether `path` (with `/` between its parts) is where this form commits +/// a gem: `/gems/.gem`, the path rules_ruby asks a source +/// for. A copy that is vendored by its path is a directory named for its +/// gem and version, and a version may end in `.gem`. +pub(crate) fn archive_path(path: &str) -> bool { + let dir = path.rsplit_once('/').map(|(dir, _)| dir); + path.ends_with(".gem") && dir.is_some_and(|dir| dir.ends_with("/gems")) +} + +/// Hold the committed gem `archive` to `record`: every file of the patch +/// is in it as patched. The error is the routing tag of +/// [`crate::vendor::verify::verify_vendored_patch_record`]. +pub(crate) async fn verify(archive: &Path, record: &PatchRecord) -> Result<(), String> { + let unreadable = |_| "vendor_artifact_unreadable".to_string(); + let bytes = read_regular_to_bytes(archive).await.map_err(unreadable)?; + match carries(bytes, &record.files).await { + true => Ok(()), + false => Err("vendor_hash_mismatch".to_string()), + } +} + +/// The download [`vendor`] makes for the gem of `prelude`: the archive and +/// its stub gemspec, which says whether the gem is one the lane takes. +/// `None` where the gem is vendored as it is without Bazel; `Some(None)` +/// where it is declined, or in place. +pub(super) async fn preflight( + purl: &str, + prelude: &GemPrelude, + project: &Path, + record: &PatchRecord, +) -> Option> { + let site = Site::of(prelude, &record.uuid)?; + let asks = match site.lane(prelude, project).await? { + Err(_) => false, + Ok(None) => !site.intact(project, record).await, + Ok(Some(_)) => site.follows(&prelude.gemfile_text) || gem_edits(purl, prelude).is_ok(), + }; + Some(asks.then(|| PlannedDownload { + secondary: Some(GEM_STUB_ARTIFACT_KIND.to_string()), + ..PlannedDownload::archive(record.uuid.clone()) + })) +} + +/// Vendor the gem of `prelude` as its archive, for a hub that reads the +/// `Gemfile` and the lock of the project (see the module docs). `None` +/// where no hub reads them, or the user asked for the copy of every other +/// project: the caller goes on. +pub(super) async fn vendor( + purl: &str, + prelude: &GemPrelude, + project: &Path, + record: &PatchRecord, + vendored_at: &str, + dry_run: bool, + service: Option<&VendorServiceConfig>, +) -> Option { + let site = Site::of(prelude, &record.uuid)?; + let hub = match site.lane(prelude, project).await? { + Ok(hub) => hub, + Err(why) => { + let detail = format!( + "a call of rules_ruby in the Bazel workspace reads the lock of this project, \ + and the patched gem cannot be committed for it: {why}" + ); + return Some(refused(GEM_CODE, detail)); + } + }; + let (name, version) = (prelude.name.as_str(), prelude.version.as_str()); + let archive = project.join(&site.archive); + if hub.is_none() && site.intact(project, record).await { + let result = already_patched_result(purl, &archive, &record.files); + return Some(done(result, None, Vec::new())); + } + // The gem meets the refusals of every vendored gem first. A + // declaration that carries the source of an earlier patch passed them + // when that patch was vendored. + if hub.is_some() && !site.follows(&prelude.gemfile_text) { + if let Err(outcome) = gem_edits(purl, prelude) { + return Some(*outcome); + } + } + if let Some(refusal) = service_offline_conflict(service) { + return Some(refusal); + } + let fetched = match gem_service_archive(service, record, name).await { + Ok((fetched, _)) => fetched, + Err(outcome) => return Some(*outcome), + }; + let sha256 = fetched.sha256_hex().to_string(); + if !carries(fetched.bytes.clone(), &record.files).await { + return Some(*ServicePolicy::Refused.miss(format!( + "prebuilt .gem for {name} extracted to an unexpected layout (patched files absent \ + at their recorded paths)" + ))); + } + let declined = |why: String| Some(refused(GEM_CODE, why)); + let plan = match &hub { + // The pair is in place and the gem is not: only the gem is + // written, and it has to be the one the lock pins. + None => match site.pinned().filter(|sum| *sum != sha256) { + Some(sum) => { + return declined(format!( + "Gemfile.lock holds {name} {version} to sha256 {sum}, and the patch \ + service's gem has {sha256}; {}", + crate::vendor::common::REVERT_ALL_AND_REVENDOR + )) + } + None => None, + }, + Some(hub) => { + if let Some(why) = hub.pinned_to_other_bytes(name, version, &sha256) { + return declined(why); + } + let (gemfile, lock) = (&prelude.gemfile_text, &site.lock); + match plan_gem_source(gemfile, lock, &site.dep, &site.source, &sha256) { + Ok(plan) => Some(plan), + Err(warning) => { + return declined(format!( + "Gemfile and Gemfile.lock cannot name the committed gem as hosted mode \ + names a patch registry ({}: {})", + warning.code, warning.detail + )) + } + } + } + }; + if dry_run { + let result = preview_result(purl, &archive, &record.files); + return Some(done(result, None, Vec::new())); + } + + // ── the gem, where rules_ruby asks the source for it ───────────────── + if let Some((code, detail)) = ignored_root_refusal(project, &site.dir).await { + return Some(refused(code, detail)); + } + let uuid_dir = prelude.uuid_dir.as_path(); + // A gem whose pair was in place keeps what it has. + let fresh = plan.is_some(); + let unwind = || async { + if fresh { + let _ = remove_tree(uuid_dir).await; + prune_empty_vendor_levels(uuid_dir).await; + } + }; + let failed = |what: &str, e: std::io::Error| { + let error = format!("failed to write {what}: {e}"); + Some(done(failed_result(purl, &archive, error), None, Vec::new())) + }; + let written = async { + tokio::fs::create_dir_all(archive.parent().unwrap_or(uuid_dir)).await?; + atomic_write_artifact(&archive, &fetched.bytes).await?; + // Stock ignore templates name `*.gem`. + restore_uuid_metadata(uuid_dir).await + }; + if let Err(e) = written.await { + unwind().await; + return failed(&site.archive, e); + } + let mut warnings = vec![fetched.downloaded_warning(name)]; + let artifact = VendorArtifact { + yarn_berry10c0: None, + path: site.archive.clone(), + sha256, + size: Some(fetched.bytes.len() as u64), + platform_locked: None, + file_inventory: None, + }; + let entry = |wiring| { + let purl = build_gem_purl(name, version); + VendorEntry::new("gem".into(), purl, record.uuid.clone(), artifact, wiring) + }; + let result = already_patched_result(purl, &archive, &record.files); + let Some((gemfile, lock, edits)) = plan else { + warnings.push(VendorWarning::new( + "vendor_artifact_rebuilt", + format!( + "the committed gem for {name}@{version} was missing or not the patched one; \ + written again at {} (Gemfile and Gemfile.lock untouched)", + site.archive + ), + )); + // The wiring is the first run's, which the caller carries forward. + return Some(done(result, Some(entry(Vec::new())), warnings)); + }; + + // ── Gemfile, then Gemfile.lock (a failure unwinds the Gemfile) ─────── + if let Err(e) = + atomic_write_bytes_preserving_mode(&prelude.gemfile_path, gemfile.as_bytes()).await + { + unwind().await; + return failed(GEMFILE, e); + } + if let Err(e) = atomic_write_bytes_preserving_mode(&prelude.lock_path, lock.as_bytes()).await { + let before = prelude.gemfile_text.as_bytes(); + let _ = atomic_write_bytes_preserving_mode(&prelude.gemfile_path, before).await; + unwind().await; + return failed(GEMFILE_LOCK, e); + } + let marker = VendorMarker::new("gem", &build_gem_purl(name, version), record, vendored_at); + write_marker_or_warn(uuid_dir, &marker, &mut warnings).await; + warnings.push(VendorWarning::new( + ADVISORY, + format!( + "{name} {version} is vendored for the Bazel hub that reads Gemfile.lock: Gemfile and \ + Gemfile.lock name {} by a relative `file:` URL, which Bazel builds. Bundler by \ + itself does not install from such a source (`bundle install` on a machine without \ + the gem and `bundle lock --update` fail; on a machine that installed the gem before, \ + `bundle install` passes and keeps that unpatched copy), so this checkout builds its \ + gems through Bazel only; `--mode hosted` serves both. Bazel does not watch the gem: \ + an output base that fetched the hub before keeps what it fetched", + site.archive + ), + )); + Some(done( + result, + Some(entry(records(name, &site.source, &edits))), + warnings, + )) +} + +/// The wiring records of the pair edit `edits` made for the gem `name` +/// ([`GEMFILE_KIND`], [`LOCK_KIND`]). An edit that followed an earlier +/// patch moved no entry of the lock: its record has no `original`, and the +/// caller carries the one of the entry it replaces forward. +fn records(name: &str, source: &str, edits: &[FileEdit]) -> Vec { + let before = |kind: &str| { + let edit = edits.iter().find(|edit| edit.kind == kind)?; + edit.original.clone() + }; + let original = before("redirect_gemfile_lock_gem_source").map(|remote| { + json!({ + "remote": remote, + "dependency": before("redirect_gemfile_lock_dependency_pin"), + "checksum": before("redirect_gemfile_lock_checksum"), + }) + }); + let record = |file: &str, kind: &str, action, original| WiringRecord { + file: file.to_string(), + kind: kind.to_string(), + action, + key: Some(name.to_string()), + original, + new: Some(Value::String(source.to_string())), + }; + vec![ + record(GEMFILE, GEMFILE_KIND, WiringAction::Added, None), + record(GEMFILE_LOCK, LOCK_KIND, WiringAction::Rewritten, original), + ] +} + +/// Revert the entry of a gem committed as its archive: the `Gemfile` loses +/// the source, the lock's entry goes back to the section it came from with +/// its `DEPENDENCIES` entry and its `CHECKSUMS` line, and the directory of +/// the patch is removed. The two files go back together or not at all: a +/// pair that no longer holds what [`vendor`] wrote is left alone +/// (`vendor_lock_entry_drifted`) with the gem, and one that names the +/// source nowhere has been put back already. +pub(super) async fn revert( + entry: &VendorEntry, + project: &Path, + uuid_dir_rel: &str, + opts: RevertOpts, +) -> RevertOutcome { + let Some((name, version)) = parse_gem_purl(&entry.base_purl) else { + return RevertOutcome::failed(format!("not a gem purl: {}", entry.base_purl)); + }; + let source = format!("file:{uuid_dir_rel}/"); + let mut files = RevertFiles::new(project); + let mut texts = Vec::new(); + for file in [GEMFILE_LOCK, GEMFILE] { + match files.text(file).await { + Ok(text) => texts.push(text.map(|text| text.text().to_string())), + Err(e) => return RevertOutcome::failed(e), + } + } + let mut outcome = RevertOutcome::ok(); + let before = entry.wiring.iter().find(|w| w.kind == LOCK_KIND); + let before = before.and_then(|w| w.original.as_ref()); + match (&texts[0], &texts[1]) { + (Some(lock), Some(gemfile)) if lock.contains(&source) || gemfile.contains(&source) => { + let lock = before.and_then(|b| unwire_lock(lock, &name, &version, &source, b)); + match (lock, unwire_gemfile(gemfile, &name, &source)) { + (Some(lock), Some(gemfile)) => { + for (file, text) in [(GEMFILE_LOCK, lock), (GEMFILE, gemfile)] { + if let Ok(Some(file)) = files.text(file).await { + file.set(text); + } + } + let key = format!("{name}-{version}"); + let (dir, sum) = (project.to_path_buf(), entry.artifact.sha256.clone()); + let left = run_blocking(move || entry_left(&dir, &key, &sum)).await; + outcome.warnings.extend(left); + } + _ => outcome.warnings.push(VendorWarning::new( + "vendor_lock_entry_drifted", + format!( + "{GEMFILE} and {GEMFILE_LOCK} no longer carry what vendor wrote for \ + {name}; left alone, and neither was changed" + ), + )), + } + } + (Some(_), Some(_)) => {} + _ => outcome.warnings.push(VendorWarning::new( + "vendor_lockfile_missing", + format!("{GEMFILE} or {GEMFILE_LOCK} is missing; the {name} entry cannot be restored"), + )), + } + if !opts.dry_run { + if let Err(e) = files.write_changed().await { + return RevertOutcome::failed(e); + } + } + revert::finish(outcome, project, uuid_dir_rel, opts, KeepPolicy::OnDrift).await +} + +/// What an undo in the project at `project` says of a call of the hub +/// whose `gem_checksums` still hold the gem `key` (`-`) to +/// `sha256`, the one of the committed gem ([`ENTRY_LEFT`]). Read apart from +/// [`gate`]: the entry fails the build whatever else the checkout says. +fn entry_left(project: &Path, key: &str, sha256: &str) -> Option { + let root = crate::bazel::bazel_root(project)?; + let workspace = Workspace::read(&disk(&root.dir)); + let holds = |tag: &Tag<'_>| match tag.call.arg("gem_checksums") { + Some(Starlark::Dict(sums)) => sums.iter().any(|(gem, sum)| { + gem == key && matches!(sum, Starlark::Str(sum) if sum.eq_ignore_ascii_case(sha256)) + }), + _ => false, + }; + let (calls, _) = hub_calls(&workspace, "gem"); + let call = calls + .iter() + .find(|(tag, _)| holds(tag)) + .map(|(tag, _)| named(tag))?; + Some(VendorWarning::new( + ENTRY_LEFT, + format!( + "the `gem_checksums` of {call} still hold {key} to the sha256 of the patched gem \ + ({sha256}), and the lock names the upstream gem again: the Bazel build fails on \ + that entry until it holds the upstream gem's sha256, or is removed (socket-patch \ + does not edit the call)" + ), + )) +} + +/// `gemfile` without the source `source` of the gem `name`: the option +/// goes from the one declaration that carries it, or the whole line where +/// the pair added it. `None` unless exactly one declaration carries it. +fn unwire_gemfile(gemfile: &str, name: &str, source: &str) -> Option { + let decls = declarations::declarations(gemfile); + let ours = |decl: &&declarations::Declaration| { + decl.source().is_some_and(|(_, url)| url == Some(source)) + }; + let mut ours = decls.of(name).filter(ours); + let (decl, None) = (ours.next()?, ours.next()) else { + return None; + }; + Some(match declarations::is_added_line(gemfile, decl) { + true => declarations::without_added_line(gemfile, decl), + false => declarations::without_arg(gemfile, decl.source()?.0), + }) +} + +/// `lock` (with `\n` line endings) with version `version` of the gem +/// `name` back where it was before the pair named `source`, as `before` +/// records it ([`LOCK_KIND`]): the entry in the section of that remote, +/// where Bundler sorts it; its `DEPENDENCIES` entry as it was, or gone +/// where the pair added it; and its `CHECKSUMS` line likewise. `None` for a +/// lock that does not hold exactly what the pair wrote, and for a record +/// that would put back a line that is not this gem's. +fn unwire_lock( + lock: &str, + name: &str, + version: &str, + source: &str, + before: &Value, +) -> Option { + let mut lines: Vec = lock.split('\n').map(str::to_string).collect(); + // The `GEM` section whose one remote is `remote`: the line of its + // first entry. + let entries = |lines: &[String], remote: &str| { + let remote = format!(" remote: {remote}"); + let head = ["GEM", remote.as_str(), " specs:"]; + let heads = |at: &usize| lines.get(*at..at + 3).is_some_and(|l| l[..] == head[..]); + (0..lines.len()).find(heads).map(|at| at + 3) + }; + // The entry of a line that is this gem's own, as the lock spells it. + let own = |key: &str, names: &dyn Fn(&str) -> bool| match before.get(key) { + None | Some(Value::Null) => Some(None), + Some(Value::String(entry)) => { + let line = format!(" {entry}"); + (is_one_line(&line, false) && names(&line)).then_some(Some(line)) + } + Some(_) => None, + }; + let dependency = own("dependency", &|line| dep_entry_name(line) == Some(name))?; + let checksum = own("checksum", &|line| { + checksum_entry(line).is_some_and(|(gem, _)| gem == name) + })?; + + // The section of the patch: the gem's entry with its dependencies, and + // the blank line after it. + let first = entries(&lines, source)?; + if lines.get(first) != Some(&format!(" {name} ({version})")) { + return None; + } + let deps = lines[first + 1..] + .iter() + .take_while(|l| l.starts_with(" ")); + let end = first + 1 + deps.count(); + if lines.get(end).is_none_or(|line| !line.is_empty()) { + return None; + } + let block: Vec = lines.drain(first - 3..=end).skip(3).collect(); + let block = &block[..block.len() - 1]; + + // Back into the section it came from, by its full name. + let full = |line: &str| { + let spec = parse_spec(line.strip_prefix(" ")?)?; + let platform = spec.platform.map(|platform| format!("-{platform}")); + let platform = platform.unwrap_or_default(); + Some(format!("{}-{}{platform}", spec.name, spec.version)) + }; + let ours = format!("{name}-{version}"); + let mut at = entries(&lines, before.get("remote")?.as_str()?)?; + while lines.get(at).is_some_and(|line| line.starts_with(" ")) { + if full(&lines[at]).is_some_and(|other| other > ours) { + break; + } + at += 1; + } + lines.splice(at..at, block.iter().cloned()); + + // The lines of a section that is all two-space entries. + let section = |lines: &[String], header: &str| { + let start = lines.iter().position(|line| line == header)? + 1; + let len = lines[start..].iter().take_while(|l| l.starts_with(" ")); + Some(start..start + len.count()) + }; + let pinned = |line: &String| line.ends_with('!') && dep_entry_name(line) == Some(name); + let at = section(&lines, "DEPENDENCIES")?.find(|at| pinned(&lines[*at]))?; + match dependency { + Some(entry) => lines[at] = entry, + None => drop(lines.remove(at)), + } + let sums = section(&lines, "CHECKSUMS").unwrap_or(0..0); + let pins = |line: &String| checksum_entry(line) == Some((name, version)); + match (sums.clone().find(|at| pins(&lines[*at])), checksum) { + (Some(at), Some(line)) => lines[at] = line, + (Some(at), None) => drop(lines.remove(at)), + (None, None) => {} + (None, Some(_)) => return None, + } + Some(lines.join("\n")) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::path::PathBuf; + + const UUID: &str = "11111111-1111-4111-8111-111111111111"; + const NEWER: &str = "33333333-3333-4333-8333-333333333333"; + const MODULE: &str = r#"ruby = use_extension("@rules_ruby//ruby:extensions.bzl", "ruby") +ruby.bundle_fetch(name = "bundle", gemfile = "//:Gemfile", gemfile_lock = "//:Gemfile.lock") +"#; + const GEMFILE_TEXT: &str = "source \"https://rubygems.org/\"\n\ngem \"rack\", \"~> 2.2\"\n"; + + fn sum(of: char) -> String { + of.to_string().repeat(64) + } + + /// A lock that resolves `rack 2.2.3`, which depends on `zeitwerk`, + /// between two other gems, with a `CHECKSUMS` section. + fn lock() -> String { + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n ast (1.0.0)\n rack (2.2.3)\n \ + zeitwerk (~> 2.6)\n zeitwerk (2.6.0)\n\nPLATFORMS\n ruby\n\nDEPENDENCIES\n rack \ + (~> 2.2)\n\nCHECKSUMS\n ast (1.0.0) sha256={}\n rack (2.2.3) sha256={}\n zeitwerk \ + (2.6.0) sha256={}\n\nBUNDLED WITH\n 2.6.9\n", + sum('a'), + sum('b'), + sum('c') + ) + } + + /// A checkout whose root `MODULE.bazel` is `module`, canonical, with + /// the files `files` and Bazel 9.3.2 in `.bazelversion`. + fn checkout(module: &str, files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let root = fs::canonicalize(tmp.path()).unwrap(); + let (lock, head) = (lock(), "ref: refs/heads/main\n"); + let all = [ + (".git/HEAD", head), + ("MODULE.bazel", module), + (".bazelversion", "9.3.2\n"), + (GEMFILE, GEMFILE_TEXT), + (GEMFILE_LOCK, lock.as_str()), + ]; + for (path, text) in all.iter().chain(files) { + let path = root.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + (tmp, root) + } + + /// Why [`gate`] declines the project at `project`, or `None`. + async fn declined(project: &Path) -> Option { + let root = crate::bazel::bazel_root(project).expect("a Bazel workspace"); + gate(&root).await.err() + } + + #[tokio::test] + async fn the_gate_holds_where_each_condition_is_read_from_the_checkout() { + let (_tmp, root) = checkout(MODULE, &[]); + assert_eq!(declined(&root).await, None); + // Each edit of that checkout, and what the gate then names. + let call = "ruby.bundle_fetch(name = \"bundle\", gemfile = \"//:Gemfile\", "; + let lock_arg = "gemfile_lock = \"//:Gemfile.lock\""; + let pinned = |sums: &str| MODULE.replace(lock_arg, &format!("{lock_arg}, {sums}")); + let bundler = |version: &str| lock().replace(" 2.6.9", &format!(" {version}")); + let unnamed = "names no Bazel release as three numbers"; + let cases: [(&str, String, &str); 15] = [ + (".bazelversion", String::new(), unnamed), + (".bazelversion", "latest\n".into(), unnamed), + (".bazelversion", "9.3.2rc1\n".into(), unnamed), + ( + ".bazelversion", + "9.1.0\n".into(), + "Bazel 9.1.0 fails on such a URL", + ), + ( + ".bazelversion", + "6.5.0\n".into(), + "not known to build on Bazel 6.5.0", + ), + ( + "WORKSPACE", + "local_repository(name = \"x\", path = \"x\")\n".into(), + "a `WORKSPACE` file of the workspace defines repositories", + ), + ( + "MODULE.bazel", + format!("{MODULE}include(\"//:more.MODULE.bazel\")\n"), + "not read with certainty (more.MODULE.bazel: it does not exist", + ), + ( + "MODULE.bazel", + MODULE.replace(lock_arg, "**LOCK"), + "`ruby.bundle_fetch` (MODULE.bazel:2) does not write out the files it reads", + ), + ( + "MODULE.bazel", + format!("{MODULE}{call}gemfile_lock = \"//svc:Gemfile.lock\")\n"), + "`ruby.bundle_fetch` (MODULE.bazel:3) reads one of Gemfile and Gemfile.lock alone", + ), + ( + "MODULE.bazel", + pinned("gem_checksums = SUMS"), + "the `gem_checksums` of `ruby.bundle_fetch` (MODULE.bazel:2) are not written out", + ), + ( + "MODULE.bazel", + pinned("gem_checksums = {\"rack-2.2.3\": SUM}"), + "the `gem_checksums` of `ruby.bundle_fetch` (MODULE.bazel:2) are not written out", + ), + ( + "MODULE.bazel", + MODULE.replace("//:", "//svc:"), + "no `ruby.bundle_fetch` call is seen to read Gemfile and Gemfile.lock", + ), + ( + GEMFILE_LOCK, + bundler("1.17.3"), + "not known to build with Bundler 1.17.3, which Gemfile.lock names", + ), + ( + GEMFILE_LOCK, + bundler("2.5.23"), + "not known to build with Bundler 2.5.23, which Gemfile.lock names", + ), + ( + GEMFILE_LOCK, + String::new(), + "Gemfile.lock names no Bundler (`BUNDLED WITH`)", + ), + ]; + for (file, text, why) in cases { + let (_tmp, root) = checkout(MODULE, &[(file, &text)]); + let said = declined(&root).await.unwrap_or_default(); + assert!( + said.contains(why), + "{file} = {text:?}: {said:?}, not {why:?}" + ); + } + // A call that reads the files of another project is none of this + // one's, whatever it holds its gems to. + let other = MODULE + .replace("//:", "//svc:") + .replace(lock_arg, "gem_checksums = SUMS"); + let (_tmp, root) = checkout(&format!("{MODULE}{}", other.lines().nth(1).unwrap()), &[]); + assert_eq!(declined(&root).await, None); + // A project below the root: Bazel opens the URL from the root. + let below = MODULE.replace("//:", "//api:"); + let files = [("api/Gemfile", GEMFILE_TEXT), ("api/Gemfile.lock", "")]; + let (_tmp, root) = checkout(&below, &files); + let said = declined(&root.join("api")).await.unwrap_or_default(); + assert!( + said.contains("is not the root of the Bazel workspace"), + "{said}" + ); + } + + #[test] + fn a_release_opens_the_url_where_one_of_its_line_was_built() { + for known in [ + (7, 0, 0), + (7, 7, 2), + (8, 8, 2), + (9, 0, 2), + (9, 1, 1), + (9, 3, 2), + ] { + assert_eq!(opens_file_urls(Some(known)), Ok(()), "{known:?}"); + } + for unknown in [None, Some((9, 1, 0)), Some((6, 5, 0)), Some((10, 0, 0))] { + assert!(opens_file_urls(unknown).is_err(), "{unknown:?}"); + } + } + + #[test] + fn the_hub_builds_with_a_bundler_of_a_line_that_was_built() { + let named = |version: &str| format!("GEM\n specs:\n\nBUNDLED WITH\n {version}\n"); + for known in ["2.6.0", "2.6.9", "2.7.2", "4.0.15"] { + assert_eq!(bundler_builds(&named(known)), Ok(()), "{known}"); + } + for unknown in ["2.2.19", "2.5.23", "3.0.0", "5.0.0", "two"] { + assert!(bundler_builds(&named(unknown)).is_err(), "{unknown}"); + } + } + + /// The artifact of the form is known by its place, so a copy vendored + /// by its path, a directory, keeps the checks of one whatever its + /// version ends in. + #[test] + fn a_committed_gem_is_known_by_its_place() { + use crate::vendor::verify::artifact_is_file_shaped; + let committed = ".socket/vendor/gem/u/gems/rack-2.2.3.gem"; + assert!(archive_path(committed) && artifact_is_file_shaped(committed)); + assert!(artifact_is_file_shaped(&committed.replace('/', "\\"))); + for copy in [".socket/vendor/gem/u/rack-1.0.0.gem", "rack.gem"] { + assert!( + !archive_path(copy) && !artifact_is_file_shaped(copy), + "{copy}" + ); + } + } + + /// The committed gem is held to its bytes by the lock's `CHECKSUMS` + /// line or by the `gem_checksums` entry of every call that reads the + /// pair, and an entry of any of them that holds the gem to other bytes + /// declines it. + #[tokio::test] + async fn a_gem_is_committed_only_where_its_bytes_are_held() { + let entry = format!("gem_checksums = {{\"rack-2.2.3\": \"{}\"}}", sum('B')); + let lock_arg = "gemfile_lock = \"//:Gemfile.lock\""; + let pinned = MODULE.replace(lock_arg, &format!("{lock_arg}, {entry}")); + let unchecked = + lock().split("CHECKSUMS").next().unwrap().to_string() + "BUNDLED WITH\n 2.6.2\n"; + let hub = |module: &str, lock: &str| { + let (module, lock) = (module.to_string(), lock.to_string()); + async move { + let (_tmp, root) = checkout(&module, &[(GEMFILE_LOCK, &lock)]); + let root = crate::bazel::bazel_root(&root).unwrap(); + gate(&root).await.expect("the gate holds") + } + }; + let (rack, version) = ("rack", "2.2.3"); + assert_eq!(hub(MODULE, &lock()).await.declines(rack, version), None); + let declined = hub(MODULE, &unchecked).await.declines(rack, version); + let unheld = |line: u32| { + format!( + "has no CHECKSUMS section and `ruby.bundle_fetch` (MODULE.bazel:{line}) has no \ + `gem_checksums` entry for rack-2.2.3" + ) + }; + assert!(declined.is_some_and(|said| said.contains(&unheld(2)))); + assert_eq!(hub(&pinned, &unchecked).await.declines(rack, version), None); + // The entry is of the gem alone, and is read without regard to case. + let held = hub(&pinned, &lock()).await; + assert_eq!(held.pinned_to_other_bytes(rack, version, &sum('b')), None); + assert_eq!(held.pinned_to_other_bytes("ast", "1.0.0", &sum('d')), None); + let other = held.pinned_to_other_bytes(rack, version, &sum('d')); + let other = other.unwrap_or_default(); + let named = [ + "the `gem_checksums` of `ruby.bundle_fetch` (MODULE.bazel:2) hold rack-2.2.3 to sha256", + &sum('B'), + &sum('d'), + "socket-patch does not edit the call", + ]; + assert!(named.iter().all(|part| other.contains(part)), "{other}"); + // A second call that reads the pair fetches the gem for a hub of + // its own: its entry holds the gem too, and where the lock has no + // section it needs one. + let second = |sums: &str| { + let call = MODULE.lines().nth(1).unwrap(); + let call = call.replace("\"bundle\"", "\"tools\""); + format!( + "{pinned}{}\n", + call.replace(lock_arg, &format!("{lock_arg}{sums}")) + ) + }; + let upstream = format!(", gem_checksums = {{\"rack-2.2.3\": \"{}\"}}", sum('d')); + let held = hub(&second(&upstream), &lock()).await; + let other = held.pinned_to_other_bytes(rack, version, &sum('b')); + let other = other.unwrap_or_default(); + let named = [ + "`ruby.bundle_fetch` (MODULE.bazel:3) hold rack-2.2.3", + &sum('d'), + ]; + assert!(named.iter().all(|part| other.contains(part)), "{other}"); + assert_eq!( + held.pinned_to_other_bytes(rack, version, &sum('d')) + .is_some(), + true + ); + let declined = hub(&second(""), &unchecked).await.declines(rack, version); + assert!(declined.is_some_and(|said| said.contains(&unheld(3)))); + let both = second(&upstream.replace(&sum('d'), &sum('b'))); + let held = hub(&both, &unchecked).await; + assert_eq!(held.declines(rack, version), None); + assert_eq!(held.pinned_to_other_bytes(rack, version, &sum('b')), None); + // A gem the lock holds as platform gems. + let platform = lock().replace(" rack (2.2.3)\n", " rack (2.2.3-java)\n"); + let declined = hub(MODULE, &platform).await.declines(rack, version); + assert!(declined.is_some_and(|said| said.contains("as platform gems"))); + } + + /// The pair the planner writes for the gem `name` of patch `uuid` in + /// the project at `dir`, on disk, with its gem committed: the ledger + /// entry of it. + fn wire(dir: &Path, name: &str, version: &str, uuid: &str) -> VendorEntry { + let rel = vendor_uuid_dir_rel("gem", uuid).unwrap(); + let (source, archive) = ( + format!("file:{rel}/"), + format!("{rel}/gems/{name}-{version}.gem"), + ); + let dep = DepOverride { + ecosystem: "gem".into(), + name: name.into(), + namespace: None, + version: version.into(), + token: String::new(), + patch_uuid: uuid.into(), + artifact_url: String::new(), + registry_override: None, + integrity: Default::default(), + }; + let read = |file: &str| fs::read_to_string(dir.join(file)).unwrap(); + let (gemfile, lock) = (read(GEMFILE), read(GEMFILE_LOCK)); + let planned = plan_gem_source(&gemfile, &lock, &dep, &source, &sum('f')); + let (gemfile, lock, edits) = planned.expect("a plan"); + assert_eq!(gem_pair_agrees(&gemfile, &lock, &dep, &source), Ok(())); + fs::write(dir.join(GEMFILE), gemfile).unwrap(); + fs::write(dir.join(GEMFILE_LOCK), lock).unwrap(); + fs::create_dir_all(dir.join(&archive).parent().unwrap()).unwrap(); + fs::write(dir.join(&archive), "a gem").unwrap(); + let artifact = VendorArtifact { + yarn_berry10c0: None, + path: archive, + sha256: sum('f'), + size: None, + platform_locked: None, + file_inventory: None, + }; + let purl = build_gem_purl(name, version); + VendorEntry::new( + "gem".into(), + purl, + uuid.into(), + artifact, + records(name, &source, &edits), + ) + } + + async fn reverted(entry: &VendorEntry, dir: &Path) -> RevertOutcome { + let rel = vendor_uuid_dir_rel("gem", &entry.uuid).unwrap(); + revert(entry, dir, &rel, RevertOpts::new(false)).await + } + + /// Every pair the planner writes goes back byte for byte, with the + /// directory of the patch: a declared gem with its own requirement, + /// options and comment, an undeclared one, a pair with CRLF line + /// endings, and a lock with no `CHECKSUMS` section. + #[tokio::test] + async fn the_revert_puts_the_pair_back_byte_for_byte() { + let decorated = "source \"https://rubygems.org/\"\n\ngem 'ast'\ngem \"rack\", \"~> 2.2\", \ + require: false # the web server\n"; + let unchecked = + lock().split("CHECKSUMS").next().unwrap().to_string() + "BUNDLED WITH\n 2.5.0"; + let crlf = |text: &str| text.replace('\n', "\r\n"); + let cases = [ + ("rack", "2.2.3", GEMFILE_TEXT.to_string(), lock()), + ("rack", "2.2.3", decorated.to_string(), lock()), + ( + "zeitwerk", + "2.6.0", + GEMFILE_TEXT.trim_end().to_string(), + lock(), + ), + ("rack", "2.2.3", crlf(GEMFILE_TEXT), crlf(&lock())), + ("zeitwerk", "2.6.0", crlf(decorated), crlf(&lock())), + ("rack", "2.2.3", GEMFILE_TEXT.to_string(), unchecked), + ]; + for (name, version, gemfile, lock) in cases { + let files = [(GEMFILE, gemfile.as_str()), (GEMFILE_LOCK, lock.as_str())]; + let (_tmp, root) = checkout(MODULE, &files); + let entry = wire(&root, name, version, UUID); + let wired = fs::read_to_string(root.join(GEMFILE_LOCK)).unwrap(); + assert!(wired.contains(&format!(" remote: file:.socket/vendor/gem/{UUID}/"))); + let outcome = reverted(&entry, &root).await; + assert!( + outcome.success && outcome.warnings.is_empty(), + "{outcome:?}" + ); + let read = |file: &str| fs::read_to_string(root.join(file)).unwrap(); + assert_eq!( + [read(GEMFILE), read(GEMFILE_LOCK)], + [gemfile, lock], + "{name}" + ); + assert!( + !root.join(".socket/vendor").exists(), + "{name}: the gem is left" + ); + } + } + + /// An undo leaves the call as the user wrote it: where its + /// `gem_checksums` still hold the gem to the committed gem's sha256, + /// which fails the build of the lock the undo puts back, it says so. + #[tokio::test] + async fn an_undo_names_the_entry_it_leaves_in_the_call() { + let lock_arg = "gemfile_lock = \"//:Gemfile.lock\""; + let pinned = |sum: &str| { + let entry = format!("{lock_arg}, gem_checksums = {{\"rack-2.2.3\": \"{sum}\"}}"); + MODULE.replace(lock_arg, &entry) + }; + // `wire` commits a gem whose sha256 is all `f`. + for (module, left) in [ + (pinned(&sum('F')), true), + (pinned(&sum('a')), false), + (MODULE.to_string(), false), + ] { + let (_tmp, root) = checkout(&module, &[]); + let entry = wire(&root, "rack", "2.2.3", UUID); + let outcome = reverted(&entry, &root).await; + let read = |file: &str| fs::read_to_string(root.join(file)).unwrap(); + assert!(outcome.success, "{outcome:?}"); + assert_eq!( + [read(GEMFILE), read(GEMFILE_LOCK)], + [GEMFILE_TEXT.to_string(), lock()] + ); + let said: Vec<&str> = outcome.warnings.iter().map(|w| w.code).collect(); + assert_eq!(said, [ENTRY_LEFT][..usize::from(left)], "{module}"); + let named = [ + "`ruby.bundle_fetch` (MODULE.bazel:2) still hold rack-2.2.3", + &sum('f'), + ]; + let detail = outcome.warnings.first().map(|w| w.detail.as_str()); + let detail = detail.unwrap_or_default(); + assert!( + !left || named.iter().all(|part| detail.contains(part)), + "{detail}" + ); + } + } + + /// A newer patch of the gem takes the source over in place, and its + /// entry, with what the caller carries forward from the one it + /// replaces, puts back the pair of before the first. + #[tokio::test] + async fn a_patch_that_follows_another_reverts_to_the_pair_of_before_both() { + let (_tmp, root) = checkout(MODULE, &[]); + let first = wire(&root, "rack", "2.2.3", UUID); + let mut second = wire(&root, "rack", "2.2.3", NEWER); + let read = |file: &str| fs::read_to_string(root.join(file)).unwrap(); + assert!(!read(GEMFILE_LOCK).contains(UUID) && !read(GEMFILE).contains(UUID)); + // The second edit moved no entry: its record holds no original. + assert_eq!(second.wiring[1].original, None); + assert!(!reverted(&second, &root).await.warnings.is_empty()); + crate::vendor::state::carry_forward_wiring(&first, &mut second); + let outcome = reverted(&second, &root).await; + assert!( + outcome.success && outcome.warnings.is_empty(), + "{outcome:?}" + ); + assert_eq!( + [read(GEMFILE), read(GEMFILE_LOCK)], + [GEMFILE_TEXT.to_string(), lock()] + ); + } + + /// A pair that no longer holds what the run wrote is left alone with + /// the gem, and so is one whose record would put back a line that is + /// not this gem's; a pair that names the source nowhere has been put + /// back, and the gem goes. + #[tokio::test] + async fn a_pair_that_drifted_is_left_alone_and_one_put_back_by_hand_is_done() { + let (_tmp, root) = checkout(MODULE, &[]); + let entry = wire(&root, "rack", "2.2.3", UUID); + let read = |file: &str| fs::read_to_string(root.join(file)).unwrap(); + let (gemfile, wired) = (read(GEMFILE), read(GEMFILE_LOCK)); + let kept = |outcome: &RevertOutcome| { + let drifted = |w: &VendorWarning| w.code == "vendor_lock_entry_drifted"; + let pair = [read(GEMFILE), read(GEMFILE_LOCK)]; + outcome.success + && outcome.warnings.iter().any(drifted) + && root.join(".socket/vendor").exists() + && pair[0] == gemfile + }; + // Another gem moved into the section of the patch. + let drifted = wired.replacen( + " rack (2.2.3)\n", + " rack (2.2.3)\n ast (1.0.0)\n", + 1, + ); + fs::write(root.join(GEMFILE_LOCK), &drifted).unwrap(); + assert!(kept(&reverted(&entry, &root).await)); + assert_eq!(read(GEMFILE_LOCK), drifted); + // The Gemfile lost the source and the lock did not. + fs::write(root.join(GEMFILE_LOCK), &wired).unwrap(); + fs::write(root.join(GEMFILE), GEMFILE_TEXT).unwrap(); + let outcome = reverted(&entry, &root).await; + let drifted = |w: &VendorWarning| w.code == "vendor_lock_entry_drifted"; + assert!(outcome.warnings.iter().any(drifted) && read(GEMFILE_LOCK) == wired); + fs::write(root.join(GEMFILE), &gemfile).unwrap(); + // A record that names another gem's line, or more than one line. + for (key, line) in [ + ("checksum", format!("ast (1.0.0) sha256={}", sum('e'))), + ( + "checksum", + format!("rack (2.2.3) sha256={}\n evil (1.0.0)", sum('e')), + ), + ("dependency", "ast".to_string()), + ] { + let mut tampered = entry.clone(); + tampered.wiring[1].original.as_mut().unwrap()[key] = json!(line); + assert!(kept(&reverted(&tampered, &root).await), "{key}: {line}"); + assert_eq!(read(GEMFILE_LOCK), wired, "{key}: {line}"); + } + // Put back by hand: nothing is left to do but to remove the gem. + fs::write(root.join(GEMFILE), GEMFILE_TEXT).unwrap(); + fs::write(root.join(GEMFILE_LOCK), lock()).unwrap(); + let outcome = reverted(&entry, &root).await; + assert!( + outcome.success && outcome.warnings.is_empty(), + "{outcome:?}" + ); + assert!(!root.join(".socket/vendor").exists()); + } + + /// A committed gem is held to the patch by the files in it. + #[tokio::test] + async fn a_committed_gem_is_held_to_the_files_of_the_patch() { + let patched = b"module Rack\nend\n"; + let record: PatchRecord = serde_json::from_value(json!({ + "uuid": UUID, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { "lib/rack.rb": { + "beforeHash": sum('0'), + "afterHash": crate::hash::git_sha256::compute_git_sha256_from_bytes(patched), + }}, + "vulnerabilities": {}, "description": "", "license": "MIT", "tier": "free", + })) + .unwrap(); + let tmp = tempfile::tempdir().unwrap(); + let archive = tmp.path().join("rack-2.2.3.gem"); + let gem = |source: &[u8]| super::super::tests::make_gem(&[("lib/rack.rb", source)]); + fs::write(&archive, gem(patched)).unwrap(); + assert_eq!(verify(&archive, &record).await, Ok(())); + fs::write(&archive, gem(b"module Rack\n # unpatched\nend\n")).unwrap(); + assert_eq!( + verify(&archive, &record).await, + Err("vendor_hash_mismatch".into()) + ); + fs::write(&archive, b"no gem").unwrap(); + assert_eq!( + verify(&archive, &record).await, + Err("vendor_hash_mismatch".into()) + ); + fs::remove_file(&archive).unwrap(); + assert_eq!( + verify(&archive, &record).await, + Err("vendor_artifact_unreadable".into()) + ); + } +} diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 3a8dd307b..e6da3bccf 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -158,7 +158,11 @@ pub async fn restore( { return Err("the downloaded artifact does not match the recorded size".into()); } - if entry.artifact.path.ends_with(".jar") { + if super::gem::bazel::is_archive(entry) { + if !super::gem::bazel::carries(archive.bytes.clone(), &record.files).await { + return Err("the downloaded gem does not carry the patched files".into()); + } + } else if entry.artifact.path.ends_with(".jar") { // A jar is read by name, case and all, by the JVM: the // installer-shaped strictness of the wheel reader (ASCII names, // no case-colliding pair) refuses obfuscated jars that hold @@ -414,7 +418,8 @@ pub async fn restore( // Likewise a gem vendored as platform gems: only the artifact dir was // swapped in from the stage, and without the uuid dir's own metadata a // `*.so` / `*.bundle` rule drops the prebuilt binaries from the commit. - if entry.ecosystem == "gem" && !entry.gem_platforms.is_empty() { + let archive = super::gem::bazel::is_archive(entry); + if entry.ecosystem == "gem" && (archive || !entry.gem_platforms.is_empty()) { if let Some(rel) = super::path::vendor_uuid_dir_rel("gem", &entry.uuid) { super::gem::restore_uuid_metadata(&root.join(rel)) .await diff --git a/crates/socket-patch-core/src/vendor/refusals.rs b/crates/socket-patch-core/src/vendor/refusals.rs index 7db1b4b2b..c582145fd 100644 --- a/crates/socket-patch-core/src/vendor/refusals.rs +++ b/crates/socket-patch-core/src/vendor/refusals.rs @@ -28,7 +28,8 @@ //! it ([`ALLOW_IN_BAZEL_ENV`]) or the lock already names the patch's //! copy: any Composer project (`vendor_composer_bazel_workspace`), and a //! PyPI or RubyGems project whose lock a hub of the workspace reads -//! (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`). +//! (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), but a gem that +//! can be committed for the hub as its archive ([`gem::bazel`]). //! //! Each check lives in its backend's module; this one only dispatches and //! scopes them. diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 72cdcb9c5..e4f0abbd0 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -132,6 +132,10 @@ pub async fn verify_vendored_patch_record( .map_err(|e| e.to_string())??; return super::pypi_distribution::verify_members(&members, &entry.artifact.path, record); } + // A gem committed as its archive, for a Bazel hub. + if super::gem::bazel::is_archive(entry) { + return super::gem::bazel::verify(&artifact, record).await; + } let path_str = artifact.to_string_lossy(); if path_str.ends_with(".jar") { let files = record.files.clone(); @@ -800,7 +804,7 @@ pub(crate) const MAX_HEALTH_HASH_BYTES: u64 = 512 * 1024 * 1024; /// audit with a million planted files. const MAX_INVENTORY_ENTRIES: usize = 10_000; -/// Is this artifact path a single committed FILE (tarball/wheel/nupkg/jar) +/// Is this artifact path a single committed FILE (tarball/wheel/nupkg/jar/gem) /// — whose whole-file drift check is the ledger `sha256` — as opposed to a /// dir-shaped copy whose counterpart is the `fileInventory`? One suffix /// rule shared by the health check, repair's fingerprint fill, and the @@ -813,6 +817,7 @@ pub fn artifact_is_file_shaped(path: &str) -> bool { || norm.ends_with(".zip") || norm.ends_with(".nupkg") || norm.ends_with(".jar") + || super::gem::bazel::archive_path(&norm) } /// Full-file inventory of a dir-shaped artifact: every regular file under diff --git a/crates/socket-patch-core/src/vex/discover/gem.rs b/crates/socket-patch-core/src/vex/discover/gem.rs index 5d6b838da..2f68ef949 100644 --- a/crates/socket-patch-core/src/vex/discover/gem.rs +++ b/crates/socket-patch-core/src/vex/discover/gem.rs @@ -188,13 +188,29 @@ //! `CHECKSUMS` entry for them), so vendored refs never set //! `locked_integrity` — the committed artifact is hashed instead. //! +//! ## Vendored for a Bazel hub (`vendor::gem::bazel`) +//! +//! ```text +//! GEM +//! remote: file:.socket/vendor/gem// +//! specs: +//! () +//! ``` +//! +//! A `GEM` section whose one remote is the directory of a patch under +//! `.socket/vendor/gem`, spelled as that relative `file:` URL, is a +//! vendored reference of the ruby-platform gem under it to the archive +//! committed at `/gems/-.gem`, which is +//! where rules_ruby asks the source for it. The manifest has to give the +//! gem that source, as for a hosted one, and `CHECKSUMS` pins the archive. +//! //! `GIT` / `PLUGIN SOURCE` sections are never Socket wiring and are ignored. use std::collections::{BTreeSet, HashMap}; use super::{ - names_vendor_dir, simple_purl, vendor_ref, vendored_leaf_purl, DiscoverCtx, Discovery, - PatchedRef, DIAG_LOCKFILE_UNPARSEABLE, DIAG_REF_INVALID, DIAG_REF_UNATTRIBUTABLE, + names_vendor_dir, simple_purl, vendor_ref, vendor_uuid_dir, vendored_leaf_purl, DiscoverCtx, + Discovery, PatchedRef, DIAG_LOCKFILE_UNPARSEABLE, DIAG_REF_INVALID, DIAG_REF_UNATTRIBUTABLE, }; use crate::crawlers::ruby_crawler::bundler_loaded_lock_in; use crate::formats::gem::{ @@ -255,7 +271,10 @@ async fn extract_file(ctx: &DiscoverCtx<'_>, file: &str, confirm: bool, out: &mu // One with a section that reads as Socket wiring. let wired = readable && lock.sections.iter().any(|sec| match sec.header { - "GEM" => sec.remotes.iter().any(|r| ctx.hosted_uuid(r).is_some()), + "GEM" => { + let wires = |r: &&str| ctx.hosted_uuid(r).is_some() || names_vendor_dir(r); + sec.remotes.iter().any(wires) + } "PATH" => sec.remotes.iter().any(|r| names_vendor_dir(r)), _ => false, }); @@ -386,7 +405,9 @@ impl ManifestSources { return Err(format!("there is no readable {rel} beside it")); }; let want = match wiring { - Wiring::Hosted { remote, .. } => format!("`source: \"{remote}\"`"), + Wiring::Hosted { remote, .. } | Wiring::Archive { remote, .. } => { + format!("`source: \"{remote}\"`") + } Wiring::Vendored(vref) => format!("`path: \"{}\"`", vref.artifact_rel), }; let mut declared = false; @@ -394,7 +415,8 @@ impl ManifestSources { declared = true; let given = Self::given(text, decl); let ours = match (&given, wiring) { - (Given::Source(url), Wiring::Hosted { remote, .. }) => same_remote(url, remote), + (Given::Source(url), Wiring::Hosted { remote, .. }) + | (Given::Source(url), Wiring::Archive { remote, .. }) => same_remote(url, remote), (Given::Path(dir), Wiring::Vendored(vref)) => { vendor_ref(dir).is_some_and(|v| v.artifact_rel == vref.artifact_rel) } @@ -760,12 +782,19 @@ enum Wiring<'t> { only: Option>, }, Vendored(super::VendorRef), + /// The directory of a patch as a `GEM` section's one remote: the gem + /// is committed there as its archive (module docs, "Vendored for a + /// Bazel hub"). + Archive { + remote: &'t str, + uuid: String, + }, } impl Wiring<'_> { fn uuid(&self) -> &str { match self { - Wiring::Hosted { uuid, .. } => uuid, + Wiring::Hosted { uuid, .. } | Wiring::Archive { uuid, .. } => uuid, Wiring::Vendored(vref) => &vref.uuid, } } @@ -783,6 +812,13 @@ fn hosted_wirings<'t>( blocks: &[(String, String)], out: &mut Discovery, ) -> Vec> { + if let [remote] = sec.remotes.as_slice() { + let uuid = vendor_uuid_dir(remote).filter(|(eco, _)| eco == "gem"); + let uuid = uuid.filter(|(_, uuid)| *remote == format!("file:.socket/vendor/gem/{uuid}/")); + if let Some((_, uuid)) = uuid { + return vec![Wiring::Archive { remote, uuid }]; + } + } for remote in sec.remotes.iter().filter(|r| names_vendor_dir(r)) { out.diag( DIAG_REF_INVALID, @@ -1007,6 +1043,21 @@ fn spec_ref( out.shadow(pin); } } + Wiring::Archive { remote, .. } => { + let archive = format!("{remote}gems/{}-{}.gem", spec.name, spec.version); + let Some(vref) = vendor_ref(&archive).filter(|_| spec.platform.is_none()) else { + out.diag( + DIAG_REF_INVALID, + file, + format!("{at}: {purl} is locked from {remote:?}, which holds no such gem"), + ); + return; + }; + if manifest_confirms(file, &at, coords, wiring, manifest, out) { + let pin = lock.integrity(spec.name, spec.version); + out.push(PatchedRef::vendored(purl, &vref, file, pin)); + } + } Wiring::Vendored(vref) => { let leaf = format!("{}-{}", spec.name, spec.version); if vref.leaf != leaf @@ -1048,7 +1099,7 @@ fn manifest_confirms( // source-pinned, so the lock has to follow the manifest first. let rewire = match wiring { Wiring::Hosted { .. } => "socket-patch scan", - Wiring::Vendored(_) => "socket-patch vendor", + Wiring::Vendored(_) | Wiring::Archive { .. } => "socket-patch vendor", }; let rel = manifest.rel; out.diag( @@ -1376,6 +1427,78 @@ mod tests { assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); } + /// `vendor::gem::bazel`'s pair for a Bazel hub: a `GEM` section whose one + /// remote is the patch's directory as a relative `file:` URL is a + /// vendored reference to the gem committed under it, pinned by + /// `CHECKSUMS`, where the manifest gives the gem that source. Any other + /// spelling of such a remote is none, nor is a platform entry there. + #[tokio::test] + async fn a_gem_section_of_the_patch_s_directory_is_a_vendored_archive() { + let source = format!("file:.socket/vendor/gem/{UUID_A}/"); + let lock = |remote: &str, spec: &str| { + format!( + "GEM\n remote: {remote}\n specs:\n {spec}\n\n\ + GEM\n remote: https://rubygems.org/\n specs:\n puma (6.4.2)\n\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n puma\n rack (~> 3.2)!\n\n\ + CHECKSUMS\n rack (3.2.6) sha256={SHA_A}\n\nBUNDLED WITH\n 2.6.9\n" + ) + }; + let declared = |source: &str| { + manifest(&[ + "gem \"puma\"".to_string(), + format!("gem \"rack\", \"~> 3.2\", source: \"{source}\""), + ]) + }; + let p = Project::new(); + p.write("Gemfile", declared(&source)); + p.write("Gemfile.lock", lock(&source, "rack (3.2.6)")); + let out = run(&p).await; + assert_refs( + &out, + &[("pkg:gem/rack@3.2.6", UUID_A, WiringMode::Vendored)], + ); + let r = only(&out); + let archive = vendored_rel(UUID_A, "gems/rack-3.2.6.gem"); + assert_eq!(r.artifact_rel.as_deref(), Some(archive.as_str())); + let pinned = crate::vendor::lock_inventory::LockIntegrity::Sha256Hex(SHA_A.into()); + assert_eq!(r.locked_integrity, Some(pinned)); + assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); + + // A manifest that does not give the gem that source, a platform + // entry, and the directory spelled any other way. + let other = format!("file:.socket/vendor/gem/{UUID_B}/"); + for (gemfile, lock, code) in [ + ( + declared(&other), + lock(&source, "rack (3.2.6)"), + DIAG_REF_UNATTRIBUTABLE, + ), + ( + declared(&source), + lock(&source, "rack (3.2.6-java)"), + DIAG_REF_INVALID, + ), + ( + declared(&source), + lock(&source.replace("file:", "file:./"), "rack (3.2.6)"), + DIAG_REF_INVALID, + ), + ( + declared(&source), + lock(source.trim_end_matches('/'), "rack (3.2.6)"), + DIAG_REF_INVALID, + ), + ] { + let p = Project::new(); + p.write("Gemfile", gemfile); + p.write("Gemfile.lock", &lock); + let out = run(&p).await; + assert!(out.refs.is_empty(), "{lock}: {:#?}", out.refs); + let codes: Vec<&str> = out.diagnostics.iter().map(|d| d.code).collect(); + assert_eq!(codes, [code], "{lock}: {:?}", out.diagnostics); + } + } + /// bundler 2.7 with `lockfile_checksums`: the path gem keeps a BARE /// CHECKSUMS entry; the transitive-gem shape leaves an empty GEM specs /// stanza behind. `./` and a trailing `/` on the remote are tolerated. diff --git a/docs/ecosystems.md b/docs/ecosystems.md index bcb8db4b3..f86c8adc5 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1871,7 +1871,7 @@ workspace and that Bazel does not build keeps the matrix at the top. | npm: aspect_rules_js `npm.npm_translate_lock` over a pnpm lock | Supported | Supported | Not supported | Supported | | PyPI: rules_python `pip.parse` over a requirements file | Supported | Not supported | Not supported | Supported | | Go: gazelle `go_deps.from_file` over `go.mod` | Supported | Supported | Not supported | Supported with a hosted or vendored patch | -| RubyGems: rules_ruby `ruby.bundle_fetch` over `Gemfile.lock` | Supported with no `gem_checksums` on the call | Not supported | Not supported | Supported | +| RubyGems: rules_ruby `ruby.bundle_fetch` over `Gemfile.lock` | Supported with no `gem_checksums` on the call | Supported with the Bazel release named in `.bazelversion` | Not supported | Supported | | Cargo: rules_rust `crate.from_cargo` over `Cargo.lock` | Supported with `cargo_config` on the hub | Supported | Not supported | Supported with a hosted or vendored patch | | NuGet: rules_csharp `nuget.from_lock` over `packages.lock.json` | Supported with `nuget_config` on the tag | Not supported | Not supported | Supported with no restored copy on the machine | | Composer: a rule of your own that runs `composer install` from `composer.lock` | Supported | Not supported | Not supported | Supported with a hosted patch | @@ -1891,15 +1891,19 @@ exits 0 and leaves a build that fails (the known problems below). What a cell sa - **Not supported**: socket-patch promises nothing about what a Bazel build holds after the mode ran, so do not use it for a package that Bazel builds. In most of these cells the patch does not reach the build, or the build breaks (see the known problems below). - Vendored mode for PyPI, RubyGems and Composer declines instead: the command exits 1 and - writes nothing. For PyPI and RubyGems that is where the call of the row reads a file the + Vendored mode for PyPI and Composer declines instead: the command exits 1 and + writes nothing. For PyPI that is where the call of the row reads a file the run would rewrite ([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)), for Composer in every Bazel workspace ([Bazel workspaces: Composer](#bazel-workspaces-composer)). + Vendored mode for RubyGems declines the same way wherever the condition of its cell, or + another one of + [Bazel workspaces: RubyGems vendored mode](#bazel-workspaces-rubygems-vendored-mode), does + not hold. - **Supported**, for VEX: `socket-patch vex` and `--vex` say `not_affected` of a package the Bazel build takes patched, and `affected` of one whose patch Bazel does not build. - [Bazel workspaces: VEX](#bazel-workspaces-vex) has the cases and the limits; a vendored gem - is one of the limits. + [Bazel workspaces: VEX](#bazel-workspaces-vex) has the cases and the limits; a gem vendored + with `--allow-vendored-in-bazel` is one of the limits. - **Supported with a condition**, for VEX: under the condition the cell names, the document says `not_affected` of a package the Bazel build takes patched, and a test holds it to that (for Maven a test without Bazel). It does not say `affected` of a package whose patch @@ -1934,7 +1938,11 @@ What the table was tested with: - **RubyGems**: rules_ruby 1.0.0-rc2, `ruby.bundle_fetch` with `gemfile` and `gemfile_lock` and no `gem_checksums`, and a `Gemfile.lock` that has a `CHECKSUMS` section. That section is what holds the patched gem to its sha256, in Bundler's step of the build: with a lock - that has none the build takes whatever the patch registry serves. + that has none the build takes whatever the patch registry serves. Vendored mode: the same + call and lock, with the project at the Bazel root and the Bazel release in `.bazelversion`; + the files it writes were built with Bundler 2.6.9 in the lock as well, written by hand; + [Bazel workspaces: RubyGems vendored mode](#bazel-workspaces-rubygems-vendored-mode) has + every condition. - **Cargo**: rules_rust 0.75.0 (Bazel 9 and 8) and 0.56.0 (Bazel 7), `crate.from_cargo` with `cargo_lockfile = "//:Cargo.lock"`, `manifests = ["//:Cargo.toml"]` and `cargo_config = "//:.cargo/config.toml"`, and no cargo-bazel lock (`lockfile`). @@ -1989,6 +1997,12 @@ Known problems. In each of these a command exits 0 today and the next Bazel buil the patched gem, which a later `rollback` does not put back. Where the lock has a `CHECKSUMS` section, deleting the entry works too: Bundler then holds the gem to that section. +- **A vendored gem that `gem_checksums` pins, after an undo.** Vendored mode declines such a + gem until the entry holds the sha256 of the patched gem, which you write. No undo puts the + old value back: after `vendor --revert`, `rollback` or `remove` the lock names the upstream + gem again and the build fails on the entry (`Checksum was ... but wanted ...`) until it + holds the upstream sha256 again or is deleted. The undo says so in a warning + (`vendor_gem_bazel_checksum_left`). - **npm on a hub with `update_pnpm_lock = True`.** Hosted mode with a pnpm of 11 or later, when `pnpm-workspace.yaml` is not in the hub's `data`: the pnpm that Bazel runs rejects the lock (`ERR_PNPM_TARBALL_URL_MISMATCH`). List `//:package.json` and @@ -2011,10 +2025,14 @@ In these a command exits 0 and the Bazel build passes on the unpatched package: - **Hosted PyPI, when `pip.parse` takes the requirements of the build's platform from another file** than the one socket-patch rewrote (`requirements_by_platform`, `requirements_linux` and its siblings). +- **RubyGems, where Bazel does not fetch the hub again**: a hub pinned in a vendor directory + (`VENDOR.bazel`) that was made before the patch, and a build with `--nofetch` after an + earlier fetch, keep the gems they have, in every mode. Measured by hand on Bazel 9.3.2; + no test here runs it, and `vex` does not see it. [Bazel workspaces: VEX](#bazel-workspaces-vex) lists what the document says in such cases. -And three that concern neither: +And five that concern neither: - **Vendored Cargo under rules_rust 0.75.0**: a build writes a `BUILD.bazel` into the committed copy, and right after it `vendor --check` exits 1 (`vendor_inventory_mismatch`) @@ -2027,6 +2045,20 @@ And three that concern neither: - **Hosted NuGet prints the access token of the patch in the build's output.** rules_csharp asks the Socket source for every package of the lock, and Bazel prints a warning with that source's URL, the token in it, for each package the source does not hold. +- **Vendored RubyGems and Bundler outside Bazel.** The lock names the committed gem by a + relative `file:` URL, which Bundler by itself does not install from: `bundle install` on a + machine that has not installed the gem fails, and so does every `bundle lock --update`, + until `vendor --revert`. On a machine that installed the gem before the patch, Bundler + keeps that installed copy: `bundle install` passes there and the program runs the + unpatched gem, with no error. The run says both in a warning. Hosted mode serves both + builds. +- **Vendored RubyGems in an output base that fetched the gems before.** Bazel does not watch + the committed gem. When the gem alone changes afterwards (another commit with the same + `Gemfile.lock`, a damaged file), such an output base keeps building what it fetched, never + the changed bytes, until it fetches the hub again: after a change of `Gemfile.lock`, or + after `bazel clean --expunge`. The same holds the other way: an output base that fetched a + damaged gem keeps failing after `repair` put the gem right, until it fetches the hub + again. ## Bazel workspaces: Maven @@ -2882,7 +2914,9 @@ and neither ruleset builds from such a file: Both were measured on Bazel 9.3.2, 8.8.2 and 7.7.2, after a `scan --mode vendored` that exited 0 and reported the package vendored. So vendored mode now declines such a package, where the -files of the workspace show that a hub reads the file it would rewrite. +files of the workspace show that a hub reads the file it would rewrite. For a gem it writes +another form there, which rules_ruby builds, and declines only where that form is not known +to build: [Bazel workspaces: RubyGems vendored mode](#bazel-workspaces-rubygems-vendored-mode). **What is read.** The project is in a Bazel workspace by the lookup of [Bazel workspaces: `.bazelignore`](#bazel-workspaces-bazelignore). There socket-patch reads @@ -2972,7 +3006,9 @@ file that your Bazel no longer reads (Bazel 9 never reads it, Bazel 8 only with `--enable_workspace`), or for a `ruby.bundle_fetch` to which you add every file of the vendored gem as `srcs`, which rules_ruby copies beside the Gemfile (no test here builds that). socket-patch checks none of these. It is the switch of -[Bazel workspaces: Composer](#bazel-workspaces-composer). +[Bazel workspaces: Composer](#bazel-workspaces-composer). With it a gem is vendored by its +path, as in every other project, also where the form of the next section would be written +without it. `vendor --revert` is never declined. Neither is a package that is already vendored: where the file that the call names already names the copy of the same patch @@ -3024,6 +3060,125 @@ Limits: [`ruby.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs) run the refusal, the switch and hosted mode on a real Bazel. +## Bazel workspaces: RubyGems vendored mode + +For a gem whose `Gemfile` and lock a `ruby.bundle_fetch` call reads, vendored mode commits +the patched gem as the archive the patch service serves, and names it in the two files as +hosted mode names a patch registry, with a relative `file:` URL in the registry's place: + +``` +gem "rack", "~> 2.2", source: "file:.socket/vendor/gem//" # Gemfile + +GEM # Gemfile.lock + remote: file:.socket/vendor/gem// + specs: + rack (2.2.3) + +DEPENDENCIES + rack (~> 2.2)! + +CHECKSUMS + rack (2.2.3) sha256= + +.socket/vendor/gem//gems/rack-2.2.3.gem # the patched gem +``` + +rules_ruby asks Bazel for `gems/-.gem`. Bazel's server runs in the +root of the workspace and opens the relative URL from there, which Bazel documents nowhere, +and Bundler, in the `bundle install` step of the build, holds the file to the lock's +`CHECKSUMS` line. No file of Bazel's is written, and `MODULE.bazel.lock` stays as it is. The +directory of the patch also holds the marker of the patch and a `.gitignore` (`!*`) and +`.gitattributes` of its own: stock ignore templates name `*.gem`. + +Built on Bazel 9.3.2, 8.8.2 and 7.7.2 with rules_ruby 1.0.0-rc2, and with Bundler 4.0.15 +and 2.6.9 in the lock, which is the Bundler the hub installs and runs: the build is the +patched one on a machine that reaches no patch host, and one changed byte of the committed +gem fails the build of a machine that fetches the hub anew (`Bundler found mismatched +checksums`). By hand, and by no test here: a gem that the `Gemfile` does not declare builds +patched (9.3.2), and a build without the committed gem fails. + +**Where it is written.** Only for a gem whose `Gemfile` or `Gemfile.lock` a call of the hub +names, read as +[Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) +says, and only where each of these holds. All are read from the files of the checkout; no +Bazel is run. Where one does not hold the gem is declined with `vendor_gem_bazel_hub`, +nothing is written, and the message names it: + +- **The checkout names a Bazel release that opens such a URL.** `.bazelversion`, or + `USE_BAZEL_VERSION` in `.bazeliskrc`, names a release of Bazel 7, 8 or 9 other than 9.1.0. + Bazel's own history says that the downloader of 9.1.0 fails on such a URL and that 9.1.1 + and 9.2.0 fixed it (read, not run). A checkout that names no release, or one that is not + three numbers (`latest`, `8.x`), is declined: 9.1.0 may build it, or a release to come. + What the environment of a machine names (`USE_BAZEL_VERSION` in a shell) is not seen. +- **The project is the root of the Bazel workspace.** Bazel opens the URL from the root, and + the committed gem lies under the project. +- **The workspace is read with certainty**: its module files are, no `WORKSPACE` file + defines a repository, every `ruby.bundle_fetch` call writes out the files it reads, and a + call that reads the `Gemfile` or the lock of the project reads both. +- **Something holds the gem to its bytes, in the hub of every call that reads the two + files**: the lock has a `CHECKSUMS` section, or the `gem_checksums` of each such call + have an entry for the gem. With neither, any bytes at that path would build in that hub. + `bundle lock --add-checksums` writes the section (Bundler 2.6 or later). `gem_checksums` + have to be written out as a dict of strings. +- **Every `gem_checksums` entry for the gem holds it to the patched gem.** rules_ruby hands + that sha256 to Bazel, which fails the download of any other bytes. An entry for the + upstream gem, in any call that reads the two files, declines the gem once the patched + one is downloaded, and the message names the call, the entry and the sha256 to write + there. socket-patch does not edit the call: write the value, and run the command again. + A dry run downloads no gem, so it cannot see this condition and lists the gem as one the + run would vendor. No undo puts the old value back: after `vendor --revert`, `rollback` or + `remove` the build fails on the entry (`Checksum was ... but wanted ...`) until it holds + the upstream sha256 again or is deleted, and the undo says so in a warning + (`vendor_gem_bazel_checksum_left`). +- **The lock names a Bundler that a hub was built with** (`BUNDLED WITH`): 2.6 or later of + the 2 line, or one of the 4 line. rules_ruby installs the Bundler of the lock in the hub + and runs it there. Built with 2.6.9 and 4.0.15, which both hold the gem to the lock's + `CHECKSUMS` line; an older one, and a lock that names none, is declined. +- **The lock holds the gem as its ruby-platform entry** and not as platform gems. + +Before any of these, the gem meets what vendored mode refuses for every gem +([Ruby gems: gems vendored mode refuses](#ruby-gems-gems-vendored-mode-refuses)): a native +extension, a declaration that cannot be edited and the rest answer as they do outside Bazel. + +**What it costs.** The run says both in a warning (`vendor_gem_bazel_file_source`): + +- **Bundler by itself does not install from that source.** `bundle install` on a machine + that has not installed the gem fails, and so does every `bundle lock --update` (measured + with Bundler 4.0.15). On a machine that installed the gem before the patch, Bundler keeps + that installed copy: `bundle install` passes there and the program runs the unpatched + gem, with no error. The checkout then builds its gems through Bazel only. Hosted mode + serves both builds. A run that vendored nothing but such gems names the Bazel build as + its next step, and no reinstall. +- **Bazel does not watch the committed gem.** An output base that fetched the hub before + keeps building what it fetched when the gem alone changes afterwards, never the changed + bytes. A change of `Gemfile.lock` fetches the hub again, and so does a new output base. + An output base that fetched a damaged gem likewise keeps failing after `repair`, until + it fetches the hub again (`bazel clean --expunge`). + +**The other commands.** A later run passes and writes nothing. `vendor --check` holds the +committed gem to the patch, by its patched files, and to the sha256 of the ledger, and +`repair` downloads it again. `vendor --revert`, `rollback` and `remove` take the source off +the `Gemfile`, put the lock's entry back into its section where Bundler sorts it, with its +`DEPENDENCIES` entry and its `CHECKSUMS` line as they were, and delete the directory of the +patch: byte for byte for a lock whose entries are in Bundler's own order. A pair whose +`source:` or `GEM` section is no longer what the run wrote is left alone with the gem +(`vendor_lock_entry_drifted`); the gem's `CHECKSUMS` line is put back as it was whatever +it holds by then. A newer patch of the gem takes the source over in place, and a vendored +scan takes over a hosted pin of the gem. `list` and `vex` show the gem as vendored; `vex` +says `not_affected` of it, and the flow below holds that document to the patched build. +`vex` holds the committed gem to its patched files; only `vendor --check` holds it to its +bytes as well, which a fresh build does too. + +With `--allow-vendored-in-bazel` vendored mode writes what it writes in every other project, +the unpacked copy named by its path, which this hub does not build. + +Not covered: `rb_bundle_fetch` in a `WORKSPACE` file, a project below the Bazel root, a gem +locked as platform gems and a lock of a Bundler older than 2.6, which are declined; Windows, +releases of rules_ruby other than 1.0.0-rc2, and a Bundler inside the hub other than 4.0.15 +and 2.6.9, which were not run. +[`ruby.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs) builds the form on a +real Bazel, written by hand and written by the command. + ## Ruby gems: hosted mode `scan --mode hosted` makes Bundler install a patched gem from that patch's own gem source on @@ -3470,12 +3625,14 @@ is patched: the file that points at the copy. rules_python 2.5.0-rc4 takes the path of the line for the name of a project, and the build of everything the hub serves fails (same three releases). A vendored npm tarball is built by rules_js and keeps its statement. So does a - vendored gem, for another reason: rules_ruby builds one only when the call lists every + vendored gem. One committed as its archive for the hub + ([Bazel workspaces: RubyGems vendored mode](#bazel-workspaces-rubygems-vendored-mode)) is + built by rules_ruby. One vendored by its path is built only when the call lists every file of the copy among its `srcs`, which is not read, so nothing is said of it. - Vendored mode declines both by default where the hub reads the file - ([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)), - so this is the state of a project vendored with `--allow-vendored-in-bazel` or by an - earlier release. + Vendored mode declines a PyPI package by default where the hub reads the file + ([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)) + and writes the path of a gem only with `--allow-vendored-in-bazel`, so these are the + states of a project vendored with that switch or by an earlier release. Each advisory of such a patch gets a statement of the package's own with the status `affected`. It names that package alone under the product, and its `action_statement` says @@ -3573,7 +3730,8 @@ The document and the build are tested to agree on real Bazel 9.3.2, 8.8.2 and aspect_rules_js's `npm.npm_translate_lock(pnpm_lock = "//:pnpm-lock.yaml")` (hosted and vendored), PyPI through rules_python's `pip.parse(requirements_lock = "//:requirements.txt")` (hosted), and RubyGems through rules_ruby's -`ruby.bundle_fetch(gemfile_lock = "//:Gemfile.lock")` without `gem_checksums` (hosted). There +`ruby.bundle_fetch(gemfile_lock = "//:Gemfile.lock")` without `gem_checksums` (hosted, and +vendored as the gem's committed archive). There the build prints the patched package, and the document of the run (`--vex`), of `vex` and of `vex --no-verify` is one `not_affected` statement that names the package and the patch; the first two are the same in a checkout with the same files that Bazel has not built in, and @@ -3609,12 +3767,13 @@ the build is broken): of its own, a file that is not given as a plain string label. And where the line that points at the copy is in a requirements file that the file the call names brings in with `-r`. Measured for PyPI, where the build fails. -- **Vendored mode for RubyGems** beside `ruby.bundle_fetch`. rules_ruby 1.0.0-rc2 runs +- **A gem vendored by its path** beside `ruby.bundle_fetch`. rules_ruby 1.0.0-rc2 runs `bundle install` in a repository that holds the Gemfile, its lock and the files the call lists as `srcs`, so the path of the copy does not exist there unless every file of the copy is listed. Measured on the three releases: the build fails, and the statement still says - `not_affected`. Vendored mode declines such a gem by default, so this is the state of a - project vendored with `--allow-vendored-in-bazel` or by an earlier release. + `not_affected`. Vendored mode writes that form beside such a hub only with + `--allow-vendored-in-bazel`, so this is the state of a project vendored with the switch or + by an earlier release. - **A vendored package whose own files the hub does not read**, while the lock the hub does read still lists the registry's package: a uv or Poetry project vendored through `pyproject.toml` and its lock while `pip.parse` reads a requirements file exported before; diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 142c5444e..792119459 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": 2585 }, "lock-readers": { "paths": [ From dd2651ed82793543927c4806e9076cb3540da0e2 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 23 Nov 2026 21:22:40 -0500 Subject: [PATCH 07/22] Close six gaps of a gem vendored for a Bazel hub that a review found - The gate did not look at the rc files of the checkout. A `.bazelrc`, or a file it imports, that names `--experimental_remote_downloader` (a remote downloader is handed the URL in the place of Bazel's own), `--repository_disable_download` or `--vendor_dir` (a hub pinned in a vendor directory keeps the gems it has) now declines the gem, and so does an rc file that cannot be read. None of the three was built. - A directory that git ignores was refused only after the download and after a dry run had returned, so a dry run showed a gem the run then refused. The check now comes first, dry run or not. - An undo treated a pair of which one file had been put back by hand (a `git checkout` of the lock, a merge that took the other side) as drifted for good: every `vendor --revert`, `rollback` and `remove` warned and left the other file and the gem. A file that names the source nowhere has been put back already, and the other now goes back by itself. A file that still names it and no longer holds what the run wrote leaves both alone, as before. - A refusal of the planner was passed on with the way on it names for a hosted run. The decline now says whose way on that is. - The closing `Next steps:` named the Bazel build only when every package of the run was such a gem, and compared a copy of the advisory's code. A run that vendored other packages too now adds a line for the Bazel build, and the code is the core's constant. - The two wiring kinds of this form were not among the kinds whose file the ledger checks. The real-Bazel flow builds the unpacked copy under `--allow-vendored-in-bazel` again: the failing `bundle install` there is what the decline is for, and the rewrite of the flow had dropped it. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../socket-patch-cli/src/commands/vendor.rs | 13 +- .../tests/e2e_bazel_build/ruby.rs | 42 ++++++- crates/socket-patch-core/src/vendor/gem.rs | 4 + .../socket-patch-core/src/vendor/gem/bazel.rs | 116 ++++++++++++++---- crates/socket-patch-core/src/vendor/state.rs | 10 +- docs/ecosystems.md | 15 ++- 7 files changed, 168 insertions(+), 34 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 817adae78..936ea9627 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2493,7 +2493,7 @@ command's integration tests check its output. | `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. For a gem the refusal is narrower: where a `ruby.bundle_fetch` call names the project's `Gemfile` or lock and the reading is certain, the gem is vendored as its committed archive (`vendor_gem_bazel_file_source`) and is refused only where that form is not known to build, which the detail names in the place of the path sentence: the checkout names no Bazel release as three numbers in `.bazelversion` or `.bazeliskrc` (none at all, or `latest` or a release candidate), or names 9.1.0 or one outside 7, 8 and 9; the project is not the root of the Bazel workspace; a `WORKSPACE` file defines repositories; a call of the hub does not write out the files it reads, or reads one of the two files alone; its `gem_checksums` are not written out; the lock has no `CHECKSUMS` section and a call that reads the two files has no `gem_checksums` entry for the gem (the detail names that call); the lock's `BUNDLED WITH` names no Bundler, or one that is neither 2.6 or later of the 2 line nor of the 4 line (the hub runs the lock's Bundler, and was built with 2.6.9 and 4.0.15); or the lock holds the gem as platform gems. One more condition is known only once the patched gem is downloaded, so it is refused by the backend, after the download and before any write, with the same code, and a dry run of `scan` or `get`, which downloads nothing, does not show it: a `gem_checksums` entry of any call that reads the two files that holds the gem to another sha256 than the patched gem's (the detail names the call, the entry and both sums, and says that no undo puts the old value back; no file is edited). See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" and "Bazel workspaces: RubyGems vendored mode" | -| `vendor_gem_bazel_file_source` | `skipped` (advisory; human: `Warning: …`) | vendor / scan / get `--mode vendored` (gem; additive): the gem was committed for a rules_ruby hub of the project's Bazel workspace as its archive, `.socket/vendor/gem//gems/-.gem`, which `Gemfile` and `Gemfile.lock` name by the relative URL `file:.socket/vendor/gem//`. The detail says what that form costs: Bundler by itself does not install from such a source (`bundle install` on a machine without the gem and `bundle lock --update` fail; on a machine that installed the gem before the patch, `bundle install` passes and keeps that unpatched copy), so the checkout builds its gems through Bazel only, and hosted mode serves both; and Bazel does not watch the gem, so an output base that fetched the hub before keeps what it fetched. A human run that vendored only such gems words the second of its `Next steps:` as ``Build with Bazel, which installs the committed gems, then run `socket-patch vex` to verify the installed patches.`` in the place of the reinstall. One event per gem vendored this way by the run; none on an in-sync run, and none with `--allow-vendored-in-bazel`. The ledger entry's artifact is the archive (`artifact.path` is `.socket/vendor/gem//gems/-.gem`, with its `sha256` and `size`), and its wiring records are `gemfile_file_source` and `gemfile_lock_file_source`. See docs/ecosystems.md "Bazel workspaces: RubyGems vendored mode" | +| `vendor_gem_bazel_file_source` | `skipped` (advisory; human: `Warning: …`) | vendor / scan / get `--mode vendored` (gem; additive): the gem was committed for a rules_ruby hub of the project's Bazel workspace as its archive, `.socket/vendor/gem//gems/-.gem`, which `Gemfile` and `Gemfile.lock` name by the relative URL `file:.socket/vendor/gem//`. The detail says what that form costs: Bundler by itself does not install from such a source (`bundle install` on a machine without the gem and `bundle lock --update` fail; on a machine that installed the gem before the patch, `bundle install` passes and keeps that unpatched copy), so the checkout builds its gems through Bazel only, and hosted mode serves both; and Bazel does not watch the gem, so an output base that fetched the hub before keeps what it fetched. A human run that vendored only such gems words the second of its `Next steps:` as ``Build with Bazel, which installs the committed gems, then run `socket-patch vex` to verify the installed patches.`` in the place of the reinstall; one that vendored other packages too keeps its reinstall step and adds the line `Build with Bazel as well: it alone installs the gems committed for its hub.` One event per gem vendored this way by the run; none on an in-sync run, and none with `--allow-vendored-in-bazel`. The ledger entry's artifact is the archive (`artifact.path` is `.socket/vendor/gem//gems/-.gem`, with its `sha256` and `size`), and its wiring records are `gemfile_file_source` and `gemfile_lock_file_source`. See docs/ecosystems.md "Bazel workspaces: RubyGems vendored mode" | | `vendor_gem_bazel_checksum_left` | warning of the undo (human: `Warning: …`) | `vendor --revert` / `rollback` / `remove` (gem; additive): the undo put `Gemfile` and `Gemfile.lock` back for a gem that was committed for a rules_ruby hub (`vendor_gem_bazel_file_source`), and the `gem_checksums` of a `ruby.bundle_fetch` call of the workspace still hold the gem to the sha256 of the patched gem, which the vendoring run asked the user to write there. socket-patch does not edit the call, so the Bazel build fails on that entry (`Checksum was … but wanted …`) until it holds the upstream gem's sha256 again or is removed. The detail names the call with its file and line, the entry and the sha256. The undo itself is complete and its exit code is unchanged; also reported by its dry run. See docs/ecosystems.md "Bazel workspaces: RubyGems vendored mode" | | `vendor_lockfile_missing` / `vendor_lockfile_version_unsupported` (bun preflight placement) | `failed` | scan / get `--mode vendored` (bun): the pre-download preflight found `bun.lock` unreadable / at a `lockfileVersion` other than 0 to 3 (a newer version: update socket-patch; no integer: re-lock with Bun ≥ 1.2 — the same text as hosted's `redirect_bun_lock_unsupported`) or outside bun's single-line `packages` grammar. Same placements as `vendor_bun_lockb_invalid`; nothing fetched, no patch record. An unreadable `.socket/vendor/state.json` met by the same preflight is `vendor_state_unreadable` (see that row), never one of these. | | `bun_lockb_invalid` | scan `warnings[]` (run-level) | scan (every mode): the native binary inventory could not parse or read `bun.lockb`; detail names the format or filesystem error. Also printed as `Warning: …` on stderr. Exit and status remain unchanged. The warning is retained on empty and non-empty scans; valid binary locks are inventoried normally without a runtime or install. | diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index d0b3d481f..db35c5b53 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -4762,10 +4762,11 @@ fn print_vendor_closing( // A gem committed for a rules_ruby hub is installed by the Bazel // build alone: Bundler by itself fails on its source, which the // warning of the run says. - let for_bazel = - |e: &&PatchEvent| e.error_code.as_deref() == Some("vendor_gem_bazel_file_source"); + let advisory = socket_patch_core::vendor::gem::BAZEL_FILE_SOURCE; + let for_bazel = |e: &&PatchEvent| e.error_code.as_deref() == Some(advisory); let for_bazel = env.events.iter().filter(for_bazel).count(); - let reinstall = if for_bazel > 0 && for_bazel == env.summary.applied as usize { + let only_for_bazel = for_bazel > 0 && for_bazel == env.summary.applied as usize; + let reinstall = if only_for_bazel { "Build with Bazel, which installs the committed gems".to_string() } else if jvm_only { let cmds: Vec = installs.iter().map(|c| format!("`{c}`")).collect(); @@ -4781,6 +4782,12 @@ fn print_vendor_closing( format!("Run {} to update the installed tree", cmds.join(" and ")) }; let mut extra = Vec::new(); + if for_bazel > 0 && !only_for_bazel { + extra.push( + "Build with Bazel as well: it alone installs the gems committed for its hub." + .to_string(), + ); + } if wired_flavors.contains("bun") && common.cwd.join("bun.lockb").exists() { extra.push( "For binary Bun workspaces, also commit the workspace members' \ diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs index 7df86e696..cc4ffdfe5 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -830,7 +830,11 @@ fn committed_for_the_hub(cell: &Cell, scan: &Ran, served: &Served, before: &Tree /// vendored --yes` declines the gem: it exits 1, names the call of /// `MODULE.bazel` that reads the lock, the missing release, hosted mode /// and the switch, writes nothing and downloads no gem. The same two -/// Bazel commands print the unpatched marker, and change no file. +/// Bazel commands print the unpatched marker, and change no file. With +/// `--allow-vendored-in-bazel` the command writes the unpacked copy named +/// by its path, as in every other project, and the same build fails in +/// `bundle install`, where the path names nothing: the failure the +/// decline is for. `vendor --revert` puts every file and the build back. /// - (c) With the release of this Bazel in `.bazelversion`, the same /// command vendors the gem: it writes the three files of /// [`file_source_by_hand`], byte for byte, with its ledger, and says @@ -865,7 +869,6 @@ fn vendored_bundle_fetch() { // (a) The unpatched build. let before = cell.builds_unpatched(&served.unpatched); - let upstream_fetches = standin.asked(&served.upstream_route); // (b) No release is named: declined, with nothing written and nothing // of the patch fetched. The same build passes, on the upstream gem. @@ -873,6 +876,34 @@ fn vendored_bundle_fetch() { assert_eq!(standin.asked(&served.artifact_route), 0, "{test}"); cell.builds_patched(&before, &served.unpatched); + // What the decline is for: on the user's word the command writes the + // copy of every other project, named by its path, and the same build + // fails where rules_ruby runs Bundler, in a repository of Bazel's that + // does not hold that path. Bundler breaks its message at the width of + // its console, so it is compared without white space. The undo, which + // takes no switch, puts every file and the build back. + { + let scan = run(&cell, &[&VENDORED[..], &[ALLOW]].concat()); + assert_eq!(scan.code, 0, "{test}: {}", scan.dump); + let copy = format!(".socket/vendor/gem/{uuid}/{NAME}-{VERSION}"); + let lock = String::from_utf8(cell.tree()["Gemfile.lock"].clone()).expect("a text file"); + let section = format!("PATH\n remote: {copy}\n specs:\n {NAME} ({VERSION})\n\n"); + assert!(lock.starts_with(§ion), "{test}: Gemfile.lock:\n{lock}"); + let build = cell.bazel("build", &[CONSUMER]); + let 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() + ); + let undo = run(&cell, &["vendor", "--revert", "--yes"]); + cell.undone(&undo, "removed", &before, &served.unpatched); + } + // The build after the undo fetched the upstream gem once more. + let upstream_fetches = standin.asked(&served.upstream_route); + // (c) The release is named: the gem, its ledger, and the two files // that name it. The document of that run and the one of `vex` say so, // before the patched build. @@ -1163,7 +1194,7 @@ fn a_gem_is_declined_where_the_committed_gem_is_not_known_to_build() { }; let (first_unheld, second_unheld) = (unheld(15), unheld(28)); type Edit<'a> = &'a dyn Fn(&Cell); - let cases: [(Edit, &str); 9] = [ + let cases: [(Edit, &str); 10] = [ ( &|cell| cell.write(".bazelversion", "9.1.0\n"), "Bazel 9.1.0 fails on such a URL", @@ -1207,6 +1238,11 @@ fn a_gem_is_declined_where_the_committed_gem_is_not_known_to_build() { }, "a `WORKSPACE` file of the workspace defines repositories", ), + ( + &|cell| cell.write(".bazelrc", "build --repository_disable_download\n"), + ".bazelrc:1 names `--repository_disable_download`, under which Bazel may not read the \ + committed gem", + ), ]; for (edit, why) in cases { let (cell, served) = checkout(); diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 2654a88c1..3e3e2ddc7 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -140,6 +140,10 @@ use crate::formats::gem::{ pub(crate) mod bazel; +/// The code of the advisory a run gives for a gem it vendored for a Bazel +/// hub, whose build alone installs it. +pub const BAZEL_FILE_SOURCE: &str = bazel::ADVISORY; + pub(super) const GEMFILE: &str = "Gemfile"; pub(super) const GEMFILE_LOCK: &str = "Gemfile.lock"; diff --git a/crates/socket-patch-core/src/vendor/gem/bazel.rs b/crates/socket-patch-core/src/vendor/gem/bazel.rs index c08b73947..d03eb3143 100644 --- a/crates/socket-patch-core/src/vendor/gem/bazel.rs +++ b/crates/socket-patch-core/src/vendor/gem/bazel.rs @@ -58,7 +58,7 @@ use super::{ }; use crate::api::client::PlannedDownload; use crate::bazel::built::{hub_calls, lock_text, reader}; -use crate::bazel::rc::{declared_release, Release}; +use crate::bazel::rc::{declared_release, mentions, Release}; use crate::bazel::starlark::Value as Starlark; use crate::bazel::workspace::{disk, Doubt, Tag, Workspace}; use crate::bazel::BazelRoot; @@ -104,8 +104,8 @@ const ENTRY_LEFT: &str = "vendor_gem_bazel_checksum_left"; /// what `Gemfile.lock` held before it followed (`original`: the `remote` of /// the section the gem came from, its `dependency` entry and its `checksum` /// line, each as the lock spelled it, the last two only where it had one). -const GEMFILE_KIND: &str = "gemfile_file_source"; -const LOCK_KIND: &str = "gemfile_lock_file_source"; +pub(crate) const GEMFILE_KIND: &str = "gemfile_file_source"; +pub(crate) const LOCK_KIND: &str = "gemfile_lock_file_source"; /// The calls of the hub that read the `Gemfile` and the lock of a project /// for which a gem committed as its archive is known to build ([`gate`]). @@ -140,7 +140,8 @@ fn named(tag: &Tag<'_>) -> String { /// the `Gemfile` or the lock of the project reads both, with /// `gem_checksums` that are written out. /// - The checkout names a Bazel release whose downloader opens such a URL -/// ([`opens_file_urls`]). +/// ([`opens_file_urls`]), and no rc file of it takes the download from +/// that downloader ([`reads_the_checkout`]). /// - The lock names a Bundler that the hub is known to build such a source /// with ([`bundler_builds`]). pub(crate) async fn gate(root: &BazelRoot) -> Result { @@ -203,6 +204,7 @@ fn read(dir: &Path, project: &Path) -> Result { return Err("no `ruby.bundle_fetch` call is seen to read Gemfile and Gemfile.lock".into()); } opens_file_urls(declared_release(&view))?; + reads_the_checkout(mentions(&view, &KEEPS_BAZEL_OFF))?; let unread = || "Gemfile.lock cannot be read".to_string(); let lock = lock_text(dir, GEMFILE_LOCK).ok_or_else(unread)?; bundler_builds(&lock)?; @@ -231,6 +233,33 @@ fn bundler_builds(lock: &str) -> Result<(), String> { } } +/// The options of an rc file under which Bazel may not read the committed +/// gem: a remote downloader is handed the URL in the place of Bazel's own +/// (read in Bazel's source: 9.3.2 keeps a `file:` URL to itself, 7.7.2 does +/// not), a build that may not download fetches nothing, and a hub pinned in +/// a vendor directory keeps the gems it has. None was built. +const KEEPS_BAZEL_OFF: [&str; 3] = [ + "experimental_remote_downloader", + "repository_disable_download", + "vendor_dir", +]; + +/// Whether the rc files of the checkout leave the download of the gem to +/// Bazel's own downloader, by what [`mentions`] found of +/// [`KEEPS_BAZEL_OFF`] in them. An option that is named counts however it +/// is set, and so does an rc file that cannot be read. +fn reads_the_checkout(found: Result, String>) -> Result<(), String> { + match found.map(|found| found.into_iter().next()) { + Ok(None) => Ok(()), + Ok(Some((file, line, word))) => Err(format!( + "{file}:{line} names `{word}`, under which Bazel may not read the committed gem" + )), + Err(file) => Err(format!( + "the rc file {file} cannot be read, and may keep Bazel from reading the committed gem" + )), + } +} + /// What a doubt of the reader of the workspace's files says of them. fn uncertain(Doubt { file, line, why }: &Doubt) -> String { let line = match line { @@ -517,6 +546,11 @@ pub(super) async fn vendor( return Some(*outcome); } } + // Dry run or not, before anything is downloaded: a directory that git + // ignores holds no gem a clone would have. + if let Some((code, detail)) = ignored_root_refusal(project, &site.dir).await { + return Some(refused(code, detail)); + } if let Some(refusal) = service_offline_conflict(service) { return Some(refusal); } @@ -555,7 +589,8 @@ pub(super) async fn vendor( Err(warning) => { return declined(format!( "Gemfile and Gemfile.lock cannot name the committed gem as hosted mode \ - names a patch registry ({}: {})", + names a patch registry, and for the reason a hosted run gives ({}: {}); \ + the way on that reason names is the one of a hosted run", warning.code, warning.detail )) } @@ -568,9 +603,6 @@ pub(super) async fn vendor( } // ── the gem, where rules_ruby asks the source for it ───────────────── - if let Some((code, detail)) = ignored_root_refusal(project, &site.dir).await { - return Some(refused(code, detail)); - } let uuid_dir = prelude.uuid_dir.as_path(); // A gem whose pair was in place keeps what it has. let fresh = plan.is_some(); @@ -689,10 +721,10 @@ fn records(name: &str, source: &str, edits: &[FileEdit]) -> Vec { /// Revert the entry of a gem committed as its archive: the `Gemfile` loses /// the source, the lock's entry goes back to the section it came from with /// its `DEPENDENCIES` entry and its `CHECKSUMS` line, and the directory of -/// the patch is removed. The two files go back together or not at all: a -/// pair that no longer holds what [`vendor`] wrote is left alone -/// (`vendor_lock_entry_drifted`) with the gem, and one that names the -/// source nowhere has been put back already. +/// the patch is removed. A file that names the source nowhere has been put +/// back already, and the other goes back by itself; a file that names it +/// and no longer holds what [`vendor`] wrote leaves both alone +/// (`vendor_lock_entry_drifted`) with the gem. pub(super) async fn revert( entry: &VendorEntry, project: &Path, @@ -716,8 +748,17 @@ pub(super) async fn revert( let before = before.and_then(|w| w.original.as_ref()); match (&texts[0], &texts[1]) { (Some(lock), Some(gemfile)) if lock.contains(&source) || gemfile.contains(&source) => { - let lock = before.and_then(|b| unwire_lock(lock, &name, &version, &source, b)); - match (lock, unwire_gemfile(gemfile, &name, &source)) { + // A file that names the source nowhere has been put back + // already: the other one goes back by itself. + let lock = match lock.contains(&source) { + true => before.and_then(|b| unwire_lock(lock, &name, &version, &source, b)), + false => Some(lock.clone()), + }; + let gemfile = match gemfile.contains(&source) { + true => unwire_gemfile(gemfile, &name, &source), + false => Some(gemfile.clone()), + }; + match (lock, gemfile) { (Some(lock), Some(gemfile)) => { for (file, text) in [(GEMFILE_LOCK, lock), (GEMFILE, gemfile)] { if let Ok(Some(file)) = files.text(file).await { @@ -960,7 +1001,7 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//:Gemfile", gemfile_lock = "//:Ge let pinned = |sums: &str| MODULE.replace(lock_arg, &format!("{lock_arg}, {sums}")); let bundler = |version: &str| lock().replace(" 2.6.9", &format!(" {version}")); let unnamed = "names no Bazel release as three numbers"; - let cases: [(&str, String, &str); 15] = [ + let cases: [(&str, String, &str); 18] = [ (".bazelversion", String::new(), unnamed), (".bazelversion", "latest\n".into(), unnamed), (".bazelversion", "9.3.2rc1\n".into(), unnamed), @@ -1024,6 +1065,22 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//:Gemfile", gemfile_lock = "//:Ge String::new(), "Gemfile.lock names no Bundler (`BUNDLED WITH`)", ), + ( + ".bazelrc", + "build --experimental_remote_downloader=grpcs://cache.example\n".into(), + ".bazelrc:1 names `--experimental_remote_downloader=grpcs://cache.example`, under \ + which Bazel may not read the committed gem", + ), + ( + ".bazelrc", + "build \"--copt\n".into(), + "the rc file .bazelrc:1 cannot be read", + ), + ( + ".bazelrc", + "common --vendor_dir=third_party/bazel\n".into(), + ".bazelrc:1 names `--vendor_dir=third_party/bazel`", + ), ]; for (file, text, why) in cases { let (_tmp, root) = checkout(MODULE, &[(file, &text)]); @@ -1368,13 +1425,7 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//:Gemfile", gemfile_lock = "//:Ge fs::write(root.join(GEMFILE_LOCK), &drifted).unwrap(); assert!(kept(&reverted(&entry, &root).await)); assert_eq!(read(GEMFILE_LOCK), drifted); - // The Gemfile lost the source and the lock did not. fs::write(root.join(GEMFILE_LOCK), &wired).unwrap(); - fs::write(root.join(GEMFILE), GEMFILE_TEXT).unwrap(); - let outcome = reverted(&entry, &root).await; - let drifted = |w: &VendorWarning| w.code == "vendor_lock_entry_drifted"; - assert!(outcome.warnings.iter().any(drifted) && read(GEMFILE_LOCK) == wired); - fs::write(root.join(GEMFILE), &gemfile).unwrap(); // A record that names another gem's line, or more than one line. for (key, line) in [ ("checksum", format!("ast (1.0.0) sha256={}", sum('e'))), @@ -1398,6 +1449,29 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//:Gemfile", gemfile_lock = "//:Ge "{outcome:?}" ); assert!(!root.join(".socket/vendor").exists()); + // One of the two put back by hand: the other goes back by itself, + // and the gem goes. + for by_hand in [GEMFILE, GEMFILE_LOCK] { + let (_tmp, root) = checkout(MODULE, &[]); + let entry = wire(&root, "rack", "2.2.3", UUID); + let before = match by_hand { + GEMFILE => GEMFILE_TEXT.to_string(), + _ => lock(), + }; + fs::write(root.join(by_hand), before).unwrap(); + let outcome = reverted(&entry, &root).await; + assert!( + outcome.success && outcome.warnings.is_empty(), + "{by_hand}: {outcome:?}" + ); + let read = |file: &str| fs::read_to_string(root.join(file)).unwrap(); + assert_eq!( + [read(GEMFILE), read(GEMFILE_LOCK)], + [GEMFILE_TEXT.to_string(), lock()], + "{by_hand}" + ); + assert!(!root.join(".socket/vendor").exists(), "{by_hand}"); + } } /// A committed gem is held to the patch by the files in it. diff --git a/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index 5857af81d..af5c61432 100644 --- a/crates/socket-patch-core/src/vendor/state.rs +++ b/crates/socket-patch-core/src/vendor/state.rs @@ -1283,8 +1283,10 @@ async fn wiring_file_refusal(rec: &WiringRecord, project_root: &Path) -> Option< super::pypi_requirements::ledger_file_refusal(project_root, file).await } // The rest. - "gemfile_line" => one_of(&["Gemfile"]), - "gemfile_lock_spec" | "gemfile_lock_checksum" => one_of(&["Gemfile.lock"]), + "gemfile_line" | super::gem::bazel::GEMFILE_KIND => one_of(&["Gemfile"]), + "gemfile_lock_spec" | "gemfile_lock_checksum" | super::gem::bazel::LOCK_KIND => { + one_of(&["Gemfile.lock"]) + } "cargo_patch_entry" => one_of(&[ super::cargo_manifest::CARGO_TOML, super::cargo_config::CONFIG_TOML, @@ -2801,6 +2803,8 @@ mod tests { ("pypi", "requirements_line", "requirements/dev.txt"), ("gem", "gemfile_line", "Gemfile"), ("gem", "gemfile_lock_spec", "Gemfile.lock"), + ("gem", "gemfile_file_source", "Gemfile"), + ("gem", "gemfile_lock_file_source", "Gemfile.lock"), ("cargo", "cargo_patch_entry", "Cargo.toml"), ("cargo", "cargo_patch_entry", ".cargo/config.toml"), ("cargo", "cargo_lock_entry", "Cargo.lock"), @@ -2838,6 +2842,8 @@ mod tests { ("pypi", "requirements_line", ".socket/vendor/notes.txt"), ("gem", "gemfile_line", "Rakefile"), ("gem", "gemfile_lock_spec", "Gemfile"), + ("gem", "gemfile_file_source", "Gemfile.lock"), + ("gem", "gemfile_lock_file_source", "MODULE.bazel"), ("cargo", "cargo_patch_entry", "build.rs"), ("golang", "go_replace", "main.go"), ("composer", "composer_lock_package", "composer.json"), diff --git a/docs/ecosystems.md b/docs/ecosystems.md index f86c8adc5..7d2990a72 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -3110,6 +3110,12 @@ nothing is written, and the message names it: and 9.2.0 fixed it (read, not run). A checkout that names no release, or one that is not three numbers (`latest`, `8.x`), is declined: 9.1.0 may build it, or a release to come. What the environment of a machine names (`USE_BAZEL_VERSION` in a shell) is not seen. +- **No rc file of the checkout takes the download from Bazel's own downloader.** `.bazelrc` + and the files it imports name none of `--experimental_remote_downloader` (a remote + downloader is handed the URL in the place of Bazel's own), `--repository_disable_download` + and `--vendor_dir` (a hub pinned in a vendor directory keeps the gems it has), however the + option is set, and each of those files can be read. An rc file of the machine or of the + home directory, and the command line, are not seen. - **The project is the root of the Bazel workspace.** Bazel opens the URL from the root, and the committed gem lies under the project. - **The workspace is read with certainty**: its module files are, no `WORKSPACE` file @@ -3160,10 +3166,11 @@ committed gem to the patch, by its patched files, and to the sha256 of the ledge `repair` downloads it again. `vendor --revert`, `rollback` and `remove` take the source off the `Gemfile`, put the lock's entry back into its section where Bundler sorts it, with its `DEPENDENCIES` entry and its `CHECKSUMS` line as they were, and delete the directory of the -patch: byte for byte for a lock whose entries are in Bundler's own order. A pair whose -`source:` or `GEM` section is no longer what the run wrote is left alone with the gem -(`vendor_lock_entry_drifted`); the gem's `CHECKSUMS` line is put back as it was whatever -it holds by then. A newer patch of the gem takes the source over in place, and a vendored +patch: byte for byte for a lock whose entries are in Bundler's own order. A file of the two +that names the source nowhere has been put back already, by hand or by git, and the other +goes back by itself. A file that still names it and whose `source:` or `GEM` section is no +longer what the run wrote leaves both alone with the gem (`vendor_lock_entry_drifted`); the +gem's `CHECKSUMS` line is put back as it was whatever it holds by then. A newer patch of the gem takes the source over in place, and a vendored scan takes over a hosted pin of the gem. `list` and `vex` show the gem as vendored; `vex` says `not_affected` of it, and the flow below holds that document to the patched build. `vex` holds the committed gem to its patched files; only `vendor --check` holds it to its From 2e0f2d3a8cd68edfb39703008aea87ad0fd62cc6 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 20 Nov 2026 14:29:54 -0500 Subject: [PATCH 08/22] Test what vendored mode does for a NuGet package of a rules_csharp hub on real Bazel Tests only. rules_csharp's `nuget.from_lock` downloads every package of `packages.lock.json` from the package sources of `nuget.config` and holds each file to the lock's `contentHash`. The real-Bazel NuGet flows ran hosted mode in that workspace, and vendored mode in none. nuget::vendored_from_lock records what vendored mode does there today, on the machine that restored the project: - `scan --mode vendored --yes` exits 0 with status `success` and reports the package vendored. It downloads the patched package from the patch service once and keeps it at `.socket/vendor/nuget//..nupkg`, names that folder as a package source in `nuget.config` (``, with a source mapping) and re-pins the lock to the patched package. `vex` attests the package. - The next `bazel build` fails. NuGet takes a folder as a package source; the hub reads the same line as the URL of a feed. Bazel 9.3.2 crashes in the module extension (exit 37, "NullPointerException thrown during Starlark evaluation"); Bazel 8.8.2 and 7.7.2 refuse the URL ("Bad URL: .socket/vendor/nuget/"). Bazel asks no host for the package and changes no file. - `vendor --revert` puts every file back, and the build with them. The flow records a defect: a command that exits 0 leaves a build broken. It is here so that the change which removes the defect shows as a change of this test's expectations. The grant names the patched package by its URL on the patch host, and vendored mode downloads it itself, so the flow passes `--patch-server-url` with the loopback stand-in, which serves the package under the path of that URL. No build and no command reaches nuget.org or a Socket host. Run on Bazel 9.3.2, 8.8.2 and 7.7.2 on macOS arm64: the flow passes on each, in about ten seconds. The workflow's comments name the flow. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-nuget.yml | 7 +- .../tests/e2e_bazel_build/nuget.rs | 171 +++++++++++++++++- 2 files changed, 174 insertions(+), 4 deletions(-) diff --git a/.github/workflows/bazel-nuget.yml b/.github/workflows/bazel-nuget.yml index e746a4755..868f27f85 100644 --- a/.github/workflows/bazel-nuget.yml +++ b/.github/workflows/bazel-nuget.yml @@ -3,7 +3,8 @@ 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. +# `nuget_config`, and vendored mode for the same package, 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. # @@ -40,8 +41,8 @@ on: # 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. + # vendor/nuget_feed.rs is the vendored backend, which the vendored flow + # runs; every one of those files calls its version and folder helpers. # Nothing else that another ecosystem's flow owns is here, so any other # change to one ecosystem starts that ecosystem's legs only. # 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..1c5829883 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs @@ -128,9 +128,17 @@ //! tag: the last tag with sources decides which config the hub reads, and //! the first lock that names a package gives its `contentHash`. //! +//! A third flow, [`vendored_from_lock`], runs vendored mode in the +//! fixture's workspace. `scan --mode vendored --yes` downloads the patched +//! package from the patch service once, keeps it under `.socket/vendor`, +//! names that folder as a package source in `nuget.config` and re-pins the +//! lock. NuGet takes a folder as a source. The hub reads the same line as +//! the URL of a feed, so the next `bazel build` fails. `vendor --revert` +//! puts every file back, and the build with them. +//! //! # 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 +150,8 @@ //! 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). +//! - Vendored mode exits 0 and reports the package vendored, and the next +//! `bazel build` fails ([`vendored_from_lock`]). use std::io::Write as _; use std::path::{Path, PathBuf}; @@ -205,6 +215,9 @@ const PATCH_HOST: &str = "patch.socket.dev"; const FLAT_CONTAINER: &str = "api.nuget.org/v3-flatcontainer"; /// The one command of hosted mode. const SCAN: [&str; 4] = ["scan", "--mode", "hosted", "--yes"]; +/// The one command of vendored mode, before the option that names the +/// patch service ([`vendored_scan`]). +const VENDORED: [&str; 4] = ["scan", "--mode", "vendored", "--yes"]; /// The sha256 of `bytes` in lowercase hex, as `MODULE.bazel.lock` and /// Bazel's downloader spell one. @@ -970,6 +983,162 @@ fn hosted_no_config() { ); } +/// `scan --mode vendored --yes ` in `cell`, on the machine whose .NET +/// home is `home`. The grant names the patched package by its URL on the +/// patch host, and vendored mode downloads it itself: `--patch-server-url` +/// sends that one download to `standin`, which serves the package there +/// under the path of that URL (`service` of [`service_route`]). +fn vendored_scan(cell: &Cell, standin: &StandIn, home: &Path, more: &[&str]) -> Ran { + let origin = standin.origin(); + let args = [&VENDORED[..], &["--patch-server-url", &origin], more].concat(); + socket_patch(cell, standin, home, &args) +} + +/// Has `standin` serve the package of `patch` to vendored mode, and gives +/// the route: the path of the URL the grant names, without the prefix of +/// the patch host that a download of Bazel's carries on the stand-in. +fn service_route(standin: &StandIn, patch: &Patched) -> String { + let route = patch.file(&patch.package); + let service = route + .strip_prefix(&format!("/{PATCH_HOST}")) + .expect("a route of the patch host"); + standin.serve(5, service, &patch.package.nupkg); + service.to_string() +} + +/// Where vendored mode keeps what it wrote for `patch`: the folder of the +/// patch under the checkout's `.socket/vendor`. +fn vendor_dir(patch: &Patched) -> String { + format!(".socket/vendor/nuget/{}", patch.uuid) +} + +/// Vendored mode in the fixture's workspace, on the machine that restored +/// the project. The command downloads the patched package from the patch +/// service once and keeps it under `.socket/vendor`; it names that folder +/// as a package source in `nuget.config`, with a source mapping, and +/// re-pins the lock. It exits 0 and reports the package vendored, and +/// `vex` attests it. The hub reads the folder as the URL of a feed, so the +/// next `bazel build` fails. `vendor --revert` puts every file back, and +/// the build with them. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn vendored_from_lock() { + let test = "nuget::vendored_from_lock"; + let started = Instant::now(); + let Some(mut cell) = Cell::open(test, &FIXTURE) else { + return; + }; + let release = cell.release().to_string(); + + 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 (purl, unpatched) = (upstream.purl(), upstream.marker()); + let standin = registry(&[&neighbour, &upstream]); + grant(&standin, &upstream, &patch, &patch.package.nupkg); + let service = service_route(&standin, &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 the .NET home"); + for package in [&neighbour, &upstream] { + package.restore_into(home.path()); + } + + // (a) The unpatched build. + let before = cell.builds_unpatched(&unpatched); + + // (b) The one command of vendored mode: the package from the patch + // service, once, into the folder of the patch; that folder as a source + // of `nuget.config`; and the lock re-pinned. + let scan = vendored_scan(&cell, &standin, home.path(), &[]); + 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 event = |action: &str, code: &str| (purl.clone(), action.to_string(), code.to_string()); + let events = [ + event("downloaded", ""), + event("applied", ""), + event("skipped", "vendor_prebuilt_downloaded"), + // NuGet's folder holds the unpatched copy, which no build here reads. + event("skipped", "vendor_nuget_stale_global_package"), + ]; + assert_eq!(event_triples(&scan.envelope), events, "{test}: {said}"); + assert_eq!(standin.asked(&service), 1, "{test}: {said}"); + let vendored = cell.tree(); + let dir = vendor_dir(&patch); + let copy = format!("{dir}/{}.{VERSION}.nupkg", upstream.lower()); + let mut written = vec![ + format!("{dir}/.gitignore"), + format!("{dir}/socket-patch.vendor.json"), + copy.clone(), + ".socket/vendor/state.json".to_string(), + CONFIG.to_string(), + LOCK.to_string(), + ]; + written.sort(); + assert_eq!(changed(&before, &vendored), written, "{test}: {said}"); + assert_eq!(vendored[©], patch.package.nupkg, "{test}: {copy}"); + let source = format!( + " \n", + patch.uuid + ); + let config = text(&vendored, CONFIG); + assert!(config.contains(&source), "{test}: {CONFIG}:\n{config}"); + assert_eq!( + text(&vendored, LOCK), + lock_pinning(&run, &[&neighbour, &patch.package]), + "{test}: {LOCK}" + ); + // `vex` attests the package: it reads the committed copy. + let document = cell.document("vendored"); + let output = document.to_string_lossy(); + let vex = socket_patch(&cell, &standin, home.path(), &["vex", "--output", &output]); + assert_eq!(vex.code, 0, "{test}: {}", vex.dump); + let attested = [event("verified", "")]; + assert_eq!(event_triples(&vex.envelope), attested, "{}", vex.dump); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}"); + + // (c) KNOWN GAP: the next build fails. The hub takes the sources of + // `nuget.config` as the URLs of its feeds, and the folder is none: + // Bazel 9 crashes in the module extension, Bazel 8 and 7 refuse the + // URL. A fix would have the build print the patched marker here. + let build = cell.bazel("build", &[CONSUMER]); + let failure = match cell.numbers() >= (9, 0, 0) { + true => "NullPointerException thrown during Starlark evaluation".to_string(), + false => format!("Bad URL: {dir}"), + }; + // Compared without white space: nothing says where Bazel breaks a long + // line. + let squeezed = |text: &str| text.split_whitespace().collect::(); + assert!( + !build.ok() && squeezed(&build.stderr()).contains(&squeezed(&failure)), + "{test}: the build after the vendored scan did not fail with {failure:?}:\n{}", + build.dump() + ); + // Bazel asked no host for the patched package, and changed no file. + assert_eq!(standin.asked(&service), 1, "{test}"); + assert_eq!(standin.asked(&patch.file(&patch.package)), 0, "{test}"); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}"); + + // (d) The undo: every file is the one of before, and so is the build. + let undo = socket_patch(&cell, &standin, home.path(), &["vendor", "--revert"]); + cell.undone(&undo, "removed", &before, &unpatched); + + println!( + "{test}: on Bazel {release}, `scan --mode vendored` exited 0, kept the patched package \ + at {copy} and named {dir} in {CONFIG}; `vex` attested the package; the next build \ + failed ({failure}); `vendor --revert` restored all {} files and the build printed \ + {unpatched:?}; {:?}", + before.len(), + 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 89f73102167bd4884ea3de5f6823a4e5c6b759d1 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 14:44:52 -0500 Subject: [PATCH 09/22] Make vendored mode work for a NuGet package of a rules_csharp hub, or decline it Vendored mode commits the patched package under `.socket/vendor/nuget//`, names that folder as a package source in `nuget.config` and re-pins the lock. NuGet takes a folder as a source. rules_csharp's `nuget.from_lock` reads the same line as the URL of a feed: after `scan --mode vendored` had exited 0 and reported the package vendored, the next `bazel build` crashed Bazel 9.3.2 in the module extension (exit 37) and failed on 8.8.2 and 7.7.2 with `Bad URL: .socket/vendor/nuget/...`. That is the flow of the previous commit. What the hub does take A feed `file:`, which Bazel reads from the root of the workspace, with the package at `///..nupkg`; and the last `nuget.from_lock` that has `feeds` decides the hub's sources (`_nuget_impl` in csharp/extensions.bzl at 0.5.0). So in the root of a Bazel workspace whose one `nuget.from_lock` reads the project's lock, `scan --mode vendored`, `get --mode vendored` and `vendor` now write: - the package at `.socket/vendor/nuget////..nupkg`, the one copy; - `nuget.config` with that directory as the source, so `dotnet restore` outside Bazel takes the same file, and the lock as before; - one block at the end of the root `MODULE.bazel`, after one blank line: # >>> socket-patch: NuGet patches for Bazel (managed block: socket-patch writes and removes it) >>> socket_patch_nuget = use_extension("@rules_csharp//csharp:extensions.bzl", "nuget") socket_patch_nuget.from_lock( feeds = [ "file:.socket/vendor/nuget/", "https://api.nuget.org/v3/index.json", ], packages_lock_json = "//:packages.lock.json", ) # <<< socket-patch <<< A second tag of the same hub, after every tag of the user's: the folder of each vendored patch, then the sources the hub had without the block (those of the tag's `nuget_config`, read line by line as the ruleset reads them, or else its `feeds`), with the label of the user's `use_extension`, their `packages_lock_json`, and the hub's `name` where the tag gives one. No call of the user's is edited. On Bazel 9.3.2, 8.8.2 and 7.7.2 with rules_csharp 0.5.0 the build then prints the patched marker and asks no host for the package, also with the stand-in stopped, a new output base and the package in no repository cache. One changed byte of the committed package fails the build ("Checksum was ... but wanted ...") and `vendor --check`. `bazel query //...` lists what it listed. `vendor --check`, `list` and `vex` see the package as any vendored NuGet package, and a later vendored run keeps the block in step with the tag (a source added to `nuget.config` reaches it). The undo `vendor --revert`, `rollback` and `remove` take the folder of a patch out of the block, and the block goes with its last folder: `MODULE.bazel` is then byte for byte what it was. With one vendored patch every other file is too. With several, `nuget.config` can keep the source mapping that the first of them created: once another patch has changed the file, the config revert takes out only the two elements of its own patch, as it does without Bazel. A block that was changed by hand cannot be taken out. Reverting the lock and the config beside it would leave the hub holding the committed package to the upstream `contentHash`, and the build would fail after an undo that exited 0. So the undo checks the block before its first write and fails with nothing changed (`revert_failed` from `vendor --revert`, `vendor_revert_failed` from `rollback` and `remove`, exit 1). The message names the line of the block and the two ways on: put the block back as socket-patch wrote it, or delete it, and run the command again. Where it declines The block is written only where the checkout shows that it works. Otherwise the package is refused with `vendor_nuget_bazel_workspace` through `vendor::refusals::bazel_workspace_refusals`, the dispatch that Composer's refusal uses: before any download, a `failed` event, exit 1; a dry run of `scan` or `get` lists it and exits 0; a hosted pin stays, and its eject says `kept hosted: ...`. The detail names the reason, with file and line where there is one, and `--mode hosted`. The reasons: - the project is below the root of its workspace, or another workspace lies above it in the checkout (built from there, Bazel reads the folder from the other root); - more than one `nuget.from_lock`, or tags that cannot be read with certainty; a tag that is not a call of its own with every argument written out, or on an isolated or dev-dependency `use_extension`; - `local_package_dirs`, which the hub asks before every feed, and `netrc` or `auth_patterns`, which the block was not built with; - a `nuget_config` that cannot be read, a source that cannot stand in a string; - `feeds` beside a `nuget_config` that has no package source. The run names its folder in that file (and nuget.org, where NuGet had it by default), rules_csharp takes the sources of a `nuget_config` in place of `feeds`, and so would the next run: it would write the block without the tag's feeds, and a package that only they hold would fail the build after a run that exited 0. Hosted mode withholds in the same shape, with the same way on: name the feeds in the file; - `MODULE.bazel.lock` does not show that Bazel selected rules_csharp 0.5.0; - the checkout does not name Bazel 9.3.2, 8.8.2 or 7.7.2 (`.bazelversion`, `.bazeliskrc`). The block rests on Bazel reading a relative `file:` URL from the root of the workspace, which Bazel does not document, and 9.1.0 has other code for such a URL than 9.0.2 and 9.1.1 (DownloadManager.java), so no release is taken for its neighbour's sake; - an rc file names `--repository_disable_download` or `--vendor_dir`, or a directory at the root holds `VENDOR.bazel`; - an rc file names a remote downloader (`--experimental_remote_downloader`), which takes no `file:` feed. Read in Bazel's source and not built: 7.7.2 hands the feed to the downloader, which cannot read the folder, and 8.8.2 and 9.3.2 download every package of the lock without it (GrpcRemoteDownloader.java); - `MODULE.bazel` is a symbolic link, or its block was changed by hand. `--allow-vendored-in-bazel` (SOCKET_ALLOW_VENDORED_IN_BAZEL) lifts the refusal, and the package is vendored as in a project without Bazel. The help text, the contract and the docs said that Composer's was the one refusal the switch lifts; they now name both. A package that is wired already passes without the switch, as Composer's does. Nothing changes for a NuGet project in no Bazel workspace, and for one whose locks no `nuget.from_lock` reads: the same files, byte for byte, and no line of `MODULE.bazel`. Hosted mode beside the block: the block's tag is the hub's last one, so hosted mode writes nothing for another package of the project (`redirect_bazel_nuget_config_undeclared`) and now says to vendor that package too or to take the vendored ones out, instead of telling the user to edit the block. How - bazel/nuget.rs: `vendored` reads the tags (without the block), the ruleset's release, the Bazel release and the rc files through the existing readers, and gives the block's contents or the reason; `with_folder` and `without_folder` edit the block. - bazel/block.rs is new and holds what the Maven block and this one share, moved out of bazel/maven.rs: finding a block by its first line, putting one at the end of a file in the file's line break, cutting it out to the byte, and the file as it reads without it. `proxy` (the label of a `use_extension`), `asked` and the stale check of a ruleset's release are shared from maven.rs as they are. - vendor/nuget_feed.rs decides the layout, writes the block after the lock, records it in the ledger (`nuget_bazel_feed`, which may name the root `MODULE.bazel` alone) and reverts it; a failed block write unwinds the config and the locks, and a revert asks the block before it writes. - vex/discover/nuget.rs and vendor/path.rs read the package below `/` as well. Limits, all in docs/ecosystems.md "Bazel workspaces: NuGet": the block works in the root module only; a module this one depends on with its own `nuget.from_lock` sources replaces the block's feeds; `--nofetch`, in an rc file or on a command line, and a vendor directory made before the patch, can build the unpatched package with exit 0; a machine whose repository cache holds the package under the sha256 of Bazel's lock builds the cached, patched file and does not read a changed or missing copy, which `vendor --check` catches; a checkout deleted and made again under a running Bazel server does not find the package until the server restarts; a frozen lock fails right after the run, as in hosted mode; three WARNING lines per other package and vendored patch when the extension runs. An earlier release does not know the layout or the block: on a checkout this one vendored its `vendor --check` fails, its vendored run writes a second copy, and its `vendor --revert` exits 0 and leaves the block and the package beside the restored lock, so the Bazel build fails (measured on 9.3.2); undo with the release that vendored. Built on macOS arm64, with packages that carry no signature. "Bazel workspaces: what is supported" in the same file follows: the NuGet row of its table says vendored mode is supported with the Bazel release in `.bazelversion`, and VEX with a vendored patch as well; the list of what was tested names the shape; NuGet leaves the known problem "vendored mode ... the next Bazel build fails" for an entry of its own (the switch, a package an earlier release vendored, and the two shapes the checkout does not show); the build that may not fetch is listed among those that pass on the unpatched package; and "Bazel workspaces: VEX" names the vendored flow and the cases in which the document says `not_affected` of a package whose block is not in `MODULE.bazel`. Tests: nuget::vendored_from_lock now holds the flow above on real Bazel, with one decline (a checkout that names no release: nothing written, the build still passes on the upstream package) and the document of `vex`, which names the package. nuget::vendored_mode_keeps_the_block_or_declines runs the commands through the binary without Bazel: the unchanged layout without a hub, the block and its three undos, the three undos beside a block that was changed by hand (exit 1, no file changed, then the undo once the block is deleted), the declines, the eject and the switch. Unit tests cover the gate row by row, the block's text and its byte-exact undo, the ledger record, the revert beside a changed block wherever its record stands, and the path git is asked about for a hub's package. The `bazel` group of the line budget follows the code, 3337 to 3758. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-nuget.yml | 23 +- crates/socket-patch-cli/CLI_CONTRACT.md | 7 +- crates/socket-patch-cli/src/args.rs | 9 +- .../tests/e2e_bazel_build/harness.rs | 15 + .../tests/e2e_bazel_build/nuget.rs | 563 ++++++++- crates/socket-patch-core/src/bazel/block.rs | 113 ++ crates/socket-patch-core/src/bazel/maven.rs | 141 +-- crates/socket-patch-core/src/bazel/mod.rs | 35 +- crates/socket-patch-core/src/bazel/nuget.rs | 1029 ++++++++++++++++- crates/socket-patch-core/src/vendor/mod.rs | 2 +- .../src/vendor/nuget_feed.rs | 550 ++++++++- crates/socket-patch-core/src/vendor/path.rs | 24 +- .../socket-patch-core/src/vendor/refusals.rs | 60 +- crates/socket-patch-core/src/vendor/state.rs | 4 + .../src/vex/discover/nuget.rs | 74 +- docs/ecosystems.md | 207 +++- scripts/loc-budget.json | 2 +- 17 files changed, 2620 insertions(+), 238 deletions(-) create mode 100644 crates/socket-patch-core/src/bazel/block.rs diff --git a/.github/workflows/bazel-nuget.yml b/.github/workflows/bazel-nuget.yml index 868f27f85..e1056f6d0 100644 --- a/.github/workflows/bazel-nuget.yml +++ b/.github/workflows/bazel-nuget.yml @@ -3,8 +3,8 @@ 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`, and vendored mode for the same package, on each Bazel -# release below. +# `nuget_config`, and vendored mode for the same package, through the block +# it keeps in `MODULE.bazel`, 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. # @@ -40,9 +40,14 @@ on: # `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, which the vendored flow - # runs; every one of those files calls its version and folder helpers. + # workspace.rs), and what hosted and vendored mode make of the tag + # (bazel/nuget.rs). vendor/nuget_feed.rs is the vendored backend, which + # the vendored flow runs; every one of those files calls its version + # and folder helpers. The vendored flow also runs through the block of + # `MODULE.bazel` (bazel/block.rs), what bazel/maven.rs shares with it + # (the label of a `use_extension` and the release of a ruleset), what + # names the Bazel release and the rc files (bazel/rc.rs), and the + # dispatch of the refusals of vendored mode (vendor/refusals.rs). # Nothing else that another ecosystem's flow owns is here, so any other # change to one ecosystem starts that ecosystem's legs only. # @@ -71,8 +76,12 @@ 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/vendor/refusals.rs' + - 'crates/socket-patch-core/src/bazel/block.rs' + - 'crates/socket-patch-core/src/bazel/maven.rs' - 'crates/socket-patch-core/src/bazel/mod.rs' - 'crates/socket-patch-core/src/bazel/nuget.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' push: @@ -98,8 +107,12 @@ 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/vendor/refusals.rs' + - 'crates/socket-patch-core/src/bazel/block.rs' + - 'crates/socket-patch-core/src/bazel/maven.rs' - 'crates/socket-patch-core/src/bazel/mod.rs' - 'crates/socket-patch-core/src/bazel/nuget.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-cli/tests/e2e_bazel_build/main.rs' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 42c5d4a95..a00ddcf39 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; it lifts two refusals today. `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_nuget_bazel_workspace`: the package is then vendored as in a project without Bazel, which a rules_csharp hub does not take, and its build fails. Any refusal of vendored mode that rests on the Bazel workspace reads this one switch. For a project whose build does find the copy, or which Bazel does not build. 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: NuGet" | **`--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. @@ -1694,7 +1694,7 @@ to **six flavors**. | 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) | -| 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) | +| nuget | deterministically rebuilt `.nupkg` at `..nupkg` (the uuid dir IS a NuGet folder feed; for a package of a rules_csharp hub in a Bazel workspace the file lies at `//..nupkg`, `nuget.config` names that directory and the root `MODULE.bazel` gains one managed block, or the package is declined with `vendor_nuget_bazel_workspace`, see docs/ecosystems.md "Bazel workspaces: NuGet"; 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) | Ecosystems with no vendor backend (jsr) refuse per-purl with @@ -2187,7 +2187,7 @@ Empty string means unset at every layer: exported-but-empty flag-bound vars are | `SOCKET_NO_VLT_INSTALL_CLEANUP` | `--no-vlt-install-cleanup` | `false` | Hosted mode, `rollback`, `remove`: keep stale vlt installed copies. | | `SOCKET_NO_GEM_INSTALL_REFRESH` | `--no-gem-install-refresh` | `false` | Hosted mode, `rollback`, `remove`: leave the project's stale installed gems and cached archives alone. | | `SOCKET_GEM_REFRESH_SHARED` | `--gem-refresh-shared` | `false` | Hosted mode, `rollback`, `remove`: also refresh stale gems in gem homes outside the project. | -| `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `--allow-vendored-in-bazel` | `false` | Vendored mode: write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. | +| `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `--allow-vendored-in-bazel` | `false` | Vendored mode: write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy (`vendor_composer_bazel_workspace`, `vendor_nuget_bazel_workspace`). | | `SOCKET_PATCH_VERSION` | `--update ` | (latest) | Local to `--update`; the same pin `install.sh` honors. | | `SOCKET_BATCH_SIZE` | `scan --batch-size` | `500` authenticated / `100` proxy | Local to `scan`. | | `SOCKET_MAX_NEW_PATCHES` | `scan --max-new-patches` | (unlimited) | Local to `scan` (v5.0): a count or `none`; empty is unset, malformed exits 2. | @@ -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_nuget_bazel_workspace` | `failed`; `skipped` (warning, vendor advisory event) for a package that is already vendored for the hub | vendor / scan / get `--mode vendored` (nuget): a rules_csharp `nuget.from_lock` tag of the project's Bazel workspace reads a lock of the project, and the block that makes the hub take the committed package cannot be shown to work from the checkout. Vendored mode keeps such a package at `.socket/vendor/nuget////..nupkg`, names that directory in `nuget.config`, and appends one managed block to the root `MODULE.bazel`: a `nuget.from_lock` of its own whose `feeds` are `file:.socket/vendor/nuget/` for each vendored patch and then the sources the hub had without it (rules_csharp 0.5.0 on Bazel 9.3.2, 8.8.2, 7.7.2). It declines when: the project is not the root of its Bazel workspace, or another workspace lies above it in the checkout; the workspace has more than one `nuget.from_lock`, or its tags cannot be read with certainty; the tag is not a call of its own with every argument written out, is called on an isolated or dev-dependency `use_extension`, or has `local_package_dirs`, `netrc` or `auth_patterns`; its `nuget_config` cannot be read, or a package source cannot stand in a string; it has `feeds` and a `nuget_config` without a package source (the run names its folder there, and rules_csharp takes the sources of that file in place of `feeds`); `MODULE.bazel.lock` does not show that Bazel selected rules_csharp 0.5.0; the checkout does not name Bazel 9.3.2, 8.8.2 or 7.7.2 (`.bazelversion` / `.bazeliskrc`); an rc file names `--repository_disable_download`, `--vendor_dir` or a remote downloader (`--experimental_remote_downloader`), or a directory at the root holds `VENDOR.bazel`; `MODULE.bazel` is a symbolic link, or its block was changed by hand. 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. The detail names the reason, with the file and line where there is one, and `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel` (the package is vendored as without Bazel), `vendor --revert`, a package whose folder `nuget.config` already names (the run leaves the config as it is), and a project whose locks no `nuget.from_lock` reads, which is vendored as without Bazel. As an advisory event: a package that is vendored for the hub, whose block can no longer be shown to work or was changed by hand; the block is left as it is. The undo of such a package beside a block that was changed by hand fails and changes nothing (`revert_failed` from `vendor --revert`, `vendor_revert_failed` from `rollback` and `remove`; exit 1): the detail names the line of the block, and the lock restored beside it would fail the Bazel build. See docs/ecosystems.md "Bazel workspaces: NuGet". | | `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..70cd22d3b 100644 --- a/crates/socket-patch-cli/src/args.rs +++ b/crates/socket-patch-cli/src/args.rs @@ -425,11 +425,14 @@ 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 NuGet package of a rules_csharp hub + /// where the `MODULE.bazel` block that makes the hub take the copy + /// cannot be shown to work (`vendor_nuget_bazel_workspace`). Pass it + /// when the build does find the copy, or does not build the project. + /// 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..2c9de6704 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -930,6 +930,21 @@ impl Cell { self.downloads = Some(rules.to_vec()); } + /// Take the file whose sha256 is `sha256` out of the repository cache, + /// which the tests of a leg and every twin share: whether it was + /// there. Bazel then has to fetch that file again from where its URLs + /// lead, as on a machine that never had it. + pub fn uncache(&self, sha256: &str) -> bool { + let cache = &self.scratch.repository_cache; + let entry = cache.join("content_addressable/sha256").join(sha256); + let held = entry.join("file").is_file(); + if held { + std::fs::remove_dir_all(&entry) + .unwrap_or_else(|e| panic!("remove {}: {e}", entry.display())); + } + held + } + /// Write a file of the workspace copy. pub fn write(&self, rel: &str, bytes: impl AsRef<[u8]>) { let path = self.scratch.workspace.join(rel); 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 1c5829883..000686788 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs @@ -130,15 +130,23 @@ //! //! A third flow, [`vendored_from_lock`], runs vendored mode in the //! fixture's workspace. `scan --mode vendored --yes` downloads the patched -//! package from the patch service once, keeps it under `.socket/vendor`, -//! names that folder as a package source in `nuget.config` and re-pins the -//! lock. NuGet takes a folder as a source. The hub reads the same line as -//! the URL of a feed, so the next `bazel build` fails. `vendor --revert` -//! puts every file back, and the build with them. +//! package from the patch service once and keeps it under `.socket/vendor`, +//! at the path a feed of the hub has a package. It names that folder as a +//! package source in `nuget.config`, which NuGet takes, re-pins the lock, +//! and appends a block to `MODULE.bazel`: a `nuget.from_lock` of its own, +//! whose feeds are the folder of the patch, as a `file:` URL that Bazel +//! reads from the root of the workspace, and then the sources of the +//! config. The build then takes the committed package and asks no host for +//! it, also on a machine with no host to ask; a changed copy fails the +//! build; and `vendor --revert` puts every file back. Where the checkout +//! does not show that the block works (it names no Bazel release), the +//! command declines the package and writes nothing. +//! [`vendored_mode_keeps_the_block_or_declines`] holds the commands to the +//! same without a Bazel, with the other ways in and out. //! //! # 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: //! @@ -150,8 +158,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). -//! - Vendored mode exits 0 and reports the package vendored, and the next -//! `bazel build` fails ([`vendored_from_lock`]). use std::io::Write as _; use std::path::{Path, PathBuf}; @@ -162,7 +168,7 @@ 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_triples}; +use crate::envelope::{all_codes as codes_of, codes_in, event_triples}; use crate::harness::{ cell_without_bazel, changed, fixture_path, rewrite, Cell, Fixture, Ran, StandIn, Tree, CONSUMER, NOTHING, @@ -1012,14 +1018,77 @@ fn vendor_dir(patch: &Patched) -> String { format!(".socket/vendor/nuget/{}", patch.uuid) } +/// Where vendored mode keeps the package of `patch` for a hub, below +/// [`vendor_dir`]: the path at which a feed of rules_csharp has a package. +fn hub_copy(patch: &Patched) -> String { + let lower = patch.package.lower(); + format!( + "{}/{lower}/{VERSION}/{lower}.{VERSION}.nupkg", + vendor_dir(patch) + ) +} + +/// The block vendored mode keeps at the end of the fixture's `MODULE.bazel` +/// for the folder `dir` of a patch: the hub's own extension and lock, and +/// as feeds that folder, which Bazel reads from the root of the workspace, +/// and then the one source of the fixture's `nuget.config`. +fn block(dir: &str) -> String { + format!( + "# >>> socket-patch: NuGet patches for Bazel (managed block: socket-patch writes and \ + removes it) >>>\n\ + socket_patch_nuget = use_extension(\"@rules_csharp//csharp:extensions.bzl\", \"nuget\")\n\ + socket_patch_nuget.from_lock(\n feeds = [\n \"file:{dir}\",\n \ + \"{SOURCE}\",\n ],\n packages_lock_json = \"//:{LOCK}\",\n)\n\ + # <<< socket-patch <<<\n" + ) +} + +/// The code with which vendored mode declines a package of a hub, where it +/// cannot show that its block works, and the file that names the Bazel +/// release of a checkout. +const DECLINED: &str = "vendor_nuget_bazel_workspace"; +const BAZEL_VERSION: &str = ".bazelversion"; + +/// For a finished vendored command that declined the package `purl`: it +/// failed with exit 1, its one event is the refusal, and the detail says +/// `why`, names hosted mode and the switch. +fn declined(test: &str, ran: &Ran, purl: &str, why: &str) { + let said = &ran.dump; + assert_eq!(ran.code, 1, "{test}: {said}"); + assert_eq!(ran.envelope["status"], "partialFailure", "{test}: {said}"); + let refusal = [(purl.to_string(), "failed".to_string(), DECLINED.to_string())]; + assert_eq!(event_triples(&ran.envelope), refusal, "{test}: {said}"); + let event = &ran.envelope["events"][0]; + let detail = event["error"].as_str().or(event["reason"].as_str()); + let detail = detail.unwrap_or_default(); + for part in [why, "`--mode hosted`", "`--allow-vendored-in-bazel`"] { + assert!(detail.contains(part), "{test}: no {part:?} in {detail:?}"); + } +} + /// Vendored mode in the fixture's workspace, on the machine that restored -/// the project. The command downloads the patched package from the patch -/// service once and keeps it under `.socket/vendor`; it names that folder -/// as a package source in `nuget.config`, with a source mapping, and -/// re-pins the lock. It exits 0 and reports the package vendored, and -/// `vex` attests it. The hub reads the folder as the URL of a feed, so the -/// next `bazel build` fails. `vendor --revert` puts every file back, and -/// the build with them. +/// the project. +/// +/// - (a) The unpatched build. The checkout names no Bazel release, so +/// `scan --mode vendored --yes` declines the package: nothing is +/// downloaded or written, and the build stays the one of before. +/// - (b) With the release in `.bazelversion`, the same command downloads +/// the patched package from the patch service once and keeps it where a +/// feed of the hub has a package, names that folder in `nuget.config`, +/// re-pins the lock, and appends its block to `MODULE.bazel`. `vendor +/// --check` passes, `vex` attests the package, and `bazel query //...` +/// lists what it listed. Bazel's own lock is stale, as after a hosted +/// scan: a frozen lock fails until a build has updated it. +/// - (c) The build of (a) prints the patched marker, from the committed +/// copy: Bazel asks no host for the package. Then on a second machine, +/// with the stand-in stopped, a new output base and the package in no +/// repository cache, the build prints it again. +/// - (d) On a third machine, one byte of the committed package is another: +/// `vendor --check` fails, and so does the build, over the sha256 that +/// Bazel's lock pins. +/// - (e) `vendor --revert` puts every file back but Bazel's own lock, and +/// the next build prints the unpatched marker and writes the lock of +/// before. #[test] #[ignore = "real Bazel; run with --ignored"] fn vendored_from_lock() { @@ -1034,7 +1103,7 @@ fn vendored_from_lock() { let upstream = Package::new(NAME, &run, &format!("PRISTINE {run}")); let neighbour = Package::new(NEIGHBOUR, &run, "NEIGHBOUR"); let patch = Patched::new(&run); - let (purl, unpatched) = (upstream.purl(), upstream.marker()); + let (purl, unpatched, patched) = (upstream.purl(), upstream.marker(), patch.package.marker()); let standin = registry(&[&neighbour, &upstream]); grant(&standin, &upstream, &patch, &patch.package.nupkg); let service = service_route(&standin, &patch); @@ -1047,13 +1116,28 @@ fn vendored_from_lock() { for package in [&neighbour, &upstream] { package.restore_into(home.path()); } + let listing = |cell: &Cell| { + let query = cell.bazel("query", &["//..."]); + assert!(query.ok(), "{test}: {}", query.dump()); + query.stdout() + }; - // (a) The unpatched build. - let before = cell.builds_unpatched(&unpatched); - - // (b) The one command of vendored mode: the package from the patch - // service, once, into the folder of the patch; that folder as a source - // of `nuget.config`; and the lock re-pinned. + // (a) The unpatched build. No file of the checkout names the Bazel + // release that builds it, and the block is written for the releases it + // was built on alone: the command declines, with nothing downloaded + // and nothing written, and the build passes on the upstream package. + let unnamed = cell.builds_unpatched(&unpatched); + let scan = vendored_scan(&cell, &standin, home.path(), &[]); + let no_release = "no file of the checkout names the Bazel release that builds it"; + declined(test, &scan, &purl, no_release); + assert_eq!(standin.asked(&service), 0, "{test}: {}", scan.dump); + assert_eq!(changed(&unnamed, &cell.tree()), NOTHING, "{test}"); + cell.builds_patched(&unnamed, &unpatched); + + // (b) The checkout names its release, as a launcher reads it. + cell.write(BAZEL_VERSION, format!("{release}\n")); + let before = cell.tree(); + let targets = listing(&cell); let scan = vendored_scan(&cell, &standin, home.path(), &[]); let said = &scan.dump; assert_eq!(scan.code, 0, "{test}: {said}"); @@ -1070,21 +1154,24 @@ fn vendored_from_lock() { assert_eq!(event_triples(&scan.envelope), events, "{test}: {said}"); assert_eq!(standin.asked(&service), 1, "{test}: {said}"); let vendored = cell.tree(); - let dir = vendor_dir(&patch); - let copy = format!("{dir}/{}.{VERSION}.nupkg", upstream.lower()); + let (dir, copy) = (vendor_dir(&patch), hub_copy(&patch)); let mut written = vec![ format!("{dir}/.gitignore"), format!("{dir}/socket-patch.vendor.json"), copy.clone(), ".socket/vendor/state.json".to_string(), + MODULE.to_string(), CONFIG.to_string(), LOCK.to_string(), ]; written.sort(); assert_eq!(changed(&before, &vendored), written, "{test}: {said}"); assert_eq!(vendored[©], patch.package.nupkg, "{test}: {copy}"); + // The config names the folder of the package, where NuGet finds it; + // the block names the folder of the patch, below which the hub does. + let folder = copy.rsplit_once('/').expect("a path").0; let source = format!( - " \n", + " \n", patch.uuid ); let config = text(&vendored, CONFIG); @@ -1094,51 +1181,429 @@ fn vendored_from_lock() { lock_pinning(&run, &[&neighbour, &patch.package]), "{test}: {LOCK}" ); - // `vex` attests the package: it reads the committed copy. + let appended = format!("{}\n{}", text(&before, MODULE), block(&dir)); + assert_eq!(text(&vendored, MODULE), appended, "{test}: {MODULE}"); + // `vendor --check` and `vex` see the package as any vendored one, and + // Bazel sees no package in the folder. + let check = socket_patch(&cell, &standin, home.path(), &["vendor", "--check"]); + assert_eq!(check.code, 0, "{test}: {}", check.dump); + let verified = [event("verified", "vendor_check_ok")]; + assert_eq!(event_triples(&check.envelope), verified, "{}", check.dump); let document = cell.document("vendored"); let output = document.to_string_lossy(); let vex = socket_patch(&cell, &standin, home.path(), &["vex", "--output", &output]); assert_eq!(vex.code, 0, "{test}: {}", vex.dump); let attested = [event("verified", "")]; assert_eq!(event_triples(&vex.envelope), attested, "{}", vex.dump); + // With its closing quote, as the document writes `"@id": ""`. + let written = std::fs::read_to_string(&document).unwrap_or_default(); + let names = written.contains(&format!("\"{purl}\"")); + assert!(names, "{test}: {}\n{written}", vex.dump); + assert_eq!(listing(&cell), targets, "{test}: `bazel query //...`"); assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}"); + frozen_build_fails(&cell, "scan --mode vendored"); - // (c) KNOWN GAP: the next build fails. The hub takes the sources of - // `nuget.config` as the URLs of its feeds, and the folder is none: - // Bazel 9 crashes in the module extension, Bazel 8 and 7 refuse the - // URL. A fix would have the build print the patched marker here. + // (c) The build of (a) and no other step: patched, from the committed + // copy. Bazel asked the folder for the other package of the lock as + // well, warned that it is not there, and took it from nuget.org as + // before. It rewrote its own lock and no other file. let build = cell.bazel("build", &[CONSUMER]); - let failure = match cell.numbers() >= (9, 0, 0) { - true => "NullPointerException thrown during Starlark evaluation".to_string(), - false => format!("Bad URL: {dir}"), - }; - // Compared without white space: nothing says where Bazel breaks a long - // line. + assert!(build.ok(), "{test}: {}", build.dump()); + // A line of Bazel's is compared without white space, here and below: + // nothing says where a tool breaks a long line. let squeezed = |text: &str| text.split_whitespace().collect::(); + let missed = format!("WARNING: Download from file:{dir}/{}/", neighbour.lower()); assert!( - !build.ok() && squeezed(&build.stderr()).contains(&squeezed(&failure)), - "{test}: the build after the vendored scan did not fail with {failure:?}:\n{}", + squeezed(&build.stderr()).contains(&squeezed(&missed)), + "{test}: no {missed:?}:\n{}", build.dump() ); - // Bazel asked no host for the patched package, and changed no file. - assert_eq!(standin.asked(&service), 1, "{test}"); - assert_eq!(standin.asked(&patch.file(&patch.package)), 0, "{test}"); - assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}"); + let built = cell.tree(); + assert_eq!(changed(&vendored, &built), [BAZEL_LOCK], "{test}"); + cell.builds_patched(&built, &patched); + let patched_route = patch.file(&patch.package); + let asked = (standin.asked(&service), standin.asked(&patched_route)); + assert_eq!(asked, (1, 0), "{test}: Bazel asked a host for the package"); + + // A second machine, with no host to ask: the stand-in is stopped, the + // output base is new, and the repository cache, which held the package + // since the build above, holds it no more. + let sum = sha256_hex(&patch.package.nupkg); + assert!(cell.uncache(&sum), "{test}: the cache did not hold {sum}"); + drop(standin); + let offline = cell.twin(); + offline.builds(&patched); + assert_eq!(changed(&built, &offline.tree()), NOTHING, "{test}"); + + // (d) A third machine, where one byte of the committed package is + // another: `vendor --check` fails, and the build fails over the sha256 + // that Bazel's lock pins. The changed bytes are never built. + assert!( + offline.uncache(&sum), + "{test}: the cache did not hold {sum}" + ); + let tampered = offline.twin(); + let mut bytes = patch.package.nupkg.clone(); + let middle = bytes.len() / 2; + bytes[middle] ^= 0x01; + tampered.write(©, &bytes); + let check = tampered.socket_patch("http://127.0.0.1:9", &["vendor", "--check"], &[]); + assert_eq!(check.code, 1, "{test}: {}", check.dump); + let failed = [event("failed", "vendor_check_failed")]; + assert_eq!(event_triples(&check.envelope), failed, "{}", check.dump); + let build = tampered.bazel("build", &[CONSUMER]); + let refusal = format!("Checksum was {} but wanted {sum}", sha256_hex(&bytes)); + assert!( + !build.ok() && squeezed(&build.stderr()).contains(&squeezed(&refusal)), + "{test}: the changed package did not fail the build with {refusal:?}:\n{}", + build.dump() + ); + drop(tampered); + drop(offline); - // (d) The undo: every file is the one of before, and so is the build. + // (e) The undo, with a registry to ask again: every file of the + // checkout is the one of before but Bazel's own lock, which the next + // build puts back with the unpatched marker. + let standin = registry(&[&neighbour, &upstream]); + cell.route_downloads(&downloads(&standin.origin())); let undo = socket_patch(&cell, &standin, home.path(), &["vendor", "--revert"]); - cell.undone(&undo, "removed", &before, &unpatched); + 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()), + [BAZEL_LOCK], + "{test}: {said}" + ); + cell.builds(&unpatched); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}"); println!( - "{test}: on Bazel {release}, `scan --mode vendored` exited 0, kept the patched package \ - at {copy} and named {dir} in {CONFIG}; `vex` attested the package; the next build \ - failed ({failure}); `vendor --revert` restored all {} files and the build printed \ - {unpatched:?}; {:?}", + "{test}: on Bazel {release}, `scan --mode vendored` declined the package while no file \ + named the release ({DECLINED}) and the build stayed {unpatched:?}; with {BAZEL_VERSION} \ + it kept the patched package at {copy} and its block in {MODULE}; `vendor --check` passed \ + and `vex` attested the package; the build printed {patched:?} with no request for the \ + package, and again with the stand-in stopped, a new output base and the package in no \ + repository cache; one changed byte failed `vendor --check` and the build ({refusal}); \ + `vendor --revert` restored all {} files but {BAZEL_LOCK}, and the next build printed \ + {unpatched:?} and wrote the lock of before; {:?}", before.len(), started.elapsed() ); } +/// Bazel's lock of a checkout that a build has selected rules_csharp 0.5.0 +/// for: the one line of it that vendored mode reads. +const SELECTED: &str = "{\"lockFileVersion\": 28, \"registryFileHashes\": {\ + \"https://bcr.bazel.build/modules/rules_csharp/0.5.0/source.json\": \"sum\"}}\n"; + +/// Without a Bazel: vendored mode through the binary, in checkouts of the +/// fixture's project on the machine that restored it. +/// +/// Where no Bazel workspace is, and where the tag of one reads the lock of +/// another project, the command gives a person and a script what it gives +/// without Bazel, and writes the same files: the package in the folder of +/// the patch, that folder in `nuget.config`, and no line of `MODULE.bazel`. +/// +/// In the fixture's workspace it keeps the package where a feed of the hub +/// has it and its block in `MODULE.bazel`; a second run changes nothing; +/// `vendor --check` passes and `list` says what it says without Bazel; and +/// `vendor --revert`, `rollback` and `remove` each put every file back +/// byte for byte, the block with its one folder. Beside a block that was +/// changed by hand no undo changes a file, and each says where the block +/// is; with the block deleted by hand, the undo puts the rest back. +/// +/// Where the block cannot be shown to work, `scan` and `get` decline the +/// package with exit 1 and write nothing, a dry run lists it and exits 0, +/// and a person reads the reason. A pin of hosted mode stays: the scan +/// that would take it over and the `vendor` that would eject it are +/// declined too, and where the block does work `vendor` ejects the pin +/// into it. With `--allow-vendored-in-bazel`, or its variable, the package +/// is vendored as without Bazel. +#[test] +fn vendored_mode_keeps_the_block_or_declines() { + let test = "nuget::vendored_mode_keeps_the_block_or_declines"; + let (upstream, neighbour) = ( + Package::new(NAME, "R1", "PRISTINE"), + Package::new(NEIGHBOUR, "R1", "NEIGHBOUR"), + ); + let (patch, purl) = (Patched::new("R1"), upstream.purl()); + let standin = registry(&[&neighbour, &upstream]); + grant(&standin, &upstream, &patch, &patch.package.nupkg); + let service = service_route(&standin, &patch); + let home = tempfile::tempdir().expect("create the .NET home"); + for package in [&neighbour, &upstream] { + package.restore_into(home.path()); + } + let era = fixture_path(FIXTURE.dir).join(FIXTURE.eras[0].1); + let module = std::fs::read_to_string(era.join(MODULE)).expect(MODULE); + // A checkout of the fixture's project and config: with `module` as its + // MODULE.bazel, beside Bazel's lock, and the release it names. + let checkout = |module: Option<&str>, release: Option<&str>| { + let cell = cell_without_bazel("9.3.2"); + check_out(&cell, "R1", &[&neighbour, &upstream]); + cell.write(CONFIG, fixture_file_as_is(CONFIG)); + cell.write(".git/HEAD", "ref: refs/heads/main\n"); + if let Some(module) = module { + cell.write(MODULE, module); + cell.write(BAZEL_LOCK, SELECTED); + } + if let Some(release) = release { + cell.write(BAZEL_VERSION, format!("{release}\n")); + } + cell + }; + let scan = |cell: &Cell, more: &[&str]| vendored_scan(cell, &standin, home.path(), more); + let (dir, flat) = ( + vendor_dir(&patch), + format!("{}.{VERSION}.nupkg", upstream.lower()), + ); + let flat = format!("{dir}/{flat}"); + // What a vendored run wrote of the three files it shares with a hub, + // and the names of everything it wrote. + let wrote = |cell: &Cell, before: &Tree| { + let after = cell.tree(); + let files = [CONFIG, LOCK].map(|file| after[file].clone()); + (changed(before, &after), files) + }; + + // Without Bazel, and beside a tag that reads the lock of another + // project: the package in the folder of the patch. + let plain = checkout(None, None); + let before = plain.tree(); + let without = scan(&plain, &[]); + assert_eq!(without.code, 0, "{test}: {}", without.dump); + let as_before = wrote(&plain, &before); + let mut written = vec![ + format!("{dir}/.gitignore"), + format!("{dir}/socket-patch.vendor.json"), + flat.clone(), + ".socket/vendor/state.json".to_string(), + CONFIG.to_string(), + LOCK.to_string(), + ]; + written.sort(); + assert_eq!(as_before.0, written, "{test}: {}", without.dump); + let elsewhere = module.replace("//:packages", "//api:packages"); + for (module, release) in [(&elsewhere, None), (&elsewhere, Some("9.3.2"))] { + let cell = checkout(Some(module), release); + let before = cell.tree(); + let ran = scan(&cell, &[]); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + assert_eq!(ran.envelope, without.envelope, "{test}: {}", ran.dump); + assert_eq!(wrote(&cell, &before), as_before, "{test}: {}", ran.dump); + } + + // The fixture's workspace: the block, and every way to take it out. + let hub = checkout(Some(&module), Some("9.3.2")); + let before = hub.tree(); + let undo: [&[&str]; 3] = [ + &["vendor", "--revert"], + &["rollback", "--yes"], + &["remove", &purl, "--yes"], + ]; + for undo in undo { + let ran = scan(&hub, &[]); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + let vendored = hub.tree(); + let mut written = vec![ + format!("{dir}/.gitignore"), + format!("{dir}/socket-patch.vendor.json"), + hub_copy(&patch), + ".socket/vendor/state.json".to_string(), + MODULE.to_string(), + CONFIG.to_string(), + LOCK.to_string(), + ]; + written.sort(); + assert_eq!(changed(&before, &vendored), written, "{test}: {}", ran.dump); + let appended = format!("{module}\n{}", block(&dir)); + assert_eq!(text(&vendored, MODULE), appended, "{test}"); + // Once more, and the check: nothing is written. + let again = scan(&hub, &[]); + assert_eq!(again.code, 0, "{test}: {}", again.dump); + let check = socket_patch(&hub, &standin, home.path(), &["vendor", "--check"]); + assert_eq!(check.code, 0, "{test}: {}", check.dump); + // `list` says of it what it says of the package without Bazel. + let list = |cell: &Cell| socket_patch(cell, &standin, home.path(), &["list"]); + let (listed, as_without) = (list(&hub), list(&plain)); + assert_eq!(listed.envelope["events"][0]["details"]["mode"], "vendored"); + assert_eq!(listed.envelope, as_without.envelope, "{}", listed.dump); + assert_eq!(changed(&vendored, &hub.tree()), NOTHING, "{test}: {undo:?}"); + let ran = socket_patch(&hub, &standin, home.path(), undo); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + assert_eq!( + changed(&before, &hub.tree()), + NOTHING, + "{test}: {}", + ran.dump + ); + } + + // A block that was changed by hand keeps the folder of the patch, and + // with the lock restored beside it the Bazel build would fail on the + // committed package: no undo changes a file, and each names the line + // of the block. With the block deleted by hand, the undo puts every + // other file back. + let squeezed = |text: &str| text.split_whitespace().collect::(); + let ran = scan(&hub, &[]); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + let wired = text(&hub.tree(), MODULE); + hub.write( + MODULE, + wired.replace(" feeds = [", " # mine\n feeds = ["), + ); + let edited = hub.tree(); + assert_ne!(text(&edited, MODULE), wired, "{test}"); + let by_hand = format!( + "{MODULE}:{}: the block that socket-patch keeps there was changed by hand", + module.lines().count() + 2 + ); + for undo in undo { + let ran = socket_patch(&hub, &standin, home.path(), undo); + assert_eq!(ran.code, 1, "{test}: {}", ran.dump); + assert!( + squeezed(&ran.dump).contains(&squeezed(&by_hand)), + "{test}: no {by_hand:?}: {}", + ran.dump + ); + assert_eq!(changed(&edited, &hub.tree()), NOTHING, "{test}: {undo:?}"); + } + hub.write(MODULE, &module); + let ran = socket_patch(&hub, &standin, home.path(), undo[0]); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + assert_eq!( + changed(&before, &hub.tree()), + NOTHING, + "{test}: {}", + ran.dump + ); + + // Where the block cannot be shown to work: declined by every command + // that would vendor, with nothing asked of the patch service. The + // last row is a tag with `feeds` beside a config without a source: the + // run would name its folder there, and the next one would take the + // sources of that file for the hub's in place of those feeds. + let asked = standin.asked(&service); + let dirs = module.replace(NAMES_CONFIG, " local_package_dirs = [\"/opt/nuget\"],\n"); + let fed = + format!(" feeds = [\"https://nuget.private.example/v3/index.json\"],\n{NAMES_CONFIG}"); + let fed = module.replace(NAMES_CONFIG, &fed); + let sourceless = "\n \n \n\n"; + let rows: [(&str, Option<&str>, Option<&str>, &str); 4] = [ + ( + &module, + None, + None, + "no file of the checkout names the Bazel release", + ), + ( + &module, + Some("8.8.1"), + None, + "the checkout names Bazel 8.8.1", + ), + ( + &dirs, + Some("9.3.2"), + None, + "MODULE.bazel:9: this `nuget.from_lock` has `local_package_dirs`", + ), + ( + &fed, + Some("9.3.2"), + Some(sourceless), + "MODULE.bazel:9: this `nuget.from_lock` has `feeds`, and its `nuget_config` \ + `//:nuget.config` names no package source", + ), + ]; + for (module, release, config, why) in rows { + let cell = checkout(Some(module), release); + if let Some(config) = config { + cell.write(CONFIG, config); + } + let before = cell.tree(); + declined(test, &scan(&cell, &[]), &purl, why); + let get = ["get", &purl, "--mode", "vendored", "--yes"]; + let get = socket_patch(&cell, &standin, home.path(), &get); + assert_eq!(get.code, 1, "{test}: {}", get.dump); + assert!( + codes_of(&get.envelope).contains(&DECLINED.to_string()), + "{}", + get.dump + ); + // A dry run lists it and passes. + let dry = scan(&cell, &["--dry-run"]); + assert_eq!(dry.code, 0, "{test}: {}", dry.dump); + let listed = [(purl.clone(), "skipped".to_string(), DECLINED.to_string())]; + assert_eq!(event_triples(&dry.envelope), listed, "{test}: {}", dry.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}: {why}"); + // A person reads the reason after the package, once. The output is + // compared without white space: nothing says where a long line is + // broken. + let run = |api: &str, env: &[(&str, &str)]| { + let origin = standin.origin(); + let args = [&VENDORED[..], &["--patch-server-url", &origin]].concat(); + cell.socket_patch_person(api, &args, env) + }; + let person = on_machine(&standin, home.path(), run); + let told = squeezed(&person.concat()); + let line = squeezed(&format!("{purl} ({DECLINED}): ")); + assert!( + told.matches(&line).count() == 1 && told.contains(&squeezed(why)), + "{test}: {person:?}" + ); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}: {why}"); + assert_eq!(standin.asked(&service), asked, "{test}: {why}"); + } + // A package that hosted mode pinned: the scan that would take the pin + // over and the `vendor` that would eject it are declined, and the pin + // stays. Once the checkout names its release, `vendor` ejects the pin + // into the block. + let cell = checkout(Some(&module), None); + let hosted = socket_patch(&cell, &standin, home.path(), &SCAN); + assert_eq!(hosted.code, 0, "{test}: {}", hosted.dump); + let pinned = cell.tree(); + declined(test, &scan(&cell, &[]), &purl, rows[0].3); + let eject = socket_patch(&cell, &standin, home.path(), &["vendor", "--yes"]); + assert_eq!(eject.code, 1, "{test}: {}", eject.dump); + let refused = &eject.envelope["error"]["code"]; + assert_eq!(*refused, "eject_refused", "{test}: {}", eject.dump); + let kept = eject.envelope["events"][0]["error"].as_str(); + let kept = kept.is_some_and(|why| why.starts_with("kept hosted: ") && why.contains(rows[0].3)); + assert!(kept, "{test}: {}", eject.dump); + assert_eq!(changed(&pinned, &cell.tree()), NOTHING, "{test}"); + assert_eq!(standin.asked(&service), asked, "{test}"); + cell.write(BAZEL_VERSION, "9.3.2\n"); + let origin = standin.origin(); + let eject = ["vendor", "--yes", "--patch-server-url", &origin]; + let eject = socket_patch(&cell, &standin, home.path(), &eject); + assert_eq!(eject.code, 0, "{test}: {}", eject.dump); + let ejected = cell.tree(); + assert_eq!(ejected[&hub_copy(&patch)], patch.package.nupkg, "{test}"); + let appended = format!("{module}\n{}", block(&dir)); + assert_eq!(text(&ejected, MODULE), appended, "{test}: {}", eject.dump); + assert!(!text(&ejected, CONFIG).contains(PATCH_HOST), "{test}"); + + // The user's word, as a flag and as its variable: as without Bazel. + for flag in [true, false] { + let cell = checkout(Some(&module), None); + let before = cell.tree(); + let ran = match flag { + true => scan(&cell, &["--allow-vendored-in-bazel"]), + false => on_machine(&standin, home.path(), |api, env| { + let origin = standin.origin(); + let args = [&VENDORED[..], &["--patch-server-url", &origin]].concat(); + let env = [env, &[("SOCKET_ALLOW_VENDORED_IN_BAZEL", "1")]].concat(); + cell.socket_patch(api, &args, &env) + }), + }; + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + assert_eq!(ran.envelope, without.envelope, "{test}: {}", ran.dump); + assert_eq!(wrote(&cell, &before), as_before, "{test}: {}", ran.dump); + } +} + /// 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 diff --git a/crates/socket-patch-core/src/bazel/block.rs b/crates/socket-patch-core/src/bazel/block.rs new file mode 100644 index 000000000..f5ae5b9b6 --- /dev/null +++ b/crates/socket-patch-core/src/bazel/block.rs @@ -0,0 +1,113 @@ +//! The text of a block that socket-patch keeps in the root `MODULE.bazel`. +//! +//! A block is the lines from a first line of its kind (`# >>> socket-patch: +//! Maven patches for Bazel (...) >>>`) to [`END`]. It is appended to the +//! file and taken out byte for byte, and it is known by its text alone: +//! [`super::maven`] and [`super::nuget`] each render what they keep there, +//! and a block that is not, byte for byte, what its owner renders for what +//! it names was changed by hand. This module holds what the two share: +//! where a block is, how one is put into a file and taken out of it, and +//! the file as it reads without one. + +use std::ops::Range; + +use crate::utils::line_endings::terminator; + +/// The last line of a block. +pub(super) const END: &str = "# <<< socket-patch <<<"; + +/// What a `MODULE.bazel` holds of the block whose first line is `begin`. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Found { + None, + /// From the first byte of its first line to the last of [`END`], and + /// the number of its first line. + At(Range, usize), + /// A second first line, one that is not as it is written, or no + /// [`END`]: the line of the first one. + Edited(usize), +} + +/// Whether `line` is the first line of the block of `begin`, as it is +/// written or touched (a blank after it, another end): `begin` up to its +/// bracket. A file without such a line holds no such block. +pub(super) fn begins(line: &str, begin: &str) -> bool { + let mark = begin.split(" (").next().unwrap_or(begin); + line.trim_start().starts_with(mark) +} + +pub(super) fn find(text: &str, begin: &str) -> Found { + let (mut at, mut first, mut end) = (0, None, None); + for (line, whole) in text.split_inclusive('\n').enumerate() { + let bare = whole.strip_suffix('\n').unwrap_or(whole); + let bare = bare.strip_suffix('\r').unwrap_or(bare); + match (first, end) { + (None, _) if bare == begin => first = Some((at, line + 1)), + // A second first line, or one that is not as it is written. + _ if begins(bare, begin) => { + return Found::Edited(first.map_or(line + 1, |(_, first)| first)); + } + (Some(_), None) if bare == END => end = Some(at + bare.len()), + _ => {} + } + at += whole.len(); + } + match (first, end) { + (None, _) => Found::None, + (Some((start, line)), Some(end)) => Found::At(start..end, line), + (Some((_, line)), None) => Found::Edited(line), + } +} + +/// Whether the block at `at` is `rendered`, whose lines a line feed ends, +/// in the line break of its own lines, whatever the rest of a file with +/// both has. +pub(super) fn is(text: &str, at: &Range, rendered: &str) -> bool { + let block = &text[at.clone()]; + rendered.replace('\n', terminator(block)) == block +} + +/// `module` with the block `rendered` in the place of the one at `at`, in +/// the line break of that one's lines, or as a new one at the end of the +/// file, after one blank line, in the line break of the file +/// ([`terminator`]: the more frequent one of a file with both). A file +/// whose last line has no line break gets a block without one, so that +/// [`cut`] can tell. +pub(super) fn put(module: &str, at: Option>, rendered: &str) -> String { + let ended = module.is_empty() || module.ends_with('\n'); + let eol = terminator(at.as_ref().map_or(module, |at| &module[at.clone()])); + let block = rendered.replace('\n', eol); + match at { + Some(at) => format!("{}{block}{}", &module[..at.start], &module[at.end..]), + None if ended => format!("{module}{eol}{block}{eol}"), + None => format!("{module}{eol}{eol}{block}"), + } +} + +/// `module` without the block at `at` and what [`put`] put before it: the +/// file is then byte for byte what it was before the block. +pub(super) fn cut(module: &str, at: Range) -> String { + let (head, tail) = (&module[..at.start], &module[at.end..]); + // The line break before the block and, when it ends a blank line, that + // line; then the block's own line break or, for a block that ends the + // file without one, the one that was added to the last line. A line + // break is one of either kind: a file can have both. + let cut = + |text: &str| text.len() - text.ends_with('\n') as usize - text.ends_with("\r\n") as usize; + let blank = |head: &str| cut(head) == 0 || head[..cut(head)].ends_with('\n'); + let after = tail.strip_prefix('\r').unwrap_or(tail).strip_prefix('\n'); + let (head, tail) = match after { + Some(tail) if blank(head) => (&head[..cut(head)], tail), + None if tail.is_empty() && blank(head) => (&head[..cut(&head[..cut(head)])], tail), + Some(tail) => (head, tail), + None => (head, tail), + }; + format!("{head}{tail}") +} + +/// `module` as the user wrote it: without the block at `at`, and with +/// every line where it was. +pub(super) fn hidden(module: &str, at: Range) -> String { + let lines = "\n".repeat(module[at.clone()].matches('\n').count()); + format!("{}{lines}{}", &module[..at.start], &module[at.end..]) +} diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 188c8b8d4..a8d185a57 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -42,6 +42,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::ops::Range; use std::path::Path; +use super::block::{self, Found, END}; use super::rc::{declared_release, mentions, ModuleLock}; use super::starlark::{Bound, Call, How, Value}; use super::workspace::{disk, disk_up_to, Doubt, Entry, Extension, Repo, Tag, Workspace}; @@ -51,7 +52,6 @@ use crate::patch::redirect::{ }; use crate::utils::digest::is_hex64_lower; use crate::utils::fs::run_blocking; -use crate::utils::line_endings::terminator; use crate::utils::purl::{parse_maven_purl, purl_qualifier}; use crate::vendor::jvm::layout::artifact_path; @@ -94,10 +94,9 @@ pub const DOWNLOAD: &str = "maven_bazel_download"; pub const FILE: &str = "MODULE.bazel"; pub const SITE_KEY: &str = ""; -/// The first and the last line of the block. +/// The first line of the block. pub const BEGIN: &str = "# >>> socket-patch: Maven patches for Bazel (managed block: socket-patch \ writes and removes it) >>>"; -const END: &str = "# <<< socket-patch <<<"; /// The releases of rules_jvm_external whose way to name the repository of /// a jar was read: `escape(coordinates)` in @@ -145,7 +144,7 @@ pub struct Hub { /// 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 { +pub(super) 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; @@ -375,7 +374,7 @@ pub enum Built<'a> { /// Discovery.java lines 158 and 159 at 7.7.2, 178 and 179 at 8.8.2 and /// 9.3.2). #[derive(Debug, PartialEq, Eq)] -enum Asked { +pub(super) enum Asked { /// No version is given. Nothing, /// A `bazel_dep` asks for this release: Bazel selects it or a newer @@ -410,11 +409,33 @@ fn ordered(version: &str) -> impl Ord + '_ { (identifiers(release), pre.is_empty(), identifiers(pre)) } -/// What the root module of `ws` says of the ruleset's release: by its -/// calls that name the ruleset, a `bazel_dep` and the overrides, which are -/// the functions whose name ends in `_override`. -fn asked(ws: &Workspace) -> Asked { - let named = Some(&Value::Str(EXTENSION.module.to_string())); +impl Asked { + /// The release that is asked for or pinned, for a message. + pub(super) fn wanted(&self) -> &str { + match self { + Asked::Exactly(wanted) | Asked::AtLeast(wanted) => wanted, + Asked::Nothing | Asked::Unknown(_) => "", + } + } + + /// Whether a `MODULE.bazel.lock` that holds the release `selected` is + /// one Bazel has not written since the root asked for another: older + /// than what is asked for, or any other than the one a + /// `single_version_override` pins. + pub(super) fn stale(&self, selected: &str) -> bool { + match self { + Asked::Exactly(pinned) => ordered(pinned) != ordered(selected), + Asked::AtLeast(least) => ordered(least) > ordered(selected), + Asked::Nothing | Asked::Unknown(_) => false, + } + } +} + +/// What the root module of `ws` says of the release of the ruleset +/// `module`: by its calls that name the ruleset, a `bazel_dep` and the +/// overrides, which are the functions whose name ends in `_override`. +pub(super) fn asked(ws: &Workspace, module: &str) -> Asked { + let named = Some(&Value::Str(module.to_string())); let names = |call: &&Call| { call.bind.is_none() && [call.arg("name"), call.arg("module_name")].contains(&named) }; @@ -481,9 +502,7 @@ impl Hubs { Block::None => {} Block::Edited(line) => edited = Some(line), Block::Ours(at, _, patches) => { - let lines = "\n".repeat(module[at.clone()].matches('\n').count()); - let (head, tail) = (&module[..at.start], &module[at.end..]); - hidden = Some(format!("{head}{lines}{tail}")); + hidden = Some(block::hidden(&module, at)); block = patches; } } @@ -503,7 +522,7 @@ impl Hubs { why: "the block that socket-patch keeps there was changed by hand".to_string(), }), ); - let asked = asked(&ws); + let asked = asked(&ws, EXTENSION.module); let overrides = ws.tags(&EXTENSION, "override").calls.into_iter(); let overrides = overrides.map(|Tag { file, call, .. }| { let (replaced, why) = match call.arg("coordinates") { @@ -732,48 +751,26 @@ enum Block { /// touched (a blank after it, another end): [`BEGIN`] up to its bracket. /// A file without such a line holds no block. pub fn begins(line: &str) -> bool { - let mark = BEGIN.split(" (").next().unwrap_or(BEGIN); - line.trim_start().starts_with(mark) + block::begins(line, BEGIN) } fn find(text: &str) -> Block { - let (mut at, mut begin, mut end) = (0, None, None); - for (line, whole) in text.split_inclusive('\n').enumerate() { - let bare = whole.strip_suffix('\n').unwrap_or(whole); - let bare = bare.strip_suffix('\r').unwrap_or(bare); - match (bare, begin, end) { - (BEGIN, None, _) => begin = Some((at, line + 1)), - // A second first line, or one that is not as it is written. - _ if begins(bare) => { - return Block::Edited(begin.map_or(line + 1, |(_, first)| first)); - } - (END, Some(_), None) => end = Some(at + bare.len()), - _ => {} - } - at += whole.len(); - } - let Some((start, line)) = begin else { - return Block::None; + let (at, line) = match block::find(text, BEGIN) { + Found::None => return Block::None, + Found::Edited(line) => return Block::Edited(line), + Found::At(at, line) => (at, line), }; - // In the line break of its own lines, whatever the rest of a file - // with both has. - let ours = end.and_then(|end| { - let (label, entries) = parse(&text[start..end])?; - let written = render(&label, &entries).replace('\n', terminator(&text[start..end])); - (written == text[start..end]).then_some((start..end, label, entries)) - }); - ours.map_or(Block::Edited(line), |(at, label, patches)| { + let ours = parse(&text[at.clone()]); + let ours = ours.filter(|(label, entries)| block::is(text, &at, &render(label, entries))); + ours.map_or(Block::Edited(line), |(label, patches)| { Block::Ours(at, label, patches) }) } /// `module` with `patch` in its block, in the place of any patch for the -/// same repository: in the block that is there, in the line break of its -/// lines, or in a new one at the end of the file, after one blank line, -/// in the line break of the file ([`terminator`]: the more frequent one -/// of a file with both). A file whose last line has no line break gets a -/// block without one, so that [`without`] can tell. `None` when the block -/// that is there was changed by hand. +/// same repository: in the block that is there or in a new one at the end +/// of the file ([`block::put`]). `None` when the block that is there was +/// changed by hand. fn with_patch(module: &str, label: &str, patch: Patch) -> Option { let (at, mut patches) = match find(module) { Block::Edited(_) => return None, @@ -782,14 +779,7 @@ fn with_patch(module: &str, label: &str, patch: Patch) -> Option { }; patches.retain(|other| other.repository() != patch.repository()); patches.push(patch); - let ended = module.is_empty() || module.ends_with('\n'); - let eol = terminator(at.as_ref().map_or(module, |at| &module[at.clone()])); - let block = render(label, &patches).replace('\n', eol); - Some(match at { - Some(at) => format!("{}{block}{}", &module[..at.start], &module[at.end..]), - None if ended => format!("{module}{eol}{block}{eol}"), - None => format!("{module}{eol}{eol}{block}"), - }) + Some(block::put(module, at, &render(label, &patches))) } /// `module` without the patches of its block that `gone` names. With the @@ -801,26 +791,10 @@ pub fn without(module: &str, gone: &mut dyn FnMut(&Patch) -> bool) -> Option (&head[..cut(head)], tail), - None if tail.is_empty() && blank(head) => (&head[..cut(&head[..cut(head)])], tail), - Some(tail) => (head, tail), - None => (head, tail), - }; - Some(format!("{head}{tail}")) + Some(match entries.is_empty() { + true => block::cut(module, at), + false => block::put(module, Some(at), &render(&label, &entries)), + }) } /// What a hosted run does in the root `MODULE.bazel` for one patch. @@ -972,19 +946,7 @@ fn settings( } _ => {} } - // A lock that holds another release than the root now takes is one - // that Bazel has not written since: older than what is asked for, or - // any other than the one a `single_version_override` pins. - let module = EXTENSION.module; - let stale = |selected: &str| match asked { - Asked::Exactly(pinned) => ordered(pinned) != ordered(selected), - Asked::AtLeast(least) => ordered(least) > ordered(selected), - Asked::Nothing | Asked::Unknown(_) => false, - }; - let wanted = match asked { - Asked::Exactly(wanted) | Asked::AtLeast(wanted) => wanted.as_str(), - Asked::Nothing | Asked::Unknown(_) => "", - }; + let (module, wanted) = (EXTENSION.module, asked.wanted()); let why = match (asked, &lock.selected(module)[..]) { (Asked::Unknown(at), _) => format!( "{at} of {module} socket-patch cannot tell which release of the ruleset Bazel \ @@ -994,7 +956,7 @@ fn settings( "Bazel selected {module} {selected}, and how the ruleset names the repository of a \ jar is known for its releases 6.4 to 7.2: update socket-patch" ), - (_, [selected]) if stale(selected) => format!( + (_, [selected]) if asked.stale(selected) => format!( "{FILE} asks for {module} {wanted} and MODULE.bazel.lock holds {selected}: build once \ so that Bazel updates its lock" ), @@ -1346,6 +1308,7 @@ fn notices_blocking(project: &Path, mut purls: Vec) -> Vec<(&'static str #[cfg(test)] pub(crate) mod tests { use super::*; + use crate::utils::line_endings::terminator; /// For the tests of what reads the block elsewhere: the `MODULE.bazel` /// of a checkout whose pinned hub fetches netty's jar, the lock of diff --git a/crates/socket-patch-core/src/bazel/mod.rs b/crates/socket-patch-core/src/bazel/mod.rs index 11f9693cd..242ddba7e 100644 --- a/crates/socket-patch-core/src/bazel/mod.rs +++ b/crates/socket-patch-core/src/bazel/mod.rs @@ -8,6 +8,7 @@ pub const WORKSPACE_FILES: [&str; 4] = ["MODULE.bazel", "REPO.bazel", "WORKSPACE", "WORKSPACE.bazel"]; +mod block; pub mod built; pub mod cargo; pub(crate) mod cargo_bazel; @@ -45,13 +46,30 @@ pub fn bazel_root(project: &Path) -> Option { root_in(&dirs, repo_at_end_of(dirs.clone())) } -/// [`bazel_root`] for the walk `dirs`, which ended at the checkout `repo`. -fn root_in(dirs: &[PathBuf], repo: Option) -> Option { +/// The root of a Bazel workspace above the one `project` is in, within the +/// bounds of [`bazel_root`]: the next directory up that holds one of +/// [`WORKSPACE_FILES`]. Bazel can build the inner workspace from there, as +/// a module of the outer one. +pub fn root_above(project: &Path) -> Option { + let dirs = search_dirs(project); + let above = roots_in(&dirs, repo_at_end_of(dirs.clone())).nth(1); + above.map(|at| dirs[at].clone()) +} + +/// The directories of the walk `dirs`, which ended at the checkout `repo`, +/// that hold one of [`WORKSPACE_FILES`], from the project up: each as its +/// place in `dirs`. +fn roots_in(dirs: &[PathBuf], repo: Option) -> impl Iterator + '_ { let within = repo.filter(|repo| repo.trusted).map_or(1, |_| dirs.len()); - let at = dirs.iter().take(within).position(|dir| { - let marks = |name| std::fs::metadata(dir.join(name)).is_ok_and(|meta| meta.is_file()); + (0..within).filter(|at| { + let marks = |name| std::fs::metadata(dirs[*at].join(name)).is_ok_and(|meta| meta.is_file()); WORKSPACE_FILES.into_iter().any(marks) - })?; + }) +} + +/// [`bazel_root`] for the walk `dirs`, which ended at the checkout `repo`. +fn root_in(dirs: &[PathBuf], repo: Option) -> Option { + let at = roots_in(dirs, repo).next()?; Some(BazelRoot { dir: dirs[at].clone(), project: dirs[0].strip_prefix(&dirs[at]).ok()?.to_path_buf(), @@ -97,11 +115,14 @@ mod tests { (below.dir, below.project), (repo.clone(), PathBuf::from("svc/app")) ); - // The nearest wins, under each name. + // The nearest wins, under each name, and the next one up is the + // workspace above it. + assert_eq!(root_above(&app), None); for name in ["WORKSPACE", "WORKSPACE.bazel", "REPO.bazel", "MODULE.bazel"] { let file = base.join("repo/svc").join(name); fs::write(&file, "").unwrap(); assert_eq!(root(&app), Some(base.join("repo/svc")), "{name}"); + assert_eq!(root_above(&app), Some(repo.clone()), "{name}"); fs::remove_file(&file).unwrap(); } fs::remove_file(repo.join("MODULE.bazel")).unwrap(); @@ -113,6 +134,8 @@ mod tests { let (_tmp, base) = tree(&["repo/.git", "repo/app"], &["MODULE.bazel", "WORKSPACE"]); assert_eq!(bazel_root(&base.join("repo/app")), None); assert_eq!(bazel_root(&base.join("repo")), None); + fs::write(base.join("repo/MODULE.bazel"), "").unwrap(); + assert_eq!(root_above(&base.join("repo/app")), None); } /// `/workspace/proj`: where the disk folds case, the directory diff --git a/crates/socket-patch-core/src/bazel/nuget.rs b/crates/socket-patch-core/src/bazel/nuget.rs index da4b8811e..42995e6a0 100644 --- a/crates/socket-patch-core/src/bazel/nuget.rs +++ b/crates/socket-patch-core/src/bazel/nuget.rs @@ -1,5 +1,6 @@ //! Whether the Bazel build of a workspace takes what hosted mode writes -//! for a NuGet package. +//! for a NuGet package, and what makes it take the copy that vendored mode +//! commits. //! //! rules_csharp hands NuGet packages to Bazel through one tag of a module //! extension. `nuget.from_lock(packages_lock_json = ...)` downloads every @@ -25,17 +26,36 @@ //! [`Hub::against`] tells hosted mode when to write nothing for a package, //! and what to say instead. //! +//! Vendored mode commits the patched package and names its folder as a +//! package source in `nuget.config`, which NuGet takes. The hub reads that +//! line as the URL of a feed, and the next `bazel build` failed: Bazel +//! 9.3.2 crashed in the module extension, 8.8.2 and 7.7.2 refused the URL +//! (`Bad URL`). What the hub does take is a feed `file:`, which +//! Bazel reads from the root of the workspace, with the package at +//! `///..nupkg`. So vendored mode keeps +//! one block at the end of the root `MODULE.bazel` ([`BEGIN`]): a +//! `nuget.from_lock` of its own, after every tag of the user's, whose +//! `feeds` are the folders of the vendored packages and then the sources +//! the hub has without it. [`vendored`] says whether that block can be +//! shown to work in a checkout, [`with_folder`] writes a folder into it and +//! [`without_folder`] takes one out, the block with the last. +//! //! The answer is read from the checkout through [`super::workspace`]: //! `MODULE.bazel` and the files it includes, and the locks the tags name. //! Nothing is evaluated and no Bazel is run. The ruleset has no //! `WORKSPACE` form, so that file is not looked at. +use std::ops::Range; use std::path::Path; use serde::{Deserialize, Serialize}; -use super::starlark::Value; -use super::workspace::{disk, disk_up_to, Entry, Extension, Repo, Tag, Workspace}; +use super::block::{self, Found, END}; +use super::maven::{asked, proxy, Asked}; +use super::rc::{declared_release, mentions, ModuleLock, Release}; +use super::starlark::{How, Value}; +use super::workspace::{disk, disk_up_to, Doubt, Entry, Extension, Repo, Tag, Tags, Workspace}; +use super::BazelRoot; use crate::formats::nuget::lock::{locked_at, nuget_lock_entries, parse_lock}; use crate::formats::nuget::parse_config; use crate::patch::redirect::NUGET_CONFIG_FILE_NAMES as NAMES; @@ -228,11 +248,7 @@ pub fn withheld(project: &Path, config: &str, locks: &[String]) -> Option = listed .filter_map(|entry| entry.file_name().into_string().ok()) @@ -265,6 +281,35 @@ pub fn withheld(project: &Path, config: &str, locks: &[String]) -> Option String { + let parts = root.project.components(); + parts + .map(|part| format!("{}/", part.as_os_str().to_string_lossy())) + .collect() +} + +/// The lock that `tag` reads, for the project in `dir` whose locks are +/// `locks`. `None`: it names none. +fn reads(ws: &Workspace, tag: &Tag, dir: &str, locks: &[String]) -> Option { + let at = format!("{}:{}", tag.file, tag.call.line); + match tag.call.arg("packages_lock_json") { + Some(Value::Str(label)) => { + let label = ws.label(label).filter(|label| label.repo == Repo::Main); + let path = label?.path(); + let ours = |lock: &&String| path.eq_ignore_ascii_case(&format!("{dir}{lock}")); + Some(match locks.iter().find(ours) { + Some(lock) => Read::Ours(lock.clone()), + None => Read::Other(at, path, None), + }) + } + Some(_) => Some(Read::Any(at)), + None => tag.call.unpacks().then_some(Read::Any(at)), + } +} + /// [`withheld`] for the workspace `ws` and the project in its directory /// `dir` (empty, or with a `/` at its end), before the locks of the other /// tags are read. `exact`: a label names `config` only in its own case. @@ -299,18 +344,7 @@ fn judge( _ => None, }; let at = |tag: &Tag| format!("{}:{}", tag.file, tag.call.line); - let read = |tag: &Tag| match tag.call.arg("packages_lock_json") { - Some(Value::Str(_)) => { - let path = file(tag, "packages_lock_json")?.path(); - let ours = |lock: &&String| path.eq_ignore_ascii_case(&format!("{dir}{lock}")); - Some(match locks.iter().find(ours) { - Some(lock) => Read::Ours(lock.clone()), - None => Read::Other(at(tag), path, None), - }) - } - Some(_) => Some(Read::Any(at(tag))), - None => tag.call.unpacks().then(|| Read::Any(at(tag))), - }; + let read = |tag: &Tag| reads(ws, tag, dir, locks); let reads: Vec> = tags.calls.iter().map(read).collect(); let mine = |read: &Option| matches!(read, Some(Read::Ours(_) | Read::Any(_))); let reader = &tags.calls[reads.iter().position(mine)?]; @@ -390,6 +424,17 @@ fn judge( format!("Name those `feeds` in {config} and run this command again"), ) } + // The tag of the block: its feeds are the hub's, as of the last + // vendored run. + _ if tag.call.callee.split('.').next() == Some(PROXY) => ( + format!( + "is the one vendored mode keeps for the vendored NuGet packages of this project, \ + and its `feeds` stand in the place of the package sources of {config}" + ), + "Vendor this package as well (`--mode vendored`), or take the vendored ones out \ + (`socket-patch vendor --revert`), and run this command again" + .to_string(), + ), Some(Value::Str(theirs)) => { // A config of NuGet's in a directory above the project's is // one the same command writes, when it runs there. @@ -435,8 +480,468 @@ fn judge( Some(hub(Some(why), locks)) } +/// The code with which vendored mode declines a NuGet package of a project +/// whose lock the hub reads, where the block cannot be shown to work. +pub const VENDOR_DECLINED: &str = "vendor_nuget_bazel_workspace"; + +/// The file of the block of vendored mode, and the first line of the block. +pub const FILE: &str = super::maven::FILE; +pub const BEGIN: &str = "# >>> socket-patch: NuGet patches for Bazel (managed block: socket-patch \ + writes and removes it) >>>"; +/// The name the block gives its `use_extension`, and how a feed of the +/// block starts that is a folder of vendored mode. +const PROXY: &str = "socket_patch_nuget"; +const FOLDER: &str = "file:.socket/vendor/nuget/"; + +/// The release of rules_csharp and the releases of Bazel the block was +/// built on, with the patch host unreachable. It rests on Bazel reading a +/// relative `file:` URL from the root of the workspace, which no document +/// of Bazel's promises: 9.1.0 has other code for such a URL than 9.0.2 and +/// 9.1.1 (`DownloadManager.java`), so no release is taken for its +/// neighbour's sake. +const RULESET: &str = "0.5.0"; +const BAZELS: [Release; 3] = [(7, 7, 2), (8, 8, 2), (9, 3, 2)]; +const BUILT_ON: &str = "the block was built on Bazel 7.7.2, 8.8.2 and 9.3.2 alone"; + +/// The arguments of a tag beside which the block was built, or which +/// change nothing for it. +const ARGUMENTS: [&str; 6] = [ + "directory_packages_props", + "feeds", + "name", + "nuget_config", + "packages_lock_json", + "use_public_sources", +]; + +/// What the block holds besides the folders of vendored mode, read from +/// the one tag of the workspace. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Feeds { + /// The label of the tag's `use_extension`, as it is written. + label: String, + /// The name the tag gives the hub, where it gives one: a tag without + /// one would give the hub the name `nuget`. + name: Option, + /// The tag's `packages_lock_json`, as it is written. + lock: String, + /// The package sources the hub has without the block, in its order. + sources: Vec, +} + +/// What vendored mode does for the NuGet packages of a project. +#[derive(Debug, PartialEq, Eq)] +pub enum Vendored { + /// What it does without Bazel: the project is in no Bazel workspace, + /// or no `nuget.from_lock` reads a lock of it. + Plain, + /// Nothing: the hub reads a lock of the project, and this is why the + /// block cannot be shown to work. + Declined(String), + /// It keeps the package where a feed of the hub has one, and its + /// folder in the block. + Block(Feeds), +} + +/// What vendored mode does for the NuGet packages of the project at +/// `project`, whose locks are `locks` (paths from the project, with `/` +/// between their parts). +/// +/// The block is written only where the checkout shows that it works: the +/// project is the root of its Bazel workspace, and no workspace lies above +/// it in the checkout; the workspace has one `nuget.from_lock`, a call of +/// its own with every argument written out and none but [`ARGUMENTS`], on +/// a `use_extension` that the block can share, and whose `feeds` no run +/// of vendored mode replaces (a `nuget_config` without a package source +/// gets one); Bazel selected rules_csharp [`RULESET`], and the checkout +/// names one of [`BAZELS`]; no rc file names +/// `--repository_disable_download`, `--vendor_dir` or a remote downloader, +/// and no directory at the root is a vendor directory of Bazel's (it holds +/// `VENDOR.bazel`); and `MODULE.bazel` is a file whose block, if it has +/// one, is as socket-patch wrote it. +/// +/// Not seen: a tag of another Bazel module, whose sources the hub takes +/// after the block's; a module that depends on this one, where Bazel reads +/// the folder from another root; a vendor directory below the first level; +/// `--nofetch`, in an rc file as on the command line; and whatever else +/// the command line tells Bazel. +pub fn vendored(project: &Path, locks: &[String]) -> Vendored { + let Some(root) = super::bazel_root(project).filter(|_| !locks.is_empty()) else { + return Vendored::Plain; + }; + let on_disk = disk(&root.dir); + let module = match on_disk(FILE) { + Entry::Text(module) => module, + _ => String::new(), + }; + // The block is socket-patch's own: the tags are read without it. + let found = find(&module); + let view = |path: &str| match &found { + Block::Ours(at, ..) if path == FILE => Entry::Text(block::hidden(&module, at.clone())), + _ => on_disk(path), + }; + let files = disk_up_to(&root.dir, MAX_LOCK); + let feeds = match ( + gate(&Workspace::read(&view), &files, &prefix(&root), locks), + &found, + ) { + (Vendored::Plain, _) => return Vendored::Plain, + // Its tag reads as one of the user's: said as what it is. + (_, Block::Edited(line)) => { + let edited = "the block that socket-patch keeps there was changed by hand"; + return Vendored::Declined(format!("{FILE}:{line}: {edited}")); + } + (Vendored::Block(feeds), _) => feeds, + (declined, _) => return declined, + }; + let link = std::fs::symlink_metadata(root.dir.join(FILE)).is_ok_and(|meta| meta.is_symlink()); + let listed = std::fs::read_dir(&root.dir).into_iter().flatten().flatten(); + let vendor = { listed }.find(|entry| entry.path().join("VENDOR.bazel").is_file()); + let why = match (vendor, super::root_above(project)) { + _ if link => { + format!("{FILE} is a symbolic link, which socket-patch does not write through") + } + (Some(vendor), _) => format!( + "{}/VENDOR.bazel: the checkout holds a vendor directory of Bazel's, from which Bazel \ + can build the unpatched package", + vendor.file_name().to_string_lossy() + ), + (_, Some(above)) => format!( + "{} holds a Bazel workspace above this one, and a build from there reads the block's \ + folder from that root", + crate::utils::pnpm_workspace::without_verbatim_prefix(above).display() + ), + _ => return Vendored::Block(feeds), + }; + Vendored::Declined(why) +} + +/// [`vendored`] for the workspace `ws`, read without the block, and the +/// project in its directory `dir` (empty, or with a `/` at its end), by +/// what `files` holds beside it: before the checkout itself is looked at. +fn gate(ws: &Workspace, files: &dyn Fn(&str) -> Entry, dir: &str, locks: &[String]) -> Vendored { + let tags = ws.tags(&EXTENSION, "from_lock"); + let mine = |tag: &&Tag| { + let read = reads(ws, tag, dir, locks); + matches!(read, Some(Read::Ours(_) | Read::Any(_))) + }; + match tags.calls.iter().find(mine) { + None => Vendored::Plain, + Some(tag) => match feeds(ws, files, &tags, tag, dir) { + Ok(feeds) => Vendored::Block(feeds), + Err(why) => Vendored::Declined(why), + }, + } +} + +/// What the block holds for the hub of `tag`, the tag of `tags` that reads +/// a lock of the project in `dir`, or why it cannot be shown to work. +fn feeds( + ws: &Workspace, + files: &dyn Fn(&str) -> Entry, + tags: &Tags, + tag: &Tag, + dir: &str, +) -> Result { + let place = |file: &str, line: usize| match line { + 0 => file.to_string(), + line => format!("{file}:{line}"), + }; + let here = format!("{}: this `nuget.from_lock`", place(tag.file, tag.call.line)); + if !dir.is_empty() { + return Err(format!( + "{here} reads the lock of a project below the root of its Bazel workspace, and the \ + block was built for a project at the root alone" + )); + } + if let Some(Doubt { file, line, why }) = ws.doubts.iter().chain(&tags.doubts).next() { + return Err(format!( + "{}: {why}, so socket-patch cannot tell which `nuget.from_lock` tags the workspace has", + place(file, *line) + )); + } + if let Some(other) = tags.calls.iter().find(|other| *other != tag) { + return Err(format!( + "{}: the workspace has more than one `nuget.from_lock`, and the block was built \ + beside one alone", + place(other.file, other.call.line) + )); + } + let written = "is not a call of its own with every argument written out"; + let against = tag.call.args.iter().find_map(|arg| match &arg.how { + How::Keyword(name) if ARGUMENTS.contains(&name.as_str()) => None, + How::Keyword(name) if name == "local_package_dirs" => Some( + "has `local_package_dirs`, which rules_csharp asks before every feed: with the \ + upstream package in one, the Bazel build fails on the re-pinned `contentHash`" + .to_string(), + ), + How::Keyword(name) => Some(format!("has `{name}`, which the block was not built with")), + _ => Some(written.to_string()), + }); + let against = against.or((!tag.call.whole).then(|| written.to_string())); + if let Some(against) = against { + return Err(format!("{here} {against}")); + } + // What can stand in a string of the block as it is. + let plain = |text: &str| { + let quoted = |b: u8| !b.is_ascii_graphic() || b == b'"' || b == b'\\'; + !text.is_empty() && !text.bytes().any(quoted) + }; + let string = |name: &str| match tag.call.arg(name) { + None => Ok(None), + Some(Value::Str(text)) if plain(text) => Ok(Some(text.clone())), + Some(_) => Err(format!("{here} has a `{name}` that is no plain string")), + }; + let (Some(lock), name) = (string("packages_lock_json")?, string("name")?) else { + return Err(format!("{here} {written}")); + }; + let Some(label) = proxy(ws, tag).filter(|_| tag.dev_dependency == Some(false)) else { + return Err(format!( + "{here} is called on a `use_extension` that is isolated, a dev dependency or not \ + written plainly, which a block of its own does not share" + )); + }; + // The sources of the tag's config, where it has any, stand in the + // place of its feeds: without the folders vendored mode names there. + let feeds = match tag.call.arg("feeds") { + None => Vec::new(), + Some(Value::List(feeds)) => feeds.clone(), + Some(_) => { + return Err(format!( + "{here} has `feeds` that are no list of plain strings" + )) + } + }; + let named = string("nuget_config")?; + let config = match &named { + None => Vec::new(), + Some(named) => { + let file = ws.label(named).filter(|label| label.repo == Repo::Main); + match file.map(|label| files(&label.path())) { + Some(Entry::Text(config)) => sources(&config), + _ => { + let unread = "as its `nuget_config`, which cannot be read"; + return Err(format!("{here} names `{named}` {unread}")); + } + } + } + }; + let own = |source: &String| !source.starts_with(&FOLDER["file:".len()..]); + let config: Vec = config.into_iter().filter(own).collect(); + // A config without a source gets one with the folder of the patch + // (nuget.org beside it, where NuGet had that by default): read on the + // next run, the file's sources would stand in the place of the feeds. + if let Some(named) = named.filter(|_| config.is_empty() && !feeds.is_empty()) { + return Err(format!( + "{here} has `feeds`, and its `nuget_config` `{named}` names no package source, where \ + vendored mode names its folder: rules_csharp would then take the sources of that \ + file in place of those `feeds`, so name those `feeds` in that file" + )); + } + let sources = if config.is_empty() { feeds } else { config }; + if !sources.iter().all(|source| plain(source)) { + return Err(format!( + "{here} has a package source that cannot stand in a string of {FILE}" + )); + } + + let module = EXTENSION.module; + let selected = match files("MODULE.bazel.lock") { + Entry::Text(lock) => ModuleLock::parse(&lock), + _ => ModuleLock::default(), + }; + let asked = asked(ws, module); + match (&asked, &selected.selected(module)[..]) { + (Asked::Unknown(at), _) => Err(format!( + "{at} of {module} socket-patch cannot tell which release of the ruleset Bazel builds \ + with, and the block was built with {module} {RULESET} alone" + )), + (_, [selected]) if asked.stale(selected) => Err(format!( + "{FILE} asks for {module} {} and MODULE.bazel.lock holds {selected}: build once so \ + that Bazel updates its lock", + asked.wanted() + )), + (_, [selected]) if *selected != RULESET => Err(format!( + "Bazel selected {module} {selected}, and the block was built with {module} {RULESET} \ + alone" + )), + (_, [_]) => Ok(()), + _ => Err(format!( + "MODULE.bazel.lock does not say which release of {module} Bazel selected: build once \ + so that Bazel writes its lock" + )), + }?; + match declared_release(files) { + Some(release) if BAZELS.contains(&release) => Ok(()), + Some((major, minor, patch)) => Err(format!( + "the checkout names Bazel {major}.{minor}.{patch} (`.bazeliskrc` or `.bazelversion`), \ + and {BUILT_ON}" + )), + None => Err(format!( + "no file of the checkout names the Bazel release that builds it, and {BUILT_ON}: \ + name the release in `.bazelversion`" + )), + }?; + let unfetched = "under which Bazel may not take the committed package"; + let remote = "which the block was not built with: a remote downloader takes no `file:` feed"; + let words = [ + "repository_disable_download", + "vendor_dir", + "remote_downloader", + ]; + match mentions(files, &words) { + Ok(named) => named + .into_iter() + .next() + .map_or(Ok(()), |(file, line, word)| { + let why = match word.contains(words[2]) { + true => remote, + false => unfetched, + }; + Err(format!("{file}:{line} names `{word}`, {why}")) + }), + Err(file) => Err(format!( + "the rc file {file} cannot be read, and may name an option {unfetched}" + )), + }?; + Ok(Feeds { + label, + name, + lock, + sources, + }) +} + +/// The package sources of the `nuget.config` text `config` as rules_csharp +/// reads them (`_parse_nuget_config` in `csharp/extensions.bzl` at 0.5.0): +/// between the first `` and the `` after +/// it, line by line, the `value` of each line that starts with ` Vec { + let inside = config.split_once(""); + let inside = inside.and_then(|(_, rest)| rest.split_once("")); + let mut sources = Vec::new(); + for line in inside.map_or("", |(inside, _)| inside).split(['\n', '\r']) { + let line = line.trim(); + let value = |quote: char| { + let (_, value) = line.split_once(&format!("value={quote}"))?; + Some(value.split_once(quote)?.0.to_string()) + }; + if line.starts_with("") || line.contains("") { + sources.clear(); + } else if line.starts_with(" String { + let folders = folders.iter().map(|folder| format!("file:{folder}")); + let listed: String = folders + .chain(feeds.sources.iter().cloned()) + .map(|feed| format!(" \"{feed}\",\n")) + .collect(); + let name = feeds + .name + .as_ref() + .map(|name| format!(" name = \"{name}\",\n")); + format!( + "{BEGIN}\n{PROXY} = use_extension(\"{}\", \"nuget\")\n{PROXY}.from_lock(\n \ + feeds = [\n{listed} ],\n{} packages_lock_json = \"{}\",\n)\n{END}", + feeds.label, + name.unwrap_or_default(), + feeds.lock + ) +} + +/// What a `MODULE.bazel` holds of the block. +#[derive(Debug, PartialEq, Eq)] +enum Block { + None, + /// The block as socket-patch writes it: where it is, and what it + /// holds, the folders apart. + Ours(Range, Feeds, Vec), + /// A block that is not what socket-patch writes for what it names: + /// the line of its [`BEGIN`]. + Edited(usize), +} + +fn find(text: &str) -> Block { + let (at, line) = match block::find(text, BEGIN) { + Found::None => return Block::None, + Found::Edited(line) => return Block::Edited(line), + Found::At(at, line) => (at, line), + }; + let lines: Vec<&str> = text[at.clone()].lines().collect(); + let between = |open: &str, close: &str| { + let inside = |line: &&str| Some(line.strip_prefix(open)?.strip_suffix(close)?.to_string()); + lines.iter().filter_map(inside).collect::>() + }; + let one = |open: &str, close: &str| between(open, close).into_iter().next(); + let label = one(&format!("{PROXY} = use_extension(\""), "\", \"nuget\")"); + let lock = one(" packages_lock_json = \"", "\","); + let listed = between(" \"", "\",").into_iter(); + let (folders, sources): (Vec, Vec) = + listed.partition(|feed| feed.starts_with(FOLDER)); + let folders: Vec = folders + .iter() + .map(|feed| feed["file:".len()..].into()) + .collect(); + let ours = label.zip(lock).map(|(label, lock)| Feeds { + label, + name: one(" name = \"", "\","), + lock, + sources, + }); + let ours = ours.filter(|feeds| block::is(text, &at, &render(feeds, &folders))); + ours.map_or(Block::Edited(line), |feeds| Block::Ours(at, feeds, folders)) +} + +/// `module`, the text of the root `MODULE.bazel`, with the folder `folder` +/// of a vendored package (from the Bazel root) in the block for `feeds`: +/// in the block that is there, which then holds what `feeds` holds now, or +/// in a new one at the end of the file ([`block::put`]). `None` when the +/// block that is there was changed by hand. +pub fn with_folder(module: &str, feeds: &Feeds, folder: &str) -> Option { + let (at, mut folders) = match find(module) { + Block::Edited(_) => return None, + Block::None => (None, Vec::new()), + Block::Ours(at, _, folders) => (Some(at), folders), + }; + folders.retain(|other| other != folder); + folders.push(folder.to_string()); + folders.sort(); + Some(block::put(module, at, &render(feeds, &folders))) +} + +/// `module` without the folder `folder` in its block. With the last folder +/// the block goes, and what [`with_folder`] put before it: the file is then +/// byte for byte what it was before its first folder. A file without a +/// block is given as it is. `Err` when the block was changed by hand: the +/// line of the file at which it starts. +pub fn without_folder(module: &str, folder: &str) -> Result { + let (at, feeds, mut folders) = match find(module) { + Block::Edited(line) => return Err(line), + Block::None => return Ok(module.to_string()), + Block::Ours(at, feeds, folders) => (at, feeds, folders), + }; + folders.retain(|other| other != folder); + Ok(match folders.is_empty() { + true => block::cut(module, at), + false => block::put(module, Some(at), &render(&feeds, &folders)), + }) +} + #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::super::workspace::Entry; use super::*; @@ -1051,4 +1556,486 @@ mod tests { assert!(read(&root).is_some()); assert_eq!(withheld(&root, "nuget.config", &[]), None); } + + /// What a checkout holds beside its `MODULE.bazel` where the block can + /// be shown to work: Bazel's lock, which says that rules_csharp 0.5.0 + /// was selected, the release of the Bazel that builds it, and the + /// config the fixture's tag names. + const SELECTED: &str = r#"{"lockFileVersion": 28, "registryFileHashes": { + "https://bcr.bazel.build/modules/rules_csharp/0.5.0/source.json": "sum"}}"#; + const CONFIG: &str = r#" + + + + + + +"#; + const NUGET_ORG: &str = "https://api.nuget.org/v3/index.json"; + /// A config whose one source is a folder of vendored mode. + const OWN: &str = "\n\n"; + const LABEL: &str = "@rules_csharp//csharp:extensions.bzl"; + + /// For the tests of what vendors a package elsewhere: makes `dir` the + /// root of a Bazel workspace whose one tag reads the project's lock and + /// config, where the block can be shown to work. Gives its + /// `MODULE.bazel`. + pub(crate) fn checkout(dir: &Path) -> String { + let module = module(WIRED); + let files = [ + (FILE, module.as_str()), + ("MODULE.bazel.lock", SELECTED), + (".bazelversion", "9.3.2\n"), + ]; + for (name, text) in files { + std::fs::write(dir.join(name), text).unwrap(); + } + module + } + + /// What [`gate`] makes of the project at the root of the workspace + /// whose `MODULE.bazel` is [`module`] with `rest`, beside the files of + /// a checkout whose block works, with `more` in the place of those of + /// the same name (`None`: the file is not there). + fn gated(rest: &str, more: &[(&str, Option<&str>)]) -> Vendored { + let module = module(rest); + let files = [ + (FILE, module.as_str()), + ("MODULE.bazel.lock", SELECTED), + (".bazelversion", "9.3.2\n"), + ("nuget.config", CONFIG), + ]; + let view = |path: &str| { + let given = more.iter().find(|(name, _)| *name == path); + let text = match given { + Some((_, text)) => *text, + None => files.iter().find(|(name, _)| *name == path).map(|f| f.1), + }; + text.map_or(Entry::Absent, |text| Entry::Text(text.to_string())) + }; + let lock = ["packages.lock.json".to_string()]; + gate(&Workspace::read(&view), &view, "", &lock) + } + + /// The block of [`gated`], when it is one. + fn block_of(rest: &str, more: &[(&str, Option<&str>)]) -> Feeds { + match gated(rest, more) { + Vendored::Block(feeds) => feeds, + other => panic!("{rest}: {other:?}"), + } + } + + fn feeds(name: Option<&str>, sources: &[&str]) -> Feeds { + Feeds { + label: LABEL.to_string(), + name: name.map(String::from), + lock: "//:packages.lock.json".to_string(), + sources: sources.iter().map(|source| source.to_string()).collect(), + } + } + + #[test] + fn the_block_holds_what_the_hub_has_without_it() { + // The sources of the tag's config, as the fixture has them. + assert_eq!(block_of(WIRED, &[]), feeds(None, &[NUGET_ORG])); + // A tag without a config, and one with feeds: nothing, the feeds. + assert_eq!(block_of(BARE, &[]), feeds(None, &[])); + let fed = BARE.replace(")", ", feeds = [\"https://a.example/v3/index.json\"])"); + let a = ["https://a.example/v3/index.json"]; + assert_eq!(block_of(&fed, &[]), feeds(None, &a)); + // The sources of a config stand in the place of the feeds. The + // folders vendored mode names there are none of the hub's. + let both = WIRED.replace( + "nuget_config", + "feeds = [\"https://a.example\"],\n nuget_config", + ); + assert_eq!(block_of(&both, &[]), feeds(None, &[NUGET_ORG])); + let only_own = [("nuget.config", Some(OWN))]; + assert_eq!(block_of(WIRED, &only_own), feeds(None, &[])); + let none = WIRED.replace("nuget_config", "feeds = [],\n nuget_config"); + assert_eq!(block_of(&none, &only_own), feeds(None, &[])); + // The name of the hub goes with it, and what changes nothing for + // the block is passed over. + let named = WIRED.replace( + "nuget_config", + "name = \"packages\",\n use_public_sources = False,\n nuget_config", + ); + assert_eq!(block_of(&named, &[]), feeds(Some("packages"), &[NUGET_ORG])); + // The label of the extension is the one the tag is called on. + let renamed = module(WIRED) + .replace("\"0.5.0\")", "\"0.5.0\", repo_name = \"csharp\")") + .replace("@rules_csharp//", "@csharp//"); + let view = |path: &str| match path { + FILE => Entry::Text(renamed.clone()), + "MODULE.bazel.lock" => Entry::Text(SELECTED.to_string()), + ".bazelversion" => Entry::Text("7.7.2\n".to_string()), + "nuget.config" => Entry::Text(CONFIG.to_string()), + _ => Entry::Absent, + }; + let lock = ["packages.lock.json".to_string()]; + let Vendored::Block(read) = gate(&Workspace::read(&view), &view, "", &lock) else { + panic!("no block"); + }; + assert_eq!(read.label, "@csharp//csharp:extensions.bzl"); + } + + #[test] + fn a_project_whose_lock_no_tag_reads_is_vendored_as_without_bazel() { + for rest in [ + String::new(), + BARE.replace("//:", "//api:"), + BARE.replace("//:", "@other//:"), + "nuget.from_lock()".to_string(), + // Also where the block could not be shown to work. + format!("{}\nMORE = [nuget]", BARE.replace("//:", "//api:")), + ] { + assert_eq!(gated(&rest, &[]), Vendored::Plain, "{rest}"); + let unnamed = [(".bazelversion", None)]; + assert_eq!(gated(&rest, &unnamed), Vendored::Plain, "{rest}"); + } + } + + #[test] + fn the_block_is_declined_where_it_cannot_be_shown_to_work() { + let with = + |more: &str| WIRED.replace("nuget_config", &format!("{more},\n nuget_config")); + let isolated = module(WIRED).replace("\"nuget\")", "\"nuget\", isolate = True)"); + let dev = module(WIRED).replace("\"nuget\")", "\"nuget\", dev_dependency = True)"); + let quoted = "\n\n\ + "; + let pinned = "single_version_override(module_name = \"rules_csharp\", version = \"0.4.0\")"; + let archive = "archive_override(module_name = \"rules_csharp\", urls = [\"https://a\"])"; + let newer = SELECTED.replace("0.5.0", "0.6.0"); + // What the workspace holds after its module line, the files beside + // it, and what the reason says. + type Row<'a> = (String, Vec<(&'a str, Option<&'a str>)>, &'a str); + let rows: Vec = + vec![ + // The tags. + ( + format!("{WIRED}\n{}", BARE.replace("//:", "//api:")), + vec![], + "MODULE.bazel:8: the workspace has more than one `nuget.from_lock`", + ), + ( + format!("{WIRED}\nMORE = [nuget]"), + vec![], + "MODULE.bazel:8: `nuget` is used other than to call a tag, so socket-patch cannot \ + tell which `nuget.from_lock` tags the workspace has", + ), + ( + "nuget.from_lock(**TAG)".to_string(), + vec![], + "MODULE.bazel:4: this `nuget.from_lock` is not a call of its own with every \ + argument written out", + ), + ( + format!("True and {}", WIRED.replace('\n', " ")), + vec![], + "is not a call of its own with every argument written out", + ), + ( + WIRED.replace("\"//:packages.lock.json\"", "LOCK"), + vec![], + "has a `packages_lock_json` that is no plain string", + ), + ( + with("local_package_dirs = [\"/opt/packages\"]"), + vec![], + "MODULE.bazel:4: this `nuget.from_lock` has `local_package_dirs`, which \ + rules_csharp asks before every feed", + ), + ( + with("netrc = \"//:.netrc\""), + vec![], + "has `netrc`, which the block was not built with", + ), + ( + with("feeds = FEEDS"), + vec![], + "has `feeds` that are no list of plain strings", + ), + ( + WIRED.to_string(), + vec![("nuget.config", None)], + "names `//:nuget.config` as its `nuget_config`, which cannot be read", + ), + ( + WIRED.to_string(), + vec![("nuget.config", Some(quoted))], + "has a package source that cannot stand in a string of MODULE.bazel", + ), + // Feeds beside a config that vendored mode gives its first + // source: an empty one, and one that holds a folder of its own. + ( + with("feeds = [\"https://a.example\"]"), + vec![("nuget.config", Some("\n\n"))], + "MODULE.bazel:4: this `nuget.from_lock` has `feeds`, and its `nuget_config` \ + `//:nuget.config` names no package source, where vendored mode names its \ + folder", + ), + ( + with("feeds = [\"https://a.example\"]"), + vec![("nuget.config", Some(OWN))], + "so name those `feeds` in that file", + ), + ( + WIRED.to_string(), + vec![(FILE, Some(&isolated))], + "is called on a `use_extension` that is isolated, a dev dependency or not \ + written plainly", + ), + ( + WIRED.to_string(), + vec![(FILE, Some(&dev))], + "is called on a `use_extension` that is isolated, a dev dependency or not \ + written plainly", + ), + // The release of the ruleset. + ( + WIRED.to_string(), + vec![("MODULE.bazel.lock", Some(&newer))], + "Bazel selected rules_csharp 0.6.0, and the block was built with rules_csharp \ + 0.5.0 alone", + ), + ( + format!("{WIRED}\n{pinned}"), + vec![], + "MODULE.bazel asks for rules_csharp 0.4.0 and MODULE.bazel.lock holds 0.5.0", + ), + ( + WIRED.to_string(), + vec![("MODULE.bazel.lock", None)], + "MODULE.bazel.lock does not say which release of rules_csharp Bazel selected: \ + build once so that Bazel writes its lock", + ), + ( + format!("{WIRED}\n{archive}"), + vec![], + "MODULE.bazel:8: with this `archive_override` of rules_csharp socket-patch cannot \ + tell which release of the ruleset Bazel builds with", + ), + // The release of Bazel. + ( + WIRED.to_string(), + vec![(".bazelversion", Some("9.1.0\n"))], + "the checkout names Bazel 9.1.0 (`.bazeliskrc` or `.bazelversion`), and the block \ + was built on Bazel 7.7.2, 8.8.2 and 9.3.2 alone", + ), + ( + WIRED.to_string(), + vec![(".bazelversion", None)], + "no file of the checkout names the Bazel release that builds it, and the block \ + was built on Bazel 7.7.2, 8.8.2 and 9.3.2 alone: name the release in \ + `.bazelversion`", + ), + // The rc files. + ( + WIRED.to_string(), + vec![(".bazelrc", Some("build --jobs=4\ncommon --vendor_dir=third_party\n"))], + ".bazelrc:2 names `--vendor_dir=third_party`, under which Bazel may not take the \ + committed package", + ), + ( + WIRED.to_string(), + vec![(".bazelrc", Some("fetch --repository_disable_download\n"))], + ".bazelrc:1 names `--repository_disable_download`", + ), + ( + WIRED.to_string(), + vec![(".bazelrc", Some("common --experimental_remote_downloader=grpcs://a\n"))], + ".bazelrc:1 names `--experimental_remote_downloader=grpcs://a`, which the block \ + was not built with: a remote downloader takes no `file:` feed", + ), + ( + WIRED.to_string(), + vec![(".bazelrc", Some("build 'unclosed\n"))], + "the rc file .bazelrc:1 cannot be read", + ), + ]; + for (rest, more, says) in rows { + let Vendored::Declined(why) = gated(&rest, &more) else { + panic!("not declined: {rest} {more:?}"); + }; + assert!(why.contains(says), "{rest}: {why}"); + } + // A project below the root of its workspace. + let below = module(&WIRED.replace("//:", "//svc/app:")); + let view = |path: &str| match path { + FILE => Entry::Text(below.clone()), + _ => Entry::Absent, + }; + let lock = ["packages.lock.json".to_string()]; + let Vendored::Declined(why) = gate(&Workspace::read(&view), &view, "svc/app/", &lock) + else { + panic!("not declined below the root"); + }; + let says = "MODULE.bazel:4: this `nuget.from_lock` reads the lock of a project below the \ + root of its Bazel workspace"; + assert!(why.starts_with(says), "{why}"); + } + + #[test] + fn the_sources_of_a_config_are_read_as_the_ruleset_reads_them() { + let config = |inside: &str| format!("\n{inside}\n"); + for (inside, read) in [ + ("", vec!["https://a"]), + (" \r\n", vec!["https://a", "b"]), + // A `\n\n", vec!["https://b"]), + ("\n", vec![]), + // No comment is passed over and no entity decoded. + ("", vec!["https://a?x=1&y=2"]), + ] { + assert_eq!(sources(&config(inside)), read, "{inside}"); + } + assert_eq!(sources(""), [""; 0]); + assert_eq!(sources("\n"), [""; 0]); + } + + /// The block as it was built on Bazel 9.3.2, 8.8.2 and 7.7.2, for the + /// patch `7e57ce11-...`. + const FOLDER_A: &str = ".socket/vendor/nuget/7e57ce11-0000-4000-8000-5184602cd3cc"; + const FOLDER_B: &str = ".socket/vendor/nuget/9f6b2c4e-1d3a-4f6b-8c2d-7e5a9b1c3d5f"; + const BLOCK: &str = r#"# >>> socket-patch: NuGet patches for Bazel (managed block: socket-patch writes and removes it) >>> +socket_patch_nuget = use_extension("@rules_csharp//csharp:extensions.bzl", "nuget") +socket_patch_nuget.from_lock( + feeds = [ + "file:.socket/vendor/nuget/7e57ce11-0000-4000-8000-5184602cd3cc", + "https://api.nuget.org/v3/index.json", + ], + packages_lock_json = "//:packages.lock.json", +) +# <<< socket-patch <<<"#; + + #[test] + fn a_folder_is_added_once_and_taken_out_to_the_byte() { + let fixture = feeds(None, &[NUGET_ORG]); + let base = module(WIRED); + let ends = ["\n", "", "\n\n"].map(|end| format!("{}{end}", base.trim_end())); + let crlf = ends[0].replace('\n', "\r\n"); + for module in ends.iter().chain([&crlf]) { + let eol = if module.contains('\r') { "\r\n" } else { "\n" }; + let one = with_folder(module, &fixture, FOLDER_A).expect("a block"); + let block = BLOCK.replace('\n', eol); + let expected = match module.ends_with('\n') { + true => format!("{module}{eol}{block}{eol}"), + false => format!("{module}{eol}{eol}{block}"), + }; + assert_eq!(one, expected); + // Once more: the same text. + assert_eq!(with_folder(&one, &fixture, FOLDER_A), Some(one.clone())); + // A second folder, in the order of their names, and the name + // of a hub that has one. + let named = feeds(Some("packages"), &[NUGET_ORG]); + let two = with_folder(&one, &named, FOLDER_B).expect("two folders"); + let both = + format!(" \"file:{FOLDER_A}\",{eol} \"file:{FOLDER_B}\",{eol}"); + assert!(two.contains(&both), "{two}"); + let name = format!(" ],{eol} name = \"packages\",{eol} packages_lock_json"); + assert!(two.contains(&name), "{two}"); + // The first one out: the block stays for the second, and goes + // with it. The file is then the one of before. + let left = without_folder(&two, FOLDER_A).expect("one folder"); + assert!( + !left.contains(FOLDER_A) && left.contains(FOLDER_B), + "{left}" + ); + assert_eq!(without_folder(&left, FOLDER_B).as_ref(), Ok(module)); + assert_eq!(without_folder(&one, FOLDER_A).as_ref(), Ok(module)); + // A folder that is not there, and a file without a block. + assert_eq!(without_folder(&one, FOLDER_B), Ok(one.clone())); + assert_eq!(without_folder(module, FOLDER_A).as_ref(), Ok(module)); + } + } + + #[test] + fn a_block_that_was_changed_by_hand_is_left_alone() { + let fixture = feeds(None, &[NUGET_ORG]); + let one = with_folder(&module(WIRED), &fixture, FOLDER_A).expect("a block"); + for edited in [ + one.replace("\"https://api.nuget.org/v3/index.json\",\n", ""), + one.replace(" feeds = [", " feeds = [ # ours"), + one.replace("# <<< socket-patch <<<", ""), + one.replace(") >>>", ") >>> "), + format!("{one}{BLOCK}\n"), + ] { + assert_ne!(edited, one); + assert_eq!(with_folder(&edited, &fixture, FOLDER_B), None, "{edited}"); + assert_eq!(without_folder(&edited, FOLDER_A), Err(10), "{edited}"); + } + } + + #[test] + fn a_checkout_is_read_without_the_block_it_holds() { + let tmp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(tmp.path()).unwrap(); + let root = base.join("repo"); + std::fs::create_dir_all(root.join("svc")).unwrap(); + std::fs::create_dir(base.join(".git")).unwrap(); + let lock = ["packages.lock.json".to_string()]; + // No Bazel workspace, and a project without a lock. + assert_eq!(vendored(&root, &lock), Vendored::Plain); + let module = checkout(&root); + assert_eq!(vendored(&root, &[]), Vendored::Plain); + // The tag names a config that is not there yet. + let unread = "as its `nuget_config`, which cannot be read"; + let declined = |why: &str| match vendored(&root, &lock) { + Vendored::Declined(said) => assert!(said.contains(why), "{said}"), + other => panic!("{why}: {other:?}"), + }; + declined(unread); + std::fs::write(root.join("nuget.config"), CONFIG).unwrap(); + let Vendored::Block(read) = vendored(&root, &lock) else { + panic!("no block"); + }; + assert_eq!(read, feeds(None, &[NUGET_ORG])); + // With its own block in the file the workspace reads as before: + // the block's tag is no second tag. + let wired = with_folder(&module, &read, FOLDER_A).expect("a block"); + std::fs::write(root.join(FILE), &wired).unwrap(); + assert_eq!(vendored(&root, &lock), Vendored::Block(read)); + // A block that was changed by hand. + std::fs::write( + root.join(FILE), + wired.replace(" feeds = [", " feeds = [ "), + ) + .unwrap(); + declined("MODULE.bazel:10: the block that socket-patch keeps there was changed by hand"); + std::fs::write(root.join(FILE), &module).unwrap(); + // A vendor directory of Bazel's, and a workspace above this one. + std::fs::write(root.join("svc/VENDOR.bazel"), "").unwrap(); + declined("svc/VENDOR.bazel: the checkout holds a vendor directory of Bazel's"); + std::fs::remove_file(root.join("svc/VENDOR.bazel")).unwrap(); + std::fs::write(base.join("MODULE.bazel"), "").unwrap(); + declined("holds a Bazel workspace above this one"); + assert_eq!(crate::bazel::root_above(&root), Some(base.clone())); + std::fs::remove_file(base.join("MODULE.bazel")).unwrap(); + assert_eq!(crate::bazel::root_above(&root), None); + // A project below the root, whose lock the tag does not read. + assert_eq!(vendored(&root.join("svc"), &lock), Vendored::Plain); + // The file is a link to a file of the workspace. + #[cfg(unix)] + { + std::fs::rename(root.join(FILE), root.join("svc/module")).unwrap(); + std::os::unix::fs::symlink(root.join("svc/module"), root.join(FILE)).unwrap(); + declined("MODULE.bazel is a symbolic link"); + } + } + + #[test] + fn a_hosted_pin_beside_the_block_of_vendored_mode_is_withheld() { + let wired = with_folder(&module(WIRED), &feeds(None, &[NUGET_ORG]), FOLDER_A); + let said = said(&[("MODULE.bazel", &wired.expect("a block"))], "").expect("withheld"); + let starts = "MODULE.bazel:12: this `nuget.from_lock` is the one vendored mode keeps for \ + the vendored NuGet packages of this project, and its `feeds` stand in the \ + place of the package sources of nuget.config"; + assert!(said.starts_with(starts), "{said}"); + let way = "So hosted mode wrote nothing for it. Vendor this package as well (`--mode \ + vendored`), or take the vendored ones out (`socket-patch vendor --revert`), and \ + run this command again"; + assert!(said.contains(way), "{said}"); + } } diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 2243aa74d..bc59daf6b 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -20,7 +20,7 @@ //! | gem | gem dir (+gemspec) | Gemfile `path:` + Gemfile.lock PATH pair | //! | pypi | rebuilt wheel | per manifest flavor: uv, poetry, pdm, pipenv, requirements ([`pypi`] routes) | //! | maven | patched jar | suffixed `-socket.` tree under `.socket/vendor/maven2` + pom pin, `.mvn/maven.config` (or Gradle / sbt / scala-cli wiring) ([`maven_repo`] routes to [`jvm`]) | -//! | nuget | rebuilt nupkg | folder feed + `nuget.config` + `packages.lock.json` pin ([`nuget_feed`]) | +//! | nuget | rebuilt nupkg | folder feed + `nuget.config` + `packages.lock.json` pin, and under a rules_csharp hub a block in the root `MODULE.bazel` ([`nuget_feed`]) | //! //! npm requests route through [`npm_flavor`], which content-sniffs the //! project's lockfile (not just file presence) and dispatches to the diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index 621d80c33..1e39f41fb 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -4,12 +4,16 @@ use std::sync::Arc; use crate::utils::digest::sha512_base64_of; use serde_json::Value; +use crate::bazel::nuget::{ + vendored, with_folder, without_folder, Feeds, Vendored, VENDOR_DECLINED, +}; use crate::manifest::schema::PatchRecord; use crate::patch::apply::{ApplyResult, PatchSources}; use crate::patch::copy_tree::remove_tree; use crate::patch::path_safety::{is_safe_multi_segment, is_safe_single_segment}; +use crate::utils::env_compat::env_flag; use crate::utils::fs::{ - atomic_write_artifact, atomic_write_bytes_preserving_mode, read_regular_to_string, + atomic_write_artifact, atomic_write_bytes_preserving_mode, read_regular_to_string, run_blocking, }; use crate::utils::line_endings::{eol_eq, respell, terminator}; use crate::utils::purl::{build_nuget_purl, parse_nuget_purl}; @@ -20,6 +24,7 @@ use super::common::{ }; use super::parse_memo::ParseMemo; use super::path::vendor_uuid_dir_rel; +use super::refusals::ALLOW_IN_BAZEL_ENV; use super::revert::{self, KeepPolicy}; use super::service_fetch::service_archive_copy; use super::state::{ @@ -40,6 +45,12 @@ use crate::formats::nuget::lock::{locked_at, PACKAGES_LOCK}; const CONFIG_SOURCE_WIRING_KIND: &str = "nuget_config_source"; const CONFIG_MAPPING_WIRING_KIND: &str = "nuget_config_mapping"; const LOCK_WIRING_KIND: &str = "nuget_lock_entry"; +/// The folder of the patch in the block of the root `MODULE.bazel` +/// ([`crate::bazel::nuget`]): the revert takes that folder out of the +/// block, whatever the record says. +pub(super) const BAZEL_WIRING_KIND: &str = "nuget_bazel_feed"; +/// The file of that block. +const MODULE_FILE: &str = crate::bazel::nuget::FILE; /// `/.gitignore`, exactly: re-include the vendored nupkg against the /// user's ignore rules (VisualStudio.gitignore's `*.nupkg`), #1061. @@ -120,10 +131,20 @@ struct NugetPrelude { version: String, version_norm: String, uuid_dir_rel: String, + /// The folder `nuget.config` names for the patch: [`Self::uuid_dir_rel`], + /// or below it `/` for a package of a + /// rules_csharp hub, where a feed of the hub has it. + feed_rel: String, copy_rel: String, uuid_dir: PathBuf, nupkg_path: PathBuf, source_key: String, + /// What the block of the root `MODULE.bazel` holds beside the folder + /// of the patch. `None`: the package has no folder there. + feeds: Option, + /// Why the block of a package that is wired for a hub can no longer + /// be shown to work. + hub_doubt: Option, config_path: Option, config_text: Option, /// Every lock the projects under the root restore into (#353, #514). @@ -174,9 +195,8 @@ async fn nuget_prelude( let id_lower = name.to_lowercase(); let version_norm = normalize_nuget_version(version); let leaf = nupkg_leaf(&id_lower, version); - let copy_rel = format!("{uuid_dir_rel}/{leaf}"); let uuid_dir = project_root.join(&uuid_dir_rel); - let nupkg_path = project_root.join(©_rel); + let nupkg_path = uuid_dir.join(&leaf); let source_key = crate::patch::redirect::generation::hosted_pin_name(&record.uuid); // The nupkg must survive the commit the vendored workflow ends with: a @@ -230,6 +250,7 @@ async fn nuget_prelude( )); } let mut locks: Vec = Vec::with_capacity(governed.locks.len()); + let governed_rels = governed.locks.clone(); for rel in governed.locks { let path = project_root.join(&rel); match read_regular_to_string(&path).await { @@ -247,10 +268,46 @@ async fn nuget_prelude( // The idempotent hot path's test (see `vendor_nuget`): a live // `` source under our key. A commented-out one — or the // key merely mentioned elsewhere — is not wiring NuGet reads. - let config_wired = config_text + let named = config_text .as_deref() .and_then(crate::formats::nuget::parse_config) - .is_some_and(|parsed| parsed.sources.iter().any(|(key, _)| *key == source_key)); + .and_then(|parsed| { + parsed + .sources + .into_iter() + .find(|(key, _)| *key == source_key) + }); + let config_wired = named.is_some(); + // Where the package lies. A rules_csharp hub that reads a lock of the + // project takes it from `///`, through the + // block of the root MODULE.bazel; every other project keeps it in the + // folder itself. A package that is wired stays where the config names + // it, and only one that lies where a hub has it is the hub's. + let nested = format!("{uuid_dir_rel}/{id_lower}/{version_norm}"); + let for_hub = named.is_some_and(|(_, value)| value == nested); + let hub = match config_wired && !for_hub { + true => Vendored::Plain, + false => { + let root = project_root.to_path_buf(); + run_blocking(move || vendored(&root, &governed_rels)).await + } + }; + let (feeds, hub_doubt) = match hub { + Vendored::Block(feeds) => (Some(feeds), None), + Vendored::Declined(why) if for_hub => (None, Some(why)), + // The caller's own refusal ([`bazel_refusals`]) comes first; this + // one holds for every way in. + Vendored::Declined(why) if !env_flag(ALLOW_IN_BAZEL_ENV) => { + return Err(refused(VENDOR_DECLINED, declined_detail(&why))); + } + _ => (None, None), + }; + let feed_rel = match for_hub || feeds.is_some() { + true => nested, + false => uuid_dir_rel.clone(), + }; + let copy_rel = format!("{feed_rel}/{leaf}"); + let nupkg_path = project_root.join(©_rel); // The mapping routes every version of the id to this feed, which serves // only the patched one: a framework that locks another version could no // longer restore (NU1102). Refused before anything is wired (#593). @@ -308,10 +365,13 @@ async fn nuget_prelude( version: version.to_string(), version_norm, uuid_dir_rel, + feed_rel, copy_rel, uuid_dir, nupkg_path, source_key, + feeds, + hub_doubt, config_path, config_text, locks, @@ -320,6 +380,112 @@ async fn nuget_prelude( }) } +/// What a declined package is told after `why`, the reason of +/// [`vendored`]: what vendored mode would have needed, and the two ways on. +fn declined_detail(why: &str) -> String { + format!( + "{why}; vendored mode makes a rules_csharp hub take the committed package through a \ + block in the root {MODULE_FILE}, which it writes only where the checkout shows that the \ + block works, so it wrote nothing for this package; use `--mode hosted`, or pass \ + `--allow-vendored-in-bazel` to vendor the package as in a project without Bazel, which \ + the hub does not take: its build then fails" + ) +} + +/// The NuGet `candidates` (`(purl, uuid)` pairs) that vendored mode +/// declines in the project at `project_root`, each with [`VENDOR_DECLINED`] +/// and the detail: those of a project whose lock a rules_csharp hub reads, +/// where the block cannot be shown to work ([`vendored`]), unless the user +/// allowed it ([`ALLOW_IN_BAZEL_ENV`]). A package whose folder +/// `nuget.config` already names is let through: the run leaves the config +/// as it is. Read-only, and it starts no program. +pub(crate) async fn bazel_refusals<'a>( + project_root: &Path, + candidates: &[(&'a str, &str)], +) -> Vec<(&'a str, &'static str, String)> { + if candidates.is_empty() || env_flag(ALLOW_IN_BAZEL_ENV) { + return Vec::new(); + } + let root = project_root.to_path_buf(); + let hub = run_blocking(move || { + let governed = super::nuget_config::governed_locks_on_disk(&root); + vendored( + &root, + &governed.map(|governed| governed.locks).unwrap_or_default(), + ) + }); + let Vendored::Declined(why) = hub.await else { + return Vec::new(); + }; + let config = match existing_config_path(project_root).await { + Some(path) => read_regular_to_string(&path).await.ok(), + None => None, + }; + let sources = config + .as_deref() + .and_then(crate::formats::nuget::parse_config); + let sources = sources.map(|config| config.sources).unwrap_or_default(); + let wired = |uuid: &str| { + let key = crate::patch::redirect::generation::hosted_pin_name(uuid); + let folder = vendor_uuid_dir_rel("nuget", uuid); + let names = |(named, value): &(String, String)| { + *named == key && folder.as_ref().is_some_and(|dir| value.starts_with(dir)) + }; + sources.iter().any(names) + }; + let detail = declined_detail(&why); + let declined = candidates.iter().filter(|(_, uuid)| !wired(uuid)); + declined + .map(|(purl, _)| (*purl, VENDOR_DECLINED, detail.clone())) + .collect() +} + +/// Keep the folder of a patch, `uuid_dir_rel`, in the block of the root +/// `MODULE.bazel`, which then holds what `feeds` holds now. +async fn keep_in_block( + project_root: &Path, + feeds: &Feeds, + uuid_dir_rel: &str, +) -> Result<(), String> { + let path = project_root.join(MODULE_FILE); + let module = read_regular_to_string(&path) + .await + .map_err(|e| format!("unreadable {}: {e}", path.display()))?; + let Some(kept) = with_folder(&module, feeds, uuid_dir_rel) else { + return Err(format!( + "the block that socket-patch keeps in {MODULE_FILE} was changed by hand" + )); + }; + if kept == module { + return Ok(()); + } + atomic_write_bytes_preserving_mode(&path, kept.as_bytes()) + .await + .map_err(|e| format!("failed to write {}: {e}", path.display())) +} + +/// For a package that is wired for a hub: its folder in the block as the +/// hub's tag has it now, or the warning that the block was left as it is, +/// and why. +async fn block_refreshed( + project_root: &Path, + feeds: Option<&Feeds>, + doubt: Option, + uuid_dir_rel: &str, +) -> Option { + let why = match feeds { + Some(feeds) => keep_in_block(project_root, feeds, uuid_dir_rel).await.err(), + None => doubt, + }?; + Some(VendorWarning::new( + VENDOR_DECLINED, + format!( + "{why}; the block of {MODULE_FILE} was left as it is, and socket-patch can no longer \ + show that the Bazel build takes the committed package" + ), + )) +} + /// Whether [`vendor_nuget`] — a wet run with the service enabled — asks the /// patch service for `record`: past every refusal it raises first and not /// answered by the in-sync hot path. The vendor loop's download plan @@ -367,10 +533,13 @@ pub async fn vendor_nuget( version, version_norm, uuid_dir_rel, + feed_rel, copy_rel, uuid_dir, nupkg_path, source_key, + feeds, + hub_doubt, config_path, config_text, locks, @@ -389,10 +558,15 @@ pub async fn vendor_nuget( // first run's ledger entry holds the only copy of the verbatim pre-vendor // originals, and re-recording here would clobber them. if config_wired { + // A package of a hub: the block follows the hub's tag, wired or not. + let block = match dry_run { + true => None, + false => block_refreshed(project_root, feeds.as_ref(), hub_doubt, &uuid_dir_rel).await, + }; if in_sync { // The warning keeps firing on re-runs until the stale copy is // gone (#352). - let mut warnings = Vec::new(); + let mut warnings: Vec = block.into_iter().collect(); if let (Some(cached), Some(bytes)) = ( extracted_content_hash(installed_dir).await, read_zip_artifact(&nupkg_path).await, @@ -424,7 +598,7 @@ pub async fn vendor_nuget( // already correct and the full path would re-record the live vendored // fragments as `original`, breaking a later `--revert`. if !dry_run { - let mut warnings: Vec = Vec::new(); + let mut warnings: Vec = block.into_iter().collect(); let (bytes, mut result) = match materialise_patched_nupkg( purl, installed_dir, @@ -572,7 +746,7 @@ pub async fn vendor_nuget( &inherited.keys, inherited.mapped, &source_key, - &uuid_dir_rel, + &feed_rel, name, ), }; @@ -661,6 +835,24 @@ pub async fn vendor_nuget( } } } + // ── the block of a rules_csharp hub (a failure unwinds both) ───────── + if let Some(feeds) = &feeds { + if let Err(detail) = keep_in_block(project_root, feeds, &uuid_dir_rel).await { + unwind_locks(&written).await; + unwind_config(&config_target, config_text.as_deref(), &uuid_dir).await; + result.success = false; + result.error = Some(detail); + return done(result, None, warnings); + } + lock_records.push(WiringRecord { + file: MODULE_FILE.to_string(), + kind: BAZEL_WIRING_KIND.to_string(), + action: WiringAction::Added, + key: Some(uuid_dir_rel.clone()), + original: None, + new: None, + }); + } if locks.is_empty() { warnings.push(VendorWarning::new( "vendor_nuget_no_lockfile", @@ -726,8 +918,8 @@ pub async fn vendor_nuget( original: None, new: Some(Value::String(config_edit.mapping_fragment.clone())), }; - // Application order: config source, config mapping, then the lock pin. - // Revert runs them in reverse (lock → mapping → source). + // Application order: config source, config mapping, the lock pin, then + // the block of a hub. Revert runs them in reverse. let mut wiring = vec![source_record, mapping_record]; wiring.extend(lock_records); @@ -849,6 +1041,15 @@ pub async fn revert_nuget_opts( version_norm: normalize_nuget_version(&version), source_key: crate::patch::redirect::generation::hosted_pin_name(&entry.uuid), }; + // The folder the config names: the patch's own, or the one below it + // where a hub has the package, when the artifact lies there. + let nested = format!( + "{uuid_dir_rel}/{}/{}", + id.to_lowercase(), + package.version_norm + ); + let for_hub = entry.artifact.path.starts_with(&format!("{nested}/")); + let feed_rel = if for_hub { &nested } else { &uuid_dir_rel }; // SECURITY: state.json is committed and tamper-able, and the records are // replayed one write at a time: every one of them is checked before the // first write, so a refused record leaves the whole entry untouched. @@ -857,6 +1058,14 @@ pub async fn revert_nuget_opts( return RevertOutcome::failed(super::state::refused_record(entry, w, &why)); } } + // Nor beside a block that was changed by hand, which keeps the folder + // of the patch: the hub would hold the committed package to the lock + // that the revert restores, and the Bazel build would fail. + if entry.wiring.iter().any(|w| w.kind == BAZEL_WIRING_KIND) { + if let Err(why) = revert_block_record(project_root, &uuid_dir_rel, true).await { + return RevertOutcome::failed(why); + } + } let mut warnings = Vec::new(); // The lock pin may only go back to the upstream contentHash when @@ -873,7 +1082,7 @@ pub async fn revert_nuget_opts( .filter(|w| w.kind == CONFIG_SOURCE_WIRING_KIND) { if matches!( - revert_config_record(project_root, &uuid_dir_rel, &package, w, true).await, + revert_config_record(project_root, feed_rel, &package, w, true).await, Ok(false) ) && config_references(project_root, &w.file, &uuid_dir_rel).await { @@ -915,8 +1124,9 @@ pub async fn revert_nuget_opts( // record, so there is nothing to undo here. CONFIG_MAPPING_WIRING_KIND => Ok(true), CONFIG_SOURCE_WIRING_KIND => { - revert_config_record(project_root, &uuid_dir_rel, &package, w, dry_run).await + revert_config_record(project_root, feed_rel, &package, w, dry_run).await } + BAZEL_WIRING_KIND => revert_block_record(project_root, &uuid_dir_rel, dry_run).await, _ => { warnings.push(VendorWarning::new( "vendor_lock_entry_drifted", @@ -967,6 +1177,37 @@ pub async fn revert_nuget_opts( revert::finish(outcome, project_root, &uuid_dir_rel, opts, policy).await } +/// Take the folder of a patch, `uuid_dir_rel`, out of the block of the +/// root `MODULE.bazel`: the block goes with its last folder. `Ok(true)` = +/// taken out (or would be on a dry run) / not there; `Err` = the block was +/// changed by hand, with the ways on, or a real I/O failure. +async fn revert_block_record( + project_root: &Path, + uuid_dir_rel: &str, + dry_run: bool, +) -> Result { + let path = project_root.join(MODULE_FILE); + let module = match read_regular_to_string(&path).await { + Ok(module) => module, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(true), + Err(e) => return Err(format!("unreadable {}: {e}", path.display())), + }; + let without = without_folder(&module, uuid_dir_rel).map_err(|line| { + format!( + "{MODULE_FILE}:{line}: the block that socket-patch keeps there was changed by hand, \ + so the folder of this patch stays in it and nothing was reverted: with the lock \ + restored, the Bazel build would fail on the committed package. Put the block back \ + as socket-patch wrote it, or delete it, and run this command again" + ) + })?; + if without != module && !dry_run { + atomic_write_bytes_preserving_mode(&path, without.as_bytes()) + .await + .map_err(|e| format!("failed to restore {}: {e}", path.display()))?; + } + Ok(true) +} + // ── materialisation (service download) ───────────────────────── #[allow(clippy::too_many_arguments)] @@ -1012,9 +1253,12 @@ async fn materialise_patched_nupkg( /// Write `bytes` to `nupkg_path`, creating the uuid dir and its /// re-including `.gitignore`. Errors are strings. async fn write_nupkg(uuid_dir: &Path, nupkg_path: &Path, bytes: &[u8]) -> Result<(), String> { - tokio::fs::create_dir_all(uuid_dir) + // The folder of the patch, or the one below it where a hub has the + // package. + let folder = nupkg_path.parent().unwrap_or(uuid_dir); + tokio::fs::create_dir_all(folder) .await - .map_err(|e| format!("cannot create {}: {e}", uuid_dir.display()))?; + .map_err(|e| format!("cannot create {}: {e}", folder.display()))?; atomic_write_artifact(nupkg_path, bytes) .await .map_err(|e| format!("cannot write {}: {e}", nupkg_path.display()))?; @@ -1046,10 +1290,10 @@ async fn keep_nupkg_committable( nupkg_path: &Path, warnings: &mut Vec, ) -> Result<(), VendorOutcome> { - let leaf = nupkg_path - .file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_default(); + // From the uuid dir, with `/` between its parts: the file itself, or + // below `/` where a hub has the package. + let below = nupkg_path.strip_prefix(uuid_dir).unwrap_or(nupkg_path); + let leaf = below.to_string_lossy().replace('\\', "/"); let shown = nupkg_path.display().to_string(); match super::npm_dir::gitignore_probe(uuid_dir, &[leaf, ".gitignore".to_string()]).await { Ok(Some(rules)) => Err(refused( @@ -1588,6 +1832,8 @@ fn record_refusal(project_root: &Path, package: &OwnPackage, w: &WiringRecord) - ) }) } + BAZEL_WIRING_KIND => (w.file != MODULE_FILE) + .then(|| format!("names a file that is not the root {MODULE_FILE}")), LOCK_WIRING_KIND => { if !is_safe_multi_segment(&w.file) { return unsafe_path(); @@ -6858,4 +7104,272 @@ mod tests { assert!(root.join(format!(".socket/vendor/nuget/{UUID}")).exists()); } } + + // ── a package of a rules_csharp hub ───────────────────────────────── + + /// The three files vendored mode edits for a package of a hub. + fn hub_files(root: &Path) -> [Vec; 3] { + [MODULE_FILE, "nuget.config", PACKAGES_LOCK] + .map(|file| std::fs::read(root.join(file)).unwrap()) + } + + /// In the root of a Bazel workspace whose one `nuget.from_lock` reads + /// the project's lock, the package lies where a feed of the hub has it, + /// `nuget.config` names that folder, and the block of `MODULE.bazel` + /// names the folder of the patch. A second run changes nothing, and + /// the revert puts the three files back byte for byte. + #[tokio::test] + #[serial_test::serial] + async fn a_package_of_a_hub_lies_where_its_feed_has_it_and_goes_to_the_byte() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + let module = crate::bazel::nuget::tests::checkout(root); + let before = hub_files(root); + + let (result, entry, warnings) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("a ledger entry"); + let folder = format!(".socket/vendor/nuget/{UUID}"); + let feed = format!("{folder}/newtonsoft.json/13.0.3"); + assert_eq!( + entry.artifact.path, + format!("{feed}/newtonsoft.json.13.0.3.nupkg") + ); + assert!(root.join(&entry.artifact.path).is_file()); + assert!( + !root.join(copy_rel()).exists(), + "no copy in the folder itself" + ); + let config = std::fs::read_to_string(root.join("nuget.config")).unwrap(); + let source = format!("", source_key()); + assert!(config.contains(&source), "{config}"); + let wired = std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(); + let feeds = format!( + " feeds = [\n \"file:{folder}\",\n \ + \"https://api.nuget.org/v3/index.json\",\n ],\n" + ); + assert!( + wired.starts_with(&module) && wired.contains(&feeds), + "{wired}" + ); + let last = entry.wiring.last().expect("records"); + assert_eq!( + (last.kind.as_str(), last.file.as_str(), last.key.as_deref()), + (BAZEL_WIRING_KIND, MODULE_FILE, Some(folder.as_str())) + ); + assert!(warnings.iter().all(|w| w.code != VENDOR_DECLINED)); + // The committed copy is what the ledger and the check hold it to. + let health = crate::vendor::check_vendored_artifact(root, &entry, &record).await; + assert_eq!(health, crate::vendor::ArtifactHealth::Healthy); + + // Once more: in sync, and no file is written again. + let vendored = hub_files(root); + let (again, rerecorded, warnings) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(again.success && rerecorded.is_none()); + assert!(warnings.iter().all(|w| w.code != VENDOR_DECLINED)); + assert_eq!(hub_files(root), vendored); + + // A record that names another file is not followed. + let mut tampered = entry.clone(); + tampered.wiring.last_mut().unwrap().file = "BUILD.bazel".to_string(); + let refused = revert_nuget(&tampered, root, false).await; + assert!(!refused.success, "{:?}", refused.warnings); + assert_eq!(hub_files(root), vendored); + + let outcome = revert_nuget(&entry, root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); + assert_eq!(hub_files(root), before); + assert!( + !root.join(&folder).exists(), + "the folder of the patch is gone" + ); + } + + /// Where the block cannot be shown to work, the package is declined + /// before anything is asked for or written. With the user's word it is + /// vendored as without Bazel, and a later run without that word leaves + /// it as it is. + #[tokio::test] + #[serial_test::serial] + async fn a_hub_whose_block_cannot_be_shown_to_work_is_declined_unless_allowed() { + let unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + crate::bazel::nuget::tests::checkout(root); + std::fs::remove_file(root.join(".bazelversion")).unwrap(); + let before = hub_files(root); + let candidates = [(PURL, UUID)]; + + let (code, detail) = + unwrap_refused(run_vendor(root, &blobs, &installed, &record, false).await); + assert_eq!(code, VENDOR_DECLINED); + for part in [ + "no file of the checkout names the Bazel release that builds it", + "`--mode hosted`", + "`--allow-vendored-in-bazel`", + ] { + assert!(detail.contains(part), "{detail}"); + } + assert!(!root.join(".socket").exists()); + assert_eq!(hub_files(root), before); + let refused = bazel_refusals(root, &candidates).await; + assert_eq!(refused, [(PURL, VENDOR_DECLINED, detail)]); + assert!(service_preflight(PURL, root, &record).await.is_none()); + drop(unset); + + // The user's word: the package in the folder of the patch, and no + // block. + let allowed = crate::test_env::EnvGuard::set(ALLOW_IN_BAZEL_ENV, "1"); + assert!(bazel_refusals(root, &candidates).await.is_empty()); + let (result, entry, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("a ledger entry"); + assert_eq!(entry.artifact.path, copy_rel()); + assert!(entry.wiring.iter().all(|w| w.kind != BAZEL_WIRING_KIND)); + assert_eq!(hub_files(root)[0], before[0], "{MODULE_FILE} is untouched"); + drop(allowed); + + // Without it again: the package that is wired passes, in sync, and + // another patch of it is declined. + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + assert!(bazel_refusals(root, &candidates).await.is_empty()); + let (again, rerecorded, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(again.success && rerecorded.is_none()); + let other = [(PURL, "33333333-3333-4333-8333-333333333333")]; + assert_eq!(bazel_refusals(root, &other).await.len(), 1); + // And its revert takes it out as any vendored package. + let outcome = revert_nuget(&entry, root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert_eq!(hub_files(root), before); + } + + /// A package that is wired for a hub follows the hub's tag on every + /// run: a source the user adds to `nuget.config` reaches the block. + /// Where the block can no longer be shown to work it is left as it is, + /// with a warning, and so is a block that was changed by hand. Beside + /// that one the revert changes nothing: the lock without its pin would + /// fail the Bazel build on the folder the block still names. With the + /// block deleted by hand, the revert takes out the rest. + #[tokio::test] + #[serial_test::serial] + async fn a_package_that_is_wired_for_a_hub_follows_its_tag() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + let module = crate::bazel::nuget::tests::checkout(root); + let before = hub_files(root); + let (_, entry, _) = unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + let entry = entry.expect("a ledger entry"); + let rerun = || async { + let (result, entry, warnings) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success && entry.is_none(), "{:?}", result.error); + let warned = warnings.into_iter().filter(|w| w.code == VENDOR_DECLINED); + warned.map(|w| w.detail).collect::>() + }; + + let config = std::fs::read_to_string(root.join("nuget.config")).unwrap(); + let mirror = " \n"; + let with_mirror = config.replacen( + " /` in the folder + /// of the patch, and that is the path git is asked about. The folder's + /// own `.gitignore` reaches over every rule above it, so only an + /// ignore file below it can drop the package: it is then refused, and + /// nothing stays written. + #[tokio::test] + #[serial_test::serial] + async fn a_package_of_a_hub_that_git_would_not_commit_is_refused() { + use crate::vendor::test_support::git_project; + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + if git_project(root, "newtonsoft.json/\n").is_none() { + return; + } + crate::bazel::nuget::tests::checkout(root); + let below = root.join(format!(".socket/vendor/nuget/{UUID}/newtonsoft.json")); + std::fs::create_dir_all(&below).unwrap(); + std::fs::write(below.join(".gitignore"), "*.nupkg\n").unwrap(); + let before = hub_files(root); + let (code, detail) = + unwrap_refused(run_vendor(root, &blobs, &installed, &record, false).await); + assert_eq!(code, "vendor_artifact_gitignored", "{detail}"); + assert!(detail.contains("*.nupkg"), "{detail}"); + assert_eq!(hub_files(root), before); + assert!( + !root.join(".socket/vendor").exists(), + "nothing stays written" + ); + + // Without that file the rule of the project is no bar: the folder's + // own `.gitignore` re-includes what lies below it. + let (result, entry, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success && entry.is_some(), "{:?}", result.error); + } } diff --git a/crates/socket-patch-core/src/vendor/path.rs b/crates/socket-patch-core/src/vendor/path.rs index c05fd8f07..bf66d7e7d 100644 --- a/crates/socket-patch-core/src/vendor/path.rs +++ b/crates/socket-patch-core/src/vendor/path.rs @@ -26,7 +26,7 @@ //! | composer | `/@/` | //! | gem | `-/` | //! | pypi | `--.whl` (PEP 427); server sdist: `-.tar.gz` / `.tgz` / `.zip` | -//! | nuget | `..nupkg` | +//! | nuget | `..nupkg`; for a rules_csharp hub: `//..nupkg` | //! | maven | `///-.jar` | use std::path::{Path, PathBuf}; @@ -488,9 +488,13 @@ pub(crate) fn leaf_to_purl(eco: &str, leaf: &str) -> Option { Some(format!("pkg:pypi/{dist}@{version}")) } "nuget" => { - let stem = leaf.strip_suffix(".nupkg")?; + // The file itself, or the same below `//`, + // where a rules_csharp hub has the package. + let (below, file) = leaf.rsplit_once('/').unwrap_or(("", leaf)); + let stem = file.strip_suffix(".nupkg")?; let (name, version) = split_nuget_leaf(stem)?; - if !is_safe_single_segment(version) { + let hub = below == format!("{name}/{version}"); + if !is_safe_single_segment(version) || !(below.is_empty() || hub) { return None; } Some(format!("pkg:nuget/{name}@{version}")) @@ -1069,6 +1073,20 @@ mod tests { // nested leaf whose recovered version would span a `/`. assert!(leaf_to_purl("nuget", ".1.2.3.nupkg").is_none()); assert!(leaf_to_purl("nuget", "foo.1.0/evil.nupkg").is_none()); + // Below `//`, where a rules_csharp hub has the + // package, and below no other directory. + assert_eq!( + leaf_to_purl("nuget", "foo.bar/1.0.0-rc1/foo.bar.1.0.0-rc1.nupkg").as_deref(), + Some("pkg:nuget/foo.bar@1.0.0-rc1") + ); + for elsewhere in [ + "foo.bar/2.0.0/foo.bar.1.0.0.nupkg", + "other/1.0.0/foo.bar.1.0.0.nupkg", + "a/foo.bar/1.0.0/foo.bar.1.0.0.nupkg", + "1.0.0/foo.bar.1.0.0.nupkg", + ] { + assert!(leaf_to_purl("nuget", elsewhere).is_none(), "{elsewhere}"); + } // maven: an empty group component, and an unsafe group (colon). assert!(leaf_to_purl("maven", "/app/1.0.0/app-1.0.0.jar").is_none()); assert!(leaf_to_purl("maven", "a:b/x/1.0/x-1.0.jar").is_none()); diff --git a/crates/socket-patch-core/src/vendor/refusals.rs b/crates/socket-patch-core/src/vendor/refusals.rs index 87e710769..8f0bc56a5 100644 --- a/crates/socket-patch-core/src/vendor/refusals.rs +++ b/crates/socket-patch-core/src/vendor/refusals.rs @@ -23,10 +23,14 @@ //! 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. what rests on the Bazel workspace of the project +//! ([`bazel_workspace_refusals`]), unless the user allowed it +//! ([`ALLOW_IN_BAZEL_ENV`]): a Composer project in one +//! (`vendor_composer_bazel_workspace`), unless the lock already names +//! the patch's copy; and a NuGet package of a project whose lock a +//! rules_csharp hub reads, where the block that makes the hub take the +//! copy cannot be shown to work (`vendor_nuget_bazel_workspace`), unless +//! `nuget.config` already names the patch's folder. //! //! Each check lives in its backend's module; this one only dispatches and //! scopes them. @@ -40,7 +44,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::{ + bun_lock, composer_lock, gem, lock_inventory, npm_flavor, npm_lock, nuget_feed, 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 @@ -102,10 +108,6 @@ fn is_cargo(purl: &str) -> bool { Ecosystem::from_purl(purl) == Some(Ecosystem::Cargo) } -fn is_composer(purl: &str) -> bool { - Ecosystem::from_purl(purl) == Some(Ecosystem::Composer) -} - /// The refusals of vendored mode that rest on the Bazel workspace of the /// project at `project_root`, for `candidates` (`(purl, uuid)` pairs): /// each refused purl with its code and detail. None when the user allowed @@ -113,17 +115,19 @@ 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: Composer's and NuGet's are the two +/// today. pub async fn bazel_workspace_refusals<'a>( project_root: &Path, candidates: &[(&'a str, &str)], ) -> Vec<(&'a str, &'static str, String)> { - let composer: Vec<(&str, &str)> = candidates - .iter() - .filter(|(purl, _)| is_composer(purl)) - .copied() - .collect(); - composer_lock::bazel::refusals(project_root, &composer).await + let of = |ecosystem: Ecosystem| -> Vec<(&'a str, &str)> { + let named = |(purl, _): &&(&str, &str)| Ecosystem::from_purl(purl) == Some(ecosystem); + candidates.iter().filter(named).copied().collect() + }; + let mut refused = composer_lock::bazel::refusals(project_root, &of(Ecosystem::Composer)).await; + refused.extend(nuget_feed::bazel_refusals(project_root, &of(Ecosystem::Nuget)).await); + refused } /// Every refusal the vendor engine can decide for `candidates` (`(purl, @@ -480,6 +484,30 @@ mod tests { assert!(!refusal_is_benign(got[one].code)); } + /// A NuGet package of a project whose lock a rules_csharp hub reads, + /// in a checkout that names no Bazel release: refused with NuGet's own + /// code, beside no candidate of another ecosystem. Where no tag reads + /// the lock nothing is. + #[tokio::test] + #[serial_test::serial] + async fn nuget_candidates_of_a_hub_without_its_block_are_refused() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let tmp = tempfile::tempdir().unwrap(); + let (one, other) = ("pkg:nuget/Lib@1.0.0", "pkg:cargo/lib@1.0.0"); + let pairs = [(one, UUID), (other, OTHER_UUID)]; + let empty = HashMap::new(); + std::fs::write(tmp.path().join("packages.lock.json"), "{}").unwrap(); + let module = crate::bazel::nuget::tests::checkout(tmp.path()); + std::fs::remove_file(tmp.path().join(".bazelversion")).unwrap(); + let got = run(tmp.path(), &pairs, Ok(&empty)).await; + assert_eq!(got.keys().collect::>(), [one]); + assert_eq!(got[one].code, "vendor_nuget_bazel_workspace"); + assert!(!refusal_is_benign(got[one].code)); + let elsewhere = module.replace("//:packages", "//api:packages"); + 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/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index 5857af81d..925f36f68 100644 --- a/crates/socket-patch-core/src/vendor/state.rs +++ b/crates/socket-patch-core/src/vendor/state.rs @@ -1297,6 +1297,7 @@ async fn wiring_file_refusal(rec: &WiringRecord, project_root: &Path) -> Option< one_of(&crate::patch::redirect::NUGET_CONFIG_FILE_NAMES) } "nuget_lock_entry" => super::nuget_feed::ledger_lock_file_refusal(project_root, file), + super::nuget_feed::BAZEL_WIRING_KIND => one_of(&[crate::bazel::nuget::FILE]), "maven_pom_repository" => one_of(&[super::jvm::layout::POM_FILE]), // The JVM kinds: `jvm::apply` checks each record's path against its // kind before it reads anything. Any other kind is a newer build's. @@ -2809,6 +2810,7 @@ mod tests { ("nuget", "nuget_config_source", "NuGet.Config"), ("nuget", "nuget_lock_entry", "src/App/packages.lock.json"), ("nuget", "nuget_lock_entry", "packages.App.lock.json"), + ("nuget", "nuget_bazel_feed", "MODULE.bazel"), ("maven", "maven_pom_repository", "pom.xml"), ]; for (ecosystem, kind, file) in passes { @@ -2844,6 +2846,8 @@ mod tests { ("nuget", "nuget_config_source", "Directory.Build.props"), ("nuget", "nuget_lock_entry", "tools/build.json"), ("nuget", "nuget_lock_entry", ".config/packages.lock.json"), + ("nuget", "nuget_bazel_feed", "BUILD.bazel"), + ("nuget", "nuget_bazel_feed", "svc/MODULE.bazel"), ("maven", "maven_pom_repository", "module/pom.xml"), ]; for (ecosystem, kind, file) in refused { diff --git a/crates/socket-patch-core/src/vex/discover/nuget.rs b/crates/socket-patch-core/src/vex/discover/nuget.rs index b495b8d16..b082f6165 100644 --- a/crates/socket-patch-core/src/vex/discover/nuget.rs +++ b/crates/socket-patch-core/src/vex/discover/nuget.rs @@ -22,11 +22,12 @@ //! | writer | `value` | mode | version from | pin | //! |---|---|---|---|---| //! | `patch::redirect::rewrite_nuget` (`scan --mode hosted`) | `https://patch.socket.dev/patch-registry/nuget///index.json` ([`DiscoverCtx::hosted_uuid`], must equal the key's uuid) | Hosted | every `packages.lock.json` entry for the id (`dependencies...resolved`, id case-insensitive) | its `contentHash` | -//! | `vendor::nuget_feed` (`vendor`, `scan --mode vendored`) | `.socket/vendor/nuget/` ([`vendor_uuid_dir`], must be the nuget dir of the key's uuid) | Vendored | the feed's single `..nupkg` (the patched version), else every locked `resolved` as above | `contentHash` when locked | +//! | `vendor::nuget_feed` (`vendor`, `scan --mode vendored`) | `.socket/vendor/nuget/` ([`vendor_uuid_dir`], must be the nuget dir of the key's uuid), or `/` below it for a package of a rules_csharp hub | Vendored | the feed's single `..nupkg` (the patched version), else every locked `resolved` as above | `contentHash` when locked | //! //! The vendored artifact is `.socket/vendor/nuget//. //! .nupkg` ([`nupkg_leaf`], the writer's own stable leaf: -//! lowercased id, version through the SAME `normalize_nuget_version`) — the exact +//! lowercased id, version through the SAME `normalize_nuget_version`), in +//! the directory the source's value names — the exact //! `VendorArtifact::path` the ledger records, which the CLI's liveness check //! compares verbatim. The feed dir is listed for the patched version (one //! nupkg for the mapped id; its name is split at the KNOWN id, not guessed @@ -597,7 +598,15 @@ async fn emit( value, id, } = src; - if let Some((eco, dir_uuid)) = vendor_uuid_dir(value) { + // The folder of a patch, or the one below it where a rules_csharp hub + // has the package (`/`), which vendored mode names + // for a package of such a hub. + let folder = vendor_uuid_dir(value).map(|(eco, uuid)| (eco, uuid, String::new())); + let folder = folder.or_else(|| { + let below = vendor_ref(value)?; + Some((below.eco, below.uuid, format!("{}/", below.leaf))) + }); + if let Some((eco, dir_uuid, below)) = folder { if eco != "nuget" || dir_uuid != *uuid { // The value is this project's vendor tree, so the key names a // Socket patch too — rejected (discover rule 11). @@ -612,7 +621,7 @@ async fn emit( ); return; } - emit_vendored(ctx, cfg_rel, src, lock, out).await; + emit_vendored(ctx, cfg_rel, src, &below, lock, out).await; return; } match ctx.hosted_uuid(value) { @@ -735,10 +744,13 @@ fn emit_hosted( /// lock's entries at it, if any — and a lock entry at any other version is /// reported through [`other_versions`], never as a ref of its own (no /// artifact serves it). Without one, the lock's versions are the refs. +/// `below` is where the feed lies under the folder of the patch: empty, +/// or a path with a `/` at its end. async fn emit_vendored( ctx: &DiscoverCtx<'_>, cfg_rel: &str, src: &SocketSource, + below: &str, lock: &Lock, out: &mut Discovery, ) { @@ -753,7 +765,7 @@ async fn emit_vendored( let serves = format!("the vendored feed {VENDOR_DIR}/nuget/{}", src.uuid); // (purl version, artifact leaf, integrity, other versions) let mut rows: Vec<(String, String, Option, Option)> = Vec::new(); - let leaves = feed_leaves(ctx, &src.uuid, &id_lower).await; + let leaves = feed_leaves(ctx, &src.uuid, below, &id_lower).await; if let [(leaf, version)] = leaves.as_slice() { let norm = normalize_nuget_version(version); match locks { @@ -803,7 +815,7 @@ async fn emit_vendored( return; } for (version, leaf, integrity, other) in rows { - let artifact = format!("{VENDOR_DIR}/nuget/{}/{leaf}", src.uuid); + let artifact = format!("{VENDOR_DIR}/nuget/{}/{below}{leaf}", src.uuid); let (Some(purl), Some(vref)) = ( simple_purl("nuget", &src.id, &version), vendor_ref(&artifact), @@ -828,16 +840,23 @@ async fn emit_vendored( } /// `(leaf, version)` of every regular `..nupkg` in the vendored -/// feed dir (id compared case-insensitively, version digit-leading and in -/// NuGet's version charset), sorted. -async fn feed_leaves(ctx: &DiscoverCtx<'_>, uuid: &str, id_lower: &str) -> Vec<(String, String)> { - // `uuid` passed the canonical grammar (socket_patch_name_uuid), so the - // join cannot escape `.socket/vendor/nuget/`. +/// feed dir, `below` under the folder of the patch (id compared +/// case-insensitively, version digit-leading and in NuGet's version +/// charset), sorted. +async fn feed_leaves( + ctx: &DiscoverCtx<'_>, + uuid: &str, + below: &str, + id_lower: &str, +) -> Vec<(String, String)> { + // `uuid` passed the canonical grammar (socket_patch_name_uuid) and + // `below` is a traversal-safe path ([`vendor_ref`]), so the join cannot + // escape `.socket/vendor/nuget/`. // The vendored feed is a dir of packages: only a disk has one. let Some(root) = ctx.disk_root() else { return Vec::new(); }; - let dir = root.join(VENDOR_DIR).join("nuget").join(uuid); + let dir = root.join(VENDOR_DIR).join("nuget").join(uuid).join(below); let Ok(mut entries) = tokio::fs::read_dir(&dir).await else { return Vec::new(); }; @@ -1065,6 +1084,37 @@ mod tests { assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); } + /// The folder a package of a rules_csharp hub lies in, below the folder + /// of the patch: the ref names the nupkg there. The folder of another + /// patch is rejected, as for the folder itself. + #[tokio::test] + async fn vendored_below_the_folder_of_the_patch_for_a_hub() { + let below = format!("{}/newtonsoft.json/13.0.3", feed(UUID_A)); + let p = Project::new(); + let wired = |value: &str| { + config( + &[ORG, (&socket_key(UUID_A), value)], + &[("nuget.org", "*"), (&socket_key(UUID_A), "Newtonsoft.Json")], + ) + }; + p.write("nuget.config", wired(&below)); + let entries = [("net8.0", "Newtonsoft.Json", "13.0.3", Some(HASH))]; + p.write("packages.lock.json", lock(&entries)); + let nupkg = format!("{below}/newtonsoft.json.13.0.3.nupkg"); + p.write(&nupkg, "PK"); + let out = run(&p).await; + assert_eq!(out.refs.len(), 1, "{:?}", out.diagnostics); + assert_eq!(out.refs[0].artifact_rel.as_deref(), Some(nupkg.as_str())); + assert_eq!(out.refs[0].mode, WiringMode::Vendored); + assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); + + let other = format!("{}/newtonsoft.json/13.0.3", feed(UUID_B)); + p.write("nuget.config", wired(&other)); + let out = run(&p).await; + assert!(out.refs.is_empty(), "{:?}", out.refs); + assert_eq!(out.diagnostics[0].code, DIAG_REF_INVALID); + } + /// The leaf uses the writer's version normalization (4th zero segment /// dropped, lowercased pre-release) while the purl keeps the lock's /// resolved spelling. diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 0d0353aca..1f2080f4b 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -26,7 +26,7 @@ below is about what a package manager installs and builds. | 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`) | -| NuGet (`nuget`) | ✅ in-place patching deletes `.nupkg.metadata` and advises on the `.nupkg.sha512` tamper-evidence sidecar — prefer vendored / hosted, see [Maven & NuGet caveats](#maven--nuget-caveats) | ✅ committed folder feed (its `.gitignore` re-includes the nupkg against `*.nupkg` rules) + `packageSourceMapping` + `packages.lock.json` contentHash pin | ✅ `nuget.config` source + source-mapping, `packages.lock.json` contentHash rewrite. See the locked-mode note in [Maven & NuGet caveats](#maven--nuget-caveats). In a Bazel workspace whose rules_csharp `nuget.from_lock` hub would not take the pin (it reads the lock and not that `nuget.config`, or has the package from a lock the run does not re-pin), nothing is written (`redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`); see [Bazel workspaces: NuGet](#bazel-workspaces-nuget) | +| NuGet (`nuget`) | ✅ in-place patching deletes `.nupkg.metadata` and advises on the `.nupkg.sha512` tamper-evidence sidecar — prefer vendored / hosted, see [Maven & NuGet caveats](#maven--nuget-caveats) | ✅ committed folder feed (its `.gitignore` re-includes the nupkg against `*.nupkg` rules) + `packageSourceMapping` + `packages.lock.json` contentHash pin. In a Bazel workspace whose rules_csharp `nuget.from_lock` reads the project's lock, also a block in the root `MODULE.bazel`, or the package is declined (`vendor_nuget_bazel_workspace`); see [Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub) | ✅ `nuget.config` source + source-mapping, `packages.lock.json` contentHash rewrite. See the locked-mode note in [Maven & NuGet caveats](#maven--nuget-caveats). In a Bazel workspace whose rules_csharp `nuget.from_lock` hub would not take the pin (it reads the lock and not that `nuget.config`, or has the package from a lock the run does not re-pin), nothing is written (`redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`); see [Bazel workspaces: NuGet](#bazel-workspaces-nuget) | | Composer (`composer`) | ✅ in place (`vendor/`) | ✅ `composer.lock` `dist: path` rewrite; declined in a Bazel workspace, see [Bazel workspaces: Composer](#bazel-workspaces-composer) | ✅ `composer.lock` dist url + shasum rewrite; the entry's `source` and `dist.mirrors` are removed. See [composer-compatibility.md](testing/composer-compatibility.md) | | Deno (`deno`) | ✅ in place (the only mode for Deno) | ❌ refused (`vendor_unsupported_ecosystem`) | ❌ not supported | @@ -1599,6 +1599,156 @@ name. Nothing is evaluated and no Bazel is run. as it does without Bazel. - A pin that an earlier release wrote in such a workspace stays in the two files: `socket-patch rollback` takes it out, and the attribute makes the build read it. +- **A package of the project is vendored.** The block of vendored mode (below) is the hub's + last tag, and its `feeds` stand in the place of the config's sources. Hosted mode then + writes nothing for another package of the project and says so: vendor that package too, or + take the vendored ones out and run the command again. + +### Vendored mode under a rules_csharp hub + +Vendored mode commits the patched package under `.socket/vendor/nuget//`, names that +folder as a package source in `nuget.config`, and re-pins the lock. NuGet takes a folder as a +source. The hub reads the same line as the URL of a feed: after a vendored run that exited 0, +the next `bazel build` crashed Bazel 9.3.2 in the module extension and failed on 8.8.2 and +7.7.2 with `Bad URL: .socket/vendor/nuget/...`. + +So in the root of a Bazel workspace whose `nuget.from_lock` reads the project's lock, `scan +--mode vendored`, `get --mode vendored` and `vendor` write three things differently: + +- The package lies where a feed of the hub has one: + `.socket/vendor/nuget////..nupkg`, with the id in lower case. + It is the one copy. +- `nuget.config` names that directory, `.socket/vendor/nuget///`, so + `dotnet restore` outside Bazel takes the same file. +- One block is appended to the root `MODULE.bazel`, after one blank line: + +```starlark +# >>> socket-patch: NuGet patches for Bazel (managed block: socket-patch writes and removes it) >>> +socket_patch_nuget = use_extension("@rules_csharp//csharp:extensions.bzl", "nuget") +socket_patch_nuget.from_lock( + feeds = [ + "file:.socket/vendor/nuget/", + "https://api.nuget.org/v3/index.json", + ], + packages_lock_json = "//:packages.lock.json", +) +# <<< socket-patch <<< +``` + +The block is a second `nuget.from_lock` of the same hub, after every tag of yours, so its +`feeds` are the ones the hub asks: first the folder of each vendored patch, which Bazel reads +from the root of the workspace, then the sources the hub had without the block (those of your +tag's `nuget_config`, or else its `feeds`). It carries the label of your `use_extension`, your +`packages_lock_json`, and your hub's `name` where the tag gives one. No call of yours is +edited, and nothing is written to `.bazelrc` or `.bazelignore`: the folder holds no BUILD +file, and `bazel query //...` lists what it listed. + +The build then takes the committed package and asks no host for it: with the patch host +unreachable, from a new output base, with the package in no repository cache (rules_csharp +0.5.0 on Bazel 9.3.2, 8.8.2 and 7.7.2). A committed package that is changed or missing fails +the build, over the lock's `contentHash` or the sha256 that `MODULE.bazel.lock` records; it is +never replaced by the upstream package. The one exception is a machine whose repository cache +holds the package under the sha256 that `MODULE.bazel.lock` records: Bazel builds the cached +file there, which is the patched one, and does not read the folder. `vendor --check` catches a +changed or missing copy on every machine. Commit `.socket/vendor`, `nuget.config`, the lock +and `MODULE.bazel` together. + +`vendor --revert`, `rollback` and `remove` take the folder of a patch out of the block, and +the block goes with its last folder: `MODULE.bazel` is then byte for byte what it was. With +one vendored patch every other file is too. With several, `nuget.config` can keep the source +mapping that the first of them created, as it does without Bazel: `vendor --revert` and +`rollback` leave it, and so does `remove` in the order the patches were vendored. + +A block that was changed by hand is not taken out, and then nothing is: the three commands +fail (`revert_failed`, `vendor_revert_failed`), name the line of the block and leave every +file as it is. With the lock restored beside such a block, the hub would hold the committed +package to the upstream `contentHash` and the build would fail. Put the block back as +socket-patch wrote it, or delete it, and run the command again. + +`vendor --check`, `list` and `vex` see the package as any vendored NuGet package. A later +vendored run keeps the block in step with your tag: a source you add to `nuget.config` +reaches the hub once socket-patch has run again. + +**Where it declines.** The block is written only where the checkout shows that it works. +Elsewhere every command that would vendor the package reports it `failed` with +`vendor_nuget_bazel_workspace` and exits 1; it downloads nothing and writes nothing, and a +package that is pinned hosted stays pinned. With `--dry-run`, `scan` and `get` list the package +and exit 0. The message names the reason, with the file and line where there is one, and +`--mode hosted`. The reasons: + +- The project is not the root of its Bazel workspace, or another Bazel workspace lies above + it in the checkout. +- The workspace has more than one `nuget.from_lock`, or socket-patch cannot read with + certainty which tags it has. +- The tag is not a call of its own with every argument written out, or it is called on a + `use_extension` that is isolated or a dev dependency. +- The tag has `local_package_dirs`: the hub asks those directories before every feed, and + with the upstream package in one the build fails on the re-pinned lock. Or it has `netrc` + or `auth_patterns`, which the block was not built with. +- Its `nuget_config` cannot be read, or a package source cannot stand in a string. +- The tag has `feeds` and names a `nuget_config` that has no package source. Vendored mode + names its folder in that file, and rules_csharp takes the sources of a `nuget_config` in + place of `feeds`: a later run would write the block without those feeds. Name the feeds in + the file. +- `MODULE.bazel.lock` does not show that Bazel selected rules_csharp 0.5.0. Build once, so + that Bazel writes its lock. +- The checkout does not name Bazel 9.3.2, 8.8.2 or 7.7.2 in `.bazelversion` or `.bazeliskrc`. + The block rests on Bazel reading a relative `file:` URL from the root of the workspace, + which Bazel does not document, and Bazel 9.1.0 has other code for such a URL than its + neighbours. So no other release is taken, and a checkout that names none is declined. +- An rc file of the checkout names `--repository_disable_download` or `--vendor_dir`, or a + directory at the root is a vendor directory of Bazel's (it holds `VENDOR.bazel`). +- An rc file of the checkout names a remote downloader (`--experimental_remote_downloader`), + which takes no `file:` feed. By Bazel's source, 7.7.2 hands it the folder, which it cannot + read, and 8.8.2 and 9.3.2 download every package of the lock without it. That is read and + not built. +- `MODULE.bazel` is a symbolic link, or its block was changed by hand. + +`--allow-vendored-in-bazel` (or `SOCKET_ALLOW_VENDORED_IN_BAZEL=1`) lifts the decline. The +package is then vendored as in a project without Bazel, which the hub does not take: that is +for a project whose lock a tag names and which Bazel does not build. A package that was +vendored that way, or by an earlier release, stays as it is on later runs, without a block; +`vendor --revert` and a new vendored run give it the layout above. + +Nothing changes for a NuGet project in no Bazel workspace, and for one whose locks no +`nuget.from_lock` reads: the package lies in the folder of the patch, and no line of +`MODULE.bazel` is written. + +**Limits.** + +- The block works in the root module only. In a workspace that depends on this one as a + module, Bazel reads the folder from the other root and the build fails. Hosted mode works + there. +- A module this workspace depends on may have a `nuget.from_lock` of its own with + `nuget_config` or `feeds`. The hub takes that tag after the block and drops the block's + feeds, and the build fails on the re-pinned lock. Hosted mode fails the same way there. +- A build with `--nofetch` in an output base that built the unpatched project, and a build + from a vendor directory made before the patch (`--vendor_dir` with `--nofetch`), build the + unpatched package and exit 0, with a warning of Bazel's. Such a build still rewrites + `MODULE.bazel.lock` to the pins of the patched package. Fetch again, or run `bazel vendor` + again. socket-patch sees `--vendor_dir` and `--repository_disable_download` in an rc file + and a vendor directory at the root of the workspace; it does not see `--nofetch`, in an rc + file or on a command line. +- A checkout that is deleted and made again at the same path under a running Bazel server + does not find the committed package until the server has restarted (`bazel shutdown`). The + build fails; it does not take the upstream package. +- `MODULE.bazel.lock` is stale right after the run, as after a hosted run: a build with + `--lockfile_mode=error` fails until a build that may update the lock has run and the lock + is committed. That build needs a registry for the other packages and no patch host. +- When the module extension runs, Bazel prints three `WARNING: Download from file:...` lines + for every other package of the lock, which the folder does not hold, for each vendored + patch. +- A source you add to `nuget.config` reaches the hub only after socket-patch has run again. +- An earlier release of socket-patch does not know the layout or the block. On a checkout + that this one vendored, its `vendor --check` fails (`vendor_check_failed`), its vendored + run writes a second copy of the package in the folder of the patch, and its + `vendor --revert` exits 0, restores the lock and leaves the block and the package: the Bazel + build then fails on the lock's `contentHash` (measured on Bazel 9.3.2). Undo with the + release that vendored. +- Measured on macOS arm64, with packages that carry no signature. + +[`e2e_bazel_build/nuget.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs) runs +the vendored flow on a real Bazel: `nuget::vendored_from_lock`. ## Gradle @@ -1994,7 +2144,7 @@ workspace and that Bazel does not build keeps the matrix at the top. | 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 | +| NuGet: rules_csharp `nuget.from_lock` over `packages.lock.json` | Supported with `nuget_config` on the tag | Supported with the Bazel release in `.bazelversion` | Not supported | Supported with a vendored patch, or a hosted one and 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 | @@ -2061,7 +2211,13 @@ What the table was tested with: `packages_lock_json = "//:packages.lock.json"` and `nuget_config = "//:nuget.config"`. `scan` finds a NuGet package only where a restore unpacked it (NuGet's global packages folder, a folder that an `obj/project.assets.json` records, or a `packages` folder): on a - machine where only Bazel ever ran it finds none, exits 0 and writes nothing. + machine where only Bazel ever ran it finds none, exits 0 and writes nothing. Vendored mode + was tested for that one tag, with the project at the root of the workspace, a + `.bazelversion` that names one of the three releases, and the `MODULE.bazel.lock` of a + build. It keeps a block in `MODULE.bazel` there, and where the checkout does not show that + the block works it declines the package and writes nothing: + [Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub) has the block, every + reason to decline and the limits. - **Composer**: no ruleset builds PHP, so the two shapes are rules a project writes itself: a repository rule that runs `composer install` from the committed `composer.lock` and takes the lock with `rctx.read`, and a genrule that runs it in a build action. Composer 2 and PHP @@ -2084,12 +2240,12 @@ fails until one that may has rewritten it. Known problems. In each of these a command exits 0 today and the next Bazel build fails: -- **Vendored mode for PyPI, RubyGems and NuGet.** The path of the committed copy means - nothing where Bazel runs: rules_python takes it for a package name, rules_ruby's - `bundle install` does not find it (`The path ... does not exist`), and rules_csharp reads - it as a URL (`Bad URL`, or a crash of Bazel 9.3.2). Run `socket-patch vendor --revert`, - then `socket-patch scan --mode hosted`. Of these builds a test of this repository runs the - PyPI one; the others were measured by hand on the three Bazel releases. +- **Vendored mode for PyPI and RubyGems.** The path of the committed copy means nothing + where Bazel runs: rules_python takes it for a package name, and rules_ruby's + `bundle install` does not find it (`The path ... does not exist`). Run + `socket-patch vendor --revert`, then `socket-patch scan --mode hosted`. Of these builds a + test of this repository runs the PyPI one; the other was measured by hand on the three + Bazel releases. - **Vendored mode for Composer, where its refusal is lifted or does not apply.** In a Bazel workspace vendored mode declines a Composer package: [Bazel workspaces: Composer](#bazel-workspaces-composer) has the refusal, what lifts it and @@ -2097,6 +2253,18 @@ Known problems. In each of these a command exits 0 today and the next Bazel buil rule runs in another directory fails the build with `Source path ... is not found`. Run `socket-patch vendor --revert`, then `socket-patch scan --mode hosted`. A test of this repository builds that failure on the three Bazel releases. +- **Vendored mode for NuGet, where its refusal is lifted or does not see the cause.** For a + package of a rules_csharp hub, vendored mode keeps a block in `MODULE.bazel` or declines: + [Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub) has both. With + `--allow-vendored-in-bazel`, and for a package that an earlier release vendored, the folder + stands in `nuget.config` alone, rules_csharp reads it as a URL, and the build fails + (`Bad URL`, or a crash of Bazel 9.3.2; measured on the three Bazel releases). Run + `socket-patch vendor --revert`, then `socket-patch scan --mode vendored` without the + switch, or `--mode hosted`. With the block, the build fails in two shapes that the checkout + does not show: a workspace that depends on this one as a module, and a module this one + depends on that has a `nuget.from_lock` with sources of its own. It also fails after the + `vendor --revert` of an earlier release, which leaves the block and the package beside the + restored lock: undo with the release that vendored. - **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 @@ -2141,6 +2309,12 @@ In these a command exits 0 and the Bazel build passes on the unpatched package: - **Hosted NuGet on a machine without a restore.** `scan` reads no package out of `packages.lock.json`, so where only Bazel ever ran it finds none and writes nothing. Run it where `dotnet restore` has run. +- **Vendored NuGet in a build that may not fetch.** `--nofetch` in an output base that built + the unpatched project, and `--vendor_dir` with `--nofetch` over a vendor directory made + before the patch, build the package Bazel already has, with a warning of Bazel's. Fetch + again, or run `bazel vendor` again. Vendored mode declines where it sees a vendor directory + at the root of the workspace or `--vendor_dir` in an rc file; it does not see `--nofetch`, + in an rc file or on a command line. - **Go, when another Bazel module of the build requires a higher version** of the patched module: gazelle builds that version and drops the replacement. With `go_deps.config(check_direct_dependencies = "error")` and the module required directly in @@ -3320,7 +3494,10 @@ 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. It lifts two refusals today: this one, and the one for a +NuGet package of a rules_csharp hub whose block cannot be shown to work +(`vendor_nuget_bazel_workspace`, see +[Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub)). `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 @@ -3909,7 +4086,9 @@ 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 +`nuget_config`, on a machine whose NuGet folder does not hold the package (and after a +vendored scan that kept its block in `MODULE.bazel`, on the machine that restored the +project as well: `vex` reads the committed package). 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. @@ -3937,6 +4116,12 @@ 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`, where the package is vendored and + `MODULE.bazel` does not hold its block: a run with `--allow-vendored-in-bazel`, a package + that an earlier release vendored, a block that was taken out by hand. `vex` reads + `nuget.config`, the lock and the committed package, and not the block. Measured for the + first two, where the build fails. With the block in place, a build that may not fetch + (`--nofetch`) can build the unpatched package while the statement says `not_affected`. - **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..1dff565e4 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": 3758 }, "lock-readers": { "paths": [ From fadf0e937b71c717bc3e410ccc811cad18bd97f2 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 16:30:03 -0500 Subject: [PATCH 10/22] Keep the block of a rules_csharp hub right through an undo, a later patch and a second run Four defects of vendored mode for a NuGet package of a rules_csharp hub, each with a unit test. An undo that leaves `nuget.config` wired took the block out. When the config was written anew since the vendored run and still names the folder, the undo keeps the config, the lock pin and the package (`vendor_lock_entry_drifted`). The block went first all the same, so the hub read the folder in `nuget.config` as the URL of a feed and the Bazel build failed on a package that built before the undo. The block now goes last, after the lock and the config, and stays where the config is left wired. A lock that cannot be restored leaves the block too, so the build is as it was for the retry. A later patch of the same package left the earlier patch's folder in the block. The config keeps the earlier patch's source with its pattern set aside; the folder that source names is now taken out of the block when the later patch is written into it, so the block names the later folder alone and goes with it on the undo. The first run for a tag whose `nuget_config` has no package source wrote a block without nuget.org, and the second run added it: the run gives such a config nuget.org beside the folder, and the block was read before that. The block is now read from the tag after the config is written, so a second run writes no file. A lock that spells the package's version otherwise than NuGet writes it (`1.2.3.0` for `1.2.3`) was vendored, and the hub did not find the package: rules_csharp 0.5.0 asks a feed for the lock's `resolved` as it is written. Such a package is declined with `vendor_nuget_bazel_workspace`, by the backend and by the refusal every way in asks first. The refusal looked for the project's locks before it knew that the project is in a Bazel workspace; it asks for the workspace first. Also: one function for the folder of a hub's package in place of the two places of the backend that wrote it out, and the real-Bazel NuGet legs start on a push to main that changes the ledger or the artifact paths of vendored mode (vendor/state.rs, vendor/path.rs), which hold the record of the block and the place of a hub's package. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-nuget.yml | 9 +- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- crates/socket-patch-core/src/bazel/nuget.rs | 46 ++- .../src/vendor/nuget_feed.rs | 353 ++++++++++++++++-- docs/ecosystems.md | 12 +- scripts/loc-budget.json | 2 +- 6 files changed, 373 insertions(+), 51 deletions(-) diff --git a/.github/workflows/bazel-nuget.yml b/.github/workflows/bazel-nuget.yml index e1056f6d0..ae2b3a8ba 100644 --- a/.github/workflows/bazel-nuget.yml +++ b/.github/workflows/bazel-nuget.yml @@ -90,8 +90,11 @@ on: # 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. + # through, `vex`, whose verdicts the flow asserts, the ledger and the + # artifact paths of vendored mode (vendor/state.rs and vendor/path.rs, + # which every ecosystem shares: they hold the record of the block and + # the place of a hub's package), 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' @@ -119,6 +122,8 @@ on: - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-core/src/vendor/path.rs' + - 'crates/socket-patch-core/src/vendor/state.rs' - 'crates/socket-patch-cli/src/commands/**' - 'crates/socket-patch-cli/tests/common/**' - 'crates/socket-patch-cli/tests/hosted_memory_common/**' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 9a071aaf0..efd582d04 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_nuget_bazel_workspace` | `failed`; `skipped` (warning, vendor advisory event) for a package that is already vendored for the hub | vendor / scan / get `--mode vendored` (nuget): a rules_csharp `nuget.from_lock` tag of the project's Bazel workspace reads a lock of the project, and the block that makes the hub take the committed package cannot be shown to work from the checkout. Vendored mode keeps such a package at `.socket/vendor/nuget////..nupkg`, names that directory in `nuget.config`, and appends one managed block to the root `MODULE.bazel`: a `nuget.from_lock` of its own whose `feeds` are `file:.socket/vendor/nuget/` for each vendored patch and then the sources the hub had without it (rules_csharp 0.5.0 on Bazel 9.3.2, 8.8.2, 7.7.2). It declines when: the project is not the root of its Bazel workspace, or another workspace lies above it in the checkout; the workspace has more than one `nuget.from_lock`, or its tags cannot be read with certainty; the tag is not a call of its own with every argument written out, is called on an isolated or dev-dependency `use_extension`, or has `local_package_dirs`, `netrc` or `auth_patterns`; its `nuget_config` cannot be read, or a package source cannot stand in a string; it has `feeds` and a `nuget_config` without a package source (the run names its folder there, and rules_csharp takes the sources of that file in place of `feeds`); `MODULE.bazel.lock` does not show that Bazel selected rules_csharp 0.5.0; the checkout does not name Bazel 9.3.2, 8.8.2 or 7.7.2 (`.bazelversion` / `.bazeliskrc`); an rc file names `--repository_disable_download`, `--vendor_dir` or a remote downloader (`--experimental_remote_downloader`), or a directory at the root holds `VENDOR.bazel`; `MODULE.bazel` is a symbolic link, or its block was changed by hand. 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. The detail names the reason, with the file and line where there is one, and `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel` (the package is vendored as without Bazel), `vendor --revert`, a package whose folder `nuget.config` already names (the run leaves the config as it is), and a project whose locks no `nuget.from_lock` reads, which is vendored as without Bazel. As an advisory event: a package that is vendored for the hub, whose block can no longer be shown to work or was changed by hand; the block is left as it is. The undo of such a package beside a block that was changed by hand fails and changes nothing (`revert_failed` from `vendor --revert`, `vendor_revert_failed` from `rollback` and `remove`; exit 1): the detail names the line of the block, and the lock restored beside it would fail the Bazel build. See docs/ecosystems.md "Bazel workspaces: NuGet". | +| `vendor_nuget_bazel_workspace` | `failed`; `skipped` (warning, vendor advisory event) for a package that is already vendored for the hub | vendor / scan / get `--mode vendored` (nuget): a rules_csharp `nuget.from_lock` tag of the project's Bazel workspace reads a lock of the project, and the block that makes the hub take the committed package cannot be shown to work from the checkout. Vendored mode keeps such a package at `.socket/vendor/nuget////..nupkg`, names that directory in `nuget.config`, and appends one managed block to the root `MODULE.bazel`: a `nuget.from_lock` of its own whose `feeds` are `file:.socket/vendor/nuget/` for each vendored patch and then the sources the hub had without it (rules_csharp 0.5.0 on Bazel 9.3.2, 8.8.2, 7.7.2). It declines when: the project is not the root of its Bazel workspace, or another workspace lies above it in the checkout; the workspace has more than one `nuget.from_lock`, or its tags cannot be read with certainty; the tag is not a call of its own with every argument written out, is called on an isolated or dev-dependency `use_extension`, or has `local_package_dirs`, `netrc` or `auth_patterns`; its `nuget_config` cannot be read, or a package source cannot stand in a string; it has `feeds` and a `nuget_config` without a package source (the run names its folder there, and rules_csharp takes the sources of that file in place of `feeds`); `MODULE.bazel.lock` does not show that Bazel selected rules_csharp 0.5.0; the checkout does not name Bazel 9.3.2, 8.8.2 or 7.7.2 (`.bazelversion` / `.bazeliskrc`); an rc file names `--repository_disable_download`, `--vendor_dir` or a remote downloader (`--experimental_remote_downloader`), or a directory at the root holds `VENDOR.bazel`; `MODULE.bazel` is a symbolic link, or its block was changed by hand; a lock spells the package's version otherwise than NuGet writes it (`1.2.3.0` for `1.2.3`: the hub asks its feeds for the lock's spelling). 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. The detail names the reason, with the file and line where there is one, and `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel` (the package is vendored as without Bazel), `vendor --revert`, a package whose folder `nuget.config` already names (the run leaves the config as it is), and a project whose locks no `nuget.from_lock` reads, which is vendored as without Bazel. As an advisory event: a package that is vendored for the hub, whose block can no longer be shown to work or was changed by hand; the block is left as it is. The undo of such a package beside a block that was changed by hand fails and changes nothing (`revert_failed` from `vendor --revert`, `vendor_revert_failed` from `rollback` and `remove`; exit 1): the detail names the line of the block, and the lock restored beside it would fail the Bazel build. An undo that leaves `nuget.config` wired (`vendor_lock_entry_drifted`: the file was written anew and still names the folder) keeps the block with the lock pin and the package. See docs/ecosystems.md "Bazel workspaces: NuGet". | | `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/nuget.rs b/crates/socket-patch-core/src/bazel/nuget.rs index 42995e6a0..6d509f978 100644 --- a/crates/socket-patch-core/src/bazel/nuget.rs +++ b/crates/socket-patch-core/src/bazel/nuget.rs @@ -908,15 +908,23 @@ fn find(text: &str) -> Block { /// `module`, the text of the root `MODULE.bazel`, with the folder `folder` /// of a vendored package (from the Bazel root) in the block for `feeds`: /// in the block that is there, which then holds what `feeds` holds now, or -/// in a new one at the end of the file ([`block::put`]). `None` when the -/// block that is there was changed by hand. -pub fn with_folder(module: &str, feeds: &Feeds, folder: &str) -> Option { +/// in a new one at the end of the file ([`block::put`]). The folders of +/// `superseded`, those of earlier patches of the same package, go out of +/// the block: the hub asks its feeds in their order, and such a folder no +/// longer holds what the lock pins. `None` when the block that is there +/// was changed by hand. +pub fn with_folder( + module: &str, + feeds: &Feeds, + folder: &str, + superseded: &[String], +) -> Option { let (at, mut folders) = match find(module) { Block::Edited(_) => return None, Block::None => (None, Vec::new()), Block::Ours(at, _, folders) => (Some(at), folders), }; - folders.retain(|other| other != folder); + folders.retain(|other| other != folder && !superseded.contains(other)); folders.push(folder.to_string()); folders.sort(); Some(block::put(module, at, &render(feeds, &folders))) @@ -1918,7 +1926,7 @@ socket_patch_nuget.from_lock( let crlf = ends[0].replace('\n', "\r\n"); for module in ends.iter().chain([&crlf]) { let eol = if module.contains('\r') { "\r\n" } else { "\n" }; - let one = with_folder(module, &fixture, FOLDER_A).expect("a block"); + let one = with_folder(module, &fixture, FOLDER_A, &[]).expect("a block"); let block = BLOCK.replace('\n', eol); let expected = match module.ends_with('\n') { true => format!("{module}{eol}{block}{eol}"), @@ -1926,11 +1934,14 @@ socket_patch_nuget.from_lock( }; assert_eq!(one, expected); // Once more: the same text. - assert_eq!(with_folder(&one, &fixture, FOLDER_A), Some(one.clone())); + assert_eq!( + with_folder(&one, &fixture, FOLDER_A, &[]), + Some(one.clone()) + ); // A second folder, in the order of their names, and the name // of a hub that has one. let named = feeds(Some("packages"), &[NUGET_ORG]); - let two = with_folder(&one, &named, FOLDER_B).expect("two folders"); + let two = with_folder(&one, &named, FOLDER_B, &[]).expect("two folders"); let both = format!(" \"file:{FOLDER_A}\",{eol} \"file:{FOLDER_B}\",{eol}"); assert!(two.contains(&both), "{two}"); @@ -1945,6 +1956,15 @@ socket_patch_nuget.from_lock( ); assert_eq!(without_folder(&left, FOLDER_B).as_ref(), Ok(module)); assert_eq!(without_folder(&one, FOLDER_A).as_ref(), Ok(module)); + // A later patch of the same package takes the place of the + // folder it supersedes, and the block goes with it alone. + let later = with_folder(&one, &fixture, FOLDER_B, &[FOLDER_A.to_string()]); + let later = later.expect("the folder of the later patch"); + assert!( + !later.contains(FOLDER_A) && later.contains(FOLDER_B), + "{later}" + ); + assert_eq!(without_folder(&later, FOLDER_B).as_ref(), Ok(module)); // A folder that is not there, and a file without a block. assert_eq!(without_folder(&one, FOLDER_B), Ok(one.clone())); assert_eq!(without_folder(module, FOLDER_A).as_ref(), Ok(module)); @@ -1954,7 +1974,7 @@ socket_patch_nuget.from_lock( #[test] fn a_block_that_was_changed_by_hand_is_left_alone() { let fixture = feeds(None, &[NUGET_ORG]); - let one = with_folder(&module(WIRED), &fixture, FOLDER_A).expect("a block"); + let one = with_folder(&module(WIRED), &fixture, FOLDER_A, &[]).expect("a block"); for edited in [ one.replace("\"https://api.nuget.org/v3/index.json\",\n", ""), one.replace(" feeds = [", " feeds = [ # ours"), @@ -1963,7 +1983,11 @@ socket_patch_nuget.from_lock( format!("{one}{BLOCK}\n"), ] { assert_ne!(edited, one); - assert_eq!(with_folder(&edited, &fixture, FOLDER_B), None, "{edited}"); + assert_eq!( + with_folder(&edited, &fixture, FOLDER_B, &[]), + None, + "{edited}" + ); assert_eq!(without_folder(&edited, FOLDER_A), Err(10), "{edited}"); } } @@ -1994,7 +2018,7 @@ socket_patch_nuget.from_lock( assert_eq!(read, feeds(None, &[NUGET_ORG])); // With its own block in the file the workspace reads as before: // the block's tag is no second tag. - let wired = with_folder(&module, &read, FOLDER_A).expect("a block"); + let wired = with_folder(&module, &read, FOLDER_A, &[]).expect("a block"); std::fs::write(root.join(FILE), &wired).unwrap(); assert_eq!(vendored(&root, &lock), Vendored::Block(read)); // A block that was changed by hand. @@ -2027,7 +2051,7 @@ socket_patch_nuget.from_lock( #[test] fn a_hosted_pin_beside_the_block_of_vendored_mode_is_withheld() { - let wired = with_folder(&module(WIRED), &feeds(None, &[NUGET_ORG]), FOLDER_A); + let wired = with_folder(&module(WIRED), &feeds(None, &[NUGET_ORG]), FOLDER_A, &[]); let said = said(&[("MODULE.bazel", &wired.expect("a block"))], "").expect("withheld"); let starts = "MODULE.bazel:12: this `nuget.from_lock` is the one vendored mode keeps for \ the vendored NuGet packages of this project, and its `feeds` stand in the \ diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index 1e39f41fb..db9e9d163 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -121,6 +121,40 @@ pub(crate) fn nupkg_leaf(id_lower: &str, version: &str) -> String { format!("{id_lower}.{}.nupkg", normalize_nuget_version(version)) } +/// Where a rules_csharp hub has the package `id version_norm` in the folder +/// `uuid_dir_rel` of its patch: `//`, the shape of +/// a folder feed. `nuget.config` names this folder for such a package. +fn hub_folder_rel(uuid_dir_rel: &str, id: &str, version_norm: &str) -> String { + format!("{uuid_dir_rel}/{}/{version_norm}", id.to_lowercase()) +} + +/// Why a hub would not find `id version_norm` in the folder of its patch: +/// a lock that spells the version otherwise. rules_csharp asks a feed for +/// the lock's `resolved` as it is written, in lower case, and the folder +/// holds the version as NuGet normalizes it, which is what `dotnet restore` +/// writes into a lock. +fn spelled_otherwise<'a>( + locks: impl IntoIterator, + id: &str, + version_norm: &str, +) -> Option { + locks.into_iter().find_map(|(rel, text)| { + let doc = lock_value(text).ok()?; + let spelled = crate::formats::nuget::lock::nuget_lock_entries(&doc) + .filter(|entry| entry.id.eq_ignore_ascii_case(id)) + .map(|entry| entry.resolved) + .find(|resolved| { + normalize_nuget_version(resolved) == version_norm + && resolved.to_lowercase() != version_norm + })?; + Some(format!( + "{rel} names {id} {spelled}, and a rules_csharp hub asks its feeds for the version as \ + the lock spells it, where the folder of the patch holds {version_norm}: run `dotnet \ + restore` so that the lock names {version_norm}" + )) + }) +} + /// Everything [`vendor_nuget`] decides before it can first ask the patch /// service: the coordinate guards, the no-op of an empty patch, the /// nuget.config and packages.lock.json reads, and whether the feed already @@ -145,6 +179,12 @@ struct NugetPrelude { /// Why the block of a package that is wired for a hub can no longer /// be shown to work. hub_doubt: Option, + /// The folders of earlier patches of this package that `nuget.config` + /// still names for a hub: this patch takes their place in the block. + superseded: Vec, + /// The locks of the project as the gate of the block is asked about + /// them ([`vendored`]). + governed_rels: Vec, config_path: Option, config_text: Option, /// Every lock the projects under the root restore into (#353, #514). @@ -268,30 +308,47 @@ async fn nuget_prelude( // The idempotent hot path's test (see `vendor_nuget`): a live // `` source under our key. A commented-out one — or the // key merely mentioned elsewhere — is not wiring NuGet reads. - let named = config_text + let sources = config_text .as_deref() .and_then(crate::formats::nuget::parse_config) - .and_then(|parsed| { - parsed - .sources - .into_iter() - .find(|(key, _)| *key == source_key) - }); + .map(|parsed| parsed.sources) + .unwrap_or_default(); + let named = sources.iter().find(|(key, _)| *key == source_key); let config_wired = named.is_some(); // Where the package lies. A rules_csharp hub that reads a lock of the // project takes it from `///`, through the // block of the root MODULE.bazel; every other project keeps it in the // folder itself. A package that is wired stays where the config names // it, and only one that lies where a hub has it is the hub's. - let nested = format!("{uuid_dir_rel}/{id_lower}/{version_norm}"); - let for_hub = named.is_some_and(|(_, value)| value == nested); + let nested = hub_folder_rel(&uuid_dir_rel, name, &version_norm); + let for_hub = named.is_some_and(|(_, value)| *value == nested); + // An earlier patch of this package keeps its source in the config (its + // pattern is set aside): where that one lies as a hub has it, its + // folder is one this patch supersedes. + let below = format!("/{id_lower}/{version_norm}"); + let earlier = sources.iter().filter(|(key, _)| *key != source_key); + let superseded: Vec = earlier + .filter_map(|(_, value)| value.strip_suffix(&below)) + .filter(|folder| { + let uuid = folder.rsplit('/').next().unwrap_or_default(); + vendor_uuid_dir_rel("nuget", uuid).as_deref() == Some(*folder) + }) + .map(str::to_string) + .collect(); let hub = match config_wired && !for_hub { true => Vendored::Plain, false => { - let root = project_root.to_path_buf(); - run_blocking(move || vendored(&root, &governed_rels)).await + let (root, rels) = (project_root.to_path_buf(), governed_rels.clone()); + run_blocking(move || vendored(&root, &rels)).await } }; + let hub = match hub { + Vendored::Block(feeds) => match spelled_otherwise(texts(&locks), name, &version_norm) { + Some(why) => Vendored::Declined(why), + None => Vendored::Block(feeds), + }, + hub => hub, + }; let (feeds, hub_doubt) = match hub { Vendored::Block(feeds) => (Some(feeds), None), Vendored::Declined(why) if for_hub => (None, Some(why)), @@ -372,6 +429,8 @@ async fn nuget_prelude( source_key, feeds, hub_doubt, + superseded, + governed_rels, config_path, config_text, locks, @@ -395,7 +454,8 @@ fn declined_detail(why: &str) -> String { /// The NuGet `candidates` (`(purl, uuid)` pairs) that vendored mode /// declines in the project at `project_root`, each with [`VENDOR_DECLINED`] /// and the detail: those of a project whose lock a rules_csharp hub reads, -/// where the block cannot be shown to work ([`vendored`]), unless the user +/// where the block cannot be shown to work ([`vendored`]) or a lock spells +/// the package's version otherwise ([`spelled_otherwise`]), unless the user /// allowed it ([`ALLOW_IN_BAZEL_ENV`]). A package whose folder /// `nuget.config` already names is let through: the run leaves the config /// as it is. Read-only, and it starts no program. @@ -407,16 +467,42 @@ pub(crate) async fn bazel_refusals<'a>( return Vec::new(); } let root = project_root.to_path_buf(); - let hub = run_blocking(move || { + let (hub, rels) = run_blocking(move || { + // Outside a Bazel workspace nothing is declined: no lock is looked + // for there. + if crate::bazel::bazel_root(&root).is_none() { + return (Vendored::Plain, Vec::new()); + } let governed = super::nuget_config::governed_locks_on_disk(&root); - vendored( - &root, - &governed.map(|governed| governed.locks).unwrap_or_default(), - ) - }); - let Vendored::Declined(why) = hub.await else { - return Vec::new(); + let rels = governed.map(|governed| governed.locks).unwrap_or_default(); + (vendored(&root, &rels), rels) + }) + .await; + // A hub whose block works still finds no package whose version a lock + // spells otherwise ([`spelled_otherwise`]). + let mut locks: Vec<(String, String)> = Vec::new(); + for rel in rels + .into_iter() + .filter(|_| matches!(hub, Vendored::Block(_))) + { + if let Ok(text) = read_regular_to_string(&project_root.join(&rel)).await { + locks.push((rel, text)); + } + } + let why = |purl: &str| match &hub { + Vendored::Plain => None, + Vendored::Declined(why) => Some(why.clone()), + Vendored::Block(_) => { + let (id, version) = parse_nuget_purl(purl)?; + let texts = locks + .iter() + .map(|(rel, text)| (rel.as_str(), text.as_str())); + spelled_otherwise(texts, &id, &normalize_nuget_version(&version)) + } }; + if matches!(hub, Vendored::Plain) { + return Vec::new(); + } let config = match existing_config_path(project_root).await { Some(path) => read_regular_to_string(&path).await.ok(), None => None, @@ -433,25 +519,26 @@ pub(crate) async fn bazel_refusals<'a>( }; sources.iter().any(names) }; - let detail = declined_detail(&why); let declined = candidates.iter().filter(|(_, uuid)| !wired(uuid)); declined - .map(|(purl, _)| (*purl, VENDOR_DECLINED, detail.clone())) + .filter_map(|(purl, _)| Some((*purl, VENDOR_DECLINED, declined_detail(&why(purl)?)))) .collect() } /// Keep the folder of a patch, `uuid_dir_rel`, in the block of the root -/// `MODULE.bazel`, which then holds what `feeds` holds now. +/// `MODULE.bazel`, which then holds what `feeds` holds now, without the +/// folders of `superseded`. async fn keep_in_block( project_root: &Path, feeds: &Feeds, uuid_dir_rel: &str, + superseded: &[String], ) -> Result<(), String> { let path = project_root.join(MODULE_FILE); let module = read_regular_to_string(&path) .await .map_err(|e| format!("unreadable {}: {e}", path.display()))?; - let Some(kept) = with_folder(&module, feeds, uuid_dir_rel) else { + let Some(kept) = with_folder(&module, feeds, uuid_dir_rel, superseded) else { return Err(format!( "the block that socket-patch keeps in {MODULE_FILE} was changed by hand" )); @@ -472,9 +559,12 @@ async fn block_refreshed( feeds: Option<&Feeds>, doubt: Option, uuid_dir_rel: &str, + superseded: &[String], ) -> Option { let why = match feeds { - Some(feeds) => keep_in_block(project_root, feeds, uuid_dir_rel).await.err(), + Some(feeds) => keep_in_block(project_root, feeds, uuid_dir_rel, superseded) + .await + .err(), None => doubt, }?; Some(VendorWarning::new( @@ -540,6 +630,8 @@ pub async fn vendor_nuget( source_key, feeds, hub_doubt, + superseded, + governed_rels, config_path, config_text, locks, @@ -561,7 +653,10 @@ pub async fn vendor_nuget( // A package of a hub: the block follows the hub's tag, wired or not. let block = match dry_run { true => None, - false => block_refreshed(project_root, feeds.as_ref(), hub_doubt, &uuid_dir_rel).await, + false => { + let feeds = feeds.as_ref(); + block_refreshed(project_root, feeds, hub_doubt, &uuid_dir_rel, &superseded).await + } }; if in_sync { // The warning keeps firing on re-runs until the stale copy is @@ -836,8 +931,17 @@ pub async fn vendor_nuget( } } // ── the block of a rules_csharp hub (a failure unwinds both) ───────── - if let Some(feeds) = &feeds { - if let Err(detail) = keep_in_block(project_root, feeds, &uuid_dir_rel).await { + if let Some(first) = feeds { + // As the hub's tag reads now: this run gave a config without a + // package source its first one, and the next run reads the block's + // sources from that file. + let root = project_root.to_path_buf(); + let feeds = match run_blocking(move || vendored(&root, &governed_rels)).await { + Vendored::Block(now) => now, + _ => first, + }; + let kept = keep_in_block(project_root, &feeds, &uuid_dir_rel, &superseded).await; + if let Err(detail) = kept { unwind_locks(&written).await; unwind_config(&config_target, config_text.as_deref(), &uuid_dir).await; result.success = false; @@ -1043,11 +1147,7 @@ pub async fn revert_nuget_opts( }; // The folder the config names: the patch's own, or the one below it // where a hub has the package, when the artifact lies there. - let nested = format!( - "{uuid_dir_rel}/{}/{}", - id.to_lowercase(), - package.version_norm - ); + let nested = hub_folder_rel(&uuid_dir_rel, &id, &package.version_norm); let for_hub = entry.artifact.path.starts_with(&format!("{nested}/")); let feed_rel = if for_hub { &nested } else { &uuid_dir_rel }; // SECURITY: state.json is committed and tamper-able, and the records are @@ -1090,7 +1190,8 @@ pub async fn revert_nuget_opts( } } // Reverse application order: lock pin, then the (no-op) mapping audit - // record, then the authoritative config restore. + // record, then the authoritative config restore. The block of a hub + // goes after them all, below. for w in entry.wiring.iter().rev() { let restored = match w.kind.as_str() { // SECURITY: state.json is committed and tamper-able; the lock @@ -1126,7 +1227,7 @@ pub async fn revert_nuget_opts( CONFIG_SOURCE_WIRING_KIND => { revert_config_record(project_root, feed_rel, &package, w, dry_run).await } - BAZEL_WIRING_KIND => revert_block_record(project_root, &uuid_dir_rel, dry_run).await, + BAZEL_WIRING_KIND => continue, _ => { warnings.push(VendorWarning::new( "vendor_lock_entry_drifted", @@ -1156,6 +1257,36 @@ pub async fn revert_nuget_opts( } } + // The block of a hub goes last, and only with the config's source: a + // lock that failed above leaves it, so the build stays as it was for + // the retry. A config that is left wired keeps its lock pin and its + // package, and the hub takes that package through the block alone: + // without it the hub would read the folder in `nuget.config` as the + // URL of a feed, and the Bazel build would fail. + if entry.wiring.iter().any(|w| w.kind == BAZEL_WIRING_KIND) { + if config_still_routes { + let config = entry + .wiring + .iter() + .find(|c| c.kind == CONFIG_SOURCE_WIRING_KIND) + .map_or("nuget.config", |c| c.file.as_str()); + warnings.push(VendorWarning::new( + "vendor_lock_entry_drifted", + format!( + "{config} still routes {id} to the vendored feed, so the block of \ + {MODULE_FILE} is kept" + ), + )); + } else if let Err(e) = revert_block_record(project_root, &uuid_dir_rel, dry_run).await { + return RevertOutcome { + kept_artifact: false, + success: false, + warnings, + error: Some(e), + }; + } + } + let outcome = RevertOutcome { kept_artifact: false, success: true, @@ -2263,6 +2394,13 @@ struct LockFile { text: String, } +/// The root-relative path and the text of each of `locks`. +fn texts(locks: &[LockFile]) -> impl Iterator { + locks + .iter() + .map(|lock| (lock.rel.as_str(), lock.text.as_str())) +} + /// Put back the locks a failed vendor already re-pinned. async fn unwind_locks(written: &[(&LockFile, &str)]) { for (lock, original) in written { @@ -7336,6 +7474,151 @@ mod tests { assert!(!root.join(&entry.artifact.path).exists()); } + /// A config that the revert leaves wired (tooling wrote it anew, and + /// it still names the folder) keeps its lock pin and its package, and + /// so the block: the hub takes that package through the block alone. + #[tokio::test] + #[serial_test::serial] + async fn a_hub_config_that_is_left_wired_keeps_the_block() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + crate::bazel::nuget::tests::checkout(root); + let (_, entry, _) = unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + let entry = entry.expect("a ledger entry"); + let config = std::fs::read_to_string(root.join("nuget.config")).unwrap(); + std::fs::write(root.join("nuget.config"), config.replace(" <", "\t\t<")).unwrap(); + let kept = hub_files(root); + + let outcome = revert_nuget(&entry, root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.kept_artifact, "{:?}", outcome.warnings); + assert_eq!(hub_files(root), kept, "the block, the config and the lock"); + assert!(root.join(&entry.artifact.path).is_file()); + let says = format!("so the block of {MODULE_FILE} is kept"); + let warned = |w: &VendorWarning| w.detail.contains(&says); + assert!( + outcome.warnings.iter().any(warned), + "{:?}", + outcome.warnings + ); + } + + /// A config without a package source gets nuget.org beside the folder + /// of the patch, and the block holds the sources of the hub's tag as + /// they are after that: the next run writes no file. + #[tokio::test] + #[serial_test::serial] + async fn a_hub_config_without_a_source_gives_the_block_of_the_next_run() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let bare = + "\n\n\n"; + let (dir, blobs, installed, record) = fixture(true, Some(bare)).await; + let root = dir.path(); + crate::bazel::nuget::tests::checkout(root); + let before = hub_files(root); + + let (result, entry, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("a ledger entry"); + let wired = std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(); + let feeds = format!( + " feeds = [\n \"file:.socket/vendor/nuget/{UUID}\",\n \ + \"https://api.nuget.org/v3/index.json\",\n ],\n" + ); + assert!(wired.contains(&feeds), "{wired}"); + let vendored = hub_files(root); + let (again, rerecorded, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(again.success && rerecorded.is_none()); + assert_eq!(hub_files(root), vendored); + + let outcome = revert_nuget(&entry, root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert_eq!(hub_files(root), before); + } + + /// A later patch of a hub's package takes the place of the earlier + /// one in the block, whose source the config keeps: the block names + /// the later folder alone, and goes with it. + #[tokio::test] + #[serial_test::serial] + async fn a_later_patch_of_a_hub_package_takes_the_place_of_the_earlier_one() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + let module = crate::bazel::nuget::tests::checkout(root); + let (first, _, _) = unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(first.success, "{:?}", first.error); + let earlier = format!("file:.socket/vendor/nuget/{UUID}\""); + let wired = std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(); + assert!(wired.contains(&earlier), "{wired}"); + + let mut later = record.clone(); + later.uuid = "33333333-3333-4333-8333-333333333333".to_string(); + let (second, entry, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &later, false).await); + assert!(second.success, "{:?}", second.error); + let entry = entry.expect("a ledger entry"); + let wired = std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(); + let folder = format!("file:.socket/vendor/nuget/{}\"", later.uuid); + assert!( + wired.contains(&folder) && !wired.contains(&earlier), + "{wired}" + ); + // And a run of it again leaves the block as it is. + let (again, rerecorded, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &later, false).await); + assert!(again.success && rerecorded.is_none()); + assert_eq!( + std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(), + wired + ); + + let outcome = revert_nuget(&entry, root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert_eq!( + std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(), + module, + "the block goes with the later folder" + ); + } + + /// A hub asks its feeds for the version as the lock spells it. A lock + /// that spells it otherwise than NuGet writes it is declined: the hub + /// would not find the package in the folder of the patch. + #[tokio::test] + #[serial_test::serial] + async fn a_hub_lock_that_spells_the_version_otherwise_is_declined() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + crate::bazel::nuget::tests::checkout(root); + let lock = std::fs::read_to_string(root.join(PACKAGES_LOCK)).unwrap(); + let spelled = lock.replace("\"resolved\": \"13.0.3\"", "\"resolved\": \"13.0.3.0\""); + assert_ne!(spelled, lock); + std::fs::write(root.join(PACKAGES_LOCK), spelled).unwrap(); + let before = hub_files(root); + + let (code, detail) = + unwrap_refused(run_vendor(root, &blobs, &installed, &record, false).await); + assert_eq!(code, VENDOR_DECLINED); + for part in [ + "packages.lock.json names Newtonsoft.Json 13.0.3.0", + "holds 13.0.3", + "`--mode hosted`", + ] { + assert!(detail.contains(part), "{detail}"); + } + assert!(!root.join(".socket").exists()); + assert_eq!(hub_files(root), before); + assert!(service_preflight(PURL, root, &record).await.is_none()); + // What every way in is told before it fetches anything. + let refused = bazel_refusals(root, &[(PURL, UUID)]).await; + assert_eq!(refused, [(PURL, VENDOR_DECLINED, detail)]); + } + /// The package of a hub lies below `/` in the folder /// of the patch, and that is the path git is asked about. The folder's /// own `.gitignore` reaches over every rule above it, so only an diff --git a/docs/ecosystems.md b/docs/ecosystems.md index e0bc721f0..a722d6358 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1665,9 +1665,15 @@ file as it is. With the lock restored beside such a block, the hub would hold th package to the upstream `contentHash` and the build would fail. Put the block back as socket-patch wrote it, or delete it, and run the command again. +A `nuget.config` that was written anew since the vendored run, and still names the folder, is +left as it is with a warning (`vendor_lock_entry_drifted`), as without Bazel. Its lock pin and +its package stay with it, and so does the block: the hub takes the package through the block +alone, and `dotnet restore` and the Bazel build both keep the patched package. + `vendor --check`, `list` and `vex` see the package as any vendored NuGet package. A later vendored run keeps the block in step with your tag: a source you add to `nuget.config` -reaches the hub once socket-patch has run again. +reaches the hub once socket-patch has run again. A later patch of the same package takes the +place of the earlier one's folder in the block. **Where it declines.** The block is written only where the checkout shows that it works. Elsewhere every command that would vendor the package reports it `failed` with @@ -1703,6 +1709,10 @@ and exit 0. The message names the reason, with the file and line where there is read, and 8.8.2 and 9.3.2 download every package of the lock without it. That is read and not built. - `MODULE.bazel` is a symbolic link, or its block was changed by hand. +- A lock spells the package's version otherwise than NuGet writes it (`1.2.3.0` for `1.2.3`). + The hub asks its feeds for the version as the lock spells it, and the folder of the patch + holds the version as `dotnet restore` writes it. Run `dotnet restore`, which rewrites the + lock. `--allow-vendored-in-bazel` (or `SOCKET_ALLOW_VENDORED_IN_BAZEL=1`) lifts the decline. The package is then vendored as in a project without Bazel, which the hub does not take: that is diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 0c5861ae8..de8cf2163 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 4036 + "max": 4041 }, "lock-readers": { "paths": [ From 5d958bc2e3b2b88efa68c53d6008cbf55b48b660 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 17:00:04 -0500 Subject: [PATCH 11/22] Build the NuGet hub tests on Windows The tests of a package of a rules_csharp hub start from a `nuget.config` that names nuget.org, through a helper of the test module that was held to Unix for the file-mode tests it was written for. The hub tests are not held to Unix, so the test build of the core crate failed on Windows (`cannot find function preexisting_cfg`). The helper is a string and now builds everywhere. Test only. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/vendor/nuget_feed.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index db9e9d163..13360466b 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -4436,7 +4436,6 @@ mod tests { tokio::fs::metadata(p).await.unwrap().permissions().mode() & 0o7777 } - #[cfg(unix)] fn preexisting_cfg() -> &'static str { "\n\ \n\ From 23398b6b1135e399e549359d5731ff1b3d881079 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 16:42:10 -0500 Subject: [PATCH 12/22] 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 12e2edbea546c42530e11eaea4b15abe2ac765a9 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 16:42:10 -0500 Subject: [PATCH 13/22] 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 f3e56238f5acc7e83023166de977e90aec4adf15 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 17:55:54 -0500 Subject: [PATCH 14/22] 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 c5d6d840128e7c3e32c63e8efa8f03c144715bf4 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 24 Nov 2026 17:55:54 -0500 Subject: [PATCH 15/22] 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 c4b202955..5f19e4013 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -3146,8 +3146,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 4fe3b14af543bcc39009df874c61a0d9863431b7 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 11:52:33 -0500 Subject: [PATCH 16/22] 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 6b67c8115573a8b913e8b036b399bccffa797a9c Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 12:24:06 -0500 Subject: [PATCH 17/22] Hold the off switch and the VEX answer to a NuGet package vendored for a hub Two changes of main say something of every package that a Bazel hub builds, and were written before vendored mode kept a block for a rules_csharp hub. The merges took both as they are. This brings their statements in line with the block and tests what they do beside it. No product code changes. The VEX answer for a hub that builds from the lock. Three places said that no test builds a vendored NuGet package under its hub, so nothing is said of one: the paragraph on vendored copies in "Bazel workspaces: VEX", the `vex_bazel_not_in_build` row of the CLI contract, and two comments of `bazel/built.rs`. A flow does build one now, through the block. They say that, and that `vex` does not read the block, so the statement is the same where the block is missing and the build fails (the list of documents that are still wrong has that entry, and now says why that build fails). `nuget::vendored_mode_keeps_the_block_or_declines` asks `vex` after the vendored run in the hub's checkout, on a machine that restored nothing: one `not_affected` statement through the committed copy, and no warning. The switch for a project that Bazel does not build (`SOCKET_NO_BAZEL`). It holds for the NuGet gate through `bazel_root`, and the undo of the block never asked for the workspace. The same flow holds both: with the switch a vendored scan is the scan of the same checkout without its Bazel files, to the byte, where the block would be written and where the package would be declined; and `vendor --revert` with the switch set takes the folder out of the block and leaves every file as it was. The docs section on a project that Bazel does not build and the section on experimental Bazel support of the CLI contract name the NuGet block and its refusal among what the switch turns off, and the undo of the block among what stays on. The module docs of the NuGet flows name the three modes they run. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 8 +-- .../tests/e2e_bazel_build/nuget.rs | 53 ++++++++++++++++--- crates/socket-patch-core/src/bazel/built.rs | 12 +++-- docs/ecosystems.md | 21 ++++++-- 4 files changed, 75 insertions(+), 19 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index d6ae23709..c0a1870d7 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -562,11 +562,11 @@ A patch mirror is a caching proxy the operator runs in front of the patch server ### Bazel workspaces (experimental) -**Experimental, and outside the semver policy.** What socket-patch does because a project is in a Bazel workspace is experimental in its first release. `--allow-vendored-in-bazel`, `--no-bazel` / `--vex-no-bazel`, `SOCKET_ALLOW_VENDORED_IN_BAZEL`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_NO_BAZEL`, the codes that only a Bazel workspace can produce (`vendor_composer_bazel_workspace`, `bazelignore_not_updated`, `vex_bazel_not_in_build`, `redirect_pnpm_bazel_workspace_hidden`, `redirect_cargo_bazel_config_unread`, `redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`, `redirect_bazel_gem_checksums_pinned` and every `maven_bazel_*`), the lines socket-patch keeps in `.bazelignore`, the block it keeps in `MODULE.bazel` and what vendored mode keeps for the jar of a hub (the directory `.socket/vendor/maven//` and the ledger entry of flavor `bazel`) may change or be removed in any release without a semver bump. The flags, variables and codes are marked **Experimental** where this document lists them, and so are its passages about a Bazel workspace; every other sentence of this document about a Bazel workspace, such as a reference to one of those codes, is under this section's rule as well. The one rule that is not experimental: none of it applies to a project in no Bazel workspace, whose runs are those of a release without it. +**Experimental, and outside the semver policy.** What socket-patch does because a project is in a Bazel workspace is experimental in its first release. `--allow-vendored-in-bazel`, `--no-bazel` / `--vex-no-bazel`, `SOCKET_ALLOW_VENDORED_IN_BAZEL`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_NO_BAZEL`, the codes that only a Bazel workspace can produce (`vendor_composer_bazel_workspace`, `vendor_nuget_bazel_workspace`, `bazelignore_not_updated`, `vex_bazel_not_in_build`, `redirect_pnpm_bazel_workspace_hidden`, `redirect_cargo_bazel_config_unread`, `redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`, `redirect_bazel_gem_checksums_pinned` and every `maven_bazel_*`), the lines socket-patch keeps in `.bazelignore`, the blocks it keeps in `MODULE.bazel` (the Maven entries, and the feeds of the NuGet packages vendored for a rules_csharp hub) and what vendored mode keeps for the jar of a hub (the directory `.socket/vendor/maven//` and the ledger entry of flavor `bazel`) may change or be removed in any release without a semver bump. The flags, variables and codes are marked **Experimental** where this document lists them, and so are its passages about a Bazel workspace; every other sentence of this document about a Bazel workspace, such as a reference to one of those codes, is under this section's rule as well. The one rule that is not experimental: none of it applies to a project in no Bazel workspace, whose runs are those of a release without it. * **The lookup.** A project is in a Bazel workspace when its directory, or one above it up to the root of its git checkout (a checkout whose `.git` belongs to a trusted owner; in no such checkout the project's own directory only), holds a regular file named `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`. A link to a regular file counts, and a directory of such a name does not. The name is looked up as Bazel's own client looks it up, by whether a file answers to it: on a disk that folds case a regular file named `workspace` or `Module.bazel` counts, as it does for Bazel itself, and is read as the workspace file it answers for. `SOCKET_NO_BAZEL` is the way out for a checkout where such a file is no workspace. -* **The off switch (`SOCKET_NO_BAZEL`).** The lookup cannot tell whether Bazel builds the project: a service of a monorepo that Bazel never builds, and a checkout with a leftover workspace file, are in a Bazel workspace by it. A truthy `SOCKET_NO_BAZEL` (`1`/`true`/`yes`/`on`/`y`/`t`, in any case and with blanks around it: what `SOCKET_NO_CONFIG`, `SOCKET_NO_API_TOKEN` and `SOCKET_NO_UPDATE_CHECK` take) makes the lookup answer that there is none, on disk and for the in-memory engine, whose path selection then asks for no Bazel file and which judges none that a host hands over all the same. Every command then gives what it gives in the same checkout without the workspace file: the exit code, both streams and every written file. It switches off the Composer refusal (`vendor_composer_bazel_workspace`), the adding of `.bazelignore` lines, the hosted withholds for Cargo, NuGet, gems and pnpm (`redirect_cargo_bazel_config_unread`, `redirect_bazel_*`, `redirect_pnpm_bazel_workspace_hidden`), the rule that keeps a pnpm lock that a rules_js hub reads, or may read, off the route through a named registry (the lock is then routed where it is in the checkout without the workspace file), everything of Maven that rests on a hub (the entries hosted and vendored mode write to the block, the directory vendored mode keeps for a hub's jar, the jars of a hub as packages of a hosted scan, the sweep of stale entries and every `maven_bazel_*` refusal and warning), the `affected` statements of VEX (`vex_bazel_not_in_build`), and the allowance for the `BUILD.bazel` that cargo-bazel writes into a vendored crate. For a vendored Maven patch that means the run of a checkout no hub is in: beside a Maven or Gradle build the run vendors for that build alone, writes nothing for a hub, says nothing of one and names no file of one among those to commit, so a Bazel build that is there after all keeps the upstream jar of a patch the run reports as vendored; and in a checkout only Bazel builds the patch is refused for want of a build (`vendor_jvm_shape_unsupported`, `no_build_file`, with no word of an entry the block holds), and a hosted entry of the block is no pin that `vendor` ejects. The switch is for the whole run and for every program it starts, while whether Bazel builds a project is a fact of each project: a bare scan covers every project of a checkout, and with the switch set a project that Bazel does build loses each of these guards too, in a run that exits 0. Set it for runs in the directory of the project that Bazel does not build, not for a run over a checkout that also holds projects Bazel builds; there is no setting per project. Environment only: there is no flag (`vex --no-bazel` is the VEX step's own option), no repository file can set it, and a run that honours it prints nothing about it. A child process inherits it (it is not among the variables of the child-process paragraph below): it is the user's word about the checkout, no credential and no flag of one run, so a socket-patch that a spawned program starts in that checkout gives the same run. -* **What stays on with the switch.** Listing and undoing what an earlier run wrote for Bazel. The block of the root `MODULE.bazel` is still read by `list`, `vex`, `scan`, `vendor --check`, `repair`, `rollback`, `remove`, `vendor --revert` and a vendored takeover, by the reader of a run without the switch: an entry of hosted mode as a hosted pin, an entry of vendored mode as the wiring of the jar committed under `.socket/vendor/maven//`, and either one withheld from attestation when no pinned hub takes it any more, which `vendor --check` names for a vendored one. `rollback` and `remove` take a hosted entry out; they and `vendor --revert` take a vendored one out with its directory and its ledger entry, in the one commit that also holds the files of a Maven or Gradle build; `repair` puts back a lost directory of a patch that only a hub takes. Each of them says what it says without the switch. No entry is written or replaced: `vendor` leaves a hosted entry of the block as it is, and a hosted run takes over no patch that vendored mode keeps for a hub alone, which stays vendored (`redirect_takeover_kept_vendored`). Beside a Maven or Gradle build the hub's directory is a copy that `vendor` writes only without the switch: with it, one that was lost is named by `vendor --check` and stays lost until the undo takes its entry out. The `.bazelignore` pair of a copy directory that is gone is still removed by the command that removed the copy (`rollback`, `remove`, `vendor --revert`, `repair`, a scan), with `bazelignore_not_updated` when the file cannot be written; no pair is added. This is of the commands on disk: the in-memory engine writes no block and undoes none, and with the switch it is handed no `MODULE.bazel` to read one from. +* **The off switch (`SOCKET_NO_BAZEL`).** The lookup cannot tell whether Bazel builds the project: a service of a monorepo that Bazel never builds, and a checkout with a leftover workspace file, are in a Bazel workspace by it. A truthy `SOCKET_NO_BAZEL` (`1`/`true`/`yes`/`on`/`y`/`t`, in any case and with blanks around it: what `SOCKET_NO_CONFIG`, `SOCKET_NO_API_TOKEN` and `SOCKET_NO_UPDATE_CHECK` take) makes the lookup answer that there is none, on disk and for the in-memory engine, whose path selection then asks for no Bazel file and which judges none that a host hands over all the same. Every command then gives what it gives in the same checkout without the workspace file: the exit code, both streams and every written file. It switches off the Composer refusal (`vendor_composer_bazel_workspace`), the block and the refusal of vendored mode for a NuGet package of a rules_csharp hub (`vendor_nuget_bazel_workspace`: the package is vendored as in a checkout without the workspace file), the adding of `.bazelignore` lines, the hosted withholds for Cargo, NuGet, gems and pnpm (`redirect_cargo_bazel_config_unread`, `redirect_bazel_*`, `redirect_pnpm_bazel_workspace_hidden`), the rule that keeps a pnpm lock that a rules_js hub reads, or may read, off the route through a named registry (the lock is then routed where it is in the checkout without the workspace file), everything of Maven that rests on a hub (the entries hosted and vendored mode write to the block, the directory vendored mode keeps for a hub's jar, the jars of a hub as packages of a hosted scan, the sweep of stale entries and every `maven_bazel_*` refusal and warning), the `affected` statements of VEX (`vex_bazel_not_in_build`), and the allowance for the `BUILD.bazel` that cargo-bazel writes into a vendored crate. For a vendored Maven patch that means the run of a checkout no hub is in: beside a Maven or Gradle build the run vendors for that build alone, writes nothing for a hub, says nothing of one and names no file of one among those to commit, so a Bazel build that is there after all keeps the upstream jar of a patch the run reports as vendored; and in a checkout only Bazel builds the patch is refused for want of a build (`vendor_jvm_shape_unsupported`, `no_build_file`, with no word of an entry the block holds), and a hosted entry of the block is no pin that `vendor` ejects. The switch is for the whole run and for every program it starts, while whether Bazel builds a project is a fact of each project: a bare scan covers every project of a checkout, and with the switch set a project that Bazel does build loses each of these guards too, in a run that exits 0. Set it for runs in the directory of the project that Bazel does not build, not for a run over a checkout that also holds projects Bazel builds; there is no setting per project. Environment only: there is no flag (`vex --no-bazel` is the VEX step's own option), no repository file can set it, and a run that honours it prints nothing about it. A child process inherits it (it is not among the variables of the child-process paragraph below): it is the user's word about the checkout, no credential and no flag of one run, so a socket-patch that a spawned program starts in that checkout gives the same run. +* **What stays on with the switch.** Listing and undoing what an earlier run wrote for Bazel. The block of the root `MODULE.bazel` is still read by `list`, `vex`, `scan`, `vendor --check`, `repair`, `rollback`, `remove`, `vendor --revert` and a vendored takeover, by the reader of a run without the switch: an entry of hosted mode as a hosted pin, an entry of vendored mode as the wiring of the jar committed under `.socket/vendor/maven//`, and either one withheld from attestation when no pinned hub takes it any more, which `vendor --check` names for a vendored one. `rollback` and `remove` take a hosted entry out; they and `vendor --revert` take a vendored one out with its directory and its ledger entry, in the one commit that also holds the files of a Maven or Gradle build; `repair` puts back a lost directory of a patch that only a hub takes. Each of them says what it says without the switch. No entry is written or replaced: `vendor` leaves a hosted entry of the block as it is, and a hosted run takes over no patch that vendored mode keeps for a hub alone, which stays vendored (`redirect_takeover_kept_vendored`). Beside a Maven or Gradle build the hub's directory is a copy that `vendor` writes only without the switch: with it, one that was lost is named by `vendor --check` and stays lost until the undo takes its entry out. The `.bazelignore` pair of a copy directory that is gone is still removed by the command that removed the copy (`rollback`, `remove`, `vendor --revert`, `repair`, a scan), with `bazelignore_not_updated` when the file cannot be written; no pair is added. The block that vendored mode keeps in `MODULE.bazel` for the NuGet packages of a rules_csharp hub is undone as without the switch: `vendor --revert`, `rollback` and `remove` take the folder of a patch out of it, and the block with its last folder; no folder is added. This is of the commands on disk: the in-memory engine writes no block and undoes none, and with the switch it is handed no `MODULE.bazel` to read one from. ### socket.yml patch policy (v5.0) @@ -4191,7 +4191,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` | **Experimental** (Bazel workspaces). 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` | **Experimental** (Bazel workspaces). 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 (no test builds one under its hub), for a vendored crate (rules_rust builds it), for a vendored NuGet package (rules_csharp builds it through the block that vendored mode keeps in `MODULE.bazel`, which `vex` does not read: the statement is the same where that block is missing and the build fails), 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 364c60e6e..120e5a76b 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs @@ -1,4 +1,4 @@ -//! Hosted and agent mode for a NuGet package that comes through +//! Hosted, vendored 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 @@ -1338,11 +1338,13 @@ const SELECTED: &str = "{\"lockFileVersion\": 28, \"registryFileHashes\": {\ /// /// In the fixture's workspace it keeps the package where a feed of the hub /// has it and its block in `MODULE.bazel`; a second run changes nothing; -/// `vendor --check` passes and `list` says what it says without Bazel; and +/// `vendor --check` passes, `list` says what it says without Bazel and +/// `vex` says not affected, through the committed copy; and /// `vendor --revert`, `rollback` and `remove` each put every file back -/// byte for byte, the block with its one folder. Beside a block that was -/// changed by hand no undo changes a file, and each says where the block -/// is; with the block deleted by hand, the undo puts the rest back. +/// byte for byte, the block with its one folder, also for a user who +/// switched the Bazel support off (`SOCKET_NO_BAZEL`). Beside a block that +/// was changed by hand no undo changes a file, and each says where the +/// block is; with the block deleted by hand, the undo puts the rest back. /// /// Where the block cannot be shown to work, `scan` and `get` decline the /// package with exit 1 and write nothing, a dry run lists it and exits 0, @@ -1350,7 +1352,9 @@ const SELECTED: &str = "{\"lockFileVersion\": 28, \"registryFileHashes\": {\ /// that would take it over and the `vendor` that would eject it are /// declined too, and where the block does work `vendor` ejects the pin /// into it. With `--allow-vendored-in-bazel`, or its variable, the package -/// is vendored as without Bazel. +/// is vendored as without Bazel. With `SOCKET_NO_BAZEL=1` the run is the +/// one of the same checkout without its Bazel files, to the byte, where +/// the block works and where the package is declined. #[test] fn vendored_mode_keeps_the_block_or_declines() { let test = "nuget::vendored_mode_keeps_the_block_or_declines"; @@ -1428,6 +1432,7 @@ fn vendored_mode_keeps_the_block_or_declines() { // The fixture's workspace: the block, and every way to take it out. let hub = checkout(Some(&module), Some("9.3.2")); let before = hub.tree(); + let bare = tempfile::tempdir().expect("create a .NET home"); let undo: [&[&str]; 3] = [ &["vendor", "--revert"], &["rollback", "--yes"], @@ -1460,6 +1465,13 @@ fn vendored_mode_keeps_the_block_or_declines() { let (listed, as_without) = (list(&hub), list(&plain)); assert_eq!(listed.envelope["events"][0]["details"]["mode"], "vendored"); assert_eq!(listed.envelope, as_without.envelope, "{}", listed.dump); + // `vex` says not affected, through the committed copy: the hub + // builds that copy through the block, so the call that hands the + // lock to rules_csharp is no reason to say affected. It is asked + // on a machine that restored nothing, where it has nothing to + // warn of: NuGet's folder of `home` holds the unpatched copy. + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, bare.path(), args); + hub.stands_alone(run, &Claim::new(&purl, &patch.uuid, How::Vendored), true); assert_eq!(changed(&vendored, &hub.tree()), NOTHING, "{test}: {undo:?}"); let ran = socket_patch(&hub, &standin, home.path(), undo); assert_eq!(ran.code, 0, "{test}: {}", ran.dump); @@ -1470,6 +1482,21 @@ fn vendored_mode_keeps_the_block_or_declines() { ran.dump ); } + // The switch for a project that Bazel does not build leaves the undo + // on: with it the folder goes out of the block all the same. + let ran = scan(&hub, &[]); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + let ran = on_machine(&standin, home.path(), |api, env| { + let env = [env, &[("SOCKET_NO_BAZEL", "1")]].concat(); + hub.socket_patch(api, undo[0], &env) + }); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + assert_eq!( + changed(&before, &hub.tree()), + NOTHING, + "{test}: {}", + ran.dump + ); // A block that was changed by hand keeps the folder of the patch, and // with the lock restored beside it the Bazel build would fail on the @@ -1633,6 +1660,20 @@ fn vendored_mode_keeps_the_block_or_declines() { assert_eq!(ran.envelope, without.envelope, "{test}: {}", ran.dump); assert_eq!(wrote(&cell, &before), as_before, "{test}: {}", ran.dump); } + + // The switch for a project that Bazel does not build: the run of the + // same checkout without its Bazel files, to the byte. Beside those + // files the run is another one: the block, or the package declined. + let bazel = [MODULE, BAZEL_LOCK, BAZEL_VERSION]; + for (release, code) in [(Some("9.3.2"), 0), (None, 1)] { + let cell = checkout(Some(&module), release); + let origin = standin.origin(); + let args = [&VENDORED[..], &["--patch-server-url", &origin]].concat(); + let beside = on_machine(&standin, home.path(), |api, env| { + cell.off_is_without_bazel(api, &args, env, &bazel) + }); + assert_eq!(beside[0]["code"], code, "{test}: {beside:#}"); + } } /// What a run of agent mode is made of. diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index f569ec39d..01efb002b 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -15,9 +15,11 @@ //! 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. +//! does build a vendored tarball, and rules_rust a vendored crate. +//! rules_csharp builds a vendored package through the block that vendored +//! mode keeps in `MODULE.bazel` ([`super::nuget`]), which is not read +//! here. What rules_ruby does with a vendored gem no test here builds, so +//! it 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 @@ -153,8 +155,8 @@ struct Hub { 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 - /// that they do not. + /// do, rules_csharp does through the block of vendored mode, and of + /// rules_ruby no test here has shown that it does 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 diff --git a/docs/ecosystems.md b/docs/ecosystems.md index c0b595c99..869fb89c6 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2574,6 +2574,10 @@ projects too. What the sections below then do for it: - Composer: vendored mode is declined until the lock names a vendored copy ([Bazel workspaces: Composer](#bazel-workspaces-composer)). +- NuGet: for a package whose lock a rules_csharp `nuget.from_lock` reads, vendored mode + keeps a block in the root `MODULE.bazel`, or declines the package where it cannot show + that the block works + ([Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub)). - Go, Cargo and Maven: the `.bazelignore` at the Bazel root gets two lines for each kind of copy under `.socket` that a run wrote: the Go module copies, the vendored crates of a crate hub, the jars that vendored mode keeps for a rules_jvm_external hub @@ -2631,6 +2635,11 @@ What an earlier run wrote for Bazel is still listed and undone with the variable Beside a Maven or Gradle build the hub's directory is a copy that only a `vendor` run without the variable writes: one that was lost stays lost, `vendor --check` names it, and the undo still takes its entry out. +- The block that vendored mode keeps there for the NuGet packages of a rules_csharp hub + ([Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub)): `vendor --revert`, + `rollback` and `remove` take the folder of a patch out of it, and the block with its last + folder, as they do without the variable. No folder is added: a vendored run writes a + package as in a checkout without the workspace file. - The `.bazelignore` lines: no pair is added, and the pair of a copy that is gone is removed by the command that removed the copy (`rollback`, `remove`, `vendor --revert`, `repair`, a scan). @@ -4681,9 +4690,12 @@ package that it is `affected`, not that it is patched: - **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 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. + releases). A vendored npm tarball is built by rules_js, a vendored crate by rules_rust and + a vendored NuGet package by rules_csharp, through the block that vendored mode keeps in + `MODULE.bazel`, and each keeps its statement. `vex` does not read that block: a vendored + NuGet package keeps its statement without it too (the list at the end of this section). + So does a vendored gem, 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 @@ -4851,7 +4863,8 @@ the build is broken): it is. - **Vendored mode for NuGet** beside `nuget.from_lock`, where the package is vendored and `MODULE.bazel` does not hold its block: a run with `--allow-vendored-in-bazel`, a package - that an earlier release vendored, a block that was taken out by hand. `vex` reads + that an earlier release vendored, a block that was taken out by hand. rules_csharp 0.5.0 + then reads the path of the committed copy as a URL. `vex` reads `nuget.config`, the lock and the committed package, and not the block. Measured for the first two, where the build fails. With the block in place, a build that may not fetch (`--nofetch`) can build the unpatched package while the statement says `not_affected`. From de7cc745bbba44622f8a9449528942cc1e4fc9aa Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 13:14:06 -0500 Subject: [PATCH 18/22] Decline a NuGet package for vendored mode where a hub may read the lock unseen For a NuGet package of a rules_csharp hub, vendored mode keeps a block in the root `MODULE.bazel`, or declines the package where it cannot show that the block works. Where it found no `nuget.from_lock` that reads a lock of the project, it vendored the package as without Bazel, in the folder of the patch alone. In two cases a hub reads the lock all the same. The package is then in none of its feeds: the next Bazel build fetches the upstream package and fails on the `contentHash` that the run re-pinned, after a command that exited 0. - The tag may be hidden. A `MODULE.bazel` that cannot be read (a link that leads out of the workspace, a file over the reader's 1 MiB) read as an empty file, and what the reader could not read was asked only once a tag was found. Where no tag is found, the package is now declined when a file of the workspace that is there was not read as a whole (`Workspace::unread`), since it may be the one that names the ruleset, and when the reader has any doubt in a workspace that names rules_csharp. A doubt in a workspace of other rulesets whose files were all read is about no hub, as it is for a Maven hub since #2228: a project there that Bazel does not build keeps its vendored run. - The tag is gone and the block is still there. The reader does not see the block, so it found no tag, and a second package was written outside the block that still hands the lock to the hub. The package is now declined when the block's own `packages_lock_json` names a lock of the project. A block for the lock of another project of the workspace changes nothing for this one. Both are the refusal this gate already has, `vendor_nuget_bazel_workspace`: exit 1, nothing asked of the patch service and nothing written, a dry run of `scan` and `get` lists the package, `--allow-vendored-in-bazel` and `SOCKET_NO_BAZEL` lift it, and a package that is already wired for the hub stays as it is, with the reason as a warning. The reason names what could not be read, in the words the gate has for a doubt beside a tag, or the line of the block and the two ways on: put the tag back, or `socket-patch vendor --revert`. In the code, `reads` shares the lock a label names with the check of the block (`named`), the words for a doubt are one function (`unsure`), and `bazel/maven.rs` shares its test for a workspace that names a ruleset (`names`). The cap of `bazel` in the line budget follows: 4468 to 4496. Tests, each of which fails without the change it holds: - `bazel/nuget.rs`: the gate over files in memory (a doubt in a workspace of the ruleset, the same doubt where nothing names it, a file that is there and is not read, the root file itself), and `vendored` on disk (the block without its tag, the same block for a project below the root, a `MODULE.bazel` over 1 MiB, and on Unix one that links out of the workspace). - `vendor/nuget_feed.rs`: after a vendored run, with the tag taken out, a later patch is refused with nothing written, by the backend and by the dispatch that every way in asks first, and the wired package keeps its files and gets the warning. - `nuget::vendored_mode_keeps_the_block_or_declines`, through the binary: both shapes are declined by `scan` and `get`, listed by a dry run and told to a person; with the flag and with its variable they are vendored as without Bazel; and with `SOCKET_NO_BAZEL=1` the run is the one of the same checkout without its Bazel files, to the byte. One expectation of this branch changes. The test of a project whose lock no tag reads held a workspace of rules_csharp with a use of the extension's proxy that is no call of a tag to the run without Bazel. It is declined now, and the row moved to the new test of the gate. The docs section "Vendored mode under a rules_csharp hub", the entry of the section on a project that Bazel does not build and the contract row of the refusal say the same. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../tests/e2e_bazel_build/nuget.rs | 67 ++++-- crates/socket-patch-core/src/bazel/maven.rs | 17 +- crates/socket-patch-core/src/bazel/nuget.rs | 222 ++++++++++++++++-- .../src/vendor/nuget_feed.rs | 57 +++++ docs/ecosystems.md | 25 +- scripts/loc-budget.json | 2 +- 7 files changed, 339 insertions(+), 53 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index c0a1870d7..fb4c4d5e9 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2548,7 +2548,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` | **Experimental** (Bazel workspaces). 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` or `SOCKET_NO_BAZEL=1`, `vendor --revert`, and a package of a project that uses vendored mode already, by a release before this refusal or by a run with the flag: any package when `packages` of `composer.lock` names a copy under `.socket/vendor/composer`, and a package of `packages-dev` when `packages-dev` names one. Such a package is refused nothing: not a newer patch, not its first patch, not a `scan` or `get` with no `--mode`. A package of `packages` is still refused while only `packages-dev` names a copy, and so is a package the lock does not hold. So the first vendored path in a section a Bazel rule may install is what is refused, and the detail says so. That keeps a setup of an earlier release working and breaks no build: either no Bazel rule installs from that lock, or one does and its build already fails on a path in a section it installs, which one more path there does not change. The section matters because a rule may run `composer install --no-dev`, which reads `packages` alone: a copy that only `packages-dev` names breaks no such build. 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_nuget_bazel_workspace` | `failed`; `skipped` (warning, vendor advisory event) for a package that is already vendored for the hub | **Experimental** (Bazel workspaces). vendor / scan / get `--mode vendored` (nuget): a rules_csharp `nuget.from_lock` tag of the project's Bazel workspace reads a lock of the project, and the block that makes the hub take the committed package cannot be shown to work from the checkout. Vendored mode keeps such a package at `.socket/vendor/nuget////..nupkg`, names that directory in `nuget.config`, and appends one managed block to the root `MODULE.bazel`: a `nuget.from_lock` of its own whose `feeds` are `file:.socket/vendor/nuget/` for each vendored patch and then the sources the hub had without it (rules_csharp 0.5.0 on Bazel 9.3.2, 8.8.2, 7.7.2). It declines when: the project is not the root of its Bazel workspace, or another workspace lies above it in the checkout; the workspace has more than one `nuget.from_lock`, or its tags cannot be read with certainty; the tag is not a call of its own with every argument written out, is called on an isolated or dev-dependency `use_extension`, or has `local_package_dirs`, `netrc` or `auth_patterns`; its `nuget_config` cannot be read, or a package source cannot stand in a string; it has `feeds` and a `nuget_config` without a package source (the run names its folder there, and rules_csharp takes the sources of that file in place of `feeds`); `MODULE.bazel.lock` does not show that Bazel selected rules_csharp 0.5.0; the checkout does not name Bazel 9.3.2, 8.8.2 or 7.7.2 (`.bazelversion` / `.bazeliskrc`); an rc file names `--repository_disable_download`, `--vendor_dir` or a remote downloader (`--experimental_remote_downloader`), or a directory at the root holds `VENDOR.bazel`; `MODULE.bazel` is a symbolic link, or its block was changed by hand; a lock spells the package's version otherwise than NuGet writes it (`1.2.3.0` for `1.2.3`: the hub asks its feeds for the lock's spelling). 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. The detail names the reason, with the file and line where there is one, and `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel` or `SOCKET_NO_BAZEL=1` (the package is vendored as without Bazel), `vendor --revert`, a package whose folder `nuget.config` already names (the run leaves the config as it is), and a project whose locks no `nuget.from_lock` reads, which is vendored as without Bazel. As an advisory event: a package that is vendored for the hub, whose block can no longer be shown to work or was changed by hand; the block is left as it is. The undo of such a package beside a block that was changed by hand fails and changes nothing (`revert_failed` from `vendor --revert`, `vendor_revert_failed` from `rollback` and `remove`; exit 1): the detail names the line of the block, and the lock restored beside it would fail the Bazel build. An undo that leaves `nuget.config` wired (`vendor_lock_entry_drifted`: the file was written anew and still names the folder) keeps the block with the lock pin and the package. See docs/ecosystems.md "Bazel workspaces: NuGet". | +| `vendor_nuget_bazel_workspace` | `failed`; `skipped` (warning, vendor advisory event) for a package that is already vendored for the hub | **Experimental** (Bazel workspaces). vendor / scan / get `--mode vendored` (nuget): a rules_csharp `nuget.from_lock` tag of the project's Bazel workspace reads a lock of the project, or may, and the block that makes the hub take the committed package cannot be shown to work from the checkout. Vendored mode keeps such a package at `.socket/vendor/nuget////..nupkg`, names that directory in `nuget.config`, and appends one managed block to the root `MODULE.bazel`: a `nuget.from_lock` of its own whose `feeds` are `file:.socket/vendor/nuget/` for each vendored patch and then the sources the hub had without it (rules_csharp 0.5.0 on Bazel 9.3.2, 8.8.2, 7.7.2). It declines when: the project is not the root of its Bazel workspace, or another workspace lies above it in the checkout; the workspace has more than one `nuget.from_lock`, or its tags cannot be read with certainty; the tag is not a call of its own with every argument written out, is called on an isolated or dev-dependency `use_extension`, or has `local_package_dirs`, `netrc` or `auth_patterns`; its `nuget_config` cannot be read, or a package source cannot stand in a string; it has `feeds` and a `nuget_config` without a package source (the run names its folder there, and rules_csharp takes the sources of that file in place of `feeds`); `MODULE.bazel.lock` does not show that Bazel selected rules_csharp 0.5.0; the checkout does not name Bazel 9.3.2, 8.8.2 or 7.7.2 (`.bazelversion` / `.bazeliskrc`); an rc file names `--repository_disable_download`, `--vendor_dir` or a remote downloader (`--experimental_remote_downloader`), or a directory at the root holds `VENDOR.bazel`; `MODULE.bazel` is a symbolic link, or its block was changed by hand; `MODULE.bazel` holds the block and the `nuget.from_lock` it was written beside is gone (the block's own tag still hands the lock to the hub: put the tag back, or run `socket-patch vendor --revert`); no tag that reads a lock of the project is found and one may be hidden (`MODULE.bazel` or a file it includes is there and is not read as a whole, or the workspace names rules_csharp and a part of those files is not read with certainty: the detail names what could not be read); a lock spells the package's version otherwise than NuGet writes it (`1.2.3.0` for `1.2.3`: the hub asks its feeds for the lock's spelling). 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. The detail names the reason, with the file and line where there is one, and `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel` or `SOCKET_NO_BAZEL=1` (the package is vendored as without Bazel), `vendor --revert`, a package whose folder `nuget.config` already names (the run leaves the config as it is), and a project whose locks no `nuget.from_lock` reads and none can be hidden (also in a workspace that does not name rules_csharp and whose files are all read as a whole, whatever else of them is not read with certainty), which is vendored as without Bazel. As an advisory event: a package that is vendored for the hub, whose block can no longer be shown to work or was changed by hand; the block is left as it is. The undo of such a package beside a block that was changed by hand fails and changes nothing (`revert_failed` from `vendor --revert`, `vendor_revert_failed` from `rollback` and `remove`; exit 1): the detail names the line of the block, and the lock restored beside it would fail the Bazel build. An undo that leaves `nuget.config` wired (`vendor_lock_entry_drifted`: the file was written anew and still names the folder) keeps the block with the lock pin and the package. See docs/ecosystems.md "Bazel workspaces: NuGet". | | `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/nuget.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs index 120e5a76b..6a54df425 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs @@ -1348,13 +1348,17 @@ const SELECTED: &str = "{\"lockFileVersion\": 28, \"registryFileHashes\": {\ /// /// Where the block cannot be shown to work, `scan` and `get` decline the /// package with exit 1 and write nothing, a dry run lists it and exits 0, -/// and a person reads the reason. A pin of hosted mode stays: the scan +/// and a person reads the reason. So it is where no tag of the checkout +/// shows the hub: a module file that is not read may hold the tag, and a +/// block without the tag it was written beside still hands the lock to +/// the hub. A pin of hosted mode stays: the scan /// that would take it over and the `vendor` that would eject it are /// declined too, and where the block does work `vendor` ejects the pin /// into it. With `--allow-vendored-in-bazel`, or its variable, the package -/// is vendored as without Bazel. With `SOCKET_NO_BAZEL=1` the run is the -/// one of the same checkout without its Bazel files, to the byte, where -/// the block works and where the package is declined. +/// is vendored as without Bazel, whatever declined it. With +/// `SOCKET_NO_BAZEL=1` the run is the one of the same checkout without its +/// Bazel files, to the byte, where the block works and wherever the +/// package is declined. #[test] fn vendored_mode_keeps_the_block_or_declines() { let test = "nuget::vendored_mode_keeps_the_block_or_declines"; @@ -1539,16 +1543,36 @@ fn vendored_mode_keeps_the_block_or_declines() { // Where the block cannot be shown to work: declined by every command // that would vendor, with nothing asked of the patch service. The - // last row is a tag with `feeds` beside a config without a source: the - // run would name its folder there, and the next one would take the - // sources of that file for the hub's in place of those feeds. + // fourth row is a tag with `feeds` beside a config without a source: + // the run would name its folder there, and the next one would take the + // sources of that file for the hub's in place of those feeds. The last + // two are hubs that no tag of the checkout shows. The module file is + // larger than socket-patch reads, so it may hold the tag; and the tag + // is gone, while the block of an earlier vendored run still hands the + // lock to the hub. let asked = standin.asked(&service); + let large = format!("{module}{}", "#\n".repeat(1 << 19)); + let unread = "MODULE.bazel: it cannot be read: it is larger than 1 MiB, so socket-patch \ + cannot tell which `nuget.from_lock` tags the workspace has"; + let tag = + format!("nuget.from_lock(\n{NAMES_CONFIG} packages_lock_json = \"//:{LOCK}\",\n)\n"); + let untagged = module.replace(&tag, ""); + assert_ne!(untagged, module, "{test}"); + let earlier = block(".socket/vendor/nuget/7e57ce11-0000-4000-8000-5184602cd3cc"); + let orphaned = format!("{untagged}\n{earlier}"); + let orphan = format!( + "MODULE.bazel:{}: the block that socket-patch keeps there still reads `//:{LOCK}` for the \ + hub, and the `nuget.from_lock` it was written beside is gone, so a package vendored now \ + would not be among the block's feeds: put that tag back, or take the vendored packages \ + out (`socket-patch vendor --revert`), and run this command again", + untagged.lines().count() + 2 + ); let dirs = module.replace(NAMES_CONFIG, " local_package_dirs = [\"/opt/nuget\"],\n"); let fed = format!(" feeds = [\"https://nuget.private.example/v3/index.json\"],\n{NAMES_CONFIG}"); let fed = module.replace(NAMES_CONFIG, &fed); let sourceless = "\n \n \n\n"; - let rows: [(&str, Option<&str>, Option<&str>, &str); 4] = [ + let rows: [(&str, Option<&str>, Option<&str>, &str); 6] = [ ( &module, None, @@ -1574,6 +1598,8 @@ fn vendored_mode_keeps_the_block_or_declines() { "MODULE.bazel:9: this `nuget.from_lock` has `feeds`, and its `nuget_config` \ `//:nuget.config` names no package source", ), + (&large, Some("9.3.2"), None, unread), + (&orphaned, Some("9.3.2"), None, &orphan), ]; for (module, release, config, why) in rows { let cell = checkout(Some(module), release); @@ -1643,9 +1669,15 @@ fn vendored_mode_keeps_the_block_or_declines() { assert_eq!(text(&ejected, MODULE), appended, "{test}: {}", eject.dump); assert!(!text(&ejected, CONFIG).contains(PATCH_HOST), "{test}"); - // The user's word, as a flag and as its variable: as without Bazel. - for flag in [true, false] { - let cell = checkout(Some(&module), None); + // The user's word, as a flag and as its variable: as without Bazel, + // also where no tag of the checkout shows the hub. + let lifted: [(&str, Option<&str>); 3] = [ + (&module, None), + (&large, Some("9.3.2")), + (&orphaned, Some("9.3.2")), + ]; + for ((module, release), flag) in lifted.iter().flat_map(|row| [(*row, true), (*row, false)]) { + let cell = checkout(Some(module), release); let before = cell.tree(); let ran = match flag { true => scan(&cell, &["--allow-vendored-in-bazel"]), @@ -1663,10 +1695,17 @@ fn vendored_mode_keeps_the_block_or_declines() { // The switch for a project that Bazel does not build: the run of the // same checkout without its Bazel files, to the byte. Beside those - // files the run is another one: the block, or the package declined. + // files the run is another one: the block, or the package declined, + // also where no tag of the checkout shows the hub. let bazel = [MODULE, BAZEL_LOCK, BAZEL_VERSION]; - for (release, code) in [(Some("9.3.2"), 0), (None, 1)] { - let cell = checkout(Some(&module), release); + let switched: [(&str, Option<&str>, i32); 4] = [ + (&module, Some("9.3.2"), 0), + (&module, None, 1), + (&large, Some("9.3.2"), 1), + (&orphaned, Some("9.3.2"), 1), + ]; + for (module, release, code) in switched { + let cell = checkout(Some(module), release); let origin = standin.origin(); let args = [&VENDORED[..], &["--patch-server-url", &origin]].concat(); let beside = on_machine(&standin, home.path(), |api, env| { diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 2fe024947..8d3ef5779 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -451,6 +451,15 @@ impl Asked { } } +/// Whether a call of a file of `ws` that was read names the ruleset +/// `module`: a `bazel_dep` of it, or an override. +pub(super) fn names(ws: &Workspace, module: &str) -> bool { + let module = Value::Str(module.to_string()); + let names = |call: &Call| [call.arg("name"), call.arg("module_name")].contains(&Some(&module)); + let mut files = ws.files.iter(); + files.any(|(_, file)| file.calls.iter().any(names)) +} + /// What the root module of `ws` says of the release of the ruleset /// `module`: by its calls that name the ruleset, a `bazel_dep` and the /// overrides, which are the functions whose name ends in `_override`. @@ -619,13 +628,7 @@ impl Hubs { } } } - let module = Value::Str(EXTENSION.module.to_string()); - let names = - |call: &Call| [call.arg("name"), call.arg("module_name")].contains(&Some(&module)); - let named = ws - .files - .iter() - .any(|(_, file)| file.calls.iter().any(names)); + let named = names(&ws, EXTENSION.module); 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()) { diff --git a/crates/socket-patch-core/src/bazel/nuget.rs b/crates/socket-patch-core/src/bazel/nuget.rs index 6d509f978..c7893e625 100644 --- a/crates/socket-patch-core/src/bazel/nuget.rs +++ b/crates/socket-patch-core/src/bazel/nuget.rs @@ -51,7 +51,7 @@ use std::path::Path; use serde::{Deserialize, Serialize}; use super::block::{self, Found, END}; -use super::maven::{asked, proxy, Asked}; +use super::maven::{asked, names, proxy, Asked}; use super::rc::{declared_release, mentions, ModuleLock, Release}; use super::starlark::{How, Value}; use super::workspace::{disk, disk_up_to, Doubt, Entry, Extension, Repo, Tag, Tags, Workspace}; @@ -296,20 +296,30 @@ fn prefix(root: &BazelRoot) -> String { fn reads(ws: &Workspace, tag: &Tag, dir: &str, locks: &[String]) -> Option { let at = format!("{}:{}", tag.file, tag.call.line); match tag.call.arg("packages_lock_json") { - Some(Value::Str(label)) => { - let label = ws.label(label).filter(|label| label.repo == Repo::Main); - let path = label?.path(); - let ours = |lock: &&String| path.eq_ignore_ascii_case(&format!("{dir}{lock}")); - Some(match locks.iter().find(ours) { - Some(lock) => Read::Ours(lock.clone()), - None => Read::Other(at, path, None), - }) - } + Some(Value::Str(label)) => Some(match named(ws, label, dir, locks)? { + Ok(lock) => Read::Ours(lock.clone()), + Err(path) => Read::Other(at, path, None), + }), Some(_) => Some(Read::Any(at)), None => tag.call.unpacks().then_some(Read::Any(at)), } } +/// The file of the checkout that the label `label` names: the lock of +/// `locks` it is for the project in `dir`, or else its path from the Bazel +/// root. `None`: it names no file of the main repository. +fn named<'a>( + ws: &Workspace, + label: &str, + dir: &str, + locks: &'a [String], +) -> Option> { + let label = ws.label(label).filter(|label| label.repo == Repo::Main); + let path = label?.path(); + let ours = |lock: &&String| path.eq_ignore_ascii_case(&format!("{dir}{lock}")); + Some(locks.iter().find(ours).ok_or(path)) +} + /// [`withheld`] for the workspace `ws` and the project in its directory /// `dir` (empty, or with a `/` at its end), before the locks of the other /// tags are read. `exact`: a label names `config` only in its own case. @@ -533,10 +543,11 @@ pub struct Feeds { #[derive(Debug, PartialEq, Eq)] pub enum Vendored { /// What it does without Bazel: the project is in no Bazel workspace, - /// or no `nuget.from_lock` reads a lock of it. + /// or no `nuget.from_lock` reads a lock of it and none that does can + /// be hidden. Plain, - /// Nothing: the hub reads a lock of the project, and this is why the - /// block cannot be shown to work. + /// Nothing: the hub reads a lock of the project, or may, and this is + /// why the block cannot be shown to work. Declined(String), /// It keeps the package where a feed of the hub has one, and its /// folder in the block. @@ -560,6 +571,13 @@ pub enum Vendored { /// `VENDOR.bazel`); and `MODULE.bazel` is a file whose block, if it has /// one, is as socket-patch wrote it. /// +/// A project whose lock no tag reads is vendored as without Bazel, unless +/// a hub may read the lock all the same. That is declined too: a package +/// in the folder of its patch alone is in no feed of such a hub, whose +/// build then fails on the re-pinned lock. The block is there and the tag +/// it was written beside is gone, so the block's own tag still hands the +/// lock to the hub; or a tag may not have been read ([`gate`]). +/// /// Not seen: a tag of another Bazel module, whose sources the hub takes /// after the block's; a module that depends on this one, where Bazel reads /// the folder from another root; a vendor directory below the first level; @@ -581,10 +599,24 @@ pub fn vendored(project: &Path, locks: &[String]) -> Vendored { _ => on_disk(path), }; let files = disk_up_to(&root.dir, MAX_LOCK); - let feeds = match ( - gate(&Workspace::read(&view), &files, &prefix(&root), locks), - &found, - ) { + let (ws, dir) = (Workspace::read(&view), prefix(&root)); + let feeds = match (gate(&ws, &files, &dir, locks), &found) { + // The tag the block was written beside is gone, and the block's + // own still hands the lock to the hub: what the hub is to hold + // for another package is no longer known. + (Vendored::Plain, Block::Ours(at, kept, _)) + if matches!(named(&ws, &kept.lock, &dir, locks), Some(Ok(_))) => + { + let line = module[..at.start].matches('\n').count() + 1; + return Vendored::Declined(format!( + "{FILE}:{line}: the block that socket-patch keeps there still reads `{}` for the \ + hub, and the `nuget.from_lock` it was written beside is gone, so a package \ + vendored now would not be among the block's feeds: put that tag back, or take \ + the vendored packages out (`socket-patch vendor --revert`), and run this command \ + again", + kept.lock + )); + } (Vendored::Plain, _) => return Vendored::Plain, // Its tag reads as one of the user's: said as what it is. (_, Block::Edited(line)) => { @@ -619,6 +651,15 @@ pub fn vendored(project: &Path, locks: &[String]) -> Vendored { /// [`vendored`] for the workspace `ws`, read without the block, and the /// project in its directory `dir` (empty, or with a `/` at its end), by /// what `files` holds beside it: before the checkout itself is looked at. +/// +/// Where no tag that was read reads a lock of the project, one that was +/// not read still may. A doubt of the reader declines the package in a +/// workspace that has to do with the ruleset: a call of a file that was +/// read names it ([`names`]), as the `bazel_dep` of every workspace does +/// that uses the extension. In a workspace of other rulesets such a doubt +/// is about no hub, and only a file that is there and was not read as a +/// whole declines ([`Workspace::unread`]): it may be the one that names +/// the ruleset. fn gate(ws: &Workspace, files: &dyn Fn(&str) -> Entry, dir: &str, locks: &[String]) -> Vendored { let tags = ws.tags(&EXTENSION, "from_lock"); let mine = |tag: &&Tag| { @@ -626,7 +667,15 @@ fn gate(ws: &Workspace, files: &dyn Fn(&str) -> Entry, dir: &str, locks: &[Strin matches!(read, Some(Read::Ours(_) | Read::Any(_))) }; match tags.calls.iter().find(mine) { - None => Vendored::Plain, + // A tag that was not read may read the lock. The doubt that says + // so: the first one in a workspace that has to do with the + // ruleset, else the one about a file that was not read. + None => { + let first = ws.doubts.iter().chain(&tags.doubts).next(); + let doubt = first.filter(|_| names(ws, EXTENSION.module)); + let doubt = doubt.or(ws.unread.as_ref()); + doubt.map_or(Vendored::Plain, |doubt| Vendored::Declined(unsure(doubt))) + } Some(tag) => match feeds(ws, files, &tags, tag, dir) { Ok(feeds) => Vendored::Block(feeds), Err(why) => Vendored::Declined(why), @@ -634,6 +683,18 @@ fn gate(ws: &Workspace, files: &dyn Fn(&str) -> Entry, dir: &str, locks: &[Strin } } +/// What `doubt` of the reader stands against: the tags of the workspace +/// are not all known. +fn unsure(Doubt { file, line, why }: &Doubt) -> String { + let place = match line { + 0 => file.clone(), + line => format!("{file}:{line}"), + }; + format!( + "{place}: {why}, so socket-patch cannot tell which `nuget.from_lock` tags the workspace has" + ) +} + /// What the block holds for the hub of `tag`, the tag of `tags` that reads /// a lock of the project in `dir`, or why it cannot be shown to work. fn feeds( @@ -654,11 +715,8 @@ fn feeds( block was built for a project at the root alone" )); } - if let Some(Doubt { file, line, why }) = ws.doubts.iter().chain(&tags.doubts).next() { - return Err(format!( - "{}: {why}, so socket-patch cannot tell which `nuget.from_lock` tags the workspace has", - place(file, *line) - )); + if let Some(doubt) = ws.doubts.iter().chain(&tags.doubts).next() { + return Err(unsure(doubt)); } if let Some(other) = tags.calls.iter().find(|other| *other != tag) { return Err(format!( @@ -950,12 +1008,13 @@ pub fn without_folder(module: &str, folder: &str) -> Result { #[cfg(test)] pub(crate) mod tests { + use super::super::starlark::MAX_BYTES; use super::super::workspace::Entry; use super::*; /// The tag of the fixture that hosted mode patches on a real Bazel, and /// the same tag without its `nuget_config`. - const WIRED: &str = r#"nuget.from_lock( + pub(crate) const WIRED: &str = r#"nuget.from_lock( nuget_config = "//:nuget.config", packages_lock_json = "//:packages.lock.json", )"#; @@ -1695,15 +1754,66 @@ pub(crate) mod tests { BARE.replace("//:", "//api:"), BARE.replace("//:", "@other//:"), "nuget.from_lock()".to_string(), - // Also where the block could not be shown to work. - format!("{}\nMORE = [nuget]", BARE.replace("//:", "//api:")), ] { assert_eq!(gated(&rest, &[]), Vendored::Plain, "{rest}"); + // Also where the block could not be shown to work. let unnamed = [(".bazelversion", None)]; assert_eq!(gated(&rest, &unnamed), Vendored::Plain, "{rest}"); } } + /// What was not read may hide the tag that reads the lock, and a + /// package vendored as without Bazel is not among the feeds of that + /// hub: its build would fail on the re-pinned lock. So where no tag + /// is found, a doubt of the reader declines the package in a workspace + /// that has to do with the ruleset, and a file that is there and was + /// not read as a whole declines it in any workspace: that file may be + /// the one that names the ruleset. A doubt in a workspace of other + /// rulesets whose files were all read is about no hub. + #[test] + fn a_tag_that_may_be_hidden_declines_where_none_is_found() { + let lock = ["packages.lock.json".to_string()]; + let gated = |files: &[(&str, Entry)]| { + let view = |path: &str| { + let found = files.iter().find(|(name, _)| *name == path); + found.map_or(Entry::Absent, |(_, entry)| entry.clone()) + }; + gate(&Workspace::read(&view), &view, "", &lock) + }; + let text = |text: &str| Entry::Text(text.to_string()); + let tells = "so socket-patch cannot tell which `nuget.from_lock` tags the workspace has"; + let declined = |says: &str| Vendored::Declined(format!("{says}, {tells}")); + // In a workspace of the ruleset: a use of the proxy that may call + // a tag, and an included file that is not there. + let include = "include(\"//:more.MODULE.bazel\")"; + let elsewhere = BARE.replace("//:", "//api:"); + for (rest, says) in [ + ( + format!("{elsewhere}\nMORE = [nuget]"), + "MODULE.bazel:5: `nuget` is used other than to call a tag", + ), + ( + include.to_string(), + "more.MODULE.bazel: it does not exist; MODULE.bazel:4 includes it", + ), + ] { + let read = gated(&[(FILE, text(&module(&rest)))]); + assert_eq!(read, declined(says), "{rest}"); + } + // The same include where nothing names the ruleset. + let go = format!("bazel_dep(name = \"rules_go\", version = \"0.50.1\")\n{include}\n"); + assert_eq!(gated(&[(FILE, text(&go))]), Vendored::Plain); + // A file that is there and is not read: the included one, and the + // root file itself. + let binary = Entry::Unreadable("it is not UTF-8".to_string()); + let files = [(FILE, text(&go)), ("more.MODULE.bazel", binary.clone())]; + let says = "more.MODULE.bazel: it cannot be read: it is not UTF-8; MODULE.bazel:2 \ + includes it"; + assert_eq!(gated(&files), declined(says)); + let says = "MODULE.bazel: it cannot be read: it is not UTF-8"; + assert_eq!(gated(&[(FILE, binary)]), declined(says)); + } + #[test] fn the_block_is_declined_where_it_cannot_be_shown_to_work() { let with = @@ -2049,6 +2159,66 @@ socket_patch_nuget.from_lock( } } + /// A hub can read the lock while no tag of the checkout is found: the + /// tag is gone and the block that was written beside it still reads + /// the lock, or the root file cannot be read. Vendored as without + /// Bazel, a package would not be among the feeds of that hub, and its + /// build would fail on the re-pinned lock: the package is declined. A + /// project whose lock neither the tag nor the block reads is vendored + /// as without Bazel. + #[test] + fn a_hub_that_no_tag_of_the_checkout_shows_is_declined() { + let tmp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(tmp.path()).unwrap(); + let root = base.join("repo"); + let below = root.join("svc"); + std::fs::create_dir_all(&below).unwrap(); + std::fs::create_dir(base.join(".git")).unwrap(); + let lock = ["packages.lock.json".to_string()]; + let module = checkout(&root); + std::fs::write(root.join("nuget.config"), CONFIG).unwrap(); + let Vendored::Block(read) = vendored(&root, &lock) else { + panic!("no block"); + }; + let declined = |why: &str| Vendored::Declined(why.to_string()); + + // The block of an earlier run, without the tag it was written + // beside. + let wired = with_folder(&module, &read, FOLDER_A, &[]).expect("a block"); + let orphaned = wired.replace(WIRED, ""); + assert_ne!(orphaned, wired); + std::fs::write(root.join(FILE), &orphaned).unwrap(); + let says = "MODULE.bazel:7: the block that socket-patch keeps there still reads \ + `//:packages.lock.json` for the hub, and the `nuget.from_lock` it was written \ + beside is gone, so a package vendored now would not be among the block's \ + feeds: put that tag back, or take the vendored packages out (`socket-patch \ + vendor --revert`), and run this command again"; + assert_eq!(vendored(&root, &lock), declined(says)); + // The block reads the lock of the project at the root alone, with + // its tag and without it. + assert_eq!(vendored(&below, &lock), Vendored::Plain); + std::fs::write(root.join(FILE), &wired).unwrap(); + assert_eq!(vendored(&below, &lock), Vendored::Plain); + + // The root file is larger than the reader takes: for every project + // of the workspace. + let tells = "so socket-patch cannot tell which `nuget.from_lock` tags the workspace has"; + let large = format!("{module}{}", "#\n".repeat(MAX_BYTES / 2)); + std::fs::write(root.join(FILE), large).unwrap(); + let says = format!("MODULE.bazel: it cannot be read: it is larger than 1 MiB, {tells}"); + assert_eq!(vendored(&root, &lock), declined(&says)); + assert_eq!(vendored(&below, &lock), declined(&says)); + // Or it is a link that leads out of the workspace. + #[cfg(unix)] + { + std::fs::write(base.join("module"), &module).unwrap(); + std::fs::remove_file(root.join(FILE)).unwrap(); + std::os::unix::fs::symlink(base.join("module"), root.join(FILE)).unwrap(); + let out = "MODULE.bazel: it cannot be read: it leads out of the Bazel workspace"; + assert_eq!(vendored(&root, &lock), declined(&format!("{out}, {tells}"))); + } + } + #[test] fn a_hosted_pin_beside_the_block_of_vendored_mode_is_withheld() { let wired = with_folder(&module(WIRED), &feeds(None, &[NUGET_ORG]), FOLDER_A, &[]); diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index 13360466b..bdce196d0 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -7473,6 +7473,63 @@ mod tests { assert!(!root.join(&entry.artifact.path).exists()); } + /// The tag of a hub is gone, and the block that was written beside it + /// still hands the lock to the hub, with the folder of the package + /// vendored before as its feed. Another patch is declined before + /// anything is asked for or written: in the folder of the patch alone + /// it would be in no feed of that hub. The package that is wired stays + /// as it is, with the same reason as a warning. + #[tokio::test] + #[serial_test::serial] + async fn a_block_whose_tag_is_gone_declines_another_patch() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + crate::bazel::nuget::tests::checkout(root); + let (first, _, _) = unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(first.success, "{:?}", first.error); + let wired = std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(); + let orphaned = wired.replace(crate::bazel::nuget::tests::WIRED, ""); + assert_ne!(orphaned, wired); + std::fs::write(root.join(MODULE_FILE), orphaned).unwrap(); + let before = hub_files(root); + + let mut later = record.clone(); + later.uuid = "33333333-3333-4333-8333-333333333333".to_string(); + let (code, detail) = + unwrap_refused(run_vendor(root, &blobs, &installed, &later, false).await); + assert_eq!(code, VENDOR_DECLINED); + let says = "MODULE.bazel:7: the block that socket-patch keeps there still reads \ + `//:packages.lock.json` for the hub"; + assert!(detail.starts_with(says), "{detail}"); + for part in [ + "put that tag back", + "`socket-patch vendor --revert`", + "`--allow-vendored-in-bazel`", + ] { + assert!(detail.contains(part), "{detail}"); + } + assert_eq!(hub_files(root), before); + let folder = format!(".socket/vendor/nuget/{}", later.uuid); + assert!(!root.join(folder).exists(), "nothing is written"); + assert!(service_preflight(PURL, root, &later).await.is_none()); + let refused = bazel_refusals(root, &[(PURL, later.uuid.as_str())]).await; + assert_eq!(refused, [(PURL, VENDOR_DECLINED, detail)]); + + let (again, rerecorded, warnings) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(again.success && rerecorded.is_none()); + let warned: Vec<&VendorWarning> = warnings + .iter() + .filter(|w| w.code == VENDOR_DECLINED) + .collect(); + assert!( + warned.len() == 1 && warned[0].detail.starts_with(says), + "{warnings:?}" + ); + assert_eq!(hub_files(root), before); + } + /// A config that the revert leaves wired (tooling wrote it anew, and /// it still names the folder) keeps its lock pin and its package, and /// so the block: the hub takes that package through the block alone. diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 869fb89c6..ddda1c300 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1873,6 +1873,18 @@ and exit 0. The message names the reason, with the file and line where there is read, and 8.8.2 and 9.3.2 download every package of the lock without it. That is read and not built. - `MODULE.bazel` is a symbolic link, or its block was changed by hand. +- `MODULE.bazel` holds the block, and the `nuget.from_lock` it was written beside is gone. + The block is a `nuget.from_lock` of the hub itself: it still hands the lock to + rules_csharp, with the folders of the packages vendored before as its feeds, and a package + vendored now would not be among them. Put the tag back, or take the vendored packages out + with `socket-patch vendor --revert`, and run the command again. +- No tag that reads the lock is found, and one may be hidden. `MODULE.bazel`, or a file it + includes, is there and is not read as a whole: a link that leads out of the workspace, a + file over 1 MiB, one that is not UTF-8 or cannot be parsed, an `include` that is not + followed. Or the workspace names rules_csharp, and a part of those files cannot be read + with certainty: an `include` of a file that does not exist, a use of the extension that is + no call of a tag. A hub that such a part declares reads the re-pinned lock, takes the + upstream package, and its build fails. The message names what could not be read. - A lock spells the package's version otherwise than NuGet writes it (`1.2.3.0` for `1.2.3`). The hub asks its feeds for the version as the lock spells it, and the folder of the patch holds the version as `dotnet restore` writes it. Run `dotnet restore`, which rewrites the @@ -1884,9 +1896,13 @@ for a project whose lock a tag names and which Bazel does not build. A package t vendored that way, or by an earlier release, stays as it is on later runs, without a block; `vendor --revert` and a new vendored run give it the layout above. -Nothing changes for a NuGet project in no Bazel workspace, and for one whose locks no -`nuget.from_lock` reads: the package lies in the folder of the patch, and no line of -`MODULE.bazel` is written. +Nothing changes for a NuGet project in no Bazel workspace, and for one whose locks neither a +`nuget.from_lock` nor the block reads, where no tag can be hidden: the package lies in the +folder of the patch, and no line of `MODULE.bazel` is written. That includes a workspace that +does not name rules_csharp and whose files are all read as a whole: a part of them that +cannot be read with certainty is then about no hub. For a project that Bazel does not build +and that is declined all the same, pass `--allow-vendored-in-bazel`, or set +[`SOCKET_NO_BAZEL`](#bazel-workspaces-a-project-that-bazel-does-not-build). **Limits.** @@ -2576,7 +2592,8 @@ projects too. What the sections below then do for it: ([Bazel workspaces: Composer](#bazel-workspaces-composer)). - NuGet: for a package whose lock a rules_csharp `nuget.from_lock` reads, vendored mode keeps a block in the root `MODULE.bazel`, or declines the package where it cannot show - that the block works + that the block works. It also declines a package whose lock such a tag may read, behind a + part of the workspace files that is not read ([Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub)). - Go, Cargo and Maven: the `.bazelignore` at the Bazel root gets two lines for each kind of copy under `.socket` that a run wrote: the Go module copies, the vendored crates of a crate diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 673eb6c1d..e952c2de2 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 4468 + "max": 4496 }, "lock-readers": { "paths": [ From ac0430adebc14a185c835799f494b5ff201e7d41 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 13:22:06 -0500 Subject: [PATCH 19/22] Mark the codes of the gem file source experimental in the contract `vendor_gem_bazel_file_source` and `vendor_gem_bazel_checksum_left` are codes that only a Bazel workspace can produce. They join the list of the "Bazel workspaces (experimental)" section and carry the mark in their rows, as that section says every such code does. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 6168b15e7..ecda50e0b 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -562,7 +562,7 @@ A patch mirror is a caching proxy the operator runs in front of the patch server ### Bazel workspaces (experimental) -**Experimental, and outside the semver policy.** What socket-patch does because a project is in a Bazel workspace is experimental in its first release. `--allow-vendored-in-bazel`, `--no-bazel` / `--vex-no-bazel`, `SOCKET_ALLOW_VENDORED_IN_BAZEL`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_NO_BAZEL`, the codes that only a Bazel workspace can produce (`vendor_composer_bazel_workspace`, `vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`, `bazelignore_not_updated`, `vex_bazel_not_in_build`, `redirect_pnpm_bazel_workspace_hidden`, `redirect_cargo_bazel_config_unread`, `redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`, `redirect_bazel_gem_checksums_pinned` and every `maven_bazel_*`), the lines socket-patch keeps in `.bazelignore`, the block it keeps in `MODULE.bazel` and what vendored mode keeps for the jar of a hub (the directory `.socket/vendor/maven//` and the ledger entry of flavor `bazel`) may change or be removed in any release without a semver bump. The flags, variables and codes are marked **Experimental** where this document lists them, and so are its passages about a Bazel workspace; every other sentence of this document about a Bazel workspace, such as a reference to one of those codes, is under this section's rule as well. The one rule that is not experimental: none of it applies to a project in no Bazel workspace, whose runs are those of a release without it. +**Experimental, and outside the semver policy.** What socket-patch does because a project is in a Bazel workspace is experimental in its first release. `--allow-vendored-in-bazel`, `--no-bazel` / `--vex-no-bazel`, `SOCKET_ALLOW_VENDORED_IN_BAZEL`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_NO_BAZEL`, the codes that only a Bazel workspace can produce (`vendor_composer_bazel_workspace`, `vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`, `vendor_gem_bazel_file_source`, `vendor_gem_bazel_checksum_left`, `bazelignore_not_updated`, `vex_bazel_not_in_build`, `redirect_pnpm_bazel_workspace_hidden`, `redirect_cargo_bazel_config_unread`, `redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`, `redirect_bazel_gem_checksums_pinned` and every `maven_bazel_*`), the lines socket-patch keeps in `.bazelignore`, the block it keeps in `MODULE.bazel` and what vendored mode keeps for the jar of a hub (the directory `.socket/vendor/maven//` and the ledger entry of flavor `bazel`) may change or be removed in any release without a semver bump. The flags, variables and codes are marked **Experimental** where this document lists them, and so are its passages about a Bazel workspace; every other sentence of this document about a Bazel workspace, such as a reference to one of those codes, is under this section's rule as well. The one rule that is not experimental: none of it applies to a project in no Bazel workspace, whose runs are those of a release without it. * **The lookup.** A project is in a Bazel workspace when its directory, or one above it up to the root of its git checkout (a checkout whose `.git` belongs to a trusted owner; in no such checkout the project's own directory only), holds a regular file named `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`. A link to a regular file counts, and a directory of such a name does not. The name is looked up as Bazel's own client looks it up, by whether a file answers to it: on a disk that folds case a regular file named `workspace` or `Module.bazel` counts, as it does for Bazel itself, and is read as the workspace file it answers for. `SOCKET_NO_BAZEL` is the way out for a checkout where such a file is no workspace. * **The off switch (`SOCKET_NO_BAZEL`).** The lookup cannot tell whether Bazel builds the project: a service of a monorepo that Bazel never builds, and a checkout with a leftover workspace file, are in a Bazel workspace by it. A truthy `SOCKET_NO_BAZEL` (`1`/`true`/`yes`/`on`/`y`/`t`, in any case and with blanks around it: what `SOCKET_NO_CONFIG`, `SOCKET_NO_API_TOKEN` and `SOCKET_NO_UPDATE_CHECK` take) makes the lookup answer that there is none, on disk and for the in-memory engine, whose path selection then asks for no Bazel file and which judges none that a host hands over all the same. Every command then gives what it gives in the same checkout without the workspace file: the exit code, both streams and every written file. It switches off the Composer refusal (`vendor_composer_bazel_workspace`), the PyPI and RubyGems refusals beside a hub that reads the lock (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), the adding of `.bazelignore` lines, the hosted withholds for Cargo, NuGet, gems and pnpm (`redirect_cargo_bazel_config_unread`, `redirect_bazel_*`, `redirect_pnpm_bazel_workspace_hidden`), the rule that keeps a pnpm lock that a rules_js hub reads, or may read, off the route through a named registry (the lock is then routed where it is in the checkout without the workspace file), everything of Maven that rests on a hub (the entries hosted and vendored mode write to the block, the directory vendored mode keeps for a hub's jar, the jars of a hub as packages of a hosted scan, the sweep of stale entries and every `maven_bazel_*` refusal and warning), the `affected` statements of VEX (`vex_bazel_not_in_build`), and the allowance for the `BUILD.bazel` that cargo-bazel writes into a vendored crate. For a vendored Maven patch that means the run of a checkout no hub is in: beside a Maven or Gradle build the run vendors for that build alone, writes nothing for a hub, says nothing of one and names no file of one among those to commit, so a Bazel build that is there after all keeps the upstream jar of a patch the run reports as vendored; and in a checkout only Bazel builds the patch is refused for want of a build (`vendor_jvm_shape_unsupported`, `no_build_file`, with no word of an entry the block holds), and a hosted entry of the block is no pin that `vendor` ejects. The switch is for the whole run and for every program it starts, while whether Bazel builds a project is a fact of each project: a bare scan covers every project of a checkout, and with the switch set a project that Bazel does build loses each of these guards too, in a run that exits 0. Set it for runs in the directory of the project that Bazel does not build, not for a run over a checkout that also holds projects Bazel builds; there is no setting per project. Environment only: there is no flag (`vex --no-bazel` is the VEX step's own option), no repository file can set it, and a run that honours it prints nothing about it. A child process inherits it (it is not among the variables of the child-process paragraph below): it is the user's word about the checkout, no credential and no flag of one run, so a socket-patch that a spawned program starts in that checkout gives the same run. @@ -2549,8 +2549,8 @@ command's integration tests check its output. | `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` | **Experimental** (Bazel workspaces). 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` or `SOCKET_NO_BAZEL=1`, `vendor --revert`, and a package of a project that uses vendored mode already, by a release before this refusal or by a run with the flag: any package when `packages` of `composer.lock` names a copy under `.socket/vendor/composer`, and a package of `packages-dev` when `packages-dev` names one. Such a package is refused nothing: not a newer patch, not its first patch, not a `scan` or `get` with no `--mode`. A package of `packages` is still refused while only `packages-dev` names a copy, and so is a package the lock does not hold. So the first vendored path in a section a Bazel rule may install is what is refused, and the detail says so. That keeps a setup of an earlier release working and breaks no build: either no Bazel rule installs from that lock, or one does and its build already fails on a path in a section it installs, which one more path there does not change. The section matters because a rule may run `composer install --no-dev`, which reads `packages` alone: a copy that only `packages-dev` names breaks no such build. 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` | **Experimental** (Bazel workspaces). 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 or with a lone Poetry or PDM lock that resolves no package, 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. For a gem the refusal is narrower: where a `ruby.bundle_fetch` call names the project's `Gemfile` or lock and the reading is certain, the gem is vendored as its committed archive (`vendor_gem_bazel_file_source`) and is refused only where that form is not known to build, which the detail names in the place of the path sentence: the checkout names no Bazel release as three numbers in `.bazelversion` or `.bazeliskrc` (none at all, or `latest` or a release candidate), or names 9.1.0 or one outside 7, 8 and 9; the project is not the root of the Bazel workspace; a `WORKSPACE` file that counts (see above) defines repositories; a call of the hub does not write out the files it reads, or reads one of the two files alone; its `gem_checksums` are not written out; the lock has no `CHECKSUMS` section and a call that reads the two files has no `gem_checksums` entry for the gem (the detail names that call); the lock's `BUNDLED WITH` names no Bundler, or one that is neither 2.6 or later of the 2 line nor of the 4 line (the hub runs the lock's Bundler, and was built with 2.6.9 and 4.0.15); or the lock holds the gem as platform gems. One more condition is known only once the patched gem is downloaded, so it is refused by the backend, after the download and before any write, with the same code, and a dry run of `scan` or `get`, which downloads nothing, does not show it: a `gem_checksums` entry of any call that reads the two files that holds the gem to another sha256 than the patched gem's (the detail names the call, the entry and both sums, and says that no undo puts the old value back; no file is edited). See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" and "Bazel workspaces: RubyGems vendored mode" | -| `vendor_gem_bazel_file_source` | `skipped` (advisory; human: `Warning: …`) | vendor / scan / get `--mode vendored` (gem; additive): the gem was committed for a rules_ruby hub of the project's Bazel workspace as its archive, `.socket/vendor/gem//gems/-.gem`, which `Gemfile` and `Gemfile.lock` name by the relative URL `file:.socket/vendor/gem//`. The detail says what that form costs: Bundler by itself does not install from such a source (`bundle install` on a machine without the gem and `bundle lock --update` fail; on a machine that installed the gem before the patch, `bundle install` passes and keeps that unpatched copy), so the checkout builds its gems through Bazel only, and hosted mode serves both; and Bazel does not watch the gem, so an output base that fetched the hub before keeps what it fetched. A human run that vendored only such gems words the second of its `Next steps:` as ``Build with Bazel, which installs the committed gems, then run `socket-patch vex` to verify the installed patches.`` in the place of the reinstall; one that vendored other packages too keeps its reinstall step and adds the line `Build with Bazel as well: it alone installs the gems committed for its hub.` One event per gem vendored this way by the run; none on an in-sync run, and none with `--allow-vendored-in-bazel`. The ledger entry's artifact is the archive (`artifact.path` is `.socket/vendor/gem//gems/-.gem`, with its `sha256` and `size`), and its wiring records are `gemfile_file_source` and `gemfile_lock_file_source`. See docs/ecosystems.md "Bazel workspaces: RubyGems vendored mode" | -| `vendor_gem_bazel_checksum_left` | warning of the undo (human: `Warning: …`) | `vendor --revert` / `rollback` / `remove` (gem; additive): the undo put `Gemfile` and `Gemfile.lock` back for a gem that was committed for a rules_ruby hub (`vendor_gem_bazel_file_source`), and the `gem_checksums` of a `ruby.bundle_fetch` call of the workspace still hold the gem to the sha256 of the patched gem, which the vendoring run asked the user to write there. socket-patch does not edit the call, so the Bazel build fails on that entry (`Checksum was … but wanted …`) until it holds the upstream gem's sha256 again or is removed. The detail names the call with its file and line, the entry and the sha256. The undo itself is complete and its exit code is unchanged; also reported by its dry run. See docs/ecosystems.md "Bazel workspaces: RubyGems vendored mode" | +| `vendor_gem_bazel_file_source` | `skipped` (advisory; human: `Warning: …`) | **Experimental** (Bazel workspaces). vendor / scan / get `--mode vendored` (gem; additive): the gem was committed for a rules_ruby hub of the project's Bazel workspace as its archive, `.socket/vendor/gem//gems/-.gem`, which `Gemfile` and `Gemfile.lock` name by the relative URL `file:.socket/vendor/gem//`. The detail says what that form costs: Bundler by itself does not install from such a source (`bundle install` on a machine without the gem and `bundle lock --update` fail; on a machine that installed the gem before the patch, `bundle install` passes and keeps that unpatched copy), so the checkout builds its gems through Bazel only, and hosted mode serves both; and Bazel does not watch the gem, so an output base that fetched the hub before keeps what it fetched. A human run that vendored only such gems words the second of its `Next steps:` as ``Build with Bazel, which installs the committed gems, then run `socket-patch vex` to verify the installed patches.`` in the place of the reinstall; one that vendored other packages too keeps its reinstall step and adds the line `Build with Bazel as well: it alone installs the gems committed for its hub.` One event per gem vendored this way by the run; none on an in-sync run, and none with `--allow-vendored-in-bazel`. The ledger entry's artifact is the archive (`artifact.path` is `.socket/vendor/gem//gems/-.gem`, with its `sha256` and `size`), and its wiring records are `gemfile_file_source` and `gemfile_lock_file_source`. See docs/ecosystems.md "Bazel workspaces: RubyGems vendored mode" | +| `vendor_gem_bazel_checksum_left` | warning of the undo (human: `Warning: …`) | **Experimental** (Bazel workspaces). `vendor --revert` / `rollback` / `remove` (gem; additive): the undo put `Gemfile` and `Gemfile.lock` back for a gem that was committed for a rules_ruby hub (`vendor_gem_bazel_file_source`), and the `gem_checksums` of a `ruby.bundle_fetch` call of the workspace still hold the gem to the sha256 of the patched gem, which the vendoring run asked the user to write there. socket-patch does not edit the call, so the Bazel build fails on that entry (`Checksum was … but wanted …`) until it holds the upstream gem's sha256 again or is removed. The detail names the call with its file and line, the entry and the sha256. The undo itself is complete and its exit code is unchanged; also reported by its dry run. See docs/ecosystems.md "Bazel workspaces: RubyGems vendored mode" | | `vendor_lockfile_missing` / `vendor_lockfile_version_unsupported` (bun preflight placement) | `failed` | scan / get `--mode vendored` (bun): the pre-download preflight found `bun.lock` unreadable / at a `lockfileVersion` other than 0 to 3 (a newer version: update socket-patch; no integer: re-lock with Bun ≥ 1.2 — the same text as hosted's `redirect_bun_lock_unsupported`) or outside bun's single-line `packages` grammar. Same placements as `vendor_bun_lockb_invalid`; nothing fetched, no patch record. An unreadable `.socket/vendor/state.json` met by the same preflight is `vendor_state_unreadable` (see that row), never one of these. | | `bun_lockb_invalid` | scan `warnings[]` (run-level) | scan (every mode): the native binary inventory could not parse or read `bun.lockb`; detail names the format or filesystem error. Also printed as `Warning: …` on stderr. Exit and status remain unchanged. The warning is retained on empty and non-empty scans; valid binary locks are inventoried normally without a runtime or install. | | `bun_lock_unsupported` | scan `warnings[]` (run-level) | scan (every mode): the text `bun.lock` is there but the lock reader refuses it — a `lockfileVersion` newer than 3, no integer version, or a `packages` section outside bun's single-line grammar (a comment line, a re-indent) — so the packages it lists were not read from the lockfile. Detail is the shared version gate's text or `bun.lock: line : …`, followed by `, so the packages it lists were NOT read from the lockfile: a package that is locked but not installed was not scanned`. Also printed as `Warning: …` on stderr, and a scan that then finds no package at all ends `No packages found (see the warning).` instead of advising an install. Status and exit are unchanged (0): before, a checkout without `node_modules` scanned as an empty project and the lock was not mentioned. Installed packages are still crawled, and hosted / vendored runs keep their own refusal (`redirect_bun_lock_unsupported` / `vendor_lockfile_version_unsupported`). The hosted in-memory engine reports the same code among its warnings. | From 4dde8a2f42593bc4fd0a7e743d3fbc924a5ca629 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 13:36:39 -0500 Subject: [PATCH 20/22] Say both ways a hub that is not seen fails after a flat vendored run The docs entry on a tag that may be hidden said that such a hub takes the upstream package and fails on the re-pinned lock. That is one of two ways. A hub whose tag names the project's `nuget.config` reads the folder that vendored mode names there as the URL of a feed, and fails on that, as measured for a flat vendored run under a hub on Bazel 9.3.2, 8.8.2 and 7.7.2. The entry names both. Docs only. Co-Authored-By: Claude Fable 5.2 --- docs/ecosystems.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/ecosystems.md b/docs/ecosystems.md index cabb267fb..917a2dff4 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1883,8 +1883,10 @@ and exit 0. The message names the reason, with the file and line where there is file over 1 MiB, one that is not UTF-8 or cannot be parsed, an `include` that is not followed. Or the workspace names rules_csharp, and a part of those files cannot be read with certainty: an `include` of a file that does not exist, a use of the extension that is - no call of a tag. A hub that such a part declares reads the re-pinned lock, takes the - upstream package, and its build fails. The message names what could not be read. + no call of a tag. A hub that such a part declares does not get the package, and its build + fails: on the upstream package, which no longer matches the re-pinned lock, or on the + folder that `nuget.config` names, which it reads as a URL. The message names what could + not be read. - A lock spells the package's version otherwise than NuGet writes it (`1.2.3.0` for `1.2.3`). The hub asks its feeds for the version as the lock spells it, and the folder of the patch holds the version as `dotnet restore` writes it. Run `dotnet restore`, which rewrites the From de3a3e53ed548f68ebfef4a8fbfe4e3d158608f4 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 14:14:30 -0500 Subject: [PATCH 21/22] Name the checksum an undo leaves in the hub's call with SOCKET_NO_BAZEL set With the switch set, the undo of a gem that an earlier run committed for a rules_ruby hub put every file back, but did not say that the `gem_checksums` of a call still hold the gem to the patched one (`vendor_gem_bazel_checksum_left`): the warning looked the Bazel root up through the lookup that the switch turns off. It now reads the workspace whatever the switch says, as the undo of the `.bazelignore` lines does. Two tests through the CLI. With the variable, vendored mode in the checkout where a gem is committed for the hub is the run of the same checkout without its `MODULE.bazel`, to the byte. And a gem committed without the variable is listed, checked and undone with it, by `vendor --revert`, `rollback` and `remove`, with the codes that the undo names without the variable. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 4 +- .../tests/e2e_bazel_build/ruby.rs | 121 ++++++++++++++++++ crates/socket-patch-core/src/bazel/mod.rs | 4 +- .../socket-patch-core/src/vendor/gem/bazel.rs | 4 +- docs/ecosystems.md | 9 ++ 5 files changed, 137 insertions(+), 5 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index ecda50e0b..95c37a2b7 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -565,8 +565,8 @@ A patch mirror is a caching proxy the operator runs in front of the patch server **Experimental, and outside the semver policy.** What socket-patch does because a project is in a Bazel workspace is experimental in its first release. `--allow-vendored-in-bazel`, `--no-bazel` / `--vex-no-bazel`, `SOCKET_ALLOW_VENDORED_IN_BAZEL`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_NO_BAZEL`, the codes that only a Bazel workspace can produce (`vendor_composer_bazel_workspace`, `vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`, `vendor_gem_bazel_file_source`, `vendor_gem_bazel_checksum_left`, `bazelignore_not_updated`, `vex_bazel_not_in_build`, `redirect_pnpm_bazel_workspace_hidden`, `redirect_cargo_bazel_config_unread`, `redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`, `redirect_bazel_gem_checksums_pinned` and every `maven_bazel_*`), the lines socket-patch keeps in `.bazelignore`, the block it keeps in `MODULE.bazel` and what vendored mode keeps for the jar of a hub (the directory `.socket/vendor/maven//` and the ledger entry of flavor `bazel`) may change or be removed in any release without a semver bump. The flags, variables and codes are marked **Experimental** where this document lists them, and so are its passages about a Bazel workspace; every other sentence of this document about a Bazel workspace, such as a reference to one of those codes, is under this section's rule as well. The one rule that is not experimental: none of it applies to a project in no Bazel workspace, whose runs are those of a release without it. * **The lookup.** A project is in a Bazel workspace when its directory, or one above it up to the root of its git checkout (a checkout whose `.git` belongs to a trusted owner; in no such checkout the project's own directory only), holds a regular file named `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`. A link to a regular file counts, and a directory of such a name does not. The name is looked up as Bazel's own client looks it up, by whether a file answers to it: on a disk that folds case a regular file named `workspace` or `Module.bazel` counts, as it does for Bazel itself, and is read as the workspace file it answers for. `SOCKET_NO_BAZEL` is the way out for a checkout where such a file is no workspace. -* **The off switch (`SOCKET_NO_BAZEL`).** The lookup cannot tell whether Bazel builds the project: a service of a monorepo that Bazel never builds, and a checkout with a leftover workspace file, are in a Bazel workspace by it. A truthy `SOCKET_NO_BAZEL` (`1`/`true`/`yes`/`on`/`y`/`t`, in any case and with blanks around it: what `SOCKET_NO_CONFIG`, `SOCKET_NO_API_TOKEN` and `SOCKET_NO_UPDATE_CHECK` take) makes the lookup answer that there is none, on disk and for the in-memory engine, whose path selection then asks for no Bazel file and which judges none that a host hands over all the same. Every command then gives what it gives in the same checkout without the workspace file: the exit code, both streams and every written file. It switches off the Composer refusal (`vendor_composer_bazel_workspace`), the PyPI and RubyGems refusals beside a hub that reads the lock (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), the adding of `.bazelignore` lines, the hosted withholds for Cargo, NuGet, gems and pnpm (`redirect_cargo_bazel_config_unread`, `redirect_bazel_*`, `redirect_pnpm_bazel_workspace_hidden`), the rule that keeps a pnpm lock that a rules_js hub reads, or may read, off the route through a named registry (the lock is then routed where it is in the checkout without the workspace file), everything of Maven that rests on a hub (the entries hosted and vendored mode write to the block, the directory vendored mode keeps for a hub's jar, the jars of a hub as packages of a hosted scan, the sweep of stale entries and every `maven_bazel_*` refusal and warning), the `affected` statements of VEX (`vex_bazel_not_in_build`), and the allowance for the `BUILD.bazel` that cargo-bazel writes into a vendored crate. For a vendored Maven patch that means the run of a checkout no hub is in: beside a Maven or Gradle build the run vendors for that build alone, writes nothing for a hub, says nothing of one and names no file of one among those to commit, so a Bazel build that is there after all keeps the upstream jar of a patch the run reports as vendored; and in a checkout only Bazel builds the patch is refused for want of a build (`vendor_jvm_shape_unsupported`, `no_build_file`, with no word of an entry the block holds), and a hosted entry of the block is no pin that `vendor` ejects. The switch is for the whole run and for every program it starts, while whether Bazel builds a project is a fact of each project: a bare scan covers every project of a checkout, and with the switch set a project that Bazel does build loses each of these guards too, in a run that exits 0. Set it for runs in the directory of the project that Bazel does not build, not for a run over a checkout that also holds projects Bazel builds; there is no setting per project. Environment only: there is no flag (`vex --no-bazel` is the VEX step's own option), no repository file can set it, and a run that honours it prints nothing about it. A child process inherits it (it is not among the variables of the child-process paragraph below): it is the user's word about the checkout, no credential and no flag of one run, so a socket-patch that a spawned program starts in that checkout gives the same run. -* **What stays on with the switch.** Listing and undoing what an earlier run wrote for Bazel. The block of the root `MODULE.bazel` is still read by `list`, `vex`, `scan`, `vendor --check`, `repair`, `rollback`, `remove`, `vendor --revert` and a vendored takeover, by the reader of a run without the switch: an entry of hosted mode as a hosted pin, an entry of vendored mode as the wiring of the jar committed under `.socket/vendor/maven//`, and either one withheld from attestation when no pinned hub takes it any more, which `vendor --check` names for a vendored one. `rollback` and `remove` take a hosted entry out; they and `vendor --revert` take a vendored one out with its directory and its ledger entry, in the one commit that also holds the files of a Maven or Gradle build; `repair` puts back a lost directory of a patch that only a hub takes. Each of them says what it says without the switch. No entry is written or replaced: `vendor` leaves a hosted entry of the block as it is, and a hosted run takes over no patch that vendored mode keeps for a hub alone, which stays vendored (`redirect_takeover_kept_vendored`). Beside a Maven or Gradle build the hub's directory is a copy that `vendor` writes only without the switch: with it, one that was lost is named by `vendor --check` and stays lost until the undo takes its entry out. The `.bazelignore` pair of a copy directory that is gone is still removed by the command that removed the copy (`rollback`, `remove`, `vendor --revert`, `repair`, a scan), with `bazelignore_not_updated` when the file cannot be written; no pair is added. This is of the commands on disk: the in-memory engine writes no block and undoes none, and with the switch it is handed no `MODULE.bazel` to read one from. +* **The off switch (`SOCKET_NO_BAZEL`).** The lookup cannot tell whether Bazel builds the project: a service of a monorepo that Bazel never builds, and a checkout with a leftover workspace file, are in a Bazel workspace by it. A truthy `SOCKET_NO_BAZEL` (`1`/`true`/`yes`/`on`/`y`/`t`, in any case and with blanks around it: what `SOCKET_NO_CONFIG`, `SOCKET_NO_API_TOKEN` and `SOCKET_NO_UPDATE_CHECK` take) makes the lookup answer that there is none, on disk and for the in-memory engine, whose path selection then asks for no Bazel file and which judges none that a host hands over all the same. Every command then gives what it gives in the same checkout without the workspace file: the exit code, both streams and every written file. It switches off the Composer refusal (`vendor_composer_bazel_workspace`), the PyPI and RubyGems refusals beside a hub that reads the lock (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), the gem that RubyGems vendored mode commits as its archive where such a hub takes it (`vendor_gem_bazel_file_source`), the adding of `.bazelignore` lines, the hosted withholds for Cargo, NuGet, gems and pnpm (`redirect_cargo_bazel_config_unread`, `redirect_bazel_*`, `redirect_pnpm_bazel_workspace_hidden`), the rule that keeps a pnpm lock that a rules_js hub reads, or may read, off the route through a named registry (the lock is then routed where it is in the checkout without the workspace file), everything of Maven that rests on a hub (the entries hosted and vendored mode write to the block, the directory vendored mode keeps for a hub's jar, the jars of a hub as packages of a hosted scan, the sweep of stale entries and every `maven_bazel_*` refusal and warning), the `affected` statements of VEX (`vex_bazel_not_in_build`), and the allowance for the `BUILD.bazel` that cargo-bazel writes into a vendored crate. For a vendored Maven patch that means the run of a checkout no hub is in: beside a Maven or Gradle build the run vendors for that build alone, writes nothing for a hub, says nothing of one and names no file of one among those to commit, so a Bazel build that is there after all keeps the upstream jar of a patch the run reports as vendored; and in a checkout only Bazel builds the patch is refused for want of a build (`vendor_jvm_shape_unsupported`, `no_build_file`, with no word of an entry the block holds), and a hosted entry of the block is no pin that `vendor` ejects. The switch is for the whole run and for every program it starts, while whether Bazel builds a project is a fact of each project: a bare scan covers every project of a checkout, and with the switch set a project that Bazel does build loses each of these guards too, in a run that exits 0. Set it for runs in the directory of the project that Bazel does not build, not for a run over a checkout that also holds projects Bazel builds; there is no setting per project. Environment only: there is no flag (`vex --no-bazel` is the VEX step's own option), no repository file can set it, and a run that honours it prints nothing about it. A child process inherits it (it is not among the variables of the child-process paragraph below): it is the user's word about the checkout, no credential and no flag of one run, so a socket-patch that a spawned program starts in that checkout gives the same run. +* **What stays on with the switch.** Listing and undoing what an earlier run wrote for Bazel. The block of the root `MODULE.bazel` is still read by `list`, `vex`, `scan`, `vendor --check`, `repair`, `rollback`, `remove`, `vendor --revert` and a vendored takeover, by the reader of a run without the switch: an entry of hosted mode as a hosted pin, an entry of vendored mode as the wiring of the jar committed under `.socket/vendor/maven//`, and either one withheld from attestation when no pinned hub takes it any more, which `vendor --check` names for a vendored one. `rollback` and `remove` take a hosted entry out; they and `vendor --revert` take a vendored one out with its directory and its ledger entry, in the one commit that also holds the files of a Maven or Gradle build; `repair` puts back a lost directory of a patch that only a hub takes. Each of them says what it says without the switch. No entry is written or replaced: `vendor` leaves a hosted entry of the block as it is, and a hosted run takes over no patch that vendored mode keeps for a hub alone, which stays vendored (`redirect_takeover_kept_vendored`). Beside a Maven or Gradle build the hub's directory is a copy that `vendor` writes only without the switch: with it, one that was lost is named by `vendor --check` and stays lost until the undo takes its entry out. The `.bazelignore` pair of a copy directory that is gone is still removed by the command that removed the copy (`rollback`, `remove`, `vendor --revert`, `repair`, a scan), with `bazelignore_not_updated` when the file cannot be written; no pair is added. A gem that an earlier run committed for a rules_ruby hub is still listed as vendored and held to its patch by `vendor --check`, and `vendor --revert`, `rollback` and `remove` still undo it whole: `Gemfile` and `Gemfile.lock` are put back and the committed gem goes, with `vendor_gem_bazel_checksum_left` where the `gem_checksums` of a call still hold the gem to the patched one, as without the switch; no gem is committed this way. This is of the commands on disk: the in-memory engine writes no block and undoes none, and with the switch it is handed no `MODULE.bazel` to read one from. ### socket.yml patch policy (v5.0) 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 d86f0678b..1cdfd3909 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -1802,6 +1802,127 @@ fn the_switch_makes_vendored_mode_the_one_of_a_checkout_without_bazel() { assert_eq!(declined[0]["code"], 1, "{declined:#}"); } +/// Without a Bazel: the switch is for the gem committed for a hub as well. +/// In the checkout where vendored mode commits the gem as its archive, +/// `SOCKET_NO_BAZEL=1` makes it vendor the gem as it does in the same +/// checkout without its `MODULE.bazel`, to the byte: the unpacked copy, +/// which the lock names by its path, and no archive. Without the variable +/// the run commits the gem for the hub there. +#[test] +fn the_switch_makes_a_gem_for_the_hub_the_vendoring_of_a_checkout_without_bazel() { + let (cell, served) = checkout(); + cell.write(".bazelversion", "9.3.2\n"); + let origin = served.standin.origin(); + let rubygems = format!("{origin}/{RUBYGEMS}"); + let env = [ + ("SOCKET_RUBYGEMS_URL", rubygems.as_str()), + patch_host(&origin)[0], + ]; + let (plain, for_the_hub) = cell.without_and_beside(&origin, &VENDORED, &env, &["MODULE.bazel"]); + let uuid = served.uuid.as_str(); + let copy = format!("PATH\n remote: .socket/vendor/gem/{uuid}/{NAME}-{VERSION}\n"); + let source = format!("file:.socket/vendor/gem/{uuid}/"); + let archive = committed_gem(uuid); + for (run, committed) in [(&plain, false), (&for_the_hub, true)] { + for form in [&run[0], &run[1]] { + assert_eq!(form["code"], 0, "{form:#}"); + let files = &form["files"]; + let lock = files["Gemfile.lock"].as_str().expect("Gemfile.lock"); + let gemfile = files["Gemfile"].as_str().expect("Gemfile"); + assert_eq!(lock.starts_with(©), !committed, "{form:#}"); + assert_eq!(gemfile.contains(&source), committed, "{form:#}"); + assert_eq!(files[archive.as_str()].is_string(), committed, "{form:#}"); + } + } +} + +/// Every code a run names in its envelope: of its events, its warnings and +/// the warnings of its events, in the order they stand. +fn named_codes(envelope: &serde_json::Value) -> Vec { + let mut codes = Vec::new(); + let mut left = vec![envelope]; + while let Some(value) = left.pop() { + match value { + serde_json::Value::Array(items) => left.extend(items.iter().rev()), + serde_json::Value::Object(fields) => { + for (key, value) in fields.iter().rev() { + match value.as_str() { + Some(code) if key == "code" || key == "errorCode" => { + codes.push(code.to_string()) + } + _ => left.push(value), + } + } + } + _ => {} + } + } + codes +} + +/// Without a Bazel: what an earlier run wrote for Bazel is still listed +/// and undone with `SOCKET_NO_BAZEL=1`. A run without the variable commits +/// the gem for the hub. With the variable, `list` shows a vendored gem and +/// `vendor --check` holds the committed gem to the patch, and each of +/// `vendor --revert`, `rollback` and `remove` puts every file back, to the +/// byte: the `Gemfile`, its lock, the committed gem and the ledger. It +/// names the codes it names without the variable: none in the fixture's +/// checkout, and the entry it leaves in the call where the call's +/// `gem_checksums` hold the gem to the patched one. +#[test] +fn the_switch_still_undoes_a_gem_committed_for_the_hub() { + let (cell, served) = checkout(); + cell.write(".bazelversion", "9.3.2\n"); + let standin = &served.standin; + let origin = standin.origin(); + let go = |args: &[&str], env: &[(&str, &str)]| { + let env = [&patch_host(&origin)[..], env].concat(); + run(standin, &cell, args, &env) + }; + let off = [("SOCKET_NO_BAZEL", "1")]; + let undos: [&[&str]; 3] = [ + &["vendor", "--revert", "--yes"], + &["rollback", "--yes"], + &["remove", PURL, "--yes"], + ]; + // The fixture's call, and the same call with a `gem_checksums` that + // holds the gem to the sha256 of the patched one. + let lock = " gemfile_lock = \"//:Gemfile.lock\",\n"; + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + assert!(module.contains(lock), "{module}"); + let sum = sha256_hex(&served.patched_gem); + let held = format!("{lock} gem_checksums = {{\"{NAME}-{VERSION}\": \"{sum}\"}},\n"); + let held = module.replace(lock, &held); + for (module, left) in [(&module, false), (&held, true)] { + cell.write("MODULE.bazel", module); + let before = cell.tree(); + for undo in undos { + let vendored = committed_for_the_hub(&cell, &go(&VENDORED, &[]), &served, &before); + let list = go(&["list"], &off); + let listed = list.envelope.to_string(); + let as_vendored = listed.contains("\"vendored\"") && !listed.contains("\"hosted\""); + assert!(as_vendored, "{}", list.dump); + let check = go(&["vendor", "--check"], &off); + assert_eq!(check.code, 0, "{}", check.dump); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{}", check.dump); + + // The undo without the variable, for what it names. + let plain = go(undo, &[]); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", plain.dump); + committed_for_the_hub(&cell, &go(&VENDORED, &[]), &served, &before); + let switched = go(undo, &off); + assert_eq!(switched.code, 0, "{undo:?}: {}", switched.dump); + let undone = changed(&before, &cell.tree()); + assert_eq!(undone, NOTHING, "{undo:?}: {}", switched.dump); + let names = named_codes(&switched.envelope); + let without = named_codes(&plain.envelope); + assert_eq!(names, without, "{undo:?}: {}", switched.dump); + let says = names.contains(&ENTRY_LEFT.to_string()); + assert_eq!(says, left, "{undo:?}: {}", switched.dump); + } + } +} + /// Without a Bazel: what else a call can say, each as the `MODULE.bazel` /// of the fixture's checkout. A lock without a `CHECKSUMS` section leaves /// the gem as it is too, and its warning does not offer to delete the gem diff --git a/crates/socket-patch-core/src/bazel/mod.rs b/crates/socket-patch-core/src/bazel/mod.rs index e25df7b3b..c3a0c5736 100644 --- a/crates/socket-patch-core/src/bazel/mod.rs +++ b/crates/socket-patch-core/src/bazel/mod.rs @@ -93,8 +93,8 @@ pub fn bazel_root(project: &Path) -> Option { (!off()).then(|| root_of(project)).flatten() } -/// [`bazel_root`] whatever the switch says: for the one caller that takes -/// away what an earlier run wrote for Bazel ([`ignore::sync`]). +/// [`bazel_root`] whatever the switch says: for the callers that take +/// away, or say what is left of, what an earlier run wrote for Bazel. pub(crate) fn root_of(project: &Path) -> Option { let dirs = search_dirs(project); root_in(&dirs, repo_at_end_of(dirs.clone())) diff --git a/crates/socket-patch-core/src/vendor/gem/bazel.rs b/crates/socket-patch-core/src/vendor/gem/bazel.rs index da7046015..9f9e3f7dc 100644 --- a/crates/socket-patch-core/src/vendor/gem/bazel.rs +++ b/crates/socket-patch-core/src/vendor/gem/bazel.rs @@ -799,8 +799,10 @@ pub(super) async fn revert( /// whose `gem_checksums` still hold the gem `key` (`-`) to /// `sha256`, the one of the committed gem ([`ENTRY_LEFT`]). Read apart from /// [`gate`]: the entry fails the build whatever else the checkout says. +/// And read whatever the switch says ([`crate::bazel::off`]): the undo of +/// what an earlier run wrote for Bazel says what it says without it. fn entry_left(project: &Path, key: &str, sha256: &str) -> Option { - let root = crate::bazel::bazel_root(project)?; + let root = crate::bazel::root_of(project)?; let workspace = Workspace::read(&disk(&root.dir)); let holds = |tag: &Tag<'_>| match tag.call.arg("gem_checksums") { Some(Starlark::Dict(sums)) => sums.iter().any(|(gem, sum)| { diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 90790c556..6b3cc1d9d 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2426,6 +2426,9 @@ projects too. What the sections below then do for it: - Composer: vendored mode is declined until the lock names a vendored copy ([Bazel workspaces: Composer](#bazel-workspaces-composer)). +- RubyGems: where a `ruby.bundle_fetch` call reads the project's `Gemfile` and lock and the + checkout shows that it builds, vendored mode commits the gem as its archive, for the hub + ([Bazel workspaces: RubyGems vendored mode](#bazel-workspaces-rubygems-vendored-mode)). - PyPI and RubyGems: vendored mode is declined where a hub call of the workspace reads the project's lock, or may read it ([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)). @@ -2486,6 +2489,12 @@ What an earlier run wrote for Bazel is still listed and undone with the variable Beside a Maven or Gradle build the hub's directory is a copy that only a `vendor` run without the variable writes: one that was lost stays lost, `vendor --check` names it, and the undo still takes its entry out. +- A gem committed for a rules_ruby hub + ([Bazel workspaces: RubyGems vendored mode](#bazel-workspaces-rubygems-vendored-mode)): + `list` shows it as vendored and `vendor --check` holds it to the patch. `vendor --revert`, + `rollback` and `remove` put the `Gemfile` and its lock back and remove the committed gem, + and warn as they do without the variable where the `gem_checksums` of a call still hold + the gem to the patched one. No gem is committed this way. - The `.bazelignore` lines: no pair is added, and the pair of a copy that is gone is removed by the command that removed the copy (`rollback`, `remove`, `vendor --revert`, `repair`, a scan). From 3e1269881ecf9ce60ed465695388b9f55b467a60 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 14:38:23 -0500 Subject: [PATCH 22/22] Hold the NuGet vendored gate apart from a WORKSPACE file Main now passes over a `WORKSPACE` file where the checkout names Bazel 9 or later: Bazel reads none there, so the file is no reader of a lock and no doubt (#2208). The gate of vendored mode for a rules_csharp hub never counted that file on any release. rules_csharp has no form for it, the tags are read from the module files alone, and the reader keeps what it makes of a `WORKSPACE` file apart from its doubts and from the file it names as not read (`Workspace::legacy`), which the gate does not ask. The test of a tag that may be hidden holds that now. A `WORKSPACE` file that cannot be read, and one that defines something, decline nothing where no tag is found and leave the block as it is beside a tag, in a checkout that names Bazel 9.3.2 and in one that names 7.7.2. Test only. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/bazel/nuget.rs | 27 +++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/socket-patch-core/src/bazel/nuget.rs b/crates/socket-patch-core/src/bazel/nuget.rs index c7893e625..82a1fb435 100644 --- a/crates/socket-patch-core/src/bazel/nuget.rs +++ b/crates/socket-patch-core/src/bazel/nuget.rs @@ -1769,7 +1769,8 @@ pub(crate) mod tests { /// that has to do with the ruleset, and a file that is there and was /// not read as a whole declines it in any workspace: that file may be /// the one that names the ruleset. A doubt in a workspace of other - /// rulesets whose files were all read is about no hub. + /// rulesets whose files were all read is about no hub, and a + /// `WORKSPACE` file is never one of those files. #[test] fn a_tag_that_may_be_hidden_declines_where_none_is_found() { let lock = ["packages.lock.json".to_string()]; @@ -1811,7 +1812,29 @@ pub(crate) mod tests { includes it"; assert_eq!(gated(&files), declined(says)); let says = "MODULE.bazel: it cannot be read: it is not UTF-8"; - assert_eq!(gated(&[(FILE, binary)]), declined(says)); + assert_eq!(gated(&[(FILE, binary.clone())]), declined(says)); + // A `WORKSPACE` file hides no tag: rules_csharp has no form for + // that file, and what the reader makes of it is kept apart from + // its doubts. One that cannot be read, and one that defines + // something, decline nothing where no tag is found and change + // nothing beside a tag, whether the Bazel the checkout names reads + // such a file (7.7.2) or not (9.3.2). + let bare = [(FILE, text(&module("")))]; + let wired = [ + (FILE, text(&module(WIRED))), + ("MODULE.bazel.lock", text(SELECTED)), + ("nuget.config", text(CONFIG)), + ]; + for release in ["9.3.2\n", "7.7.2\n"] { + for legacy in [binary.clone(), text("nuget_repo(name = \"nuget\")\n")] { + let beside = [("WORKSPACE", legacy), (".bazelversion", text(release))]; + let read = gated(&[&bare[..], &beside].concat()); + assert_eq!(read, Vendored::Plain, "{release}"); + let read = gated(&[&wired[..], &beside].concat()); + let block = Vendored::Block(feeds(None, &[NUGET_ORG])); + assert_eq!(read, block, "{release}"); + } + } } #[test]