diff --git a/.github/workflows/bazel-maven.yml b/.github/workflows/bazel-maven.yml new file mode 100644 index 000000000..519dbb6bd --- /dev/null +++ b/.github/workflows/bazel-maven.yml @@ -0,0 +1,147 @@ +name: Bazel patch compatibility (Maven) + +# The Maven flows of the real-Bazel tests (`maven::` in `e2e_bazel_build`): +# what a hosted patch of an artifact does in a workspace whose +# rules_jvm_external hub builds that artifact from a pinned lock, on each +# Bazel release below. bazel-compatibility.yml holds the legs and what every +# ecosystem shares; this file says when the Maven legs run and on which +# releases. +# +# Each release has an era of its own, because the ruleset decides the +# format of the lock and the name of an artifact's repository: +# rules_jvm_external 7.2 on Bazel 9, 6.9 on Bazel 8 and 6.5 on Bazel 7. +# +# Beyond what every leg needs, a Maven leg downloads one JDK (the one its +# era's rules_java runs javac on, about 215 MB; each era's .bazelrc names +# it for every Java role, so no build takes a Java from the machine or +# downloads a second one), java_tools (about 50 MB), the archive of +# rules_kotlin, a Bazel module the ruleset depends on (about 45 MB), +# Coursier (about 40 MB) and a Python toolchain that a Bazel module of the +# graph asks for (about 20 MB). Its repository cache holds them and comes +# to about 400 MB (macOS arm64, Bazel 9.3.2). +# +# No leg asks a public Maven repository, for a pin or for a build. The two +# artifacts under test are made by the test, under a group only the owner +# of socket.dev can publish to Maven Central, with an id of the run in the +# jar. The fixture's hub has a name of its own, because a hub named `maven` +# also takes the artifacts that other Bazel modules add to a hub of that +# name, which a pin resolves from Maven Central. Its one repository is the +# test's loopback server: Coursier resolves the two artifacts there, the +# lock a test pins holds them alone, with the sha256 of this run's jar, +# the build takes the jar from that server, and no cache holds a jar of +# the run. Era e7 (rules_jvm_external 6.5) starts Coursier with the Java +# of JAVA_HOME, else the `java` on PATH, which the runner images have; the +# later eras use the Java embedded in Bazel. +# +# Not required for merge: no `merge_group` trigger, and no job here is a +# `needs` of ci.yml's `ci-ok`. + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + # What a pull request run covers: the Maven flows and their fixture, the + # harness and the workflows that run it, the Bazel installer and its + # pins, and the Maven files of socket-patch-core that `get --mode + # hosted` and `rollback` run through in the fixture, each by its own + # path: the pom model and the trusted checksums (formats/maven), the + # rewriter's index of a pom, the model of what Maven selects with the + # pom walk under it (the hosted lane pins only where Maven selects the + # patch's version), the crawler that says where the Maven local + # repository is, lock discovery and the upstream restore of `rollback`, + # and what socket-patch reads only in a Bazel workspace (`bazel/`: the + # hubs of MODULE.bazel and their locks). Nothing another ecosystem's + # flow owns is here, so a change to one ecosystem starts that + # ecosystem's legs only. + # + # What it does not cover: shared engine code (`rewrite_maven_pom` is in + # patch/redirect/mod.rs, the file of every ecosystem's rewriter; hosted/, + # commands/), the shared test helpers and the toolchain files. A change + # there gets its run on the push to main (when the file is in the list + # below) or in the nightly run, not on the pull request: that is the + # price of not running every ecosystem's legs on every shared change. + # On demand, workflow_dispatch runs the legs on any branch. + paths: + - '.github/workflows/bazel-maven.yml' + - '.github/workflows/bazel-compatibility.yml' + - 'scripts/install-bazel.sh' + - 'scripts/bazel-pins.txt' + - 'crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs' + - 'crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs' + - 'crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/**' + - 'crates/socket-patch-core/src/formats/maven/**' + - 'crates/socket-patch-core/src/patch/redirect/maven_index.rs' + - 'crates/socket-patch-core/src/crawlers/maven_selection.rs' + - 'crates/socket-patch-core/src/crawlers/maven_scope.rs' + - 'crates/socket-patch-core/src/crawlers/maven_crawler.rs' + - 'crates/socket-patch-core/src/vex/discover/maven.rs' + - 'crates/socket-patch-core/src/patch/redirect/upstream/maven.rs' + - 'crates/socket-patch-core/src/bazel/**' + push: + branches: [main] + # The pull request paths, and what only a push to main covers: the + # root of the test target (it changes when an ecosystem's module is + # added; ci.yml builds the target and runs its hermetic tests on every + # pull request), the shared engine code and test helpers the flows run + # through, and the toolchain files. A main push outside this list waits + # for the nightly run below. + paths: + - '.github/workflows/bazel-maven.yml' + - '.github/workflows/bazel-compatibility.yml' + - 'scripts/install-bazel.sh' + - 'scripts/bazel-pins.txt' + - 'crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs' + - 'crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs' + - 'crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/**' + - 'crates/socket-patch-core/src/formats/maven/**' + - 'crates/socket-patch-core/src/patch/redirect/maven_index.rs' + - 'crates/socket-patch-core/src/crawlers/maven_selection.rs' + - 'crates/socket-patch-core/src/crawlers/maven_scope.rs' + - 'crates/socket-patch-core/src/crawlers/maven_crawler.rs' + - 'crates/socket-patch-core/src/vex/discover/maven.rs' + - 'crates/socket-patch-core/src/patch/redirect/upstream/maven.rs' + - 'crates/socket-patch-core/src/bazel/**' + - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' + - 'crates/socket-patch-core/src/patch/redirect/**' + - 'crates/socket-patch-core/src/hosted/**' + - 'crates/socket-patch-cli/src/commands/**' + - 'crates/socket-patch-cli/tests/common/**' + - 'crates/socket-patch-cli/tests/hosted_memory_common/**' + - 'Cargo.lock' + - 'Cargo.toml' + - 'crates/*/Cargo.toml' + - 'rust-toolchain.toml' + - '.cargo/**' + schedule: + # Nightly, so a main change outside the push list still gets a run + # within a day. The macOS leg runs here and on demand only. + - cron: '27 5 * * *' + workflow_dispatch: + +permissions: + contents: read + +# The nightly run has a group of its own. A group holds one pending run, so +# in the group of main's pushes a second push would replace a nightly that +# waits behind the first, and the nightly is the only run with the macOS leg. +concurrency: + group: bazel-maven-${{ github.event.pull_request.number || github.ref }}${{ github.event_name == 'schedule' && '-nightly' || '' }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + maven: + uses: ./.github/workflows/bazel-compatibility.yml + with: + eco: maven + fixtures: rules_jvm_external/bzlmod + # One leg per line: a Bazel release, and the era of the fixture that + # `maven::FIXTURE` gives it. + releases: >- + [ + {"bazel": "9.3.2", "era": "e9"}, + {"bazel": "8.8.2", "era": "e8"}, + {"bazel": "7.7.2", "era": "e7"} + ] + macos: >- + [ + {"bazel": "9.3.2", "era": "e9"} + ] diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 1fc54780b..693b5e76c 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2533,6 +2533,8 @@ command's integration tests check its output. | `patch_withdrawn` | `rolledBack` / `verified` (hosted event) | scan `--mode hosted`: the lockfile pinned a patch the server reports `withdrawn` or `not_found`; the pin was restored (dry run: would be) to its upstream registry entry. `reason` names the uuid and status. See "Withdrawn pins". | | `vendor_prebuilt_stub_invalid` | `failed` | RubyGems: the server stub lacks required attributes or is otherwise invalid; no local stub fallback is permitted. | | `bazelignore_not_updated` | run-level `warnings[]` | Go vendored and agent mode in a Bazel workspace (additive): the `.bazelignore` at the Bazel root, which keeps Bazel and gazelle out of the module copies under `.socket/vendor/golang` and `.socket/go-patches`, was not updated. It could not be read or written (a symbolic link or a directory in its place, a read-only directory, a read-only file). The detail names the line to add, or says that the lines of a copy that is gone can be deleted; the command's patch or undo stands and its exit code is unchanged. See docs/ecosystems.md "Bazel workspaces: `.bazelignore`". | +| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch that this run pinned, vendored or applied, or tried to (`get`, `scan`, `vendor`, `apply`, in hosted, vendored and agent mode; in agent mode only for a package it found installed; never under `--global`). The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build: socket-patch does not patch a hub yet. One warning per purl; the detail names the lock, the hub, and the file and line of its `maven.install`. The events, the exit code and every written file are those of the same run without the workspace. No other warning is removed or replaced for it: a hosted run of a tree without `pom.xml` gives `redirect_maven_no_pom` and, after it, this one. A `vendor` whose `--ecosystems` leaves Maven out gives none. See docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_unreadable` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace (additive): for the same runs, whether a hub builds the jar could not be told, because something could not be read with certainty: a hub without `lock_file` (also one that only `maven.artifact` or `maven.from_toml` tags make), one of those two tags that cannot be read, a lock that is missing, empty, not format 2 or 3, larger than 16 MiB or no JSON, or a `WORKSPACE` file that calls `maven_install` or cannot be read, while `.bazeliskrc` or `.bazelversion` at the Bazel root names no release of Bazel 9 or later (three numbers, read as bazelisk reads them); and, also for a jar that a hub's lock holds, a `maven.install` whose `name` or `lock_file` is not a plain string, a construct of `MODULE.bazel` the reader does not follow, or a `maven.override` of the artifact. One warning per purl; the detail names the file, the line and the reason. Nothing else changes. | | `vendor_*` / `pypi_*` / `gemfile_*` / `lock_*` / `locked_version_mismatch` / `user_authored_*` / `native_extensions_unsupported` / `platform_gem_unsupported` | `failed`/`skipped` | vendor: per-ecosystem refusal + drift vocabulary; see the Vendor command contract section. New tags are additive (MINOR). | `user_patch_conflict` is a `skipped` event and a scan/apply run warning for packages diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index aab8ae3b9..bc28e318b 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -1773,6 +1773,8 @@ pub(crate) async fn run_locked( .collect(); run_warnings.extend(user_patch_warnings.iter().cloned()); run_warnings.extend(unsupported_warning); + let patched = results.iter().map(|r| r.package_key.as_str()); + run_warnings.extend(super::bazel_maven_notices(&args.common, patched, false).await); run_warnings.extend(results.iter().flat_map(|r| { let note = r.error.as_deref().filter(|_| r.success).unwrap_or_default(); socket_patch_core::patch::apply::advisory_warning_codes(note) diff --git a/crates/socket-patch-cli/src/commands/mod.rs b/crates/socket-patch-cli/src/commands/mod.rs index 378213a89..2c3abf4b4 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -109,6 +109,37 @@ pub(crate) async fn sync_bazelignore( warnings } +/// In a Bazel workspace a rules_jvm_external hub builds the jars its own +/// lock pins, whatever a `pom.xml`, a Gradle build or an installed jar +/// holds (`socket_patch_core::bazel::maven`). A command that pins or +/// applies patches calls this once with the purls it was about, and hands +/// what it gets to the warnings of its run: one for each Maven jar among +/// them that a hub builds, or may build. Nothing for a `--global` run, +/// whose target is not the project, and no file is looked for when no purl +/// is a Maven one. +/// +/// With `tell`, a human run is told here, as [`sync_bazelignore`] tells +/// it. A command that prints the warnings of its run itself passes +/// `false`. +pub(crate) async fn bazel_maven_notices<'a>( + common: &crate::args::GlobalArgs, + purls: impl Iterator, + tell: bool, +) -> Vec { + if common.is_global() { + return Vec::new(); + } + let purls = purls.map(str::to_string).collect(); + let said = socket_patch_core::bazel::maven::notices(&common.cwd, purls).await; + let warning = |(code, detail): (&str, String)| { + if tell && !common.json && !common.silent { + eprintln!("Warning: {detail}"); + } + crate::json_envelope::RunWarning::new(code, detail) + }; + said.into_iter().map(warning).collect() +} + /// The vendor-ledger keys (`ledger`, the project's /// [`VendorState::purl_keys`]) that own this run's installed copies. In /// project scope that is the whole ledger. Under global scope the ledger diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index a74752506..4b8bbfe30 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -2185,6 +2185,12 @@ async fn run_redirect_selected_untracked( .iter() .map(|w| RunWarning::new(w.code.as_str(), w.detail.as_str())) .collect(); + // What a rules_jvm_external hub of a Bazel workspace builds, no pin of + // this run reaches: said for each such artifact, beside whatever the + // rewriters said and never in their list, which is what explains a + // lock entry that was not pinned. + let hub = selected.iter().map(|(purl, _)| purl.as_str()); + warnings.extend(crate::commands::bazel_maven_notices(common, hub, false).await); warnings.extend(gem_stale.warnings.iter().map(run_warning_of)); warnings.extend(nuget_stale.warnings.iter().map(run_warning_of)); warnings.extend(python_stale.warnings.iter().map(run_warning_of)); diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 16dfd1547..c6f378d45 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -4441,6 +4441,12 @@ pub(crate) async fn vendor_records_reusing( } } + // A hub of a Bazel workspace builds the jar of its own lock, whatever + // this run vendored for the Maven or the Gradle build. + let vendored = vendorable.iter().map(String::as_str); + env.warnings + .extend(crate::commands::bazel_maven_notices(common, vendored, true).await); + // A rolled-back eject's summary would describe a vendoring that was // undone: the eject prints it itself once it knows the outcome (#1005). match eject { diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs index 19204f18d..201b666a1 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -921,6 +921,15 @@ impl Cell { self.bazel_with("update", command, args) } + /// [`Cell::bazel`] with variables of the one command: the `REPIN=1` of + /// a ruleset's relock. Bazel's client hands its environment to the + /// repository rules and to what `bazel run` starts. + pub fn bazel_env(&self, command: &str, args: &[&str], env: &[(&str, &str)]) -> Run { + let mut cmd = self.command("update", command, args); + cmd.envs(env.iter().copied()); + Run::of(cmd).unwrap_or_else(|why| panic!("{}: {why}", self.test)) + } + /// `bazel build --lockfile_mode=error `: passes only when /// `MODULE.bazel.lock` already holds what the build resolves. fn frozen_build(&self, targets: &[&str]) -> Run { diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs index c4bcc1ff7..06acc4969 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs @@ -73,6 +73,7 @@ mod cargo; mod composer; mod go; mod harness; +mod maven; mod npm; mod nuget; mod pypi; diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs new file mode 100644 index 000000000..8ea716450 --- /dev/null +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs @@ -0,0 +1,497 @@ +//! A Maven artifact that Bazel builds through a rules_jvm_external hub: +//! `maven.install(artifacts = [...], lock_file = "//:maven_install.json")` +//! under Bzlmod, pinned with the ruleset's own `REPIN=1 bazel run +//! @fixture_maven//:pin`. +//! +//! Such a hub fetches each jar its lock names, with the sha256 the lock +//! holds, and reads no `pom.xml` and no Gradle file. So nothing +//! `socket-patch` does for a Maven artifact reaches a Bazel build yet, and +//! these flows hold what a user sees instead, on +//! the Bazel the run is given ([`FIXTURE`] says which ruleset goes with +//! its release): +//! +//! - [`a_pom_patch_beside_a_pinned_hub`]: a checkout that Maven builds +//! too. `socket-patch get --mode hosted --yes` pins the artifact +//! in `pom.xml` and reports it `applied`. The Bazel build before and +//! after prints the upstream marker, and Bazel never asks for the +//! patched jar. `rollback --yes` restores every file. +//! - [`a_tree_only_bazel_builds`]: the same checkout without a `pom.xml`. +//! The same command writes nothing and reports the patch `skipped` +//! (`redirect_unconfirmed`), and the build is as before. +//! +//! In both the command says what the build shows: one warning, +//! `maven_bazel_hub_unpatched`, that Bazel builds the artifact from +//! `maven_install.json`, with the hub and the line of its `maven.install`. +//! In the second it stands after `redirect_maven_no_pom`, "no pom.xml +//! present", which the command says as it does without a Bazel workspace. +//! The lock each ruleset release writes is the one socket-patch reads it +//! from ([`Lock`]). +//! +//! The artifacts are made here, for the run, under the group +//! `dev.socket.fixture`, which only the owner of `socket.dev` can publish +//! to Maven Central: `consumer:2.0`, the one artifact `MODULE.bazel` names, +//! and `victim:1.10.0`, which `consumer` depends on and the patch is for. +//! The victim's jar holds one file, the text `//:consumer` prints after +//! `OUT: `, with an id of the run in it, so no cache of an earlier run can +//! supply the jar. No lock is committed: a flow writes its stand-in's +//! origin into `MODULE.bazel` in the place of the hub's one repository +//! and pins, so the lock is the one the ruleset of the era writes (format +//! 3 from rules_jvm_external 6.10, format 2 before). +//! +//! One loopback server stands in for three hosts, by route prefix: the +//! Socket API at its own paths, the Maven repository of the two artifacts +//! (`/maven2`), and `patch.socket.dev` with the patched jar at the path of +//! the production patch registry. The pin runs Coursier, which the ruleset +//! starts and which asks the stand-in alone; the build fetches each jar +//! with Bazel's downloader from the URL in the lock. +//! +//! No pin and no build asks a public Maven repository. The hub is named +//! [`HUB`], not `maven`: other Bazel modules of the build add artifacts of +//! their own to a hub named `maven` (protobuf does), which a pin would +//! resolve from Maven Central, and nothing but the fixture adds to this +//! one. Its one repository is the stand-in, and [`Pinned::open`] holds +//! that the lock names the two artifacts and that repository, and nothing +//! else. A hub of the default name, whose lock also holds what other +//! modules added, is read without a Bazel in `e2e_bazel_maven_beside.rs`. +//! +//! What the stand-in lacks still comes from the network: the Bazel +//! registry, the ruleset archives, Coursier itself and the JDK that +//! rules_java downloads (each era's `.bazelrc` names the one its rules_java +//! runs javac on, so a build takes no Java from the machine and downloads +//! one JDK). rules_jvm_external before 6.8 (era `e7`) runs Coursier with +//! the Java of `JAVA_HOME`, else the `java` on `PATH`; later ones use the +//! Java embedded in Bazel. + +use std::io::Write as _; +use std::time::Instant; + +use serde_json::{json, Value}; +use sha1::Sha1; +use sha2::{Digest, Sha256}; +use socket_patch_core::bazel::maven::{Lock, Pinned as Jar}; + +use crate::envelope::event_for; +use crate::harness::{changed, Cell, Fixture, Ran, StandIn, Tree, NOTHING}; +use crate::hosted_memory_common::Patch; + +/// The workspace the tests build, and the ruleset each Bazel release +/// builds it with. One era per way the ruleset names an artifact's +/// repository and writes its lock. +const FIXTURE: Fixture = Fixture { + name: "maven::FIXTURE", + dir: "rules_jvm_external/bzlmod", + workflow: "bazel-maven.yml", + eras: &[ + // rules_jvm_external 6.5 and rules_java 7.6.5: lock format 2. + ((7, 0, 0)..(8, 0, 0), "e7"), + // rules_jvm_external 6.9 and rules_java 8.13.0: lock format 2. + ((8, 0, 0)..(9, 0, 0), "e8"), + // rules_jvm_external 7.2 and rules_java 9.3.0: lock format 3. + ((9, 0, 0)..(10, 0, 0), "e9"), + ], +}; + +/// The group of the fixture's artifacts, and its directory in a Maven +/// repository. +const GROUP: &str = "dev.socket.fixture"; +const GROUP_PATH: &str = "dev/socket/fixture"; +/// The artifact the patch is for, which `consumer:2.0` depends on. +const VICTIM: &str = "victim"; +const VERSION: &str = "1.10.0"; +const PURL: &str = "pkg:maven/dev.socket.fixture/victim@1.10.0"; +/// The file of the victim's jar that `App.java` prints. +const MARKER: &str = "dev/socket/fixture/victim/marker.txt"; +/// The fixture's hub, under a name no other Bazel module adds to. +const HUB: &str = "fixture_maven"; +/// The one repository of the fixture's `maven.install`, which a flow +/// replaces with its stand-in's. +const PLACEHOLDER: &str = "http://socket-fixture.invalid/maven2"; +/// The route prefixes of the stand-in, one per host it plays. +const UPSTREAM: &str = "maven2"; +const PATCH_HOST: &str = "patch.socket.dev"; +/// The files hosted mode writes for a Maven pin. +const PINNED: [&str; 3] = [ + ".mvn/checksums/checksums.sha256", + ".mvn/maven.config", + "pom.xml", +]; + +fn sha256_hex(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) +} + +/// A jar of `files`, stored and with one fixed time. +fn jar(files: &[(&str, &str)]) -> Vec { + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Stored) + .last_modified_time( + zip::DateTime::from_date_and_time(2026, 1, 1, 0, 0, 0).expect("a date"), + ); + let manifest = ("META-INF/MANIFEST.MF", "Manifest-Version: 1.0\r\n\r\n"); + for (name, text) in std::iter::once(&manifest).chain(files) { + zip.start_file(*name, options).expect("a jar member"); + zip.write_all(text.as_bytes()).expect("a jar member"); + } + zip.finish().expect("a jar").into_inner() +} + +/// The victim's jar, whose one file holds `marker`. +fn victim(marker: &str) -> Vec { + jar(&[(MARKER, &format!("{marker}\n"))]) +} + +/// The pom of `artifact` at `version`, which depends on `needs`. +fn pom(artifact: &str, version: &str, needs: Option<(&str, &str)>) -> String { + let needs = needs.map_or_else(String::new, |(artifact, version)| { + format!( + " \n \n {GROUP}\n \ + {artifact}\n {version}\n \ + \n \n" + ) + }); + format!( + "\n\ + \n \ + 4.0.0\n {GROUP}\n \ + {artifact}\n {version}\n{needs}\n" + ) +} + +/// `///-.`, the path of +/// a file in a Maven repository. +fn repo_path(artifact: &str, version: &str, ext: &str) -> String { + format!("{GROUP_PATH}/{artifact}/{version}/{artifact}-{version}.{ext}") +} + +/// A checkout whose hub is pinned, and what its flow reads afterwards. +struct Pinned { + cell: Cell, + standin: StandIn, + /// Where the JVM tools of the machine keep artifacts: `m2`, the Maven + /// local repository, with the victim in it as a Maven build of the + /// checkout leaves it; `coursier`, the cache the ruleset's Coursier + /// fills when it pins; `gradle`, which nothing fills. + tools: tempfile::TempDir, + uuid: String, + /// The line of `maven.install` in the checkout's `MODULE.bazel`. + install: usize, + /// What `//:consumer` prints while Bazel builds the upstream jar. + upstream: String, + /// The routes of the upstream and of the patched jar on the stand-in. + upstream_route: String, + patched_route: String, + started: Instant, +} + +impl Pinned { + /// Step 0 of both flows: the fixture's checkout for `test`, with a + /// `pom.xml` that declares the victim when `maven` is set, pinned by + /// the ruleset against a stand-in that has the two artifacts, the + /// patched jar and the grant of its patch. `None` when no Bazel runs + /// here. + fn open(test: &str, maven: bool) -> Option { + let started = Instant::now(); + let mut cell = Cell::open(test, &FIXTURE)?; + // The cache of the Coursier that pins. Before 7.2 the ruleset + // leaves the choice to Coursier, which without this takes the home + // directory from the system, whatever `HOME` says. + let tools = tempfile::tempdir().expect("the directories of the JVM tools"); + let coursier = tools.path().join("coursier").to_string_lossy().into_owned(); + cell.repo_env.push(("COURSIER_CACHE".to_string(), coursier)); + 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 suffixed = format!("{VERSION}-socket.{}", &uuid[..8]); + let upstream_jar = victim(&format!("PRISTINE {run}")); + let patched_jar = victim(&format!("PATCHED {uuid}")); + let victim_pom = pom(VICTIM, VERSION, None); + let served_pom = pom(VICTIM, &suffixed, None); + + let standin = StandIn::start(); + let origin = standin.origin(); + let served: [(String, Vec); 4] = [ + (repo_path(VICTIM, VERSION, "jar"), upstream_jar.clone()), + (repo_path(VICTIM, VERSION, "pom"), victim_pom.clone().into()), + (repo_path("consumer", "2.0", "jar"), jar(&[])), + ( + repo_path("consumer", "2.0", "pom"), + pom("consumer", "2.0", Some((VICTIM, VERSION))).into(), + ), + ]; + for (path, bytes) in &served { + // Coursier takes a file only with a checksum beside it. + let (route, sha1) = ( + format!("/{UPSTREAM}/{path}"), + hex::encode(Sha1::digest(bytes)), + ); + standin.serve(5, &route, bytes); + standin.serve(5, &format!("{route}.sha1"), sha1.as_bytes()); + } + // The patch registry and the grant, as production has them: a + // token and the patch id in the path, the version with the suffix + // only that registry serves. + let registry = format!("{PATCH_HOST}/patch-registry/maven/{token}/{uuid}/maven2"); + let patched_route = format!("/{registry}/{}", repo_path(VICTIM, &suffixed, "jar")); + standin.serve(5, &patched_route, &patched_jar); + let artifact = format!( + "https://{PATCH_HOST}/patch/maven/{GROUP}/{VICTIM}/{VERSION}/{token}/{uuid}/{VICTIM}-{suffixed}.jar" + ); + let reference = json!({ + "status": "granted", + "url": artifact, + "purl": PURL, + "artifacts": [{ + "kind": "tarball", + "url": artifact, + "integrity": { "sha256": sha256_hex(&patched_jar) }, + }], + "registryOverride": { + "kind": "maven2", + "indexUrl": format!("https://{registry}"), + "identifiers": { + "name": format!("{GROUP}/{VICTIM}"), + "version": VERSION, + "mavenGroupId": GROUP, + "mavenArtifactId": VICTIM, + "mavenSuffixedVersion": suffixed, + "mavenPomSha256": sha256_hex(served_pom.as_bytes()), + }, + }, + }); + standin.api(&[Patch { + purl: PURL.to_string(), + uuid: uuid.clone(), + reference, + }]); + + // The checkout: the hub's repository is the stand-in, the lock is + // the empty file the ruleset's documentation starts from. + let module = std::fs::read_to_string(cell.path("MODULE.bazel")).expect("MODULE.bazel"); + assert_eq!(module.matches(PLACEHOLDER).count(), 1, "{test}: {module}"); + let install = module.lines().position(|line| line == "maven.install("); + let install = install.expect("the fixture's maven.install") + 1; + let repository = format!("{origin}/{UPSTREAM}"); + cell.write("MODULE.bazel", module.replace(PLACEHOLDER, &repository)); + cell.write("maven_install.json", ""); + if maven { + cell.write("pom.xml", pom("app", "1.0.0", Some((VICTIM, VERSION)))); + } + for (ext, bytes) in [("jar", &upstream_jar[..]), ("pom", victim_pom.as_bytes())] { + let file = tools + .path() + .join("m2") + .join(repo_path(VICTIM, VERSION, ext)); + std::fs::create_dir_all(file.parent().expect("a directory")).expect("create it"); + std::fs::write(&file, bytes).expect("write the local repository"); + } + + // The ruleset's own relock. The lock it writes holds the victim, + // which `MODULE.bazel` does not name, at the sha256 of this run's + // jar, in the format of the era. + let pin = cell.bazel_env("run", &[&format!("@{HUB}//:pin")], &[("REPIN", "1")]); + assert!(pin.ok(), "{test}: {}", pin.dump()); + let lock = std::fs::read_to_string(cell.path("maven_install.json")).expect("the lock"); + let raw: Value = serde_json::from_str(&lock).expect("the lock is JSON"); + // Nothing else is in it: no other Bazel module added to the hub, + // and its one repository is the stand-in. + let keys = |of: &str| { + let map = raw[of].as_object().expect("a map of the lock"); + map.keys().map(String::as_str).collect::>().join(" ") + }; + assert_eq!( + (keys("artifacts"), keys("repositories")), + ( + format!("{GROUP}:consumer {GROUP}:{VICTIM}"), + format!("{repository}/") + ), + "{test}: {raw:#}" + ); + let lock = Lock::parse(&lock).unwrap_or_else(|why| panic!("{test}: {why}:\n{lock}")); + let format = if cell.numbers() >= (9, 0, 0) { 3 } else { 2 }; + let jar = Jar { + version: VERSION.to_string(), + jar_sha256: Some(sha256_hex(&upstream_jar)), + fetched: true, + }; + assert_eq!( + (lock.format, lock.plain_jar(GROUP, VICTIM)), + (format, Some(&jar)), + "{test}: {lock:?}" + ); + Some(Pinned { + cell, + standin, + tools, + uuid, + install, + upstream: format!("OUT: PRISTINE {run}"), + upstream_route: format!("/{UPSTREAM}/{}", repo_path(VICTIM, VERSION, "jar")), + patched_route, + started, + }) + } + + /// Step 1: the build prints the upstream marker, from a jar Bazel + /// fetched from the stand-in. Gives the files of the checkout. + fn builds_upstream(&self) -> Tree { + let (test, route) = (&self.cell.test, &self.upstream_route); + let pinned = self.standin.asked(route); + let before = self.cell.builds_unpatched(&self.upstream); + let fetched = self.standin.asked(route) > pinned; + assert!(fetched, "{test}: the build did not fetch {route}"); + before + } + + /// `socket-patch ` in the checkout, against the stand-in, with + /// the directories of [`Pinned::tools`] in the place of the machine's. + fn socket_patch(&self, args: &[&str]) -> Ran { + let dir = |name: &str| self.tools.path().join(name).to_string_lossy().into_owned(); + let (m2, gradle, coursier) = (dir("m2"), dir("gradle"), dir("coursier")); + let env = [ + ("MAVEN_REPO_LOCAL", m2.as_str()), + ("GRADLE_USER_HOME", &gradle), + ("COURSIER_CACHE", &coursier), + ]; + self.cell.socket_patch(&self.standin.origin(), args, &env) + } + + /// What the command says of the hub: one warning, that Bazel builds + /// the victim from the lock that the hub's `maven.install` names, + /// after the warnings `others` of the same run without a workspace. + fn names_the_hub(&self, get: &Ran, others: &[Value]) { + let detail = format!( + "{PURL}: Bazel takes this artifact from maven_install.json (hub \"{HUB}\", \ + `maven.install` at MODULE.bazel:{}), which pins the upstream jar. socket-patch \ + does not patch a rules_jvm_external hub yet, so the Bazel build stays unpatched \ + whatever this command did for another build of the checkout", + self.install + ); + let warning = json!({ "code": "maven_bazel_hub_unpatched", "detail": detail }); + let (test, said) = (&self.cell.test, &get.dump); + let warnings = [others, &[warning]].concat(); + assert_eq!(get.envelope["warnings"], json!(warnings), "{test}: {said}"); + } + + /// The step after the command: the build prints the upstream marker + /// as before and changed no file of `after`, and no request for the + /// patched jar reached the stand-in. + fn still_builds_upstream(&self, after: &Tree) { + let test = &self.cell.test; + self.cell.builds(&self.upstream); + assert_eq!(changed(after, &self.cell.tree()), NOTHING, "{test}"); + let asked = self.standin.asked(&self.patched_route); + assert_eq!(asked, 0, "{test}: something fetched the patched jar"); + } +} + +/// A Maven build and a Bazel build of one checkout: the command pins the +/// Maven build, reports the patch applied, and the Bazel build keeps the +/// upstream jar. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn a_pom_patch_beside_a_pinned_hub() { + let test = "maven::a_pom_patch_beside_a_pinned_hub"; + let Some(flow) = Pinned::open(test, true) else { + return; + }; + let before = flow.builds_upstream(); + + // The one command of hosted mode: the three files of a Maven pin, and + // the warning about the hub whose lock still names the upstream jar. + let get = flow.socket_patch(&["get", PURL, "--mode", "hosted", "--yes"]); + let pinned = flow + .cell + .pinned_by(&get, PURL, &flow.uuid, &before, &PINNED); + flow.names_the_hub(&get, &[]); + flow.still_builds_upstream(&pinned); + + let undo = flow.socket_patch(&["rollback", "--yes"]); + flow.cell + .undone(&undo, "rolledBack", &before, &flow.upstream); + println!( + "{test}: Bazel {} built {:?} before and after `get --mode hosted` pinned {PURL} in \ + pom.xml, reported it applied and named the hub; {:?}", + flow.cell.release(), + flow.upstream, + flow.started.elapsed() + ); +} + +/// The same checkout without a `pom.xml`: the command writes nothing, +/// says that there is no pom, and says which lock builds the artifact. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn a_tree_only_bazel_builds() { + let test = "maven::a_tree_only_bazel_builds"; + let Some(flow) = Pinned::open(test, false) else { + return; + }; + let before = flow.builds_upstream(); + + let get = flow.socket_patch(&["get", PURL, "--mode", "hosted", "--yes"]); + let said = &get.dump; + assert_eq!(get.code, 0, "{test}: {said}"); + let event = event_for(&get.envelope, PURL); + assert_eq!( + (&event["action"], &event["errorCode"]), + (&json!("skipped"), &json!("redirect_unconfirmed")), + "{test}: {said}" + ); + let no_pom = "no pom.xml present; maven redirect skipped"; + flow.names_the_hub( + &get, + &[json!({ "code": "redirect_maven_no_pom", "detail": no_pom })], + ); + assert_eq!( + changed(&before, &flow.cell.tree()), + NOTHING, + "{test}: {said}" + ); + flow.still_builds_upstream(&before); + println!( + "{test}: Bazel {} built {:?} before and after `get --mode hosted` skipped {PURL} \ + and named the hub; {:?}", + flow.cell.release(), + flow.upstream, + flow.started.elapsed() + ); +} + +/// Without a Bazel: the fixture's directories and the legs of its workflow +/// are those of the table, each era's `MODULE.bazel` has a hub of its own +/// name with the one repository a flow replaces, and a jar made here holds +/// what `App.java` reads. +#[test] +fn the_fixture_has_one_repository_to_replace_per_era() { + FIXTURE.check(); + for (_, era) in FIXTURE.eras { + let module = crate::harness::fixture_path(FIXTURE.dir) + .join(era) + .join("MODULE.bazel"); + let module = std::fs::read_to_string(&module).expect("MODULE.bazel"); + assert_eq!(module.matches(PLACEHOLDER).count(), 1, "{era}: {module}"); + // No other URL, and the hub is [`HUB`]: no pin resolves what other + // modules add to a hub named `maven`, or asks a public repository. + assert_eq!(module.matches("://").count(), 1, "{era}: {module}"); + for named in [ + format!("name = \"{HUB}\","), + format!("use_repo(maven, \"{HUB}\")"), + ] { + assert!(module.contains(&named), "{era}: {named} is not in {module}"); + } + } + let build = crate::harness::fixture_path(FIXTURE.dir).join("common/BUILD.bazel"); + let build = std::fs::read_to_string(&build).expect("BUILD.bazel"); + let dep = format!("\"@{HUB}//:dev_socket_fixture_consumer\""); + assert!(build.contains(&dep), "{build}"); + let app = crate::harness::fixture_path(FIXTURE.dir).join("common/App.java"); + let app = std::fs::read_to_string(&app).expect("App.java"); + assert!(app.contains(&format!("\"/{MARKER}\"")), "{app}"); + let jar = victim("PRISTINE of a run"); + let mut jar = zip::ZipArchive::new(std::io::Cursor::new(&jar[..])).expect("a jar"); + let mut marker = String::new(); + let mut file = jar.by_name(MARKER).expect("the marker"); + std::io::Read::read_to_string(&mut file, &mut marker).expect("its text"); + assert_eq!(marker, "PRISTINE of a run\n"); +} diff --git a/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs b/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs new file mode 100644 index 000000000..0eb89632c --- /dev/null +++ b/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs @@ -0,0 +1,444 @@ +//! A Maven project beside a Bazel workspace, without a Bazel: what +//! `socket-patch` says about a rules_jvm_external hub, and that it says and +//! writes nothing else. +//! +//! The first test is the one that holds "nothing changes": a hosted `get` +//! and an agent `apply` of a Maven patch print the same bytes and write the +//! same files in a checkout without a Bazel file, in one whose workspace +//! has no rules_jvm_external hub, and in one whose pinned hub does not hold +//! the artifact. A change that turns it red has changed what a project +//! that no hub builds gets. The others hold the one difference a hub +//! makes: one more warning of the run, also beside "no pom.xml" in a tree +//! that only Bazel builds, and none under `--global`. +//! +//! The vendored twin is in `vendor_jvm_cli.rs`, which has the fixture of a +//! vendored Maven run. `e2e_bazel_build/maven.rs` holds the hosted flows +//! against what a real Bazel builds, with a hub of the fixture's own name +//! whose lock holds its two artifacts. Here the hub has the default name, +//! `maven`, and its lock also holds an artifact that another Bazel module +//! added, under two repositories ([`lock`]). + +#[path = "common/envelope.rs"] +mod envelope; +#[path = "hosted_memory_common/mod.rs"] +mod hosted_memory_common; + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use envelope::{event_for, warning_codes}; +use hosted_memory_common::{hermetic, mount_api, read_tree, Patch, ORG}; +use serde_json::{json, Value}; +use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes as git_sha256; + +const PURL: &str = "pkg:maven/dev.socket.fixture/victim@1.10.0"; +const UUID: &str = "5e0a7c1d-7b4e-4c1a-9f0e-2a3b4c5d6e7f"; +const SUFFIXED: &str = "1.10.0-socket.5e0a7c1d"; +const POM: &str = + "4.0.0dev.socket.fixture\ + victim1.10.0\n"; +const PATCHED_POM: &str = "4.0.0dev.socket.fixture\ + victim1.10.0\ + \n"; +/// The checkout's own build of the artifact. +const PROJECT_POM: &str = "\n 4.0.0\n \ + com.example\n app\n \ + 1\n \n \n \ + dev.socket.fixture\n \ + victim\n 1.10.0\n \ + \n \n\n"; + +/// A workspace whose hub is pinned, under the name a hub has when its tag +/// gives none: `maven`, the one other Bazel modules add to. +const HUB: &str = r#"bazel_dep(name = "rules_jvm_external", version = "7.2") + +maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") +maven.install( + artifacts = ["dev.socket.fixture:consumer:2.0"], + lock_file = "//:maven_install.json", +) +use_repo(maven, "maven") +"#; +/// A workspace whose only hub is another ruleset's. +const OTHER_HUB: &str = r#"bazel_dep(name = "rules_python", version = "1.4.1") + +pip = use_extension("@rules_python//python/extensions:pip.bzl", "pip") +pip.parse(hub_name = "pypi", python_version = "3.11", requirements_lock = "//:maven_install.json") +use_repo(pip, "pypi") +"#; + +/// A lock of format 3 as a pin of [`HUB`] writes it when another Bazel +/// module adds to the hub named `maven` too, which the real-Bazel flows do +/// not build: the jar of each of `jars`, an artifact of the group and its +/// version, beside one that the other module asked for, and every artifact +/// under each of the hub's two repositories. +fn lock(jars: &[(&str, &str)]) -> String { + let pinned = |key: String, version: &str| { + let pinned = json!({ "shasums": { "jar": "0".repeat(64) }, "version": version }); + (key, pinned) + }; + let own = |jar: &(&str, &str)| pinned(format!("dev.socket.fixture:{}", jar.0), jar.1); + let other = pinned("com.google.code.gson:gson".to_string(), "2.8.9"); + let artifacts: serde_json::Map<_, _> = jars.iter().map(own).chain([other]).collect(); + let listed: Vec<&String> = artifacts.keys().collect(); + let lock = json!({ + "artifacts": artifacts, + "dependencies": {}, + "repositories": { + "https://repo.example/maven2/": listed, + "https://repo1.maven.org/maven2/": listed, + }, + "version": "3", + }); + format!("{lock:#}\n") +} + +/// The Bazel files of the four checkouts: none; a workspace without a +/// rules_jvm_external hub, beside a lock that holds the artifact; a +/// pinned hub that holds another artifact, and the patched one at another +/// version; a pinned hub that builds it. +fn checkouts() -> [Vec<(&'static str, String)>; 4] { + let module = |text: &str| ("MODULE.bazel", text.to_string()); + let locked = |jars: &[(&str, &str)]| ("maven_install.json", lock(jars)); + let builds = [("consumer", "2.0"), ("victim", "1.10.0")]; + [ + vec![], + vec![module(OTHER_HUB), locked(&builds)], + vec![ + module(HUB), + locked(&[("consumer", "2.0"), ("victim", "1.9.0")]), + ], + vec![module(HUB), locked(&builds)], + ] +} + +/// What one command did. +#[derive(Debug, PartialEq)] +struct Ran { + code: Option, + stdout: String, + stderr: String, + /// The files of the checkout and of the Maven local repository that + /// are not as they were before, with their bytes. + wrote: BTreeMap>, +} + +impl Ran { + fn envelope(&self) -> Value { + serde_json::from_str(&self.stdout).unwrap_or_else(|e| panic!("no envelope ({e}): {self:?}")) + } +} + +/// One directory for every checkout of a test, so that no path in an +/// output differs between two of them, and the Socket API of the patch. +struct Machine { + root: PathBuf, + api: wiremock::MockServer, + // The server runs on it. + _runtime: tokio::runtime::Runtime, + _tmp: tempfile::TempDir, +} + +impl Machine { + fn start() -> Machine { + let tmp = tempfile::tempdir().expect("a directory"); + let root = tmp.path().canonicalize().expect("its real path"); + let runtime = tokio::runtime::Runtime::new().expect("a runtime"); + let api = runtime.block_on(wiremock::MockServer::start()); + // The grant of the hosted patch: the maven2 registry override of + // production, with the version only that registry serves. + let index = format!("https://patch.socket.dev/patch-registry/maven/token/{UUID}/maven2"); + let url = + format!("https://patch.socket.dev/patch/maven/token/{UUID}/victim-{SUFFIXED}.jar"); + let reference = json!({ + "status": "granted", + "url": url, + "purl": PURL, + "artifacts": [{ "kind": "tarball", "url": url, "integrity": { "sha256": "a".repeat(64) } }], + "registryOverride": { "kind": "maven2", "indexUrl": index, "identifiers": { + "name": "dev.socket.fixture/victim", + "version": "1.10.0", + "mavenGroupId": "dev.socket.fixture", + "mavenArtifactId": "victim", + "mavenSuffixedVersion": SUFFIXED, + "mavenPomSha256": "b".repeat(64), + } }, + }); + let patch = Patch { + purl: PURL.to_string(), + uuid: UUID.to_string(), + reference, + }; + runtime.block_on(mount_api(&api, &[patch])); + Machine { + root, + api, + _runtime: runtime, + _tmp: tmp, + } + } + + /// Makes the checkout anew, with the Bazel files `bazel` and, when + /// `maven` is set, its `pom.xml`; a manifest of an agent patch of the + /// artifact's pom; and the Maven local repository as a build of the + /// checkout leaves it. Then runs `socket-patch ` there. + fn run(&self, bazel: &[(&str, String)], maven: bool, args: &[&str]) -> Ran { + let (proj, m2) = (self.root.join("proj"), self.root.join("m2")); + for dir in [&proj, &m2, &self.root.join("home")] { + let _ = std::fs::remove_dir_all(dir); + } + let write = |path: PathBuf, bytes: &[u8]| { + std::fs::create_dir_all(path.parent().expect("a directory")).expect("create it"); + std::fs::write(&path, bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + }; + std::fs::create_dir_all(proj.join(".git")).expect("a checkout"); + for (path, text) in bazel { + write(proj.join(path), text.as_bytes()); + } + if maven { + write(proj.join("pom.xml"), PROJECT_POM.as_bytes()); + } + let record = json!({ PURL: { + "uuid": UUID, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { "package/victim-1.10.0.pom": { + "beforeHash": git_sha256(POM.as_bytes()), + "afterHash": git_sha256(PATCHED_POM.as_bytes()), + } }, + "vulnerabilities": {}, + "description": "a pom patch", + "license": "MIT", + "tier": "free", + } }); + let manifest = format!("{:#}\n", json!({ "patches": record })); + write(proj.join(".socket/manifest.json"), manifest.as_bytes()); + for bytes in [POM, PATCHED_POM].map(str::as_bytes) { + write(proj.join(".socket/blobs").join(git_sha256(bytes)), bytes); + } + write( + m2.join("dev/socket/fixture/victim/1.10.0/victim-1.10.0.pom"), + POM.as_bytes(), + ); + let before = self.files(); + + // Nothing of the machine reaches the child: no tool on PATH, an + // empty home, and the JVM caches a crawl reads in this directory. + // `LLVM_PROFILE_FILE` stays: a binary built for coverage writes + // its profile where that names, and without it into the project + // directory, where a test holds a run to the files it wrote. + let mut cmd = hermetic::binary_command(); + cmd.env_clear() + .envs(hermetic::FORCED_OPT_OUTS.iter().copied()); + for keep in [ + "SYSTEMROOT", + "SystemRoot", + "windir", + "TMPDIR", + "TEMP", + "TMP", + "LLVM_PROFILE_FILE", + ] { + cmd.envs(std::env::var_os(keep).map(|value| (keep, value))); + } + let home = self.root.join("home"); + std::fs::create_dir_all(&home).expect("a home"); + cmd.current_dir(&proj) + .env("PATH", "") + .env("HOME", &home) + .env("USERPROFILE", &home) + .env("MAVEN_REPO_LOCAL", &m2) + .env("GRADLE_USER_HOME", home.join("gradle")) + .env("COURSIER_CACHE", home.join("coursier")) + .args(args) + .args(["--org", ORG, "--api-token", "fake-token"]) + .args(["--api-url", &self.api.uri()]); + let out = cmd.output().expect("spawn socket-patch"); + let wrote = self.files(); + let wrote = wrote + .into_iter() + .filter(|(path, bytes)| before.get(path) != Some(bytes)); + Ran { + code: out.status.code(), + stdout: String::from_utf8_lossy(&out.stdout).into_owned(), + stderr: String::from_utf8_lossy(&out.stderr).into_owned(), + wrote: wrote.collect(), + } + } + + /// The files of the checkout and of the Maven local repository. + fn files(&self) -> BTreeMap> { + let mut files = BTreeMap::new(); + for dir in ["proj", "m2"] { + let under = read_tree(&self.root.join(dir)).into_iter(); + files.extend(under.map(|(path, bytes)| (format!("{dir}/{path}"), bytes))); + } + files + } +} + +/// The commands of a run that patches the artifact: hosted and agent mode, +/// each as a program and as a person reads it, and as a dry run. +const COMMANDS: [&[&str]; 6] = [ + &["get", PURL, "--mode", "hosted", "--yes", "--json"], + &["get", PURL, "--mode", "hosted", "--yes"], + &["apply", "--offline", "--json"], + &["apply", "--offline"], + &[ + "get", + PURL, + "--mode", + "hosted", + "--yes", + "--dry-run", + "--json", + ], + &["apply", "--offline", "--dry-run", "--json"], +]; + +/// The warning of a run in the checkout whose hub builds the artifact. +const HUB_WARNING: &str = "pkg:maven/dev.socket.fixture/victim@1.10.0: Bazel takes this artifact \ + from maven_install.json (hub \"maven\", `maven.install` at MODULE.bazel:4), which pins the \ + upstream jar. socket-patch does not patch a rules_jvm_external hub yet, so the Bazel build \ + stays unpatched whatever this command did for another build of the checkout"; + +#[test] +fn a_maven_project_no_hub_builds_reports_as_without_bazel() { + let machine = Machine::start(); + let [plain, other, elsewhere, _] = checkouts(); + for args in COMMANDS { + let without = machine.run(&plain, true, args); + // The run did its work: a pin in pom.xml, a patched pom. A dry + // run writes neither. + assert_eq!(without.code, Some(0), "{args:?}: {without:?}"); + let patched = match args[0] { + "get" => "proj/pom.xml", + _ => "m2/dev/socket/fixture/victim/1.10.0/victim-1.10.0.pom", + }; + assert_eq!( + without.wrote.contains_key(patched), + !args.contains(&"--dry-run"), + "{args:?}: {without:?}" + ); + for bazel in [&other, &elsewhere] { + let beside = machine.run(bazel, true, args); + assert_eq!(beside, without, "{args:?} beside {:?}", bazel[0].1); + } + } +} + +#[test] +fn a_hub_that_pins_the_artifact_adds_one_warning_and_nothing_else() { + let machine = Machine::start(); + let [plain, _, _, hub] = checkouts(); + for args in COMMANDS { + let (without, beside) = ( + machine.run(&plain, true, args), + machine.run(&hub, true, args), + ); + assert_eq!( + (beside.code, &beside.wrote), + (without.code, &without.wrote), + "{args:?}: {beside:?}" + ); + if args.contains(&"--json") { + let (mut said, mut expected) = (beside.envelope(), without.envelope()); + let warning = json!({ "code": "maven_bazel_hub_unpatched", "detail": HUB_WARNING }); + let warnings = expected["warnings"].as_array().cloned().unwrap_or_default(); + assert_eq!( + said["warnings"].take(), + Value::Array([warnings, vec![warning]].concat()), + "{args:?}: {beside:?}" + ); + expected + .as_object_mut() + .expect("an envelope") + .remove("warnings"); + said.as_object_mut() + .expect("an envelope") + .remove("warnings"); + assert_eq!(said, expected, "{args:?}"); + assert_eq!(beside.stderr, without.stderr, "{args:?}"); + } else { + // One line more on stderr, and it is the warning. + assert_eq!(beside.stdout, without.stdout, "{args:?}"); + let line = format!("Warning: {HUB_WARNING}"); + let (mut said, expected) = (beside.stderr.lines(), without.stderr.lines()); + let rest: Vec<&str> = said.by_ref().filter(|said| *said != line).collect(); + assert_eq!(rest, expected.collect::>(), "{args:?}: {beside:?}"); + assert_eq!( + beside.stderr.matches(&line).count(), + 1, + "{args:?}: {beside:?}" + ); + } + } +} + +#[test] +fn a_hub_only_tree_names_the_lock_beside_the_missing_pom() { + let machine = Machine::start(); + let [plain, _, elsewhere, hub] = checkouts(); + let lockless = HUB.replace(" lock_file = \"//:maven_install.json\",\n", ""); + let unreadable = vec![("MODULE.bazel", lockless)]; + let json = COMMANDS[0]; + let no_pom = "redirect_maven_no_pom"; + for (bazel, codes) in [ + // Without a hub that holds it, the release's answer. + (&plain, &[no_pom][..]), + (&elsewhere, &[no_pom]), + // What is said of a hub stands after it: no warning of the run + // is taken away for it. + (&hub, &[no_pom, "maven_bazel_hub_unpatched"]), + (&unreadable, &[no_pom, "maven_bazel_unreadable"]), + ] { + let ran = machine.run(bazel, false, json); + let envelope = ran.envelope(); + let event = event_for(&envelope, PURL); + assert_eq!( + (ran.code, &event["action"], &event["errorCode"]), + (Some(0), &json!("skipped"), &json!("redirect_unconfirmed")), + "{codes:?}: {ran:?}" + ); + assert_eq!(warning_codes(&envelope), codes, "{ran:?}"); + assert_eq!(ran.wrote, BTreeMap::new(), "{codes:?}"); + } + // A person is pointed at one warning, the lock rewriter's, which says + // why no lock entry was pinned, and reads the one about the hub below + // it: that one is no reason for a missing lock entry, of this package + // or of another. + let pointed = "no lockfile entry pinning it could be rewritten (see the warning below)\n"; + let no_pom = "Warning: No pom.xml present; maven redirect skipped\n"; + for (bazel, about_the_hub) in [ + (&hub, format!("Warning: {HUB_WARNING}\n")), + ( + &unreadable, + format!("Warning: {PURL}: socket-patch could not tell"), + ), + ] { + let ran = machine.run(bazel, false, COMMANDS[1]); + let at = [pointed, no_pom, &about_the_hub].map(|line| ran.stderr.find(line)); + assert!(at[0].is_some() && at[0] < at[1] && at[1] < at[2], "{ran:?}"); + } + let detail = machine.run(&unreadable, false, json).envelope()["warnings"][1]["detail"].clone(); + let why = "pkg:maven/dev.socket.fixture/victim@1.10.0: socket-patch could not tell whether \ + Bazel takes this artifact from a rules_jvm_external hub: MODULE.bazel:4: hub \ + \"maven\" has no `lock_file`"; + assert_eq!(detail, why); +} + +#[test] +fn a_global_run_says_nothing() { + let machine = Machine::start(); + let [plain, _, _, hub] = checkouts(); + // A hub that builds the artifact, and one that cannot be read. + let unpinned = vec![("MODULE.bazel", HUB.to_string())]; + let global = ["apply", "--offline", "--global", "--json"]; + for args in [&global[..], &global[..3]] { + let without = machine.run(&plain, true, args); + assert_eq!(without.code, Some(0), "{args:?}: {without:?}"); + assert!(!without.wrote.is_empty(), "{args:?}: {without:?}"); + for bazel in [&hub, &unpinned] { + assert_eq!(machine.run(bazel, true, args), without, "{args:?}"); + } + } +} diff --git a/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/common/App.java b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/common/App.java new file mode 100644 index 000000000..d01f47f6a --- /dev/null +++ b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/common/App.java @@ -0,0 +1,11 @@ +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +public class App { + public static void main(String[] args) throws Exception { + // The one file of dev.socket.fixture:victim, read from the classpath. + try (InputStream marker = App.class.getResourceAsStream("/dev/socket/fixture/victim/marker.txt")) { + System.out.println("OUT: " + new String(marker.readAllBytes(), StandardCharsets.UTF_8).trim()); + } + } +} diff --git a/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/common/BUILD.bazel b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/common/BUILD.bazel new file mode 100644 index 000000000..b513c8401 --- /dev/null +++ b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/common/BUILD.bazel @@ -0,0 +1,11 @@ +load("@rules_java//java:defs.bzl", "java_binary") + +# Prints OUT: and the marker in the victim's jar. The workspace names only +# `consumer`: the victim is on the classpath through the hub's own +# dependency edge. +java_binary( + name = "consumer", + srcs = ["App.java"], + main_class = "App", + deps = ["@fixture_maven//:dev_socket_fixture_consumer"], +) diff --git a/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e7/.bazelrc b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e7/.bazelrc new file mode 100644 index 000000000..b0ed89275 --- /dev/null +++ b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e7/.bazelrc @@ -0,0 +1,5 @@ +# One JDK for everything: the one this era's rules_java runs javac on +# compiles for itself, runs the tools of the build and runs //:consumer. +# So a build takes no Java from the machine and downloads one JDK. +build --java_language_version=21 --java_runtime_version=remotejdk_21 +build --tool_java_language_version=21 --tool_java_runtime_version=remotejdk_21 diff --git a/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e7/MODULE.bazel b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e7/MODULE.bazel new file mode 100644 index 000000000..4bb7babc0 --- /dev/null +++ b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e7/MODULE.bazel @@ -0,0 +1,21 @@ +module(name = "socket_fixture", version = "0.0.0") + +bazel_dep(name = "rules_jvm_external", version = "6.5") +bazel_dep(name = "rules_java", version = "7.6.5") +single_version_override(module_name = "rules_jvm_external", version = "6.5") + +# The hub has a name of its own. A hub named "maven" also takes the +# artifacts that other Bazel modules of the build add to a hub of that name +# (protobuf does), and a pin resolves those from Maven Central. Nothing but +# this file adds to this hub, and its one repository is the test's own, +# which a test puts in the place of the URL below: no pin and no build asks +# a public Maven repository. Only `consumer` is named here; the victim is +# its dependency. +maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") +maven.install( + name = "fixture_maven", + artifacts = ["dev.socket.fixture:consumer:2.0"], + lock_file = "//:maven_install.json", + repositories = ["http://socket-fixture.invalid/maven2"], +) +use_repo(maven, "fixture_maven") diff --git a/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e8/.bazelrc b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e8/.bazelrc new file mode 100644 index 000000000..b0ed89275 --- /dev/null +++ b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e8/.bazelrc @@ -0,0 +1,5 @@ +# One JDK for everything: the one this era's rules_java runs javac on +# compiles for itself, runs the tools of the build and runs //:consumer. +# So a build takes no Java from the machine and downloads one JDK. +build --java_language_version=21 --java_runtime_version=remotejdk_21 +build --tool_java_language_version=21 --tool_java_runtime_version=remotejdk_21 diff --git a/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e8/MODULE.bazel b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e8/MODULE.bazel new file mode 100644 index 000000000..22b5643f5 --- /dev/null +++ b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e8/MODULE.bazel @@ -0,0 +1,21 @@ +module(name = "socket_fixture", version = "0.0.0") + +bazel_dep(name = "rules_jvm_external", version = "6.9") +bazel_dep(name = "rules_java", version = "8.13.0") +single_version_override(module_name = "rules_jvm_external", version = "6.9") + +# The hub has a name of its own. A hub named "maven" also takes the +# artifacts that other Bazel modules of the build add to a hub of that name +# (protobuf does), and a pin resolves those from Maven Central. Nothing but +# this file adds to this hub, and its one repository is the test's own, +# which a test puts in the place of the URL below: no pin and no build asks +# a public Maven repository. Only `consumer` is named here; the victim is +# its dependency. +maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") +maven.install( + name = "fixture_maven", + artifacts = ["dev.socket.fixture:consumer:2.0"], + lock_file = "//:maven_install.json", + repositories = ["http://socket-fixture.invalid/maven2"], +) +use_repo(maven, "fixture_maven") diff --git a/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e9/.bazelrc b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e9/.bazelrc new file mode 100644 index 000000000..bc79a6a49 --- /dev/null +++ b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e9/.bazelrc @@ -0,0 +1,5 @@ +# One JDK for everything: the one this era's rules_java runs javac on +# compiles for itself, runs the tools of the build and runs //:consumer. +# So a build takes no Java from the machine and downloads one JDK. +build --java_language_version=25 --java_runtime_version=remotejdk_25 +build --tool_java_language_version=25 --tool_java_runtime_version=remotejdk_25 diff --git a/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e9/MODULE.bazel b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e9/MODULE.bazel new file mode 100644 index 000000000..4063472d3 --- /dev/null +++ b/crates/socket-patch-cli/tests/fixtures/bazel/rules_jvm_external/bzlmod/e9/MODULE.bazel @@ -0,0 +1,21 @@ +module(name = "socket_fixture", version = "0.0.0") + +bazel_dep(name = "rules_jvm_external", version = "7.2") +bazel_dep(name = "rules_java", version = "9.3.0") +single_version_override(module_name = "rules_jvm_external", version = "7.2") + +# The hub has a name of its own. A hub named "maven" also takes the +# artifacts that other Bazel modules of the build add to a hub of that name +# (protobuf does), and a pin resolves those from Maven Central. Nothing but +# this file adds to this hub, and its one repository is the test's own, +# which a test puts in the place of the URL below: no pin and no build asks +# a public Maven repository. Only `consumer` is named here; the victim is +# its dependency. +maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") +maven.install( + name = "fixture_maven", + artifacts = ["dev.socket.fixture:consumer:2.0"], + lock_file = "//:maven_install.json", + repositories = ["http://socket-fixture.invalid/maven2"], +) +use_repo(maven, "fixture_maven") diff --git a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs index 331f61200..f873d505b 100644 --- a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs +++ b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs @@ -148,22 +148,37 @@ fn fixture(root: &Path, shape: Shape, packages: &[(&str, &str)]) { } } -/// `socket-patch --json --offline --cwd /proj`; `(exit, envelope)`. -fn socket(root: &Path, args: &[&str]) -> (Option, serde_json::Value) { +/// `socket-patch --offline --cwd /proj`, with `--json` or as a +/// person runs it, and the download fixture it needs while it runs. +fn command( + root: &Path, + args: &[&str], + json: bool, +) -> (std::process::Command, Option) { let mut cmd = hermetic::binary_command(); let proj = root.join("proj"); - let _fixture = prebuilt_common::prepare_command( + let fixture = prebuilt_common::prepare_command( &mut cmd, &proj, args, &[("MAVEN_REPO_LOCAL", root.join("m2").to_str().unwrap())], ); - let out = cmd - .args(["--json", "--cwd", proj.to_str().unwrap()]) + cmd.args(json.then_some("--json")) + .args(["--cwd", proj.to_str().unwrap()]) .env("MAVEN_REPO_LOCAL", root.join("m2")) - .env_remove("M2_HOME") - .output() - .expect("run socket-patch"); + .env_remove("M2_HOME"); + (cmd, fixture) +} + +/// What [`command`] printed and how it ended. +fn spawn(root: &Path, args: &[&str], json: bool) -> std::process::Output { + let (mut cmd, _fixture) = command(root, args, json); + cmd.output().expect("run socket-patch") +} + +/// `socket-patch --json --offline --cwd /proj`; `(exit, envelope)`. +fn socket(root: &Path, args: &[&str]) -> (Option, serde_json::Value) { + let out = spawn(root, args, true); let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); let env = serde_json::from_str(&stdout).unwrap_or_else(|e| { panic!( @@ -1678,3 +1693,108 @@ fn gradle_vendor_395_repair_refuses_a_linked_gradle_tree() { assert!(env.to_string().contains("vendor_path_unsafe"), "{env}"); assert_eq!(listing(&outside.join("org/example/foo/1.0")), before); } + +/// A rules_jvm_external hub of a Bazel workspace builds the jar its own +/// lock pins, not the vendored one. `vendor` beside such a hub warns once +/// for each jar the hub builds, in the envelope or as a line a person +/// reads, and its events and every file it writes are those of the same +/// run without the workspace. A hub that does not build a vendored jar +/// adds nothing. +#[test] +fn a_bazel_hub_that_builds_a_vendored_jar_adds_one_warning_and_nothing_else() { + let module = "bazel_dep(name = \"rules_jvm_external\", version = \"7.2\")\n\ + maven = use_extension(\"@rules_jvm_external//:extensions.bzl\", \"maven\")\n\ + maven.install(lock_file = \"//:maven_install.json\")\n"; + let lock = |artifact: &str| { + format!( + "{{\"artifacts\": {{\"org.example:{artifact}\": {{\"shasums\": {{\"jar\": \"00\"}}, \ + \"version\": \"1.0\"}}}}, \"repositories\": {{\"https://repo1.maven.org/maven2/\": \ + [\"org.example:{artifact}\"]}}, \"version\": \"3\"}}\n" + ) + }; + let checkout = |lock: Option| { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fixture( + root, + Shape::Reactor, + &[("foo", FOO_UUID), ("bar", BAR_UUID)], + ); + if let Some(lock) = lock { + write(root, "proj/MODULE.bazel", module.as_bytes()); + write(root, "proj/maven_install.json", lock.as_bytes()); + } + tmp + }; + let vendor = |lock: Option| { + let tmp = checkout(lock); + let root = tmp.path(); + let env = ok(root, &["vendor"]); + let mut tree = snapshot(root); + tree.retain(|rel, _| rel != "MODULE.bazel" && rel != "maven_install.json"); + let warnings = env["warnings"].as_array().cloned().unwrap_or_default(); + (events(&env), tree, warnings) + }; + let without = vendor(None); + let applied = without.0.iter().filter(|event| event.1 == "applied"); + assert_eq!(applied.count(), 2, "{:?}", without.0); + assert_eq!(vendor(Some(lock("other"))), without); + let (events, tree, warnings) = vendor(Some(lock("foo"))); + assert_eq!((&events, &tree), (&without.0, &without.1)); + let detail = format!( + "{}: Bazel takes this artifact from maven_install.json (hub \"maven\", `maven.install` \ + at MODULE.bazel:3), which pins the upstream jar. socket-patch does not patch a \ + rules_jvm_external hub yet, so the Bazel build stays unpatched whatever this command \ + did for another build of the checkout", + purl("foo") + ); + let warning = serde_json::json!({ "code": "maven_bazel_hub_unpatched", "detail": detail }); + assert_eq!(warnings, [without.2, vec![warning]].concat()); + // A person reads it once, on stderr, and not under `--silent`; a + // program reads it in the envelope alone. + let line = format!("Warning: {detail}"); + for (args, json, times) in [ + (&["vendor"][..], false, 1), + (&["vendor", "--silent"], false, 0), + (&["vendor"], true, 0), + ] { + let tmp = checkout(Some(lock("foo"))); + let out = spawn(tmp.path(), args, json); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(stderr.matches(&line).count(), times, "{args:?}: {stderr}"); + } + // And reads it above the summary of the run and its next steps: both + // streams in one file, in the order they were written. + let tmp = checkout(Some(lock("foo"))); + let (mut cmd, _fixture) = command(tmp.path(), &["vendor"], false); + let log = std::fs::File::create(tmp.path().join("log")).unwrap(); + let status = cmd + .stdout(log.try_clone().unwrap()) + .stderr(log) + .status() + .unwrap(); + let said = std::fs::read_to_string(tmp.path().join("log")).unwrap(); + assert!(status.success(), "{said}"); + let at = [line.as_str(), "Vendored 2 packages.", "Next steps:"].map(|text| said.find(text)); + assert!(at[0].is_some() && at[0] < at[1] && at[1] < at[2], "{said}"); + // A run whose `--ecosystems` leaves Maven out vendors no Maven patch + // and says nothing of the hub, as without the workspace: here the one + // npm patch of the manifest, whose package is not installed. + let others = |lock: Option| { + let tmp = checkout(lock); + let manifest = tmp.path().join("proj/.socket/manifest.json"); + let mut patches: serde_json::Value = + serde_json::from_slice(&std::fs::read(&manifest).unwrap()).unwrap(); + patches["patches"]["pkg:npm/left-pad@1.3.0"] = patches["patches"][purl("foo")].clone(); + std::fs::write(&manifest, patches.to_string()).unwrap(); + // No server: the run downloads nothing. + let npm = ["vendor", "--ecosystems", "npm", "--offline"]; + let nowhere = ["--patch-server-url", "http://127.0.0.1:9"]; + let (_, env) = socket(tmp.path(), &[npm.as_slice(), &nowhere].concat()); + let about = env["events"].as_array().unwrap().iter(); + let about: Vec<_> = about.map(|event| event["purl"].clone()).collect(); + assert_eq!(about, ["pkg:npm/left-pad@1.3.0"], "{env}"); + env["warnings"].clone() + }; + assert_eq!(others(Some(lock("foo"))), others(None)); +} diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs new file mode 100644 index 000000000..b1d831d6a --- /dev/null +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -0,0 +1,1231 @@ +//! What a rules_jvm_external hub of a Bazel workspace builds. +//! +//! Under Bzlmod a hub is the tags of the ruleset's `maven` extension that +//! share a `name` (`maven` when none is given): `install`, and `artifact` +//! and `from_toml`, which add artifacts. A hub whose `install` gives a +//! `lock_file` is pinned: Bazel fetches each jar the lock names, at the +//! sha256 the lock holds, and reads no `pom.xml` and no Gradle file. A +//! lock with `m2local` takes a jar that none of its repositories lists +//! from the Maven local repository, at that sha256 too. So a patch that +//! socket-patch puts in a `pom.xml`, a Gradle build or a jar does not +//! reach what Bazel builds, and [`notices`] says so for each artifact a +//! hub builds. +//! +//! Everything is read from the checkout through [`super::workspace`]: the +//! root `MODULE.bazel` with the files it includes, the locks its hubs +//! name, the `WORKSPACE` file and what names the Bazel release. Nothing is +//! evaluated, no Bazel is run and nothing is written. What cannot be read +//! with certainty is said as such ([`UNREADABLE`]) and never guessed. +//! +//! Not seen: a hub or an override that another Bazel module declares, a +//! `maven_install` inside a function of a `.bzl` file, a jar that reaches +//! Bazel without a hub, and what a flag or an rc file tells Bazel. + +use std::collections::{HashMap, HashSet}; +use std::path::Path; + +use super::rc::declared_release; +use super::starlark::{Call, How, Value}; +use super::workspace::{disk, disk_up_to, Doubt, Entry, Extension, Repo, Tag, Workspace}; +use crate::formats::maven::is_variant; +use crate::utils::fs::run_blocking; +use crate::utils::purl::{parse_maven_purl, purl_qualifier}; + +/// The extension whose tags make a hub. +pub const EXTENSION: Extension<'static> = Extension { + module: "rules_jvm_external", + file: "//:extensions.bzl", + name: "maven", +}; + +/// The warning for an artifact that a pinned hub builds: no patch of a +/// socket-patch command reaches that build. +pub const HUB_UNPATCHED: &str = "maven_bazel_hub_unpatched"; +/// The warning for an artifact when the hubs of the workspace cannot be +/// read: a hub may build it. +pub const UNREADABLE: &str = "maven_bazel_unreadable"; + +/// The largest lock that is read. +const MAX_LOCK: usize = 16 << 20; + +/// The tags that make a hub of their `name` or add to it, `install` +/// first: the ruleset's `private/extensions/maven.bzl` has `artifact` at +/// 6.5, 6.9 and 7.2 and `from_toml` at 6.9 and 7.2. Its two other tags, +/// `override` and `amend_artifact`, make no hub. +const MAKE_A_HUB: [&str; 3] = ["install", "artifact", "from_toml"]; + +/// A hub of the root module. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Hub { + pub name: String, + /// Where its first `maven.install` is, or without one the first tag + /// that makes it: the file, from the Bazel root, and the line. + pub file: String, + pub line: usize, + /// The lock its tags name, from the Bazel root. `None`: the hub is not + /// pinned, and Bazel resolves what it builds when it builds. + pub lock: Option, +} + +const NOT_A_FILE: &str = "the `lock_file` of this hub is not a file of this repository"; + +/// The name of the hub that `call`, a `tag` of [`MAKE_A_HUB`], adds to, +/// and the lock it names for it, which only an `install` can, or why they +/// cannot be read. +fn install(ws: &Workspace, tag: &str, call: &Call) -> Result<(String, Option), String> { + if !call.whole || call.unpacks() { + return Err(format!("this `maven.{tag}` is not a plain call of its own")); + } + // What a repository name is made of: Bazel takes no other name, and + // a warning prints this one. + let named = |b: u8| b.is_ascii_alphanumeric() || b"_.-+".contains(&b); + let name = match call.arg("name") { + None => "maven", + Some(Value::Str(name)) if name.bytes().all(named) => name, + Some(_) => { + return Err("the `name` of this hub is not a repository name in a string".into()) + } + }; + let lock = match call.arg("lock_file") { + None => None, + Some(Value::Str(label)) => match ws.label(label) { + Some(file) if file.repo == Repo::Main => Some(file.path()), + _ => return Err(NOT_A_FILE.into()), + }, + Some(_) => return Err(NOT_A_FILE.into()), + }; + Ok((name.to_string(), lock)) +} + +/// The hubs of the workspace, and what makes the list uncertain: the +/// doubts of the reader, a tag that cannot be read, and `install` tags of +/// one hub that name different locks. The ruleset takes the lock of the +/// last root `install` (`private/extensions/maven.bzl` at 6.5 and 7.2), so +/// such a hub is left out instead of given one of them. And no hub at all +/// is given when an `install` cannot be read or the reader may have missed +/// one: that tag may be the last one of any hub. A hub that only the other +/// tags of [`MAKE_A_HUB`] make has no lock. +pub fn hubs(ws: &Workspace) -> (Vec, Vec) { + // What the reader doubts is about the extension: the same for each tag. + let tags = MAKE_A_HUB.map(|tag| ws.tags(&EXTENSION, tag)); + let mut doubts: Vec = ws.doubts.iter().chain(&tags[0].doubts).cloned().collect(); + let mut every_tag_read = doubts.is_empty(); + let (mut hubs, mut split): (Vec, Vec) = Default::default(); + let calls = MAKE_A_HUB.iter().zip(&tags); + let calls = calls.flat_map(|(class, tags)| tags.calls.iter().map(move |tag| (*class, tag))); + for (class, tag) in calls { + let (file, line, pins) = (tag.file.to_string(), tag.call.line, class == "install"); + let (name, lock) = match install(ws, class, tag.call) { + Ok(read) => read, + Err(why) => { + // Only an `install` names a lock: without one that was + // not read, the hubs that were read stay. + every_tag_read &= !pins; + doubts.push(Doubt { file, line, why }); + continue; + } + }; + let Some(hub) = hubs.iter().find(|hub| hub.name == name) else { + hubs.push(Hub { + name, + file, + line, + lock, + }); + continue; + }; + if pins && hub.lock != lock { + let (first, at) = (&hub.file, hub.line); + let why = format!("this tag and the one at {first}:{at} name different locks"); + doubts.push(Doubt { file, line, why }); + split.push(name); + } + } + hubs.retain(|hub| every_tag_read && !split.contains(&hub.name)); + (hubs, doubts) +} + +/// The jar of an artifact in a lock. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pinned { + pub version: String, + /// The sha256 the lock holds for it. `None`: the lock has none. + pub jar_sha256: Option, + /// The hub fetches it: the lock has its sha256 and does not skip it, + /// and a repository of the lock lists it or, under `m2local`, the hub + /// takes it from the Maven local repository. + pub fetched: bool, +} + +/// A hub's lock, `maven_install.json`, in format 2 (rules_jvm_external 6.5 +/// and 6.9 write it) or 3 (7.2 does). +#[derive(Debug)] +pub struct Lock { + pub format: u8, + /// The jar without a classifier of each `group:artifact`. + jars: HashMap, +} + +impl Lock { + /// Reads a lock. An empty file (the hub is not pinned yet), text that + /// is no JSON of this shape (a merge conflict), and any other format + /// are an error: the reason. + pub fn parse(text: &str) -> Result { + #[derive(serde::Deserialize)] + struct Artifact { + version: String, + #[serde(default)] + shasums: HashMap>, + } + #[derive(serde::Deserialize)] + struct Raw { + version: Option, + #[serde(default)] + artifacts: HashMap, + #[serde(default)] + repositories: HashMap>, + #[serde(default)] + skipped: HashSet, + #[serde(default)] + m2local: bool, + } + if text.trim().is_empty() { + return Err("it is empty: the hub is not pinned yet".to_string()); + } + let raw: Raw = serde_json::from_str(text).map_err(|e| format!("it is no lock ({e})"))?; + let format = match raw.version.as_deref() { + Some("2") => 2, + Some("3") => 3, + _ => return Err("it is not a lock of format 2 or 3".to_string()), + }; + let jar = |(key, mut artifact): (String, Artifact)| { + // A third part of the key is a packaging other than `jar`, and + // every other name among the sums is a classifier. + let sum = artifact.shasums.remove("jar")?; + let lists = |keys: &HashSet| keys.contains(&key); + let listed = raw.m2local || raw.repositories.values().any(lists); + let pinned = Pinned { + version: artifact.version, + fetched: sum.is_some() && listed && !raw.skipped.contains(&key), + jar_sha256: sum, + }; + (key.matches(':').count() == 1).then_some((key, pinned)) + }; + let jars = raw.artifacts.into_iter().filter_map(jar).collect(); + Ok(Lock { format, jars }) + } + + /// The jar of `group:artifact` without a classifier, when the lock + /// holds one. + pub fn plain_jar(&self, group: &str, artifact: &str) -> Option<&Pinned> { + self.jars.get(&format!("{group}:{artifact}")) + } +} + +/// The name a hub gives the target of an artifact: `escape` in the +/// ruleset's `private/coursier_utilities.bzl` at 6.5, 6.9 and 7.2. An +/// override replaces the artifact whose target has the name of its +/// `coordinates`. +fn target(coordinates: &str) -> String { + let first = coordinates.split(',').next().unwrap_or_default(); + let named = first.replace(['.', '-', ':', '/', '+', '$'], "_"); + named.replace(['[', ']'], "") +} + +/// Why a hub that fetches a jar may not build it. +const OVERRIDDEN: &str = "a `maven.override` gives this artifact another target"; + +/// Whether Bazel builds an artifact through a hub of the workspace. +#[derive(Debug, PartialEq, Eq)] +pub enum Built<'a> { + /// No hub does, and every hub was read. + No, + /// These pinned hubs fetch its jar at that version. + Yes(Vec<(&'a Hub, &'a Pinned)>), + /// It is not known. No hub that was read fetches its jar and this + /// could not be read, or one does and this `maven.override` may put + /// another target in the jar's place. + Unknown(&'a Doubt), +} + +/// What the hubs of a workspace build: read once, asked per artifact. +#[derive(Debug)] +pub struct Hubs { + pinned: Vec<(Hub, Lock)>, + /// The `override` tags of the root module: the [`target`] each + /// replaces (`None`: its `coordinates` are no string, so any), and + /// where it is. The tag's `name` is not asked for: the ruleset at 6.5 + /// takes an override for every hub. + overrides: Vec<(Option, Doubt)>, + /// The first thing that could not be read. + doubt: Option, +} + +impl Hubs { + /// Reads the hubs of the workspace behind `view` and the overrides, + /// and the lock of each hub through `locks`, a view of the same + /// workspace that may hand out a larger file. A hub without a lock, a + /// lock that cannot be read, and a `WORKSPACE` file that calls + /// `maven_install` or cannot be read while Bazel may read it (the + /// workspace names no release, or one before 9) are doubts. + pub fn read(view: &dyn Fn(&str) -> Entry, locks: &dyn Fn(&str) -> Entry) -> Hubs { + let ws = Workspace::read(view); + let (hubs, mut doubts) = hubs(&ws); + let overrides = ws.tags(&EXTENSION, "override").calls.into_iter(); + let overrides = overrides.map(|Tag { file, call, .. }| { + let (replaced, why) = match call.arg("coordinates") { + Some(Value::Str(artifact)) => (Some(target(artifact)), OVERRIDDEN), + _ => (None, "this `maven.override` cannot be read"), + }; + let (file, line, why) = (file.to_string(), call.line, why.to_string()); + (replaced, Doubt { file, line, why }) + }); + let overrides = overrides.collect(); + let mut pinned = Vec::new(); + for hub in hubs { + // Where a doubt about its lock is: the lock, or the tag. + let (file, line) = match &hub.lock { + Some(lock) => (lock.clone(), 0), + None => (hub.file.clone(), hub.line), + }; + let lock = match hub.lock.as_deref().map(locks) { + None => Err(format!("hub \"{}\" has no `lock_file`", hub.name)), + Some(Entry::Text(text)) => Lock::parse(&text), + Some(Entry::Absent) => Err("it does not exist".to_string()), + Some(Entry::Unreadable(why)) => Err(format!("it cannot be read: {why}")), + }; + match lock { + Ok(lock) => pinned.push((hub, lock)), + Err(why) => doubts.push(Doubt { file, line, why }), + } + } + let before_9 = || declared_release(view).is_none_or(|release| release < (9, 0, 0)); + doubts.extend(match ws.legacy.filter(|_| before_9()) { + Some(Ok((file, read))) => { + // By its own name, or by one that a `load` gives it. + let symbol = Value::Str("maven_install".to_string()); + let loads = read.calls.iter().filter(|call| call.callee == "load"); + let args = loads.flat_map(|load| &load.args); + let aliases = args.filter_map(|arg| match &arg.how { + How::Keyword(alias) if arg.value == symbol => Some(alias.as_str()), + _ => None, + }); + let names: Vec<_> = aliases.chain(["maven_install"]).collect(); + let installs = |call: &&Call| names.contains(&call.callee.as_str()); + read.calls.iter().find(installs).map(|call| Doubt { + file, + line: call.line, + why: "a `maven_install` of a WORKSPACE file is not read".to_string(), + }) + } + unread => unread.and_then(Result::err), + }); + Hubs { + pinned, + overrides, + doubt: doubts.into_iter().next(), + } + } + + /// Whether Bazel builds the jar of `group:artifact` at `version`. + pub fn built(&self, group: &str, artifact: &str, version: &str) -> Built<'_> { + let mut by = Vec::new(); + for (hub, lock) in &self.pinned { + let jar = lock.plain_jar(group, artifact); + let fetched = jar.filter(|jar| jar.fetched && jar.version == version); + by.extend(fetched.map(|jar| (hub, jar))); + } + // In the place of a jar that a hub fetches, an override puts the + // target it names: what that one builds is not read. + let named = Some(target(&format!("{group}:{artifact}"))); + let over = |(of, _): &&(Option, Doubt)| of.is_none() || *of == named; + match self.overrides.iter().find(over) { + _ if by.is_empty() => self.doubt.as_ref().map_or(Built::No, Built::Unknown), + Some((_, tag)) => Built::Unknown(tag), + None => Built::Yes(by), + } + } +} + +/// The warnings for the patches `purls` of a command that ran in +/// `project`: a code and a detail for each Maven jar that a hub of the +/// project's Bazel workspace builds ([`HUB_UNPATCHED`]) or may build +/// ([`UNREADABLE`]). Nothing for a project in no Bazel workspace, and +/// nothing is looked for without a Maven purl among them. +pub async fn notices(project: &Path, purls: Vec) -> Vec<(&'static str, String)> { + let project = project.to_path_buf(); + run_blocking(move || notices_blocking(&project, purls)).await +} + +fn notices_blocking(project: &Path, mut purls: Vec) -> Vec<(&'static str, String)> { + purls.sort(); + purls.dedup(); + // A classifier or another packaging is not the jar that a lock names + // by group and artifact alone. + let jar = |purl| { + let variant = is_variant( + purl_qualifier(purl, "type"), + purl_qualifier(purl, "classifier"), + ); + Some((purl, parse_maven_purl(purl).filter(|_| !variant)?)) + }; + let jars: Vec<_> = purls.iter().map(String::as_str).filter_map(jar).collect(); + let root = (!jars.is_empty()).then(|| super::bazel_root(project)); + let Some(root) = root.flatten() else { + return Vec::new(); + }; + let hubs = Hubs::read(&disk(&root.dir), &disk_up_to(&root.dir, MAX_LOCK)); + let mut said = Vec::new(); + for (purl, (group, artifact, version)) in jars { + let (code, detail) = match hubs.built(&group, &artifact, &version) { + Built::No => continue, + Built::Yes(by) => { + let from = |(hub, _): &(&Hub, &Pinned)| { + let (lock, name) = (hub.lock.as_deref().unwrap_or_default(), &hub.name); + let (file, line) = (&hub.file, hub.line); + format!("{lock} (hub \"{name}\", `maven.install` at {file}:{line})") + }; + let from = by.iter().map(from).collect::>().join(" and "); + let detail = format!( + "Bazel takes this artifact from {from}, which pins the upstream jar. \ + socket-patch does not patch a rules_jvm_external hub yet, so the Bazel \ + build stays unpatched whatever this command did for another build of the \ + checkout" + ); + (HUB_UNPATCHED, detail) + } + Built::Unknown(Doubt { file, line, why }) => { + let at = match line { + 0 => file.clone(), + line => format!("{file}:{line}"), + }; + let detail = format!( + "socket-patch could not tell whether Bazel takes this artifact from \ + a rules_jvm_external hub: {at}: {why}" + ); + (UNREADABLE, detail) + } + }; + said.push((code, format!("{purl}: {detail}"))); + } + said +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A pinned hub, as teams write one. + const PINNED: &str = r#"bazel_dep(name = "rules_jvm_external", version = "7.2") + +maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") +maven.install( + artifacts = ["io.netty:netty-tcnative-boringssl-static:2.0.61.Final"], + lock_file = "//:maven_install.json", +) +use_repo(maven, "maven") +"#; + + // The ruleset's own `maven_install.json` at its tags 6.9 and 7.2, cut + // down to two artifacts: format 2 as 6.9 wrote it, format 3 as 7.2 + // did. + const NETTY: &str = r#" + "artifacts": { + "io.netty:netty-tcnative-boringssl-static": { + "shasums": { + "jar": "b6f974972c44cd6f9cecabc255290286faac40b6393c66c3c3c0db7f421cc28e", + "linux-x86_64": "4ff9d14f1ec6ccee35b78f53a6f3d9c7c54535aa2a76138311c2f619c5e150e1", + "osx-aarch_64": "58e0302c9fde3db984c3ff7ee7ec7159dc0320bdb91533cc290e12e40911cd1a" + }, + "version": "2.0.61.Final" + }, + "io.netty:netty-tcnative-classes": { + "shasums": {"jar": "9b970eccd844bfae175a5cbbf7bf94891894add06d6ccbe1abf2250cd64080f6"}, + "version": "2.0.61.Final" + } + }, + "dependencies": { + "io.netty:netty-tcnative-boringssl-static": [ + "io.netty:netty-tcnative-boringssl-static:jar:linux-x86_64", + "io.netty:netty-tcnative-boringssl-static:jar:osx-aarch_64", + "io.netty:netty-tcnative-classes" + ] + }, + "repositories": { + "https://repo1.maven.org/maven2/": [ + "io.netty:netty-tcnative-boringssl-static", + "io.netty:netty-tcnative-boringssl-static:jar:linux-x86_64", + "io.netty:netty-tcnative-boringssl-static:jar:osx-aarch_64", + "io.netty:netty-tcnative-classes" + ] + }, +"#; + const NETTY_JAR: &str = "b6f974972c44cd6f9cecabc255290286faac40b6393c66c3c3c0db7f421cc28e"; + + fn lock_69() -> String { + let signed = + r#""__INPUT_ARTIFACTS_HASH": 1448912684, "__RESOLVED_ARTIFACTS_HASH": 771049556,"#; + format!("{{{signed}{NETTY}\"version\": \"2\"}}\n") + } + + fn lock_72() -> String { + let signed = r#""__INPUT_ARTIFACTS_HASH": {"repositories": -1949687017}, + "__RESOLVED_ARTIFACTS_HASH": {"io.netty:netty-tcnative-classes": 1239547355},"#; + format!("{{{signed}{NETTY}\"version\": \"3\"}}\n") + } + + /// From `regression_testing_maven_install.json` of the ruleset's tests + /// at 7.2: an artifact the lock skips, and a packaging other than jar. + const LOCK_SKIPS: &str = r#"{ + "artifacts": { + "org.codehaus.plexus:plexus": {"shasums": {"jar": null}, "version": "1.0.4"}, + "com.almworks.sqlite4java:libsqlite4java-osx:dylib": { + "shasums": {"jar": "b84122142173f33137c76d05dd6c80cc96f619ead3dc476c12d6ea46ef12dd05"}, + "version": "1.0.392" + }, + "com.almworks.sqlite4java:sqlite4java": { + "shasums": {"jar": "243a64470fda0e86a6fddeb0af4c7aa9426ce84e68cbfe18d75ee5da4b7e0b92"}, + "version": "1.0.392" + }, + "org.example:only-sources": {"shasums": {"sources": "00"}, "version": "1.0"}, + "org.example:unlisted": {"shasums": {"jar": "11"}, "version": "1.0"} + }, + "dependencies": {}, + "repositories": { + "https://repo1.maven.org/maven2/": [ + "com.almworks.sqlite4java:libsqlite4java-osx:dylib", + "com.almworks.sqlite4java:sqlite4java", + "org.codehaus.plexus:plexus", + "org.example:only-sources:jar:sources" + ], + "https://maven.google.com/": [] + }, + "skipped": ["org.codehaus.plexus:plexus"], + "version": "3" +} +"#; + + /// The view of the files `files`, held in memory. + fn view<'a>(files: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Entry + 'a { + move |path| match files.iter().find(|(name, _)| *name == path) { + Some((_, text)) => Entry::Text(text.to_string()), + None => Entry::Absent, + } + } + + /// Each hub as `name file:line lock`, and each doubt as + /// `file:line: why`. + fn listed(files: &[(&str, &str)]) -> (Vec, Vec) { + let (hubs, doubts) = hubs(&Workspace::read(&view(files))); + let hub = |hub: Hub| { + let lock = hub.lock.unwrap_or_else(|| "-".to_string()); + format!("{} {}:{} {lock}", hub.name, hub.file, hub.line) + }; + let doubt = |doubt: Doubt| format!("{}:{}: {}", doubt.file, doubt.line, doubt.why); + ( + hubs.into_iter().map(hub).collect(), + doubts.into_iter().map(doubt).collect(), + ) + } + + /// The hubs and the doubts of one `MODULE.bazel`. + fn module(text: &str) -> (Vec, Vec) { + listed(&[("MODULE.bazel", text)]) + } + + /// The hubs of the workspace with the files `files`. + fn read(files: &[(&str, &str)]) -> Hubs { + let view = view(files); + Hubs::read(&view, &view) + } + + /// What [`Hubs::built`] says of netty's jar at the version the locks + /// above hold, in a word, with the doubt of an `Unknown`. + fn built(files: &[(&str, &str)]) -> String { + let hubs = read(files); + let said = match hubs.built("io.netty", "netty-tcnative-classes", "2.0.61.Final") { + Built::No => "no".to_string(), + Built::Yes(by) => format!("yes, {}", by.len()), + Built::Unknown(doubt) => format!("{}:{}: {}", doubt.file, doubt.line, doubt.why), + }; + said + } + + #[test] + fn a_hub_is_a_tag_of_the_rulesets_maven_extension() { + assert_eq!( + module(PINNED), + ( + vec!["maven MODULE.bazel:4 maven_install.json".to_string()], + vec![] + ) + ); + // Under another name for the proxy and for the ruleset, in a file + // the root includes, and beside an extension called `maven` that + // another module defines. The `artifact` tag there gives no name, + // so it makes the hub `maven`, which has no lock. + let root = r#"bazel_dep(name = "rules_jvm_external", version = "6.9", repo_name = "rje") +bazel_dep(name = "rules_other", version = "1.0") +include("//third_party:jvm.MODULE.bazel") +other = use_extension("@rules_other//:extensions.bzl", "maven") +other.install(name = "not_a_hub", lock_file = "//:other.json") +"#; + let included = r#"jvm = use_extension("@rje//:extensions.bzl", "maven", dev_dependency = True) +jvm.install(name = "deps", lock_file = "@//third_party:deps_install.json") +jvm.artifact(group = "com.example", artifact = "a", version = "1") +"#; + let files = [ + ("MODULE.bazel", root), + ("third_party/jvm.MODULE.bazel", included), + ]; + let hubs = [ + "deps third_party/jvm.MODULE.bazel:2 third_party/deps_install.json", + "maven third_party/jvm.MODULE.bazel:3 -", + ]; + assert_eq!(listed(&files), (hubs.map(String::from).to_vec(), vec![])); + assert_eq!(module("module(name = 'no_java')\n"), (vec![], vec![])); + } + + #[test] + fn the_lock_of_a_hub_is_the_plain_label_its_tags_agree_on() { + let hub = |tags: &str| { + let proxy = "maven = use_extension('@rules_jvm_external//:extensions.bzl', 'maven')"; + module(&format!("{proxy}\n{tags}\n")) + }; + // The default name, with and without a lock; two tags of one hub + // that agree; two hubs. + for (tags, hubs) in [ + ("maven.install()", vec!["maven MODULE.bazel:2 -"]), + ( + "maven.install(lock_file = '//:a.json')\nmaven.install(lock_file = ':a.json')", + vec!["maven MODULE.bazel:2 a.json"], + ), + ( + "maven.install(lock_file = '//:a.json')\nmaven.install(name = 'b')", + vec!["maven MODULE.bazel:2 a.json", "b MODULE.bazel:3 -"], + ), + ] { + assert_eq!( + hub(tags), + (hubs.iter().map(|h| h.to_string()).collect(), vec![]), + "{tags}" + ); + } + // What cannot be read is a doubt, and gives no hub. + let plain = "MODULE.bazel:2: this `maven.install` is not a plain call of its own"; + let label = "MODULE.bazel:2: the `lock_file` of this hub is not a file of this repository"; + let name = "MODULE.bazel:2: the `name` of this hub is not a repository name in a string"; + for (tags, doubt) in [ + ("maven.install(lock_file = LOCK)", label), + ("maven.install(lock_file = '@other//:a.json')", label), + ("maven.install(lock_file = '//:a' + '.json')", label), + ("maven.install(name = NAME)", name), + // Nothing Bazel takes for a name, and a line of its own in a + // warning. + ("maven.install(name = 'a\\nb')", name), + ("maven.install(**ARGS)", plain), + ("PINNED and maven.install(lock_file = '//:a.json')", plain), + // A tag that cannot be read may be the last one of a hub that + // another tag made: its lock is not known either. + ( + "maven.install(name = NAME)\nmaven.install(lock_file = '//:a.json')", + name, + ), + ] { + assert_eq!(hub(tags), (vec![], vec![doubt.to_string()]), "{tags}"); + } + // Two tags of one hub with different locks: the ruleset takes the + // last one's, so neither is taken here. + let split = + "maven.install(lock_file = '//:a.json')\nmaven.install()\nmaven.install(name = 'b')"; + let doubt = "MODULE.bazel:3: this tag and the one at MODULE.bazel:2 name different locks"; + assert_eq!( + hub(split), + ( + vec!["b MODULE.bazel:4 -".to_string()], + vec![doubt.to_string()] + ) + ); + } + + /// `artifact` and `from_toml` tags make a hub or add to one as + /// `install` does (`_process_module_tags` in the ruleset's + /// `private/extensions/maven.bzl`: 7.2 lines 379 to 475, 6.9 lines 394 + /// to 499; at 6.5, which has no `from_toml`, lines 237 to 345). Only + /// an `install` names a lock (7.2 lines 609 to 649), and `override` + /// and `amend_artifact` make no hub. + #[test] + fn an_artifact_or_a_from_toml_tag_makes_a_hub_too() { + let hub = |tags: &str| { + let proxy = "maven = use_extension('@rules_jvm_external//:extensions.bzl', 'maven')"; + module(&format!("{proxy}\n{tags}\n")) + }; + let artifact = "maven.artifact(group = 'g', artifact = 'a', version = '1')"; + let toml = "maven.from_toml(name = 'libs', libs_versions_toml = '//:libs.versions.toml')"; + let pinned = "maven.install(lock_file = '//:a.json')"; + let none = "maven.amend_artifact(coordinates = 'g:a')\n\ + maven.override(coordinates = 'g:a', target = '//:a')"; + for (tags, hubs) in [ + (artifact.to_string(), vec!["maven MODULE.bazel:2 -"]), + (toml.to_string(), vec!["libs MODULE.bazel:2 -"]), + // A pinned hub stays what it is, at its `install`, wherever + // the tag that adds to it stands. + ( + format!("{pinned}\n{artifact}"), + vec!["maven MODULE.bazel:2 a.json"], + ), + ( + format!("{artifact}\n{pinned}"), + vec!["maven MODULE.bazel:3 a.json"], + ), + ( + format!("{pinned}\n{toml}"), + vec!["maven MODULE.bazel:2 a.json", "libs MODULE.bazel:3 -"], + ), + (none.to_string(), vec![]), + ] { + assert_eq!( + hub(&tags), + (hubs.iter().map(|h| h.to_string()).collect(), vec![]), + "{tags}" + ); + } + // One that cannot be read is a doubt. It names no lock, so the + // hubs that were read stay. + let name = "MODULE.bazel:3: the `name` of this hub is not a repository name in a string"; + let plain = "MODULE.bazel:3: this `maven.from_toml` is not a plain call of its own"; + for (tag, doubt) in [ + ( + "maven.artifact(name = NAME, group = 'g', artifact = 'a')", + name, + ), + ("maven.from_toml(**ARGS)", plain), + ] { + assert_eq!( + hub(&format!("{pinned}\n{tag}")), + ( + vec!["maven MODULE.bazel:2 a.json".to_string()], + vec![doubt.to_string()] + ), + "{tag}" + ); + } + // Such a hub has no lock, as an `install` without `lock_file` has + // none: Bazel resolves what it builds when it builds. + let add = |tag: &str| format!("{PINNED}maven.{tag}\n"); + let artifact = "group = \"io.netty\", artifact = \"netty-tcnative-classes\""; + let tools = add(&format!("artifact(name = \"tools\", {artifact})")); + let libs = add("from_toml(name = \"libs\", libs_versions_toml = \"//:libs.toml\")"); + let unnamed = add(&format!("artifact(name = NAME, {artifact})")); + let own = add(&format!("artifact({artifact}, version = \"2.0.61.Final\")")); + let (netty, other) = (lock_72(), LOCK_SKIPS); + let no_lock = |hub: &str| format!("MODULE.bazel:9: hub \"{hub}\" has no `lock_file`"); + for (module, lock, said) in [ + (&tools, other, no_lock("tools")), + (&libs, other, no_lock("libs")), + ( + &unnamed, + other, + name.replace("MODULE.bazel:3", "MODULE.bazel:9"), + ), + // A hub that holds the jar is an answer beside each of them, + // and so is the pinned hub that a tag adds an artifact to. + (&tools, &netty, "yes, 1".to_string()), + (&unnamed, &netty, "yes, 1".to_string()), + (&own, &netty, "yes, 1".to_string()), + (&own, other, "no".to_string()), + ] { + let files = [ + ("MODULE.bazel", module.as_str()), + ("maven_install.json", lock), + ]; + assert_eq!(built(&files), said, "{module}"); + } + } + + /// Under `m2local` a hub takes a jar that no repository of its lock + /// lists from the Maven local repository, at the sha256 of the lock: + /// `download_pinned_deps` in the ruleset's + /// `private/extensions/download_pinned_deps.bzl` (lines 23 to 28 at + /// 6.5, 24 to 29 at 6.9, 27 to 32 at 7.2) with `has_m2local` of + /// `v2_lock_file.bzl` (6.5 line 29, 6.9 line 31) and `v3_lock_file.bzl` + /// (7.2 line 37). + #[test] + fn under_m2local_a_jar_no_repository_lists_is_fetched() { + for (format, flag, fetched) in [ + ("2", "\"m2local\": true,", true), + ("3", "\"m2local\": true,", true), + ("3", "\"m2local\": false,", false), + ] { + let version = format!("{flag}\n \"version\": \"{format}\""); + let text = LOCK_SKIPS.replace("\"version\": \"3\"", &version); + let lock = Lock::parse(&text).unwrap(); + let unlisted = lock.plain_jar("org.example", "unlisted").unwrap(); + assert_eq!(unlisted.fetched, fetched, "{format} {flag}"); + // Not one the lock skips, which has no sum either. + let plexus = lock.plain_jar("org.codehaus.plexus", "plexus").unwrap(); + assert!(!plexus.fetched, "{format} {flag}"); + let hubs = read(&[("MODULE.bazel", PINNED), ("maven_install.json", &text)]); + let built = hubs.built("org.example", "unlisted", "1.0"); + assert_eq!(matches!(built, Built::Yes(_)), fetched, "{format} {flag}"); + } + // A flag that is no boolean is no lock. + let odd = LOCK_SKIPS.replace("\"version\"", "\"m2local\": \"yes\", \"version\""); + assert!(Lock::parse(&odd) + .unwrap_err() + .starts_with("it is no lock (")); + } + + #[test] + fn a_v2_and_a_v3_lock_give_the_version_and_the_jar_sum() { + for (lock, format) in [(lock_69(), 2), (lock_72(), 3)] { + let lock = Lock::parse(&lock).unwrap(); + // The jar without a classifier, beside two with one. + let jar = lock + .plain_jar("io.netty", "netty-tcnative-boringssl-static") + .unwrap(); + let pinned = Pinned { + version: "2.0.61.Final".to_string(), + jar_sha256: Some(NETTY_JAR.to_string()), + fetched: true, + }; + assert_eq!((lock.format, jar), (format, &pinned)); + assert_eq!(lock.plain_jar("io.netty", "netty"), None); + } + } + + #[test] + fn a_classifier_or_a_packaging_key_is_not_the_plain_jar() { + let lock = Lock::parse(LOCK_SKIPS).unwrap(); + assert!( + lock.plain_jar("com.almworks.sqlite4java", "sqlite4java") + .unwrap() + .fetched + ); + for (group, artifact) in [ + ("com.almworks.sqlite4java", "libsqlite4java-osx"), + ("com.almworks.sqlite4java", "libsqlite4java-osx:dylib"), + ("org.example", "only-sources"), + ] { + assert_eq!(lock.plain_jar(group, artifact), None, "{artifact}"); + } + } + + #[test] + fn a_skipped_or_unlisted_artifact_is_not_fetched() { + let lock = Lock::parse(LOCK_SKIPS).unwrap(); + let plexus = lock.plain_jar("org.codehaus.plexus", "plexus").unwrap(); + assert_eq!( + (plexus.version.as_str(), &plexus.jar_sha256, plexus.fetched), + ("1.0.4", &None, false) + ); + let unlisted = lock.plain_jar("org.example", "unlisted").unwrap(); + assert_eq!( + (unlisted.jar_sha256.as_deref(), unlisted.fetched), + (Some("11"), false) + ); + // Listed with a sum, and skipped all the same. + let skipped = LOCK_SKIPS.replace( + r#"["org.codehaus.plexus:plexus"]"#, + r#"["org.example:unlisted", "com.almworks.sqlite4java:sqlite4java"]"#, + ); + let lock = Lock::parse(&skipped).unwrap(); + assert!( + !lock + .plain_jar("com.almworks.sqlite4java", "sqlite4java") + .unwrap() + .fetched + ); + } + + #[test] + fn an_empty_v1_conflicted_or_broken_lock_is_not_read() { + let conflicted = lock_72().replace("\"artifacts\"", "<<<<<<< HEAD\n\"artifacts\""); + let other = "it is not a lock of format 2 or 3"; + for (text, why) in [ + ("", "it is empty: the hub is not pinned yet"), + (" \n", "it is empty: the hub is not pinned yet"), + (r#"{"dependency_tree": {"dependencies": []}}"#, other), + (r#"{"artifacts": {}, "version": "4"}"#, other), + (r#"{"artifacts": {}, "version": 3}"#, "it is no lock ("), + ( + r#"{"artifacts": {"a:b": {"shasums": {}}}, "version": "3"}"#, + "it is no lock (", + ), + (r#"{"artifacts": [], "version": "3"}"#, "it is no lock ("), + (&conflicted, "it is no lock ("), + ("[]", "it is no lock ("), + ] { + let said = Lock::parse(text).unwrap_err(); + assert!(said.starts_with(why), "{text:?}: {said}"); + } + } + + #[test] + fn built_is_yes_only_at_the_locked_version() { + let lock = lock_72(); + let hubs = read(&[("MODULE.bazel", PINNED), ("maven_install.json", &lock)]); + let built = |artifact, version| hubs.built("io.netty", artifact, version); + let Built::Yes(by) = built("netty-tcnative-classes", "2.0.61.Final") else { + panic!("not built"); + }; + let [(hub, jar)] = by[..] else { + panic!("{by:?}"); + }; + assert_eq!( + (hub.name.as_str(), hub.line, jar.version.as_str()), + ("maven", 4, "2.0.61.Final") + ); + for (artifact, version) in [ + ("netty-tcnative-classes", "2.0.62.Final"), + ("netty-tcnative-classes", "2.0.61.Final-socket.0a1b2c3d"), + ("netty-tcnative-classes", ""), + ("netty-tcnative", "2.0.61.Final"), + ] { + assert_eq!(built(artifact, version), Built::No, "{artifact} {version}"); + } + // Not what the lock holds without a jar to fetch. + let hubs = read(&[("MODULE.bazel", PINNED), ("maven_install.json", LOCK_SKIPS)]); + assert_eq!( + hubs.built("org.codehaus.plexus", "plexus", "1.0.4"), + Built::No + ); + assert_eq!(hubs.built("org.example", "unlisted", "1.0"), Built::No); + } + + #[test] + fn built_is_no_when_every_hub_is_pinned_and_none_holds_it() { + let second = + format!("{PINNED}maven.install(name = \"tools\", lock_file = \"//:tools.json\")\n"); + let (netty, other) = (lock_69(), LOCK_SKIPS); + for (files, said) in [ + (vec![], "no"), + (vec![("MODULE.bazel", "module(name = 'no_java')\n")], "no"), + ( + vec![("MODULE.bazel", PINNED), ("maven_install.json", other)], + "no", + ), + ( + vec![ + ("MODULE.bazel", &second), + ("maven_install.json", other), + ("tools.json", other), + ], + "no", + ), + ( + vec![ + ("MODULE.bazel", &second), + ("maven_install.json", other), + ("tools.json", &netty), + ], + "yes, 1", + ), + ( + vec![ + ("MODULE.bazel", &second), + ("maven_install.json", &netty), + ("tools.json", &netty), + ], + "yes, 2", + ), + ] { + assert_eq!( + built(&files), + said, + "{:?}", + files.iter().map(|f| f.0).collect::>() + ); + } + } + + #[test] + fn a_lockless_hub_or_a_doubt_is_unknown() { + let lockless = PINNED.replace(" lock_file = \"//:maven_install.json\",\n", ""); + let computed = PINNED.replace("\"//:maven_install.json\"", "LOCK"); + let beside = format!("{PINNED}maven.install(name = \"tools\")\n"); + let odd = format!("{PINNED}print(use_repo)\n"); + // A second tag of the hub that the ruleset takes the lock from, + // and one that may be of any hub. + let later = format!("{PINNED}LOCK = \"//:b.json\"\nmaven.install(lock_file = LOCK)\n"); + let unnamed = format!("{PINNED}maven.install(name = NAME, lock_file = \"//:b.json\")\n"); + let over = |tag: &str| format!("{PINNED}maven.override({tag}, target = \"//lib:netty\")\n"); + let overridden = over("coordinates = \"io.netty:netty-tcnative-classes\""); + // As the ruleset matches it: by the name of the artifact's target, + // for every hub at 6.5. + let by_target = over("name = \"tools\", coordinates = \"io_netty_netty-tcnative.classes\""); + let another = over("coordinates = \"io.netty:netty-tcnative-boringssl-static\""); + let unread = over("coordinates = NETTY"); + let (netty, other) = (lock_72(), LOCK_SKIPS); + let gives = "MODULE.bazel:9: a `maven.override` gives this artifact another target"; + for (module, lock, said) in [ + ( + lockless.as_str(), + None, + "MODULE.bazel:4: hub \"maven\" has no `lock_file`", + ), + ( + &computed, + None, + "MODULE.bazel:4: the `lock_file` of this hub is not a file of this repository", + ), + (PINNED, None, "maven_install.json:0: it does not exist"), + ( + PINNED, + Some(""), + "maven_install.json:0: it is empty: the hub is not pinned yet", + ), + ( + PINNED, + Some("{}"), + "maven_install.json:0: it is not a lock of format 2 or 3", + ), + ( + &beside, + Some(other), + "MODULE.bazel:9: hub \"tools\" has no `lock_file`", + ), + // A hub that holds the jar is an answer, whatever another hub + // leaves unread. + (&beside, Some(&netty), "yes, 1"), + // Not when the tags of the hub itself may be others than the + // ones read: the ruleset takes the lock of the last. + ( + &odd, + Some(&netty), + "MODULE.bazel:9: `use_repo` is used other than to call it", + ), + ( + &later, + Some(&netty), + "MODULE.bazel:10: the `lock_file` of this hub is not a file of this repository", + ), + ( + &unnamed, + Some(&netty), + "MODULE.bazel:9: the `name` of this hub is not a repository name in a string", + ), + // And not when an override puts another target in its place, + // which matters only for a jar that a hub fetches. + (&overridden, Some(&netty), gives), + (&by_target, Some(&netty), gives), + ( + &unread, + Some(&netty), + "MODULE.bazel:9: this `maven.override` cannot be read", + ), + (&another, Some(&netty), "yes, 1"), + (&overridden, Some(other), "no"), + (&unread, Some(other), "no"), + ] { + let mut files = vec![("MODULE.bazel", module)]; + files.extend(lock.map(|lock| ("maven_install.json", lock))); + assert_eq!(built(&files), said, "{module}"); + } + // The view's own reason for a lock it does not hand out: the one + // of the two views that the locks are read through. + let files = [("MODULE.bazel", PINNED)]; + let unreadable = |_: &str| Entry::Unreadable("it is larger than 16 MiB".to_string()); + let hubs = Hubs::read(&view(&files), &unreadable); + let Built::Unknown(doubt) = + hubs.built("io.netty", "netty-tcnative-classes", "2.0.61.Final") + else { + panic!("read"); + }; + assert_eq!( + (doubt.file.as_str(), doubt.why.as_str()), + ( + "maven_install.json", + "it cannot be read: it is larger than 16 MiB" + ) + ); + } + + #[test] + fn a_workspace_file_that_calls_maven_install_is_unknown_below_bazel_9() { + let direct = "load('@rules_jvm_external//:defs.bzl', 'maven_install')\n\nmaven_install(\n artifacts = [],\n)\n"; + let renamed = + "load('@rules_jvm_external//:defs.bzl', pin = 'maven_install')\npin(artifacts = [])\n"; + let none = + "workspace(name = 'w')\nmaven_install = 1\nhttp_archive(name = 'maven_install')\n"; + let why = "a `maven_install` of a WORKSPACE file is not read"; + for (name, text, line) in [ + ("WORKSPACE", direct, 3), + ("WORKSPACE.bazel", direct, 3), + ("WORKSPACE.bzlmod", renamed, 2), + ] { + let said = format!("{name}:{line}: {why}"); + for (release, expected) in [ + (None, said.as_str()), + (Some("7.7.2\n"), &said), + (Some("8.8.2\n"), &said), + (Some("latest\n"), &said), + (Some("9.0.0\n"), "no"), + (Some("9.3.2\n"), "no"), + ] { + let mut files = vec![(name, text)]; + files.extend(release.map(|release| (".bazelversion", release))); + assert_eq!(built(&files), expected, "{name} {release:?}"); + // Beside a hub that holds the jar, the hub answers. + let lock = lock_72(); + files.extend([ + ("MODULE.bazel", PINNED), + ("maven_install.json", lock.as_str()), + ]); + assert_eq!(built(&files), "yes, 1", "{name} {release:?}"); + } + } + // A file without the call says nothing, and of the three Bazel + // reads the first that is there, alone. + let shadowed = [ + ("WORKSPACE.bzlmod", none), + ("WORKSPACE.bazel", direct), + ("WORKSPACE", direct), + ]; + assert_eq!(built(&shadowed[..1]), "no"); + assert_eq!(built(&shadowed), "no"); + assert_eq!(built(&shadowed[1..]), format!("WORKSPACE.bazel:3: {why}")); + // One that cannot be read may call it, unless Bazel 9 leaves it. + let open = [ + ("WORKSPACE", "maven_install(\n"), + (".bazelversion", "9.0.0\n"), + ]; + assert_eq!(built(&open[..1]), "WORKSPACE:1: a bracket is never closed"); + assert_eq!(built(&open), "no"); + } + + /// A project directory with the files `files`, in a checkout of its + /// own. + fn project(files: &[(&str, &str)]) -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join(".git")).unwrap(); + for (path, text) in files { + std::fs::write(dir.path().join(path), text).unwrap(); + } + dir + } + + const NETTY_PURL: &str = "pkg:maven/io.netty/netty-tcnative-classes@2.0.61.Final"; + + #[test] + fn a_notice_names_the_lock_and_the_hub_or_what_was_not_read() { + // A lock larger than the 1 MiB of a Starlark file. + let lock = lock_72() + &" ".repeat(1 << 20); + let dir = project(&[("MODULE.bazel", PINNED), ("maven_install.json", &lock)]); + let purls = |purls: &[&str]| purls.iter().map(|purl| purl.to_string()).collect(); + // Once per jar, whatever else the command patched, and not for a + // version, a classifier or a packaging the lock does not hold. + let asked = purls(&[ + NETTY_PURL, + "pkg:npm/left-pad@1.3.0", + "pkg:maven/io.netty/netty-tcnative-classes@2.0.62.Final", + "pkg:maven/io.netty/netty-tcnative-classes@2.0.61.Final?classifier=sources", + "pkg:maven/io.netty/netty-tcnative-classes@2.0.61.Final?type=aar", + NETTY_PURL, + ]); + let said = notices_blocking(dir.path(), asked); + let detail = format!( + "{NETTY_PURL}: Bazel takes this artifact from maven_install.json (hub \"maven\", \ + `maven.install` at MODULE.bazel:4), which pins the upstream jar. socket-patch does \ + not patch a rules_jvm_external hub yet, so the Bazel build stays unpatched whatever \ + this command did for another build of the checkout" + ); + assert_eq!(said, [(HUB_UNPATCHED, detail.clone())]); + // The same for a project below the Bazel root of its checkout. + let below = dir.path().join("services/billing"); + std::fs::create_dir_all(&below).unwrap(); + let said = notices_blocking(&below, purls(&[NETTY_PURL])); + assert_eq!(said, [(HUB_UNPATCHED, detail)]); + // What cannot be read is said for every Maven jar of the run. + std::fs::write(dir.path().join("maven_install.json"), "").unwrap(); + let said = notices_blocking(dir.path(), purls(&[NETTY_PURL, "pkg:maven/a.b/c@1"])); + let why = "could not tell whether Bazel takes this artifact from a \ + rules_jvm_external hub: maven_install.json: it is empty: the hub is not \ + pinned yet"; + let expected = ["pkg:maven/a.b/c@1", NETTY_PURL] + .map(|purl| (UNREADABLE, format!("{purl}: socket-patch {why}"))); + assert_eq!(said, expected); + // And a lock over the bound is not read. + let large = lock + &" ".repeat(MAX_LOCK); + std::fs::write(dir.path().join("maven_install.json"), large).unwrap(); + let said = notices_blocking(dir.path(), purls(&[NETTY_PURL])); + let why = "hub: maven_install.json: it cannot be read: it is larger than 16 MiB"; + assert!(said[0].1.ends_with(why), "{said:?}"); + std::fs::remove_file(dir.path().join("maven_install.json")).unwrap(); + let lockless = PINNED.replace(" lock_file = \"//:maven_install.json\",\n", ""); + std::fs::write(dir.path().join("MODULE.bazel"), lockless).unwrap(); + let said = notices_blocking(dir.path(), purls(&[NETTY_PURL])); + assert!( + said[0] + .1 + .ends_with("hub: MODULE.bazel:4: hub \"maven\" has no `lock_file`"), + "{said:?}" + ); + // A directory that has the name of a `WORKSPACE` file is none, as + // for Bazel, and a file that cannot be read is said with its reason. + let odd = project(&[("MODULE.bazel", "module(name = 'no_java')\n")]); + std::fs::create_dir(odd.path().join("WORKSPACE")).unwrap(); + assert_eq!(notices_blocking(odd.path(), purls(&[NETTY_PURL])), []); + std::fs::write(odd.path().join("WORKSPACE.bazel"), "maven_install(\n").unwrap(); + let said = notices_blocking(odd.path(), purls(&[NETTY_PURL])); + assert!( + said[0] + .1 + .ends_with("hub: WORKSPACE.bazel:1: a bracket is never closed"), + "{said:?}" + ); + } + + /// The files of the workspace keep the reader's bound of 1 MiB, + /// whatever a lock may hold: one over it is not read, with the + /// reader's own reason, and names no release either. + #[test] + fn a_file_of_the_workspace_over_1_mib_is_not_read() { + let (lock, filler) = (lock_72(), "#".repeat(1 << 20)); + let large = format!("{PINNED}{filler}\n"); + let dir = project(&[("MODULE.bazel", &large), ("maven_install.json", &lock)]); + let said = notices_blocking(dir.path(), vec![NETTY_PURL.to_string()]); + let why = "hub: MODULE.bazel: it cannot be read: it is larger than 1 MiB"; + assert_eq!(said.len(), 1, "{said:?}"); + assert!( + said[0].0 == UNREADABLE && said[0].1.ends_with(why), + "{said:?}" + ); + // `.bazelversion` begins with a release that reads no `WORKSPACE` + // file, and is not read to say so. + let release = format!("9.3.2\n{filler}"); + let legacy = project(&[ + ("WORKSPACE", "maven_install(artifacts = [])\n"), + (".bazelversion", &release), + ]); + let said = notices_blocking(legacy.path(), vec![NETTY_PURL.to_string()]); + let why = "hub: WORKSPACE:1: a `maven_install` of a WORKSPACE file is not read"; + assert!(said.len() == 1 && said[0].1.ends_with(why), "{said:?}"); + } + + #[test] + fn outside_a_bazel_workspace_or_without_a_maven_patch_nothing_is_said() { + let lock = lock_72(); + let maven = vec![NETTY_PURL.to_string()]; + // A Maven project with a lock of that name and no workspace file, + // and one below a workspace that its checkout does not reach. + let plain = project(&[("pom.xml", ""), ("maven_install.json", &lock)]); + assert_eq!(notices_blocking(plain.path(), maven.clone()), []); + let outer = project(&[("MODULE.bazel", PINNED), ("maven_install.json", &lock)]); + let inner = outer.path().join("inner"); + std::fs::create_dir_all(inner.join(".git")).unwrap(); + assert_eq!(notices_blocking(&inner, maven.clone()), []); + // In the workspace: a hub that cannot be read says nothing for a + // run without a Maven jar. + let broken = project(&[("MODULE.bazel", PINNED)]); + assert_eq!(notices_blocking(broken.path(), maven).len(), 1); + let others = [ + "pkg:npm/a@1", + "pkg:maven/a/b@1?classifier=tests", + "pkg:maven/broken", + ]; + let others = others.map(String::from).to_vec(); + assert_eq!(notices_blocking(broken.path(), others), []); + assert_eq!(notices_blocking(broken.path(), Vec::new()), []); + } +} diff --git a/crates/socket-patch-core/src/bazel/mod.rs b/crates/socket-patch-core/src/bazel/mod.rs index 704f70ac9..e6f8e1913 100644 --- a/crates/socket-patch-core/src/bazel/mod.rs +++ b/crates/socket-patch-core/src/bazel/mod.rs @@ -9,6 +9,8 @@ pub const WORKSPACE_FILES: [&str; 4] = ["MODULE.bazel", "REPO.bazel", "WORKSPACE", "WORKSPACE.bazel"]; pub mod ignore; +pub mod maven; +pub mod rc; pub mod starlark; pub mod workspace; diff --git a/crates/socket-patch-core/src/bazel/rc.rs b/crates/socket-patch-core/src/bazel/rc.rs new file mode 100644 index 000000000..8c618b6ff --- /dev/null +++ b/crates/socket-patch-core/src/bazel/rc.rs @@ -0,0 +1,186 @@ +//! What the files beside a Bazel workspace say about the Bazel that builds +//! it. + +use super::workspace::Entry; + +/// A Bazel release as three numbers: `9.3.2` is `(9, 3, 2)`. +pub type Release = (u32, u32, u32); + +/// The release the files at the Bazel root name for a launcher, read as +/// bazelisk reads them (v1.30.0: `parseFileConfig` in config/config.go, +/// `GetBazelVersion` in core/core.go): the value of the last +/// `USE_BAZEL_VERSION` line of `.bazeliskrc`, without the blanks around +/// the key and the value, and when there is none or it is empty the first +/// line of `.bazelversion`, as it is written. +/// +/// `None` unless that is exactly three numbers (`releasePattern` in +/// versions/versions.go): `latest`, `8.x`, a release candidate, a commit +/// and a fork's `name/7.7.2` name no release that the checkout can tell, +/// and neither does a file that cannot be read. So `None` is no promise +/// of an old Bazel or a new one. +/// +/// Not read: `USE_BAZEL_VERSION` in the environment and in the +/// `.bazeliskrc` of the home directory, which bazelisk asks before +/// `.bazelversion`. socket-patch does not run in the environment that a +/// build's bazelisk has. And a Bazel that is started without a launcher +/// reads neither file. +pub fn declared_release(view: &dyn Fn(&str) -> Entry) -> Option { + let setting = |line: &str| { + let (key, value) = line.split_once('=')?; + (key.trim() == "USE_BAZEL_VERSION").then(|| value.trim().to_string()) + }; + let set = match view(".bazeliskrc") { + Entry::Text(rc) => rc.split('\n').filter_map(setting).next_back(), + Entry::Absent => None, + Entry::Unreadable(_) => return None, + }; + let named = match set.filter(|value| !value.is_empty()) { + Some(value) => value, + None => match view(".bazelversion") { + // The line as Go's `bufio.Scanner` gives it. + Entry::Text(text) => { + let line = text.split('\n').next()?; + line.strip_suffix('\r').unwrap_or(line).to_string() + } + _ => return None, + }, + }; + let number = |part: &str| -> Option { + let digits = !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()); + part.parse().ok().filter(|_| digits) + }; + let numbers: Option> = named.split('.').map(number).collect(); + match numbers?[..] { + [major, minor, patch] => Some((major, minor, patch)), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The release of a workspace with the files `files`. + fn release(files: &[(&str, &str)]) -> Option { + declared_release(&|path| match files.iter().find(|(name, _)| *name == path) { + Some((_, text)) => Entry::Text(text.to_string()), + None => Entry::Absent, + }) + } + + /// The rows whose text does not give its release, with what `files` + /// puts around it: every wrong row in one message. + fn wrong<'a>( + rows: &[(&'a str, Option)], + files: impl Fn(&'a str) -> Vec<(&'a str, &'a str)>, + ) -> Vec<&'a str> { + let differs = |row: &&(&'a str, Option)| release(&files(row.0)) != row.1; + rows.iter().filter(differs).map(|row| row.0).collect() + } + + /// `.bazelversion`, as `GetBazelVersion` reads it (bazelisk v1.30.0, + /// core/core.go): the first line of a `bufio.Scanner` (lines 424 to + /// 426), which ends at the line feed and drops one carriage return + /// before it, taken as it is, and passed over when it is empty (line + /// 431). The forms are those of versions/versions.go. + #[test] + fn a_release_is_three_numbers_or_nothing() { + let rows = [ + ("7.7.2\n", Some((7, 7, 2))), + ("9.3.2\r\nanything below the first line\n", Some((9, 3, 2))), + ("10.0.0", Some((10, 0, 0))), + ("9.3.2\r", Some((9, 3, 2))), + // No blank is taken off the line: bazelisk asks for a release + // of that name, and fails. + (" 9.3.2 \n", None), + ("9.3.2\t\n", None), + ("9.3.2\r\r\n", None), + // An empty first line names nothing, whatever stands below: + // the fallback, `latest`, is used (lines 436 to 443). + ("\n9.3.2\n", None), + ("", None), + // `releasePattern` alone is one release (versions.go line 20). + // A track (line 21), a patch (22), a candidate (23), a rolling + // release (25), `latest` (26), a commit (27), `last_rc`, + // `last_green` and `rolling` (72 to 83) are none. + ("8.x\n", None), + ("8.*\n", None), + ("7.7.2-patch1\n", None), + ("7.7.2rc1\n", None), + ("9.0.0-pre.20250101.1\n", None), + ("latest\n", None), + ("latest-1\n", None), + ("0123456789abcdef0123456789abcdef01234567\n", None), + ("last_rc\n", None), + ("last_green\n", None), + ("rolling\n", None), + // The release of a fork (`parseBazelForkAndVersion`, core.go + // lines 457 to 471) is not Bazel's. + ("a-fork/7.7.2\n", None), + ("7.7\n", None), + ("7.7.2.1\n", None), + ("+7.7.2\n", None), + ("7..2\n", None), + ("\u{feff}7.7.2\n", None), + ]; + assert_eq!( + wrong(&rows, |named| vec![(".bazelversion", named)]), + [""; 0] + ); + assert_eq!(release(&[]), None); + } + + /// `.bazeliskrc`, as `parseFileConfig` reads it (config/config.go lines + /// 62 to 73): split at each line feed, then at the first `=` of a + /// line; the blanks around the key and around the value are dropped; + /// a later line of a key replaces an earlier one; nothing is unquoted + /// and no comment ends a value. `USE_BAZEL_VERSION` there outranks + /// `.bazelversion` (core.go lines 406 to 409), unless it is empty + /// (`layered.Get`, config.go line 110). + #[test] + fn bazeliskrc_is_read_as_bazelisk_reads_it() { + let rows = [ + ("USE_BAZEL_VERSION=8.8.2\n", Some((8, 8, 2))), + ("# a launcher's settings\nBAZELISK_BASE_URL=https://mirror.example\nUSE_BAZEL_VERSION=8.8.2", Some((8, 8, 2))), + // Blanks around the key and the value, and a carriage return. + (" USE_BAZEL_VERSION = 8.8.2 \r\n", Some((8, 8, 2))), + ("\tUSE_BAZEL_VERSION\t=\t8.8.2\n", Some((8, 8, 2))), + // The last line of the key wins. + ("USE_BAZEL_VERSION=9.3.2\nUSE_BAZEL_VERSION=8.8.2\n", Some((8, 8, 2))), + ("USE_BAZEL_VERSION=8.8.2\nUSE_BAZEL_VERSION=latest\n", None), + // A value that is no release names none, and `.bazelversion` + // is not asked. + ("USE_BAZEL_VERSION=latest\n", None), + ("USE_BAZEL_VERSION=8.x\n", None), + ("USE_BAZEL_VERSION=\"8.8.2\"\n", None), + ("USE_BAZEL_VERSION=8.8.2 # pinned\n", None), + ("USE_BAZEL_VERSION=8.8.2=\n", None), + // An empty value, also as the last of two, leaves it to + // `.bazelversion`. + ("USE_BAZEL_VERSION=\n", Some((7, 7, 2))), + ("USE_BAZEL_VERSION=8.8.2\nUSE_BAZEL_VERSION= \n", Some((7, 7, 2))), + // Another key: a comment (line 63) and what looks like one, + // a line without `=`, a shell's `export`, another case. + ("#USE_BAZEL_VERSION=8.8.2\n", Some((7, 7, 2))), + (" # USE_BAZEL_VERSION=8.8.2\n", Some((7, 7, 2))), + ("USE_BAZEL_VERSION 8.8.2\n", Some((7, 7, 2))), + ("export USE_BAZEL_VERSION=8.8.2\n", Some((7, 7, 2))), + ("use_bazel_version=8.8.2\n", Some((7, 7, 2))), + ("BAZELISK_BASE_URL=https://mirror.example/USE_BAZEL_VERSION=8.8.2\n", Some((7, 7, 2))), + ("", Some((7, 7, 2))), + ]; + let beside = |rc| vec![(".bazeliskrc", rc), (".bazelversion", "7.7.2\n")]; + assert_eq!(wrong(&rows, beside), [""; 0]); + // Alone it is enough, and a file that cannot be read may name any + // release. + assert_eq!( + release(&[(".bazeliskrc", "USE_BAZEL_VERSION=9.3.2")]), + Some((9, 3, 2)) + ); + let unreadable = |path: &str| match path { + ".bazeliskrc" => Entry::Unreadable("it is not UTF-8".to_string()), + _ => Entry::Text("7.7.2\n".to_string()), + }; + assert_eq!(declared_release(&unreadable), None); + } +} diff --git a/crates/socket-patch-core/src/bazel/workspace.rs b/crates/socket-patch-core/src/bazel/workspace.rs index 0e1943fce..da0cecddc 100644 --- a/crates/socket-patch-core/src/bazel/workspace.rs +++ b/crates/socket-patch-core/src/bazel/workspace.rs @@ -80,6 +80,12 @@ pub enum Entry { /// other process changes meanwhile: one that swaps a directory for a link /// between the two steps of a read is not seen. pub fn disk(root: &Path) -> impl Fn(&str) -> Entry + '_ { + disk_up_to(root, MAX_BYTES) +} + +/// [`disk`] for files of up to `max` bytes: a lock that a tag names is +/// data, and can be larger than a file of Starlark. +pub fn disk_up_to(root: &Path, max: usize) -> impl Fn(&str) -> Entry + '_ { let top = std::fs::canonicalize(root); move |path| { let read = || -> std::io::Result { @@ -87,7 +93,7 @@ pub fn disk(root: &Path) -> impl Fn(&str) -> Entry + '_ { let plain = |part| matches!(part, Component::Normal(_)); if Path::new(path).components().all(plain) { if let Some(pending) = group_commit::read(&top.join(path)) { - return text(&pending?[..]); + return text(&pending?[..], max); } } let real = std::fs::canonicalize(top.join(path))?; @@ -99,7 +105,7 @@ pub fn disk(root: &Path) -> impl Fn(&str) -> Entry + '_ { if real.is_dir() { return Err(ErrorKind::InvalidInput.into()); } - text(open_regular_file_sync(&real)?.0) + text(open_regular_file_sync(&real)?.0, max) }; let unreadable = |why: &str| Entry::Unreadable(why.to_string()); match read() { @@ -116,14 +122,15 @@ pub fn disk(root: &Path) -> impl Fn(&str) -> Entry + '_ { } } -/// The text of `from`, read to its end. One byte more than [`MAX_BYTES`] -/// is asked for: a file that grew since its size was taken is refused, -/// not cut there and read as if it were whole. -fn text(from: impl Read) -> std::io::Result { +/// The text of `from`, read to its end. One byte more than `max` is +/// asked for: a file that grew since its size was taken is refused, not +/// cut there and read as if it were whole. +fn text(from: impl Read, max: usize) -> std::io::Result { let mut bytes = Vec::new(); - from.take(MAX_BYTES as u64 + 1).read_to_end(&mut bytes)?; - if bytes.len() > MAX_BYTES { - return Err(std::io::Error::other("it is larger than 1 MiB")); + from.take(max as u64 + 1).read_to_end(&mut bytes)?; + if bytes.len() > max { + let why = format!("it is larger than {} MiB", max >> 20); + return Err(std::io::Error::other(why)); } String::from_utf8(bytes).map_err(|e| std::io::Error::new(ErrorKind::InvalidData, e)) } @@ -2136,17 +2143,17 @@ use_repo(go_deps, "com_github_google_uuid", "org_golang_x_net") /// it would be read as if it ended there. #[test] fn a_file_that_grows_past_the_bound_is_not_cut_there() { - let read = |len: u64| text(std::io::repeat(b'#').take(len)); + let read = |len: u64| text(std::io::repeat(b'#').take(len), MAX_BYTES); assert_eq!(read(MAX_BYTES as u64).unwrap().len(), MAX_BYTES); for len in [MAX_BYTES as u64 + 1, u64::MAX] { let refused = read(len).unwrap_err(); assert_eq!(refused.to_string(), "it is larger than 1 MiB", "{len}"); } assert_eq!( - text(&b"caf\xe9"[..]).unwrap_err().kind(), + text(&b"caf\xe9"[..], MAX_BYTES).unwrap_err().kind(), ErrorKind::InvalidData ); - assert_eq!(text(&b"caf\xc3\xa9"[..]).unwrap(), "caf\u{e9}"); + assert_eq!(text(&b"caf\xc3\xa9"[..], MAX_BYTES).unwrap(), "caf\u{e9}"); } /// A command that has written `MODULE.bazel` in a group commit reads @@ -2216,6 +2223,8 @@ use_repo(go_deps, "com_github_google_uuid", "org_golang_x_net") write("tools/new.MODULE.bazel", "#".repeat(MAX_BYTES + 1)).await; let big = Entry::Unreadable("it is larger than 1 MiB".to_string()); assert_eq!(view("tools/new.MODULE.bazel"), big); + let lock = disk_up_to(root, 2 * MAX_BYTES); + assert!(matches!(lock("tools/new.MODULE.bazel"), Entry::Text(_))); atomic_write_bytes(&root.join("tools/new.MODULE.bazel"), b"# caf\xe9\n") .await .unwrap(); @@ -2301,6 +2310,13 @@ use_repo(go_deps, "com_github_google_uuid", "org_golang_x_net") ("WORKSPACE", "maven_install") ); assert_eq!((ws.files.len(), &ws.doubts), (3, &vec![])); + // The same view with the bound of a lock, which is larger. + let lock = disk_up_to(&root, 2 * MAX_BYTES); + assert!(matches!(lock("big.MODULE.bazel"), Entry::Text(_))); + std::fs::write(root.join("huge.json"), vec![b' '; 2 * MAX_BYTES + 1]).unwrap(); + let huge = Entry::Unreadable("it is larger than 2 MiB".to_string()); + assert_eq!(lock("huge.json"), huge); + assert_eq!(lock("../outside.MODULE.bazel"), out); // And a root that is not there at all. assert_eq!( disk(&tmp.path().join("gone"))("MODULE.bazel"), diff --git a/docs/ecosystems.md b/docs/ecosystems.md index cf7234209..f2bf5ded5 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1664,6 +1664,75 @@ the repository list, so it is left as a (`projectMatrix`, `crossProject`, a computed `Project(...)`). The note names the cause and its remedy. +## Bazel workspaces: Maven + +A rules_jvm_external hub (`maven.install` in `MODULE.bazel`) builds the jars that its own lock, +`maven_install.json`, names, each at the sha256 the lock holds. It reads no `pom.xml` and no +Gradle file. A lock with `m2local` takes a jar that none of its repositories lists from the +Maven local repository, at the lock's sha256 too. So a Maven patch does not reach what Bazel +builds, in hosted, vendored or agent mode, and socket-patch does not patch a hub yet. It says +when a hub builds an artifact it has a patch for. + +When the project is in a Bazel workspace (the rule is under +[Bazel workspaces: `.bazelignore`](#bazel-workspaces-bazelignore)), a `get`, `scan`, `vendor` or +`apply` that has a Maven patch reads the root `MODULE.bazel` and the files it includes for the +tags of the `maven` extension of `rules_jvm_external`, under whatever name the file gives the +ruleset and the extension. A hub is the `install`, `artifact` and `from_toml` tags of one +`name`, and `override` replaces an artifact of one. Then it reads the lock each hub names with +the `lock_file` of its `install` (format 2 or 3, up to 16 MiB; each other file up to 1 MiB). +Nothing is evaluated, no Bazel is run and nothing is written. A `--global` run reads none of +it: its target is not the project, and a `vendor` whose `--ecosystems` leaves Maven out reads +none either. + +- `maven_bazel_hub_unpatched`: a pinned hub fetches the jar of the artifact at the patch's + version. One warning per artifact names the lock, the hub, and the file and line of its + `maven.install`. The events, the exit code and every file the command writes are those of the + same run without the workspace: a `pom.xml` or a Gradle build of the checkout is patched as + before, and the Bazel build keeps the upstream jar. No other warning is removed or replaced + for it: a hosted run of a tree without a `pom.xml` gives `redirect_maven_no_pom` and, after + it, this one. +- `maven_bazel_unreadable`: whether a hub builds the jar could not be told, because something + could not be read with certainty. The warning names the file, the line and the reason. + - When no hub that was read holds the jar: a hub without `lock_file`, which is also a hub + that only `maven.artifact` or `maven.from_toml` tags make (Bazel resolves what it builds + when it builds); one of those two tags that cannot be read; `install` tags of one hub that + name different locks; a lock that is missing, empty (the hub is not pinned yet), not format + 2 or 3, larger than 16 MiB or no JSON (a merge conflict); and the `WORKSPACE` file Bazel + would take (`WORKSPACE.bzlmod`, else `WORKSPACE.bazel`, else `WORKSPACE`) when it calls + `maven_install` or cannot be read, unless the Bazel root names Bazel 9 or later, which + reads no such file. + - Whether or not a hub's lock holds the jar: a `maven.install` whose `name` or `lock_file` is + not a plain string or that is not a statement of its own, and a construct of `MODULE.bazel` + that cannot be read without running it. The ruleset takes a hub's lock from the last of its + `install` tags, and one that was not read may be the last of any hub, so no lock is named + beside one. + - When a hub's lock holds the jar: a `maven.override` of the artifact, which puts a target of + the checkout in the jar's place, and one whose `coordinates` cannot be read. +- Nothing is said when every hub was read and none holds the artifact as a jar without a + classifier at the patch's version, and nothing for a project outside a Bazel workspace. + +The Bazel release is the one that `.bazeliskrc` (`USE_BAZEL_VERSION`) or else `.bazelversion` +at the Bazel root names, read as bazelisk reads them: the last `USE_BAZEL_VERSION` line counts, +without the blanks around the name and the value, and an empty one leaves it to the first line +of `.bazelversion`, taken as it is written. Only one release of three numbers (`9.3.2`) names a +release: with `latest`, `9.x`, a release candidate, a fork's release, or a file that cannot be +read, the `WORKSPACE` file counts as one Bazel may read. + +Limits: + +- Not seen: a hub or a `maven.override` that another Bazel module declares, a `maven_install` + inside a function of a `.bzl` file, a jar that reaches Bazel without a hub (`http_jar`, a + checked-in jar, the target of a `maven.override`), what a flag or an rc file tells Bazel + (`--ignore_dev_dependency`, `--override_repository`), and a `USE_BAZEL_VERSION` of the + environment or of the `.bazeliskrc` in the home directory, which a bazelisk asks before + `.bazelversion`. +- A vendored or agent `get` that fails before it patches anything says what it said before: in + a tree that only Bazel builds those are `vendor_jvm_shape_unsupported` and + `package_not_installed`. So does a `vendor` that is refused before it vendors anything (a + ledger that cannot be read, or one that git ignores). +- `socket-patch vex` does not look at the hub yet: a patch that the `pom.xml` pin or a patched + jar attests is attested, although the Bazel build does not have it. + ## Cargo: shared registry cache Agent mode patches the crate in place wherever the crawler finds it. For a non-vendored diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 17633259a..183cb589a 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 1134 + "max": 1459 }, "lock-readers": { "paths": [