diff --git a/.github/workflows/bazel-ruby.yml b/.github/workflows/bazel-ruby.yml index 1615b3a12..9ed16999c 100644 --- a/.github/workflows/bazel-ruby.yml +++ b/.github/workflows/bazel-ruby.yml @@ -12,9 +12,11 @@ name: Bazel patch compatibility (RubyGems) # downloads no JDK and needs none on the runner: rules_ruby's rules name a # Java runtime toolchain that only JRuby uses, and the fixture registers # one with nothing behind it. A gem under test never comes from the -# repository cache: the fixture names no `gem_checksums`, so rules_ruby -# gives Bazel no checksum for a gem, and Bazel looks a file up in that -# cache by its checksum only. +# repository cache of an earlier run: the fixture names no `gem_checksums`, +# so rules_ruby gives Bazel no checksum for a gem, and Bazel looks a file +# up in that cache by its checksum only. The flow that writes a +# `gem_checksums` into its workspace copy names gems it built for its own +# run, which no earlier run has. # # Not required for merge: no `merge_group` trigger, and no job here is a # `needs` of ci.yml's `ci-ok`. diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 42c5d4a95..da831486f 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2581,6 +2581,7 @@ command's integration tests check its output. | `upstream_gem_install_refreshed` | `warnings[]` (note); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem): an installed copy or cache-dir archive the unwind replaced with the sha256-verified upstream gem. A wet vendored gem unwind (#2083, #2093): an installed copy only. A human run prints a progress line instead. | | `upstream_gem_install_would_refresh` | `warnings[]` (note) | the same on `--dry-run`: what a wet unwind would replace. | | `redirect_gem_version_not_locked` | `warnings[]` (warning) | scan `--mode hosted` (gem): the crawled gem version is installed on the machine but no `GEM` section of the project's lock resolves it (another project's copy in the shared gem home). The gem is skipped and the Gemfile and lock stay byte-identical. | +| `redirect_bazel_gem_checksums_pinned` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (gem, additive): a rules_ruby `ruby.bundle_fetch` call of the root `MODULE.bazel` (or of a file it includes) reads the project's lock, or may (its `gemfile_lock` is not a label in a plain string), and its `gem_checksums` holds a build of the gem that the lock names (`-`, or `--`) to another sha256 than the patched archive has (in either case of its letters), or is not written out as a dict of strings (a constant, an expression, a `**` argument). rules_ruby gives Bazel's downloader that sha256, so the build after a redirect would fail (`Bundler found mismatched checksums`, `Checksum was ... but wanted ...`) or keep the upstream gem: nothing is written for the gem (no `source:` option, no lock change). The gem is a `skipped` / `redirect_unconfirmed` event; status and exit are unchanged (exit 0), and the other gems of the run are rewritten. One warning per gem that the run would otherwise pin (a gem refused for another reason keeps that reason's warning alone). The detail starts `@: \`\` at :`, names each such entry, and says to change it to the sha256 of the patched archive, which it gives, or, where the lock has a `CHECKSUMS` section for Bundler to hold the gem to, to delete the gem from the dict, and to re-run; where further calls hold the gem it ends by naming them (`The same holds for at : ...: change it there too`); socket-patch never edits the call, so an entry changed by hand goes back by hand after a `rollback`. A call counts whether or not it is a statement of its own; an `rb_bundle_fetch` call of the `WORKSPACE` file counts unless a tag of the module files names the lock in a plain string, and `@//` is the main repository there for the name `workspace(name = ...)` gives; what the reader cannot read of the workspace changes nothing. Not given in no Bazel workspace, for a lock no call may read, beside a call without `gem_checksums`, and for an entry that holds the patched sha256 or an empty string. A pin an earlier release wrote stays, is still reported `applied` (and attested by `--vex`), and gets the warning, which then says `the pin an earlier run wrote is left as it is` in place of `redirect skipped` and names `socket-patch rollback pkg:gem/@` (the gem's own pin, never a bare `rollback`, which would unwind every patch) as the other way out. Every call that may read the lock counts, also one whose hub the built targets do not use. The in-memory engine reads the calls where the project's directory is the Bazel root. See [Bazel workspaces: RubyGems](../../docs/ecosystems.md#bazel-workspaces-rubygems). | | `redirect_maven_trusted_checksums_maven3_only` / `maven_trusted_checksums_maven3_only` | `warnings[]` (warning) | scan / get `--mode hosted` (the first code) and rollback / remove (the second), Maven: the Trusted Checksums settings hosted mode wrote into `.mvn/maven.config` named the checksums directory through `${session.rootDirectory}`, which stops Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the project, and this run respelled that line with `${maven.multiModuleProjectDirectory}` in a project that declares no Maven (no Maven Wrapper naming an Apache Maven release, a root pom of model 4.0.0). Maven 3.9.4 and later 3.x enforce the checksums as before; a Maven 4 build of the project no longer does. Reported once, by the run that changes the line. The remedy for a project Maven 4 builds: declare Maven 4 (a wrapper that pins it, or a root pom of model 4.1.0); the next hosted scan then writes the spelling Maven 4 reads. Status and exit code are unchanged. | | `redirect_maven_version_not_selected` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the build does not resolve the artifact at the patch's base version; the detail names the version Maven selects instead, or says that the build does not resolve the artifact. The run writes nothing for the dep and it is not counted as redirected. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). | | `redirect_maven_selection_undetermined` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): what the build selects for the artifact cannot be read and `pom.xml` declares no version of it to replace, so no `` pin is written on a guess. The detail carries the reason and the remedy (resolve the project once and re-run, or declare the artifact at the base version). For a single pom the run then writes nothing for the dep. In a reactor the warning is a note on a plan that may still be written: it names the first module whose selection cannot be read and counts the rest; those modules get no new pin, while the modules that are certain are still pinned and a declaration that names the base version is still rewritten, so the dep may be counted as redirected beside this warning. | 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..6646f9707 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -26,6 +26,14 @@ //! //! The flow asserts the VEX document of its patch as `main.rs` says. //! +//! A second flow, [`hosted_bundle_fetch_gem_checksums`], runs the command +//! in the same workspace with a `gem_checksums` on the call that names the +//! two gems. There the scan leaves the gem as it is and says how to go on, +//! the build stays the upstream one, and on each of the two ways on the +//! same scan pins the gem and the build is the patched one. Two tests +//! without a Bazel hold the command to the same in the fixture's checkout, +//! with what a person reads and the calls that stand against nothing. +//! //! Both markers are read from what Bazel built, and each holds an id made //! for the run, so no cache of an earlier run can supply either gem. The //! fixture's lock therefore holds no sha256 of a gem: it has a placeholder @@ -68,10 +76,12 @@ use std::time::Instant; use serde_json::json; use sha2::{Digest, Sha256}; +use crate::envelope::{codes_in, event_for}; use crate::harness::{ - fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, StandIn, CONSUMER, + cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, + StandIn, Tree, CONSUMER, NOTHING, }; -use crate::hosted_memory_common::Patch; +use crate::hosted_memory_common::{read_tree, Patch}; /// The sha256 of `bytes` in lowercase hex, as a `Gemfile.lock` and the gem /// index spell a sum. @@ -222,6 +232,89 @@ fn grant(standin: &StandIn, uuid: &str, url: &str, index: &str, patched: &[u8]) standin.api(&[patch]); } +/// What a flow serves on its stand-in and builds: the upstream gem and the +/// patched gem, one gem with two texts in its one file, each with an id +/// that is new for every run. The grant names the patch host as production +/// does, with a token and the patch id in the paths of the artifact and of +/// the patch registry. +struct Served { + standin: StandIn, + /// The id of the patch. + uuid: String, + /// The line the consumer prints from the upstream gem, and from the + /// patched one. + unpatched: String, + patched: String, + upstream_gem: Vec, + patched_gem: Vec, + neighbour_gem: Vec, + /// The patch registry of the grant, and the routes of the gem on + /// rubygems.org and on that registry. + index: String, + upstream_route: String, + patched_route: String, +} + +impl Served { + /// Starts the stand-in, and sends the downloads of `cell`'s Bazel to it. + fn start(cell: &mut Cell) -> Served { + let run = uuid::Uuid::new_v4().to_string(); + let uuid = uuid::Uuid::new_v4().to_string(); + let token = uuid::Uuid::new_v4().to_string(); + let patched_gem = victim(&format!("PATCHED {uuid}")); + let upstream_gem = victim(&format!("PRISTINE {run}")); + 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 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); + // 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}"), + ]); + Served { + standin, + unpatched: format!("OUT: PRISTINE {run}"), + patched: format!("OUT: PATCHED {uuid}"), + uuid, + upstream_gem, + patched_gem, + neighbour_gem, + index, + upstream_route, + patched_route, + } + } +} + +/// `socket-patch ` in `cell`, against `standin`. +fn socket_patch_at(standin: &StandIn, cell: &Cell, args: &[&str]) -> Ran { + let origin = standin.origin(); + let rubygems = format!("{origin}/{RUBYGEMS}"); + cell.socket_patch(&origin, args, &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())]) +} + /// The flow of the module docs. #[test] #[ignore = "real Bazel; run with --ignored"] @@ -232,51 +325,20 @@ fn hosted_bundle_fetch() { return; }; 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, + neighbour_gem, + index, + upstream_route, + patched_route, + } = Served::start(&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}"), - ]); + let socket_patch = |cell: &Cell, args: &[&str]| socket_patch_at(&standin, cell, args); // (a) The unpatched build. The lock of the checkout pins the two // upstream gems of this run, which only the stand-in has. @@ -398,6 +460,395 @@ fn hosted_bundle_fetch() { ); } +/// The fixture's `MODULE.bazel` with a `gem_checksums` on its +/// `ruby.bundle_fetch` call, which holds version [`VERSION`] of each gem of +/// `sums` to the sha256 beside its name: the file a test writes into its +/// workspace copy. The call stays on the line it is on. +fn module_pinning(sums: &[(&str, &str)]) -> String { + let path = fixture_path(FIXTURE.dir).join("e9/MODULE.bazel"); + let module = std::fs::read_to_string(&path).expect("the fixture's MODULE.bazel"); + let lock = " gemfile_lock = \"//:Gemfile.lock\",\n"; + assert_eq!(module.matches(lock).count(), 1, "{}", path.display()); + let entry = + |(name, sha256): &(&str, &str)| format!(" \"{name}-{VERSION}\": \"{sha256}\",\n"); + let entries: String = sums.iter().map(entry).collect(); + module.replace( + lock, + &format!("{lock} gem_checksums = {{\n{entries} }},\n"), + ) +} + +/// The code of the warning for a gem that a call holds to another sha256. +const HELD: &str = "redirect_bazel_gem_checksums_pinned"; + +/// What a hosted scan that left the fixture's gem as it is says, for its +/// finished `scan`: it passes, applies nothing and rewrites no file, the +/// gem is skipped as one that nothing pins, one warning names the call of +/// `MODULE.bazel` and the entry of the gem, and no file of the checkout +/// differs from `before`. Gives the text of that warning. +fn left_alone(cell: &Cell, scan: &Ran, before: &Tree) -> String { + 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"], 0, "{test}: {said}"); + let event = event_for(&scan.envelope, PURL); + assert_eq!(event["action"], "skipped", "{test}: {said}"); + assert_eq!(event["errorCode"], "redirect_unconfirmed", "{test}: {said}"); + let rewritten = &scan.envelope["redirect"]["rewrittenFiles"]; + assert_eq!(*rewritten, json!([]), "{test}: {said}"); + let warnings = scan.envelope["warnings"].as_array().expect("warnings"); + let held = |warning: &&serde_json::Value| warning["code"] == HELD; + let held: Vec<_> = warnings.iter().filter(held).collect(); + assert_eq!(held.len(), 1, "{test}: {said}"); + let detail = held[0]["detail"].as_str().expect("a detail"); + let named = format!( + "{NAME}@{VERSION}: `ruby.bundle_fetch` at MODULE.bazel:15 holds `{NAME}-{VERSION}` to \ + another sha256" + ); + assert!(detail.starts_with(&named), "{test}: {said}"); + assert_eq!(changed(before, &cell.tree()), NOTHING, "{test}: {said}"); + assert!(!cell.path(".socket").exists(), "{test}: {said}"); + detail.to_string() +} + +/// The sha256 that the warning `detail` says to put in the entry of the +/// fixture's gem, and whether it also offers to delete the gem from the +/// dict. +fn way_on(detail: &str) -> (&str, bool) { + let change = format!("To patch it, change `{NAME}-{VERSION}` to `"); + let (_, sha256) = detail.split_once(&change).expect("the sha256 to put there"); + let sha256 = sha256.split('`').next().expect("a sha256"); + (sha256, detail.contains("or delete the gem from the dict")) +} + +/// Hosted mode beside a hub that holds the gem to a sha256 of its own: the +/// `ruby.bundle_fetch` call of the workspace copy names the two gems in +/// `gem_checksums`, each with the sha256 of its upstream archive, as the +/// examples of rules_ruby do. rules_ruby gives Bazel's downloader that +/// sha256 for the gem, whatever the lock says. +/// +/// - (a) The build prints the unpatched marker. +/// - (b) `socket-patch scan --mode hosted --yes` leaves the gem as it is +/// ([`left_alone`]): the redirect would fail the next build on the +/// sha256 of the call. +/// - (c) The same build passes, on the upstream gem, and nothing asked the +/// patch registry. +/// - (d) The first way on of the warning: with the sha256 it names in the +/// entry, the same scan rewrites `Gemfile` and `Gemfile.lock` and the +/// build prints the patched marker, from the patch registry. The VEX +/// documents of that run and of `vex` say so. +/// - (e) `rollback` restores the two files and leaves the call. With the +/// old sha256 back in the entry, as the warning says, every file is the +/// one of before and so is the build. +/// - (f) The second way on, which the warning offers for a lock with a +/// `CHECKSUMS` section: with the gem deleted from the dict, which then +/// names the other gem alone, the same scan rewrites the two files and +/// the build prints the patched marker. +/// +/// After (a), which writes Bazel's own lock, no build of the flow changes +/// a file of the checkout, also after the test changed the call: +/// rules_ruby declares its extension reproducible, and Bazel keeps such a +/// one out of that lock. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn hosted_bundle_fetch_gem_checksums() { + let test = "ruby::hosted_bundle_fetch_gem_checksums"; + let started = Instant::now(); + let Some(mut cell) = Cell::open(test, &FIXTURE) else { + return; + }; + let release = cell.release().to_string(); + let served = Served::start(&mut cell); + let standin = &served.standin; + let socket_patch = |cell: &Cell, args: &[&str]| socket_patch_at(standin, cell, args); + let (other, upstream, patched) = ( + sha256_hex(&served.neighbour_gem), + sha256_hex(&served.upstream_gem), + sha256_hex(&served.patched_gem), + ); + let files = ["Gemfile", "Gemfile.lock"]; + + // (a) The unpatched build, with the two upstream gems pinned in the + // lock and in the call. + cell.write( + "Gemfile.lock", + lock_pinning(&served.neighbour_gem, &served.upstream_gem), + ); + let held = module_pinning(&[(NEIGHBOUR, &other), (NAME, &upstream)]); + cell.write("MODULE.bazel", &held); + let before = cell.builds_unpatched(&served.unpatched); + let upstream_fetches = standin.asked(&served.upstream_route); + + // (b) The one command of hosted mode leaves the gem as it is. + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let warned = left_alone(&cell, &socket_patch(&cell, &hosted), &before); + let named = way_on(&warned); + assert_eq!(named, (patched.as_str(), true), "{test}: {warned}"); + let (named, _) = named; + + // (c) The same build, on the upstream gem. + cell.builds(&served.unpatched); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}"); + assert_eq!(standin.asked(&served.patched_route), 0, "{test}"); + + // (d) The first way on: the sha256 the warning names, in the entry. + cell.write( + "MODULE.bazel", + module_pinning(&[(NEIGHBOUR, &other), (NAME, named)]), + ); + let edited = cell.tree(); + let claim = Claim::new(PURL, &served.uuid, How::Hosted); + let in_run = cell.document("in-run"); + let scan = socket_patch(&cell, &[&hosted[..], &with_vex(&in_run)].concat()); + let pinned = cell.pinned_by(&scan, PURL, &served.uuid, &edited, &files); + let lock = String::from_utf8_lossy(&pinned["Gemfile.lock"]).into_owned(); + assert!(lock.contains(&checksum(NAME, &patched)), "{test}:\n{lock}"); + cell.wrote_in_run(&scan, &in_run, &claim); + cell.builds_patched(&pinned, &served.patched); + assert!(standin.asked(&served.patched_route) > 0, "{test}"); + assert_eq!( + standin.asked(&served.upstream_route), + upstream_fetches, + "{test}: the patched build fetched the upstream gem" + ); + cell.stands_alone(socket_patch, &claim, true); + + // (e) The undo restores the two files and leaves the call, which the + // warning says to put back by hand: then nothing differs from before. + let undo = socket_patch(&cell, &["rollback", "--yes"]); + let left = changed(&before, &cell.tree()); + assert_eq!(left, ["MODULE.bazel"], "{test}: {}", undo.dump); + cell.write("MODULE.bazel", &held); + cell.undone(&undo, "rolledBack", &before, &served.unpatched); + + // (f) The second way on: the gem deleted from the dict. + cell.write("MODULE.bazel", module_pinning(&[(NEIGHBOUR, &other)])); + let edited = cell.tree(); + let patched_fetches = standin.asked(&served.patched_route); + let scan = socket_patch(&cell, &hosted); + let pinned = cell.pinned_by(&scan, PURL, &served.uuid, &edited, &files); + assert_eq!(codes_in(&scan.envelope["warnings"]), NOTHING, "{test}"); + cell.builds_patched(&pinned, &served.patched); + assert!( + standin.asked(&served.patched_route) > patched_fetches, + "{test}: the patched build did not fetch the patched gem from the stand-in" + ); + + println!( + "{test}: Bazel {release} built {:?} before and after `scan --mode hosted` left the gem \ + that `gem_checksums` holds as it was ({HELD}); with the sha256 of the warning in the \ + entry, and again with the gem deleted from the dict, the same scan pinned it and the \ + build printed {:?} and changed no file; `rollback` restored the files but the call; \ + {:?}", + served.unpatched, + served.patched, + started.elapsed() + ); +} + +/// Without a Bazel: the fixture in a checkout of its own, with the lock +/// that pins the two upstream gems of `served` and `module` as its +/// `MODULE.bazel`; `None` leaves the checkout without one, in no Bazel +/// workspace. +fn checkout(served: &Served, module: Option<&str>) -> Cell { + let cell = cell_without_bazel("9.3.2"); + for part in ["common", "e9"] { + for (rel, bytes) in read_tree(&fixture_path(FIXTURE.dir).join(part)) { + cell.write(&rel, bytes); + } + } + cell.write(".git/HEAD", "ref: refs/heads/main\n"); + cell.write( + "Gemfile.lock", + lock_pinning(&served.neighbour_gem, &served.upstream_gem), + ); + match module { + Some(module) => cell.write("MODULE.bazel", module), + None => std::fs::remove_file(cell.path("MODULE.bazel")).expect("remove MODULE.bazel"), + } + cell +} + +/// `text` without its white space: a line a terminal may have wrapped. +fn unspaced(text: &str) -> String { + text.split_whitespace().collect() +} + +/// Without a Bazel: 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 +/// `--vex`. On either way on, the two files a scan rewrites are, byte for +/// byte, the ones it rewrites in the same checkout without a +/// `MODULE.bazel`, and `rollback` restores them and leaves the call. +#[test] +fn a_gem_that_the_hub_holds_to_its_upstream_sha256_is_left_alone() { + let served = Served::start(&mut cell_without_bazel("9.3.2")); + let run = |cell: &Cell, args: &[&str]| socket_patch_at(&served.standin, cell, args); + let (other, upstream, patched) = ( + sha256_hex(&served.neighbour_gem), + sha256_hex(&served.upstream_gem), + sha256_hex(&served.patched_gem), + ); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let files = ["Gemfile", "Gemfile.lock"]; + let plain = checkout(&served, None); + let before = plain.tree(); + let scan = run(&plain, &hosted); + let plain = plain.pinned_by(&scan, PURL, &served.uuid, &before, &files); + + let held = module_pinning(&[(NEIGHBOUR, &other), (NAME, &upstream)]); + let cell = checkout(&served, Some(&held)); + let before = cell.tree(); + let warned = left_alone(&cell, &run(&cell, &hosted), &before); + assert_eq!(way_on(&warned), (patched.as_str(), true), "{warned}"); + let preview = run(&cell, &[&hosted[..], &["--dry-run"]].concat()); + assert_eq!(left_alone(&cell, &preview, &before), warned); + // With `--vex` the run has nothing to attest, like any run that pins + // nothing: it fails on that, with the warning and no document. + let document = cell.document("left-alone"); + let scan = run(&cell, &[&hosted[..], &with_vex(&document)].concat()); + assert_eq!(scan.code, 1, "{}", scan.dump); + let error = &scan.envelope["error"]["code"]; + assert_eq!(error, "manifest_not_found", "{}", scan.dump); + let warnings = codes_in(&scan.envelope["warnings"]); + assert!(warnings.iter().any(|code| code == HELD), "{}", scan.dump); + assert!(!document.exists(), "{}", scan.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", scan.dump); + + // A person reads the same words, after the line that names the gem. + let origin = served.standin.origin(); + let [stdout, stderr] = cell.socket_patch_person(&origin, &hosted, &[]); + let said = format!("--- stdout\n{stdout}\n--- stderr\n{stderr}"); + let summary = "Switched 0 packages to hosted patches; rewrote 0 files."; + assert!(stdout.lines().any(|line| line == summary), "{said}"); + let unpinned = format!( + " {PURL}: no lockfile entry pinning it could be rewritten (see the warning below)" + ); + assert!(stderr.lines().any(|line| line == unpinned), "{said}"); + let warning = unspaced(&format!("Warning: {warned}")); + assert!(unspaced(&stderr).contains(&warning), "{said}"); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{said}"); + + // A pin that an earlier release wrote beside the entry stays: the scan + // names the entry and says that the pin stays, not that a redirect was + // skipped, and counts the gem as hosted, for the pin in the lock. + for file in files { + cell.write(file, &plain[file]); + } + let earlier = cell.tree(); + let scan = run(&cell, &hosted); + assert_eq!(scan.code, 0, "{}", scan.dump); + let event = event_for(&scan.envelope, PURL); + assert_eq!(event["action"], "applied", "{}", scan.dump); + assert_eq!( + codes_in(&scan.envelope["warnings"]), + [HELD], + "{}", + scan.dump + ); + let detail = scan.envelope["warnings"][0]["detail"].as_str().unwrap(); + let stays = format!( + "; the pin an earlier run wrote is left as it is (nothing rewritten). To build it \ + patched, change `{NAME}-{VERSION}` to `{patched}` there, or delete the gem from the dict" + ); + assert!(detail.contains(&stays), "{}", scan.dump); + let undo_one = format!("`socket-patch rollback pkg:gem/{NAME}@{VERSION}`"); + assert!(detail.contains(&undo_one), "{}", scan.dump); + assert!(!detail.contains("redirect skipped"), "{}", scan.dump); + assert_eq!(changed(&earlier, &cell.tree()), NOTHING, "{}", scan.dump); + let undo = run(&cell, &["rollback", "--yes"]); + assert_eq!(undo.envelope["summary"]["rolledBack"], 1, "{}", undo.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); + + // The two ways on. + for sums in [ + vec![(NEIGHBOUR, other.as_str()), (NAME, patched.as_str())], + vec![(NEIGHBOUR, other.as_str())], + ] { + cell.write("MODULE.bazel", module_pinning(&sums)); + let edited = cell.tree(); + let scan = run(&cell, &hosted); + let pinned = cell.pinned_by(&scan, PURL, &served.uuid, &edited, &files); + assert_eq!(codes_in(&scan.envelope["warnings"]), NOTHING, "{sums:?}"); + for file in files { + assert_eq!(pinned[file], plain[file], "{file}: {sums:?}"); + } + let undo = run(&cell, &["rollback", "--yes"]); + assert_eq!(undo.envelope["summary"]["rolledBack"], 1, "{}", undo.dump); + assert_eq!(changed(&edited, &cell.tree()), NOTHING, "{}", undo.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 +/// from the dict: nothing but the entry would hold the gem to a sha256. +/// A `gem_checksums` that is not written out may hold the gem. A call that +/// reads the lock of another project, and one without `gem_checksums`, +/// stand against nothing: the scan rewrites what it rewrites without a +/// `MODULE.bazel`. +#[test] +fn a_call_stands_against_a_gem_only_where_it_may_hold_it() { + let served = Served::start(&mut cell_without_bazel("9.3.2")); + let run = |cell: &Cell, args: &[&str]| socket_patch_at(&served.standin, cell, args); + let (upstream, patched) = ( + sha256_hex(&served.upstream_gem), + sha256_hex(&served.patched_gem), + ); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let files = ["Gemfile", "Gemfile.lock"]; + let held = module_pinning(&[(NAME, &upstream)]); + + // A lock that Bundler holds no gem to. + let cell = checkout(&served, Some(&held)); + let lock = lock_pinning(&served.neighbour_gem, &served.upstream_gem); + let (unchecked, _) = lock.split_once("CHECKSUMS\n").expect("the section"); + cell.write( + "Gemfile.lock", + format!("{unchecked}BUNDLED WITH\n 4.0.15\n"), + ); + let before = cell.tree(); + let warned = left_alone(&cell, &run(&cell, &hosted), &before); + assert_eq!(way_on(&warned), (patched.as_str(), false), "{warned}"); + + // A `gem_checksums` that names a constant of the file. + let (calls, _) = held.split_once(" gem_checksums = {").expect("the dict"); + let unread = format!("{calls} gem_checksums = HELD,\n)\n"); + let unread = unread.replace("ruby.bundle_fetch(", "HELD = {}\n\nruby.bundle_fetch("); + let cell = checkout(&served, Some(&unread)); + let before = cell.tree(); + let scan = run(&cell, &hosted); + let warned = codes_in(&scan.envelope["warnings"]); + assert_eq!(warned, [HELD], "{}", scan.dump); + let detail = scan.envelope["warnings"][0]["detail"].as_str().unwrap(); + let named = format!( + "{NAME}@{VERSION}: `ruby.bundle_fetch` at MODULE.bazel:17 has a `gem_checksums` that is \ + not written out" + ); + assert!(detail.starts_with(&named), "{}", scan.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", scan.dump); + + // Nothing stands against the gem: as without a `MODULE.bazel`. + let plain = checkout(&served, None); + let before = plain.tree(); + let scan = run(&plain, &hosted); + let plain = plain.pinned_by(&scan, PURL, &served.uuid, &before, &files); + let elsewhere = held.replace("\"//:Gemfile.lock\"", "\"//other:Gemfile.lock\""); + let unheld = fixture_path(FIXTURE.dir).join("e9/MODULE.bazel"); + let unheld = std::fs::read_to_string(unheld).expect("the fixture's MODULE.bazel"); + for module in [elsewhere, unheld] { + assert!(module.contains("ruby.bundle_fetch("), "{module}"); + let cell = checkout(&served, Some(&module)); + let before = cell.tree(); + let scan = run(&cell, &hosted); + let pinned = cell.pinned_by(&scan, PURL, &served.uuid, &before, &files); + assert_eq!(codes_in(&scan.envelope["warnings"]), NOTHING, "{module}"); + for file in files { + assert_eq!(pinned[file], plain[file], "{file}: {module}"); + } + } +} + /// 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-cli/tests/hosted_memory_parity.rs b/crates/socket-patch-cli/tests/hosted_memory_parity.rs index 37d01c8c9..ea168f952 100644 --- a/crates/socket-patch-cli/tests/hosted_memory_parity.rs +++ b/crates/socket-patch-cli/tests/hosted_memory_parity.rs @@ -299,6 +299,65 @@ async fn parity_gemfile_platform_prebuilds() { assert_parity(case("gem/bundler/platform-prebuilds")).await; } +/// The gem fixture as the root of a Bazel workspace whose rules_ruby hub +/// reads the lock and names the patched gem in `gem_checksums`. With the +/// sha256 of the upstream archive there, the checkout and the engine write +/// no file and say why in the same words. With the one of the patched +/// archive both write what they write without Bazel. The engine is given +/// the files that path selection asks for. +#[tokio::test] +async fn parity_gem_checksums_of_a_bazel_hub_through_selection() { + let dir = fixtures_root().join("redirect/gem/bundler/basic"); + let server = MockServer::start().await; + let patches = patches_from_overrides(&dir.join("overrides.json"), Some(&server.uri())); + mount_api(&server, &patches).await; + let mut files = fixture_files(&dir.join("input")); + let plain = run_disk(&server, &files, false); + assert!( + plain.changed.contains_key("Gemfile.lock"), + "{}", + plain.stderr + ); + let code = "redirect_bazel_gem_checksums_pinned"; + for (sum, left) in [("2".repeat(64), true), ("deadbeef".repeat(8), false)] { + let module = format!( + "bazel_dep(name = \"rules_ruby\", version = \"1.0.0-rc2\")\n\ + ruby = use_extension(\"@rules_ruby//ruby:extensions.bzl\", \"ruby\")\n\ + ruby.bundle_fetch(\n name = \"bundle\",\n gemfile = \"//:Gemfile\",\n \ + gemfile_lock = \"//:Gemfile.lock\",\n gem_checksums = {{\"rails-7.0.0\": \ + \"{sum}\"}},\n)\n" + ); + files.insert("MODULE.bazel".into(), module.into_bytes()); + let disk = run_disk(&server, &files, false); + let memory = run_engine(&server, selected_input(&files)).await; + let project = &memory.projects[0]; + assert!(project.error.is_none(), "{:?}", project.error); + assert_eq!( + sorted_redirect(&project.redirect), + disk.redirect, + "{}", + disk.stderr + ); + assert_eq!(engine_changed(&memory), disk.changed, "{}", disk.stderr); + let warnings = disk.redirect["warnings"].as_array().unwrap(); + let said: Vec<&str> = warnings + .iter() + .filter(|warning| warning["code"] == code) + .filter_map(|warning| warning["detail"].as_str()) + .collect(); + if left { + assert_eq!(disk.changed.len(), 0, "{}", disk.stderr); + assert_eq!(said.len(), 1, "{:#}", disk.redirect); + let named = "rails@7.0.0: `ruby.bundle_fetch` at MODULE.bazel:3 holds `rails-7.0.0`"; + assert!(said[0].starts_with(named), "{}", said[0]); + assert_eq!(disk.redirect["patches"][0]["action"], "unpinned"); + } else { + assert_eq!(disk.changed, plain.changed, "{}", disk.stderr); + assert_eq!(disk.redirect, plain.redirect, "{}", disk.stderr); + } + } +} + #[tokio::test] async fn parity_golang() { assert_parity(case("golang/gomod/basic")).await; diff --git a/crates/socket-patch-core/src/bazel/mod.rs b/crates/socket-patch-core/src/bazel/mod.rs index 11f9693cd..fe8331b95 100644 --- a/crates/socket-patch-core/src/bazel/mod.rs +++ b/crates/socket-patch-core/src/bazel/mod.rs @@ -16,6 +16,7 @@ pub mod maven; pub mod nuget; pub mod pnpm; pub mod rc; +pub mod ruby; pub mod starlark; pub mod workspace; diff --git a/crates/socket-patch-core/src/bazel/ruby.rs b/crates/socket-patch-core/src/bazel/ruby.rs new file mode 100644 index 000000000..e6b8662bb --- /dev/null +++ b/crates/socket-patch-core/src/bazel/ruby.rs @@ -0,0 +1,730 @@ +//! The sha256 a rules_ruby hub holds a gem to, beside the project's lock. +//! +//! rules_ruby's `ruby.bundle_fetch` tag downloads every gem of its +//! `gemfile_lock` through Bazel's downloader, from the remote the lock +//! names. Its `gem_checksums` is a dict from `-` (the words +//! of the gem's line of the lock, so `-` for a platform +//! build) to a sha256, and Bazel is given the sha256 of a gem the dict +//! names (`bundle_fetch.bzl` at 1.0.0-rc2). The lock's `CHECKSUMS` section +//! is not Bazel's: Bundler holds the downloaded archives to it afterwards, +//! in the `bundle install` action of the build. +//! +//! Hosted mode points a gem of the lock at the patch registry and puts the +//! sha256 of the patched archive in `CHECKSUMS`. A call that still names +//! the sha256 of the upstream archive then fails the build: Bazel takes +//! the upstream archive from its repository cache under that sha256, and +//! Bundler refuses it for the one of the lock; with an empty cache Bazel +//! refuses the patched archive itself; and with a lock that has no +//! `CHECKSUMS` section the build passes on the upstream gem. With the +//! sha256 of the patched archive in the entry the build takes the patched +//! gem, and so it does without the entry, whatever other gems the dict +//! names (all of it on Bazel 9.3.2, 8.8.2 and 7.7.2). +//! +//! So [`handed`] gives the gem rewriter the `gem_checksums` of every call +//! that may read the project's lock, and [`stands_against`] tells it which +//! gem to leave alone. socket-patch never edits the call. +//! +//! Nothing is evaluated, so some of this is read without certainty, and +//! one rule decides: what is seen of a call that may hold the gem to +//! another sha256 stands against the redirect, because a build that fails +//! outranks a patch that is missed and explained; and what is not seen +//! changes nothing, because withholding wherever a part of the workspace +//! cannot be read would take hosted mode from projects it patches today. +//! +//! - A call counts whether or not it is a statement of its own +//! ([`Call::whole`]): one in a comprehension or a conditional may run. +//! - A call whose `gemfile_lock` is no label in a plain string may read +//! any lock, this one too. One that names another file does not count. +//! - A `gem_checksums` that is no dict of strings written out in the call +//! (a constant, an expression, a `**` argument) may name every gem. +//! - The doubts of the reader ([`Workspace::doubts`], the hub's +//! [`Tags::doubts`]) say that a call may be hidden. They are not looked +//! at: a project whose lock no call that is read may read is rewritten +//! as it is without Bazel. +//! - `rb_bundle_fetch` in the file of the older `WORKSPACE` system +//! ([`Workspace::legacy`]) is the same rule under that name. Its calls +//! count unless a tag of the module files names the lock in a plain +//! string: beside such a tag, Bazel 8 and 9 build from the tag and the +//! file is a leftover. Which Bazel runs is not known here, so they count +//! on every release, also where Bazel no longer reads the file. In that +//! file `workspace(name = "shop")` makes `@shop//` the main repository, +//! and `@__main__//` is that repository where no name is given. +//! - An entry that is an empty string holds nothing: rules_ruby hands +//! Bazel no sha256 for it. +//! +//! Not looked at: a call of another Bazel module, a macro of a `.bzl` file +//! that makes the call, a name other than `rb_bundle_fetch` that a +//! `WORKSPACE` file loads the rule under, an `rb_bundle_fetch` beside a tag +//! that names the lock (Bazel 7 reads both files, and a target may use the +//! hub of either), and what the command line or an rc file tells Bazel. +//! +//! [`Tags::doubts`]: super::workspace::Tags::doubts + +use std::collections::BTreeMap; +use std::path::Path; + +use super::starlark::{Call, Value}; +use super::workspace::{disk, Entry, Extension, Repo, Workspace, LEGACY}; + +/// The code of the warning for a gem that is left alone. +pub const PINNED: &str = "redirect_bazel_gem_checksums_pinned"; + +/// The key under which the hosted engine hands [`handed`] to the gem +/// rewriter, among the project's files. +pub const KEY: &str = ""; + +const HUB: Extension<'static> = Extension { + module: "rules_ruby", + file: "//ruby:extensions.bzl", + name: "ruby", +}; + +/// A call that may read the lock: how a warning names it, and its +/// `gem_checksums`, each gem with its sha256. `None` for one that is not +/// written out. +pub type Held = (String, Option>); + +/// Whether the reader asks for the file `path` of a workspace, by its path +/// from the Bazel root: `MODULE.bazel`, a file that one can include, and +/// the names of the `WORKSPACE` file. +pub fn is_workspace_file(path: &str) -> bool { + path == "MODULE.bazel" || path.ends_with(".MODULE.bazel") || LEGACY.contains(&path) +} + +/// Whether `call` reads the lock at `lock`, a path from the Bazel root. +/// `None` when the call does not say so in a plain string. `own` is the +/// name a `WORKSPACE` file gives the main repository, for a call of that +/// file: `@//` is the main repository there, and under a name +/// that is not written out any repository may be. +fn reads(workspace: &Workspace, call: &Call, lock: &str, own: Option<&Value>) -> Option { + match call.arg("gemfile_lock") { + Some(Value::Str(label)) => { + let label = workspace.label(label)?; + if label.path() != lock { + return Some(false); + } + match (&label.repo, own) { + (Repo::Main, _) => Some(true), + (Repo::Apparent(repo), Some(Value::Str(own))) => Some(repo == own), + (Repo::Apparent(_), Some(_)) => None, + _ => Some(false), + } + } + None if !call.unpacks() => Some(false), + _ => None, + } +} + +/// The calls of `workspace` that may read the lock at `lock` and have a +/// `gem_checksums`. +fn held(workspace: &Workspace, lock: &str) -> Vec { + let tags = workspace.tags(&HUB, "bundle_fetch"); + let read = |call: &Call| reads(workspace, call, lock, None); + let tags = tags.calls.iter().map(|tag| (tag.file, tag.call)); + let tags: Vec<_> = tags.map(|(file, call)| (file, call, read(call))).collect(); + let named = tags.iter().any(|(.., reads)| *reads == Some(true)); + let may = tags.into_iter().filter(|(.., reads)| *reads != Some(false)); + let mut calls: Vec<(&str, &Call)> = may.map(|(file, call, _)| (file, call)).collect(); + if let Some(Ok((file, legacy))) = workspace.legacy.as_ref().filter(|_| !named) { + let free = |call: &&Call| call.bind.is_none(); + let naming = legacy + .calls + .iter() + .filter(free) + .find(|call| call.callee == "workspace"); + // Without a name Bazel calls the main repository `__main__`; one + // that `**` may pass is not known. + let (main, unknown) = (Value::Str("__main__".into()), Value::Other); + let own = match naming { + Some(call) if call.unpacks() => Some(call.arg("name").unwrap_or(&unknown)), + Some(call) => Some(call.arg("name").unwrap_or(&main)), + None => Some(&main), + }; + let fetches = legacy.calls.iter().filter(free); + let fetches = fetches.filter(|call| call.callee == "rb_bundle_fetch"); + calls.extend( + fetches + .filter(|call| reads(workspace, call, lock, own) != Some(false)) + .map(|call| (file.as_str(), call)), + ); + } + let held = |(file, call): (&str, &Call)| { + let sums = match call.arg("gem_checksums") { + Some(Value::Dict(sums)) => { + let sum = |sum: &Value| match sum { + Value::Str(sum) => sum.clone(), + // Bazel takes no list here: no sha256 of a gem. + _ => String::new(), + }; + Some( + sums.iter() + .map(|(gem, held)| (gem.clone(), sum(held))) + .collect(), + ) + } + None if !call.unpacks() => return None, + _ => None, + }; + Some((format!("`{}` at {file}:{}", call.callee, call.line), sums)) + }; + calls.into_iter().filter_map(held).collect() +} + +/// What the gem rewriter is handed under [`KEY`] for the lock at `lock`, a +/// path from the Bazel root, of the workspace whose files `view` has: the +/// calls that may read the lock, each with its `gem_checksums`, as JSON. +/// `None` when there is no such call. +pub fn handed(view: &dyn Fn(&str) -> Entry, lock: &str) -> Option { + let held = held(&Workspace::read(view), lock); + (!held.is_empty()).then(|| serde_json::to_string(&held).expect("strings are JSON")) +} + +/// [`handed`] for the lock `lock` in the directory of the project at +/// `project`, read from the checkout. `None` also for a project in no +/// Bazel workspace ([`super::bazel_root`], whose bounds these are). +pub fn handed_on_disk(project: &Path, lock: &str) -> Option { + let root = super::bazel_root(project)?; + // Bazel has `/` between the parts of a path on every system. + let parts = root.project.components(); + let parts = parts.map(|part| part.as_os_str().to_string_lossy()); + let lock: Vec<_> = parts.chain([lock.into()]).collect(); + let view = disk(&root.dir); + handed(&view, &lock.join("/")) +} + +/// The calls that the hosted engine handed over among `files` under +/// [`KEY`]: none for a project it handed none for. +pub fn handed_over(files: &BTreeMap) -> Vec { + let held = files + .get(KEY) + .and_then(|held| serde_json::from_str(held).ok()); + held.unwrap_or_default() +} + +/// Why hosted mode leaves version `version` of the gem `name` as it is, +/// with what a warning says of the way on: `None` when none of the calls +/// `held` ([`handed_over`]) stands against the redirect. `builds` is each +/// build of the gem that the lock `lock` names, as the words of its line +/// (``, or `-`), with the sha256 of its patched +/// archive. +/// `checked` says that the lock has a `CHECKSUMS` section, and `pinned` +/// that an earlier run pinned the gem already: that pin stays, and the +/// warning says so in place of a redirect that was skipped. +/// +/// A call stands against the redirect when it holds one of the builds to +/// another sha256, or has a `gem_checksums` that is not written out. A +/// sha256 is the same one in either case of its letters, as it is for +/// Bazel, and an empty one is none: rules_ruby gives Bazel no sha256 for +/// it. The way on is that sha256 in the entry. To delete the entry is +/// one too where the lock is `checked`: Bundler then holds the gem to that +/// section. Without the section nothing would, so it is not offered. The +/// warning words the way on for the first such call and names the others. +pub fn stands_against( + held: &[Held], + name: &str, + version: &str, + builds: &[(String, String)], + lock: &str, + (checked, pinned): (bool, bool), +) -> Option { + let entry = |build: &String| format!("{name}-{build}"); + let stale = |sums: &Option>| { + let stale = builds.iter().filter(|(build, sum)| match sums { + Some(sums) => { + let held = sums.get(&entry(build)).filter(|held| !held.is_empty()); + held.is_some_and(|held| !held.eq_ignore_ascii_case(sum)) + } + None => true, + }); + stale + .map(|(build, sum)| (entry(build), sum)) + .collect::>() + }; + let standing = held.iter().map(|(call, sums)| (call, sums, stale(sums))); + let mut standing = standing.filter(|(.., stale)| !stale.is_empty()); + if let Some((call, sums, stale)) = standing.next() { + let others: Vec<&str> = standing.map(|(call, ..)| call.as_str()).collect(); + let also = match others.is_empty() { + true => String::new(), + false => format!( + ". The same holds for {}: change it there too", + others.join(" and ") + ), + }; + let listed = |each: &dyn Fn(&(String, &String)) -> String| { + stale.iter().map(each).collect::>().join(" and ") + }; + let named = listed(&|(entry, _)| format!("`{entry}`")); + let change = listed(&|(entry, sum)| format!("`{entry}` to `{sum}`")); + let (holds, would, way) = match sums { + Some(_) => ( + format!( + "holds {named} to another sha256 in `gem_checksums` than the patched gem has" + ), + "would", + format!("change {change} there"), + ), + None => ( + format!( + "has a `gem_checksums` that is not written out as a dict of strings, which \ + may hold {named} to the sha256 of the upstream gem" + ), + "could", + format!("write the dict out in the call and change {change}"), + ), + }; + let delete = match checked { + true => format!( + ", or delete the gem from the dict (Bundler holds it to the CHECKSUMS section \ + of {lock})," + ), + false => String::new(), + }; + // The pin is named as `rollback` selects it, by the gem's base purl: + // a bare `rollback` would unwind every patch of the project. + let (left, to, undo) = match pinned { + false => ("redirect skipped", "patch it", String::new()), + true => ( + "the pin an earlier run wrote is left as it is", + "build it patched", + format!( + "; or take that pin out with `socket-patch rollback pkg:gem/{name}@{version}`" + ), + ), + }; + return Some(format!( + "{name}@{version}: {call} {holds}, so the next Bazel build {would} fail on the \ + patched gem or keep the upstream one; {left} (nothing rewritten). To {to}, \ + {way}{delete} and re-run the hosted scan{undo}. A later `rollback` does not touch \ + the call: put the old sha256 back in a changed entry then{also}" + )); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A root module that asks for the hub under the name `ruby`: a call + /// after it is on line 4. + const HEAD: &str = "module(name = \"app\")\n\ + bazel_dep(name = \"rules_ruby\", version = \"1.0.0-rc2\")\n\ + ruby = use_extension(\"@rules_ruby//ruby:extensions.bzl\", \"ruby\")\n"; + const LOCK: &str = "gemfile_lock = \"//:Gemfile.lock\""; + const SUMS: &str = "gem_checksums = {\"a-1.0\": \"11\", \"b-2.0-arm64-darwin\": \"22\"}"; + const TAG: &str = "`ruby.bundle_fetch` at MODULE.bazel:4"; + const RULE: &str = "load(\"@rules_ruby//ruby:deps.bzl\", \"rb_bundle_fetch\")\n\ + rb_bundle_fetch(name = \"bundle\", gemfile_lock = \"//:Gemfile.lock\", \ + gem_checksums = {\"a-1.0\": \"11\"})\n"; + + /// `HEAD` and one `ruby.bundle_fetch` call with `arguments`. + fn hub(arguments: &str) -> String { + format!("{HEAD}ruby.bundle_fetch(name = \"bundle\", {arguments})\n") + } + + /// What is handed over for `lock` in a workspace of `files`, each a + /// path and its text. + fn held_in(files: &[(&str, &str)], lock: &str) -> Vec { + let text = |path: &str| files.iter().find(|(name, _)| *name == path); + let view = |path: &str| match text(path) { + Some((_, text)) => Entry::Text(text.to_string()), + None => Entry::Absent, + }; + let handed = handed(&view, lock); + handed.map_or(Vec::new(), |handed| serde_json::from_str(&handed).unwrap()) + } + + fn sums(sums: &[(&str, &str)]) -> Option> { + let owned = |(gem, sum): &(&str, &str)| (gem.to_string(), sum.to_string()); + Some(sums.iter().map(owned).collect()) + } + + #[test] + fn a_call_is_handed_over_when_it_may_read_the_lock_and_has_gem_checksums() { + let handed = |arguments: &str, lock: &str| { + let module = hub(arguments); + let held = held_in(&[("MODULE.bazel", &module)], lock); + assert!(held.iter().all(|(call, _)| call == TAG), "{arguments}"); + held.into_iter().map(|(_, sums)| sums).collect::>() + }; + // The label of the call's lock, a lock, and whether it is that one: + // a project below the root, and the spellings of a label. + let both = sums(&[("a-1.0", "11"), ("b-2.0-arm64-darwin", "22")]); + for (label, lock, reads) in [ + ("//:Gemfile.lock", "Gemfile.lock", true), + ("//:Gemfile.lock", "svc/Gemfile.lock", false), + ("//svc:Gemfile.lock", "svc/Gemfile.lock", true), + (":Gemfile.lock", "Gemfile.lock", true), + ("Gemfile.lock", "Gemfile.lock", true), + ("@//:Gemfile.lock", "Gemfile.lock", true), + ("@app//:Gemfile.lock", "Gemfile.lock", true), + ("@other//:Gemfile.lock", "Gemfile.lock", false), + ] { + let held = handed(&format!("gemfile_lock = \"{label}\", {SUMS}"), lock); + let wanted = if reads { + vec![both.clone()] + } else { + Vec::new() + }; + assert_eq!(held, wanted, "{label} for {lock}"); + } + // Other arguments, and the `gem_checksums` that are handed over. + let (one, list) = (sums(&[("a-1.0", "11")]), sums(&[("a-1.0", "")])); + for (arguments, held) in [ + // No lock, and no `gem_checksums`: the call holds no gem. + (SUMS.to_string(), None), + (LOCK.to_string(), None), + // A lock that is not written out may be this one. + ( + "gemfile_lock = NAME, gem_checksums = {\"a-1.0\": \"11\"}".into(), + Some(&one), + ), + ( + "gemfile_lock = \"//:\" + N, gem_checksums = {\"a-1.0\": \"11\"}".into(), + Some(&one), + ), + // A `gem_checksums` that is not written out may name every gem. + (format!("{LOCK}, gem_checksums = HELD"), Some(&None)), + ( + format!("{LOCK}, gem_checksums = {{\"a-1.0\": HELD}}"), + Some(&None), + ), + ( + format!("{LOCK}, gem_checksums = {{\"a-1.0\": \"11\"}} | HELD"), + Some(&None), + ), + (format!("{LOCK}, **more"), Some(&None)), + ("**more".to_string(), Some(&None)), + // A list is no sha256. + ( + format!("{LOCK}, gem_checksums = {{\"a-1.0\": [\"11\"]}}"), + Some(&list), + ), + ] { + let held: Vec<_> = held.into_iter().cloned().collect(); + assert_eq!(handed(&arguments, "Gemfile.lock"), held, "{arguments}"); + } + } + + /// A call that is no statement of its own may run, and counts. The hub + /// is known by the module and the file that define it, and named as + /// the file writes it; a tag of another ruleset is none. + #[test] + fn a_call_counts_wherever_it_stands_and_under_the_name_of_its_file() { + let call = format!("ruby.bundle_fetch(name = n, {LOCK}, {SUMS})"); + for statement in [ + format!("[{call} for n in NAMES]"), + format!("FLAG and {call}"), + ] { + let module = format!("{HEAD}{statement}\n"); + let held = held_in(&[("MODULE.bazel", &module)], "Gemfile.lock"); + assert_eq!(held.len(), 1, "{statement}"); + assert_eq!(held[0].0, TAG, "{statement}"); + } + let included = format!( + "rb = use_extension(\"@rules_ruby//ruby:extensions.bzl\", \"ruby\")\n\n\ + rb.bundle_fetch({LOCK}, {SUMS})\n" + ); + let root = "bazel_dep(name = \"rules_ruby\", version = \"1.0.0-rc2\")\n\ + include(\"//pkg:gems.MODULE.bazel\")\n"; + let files = [("MODULE.bazel", root), ("pkg/gems.MODULE.bazel", &included)]; + let held = held_in(&files, "Gemfile.lock"); + assert_eq!(held.len(), 1); + assert_eq!(held[0].0, "`rb.bundle_fetch` at pkg/gems.MODULE.bazel:3"); + let other = hub(&format!("{LOCK}, {SUMS}")).replace("rules_ruby", "rules_other"); + assert_eq!(held_in(&[("MODULE.bazel", &other)], "Gemfile.lock"), []); + } + + /// The `rb_bundle_fetch` calls of a `WORKSPACE` file count unless a + /// tag of the module files names the lock: beside such a tag the file + /// is a leftover, and the gem stays one that hosted mode patches. + #[test] + fn the_workspace_file_counts_unless_a_tag_names_the_lock() { + let rule = |file: &str| { + vec![( + format!("`rb_bundle_fetch` at {file}:2"), + sums(&[("a-1.0", "11")]), + )] + }; + for file in ["WORKSPACE", "WORKSPACE.bazel", "WORKSPACE.bzlmod"] { + assert_eq!( + held_in(&[(file, RULE)], "Gemfile.lock"), + rule(file), + "{file}" + ); + assert_eq!(held_in(&[(file, RULE)], "svc/Gemfile.lock"), [], "{file}"); + } + // The module files, and whether the rule of `WORKSPACE` counts. + let elsewhere = hub("gemfile_lock = \"//svc:Gemfile.lock\""); + for (module, counts) in [ + ("module(name = \"app\")\n", true), + (HEAD, true), + (elsewhere.as_str(), true), + (hub(LOCK).as_str(), false), + // A tag that only may read the lock is no sign of a leftover. + (hub("gemfile_lock = NAME").as_str(), true), + ] { + let files = [("MODULE.bazel", module), ("WORKSPACE", RULE)]; + let handed = if counts { + rule("WORKSPACE") + } else { + Vec::new() + }; + assert_eq!(held_in(&files, "Gemfile.lock"), handed, "{module}"); + } + // A name the file binds is not the rule. + let bound = format!("rb_bundle_fetch = other\n{RULE}"); + assert_eq!(held_in(&[("WORKSPACE", &bound)], "Gemfile.lock"), []); + } + + /// In a `WORKSPACE` file the name `workspace(name = ...)` gives is the + /// main repository; one that is not written out may be any name. + #[test] + fn a_workspace_file_names_the_main_repository_itself() { + let fetch = |label: &str| { + format!("rb_bundle_fetch(gemfile_lock = \"{label}\", gem_checksums = {{\"a-1.0\": \"11\"}})\n") + }; + // What the file says before the call, the label, and whether the + // call may read the root's lock. + for (naming, label, counts) in [ + ("workspace(name = \"shop\")\n", "@shop//:Gemfile.lock", true), + ( + "workspace(name = \"shop\")\n", + "@other//:Gemfile.lock", + false, + ), + ( + "workspace(name = \"shop\")\n", + "@shop//svc:Gemfile.lock", + false, + ), + ("workspace(name = NAME)\n", "@other//:Gemfile.lock", true), + ( + "workspace(name = NAME)\n", + "@other//svc:Gemfile.lock", + false, + ), + ("", "@shop//:Gemfile.lock", false), + // Bazel's own name for a main repository that is not named. + ("", "@__main__//:Gemfile.lock", true), + ("workspace()\n", "@__main__//:Gemfile.lock", true), + ("", "@__main__//svc:Gemfile.lock", false), + ("workspace(**kw)\n", "@other//:Gemfile.lock", true), + // A name the file binds is not the call that names it. + ( + "workspace = other\nworkspace(name = \"shop\")\n", + "@shop//:Gemfile.lock", + false, + ), + ] { + let file = format!("{naming}{}", fetch(label)); + let held = held_in(&[("WORKSPACE", &file)], "Gemfile.lock"); + assert_eq!(held.len(), usize::from(counts), "{naming}{label}"); + } + // A tag is not a call of that file: the module's own name alone is + // the main repository there. + let module = hub(&format!("gemfile_lock = \"@shop//:Gemfile.lock\", {SUMS}")); + let files = [ + ("MODULE.bazel", module.as_str()), + ( + "WORKSPACE", + "workspace(name = \"shop\")\nload(\"//:x.bzl\", \"x\")\n", + ), + ]; + assert_eq!(held_in(&files, "Gemfile.lock"), []); + } + + /// What the reader cannot read may hide a call. A call that is read + /// counts beside it, and where none is read nothing is handed over. + #[test] + fn a_doubt_of_the_reader_changes_nothing() { + let doubtful = |module: String| { + let module = format!("{module}include(\"//:missing.MODULE.bazel\")\n"); + let files = [("MODULE.bazel", module.as_str())]; + let view = |path: &str| match path { + "MODULE.bazel" => Entry::Text(module.clone()), + _ => Entry::Absent, + }; + assert_eq!(Workspace::read(&view).doubts.len(), 1, "{module}"); + held_in(&files, "Gemfile.lock") + }; + assert_eq!(doubtful(hub(&format!("{LOCK}, {SUMS}"))).len(), 1); + assert_eq!(doubtful(hub(LOCK)), []); + assert_eq!(doubtful(HEAD.to_string()), []); + } + + #[test] + fn a_gem_is_left_alone_while_a_call_holds_it_to_another_sha256() { + // The rewriter gets the calls as the engine handed them over. + let files = |held: &[Held]| { + let held = serde_json::to_string(held).unwrap(); + BTreeMap::from([(KEY.to_string(), held)]) + }; + let said = |held: &[Held], builds: &[(&str, &str)], said: (bool, bool)| { + let owned = |(build, sum): &(&str, &str)| (build.to_string(), sum.to_string()); + let builds: Vec<_> = builds.iter().map(owned).collect(); + let held = handed_over(&files(held)); + stands_against(&held, "a", "1.0", &builds, "Gemfile.lock", said) + }; + let against = |held: &[Held], builds: &[(&str, &str)], checked: bool| { + said(held, builds, (checked, false)) + }; + let call = |held: &[(&str, &str)]| (TAG.to_string(), sums(held)); + let ruby = [("1.0", "99")]; + + // The entry of another gem, of another build, and one that holds + // the patched sha256 already, in either case of its letters. + for held in [ + vec![], + vec![call(&[])], + vec![call(&[ + ("b-1.0", "11"), + ("a-1.0-java", "11"), + ("a-1.1", "11"), + ])], + vec![call(&[("a-1.0", "99")])], + // An empty entry holds the gem to nothing. + vec![call(&[("a-1.0", "")])], + ] { + assert_eq!(against(&held, &ruby, true), None, "{held:?}"); + } + let lower = [("1.0", "9a")]; + assert_eq!(against(&[call(&[("a-1.0", "9A")])], &lower, true), None); + assert!(against(&[call(&[("a-1.0", "9B")])], &lower, true).is_some()); + // A project the engine handed nothing for, and what is no JSON. + assert_eq!(handed_over(&BTreeMap::new()), []); + let broken = BTreeMap::from([(KEY.to_string(), "[".to_string())]); + assert_eq!(handed_over(&broken), []); + + let stale = against(&[call(&[("a-1.0", "11")])], &ruby, true).unwrap(); + assert_eq!( + stale, + "a@1.0: `ruby.bundle_fetch` at MODULE.bazel:4 holds `a-1.0` to another sha256 in \ + `gem_checksums` than the patched gem has, so the next Bazel build would fail on \ + the patched gem or keep the upstream one; redirect skipped (nothing rewritten). To \ + patch it, change `a-1.0` to `99` there, or delete the gem from the dict (Bundler \ + holds it to the CHECKSUMS section of Gemfile.lock), and re-run the hosted scan. A \ + later `rollback` does not touch the call: put the old sha256 back in a changed \ + entry then" + ); + // A pin that an earlier run wrote is not a redirect that was + // skipped: it stays, and `rollback` takes it out. + let pinned = said(&[call(&[("a-1.0", "11")])], &ruby, (true, true)).unwrap(); + assert_eq!( + pinned, + "a@1.0: `ruby.bundle_fetch` at MODULE.bazel:4 holds `a-1.0` to another sha256 in \ + `gem_checksums` than the patched gem has, so the next Bazel build would fail on \ + the patched gem or keep the upstream one; the pin an earlier run wrote is left as \ + it is (nothing rewritten). To build it patched, change `a-1.0` to `99` there, or \ + delete the gem from the dict (Bundler holds it to the CHECKSUMS section of \ + Gemfile.lock), and re-run the hosted scan; or take that pin out with \ + `socket-patch rollback pkg:gem/a@1.0`. A later `rollback` does not touch the call: put the old \ + sha256 back in a changed entry then" + ); + // Without the section of the lock nothing but the entry holds the + // gem to a sha256: to delete it is not offered. + let unchecked = against(&[call(&[("a-1.0", "11")])], &ruby, false).unwrap(); + assert_eq!(unchecked, stale.replace(", or delete the gem from the dict (Bundler holds it to the CHECKSUMS section of Gemfile.lock),", "")); + assert!(!unchecked.contains("delete"), "{unchecked}"); + + // The first call that stands against it is worded, with every + // build it holds to another sha256 and no other, and each further + // call that stands against it is named. + let builds = [ + ("1.0", "99"), + ("1.0-java", "88"), + ("1.0-arm64-darwin", "77"), + ]; + let held = [ + call(&[("a-1.0", "99")]), + ( + "`rb_bundle_fetch` at WORKSPACE:2".to_string(), + sums(&[ + ("a-1.0", "99"), + ("a-1.0-java", "11"), + ("a-1.0-arm64-darwin", "11"), + ]), + ), + ]; + let stale = against(&held, &builds, false).unwrap(); + assert!(stale.starts_with("a@1.0: `rb_bundle_fetch` at WORKSPACE:2 holds `a-1.0-java` and `a-1.0-arm64-darwin` to another sha256"), "{stale}"); + assert!( + stale.contains( + "change `a-1.0-java` to `88` and `a-1.0-arm64-darwin` to `77` there and re-run" + ), + "{stale}" + ); + assert!(stale.ends_with("in a changed entry then"), "{stale}"); + let third = |at: &str, sums| (format!("`rb.bundle_fetch` at {at}"), sums); + let more = [ + held[1].clone(), + third("a.MODULE.bazel:3", sums(&[("a-1.0", "99")])), + third("b.MODULE.bazel:3", None), + third("c.MODULE.bazel:3", sums(&[("a-1.0", "11")])), + ]; + let stale = against(&more, &builds, false).unwrap(); + assert!( + stale.ends_with( + "in a changed entry then. The same holds for `rb.bundle_fetch` at \ + b.MODULE.bazel:3 and `rb.bundle_fetch` at c.MODULE.bazel:3: change it there too" + ), + "{stale}" + ); + + // A `gem_checksums` that is not written out may hold every build. + let unread = against(&[(TAG.to_string(), None)], &ruby, true).unwrap(); + assert_eq!( + unread, + "a@1.0: `ruby.bundle_fetch` at MODULE.bazel:4 has a `gem_checksums` that is not \ + written out as a dict of strings, which may hold `a-1.0` to the sha256 of the \ + upstream gem, so the next Bazel build could fail on the patched gem or keep the \ + upstream one; redirect skipped (nothing rewritten). To patch it, write the dict \ + out in the call and change `a-1.0` to `99`, or delete the gem from the dict \ + (Bundler holds it to the CHECKSUMS section of Gemfile.lock), and re-run the hosted \ + scan. A later `rollback` does not touch the call: put the old sha256 back in a \ + changed entry then" + ); + } + + /// On disk the lock is the one in the project's directory, by its path + /// from the Bazel root, and a project in no Bazel workspace has none. + #[test] + fn a_checkout_is_read_from_its_bazel_root() { + let tmp = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(tmp.path()).unwrap(); + std::fs::create_dir_all(root.join(".git")).unwrap(); + std::fs::create_dir_all(root.join("svc/api")).unwrap(); + assert_eq!(handed_on_disk(&root.join("svc/api"), "Gemfile.lock"), None); + let module = hub(&format!("gemfile_lock = \"//svc/api:gems.locked\", {SUMS}")); + std::fs::write(root.join("MODULE.bazel"), module).unwrap(); + let handed = |project: &str, lock: &str| handed_on_disk(&root.join(project), lock); + assert!(handed("svc/api", "gems.locked").is_some_and(|held| held.contains(TAG))); + assert_eq!(handed("svc/api", "Gemfile.lock"), None); + assert_eq!(handed("svc", "gems.locked"), None); + assert_eq!(handed("", "gems.locked"), None); + } + + #[test] + fn the_files_of_a_workspace_are_known_by_name() { + for file in [ + "MODULE.bazel", + "gems.MODULE.bazel", + "a/b/gems.MODULE.bazel", + "WORKSPACE", + "WORKSPACE.bazel", + "WORKSPACE.bzlmod", + ] { + assert!(is_workspace_file(file), "{file}"); + } + for file in [ + "a/MODULE.bazel", + "a/WORKSPACE", + "MODULE.bazel.lock", + "BUILD.bazel", + "REPO.bazel", + ] { + assert!(!is_workspace_file(file), "{file}"); + } + } +} diff --git a/crates/socket-patch-core/src/bazel/workspace.rs b/crates/socket-patch-core/src/bazel/workspace.rs index da0cecddc..292811c2e 100644 --- a/crates/socket-patch-core/src/bazel/workspace.rs +++ b/crates/socket-patch-core/src/bazel/workspace.rs @@ -56,7 +56,7 @@ const MAX_LABEL: usize = 4096; /// The names of the file of the older `WORKSPACE` system, in the order /// Bazel takes one: `WorkspaceFileFunction` and `ExternalPackageHelper` at /// 7.7.2 and 8.8.2. 9.3.2 has neither. -const LEGACY: [&str; 3] = ["WORKSPACE.bzlmod", "WORKSPACE.bazel", "WORKSPACE"]; +pub(super) const LEGACY: [&str; 3] = ["WORKSPACE.bzlmod", "WORKSPACE.bazel", "WORKSPACE"]; /// What [`disk`] says of a directory, a FIFO or a device. const NOT_A_FILE: &str = "it is not a regular file"; diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index ac5fa1f44..008b33862 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -1683,6 +1683,36 @@ pub async fn read_candidate_files_in( if candidates.iter().any(|c| c.dep.ecosystem == "gem") { keep_bundler_loaded_gem_files(view, candidates, &mut out).await; read_gemspecs(view, unreadable, &mut out).await; + // In a Bazel workspace a rules_ruby hub can hold a gem of the lock + // to a sha256 of its own (`gem_checksums`), which a redirect leaves + // on the upstream archive. What the calls that may read the lock + // hold is read here and rides a synthetic key to the gem rewriter: + // from the checkout on disk, and in memory from the files handed + // over, where the project's directory is the Bazel root. A project + // in no Bazel workspace, or whose lock no such call may read, gets + // none, and its run is the one it was. + let (_, lock) = crate::patch::redirect::gem_pair(&out.files); + if out.files.contains_key(lock) { + use crate::bazel::ruby::{handed, handed_on_disk, KEY}; + use crate::bazel::workspace::Entry; + use crate::vendor::lock_inventory::MemoryEntry; + let held = match view { + ProjectView::Memory(project) => { + let file = |path: &str| match project.get(path) { + Some(MemoryEntry::Text(text)) => Entry::Text(text.to_string()), + None => Entry::Absent, + Some(_) => Entry::Unreadable("it was not handed over as text".into()), + }; + handed(&file, lock) + } + _ => { + let root = view.disk_root().expect("a disk view has a root"); + let root = root.to_path_buf(); + crate::utils::fs::run_blocking(move || handed_on_disk(&root, lock)).await + } + }; + out.files.extend(held.map(|held| (KEY.to_string(), held))); + } } // A Gradle build: every script, catalog and lock file its script graph // reaches, for the hosted Gradle planner. @@ -8122,6 +8152,81 @@ snapshots: (read, done) } + /// In a Bazel workspace the read of a run with a gem candidate hands + /// the gem rewriter what the rules_ruby calls that may read the lock + /// hold in `gem_checksums`, from a checkout and from the same files in + /// memory alike, and a gem that a call holds to another sha256 than the + /// patched archive's is left as it is. In no Bazel workspace, beside a + /// call that reads another lock and with the patched sha256 in the + /// entry, the run is the one it is without Bazel. + #[tokio::test] + async fn gem_checksums_of_a_bazel_hub_ride_to_the_gem_rewriter() { + use crate::bazel::ruby::{KEY, PINNED}; + let module = |lock: &str, sum: &str| { + format!( + "bazel_dep(name = \"rules_ruby\", version = \"1.0.0-rc2\")\n\ + ruby = use_extension(\"@rules_ruby//ruby:extensions.bzl\", \"ruby\")\n\ + ruby.bundle_fetch(gemfile_lock = \"{lock}\", gem_checksums = \ + {{\"rails-7.0.0\": \"{sum}\"}})\n" + ) + }; + let (upstream, patched) = ("1".repeat(64), "f".repeat(64)); + // A file over the size the reader takes is read on neither side. + let large = "#".repeat(crate::bazel::starlark::MAX_BYTES); + let large = module("//:Gemfile.lock", &upstream) + &large; + // The `MODULE.bazel`, whether its call is handed over, and whether + // the gem is left as it is. + for (module, handed, left) in [ + (None, false, false), + (Some(module("//:Gemfile.lock", &upstream)), true, true), + (Some(module("//:Gemfile.lock", &patched)), true, false), + (Some(large), false, false), + ( + Some(module("//other:Gemfile.lock", &upstream)), + false, + false, + ), + ] { + let tmp = tempfile::tempdir().unwrap(); + let mut p = MemoryProject::new(); + let module = module.as_deref().map(|module| ("MODULE.bazel", module)); + for (rel, text) in [("Gemfile", GEMFILE), ("Gemfile.lock", GEM_LOCK)] + .into_iter() + .chain(module) + { + std::fs::write(tmp.path().join(rel), text).unwrap(); + p.insert_text(rel, text); + } + let (on_disk, disk) = gem_rewrite_in(&ProjectView::Disk(tmp.path())).await; + let (in_memory, memory) = gem_rewrite(&p).await; + let module = module.map(|(_, module)| &module[..module.len().min(200)]); + assert_eq!( + on_disk.files.get(KEY), + in_memory.files.get(KEY), + "{module:?}" + ); + assert_eq!(on_disk.files.contains_key(KEY), handed, "{module:?}"); + assert!(disk.rewrite == memory.rewrite, "{module:?}"); + assert_eq!(disk.confirmed, memory.confirmed, "{module:?}"); + let pinned = |w: &RewriteWarning| w.code == PINNED; + assert_eq!(disk.rewrite.warnings.iter().any(pinned), left, "{module:?}"); + assert_eq!(disk.confirmed.is_empty(), left, "{module:?}"); + assert_eq!(disk.rewrite.files.is_empty(), left, "{module:?}"); + } + // In memory a file that was not handed over as text is there, and + // unread: Bazel takes `WORKSPACE.bazel` before `WORKSPACE`, so the + // call of the second is not what it builds from. + let rule = "rb_bundle_fetch(gemfile_lock = \"//:Gemfile.lock\", gem_checksums = {})\n"; + let mut p = MemoryProject::new(); + for (rel, text) in [("Gemfile", GEMFILE), ("Gemfile.lock", GEM_LOCK)] { + p.insert_text(rel, text); + } + p.insert_text("WORKSPACE", rule); + assert!(gem_rewrite(&p).await.0.files.contains_key(KEY)); + p.insert_present("WORKSPACE.bazel"); + assert!(!gem_rewrite(&p).await.0.files.contains_key(KEY)); + } + /// A gem locked as precompiled platform builds, with a prebuild for /// each: the rewrite moves every build, and lockfile discovery (what /// `vex`, `rollback` and `remove` read) attributes them to the one pin, diff --git a/crates/socket-patch-core/src/hosted/memory/select.rs b/crates/socket-patch-core/src/hosted/memory/select.rs index 61bfb1738..dfc002a11 100644 --- a/crates/socket-patch-core/src/hosted/memory/select.rs +++ b/crates/socket-patch-core/src/hosted/memory/select.rs @@ -152,8 +152,13 @@ fn is_rush_subspace_file(rel: &str, basename: &str) -> bool { /// What `rel` (relative to a root whose files are `root_files`) is needed /// for. `user_patches` says whether npm is selected, so the files only the -/// npm user-patch walk reads ([`user_patch_need`]) are fetched at all. -fn classify(rel: &str, root_files: &BTreeSet<&str>, user_patches: bool) -> Option { +/// npm user-patch walk reads ([`user_patch_need`]) are fetched at all, and +/// `gems` whether gem is, for the files only the gem rewriter is handed. +fn classify( + rel: &str, + root_files: &BTreeSet<&str>, + (user_patches, gems): (bool, bool), +) -> Option { if rel == BUN_LOCKB { return Some(Need::Binary); } @@ -163,6 +168,16 @@ fn classify(rel: &str, root_files: &BTreeSet<&str>, user_patches: bool) -> Optio if PNP_MARKERS.contains(&rel) || rel == "rush.json" { return Some(Need::Present); } + // Beside a gem lock, the files of a Bazel workspace at this root: they + // say whether a rules_ruby hub holds a gem of the lock to a sha256 of + // its own (`bazel::ruby`). + let locks = ["Gemfile.lock", "gems.locked"]; + if gems + && locks.iter().any(|lock| root_files.contains(lock)) + && crate::bazel::ruby::is_workspace_file(rel) + { + return Some(Need::Text); + } if !rel.contains('/') { if is_python_lock_name(rel) { return Some(Need::Text); @@ -477,14 +492,17 @@ pub fn select_paths(entries: &[TreeEntryInput], options: &SelectOptions) -> Path // The user-patch walk only protects npm packages: without npm, its // nested manifests and `.patch` files would only count against the // session's file and byte limits. - let user_patches = options - .ecosystems - .as_deref() - .is_none_or(|list| list.iter().any(|e| e == "npm")); + let selected = |ecosystem: &str| { + let list = options.ecosystems.as_deref(); + list.is_none_or(|list| list.iter().any(|e| e == ecosystem)) + }; + // The same for the files of a Bazel workspace, which only the gem + // rewriter is handed. + let wanted = (selected("npm"), selected("gem")); let mut needs: BTreeMap = BTreeMap::new(); for (root, files) in &per_root { for rel in files { - let Some(need) = classify(rel, files, user_patches) else { + let Some(need) = classify(rel, files, wanted) else { continue; }; let full = join_root(root, rel); @@ -604,6 +622,7 @@ pub fn candidate_files() -> Vec { "pnpm-lock.*.yaml (presence only)", "MODULE.bazel (beside pnpm-lock.yaml)", "**/Cargo.toml (Cargo workspaces)", + "MODULE.bazel, **/*.MODULE.bazel and WORKSPACE files (beside a gem lock)", ] { out.insert(pattern.to_string()); } @@ -857,6 +876,55 @@ mod tests { assert_eq!(safe_root_path("a/").as_deref(), Some("a")); } + /// Beside a gem lock, the files of a Bazel workspace at that root are + /// fetched, with the files a `MODULE.bazel` can include: the engine + /// reads which sha256 a rules_ruby hub holds a gem to. No other root + /// fetches them. + #[test] + fn a_gem_root_fetches_the_files_of_its_bazel_workspace() { + let bazel = [ + "MODULE.bazel", + "WORKSPACE", + "WORKSPACE.bazel", + "WORKSPACE.bzlmod", + "tools/gems.MODULE.bazel", + ]; + let others = ["MODULE.bazel.lock", "BUILD.bazel", "tools/MODULE.bazel"]; + let files = bazel.iter().chain(&others).copied(); + for (lock, fetched) in [ + ("Gemfile.lock", true), + ("gems.locked", true), + ("package-lock.json", false), + ] { + let entries: Vec<_> = files.clone().chain([lock]).map(blob).collect(); + let s = select_paths(&entries, &SelectOptions::default()); + assert_eq!(s.roots, vec![""], "{lock}"); + let mut wanted: Vec<&str> = if fetched { bazel.to_vec() } else { Vec::new() }; + wanted.push(lock); + wanted.sort_unstable(); + assert_eq!(s.fetch_text, wanted, "{lock}"); + } + // Nor does a run that leaves gem out, whose rewriter is not asked. + let both = files.clone().chain(["Gemfile.lock", "package-lock.json"]); + let entries: Vec<_> = both.map(blob).collect(); + let only = |ecosystem: &str| SelectOptions { + ecosystems: Some(vec![ecosystem.into()]), + ..SelectOptions::default() + }; + let fetched = |ecosystem: &str| { + let fetched = select_paths(&entries, &only(ecosystem)).fetch_text; + fetched.iter().any(|path| path == "MODULE.bazel") + }; + assert!(fetched("gem") && !fetched("npm")); + // A gem root below the Bazel root has no file of the workspace. + let entries: Vec<_> = ["MODULE.bazel", "svc/Gemfile.lock"].map(blob).to_vec(); + let s = select_paths(&entries, &SelectOptions::default()); + assert_eq!( + (s.roots, s.fetch_text), + (vec!["svc".into()], vec!["svc/Gemfile.lock".into()]) + ); + } + #[test] fn candidate_listing_is_sorted_and_names_the_vendored_ledger_only() { let listed = candidate_files(); diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 7178a0d91..aadf4f438 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -8158,6 +8158,9 @@ struct GemPlan { mixed: bool, /// The lock has no `CHECKSUMS` section to record the artifact's sha256. unchecked: bool, + /// An earlier run's pin: the manifest gave the gem a Socket source + /// already, under whatever address the patch registry had for it then. + prior: bool, } /// How the manifest gives a gem its Socket source. @@ -8810,9 +8813,19 @@ fn plan_gem_redirect( staged, mixed, unchecked, + prior: prior_url.is_some(), }) } +/// The Bundler manifest and lock that the gem rewriter edits among `files`: +/// `gems.rb` and `gems.locked` where the project has a `gems.rb`. +pub(crate) fn gem_pair(files: &BTreeMap) -> (&'static str, &'static str) { + match files.contains_key("gems.rb") { + true => ("gems.rb", "gems.locked"), + false => ("Gemfile", "Gemfile.lock"), + } +} + fn rewrite_gem( files: &BTreeMap, overrides: &[DepOverride], @@ -8850,11 +8863,7 @@ fn rewrite_gem( }); return; } - let (gemfile_name, lock_name) = if modern { - ("gems.rb", "gems.locked") - } else { - ("Gemfile", "Gemfile.lock") - }; + let (gemfile_name, lock_name) = gem_pair(files); let mut gemfile = files.get(gemfile_name).cloned(); let mut gemfile_changed = false; let mut lock = files.get(lock_name).cloned(); @@ -8898,6 +8907,9 @@ fn rewrite_gem( // Which lock layout the project's bundler writes and accepts. let layout = files.get(lock_name).and_then(|lk| lock_layout(lk)); + // What the calls of a rules_ruby hub hold the gems of this lock to, + // read once for every gem (`bazel::ruby`). + let held = crate::bazel::ruby::handed_over(files); for dep in &gem { let Some(ov) = registry_override_of_kind(dep, "rubygems-compact-index") else { result.warnings.push(RewriteWarning { @@ -9115,6 +9127,18 @@ fn rewrite_gem( layout.as_ref(), ) { Ok(plan) => { + // In a Bazel workspace a rules_ruby hub may hold the gem to + // the sha256 of its upstream archive, which the build after + // a redirect fails on: nothing of the plan is taken, and a + // pin that an earlier run wrote stays as it is. + let said = (GEM_CHECKSUMS_HEADER_RE.is_match(lk), plan.prior); + let (name, version) = (&dep.name, &dep.version); + let against = crate::bazel::ruby::stands_against; + if let Some(detail) = against(&held, name, version, &checksums, lock_name, said) { + let code = crate::bazel::ruby::PINNED.into(); + result.warnings.push(RewriteWarning { code, detail }); + continue; + } if plan.gemfile_changed { gemfile = Some(plan.gemfile); gemfile_changed = true; @@ -21645,6 +21669,90 @@ mod tests { out } + /// In a Bazel workspace the engine hands over what the rules_ruby + /// calls that may read the lock hold in `gem_checksums` + /// (`bazel::ruby`). A gem that one of them holds to another sha256 than + /// the one of its patched archive is left as it is, with one warning + /// that names the call, the entry and the sha256 to put there. The gem + /// beside it is redirected as it is alone, and with the patched sha256 + /// in the entry the run is the one it is without Bazel. + #[test] + fn gem_a_bazel_hub_holds_to_another_sha256_is_left_alone() { + use crate::bazel::ruby::{KEY, PINNED}; + let lock = "GEM\n remote: https://rubygems.org/\n specs:\n colorize (1.1.0)\n \ + rake (13.2.1)\n\nPLATFORMS\n ruby\n\nDEPENDENCIES\n colorize\n rake\n\n\ + CHECKSUMS\n colorize (1.1.0) sha256=aaaa\n rake (13.2.1) sha256=bbbb\n\n\ + BUNDLED WITH\n 4.0.22\n"; + let gemfile = "source \"https://rubygems.org\"\n\ngem \"rake\"\ngem \"colorize\"\n"; + let both = [ + gem_override("colorize", "1.1.0"), + gem_override("rake", "13.2.1"), + ]; + let patched = "f".repeat(64); + let run = |held: Option, overrides: &[DepOverride]| { + let mut files = BTreeMap::new(); + files.insert("Gemfile".to_string(), gemfile.to_string()); + files.insert("Gemfile.lock".to_string(), lock.to_string()); + files.extend(held.map(|held| (KEY.to_string(), held))); + rewrite_registry_redirect(&files, overrides) + }; + let call = "`ruby.bundle_fetch` at MODULE.bazel:15"; + let held = |colorize: &str| { + let rake = format!("\"rake-13.2.1\":\"{patched}\""); + Some(format!( + "[[\"{call}\",{{\"colorize-1.1.0\":\"{colorize}\",{rake}}}]]" + )) + }; + let plain = run(None, &both); + assert!( + plain.files.contains_key("Gemfile.lock"), + "{:?}", + plain.warnings + ); + assert!(run(held(&patched), &both) == plain); + + let left = run(held("aaaa"), &both); + assert_eq!(warning_codes(&left), [PINNED], "{:?}", left.warnings); + let detail = &left.warnings[0].detail; + let named = format!("colorize@1.1.0: {call} holds `colorize-1.1.0` to another sha256"); + assert!(detail.starts_with(&named), "{detail}"); + let way = format!("change `colorize-1.1.0` to `{patched}` there, or delete the gem"); + assert!(detail.contains(&way), "{detail}"); + let rake = run(None, &both[1..]); + assert_eq!((&left.files, &left.edits), (&rake.files, &rake.edits)); + + // A pin that an earlier run wrote stays as it is, also under the + // address the patch registry had for the gem then, which a run + // without the call brings up to date: the warning says that it + // stays, in place of a redirect that was skipped. + assert!(detail.contains("; redirect skipped (nothing rewritten)")); + for address in ["/tok/", "/old/"] { + let mut earlier = run(None, &both[..1]).files; + for text in earlier.values_mut() { + *text = text.replace("/tok/", address); + } + let refreshed = rewrite_registry_redirect(&earlier, &both[..1]); + assert_eq!(refreshed.files.is_empty(), address == "/tok/"); + earlier.extend(held("aaaa").map(|held| (KEY.to_string(), held))); + let kept = rewrite_registry_redirect(&earlier, &both[..1]); + assert_eq!(warning_codes(&kept), [PINNED], "{:?}", kept.warnings); + assert!(kept.files.is_empty() && kept.edits.is_empty(), "{address}"); + let stays = "; the pin an earlier run wrote is left as it is (nothing rewritten)"; + assert!(kept.warnings[0].detail.contains(stays), "{address}"); + } + + // A `gem_checksums` that is not written out may hold either gem. + let unread = run(Some(format!("[[\"{call}\",null]]")), &both); + assert_eq!(warning_codes(&unread), [PINNED, PINNED]); + assert!(unread.files.is_empty() && unread.edits.is_empty()); + // A gem that is refused without Bazel keeps that refusal alone. + let unlocked = run(held("aaaa"), &[gem_override("colorize", "0.8.1")]); + assert_eq!( + warning_codes(&unlocked), + ["redirect_gem_version_not_locked"] + ); + } + fn gem_override(name: &str, version: &str) -> DepOverride { DepOverride { ecosystem: "gem".into(), diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 0d0353aca..6487d05dd 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -22,7 +22,7 @@ below is about what a package manager installs and builds. | 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). | | pixi (`pypi`) — the Python packages of a pixi project, from conda channels or PyPI | ✅ in place, in every environment under `.pixi/envs`: PyPI wheels and pure-Python conda packages (compiled conda packages are not supported yet and are skipped) — see [PyPI: pixi projects](#pypi-pixi-projects) | ❌ refused (`pypi_no_requirements` / `pypi_pyproject_only`, which name agent mode) | ❌ nothing rewritten (`redirect_pypi_pixi_project` names agent mode) | | Cargo (`cargo`) | ✅ in-place + `.cargo-checksum.json` rewrite (shared registry-cache caveat — see [Cargo: shared registry cache](#cargo-shared-registry-cache)) | ✅ `[patch.crates-io]` path entry in the root `Cargo.toml` (v5; per-version Socket keys; pre-v5 `.cargo/config*` wiring migrates on re-run) | ✅ per-patch sparse registry (`[registries.socket-patch-]` + Cargo.lock source/checksum); needs cargo 1.68+ (sparse registries) — a project whose `rust-version` or `rust-toolchain[.toml]` declares an older cargo is refused (`redirect_cargo_old_cargo`), use `--mode vendored`; direct dependencies only — a crate another dependency also pulls in is refused, use `--mode vendored`; a crate the user overrides with `[patch]` (path, git or another registry) is refused too, the override is left alone; a `cargo vendor` or `cargo local-registry` project (crates.io replaced by an on-disk source in the project's, a parent directory's or `$CARGO_HOME`'s `.cargo/config*`) is refused, use agent mode; with no `Cargo.lock` the graph is unknown, so only a project whose sole dependency is the patched crate is redirected; in a Bazel workspace a crate is not pinned while a rules_rust hub reads the project's Cargo files without its cargo config (`redirect_cargo_bazel_config_unread`), see [Bazel workspaces: Cargo](#bazel-workspaces-cargo) | -| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from prebuilt patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard") | +| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from prebuilt patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard"). In a Bazel workspace whose rules_ruby call holds the gem to another sha256 in `gem_checksums`, or has a `gem_checksums` that is not written out in the call, nothing is written for it (`redirect_bazel_gem_checksums_pinned`); see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems) | | 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`) | @@ -1992,7 +1992,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 with `pnpm-workspace.yaml` in the `data` of a hub that runs pnpm 11 or later | Supported | Not supported | Supported | | PyPI: rules_python `pip.parse` over a requirements file | Supported | Not supported | Not supported | Supported | | 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, or with one written out in the call that does not name the gem or holds it to the patched gem's sha256 | Not supported | Not supported | Supported | | Cargo: rules_rust `crate.from_cargo` over `Cargo.lock` | Supported with `cargo_config` on the hub | Supported | Not supported | Supported with a hosted or vendored patch | | NuGet: rules_csharp `nuget.from_lock` over `packages.lock.json` | Supported with `nuget_config` on the tag | Not supported | Not supported | Supported with no restored copy on the machine | | Composer: a rule of your own that runs `composer install` from `composer.lock` | Supported | Not supported | Not supported | Supported with a hosted patch | @@ -2050,10 +2050,14 @@ What the table was tested with: `go.mod`. Vendored mode keeps its copy out of Bazel's packages with [`.bazelignore`](#bazel-workspaces-bazelignore). Hosted mode for Go has the limit of the matrix at the top: free-tier patches. -- **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. +- **RubyGems**: rules_ruby 1.0.0-rc2, `ruby.bundle_fetch` with `gemfile` and `gemfile_lock`, + with no `gem_checksums` or with one written out in the call that does not name the gem or + holds it to the sha256 of the patched gem, 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. + A gem that `gem_checksums` names is left as it is until its entry holds the sha256 of the + patched gem, and so is every gem beside a `gem_checksums` that is not written out in the + call: see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems). - **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`). @@ -2111,14 +2115,19 @@ Known problems. In each of these a command exits 0 today and the next Bazel buil tag `nuget_config = "//:nuget.config"` and commit that file, which is the shape the table lists; or run `socket-patch rollback`, which restores the lock and leaves the `nuget.config` it created behind. -- **A hosted gem that `gem_checksums` pins**: the call still holds the gem to the upstream - sha256 (`Bundler found mismatched checksums`, or `Checksum was ... but wanted ...` on a - machine with an empty repository cache). Where the lock has no `CHECKSUMS` section the - build can also pass on the upstream gem from Bazel's repository cache. Run - `socket-patch rollback`. To keep the patch, set the gem's entry by hand to the sha256 of - 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. +- **`rollback` of a hosted gem whose `gem_checksums` entry you changed** to the sha256 of + the patched gem, as the scan's warning says to: the undo restores `Gemfile` and + `Gemfile.lock` and leaves the call, which then holds the upstream gem to the wrong sha256 + (`Bundler found mismatched checksums`, or `Checksum was ... but wanted ...` on a machine + with an empty repository cache). Put the old sha256 back in the entry. See + [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems). +- **A hosted gem that a call socket-patch does not read holds in `gem_checksums`** (a part + of `MODULE.bazel` it cannot read, and the cases under *Not seen* and *Not covered* of + [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems)): the scan pins the gem as it + does without Bazel, and the build fails in the same two ways, or, with a lock that has no + `CHECKSUMS` section, keeps the upstream gem. Change the entry by hand to the sha256 of + the patched gem (the scan wrote it for the gem in the lock's `CHECKSUMS` section, where + the lock has one), or run `socket-patch rollback`. - **Vendored npm on a hub with `update_pnpm_lock = True`** (measured with pnpm 9 and 10): the pnpm that Bazel runs does not see `.socket/vendor`. Use hosted mode there. - **Hosted npm on such a hub with a pnpm of 11 or later, when hosted mode is told not to @@ -3769,6 +3778,103 @@ installed tree leaves the gem with its patched sources and no finished extension Patch runs again: `apply` puts the previous build back and completes the rebuild, and `rollback` restores the original sources and build. +## Bazel workspaces: RubyGems + +rules_ruby's `ruby.bundle_fetch` tag (in `MODULE.bazel`) downloads every gem of its +`gemfile_lock` with Bazel's downloader. Its `gem_checksums` names a sha256 per gem, under +`-` (the words of the gem's line in the lock, so `-` for a +platform build), and Bazel holds a gem the dict names to it. The lock's `CHECKSUMS` section is +Bundler's: it holds the downloaded files to it afterwards, in the `bundle install` step of the +build. A build of such a hub prints the dict to add, so many workspaces have one that names +every gem. + +Hosted mode points a gem at the patch registry in `Gemfile` and `Gemfile.lock` and records the +sha256 of the patched gem in `CHECKSUMS`. It does not edit `MODULE.bazel`. An entry that still +holds the sha256 of the upstream gem then fails the next build: Bazel takes the upstream gem +from its repository cache and Bundler refuses it (`Bundler found mismatched checksums`), or, +with an empty cache, Bazel refuses the patched gem (`Checksum was ... but wanted ...`). Where +the lock has no `CHECKSUMS` section the build can also pass, on the upstream gem. + +So `scan --mode hosted` and `get --mode hosted` read the calls, and write nothing for a gem +that a call which may read the project's lock holds to another sha256 than the patched gem +has: no `source:` option, no change to the lock. The gem is `skipped` (`redirect_unconfirmed`), +the run exits 0 as for any other gem hosted mode does not pin, the other gems of the run are +rewritten, and one warning per gem (`redirect_bazel_gem_checksums_pinned`) names the call by +its file and line, the entry, and the way on; where more than one call holds the gem, it +names the others too: + +- **Change the entry** to the sha256 the warning gives, which is the one of the patched gem, + and run the command again. It then rewrites the two files, and the next build takes the + patched gem, which Bazel holds to that sha256. +- **Or delete the gem from the dict**, where the lock has a `CHECKSUMS` section: Bundler then + holds the gem to the sha256 of that section, as in a workspace without `gem_checksums`. The + warning does not offer this for a lock without the section, where nothing would hold the + gem to a sha256. + +A test does both on Bazel 9.3.2, 8.8.2 and 7.7.2 with rules_ruby 1.0.0-rc2. The build after +either changes no file of the checkout: a `MODULE.bazel.lock` that is there stays as it is. + +socket-patch never edits the call, in `rollback` and `remove` either. After one of them an +entry you changed still holds the sha256 of the patched gem, and the build fails on it until +the old value is back (the known problem above). A gem you deleted from the dict needs nothing. +With `--vex`, a run that leaves its only gem as it is has nothing to attest and exits 1 +(`manifest_not_found`), like any run that pins nothing. + +What is read, and what is not: + +- **Read from the checkout:** the root `MODULE.bazel` and the files it includes, under + whatever name the file gives the `ruby` extension of `rules_ruby`. Nothing is evaluated and + no Bazel is run. +- **Nothing changes** for a project in no Bazel workspace (the rule is under + [Bazel workspaces: `.bazelignore`](#bazel-workspaces-bazelignore)), for one whose lock no + call may read, beside a call without `gem_checksums`, and for a gem that the dict does not + name or holds to the sha256 of the patched gem already, in upper or lower case, or to an + empty string, for which rules_ruby gives Bazel no sha256. The Bundler pair is the one + hosted mode rewrites: `gems.locked` where the project has a `gems.rb`. +- **A call that is not written out stands against the gem all the same**, because a build + that fails outranks a patch that is missed and explained. That is a call in a comprehension + or a condition, which may run; one whose `gemfile_lock` is not a label in a plain string, + which may be this lock; and a `gem_checksums` that is a constant, an expression or a `**` + argument, which may name the gem. For the last the warning says to write the dict out in + the call. Two shapes built the patched gem before and are left alone now: a constant + that does not name the gem, and a second call on the same lock that holds the gem while + the targets you build use the hub of the call without the entry. Every call that may read + the lock counts, whichever hub your targets use. +- **A part of `MODULE.bazel` that socket-patch cannot read** (an `include` it cannot follow, + a `bazel_dep` whose name is an expression) can hide a call and changes nothing else. The + calls that are read decide, and where none of them may read the lock hosted mode writes as + it does without Bazel. Withholding there instead would take hosted mode from every gem of + such a workspace, also where no rules_ruby hub reads the lock. +- **`rb_bundle_fetch` in a `WORKSPACE` file** (`WORKSPACE.bzlmod`, `WORKSPACE.bazel`) counts + like the tag unless a `ruby.bundle_fetch` of the module files names the lock in a plain + string. Bazel 7 reads that file, Bazel 8 when it is told to and Bazel 9 never, and + socket-patch does not know which Bazel runs, so the call counts on each. In that file the + name that `workspace(name = "shop")` gives is the main repository, so + `@shop//:Gemfile.lock` is the root's lock, and under a name that is not written out any + repository may be. Beside a tag that names the lock the file is taken for a leftover of a + migration and not looked at. No test builds such a hub; the failing build was measured by + hand on Bazel 7.7.2 with rules_ruby 0.21.1. +- **Not seen:** a call of another Bazel module; a macro of a `.bzl` file that makes the call; + `rb_bundle_fetch` loaded under another name; an `rb_bundle_fetch` of the `WORKSPACE` file + beside a tag that names the lock, where Bazel 7 reads both and your targets use the hub of + that file; a label that spells the lock's name in another case; and what the command line + or an rc file tells Bazel. Hosted mode writes in each as it does without Bazel. +- **Not covered:** a project below the root of a workspace that is in no git checkout, or + that is a git checkout of its own (a submodule), because a workspace is looked for only up + to the root of the project's checkout; and a project whose directory the call names + through a symbolic link, because the lock is compared by the path the directory really + has. And the in-memory engine (a Socket-opened pull request) reads the calls only where + the project's directory is the Bazel root, and only from workspace files that are files of + the repository themselves: for a project below the root it is not given the files of the + workspace, and a `MODULE.bazel` or `WORKSPACE` that is a symbolic link is not read. +- A pin that an earlier release wrote beside such an entry stays in the two files, and the + build keeps failing on it, or keeps the upstream gem. The scan now names the entry in a + warning that says the pin is left as it is, and still counts the gem as hosted, because + the pin is in the lock; `--vex` attests it for the same reason, which is not true of that + build. Change the entry and run the scan again, or take the pin out with + `socket-patch rollback pkg:gem/@`, as the warning says (a bare `rollback` + would unwind every patch of the project). + ## Bazel workspaces: VEX `vex` and `--vex` read what socket-patch wrote and what the project's own package manager diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 25c6e29f0..39be6684f 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": 3518 }, "lock-readers": { "paths": [