diff --git a/.github/workflows/bazel-maven.yml b/.github/workflows/bazel-maven.yml index 519dbb6bd..c4a320fac 100644 --- a/.github/workflows/bazel-maven.yml +++ b/.github/workflows/bazel-maven.yml @@ -1,15 +1,21 @@ 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. +# a hosted patch of an artifact in a workspace whose rules_jvm_external hub +# builds that artifact from a pinned lock, on each Bazel release below. The +# patch is one block in MODULE.bazel that puts a repository with the +# patched jar in the place of the hub's own (`override_repo`): the flows +# hold the block's text, the patched build and its sha256 check, the undo, +# a version bump of the patched artifact, and a hub the block cannot +# patch. 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: +# Each major 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. +# Bazel 7 has two legs: 7.7.2, and 7.4.0, the first release with +# `override_repo`, which is the oldest Bazel a Maven patch for a hub can +# be written for. # # 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 @@ -29,9 +35,12 @@ name: Bazel patch compatibility (Maven) # 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. +# the run. The patched jar comes from the same server too: the block names +# the Socket patch host, and a downloader config on Bazel's command line +# sends that host there and refuses every other URL of it. 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`. @@ -47,9 +56,10 @@ on: # rewriter's index of a pom, the model of what Maven selects with the # pom walk under it (the hosted lane pins only where Maven selects the # patch's version), the crawler that says where the Maven local - # repository is, lock discovery and the upstream restore of `rollback`, - # and what socket-patch reads only in a Bazel workspace (`bazel/`: the - # hubs of MODULE.bazel and their locks). Nothing another ecosystem's + # repository is, lock discovery and the upstream restore of `rollback` + # (for a pom and for the block of MODULE.bazel), and what socket-patch + # reads and writes only in a Bazel workspace (`bazel/`: the hubs of + # MODULE.bazel, their locks and the block). Nothing another ecosystem's # flow owns is here, so a change to one ecosystem starts that # ecosystem's legs only. # @@ -74,7 +84,9 @@ on: - 'crates/socket-patch-core/src/crawlers/maven_scope.rs' - 'crates/socket-patch-core/src/crawlers/maven_crawler.rs' - 'crates/socket-patch-core/src/vex/discover/maven.rs' + - 'crates/socket-patch-core/src/vex/discover/bazel_maven.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/maven.rs' + - 'crates/socket-patch-core/src/patch/redirect/upstream/bazel_maven.rs' - 'crates/socket-patch-core/src/bazel/**' push: branches: [main] @@ -98,7 +110,9 @@ on: - 'crates/socket-patch-core/src/crawlers/maven_scope.rs' - 'crates/socket-patch-core/src/crawlers/maven_crawler.rs' - 'crates/socket-patch-core/src/vex/discover/maven.rs' + - 'crates/socket-patch-core/src/vex/discover/bazel_maven.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/maven.rs' + - 'crates/socket-patch-core/src/patch/redirect/upstream/bazel_maven.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/patch/redirect/**' @@ -139,7 +153,8 @@ jobs: [ {"bazel": "9.3.2", "era": "e9"}, {"bazel": "8.8.2", "era": "e8"}, - {"bazel": "7.7.2", "era": "e7"} + {"bazel": "7.7.2", "era": "e7"}, + {"bazel": "7.4.0", "era": "e7"} ] macos: >- [ diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 489be8ef2..cdcae4bc9 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2559,8 +2559,14 @@ 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. | +| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace, vendored and agent mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch that this run vendored or applied, or tried to (`vendor`, `apply`, and `get` / `scan` in those modes; in agent mode only for a package it found installed; never under `--global`), and the block that hosted mode keeps in `MODULE.bazel` holds no entry for that jar. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build: these modes patch no hub. One warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub. The events, the exit code and every written file are those of the same run without the workspace. A `vendor` whose `--ecosystems` leaves Maven out gives none. A vendored run that takes a hosted pin over (`vendor`, `scan` / `get --mode vendored`, `vendor --revert`) leaves the block's entry for it as it is. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_unreadable` | vendored / agent: run-level `warnings[]` (human: `Warning: …`); scan/get `--mode hosted`: `warnings[]` (warning) | Maven in a Bazel workspace (additive): whether a rules_jvm_external hub builds the jar of a Maven patch could not be told, because something could not be read with certainty: a hub without `lock_file` in vendored and agent mode (hosted mode gives `maven_bazel_not_pinned`), a `maven.artifact` or `maven.from_toml` tag that cannot be read, a lock that is missing, empty, not format 2 or 3, larger than 16 MiB or no JSON, a `WORKSPACE` file that calls `maven_install` or cannot be read while `.bazeliskrc` or `.bazelversion` at the Bazel root names no release of Bazel 9 or later, a `maven.install` whose `name` or `lock_file` is not a plain string, a construct of `MODULE.bazel` the reader does not follow, and, in vendored and agent mode, a `maven.override` of the artifact (hosted mode gives `maven_bazel_no_effect`). Hosted mode also gives it for a hub on an isolated `use_extension`, an rc file that cannot be read (also one that an import takes from outside the workspace by a relative path, and one with a line whose reading Bazel's own source calls an oversight: a quote that is never closed, a `\` with nothing after it), a `MODULE.bazel` that is a symbolic link, and a block of `MODULE.bazel` that was changed by hand (also in its first line alone), and then writes no entry for the hub. One warning per purl; the detail names the file, the line and the reason. | +| `maven_bazel_not_at_root` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_jvm_external hub builds the jar of a Maven patch, and the project is below the root of its Bazel workspace, in whose `MODULE.bazel` the patch of a hub is written. Like the five codes below and `maven_bazel_unreadable` in hosted mode, it means that the run wrote no entry for the jar in the block of the root `MODULE.bazel`, because it could not show from the checkout that the entry works. One warning per purl, in the place of `redirect_maven_no_pom` for that purl; the detail says why and ends with what the block of the root holds for the jar, which is read for a project below the root too (the detail then names the file as "the MODULE.bazel at the root"). Nothing: "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps the upstream jar". The event is the one of the same run without the hub: `skipped` / `redirect_unconfirmed` in a tree only Bazel builds, `applied` beside a `pom.xml` or Gradle pin that landed. The entry of the patch, from an earlier run: that entry stays, the event is `applied`, and the detail ends "socket-patch left the entry that MODULE.bazel holds for it as it is". The entry of another patch of the same jar: it stays too, the event is the one without the hub, and the detail ends "socket-patch wrote nothing to MODULE.bazel for it: the entry of patch remains there, and where the block is in effect the Bazel build takes that patch's jar". Exit code unchanged. With none of these codes the run writes the block: `redirect.rewrittenFiles` holds `MODULE.bazel`, the event is `applied`, and `rollback` / `remove` take the entry out. See docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_not_pinned` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: a hub of the workspace has no `lock_file` (also one that only `maven.artifact` or `maven.from_toml` tags make), so Bazel resolves its jars when it builds and none can be replaced. Also given beside a pinned hub that holds the artifact. The detail names the hub's file and line and how to pin it. | +| `maven_bazel_release` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: the Bazel release is not known to be 7.4.0 or later, the first with `override_repo` (`.bazeliskrc` or `.bazelversion` names an older one, or neither names a release of three numbers and `MODULE.bazel.lock` is missing or of a format before the one Bazel 7.5.0 writes), or the rules_jvm_external release Bazel selected is not known to be one of 6.4 to 7.2 (`MODULE.bazel.lock` holds the `source.json` of no release of it or of more than one, of a release outside that range, of an older one than the `bazel_dep` of `MODULE.bazel` asks for, or of another one than a `single_version_override` there pins; or an `archive_override`, `git_override`, `local_path_override` or `multiple_version_override` of the ruleset, or a `single_version_override` whose version is no plain string, leaves the release unknown). Versions are compared as Bazel compares them. The detail names the remedy (a `.bazelversion`, one build so that Bazel writes its lock, or an update of socket-patch) or the line of the override. | +| `maven_bazel_artifact` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: the repository through which the hub fetches this jar has no known name (a character other than letters, digits, `.`, `_` and `-` in its group, artifact or version), the lock lists no repository for the jar (`m2local`), or the patch comes without the version it is served under or without a sha256. | +| `maven_bazel_no_effect` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: the build would pass on the upstream jar with the block in place. The root has a `maven.override` for the artifact, or an rc file of the checkout (`.bazelrc` and what it imports with `import`, `try-import` and `try-import-if-bazel-version`, by a path under `%workspace%/` or a relative one; each read as Bazel reads an rc file: lines joined at a `\` before a line break, comments from a `#`, words without their quotes and escapes) names `--ignore_dev_dependency` without switching it off, or names `enable_bzlmod` other than switched on (Bazel reads `false`, `0`, `no`, `f`, `n` in any case and a `no` before the name as off) while the checkout names no Bazel 9 or later. The detail names the file and the line. | +| `maven_bazel_download` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: an rc file of the checkout names a downloader config, `--repository_disable_download` or `--vendor_dir`, under which Bazel may not be able to download the patched jar from the Socket patch host. The detail names the file, the line and the option. | | `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/mod.rs b/crates/socket-patch-cli/src/commands/mod.rs index 7269343db..07d188caf 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -113,12 +113,14 @@ pub(crate) async fn sync_bazelignore( /// 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 +/// holds (`socket_patch_core::bazel::maven`). A command that vendors 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. +/// them that a hub builds, or may build, from its lock. Nothing for a +/// `--global` run, whose target is not the project, for a jar that hosted +/// mode has patched for the hub, and no file is looked for when no purl is +/// a Maven one. A hosted run does not come here: its hub lane patches such +/// a jar, or says why not, among the warnings of its rewriters. /// /// With `tell`, a human run is told here, as [`sync_bazelignore`] tells /// it. A command that prints the warnings of its run itself passes diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 59b344e08..adfa62b62 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -2213,12 +2213,6 @@ 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 72017356b..30c13064b 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -1713,9 +1713,26 @@ pub(crate) async fn gem_takeover_refusals_for<'a>( refusals } -/// The hosted pins whose ecosystem `--ecosystems` selects. +/// The hosted pins a vendored run takes over, of `pins`. Vendored mode +/// patches no rules_jvm_external hub of a Bazel workspace, so the entry +/// that hosted mode keeps for a pin in the block of the root +/// `MODULE.bazel` is none of its wiring: the entry stays as it is, and the +/// Bazel build keeps the patched jar. A pin that only such an entry wires +/// is no takeover at all. `rollback` and `remove` take the entry out. +fn takeover_pins(pins: Vec) -> Vec { + let beside_the_hub = |mut pin: HostedPin| { + pin.files + .retain(|file| file != socket_patch_core::bazel::maven::FILE); + (!pin.files.is_empty()).then_some(pin) + }; + pins.into_iter().filter_map(beside_the_hub).collect() +} + +/// The hosted pins of an eject: those a vendored run takes over +/// ([`takeover_pins`]) whose ecosystem `--ecosystems` selects. fn hosted_pins_in_scope(common: &GlobalArgs, pins: Vec) -> Vec { - pins.into_iter() + takeover_pins(pins) + .into_iter() .filter(|pin| { socket_patch_core::utils::purl::purl_parts(&pin.purl) .is_some_and(|(eco, _, _)| ecosystem_in_scope(common, &eco)) @@ -3461,7 +3478,9 @@ pub(crate) async fn vendor_records_reusing( let hosted_pins = if eject.is_some() { Vec::new() } else { - HostedPin::all(&crate::commands::discover_wiring(common, &common.cwd).await) + takeover_pins(HostedPin::all( + &crate::commands::discover_wiring(common, &common.cwd).await, + )) }; let hosted_pin_of = |purl: &str| { hosted_pins @@ -4982,11 +5001,12 @@ async fn run_revert(args: &VendorArgs, env: &mut Envelope) -> i32 { .filter(|e| e.action == PatchAction::Removed) .filter_map(|e| e.purl.as_deref().map(PurlKey::new)) .collect(); - let rehosted: Vec = - HostedPin::all(&crate::commands::discover_wiring(common, &common.cwd).await) - .into_iter() - .filter(|pin| reverted.contains(&PurlKey::new(&pin.purl))) - .collect(); + let rehosted: Vec = takeover_pins(HostedPin::all( + &crate::commands::discover_wiring(common, &common.cwd).await, + )) + .into_iter() + .filter(|pin| reverted.contains(&PurlKey::new(&pin.purl))) + .collect(); if !rehosted.is_empty() { let leg = crate::commands::hosted_unwind::run_hosted_leg( common, @@ -7464,6 +7484,33 @@ mod gc_tests { mod scope_and_hint_tests { use super::*; + /// A vendored run takes over what wires a hosted pin in a build it + /// can vendor into, and never the entry of a Bazel hub: that file is + /// no file of the pin it restores, and a pin of that entry alone is + /// none of its pins. + #[test] + fn a_takeover_leaves_the_entry_of_a_bazel_hub() { + let pin = |purl: &str, files: &[&str]| HostedPin { + purl: purl.to_string(), + uuid: "1d3c1fd2-7b4e-4c1a-9f0e-2a3b4c5d6e7f".to_string(), + files: files.iter().map(|file| file.to_string()).collect(), + }; + let maven = "pkg:maven/org.example/foo@1.0"; + let pom = [".mvn/maven.config", "MODULE.bazel", "pom.xml"]; + let pins = vec![ + pin(maven, &pom), + pin("pkg:maven/org.example/bar@1.0", &["MODULE.bazel"]), + pin("pkg:npm/left-pad@1.3.0", &["package-lock.json"]), + ]; + let taken = vec![ + pin(maven, &[".mvn/maven.config", "pom.xml"]), + pins[2].clone(), + ]; + assert_eq!(takeover_pins(pins.clone()), taken); + let common = GlobalArgs::default(); + assert_eq!(hosted_pins_in_scope(&common, pins), taken); + } + /// [`flavor_install_command`] drives the human reinstall hints: every /// npm-family flavor must name its own package manager's install, and /// flavors with no consuming install step stay silent. diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs index 8ea716450..c2d13aa7c 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs @@ -4,28 +4,46 @@ //! @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): +//! holds, through a repository of its own, and reads no `pom.xml` and no +//! Gradle file. Hosted mode patches it with one block at the end of the +//! root `MODULE.bazel`: a repository that downloads the patched jar at +//! its sha256, and Bazel's `override_repo` of the hub's one. These flows +//! hold that on the Bazel the run is given ([`FIXTURE`] says which ruleset +//! goes with its release): //! +//! - [`a_tree_only_bazel_builds`]: a checkout without a `pom.xml`. +//! `socket-patch get --mode hosted --yes` reports the patch +//! `applied` and rewrites `MODULE.bazel` alone, which is then the file of +//! before with the block of [`block`] after one blank line. The same +//! build prints the marker of the patched jar, which Bazel fetched from +//! the patch host; a `--lockfile_mode=error` build passes; the +//! ruleset's relock leaves the lock as it is; `bazel mod tidy` leaves +//! the file as it is; `rollback --yes` puts every file back +//! byte for byte, and the upstream build with them. A second machine +//! gets a patch whose host serves other bytes than the patch pins: its +//! build fails on the sha256 and never goes to the upstream jar. On a +//! Bazel before 7.5.0 the checkout first has no `.bazelversion`: the +//! command then writes nothing and says so (`maven_bazel_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. +//! too. The one command pins both builds: the three files of a Maven pin +//! and `MODULE.bazel`. The Bazel build is patched, and `rollback --yes` +//! restores every file. +//! - [`a_version_bump_of_the_patched_artifact`]: after the command the +//! checkout asks for the artifact one version up and pins again, which +//! passes. The build then stops at the line of the entry's +//! `override_repo(`, where the block says what to run. `socket-patch +//! rollback --yes` takes the entry out, and the build takes the +//! new upstream jar. +//! - [`the_users_own_override_of_the_artifact`]: the hub has a +//! `maven.override` that puts a target of the checkout in the artifact's +//! place. The command writes nothing and names the override's line +//! (`maven_bazel_no_effect`), and the build prints that target's marker +//! before and after. //! -//! 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`]). +//! A command that writes the block gives no warning. One that does not +//! gives one, in the place of "no pom.xml", with the reason and the words +//! that the Bazel build keeps the upstream jar. The lock each ruleset +//! release writes is the one socket-patch reads ([`Lock`]). //! //! The artifacts are made here, for the run, under the group //! `dev.socket.fixture`, which only the owner of `socket.dev` can publish @@ -43,7 +61,11 @@ //! (`/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. +//! with Bazel's downloader from the URL in the lock, and the patched jar +//! from the URL in the block, which names the patch host as production +//! does: a downloader config, given on the command line as a machine +//! behind a mirror has it, sends that host to the stand-in and refuses +//! every other URL of it. //! //! 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 @@ -71,7 +93,7 @@ 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::harness::{changed, rewrite, Cell, Fixture, Ran, StandIn, Tree, CONSUMER, NOTHING}; use crate::hosted_memory_common::Patch; /// The workspace the tests build, and the ruleset each Bazel release @@ -109,12 +131,24 @@ 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] = [ +/// The file of the block, and the files hosted mode writes in a checkout +/// that Maven builds too: those of a Maven pin, and that one. +const MODULE: &str = "MODULE.bazel"; +const PINNED: [&str; 4] = [ ".mvn/checksums/checksums.sha256", ".mvn/maven.config", + MODULE, "pom.xml", ]; +/// What the command says after its reason when it writes no entry. +const KEEPS: &str = "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps \ + the upstream jar"; +/// Its reason on a Bazel before 7.5.0 in a checkout without a launcher's +/// file: the lock such a Bazel writes does not tell it from one without +/// `override_repo`. +const NO_RELEASE: &str = "no file of the checkout says that Bazel 7.4.0 or later builds it, and \ + an older Bazel fails on the `override_repo` an entry needs: name the \ + release in `.bazelversion`"; fn sha256_hex(bytes: &[u8]) -> String { hex::encode(Sha256::digest(bytes)) @@ -164,6 +198,128 @@ fn repo_path(artifact: &str, version: &str, ext: &str) -> String { format!("{GROUP_PATH}/{artifact}/{version}/{artifact}-{version}.{ext}") } +/// Puts the jar `bytes` of `artifact` at `version` and its pom, which +/// depends on `needs`, in the stand-in's Maven repository. Gives the route +/// of the jar. +fn serve_upstream( + standin: &StandIn, + artifact: &str, + version: &str, + bytes: &[u8], + needs: Option<(&str, &str)>, +) -> String { + let pom = pom(artifact, version, needs); + for (ext, bytes) in [("jar", bytes), ("pom", pom.as_bytes())] { + // Coursier takes a file only with a checksum beside it. + let route = format!("/{UPSTREAM}/{}", repo_path(artifact, version, ext)); + let sha1 = hex::encode(Sha1::digest(bytes)); + standin.serve(5, &route, bytes); + standin.serve(5, &format!("{route}.sha1"), sha1.as_bytes()); + } + format!("/{UPSTREAM}/{}", repo_path(artifact, version, "jar")) +} + +/// A patch of the victim that a stand-in grants. +struct Granted { + uuid: String, + /// The sha256 the grant pins, of a jar with [`Granted::marker`]. + sha256: String, + /// The URL of the patched jar on the patch host, and its route on the + /// stand-in. + url: String, + route: String, + /// What `//:consumer` prints with the patched jar. + marker: String, +} + +/// Puts the grant of a new patch of the victim on the API of `standin`, +/// as production has it: a token and the patch id in the path of the patch +/// registry, the version with the suffix only that registry serves. The +/// route of the jar answers with `tampered`, or with the jar the grant +/// pins. +fn grant(standin: &StandIn, tampered: Option<&[u8]>) -> Granted { + let uuid = uuid::Uuid::new_v4().to_string(); + let token = uuid::Uuid::new_v4().to_string(); + let suffixed = format!("{VERSION}-socket.{}", &uuid[..8]); + let jar = victim(&format!("PATCHED {uuid}")); + let registry = format!("{PATCH_HOST}/patch-registry/maven/{token}/{uuid}/maven2"); + let file = repo_path(VICTIM, &suffixed, "jar"); + let route = format!("/{registry}/{file}"); + standin.serve(5, &route, tampered.unwrap_or(&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(&jar) }, + }], + "registryOverride": { + "kind": "maven2", + "indexUrl": format!("https://{registry}"), + "identifiers": { + "name": format!("{GROUP}/{VICTIM}"), + "version": VERSION, + "mavenGroupId": GROUP, + "mavenArtifactId": VICTIM, + "mavenSuffixedVersion": suffixed, + "mavenPomSha256": sha256_hex(pom(VICTIM, &suffixed, None).as_bytes()), + }, + }, + }); + standin.api(&[Patch { + purl: PURL.to_string(), + uuid: uuid.clone(), + reference, + }]); + Granted { + sha256: sha256_hex(&jar), + url: format!("https://{registry}/{file}"), + route, + marker: format!("OUT: PATCHED {uuid}"), + uuid, + } +} + +/// The name of the repository through which the fixture's hub fetches the +/// victim, on every era. +const REPOSITORY: &str = "dev_socket_fixture_victim_1_10_0"; + +/// The block of `MODULE.bazel` for `patch`, with its last line break. +fn block(patch: &Granted) -> String { + let Granted { + uuid, sha256, url, .. + } = patch; + format!( + r#"# >>> socket-patch: Maven patches for Bazel (managed block: socket-patch writes and removes it) >>> +socket_patch_http_file = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") + +socket_patch_maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") + +# {PURL}, Socket patch {uuid} +socket_patch_http_file( + name = "socket_patch_{REPOSITORY}", + downloaded_file_path = "v1/{GROUP_PATH}/{VICTIM}/{VERSION}/{VICTIM}-{VERSION}.jar", + sha256 = "{sha256}", + urls = ["{url}"], +) + +# If Bazel stops at the next line ("does not generate repository"), the hub's lock no longer pins +# {GROUP}:{VICTIM} at {VERSION}: run `socket-patch rollback {PURL}`. +# Do not change it to inject_repo(): the build would pass without the patch. +override_repo( + socket_patch_maven, + {REPOSITORY} = "socket_patch_{REPOSITORY}", +) +# <<< socket-patch <<< +"# + ) +} + /// A checkout whose hub is pinned, and what its flow reads afterwards. struct Pinned { cell: Cell, @@ -173,24 +329,25 @@ struct Pinned { /// 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. + /// The patch the stand-in grants, whose jar it serves. + patch: Granted, + /// The id of the run, which every upstream jar made for it holds. + run: String, + /// What `//:consumer` prints while Bazel builds the upstream jar, and + /// the route of that jar on the stand-in. 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 { + /// Step 0 of every flow: the fixture's checkout for `test`, with a + /// `pom.xml` that declares the victim when `maven` is set and with + /// what `prepare` adds to its files and to the text of `MODULE.bazel`, + /// pinned by the ruleset against a stand-in that has the two + /// artifacts, the patched jar and the grant of its patch. `None` when + /// no Bazel runs here. + fn open(test: &str, maven: bool, prepare: &dyn Fn(&Cell, &mut String)) -> Option { let started = Instant::now(); let mut cell = Cell::open(test, &FIXTURE)?; // The cache of the Coursier that pins. Before 7.2 the ruleset @@ -200,79 +357,37 @@ impl Pinned { 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" + // Bazel's downloads from the patch host go to the stand-in, under + // the route prefix of the host. A URL of that host that the rule + // did not rewrite is refused, so no download reaches the real one. + let rules = |origin: &str| { + let host = format!("{PATCH_HOST}/"); + [rewrite(&host, origin), format!("block {PATCH_HOST}")] + }; + cell.route_downloads(&rules(&origin)); + serve_upstream(&standin, VICTIM, VERSION, &upstream_jar, None); + serve_upstream( + &standin, + "consumer", + "2.0", + &jar(&[]), + Some((VICTIM, VERSION)), ); - 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, - }]); + let patch = grant(&standin, None); // 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)); + let mut module = module.replace(PLACEHOLDER, &repository); + prepare(&cell, &mut module); + cell.write("MODULE.bazel", module); cell.write("maven_install.json", ""); if maven { cell.write("pom.xml", pom("app", "1.0.0", Some((VICTIM, VERSION)))); @@ -319,15 +434,15 @@ impl Pinned { (format, Some(&jar)), "{test}: {lock:?}" ); + let upstream = format!("OUT: PRISTINE {run}"); Some(Pinned { cell, standin, tools, - uuid, - install, - upstream: format!("OUT: PRISTINE {run}"), + patch, + run, + upstream, upstream_route: format!("/{UPSTREAM}/{}", repo_path(VICTIM, VERSION, "jar")), - patched_route, started, }) } @@ -343,9 +458,15 @@ impl Pinned { before } - /// `socket-patch ` in the checkout, against the stand-in, with - /// the directories of [`Pinned::tools`] in the place of the machine's. + /// `socket-patch ` in the checkout, against the stand-in. fn socket_patch(&self, args: &[&str]) -> Ran { + self.socket_patch_in(&self.cell, &self.standin, args) + } + + /// `socket-patch ` in the checkout `cell`, against the API of + /// `standin`, with the directories of [`Pinned::tools`] in the place of + /// the machine's. + fn socket_patch_in(&self, cell: &Cell, standin: &StandIn, args: &[&str]) -> Ran { let dir = |name: &str| self.tools.path().join(name).to_string_lossy().into_owned(); let (m2, gradle, coursier) = (dir("m2"), dir("gradle"), dir("coursier")); let env = [ @@ -353,111 +474,391 @@ impl Pinned { ("GRADLE_USER_HOME", &gradle), ("COURSIER_CACHE", &coursier), ]; - self.cell.socket_patch(&self.standin.origin(), args, &env) + cell.socket_patch(&standin.origin(), args, &env) + } + + /// The command where it writes no entry for the hub, in a tree without + /// `pom.xml`: it reports the patch skipped, gives one warning, `code` + /// with the reason `why` and the words that the Bazel build keeps the + /// upstream jar, and changes no file of `before`. + fn declines(&self, before: &Tree, code: &str, why: &str) { + let test = &self.cell.test; + let get = self.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 detail = format!("{PURL}: {why}. {KEEPS}"); + let warnings = json!([{ "code": code, "detail": detail }]); + assert_eq!(get.envelope["warnings"], warnings, "{test}: {said}"); + assert_eq!( + changed(before, &self.cell.tree()), + NOTHING, + "{test}: {said}" + ); + } + + /// A Bazel before 7.5.0 writes a lock that does not tell it from one + /// without `override_repo`, so its checkout names the release as a + /// launcher reads it. Gives the files of the checkout. + fn names_its_bazel(&self) -> Tree { + if self.cell.numbers() < (7, 5, 0) { + let release = format!("{}\n", self.cell.release()); + self.cell.write(".bazelversion", release); + } + self.cell.tree() + } + + /// The one command of hosted mode: it reports the patch applied, + /// rewrites `files` and no other file of `before`, and gives no + /// warning. `MODULE.bazel` is the one of before with the block after + /// one blank line, and nothing has asked for the patched jar yet. + /// Gives the files of the checkout. + fn pins(&self, before: &Tree, files: &[&str]) -> Tree { + let test = &self.cell.test; + let get = self.socket_patch(&["get", PURL, "--mode", "hosted", "--yes"]); + let said = &get.dump; + let pinned = self + .cell + .pinned_by(&get, PURL, &self.patch.uuid, before, files); + assert_eq!(get.envelope["warnings"], Value::Null, "{test}: {said}"); + let text = |tree: &Tree| String::from_utf8(tree[MODULE].clone()).expect("a text file"); + let with_block = format!("{}\n{}", text(before), block(&self.patch)); + assert_eq!(text(&pinned), with_block, "{test}: {said}"); + let asked = self.standin.asked(&self.patch.route); + assert_eq!(asked, 0, "{test}: the command fetched the patched jar"); + pinned + } + + /// The same build after the command, no step in between: it prints the + /// marker of the patched jar, which Bazel fetched from the patch host + /// and not from the hub's repository. Bazel changed no file of + /// `pinned`, its own lock included, and that lock still stands when + /// Bazel may not update it. + fn builds_patched(&self, pinned: &Tree) { + let test = &self.cell.test; + let upstream = self.standin.asked(&self.upstream_route); + self.cell.builds_patched(pinned, &self.patch.marker); + let asked = self.standin.asked(&self.patch.route); + assert!(asked > 0, "{test}: the build did not fetch the patched jar"); + let again = self.standin.asked(&self.upstream_route); + assert_eq!( + again, upstream, + "{test}: the build fetched the upstream jar" + ); + } + + /// A second machine with the checkout. Bazel keeps a download that has + /// a checksum in the repository cache, which the two machines share, + /// so this one gets a patch whose jar no machine has fetched: another + /// service grants it, and its host serves other bytes than the grant + /// pins. The build has to ask that host, fails on the sha256 of the + /// entry, and does not go to the upstream jar. Gives what Bazel said. + fn a_second_machine_refuses_other_bytes(&self) -> String { + let test = &self.cell.test; + let mut twin = self.cell.twin(); + let rogue = StandIn::start(); + let tampered = victim("TAMPERED"); + let other = grant(&rogue, Some(&tampered)); + let host = format!("{PATCH_HOST}/"); + twin.route_downloads(&[ + rewrite(&host, &rogue.origin()), + format!("block {PATCH_HOST}"), + ]); + let get = self.socket_patch_in(&twin, &rogue, &["get", PURL, "--mode", "hosted", "--yes"]); + let said = &get.dump; + assert_eq!(get.code, 0, "{test}: {said}"); + assert_eq!(get.envelope["summary"]["applied"], 1, "{test}: {said}"); + let upstream = self.standin.asked(&self.upstream_route); + let build = twin.bazel("build", &[CONSUMER]); + assert!( + !build.ok(), + "{test}: the tampered jar built:\n{}", + build.dump() + ); + let refusal = format!( + "Checksum was {} but wanted {}", + sha256_hex(&tampered), + other.sha256 + ); + assert!( + build.stderr().contains(&refusal), + "{test}: the build did not fail on the sha256 of the entry:\n{}", + build.dump() + ); + assert!( + rogue.asked(&other.route) > 0, + "{test}: the patch host was not asked, so the failed build proves nothing" + ); + let again = self.standin.asked(&self.upstream_route); + assert_eq!( + again, upstream, + "{test}: the build went to the upstream jar" + ); + refusal } - /// 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 + /// The ruleset's own relock passes with the block in place, and + /// leaves the lock as it is: the hub still pins the upstream jar. + fn relock_keeps_the_lock(&self) { + let test = &self.cell.test; + let lock = std::fs::read(self.cell.path("maven_install.json")).expect("the lock"); + let pin = self + .cell + .bazel_env("run", &[&format!("@{HUB}//:pin")], &[("REPIN", "1")]); + assert!(pin.ok(), "{test}: {}", pin.dump()); + let after = std::fs::read(self.cell.path("maven_install.json")).expect("the lock"); + assert!( + lock == after, + "{test}: the relock changed maven_install.json" + ); + } + + /// `bazel mod tidy` passes and leaves `MODULE.bazel` as it is. + fn tidy_keeps_the_module_file(&self) { + let test = &self.cell.test; + let module = std::fs::read(self.cell.path("MODULE.bazel")).expect("MODULE.bazel"); + let tidy = self.cell.bazel("mod", &["tidy"]); + assert!(tidy.ok(), "{test}: {}", tidy.dump()); + let after = std::fs::read(self.cell.path("MODULE.bazel")).expect("MODULE.bazel"); + assert!( + module == after, + "{test}: `bazel mod tidy` changed MODULE.bazel to:\n{}", + String::from_utf8_lossy(&after) ); - 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) { + /// The checkout asks for the victim at `version` by name, the stand-in + /// has that release, and the ruleset's relock takes it into the lock. + /// Gives what `//:consumer` prints with that jar. + fn bump(&self, version: &str) -> String { 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"); + let marker = format!("PRISTINE {version} {}", self.run); + serve_upstream(&self.standin, VICTIM, version, &victim(&marker), None); + let module = std::fs::read_to_string(self.cell.path("MODULE.bazel")).expect("MODULE.bazel"); + let named = format!("\"{GROUP}:consumer:2.0\""); + assert_eq!(module.matches(&named).count(), 1, "{test}: {module}"); + let both = format!("{named}, \"{GROUP}:{VICTIM}:{version}\""); + self.cell + .write("MODULE.bazel", module.replace(&named, &both)); + let pin = self + .cell + .bazel_env("run", &[&format!("@{HUB}//:pin")], &[("REPIN", "1")]); + assert!(pin.ok(), "{test}: {}", pin.dump()); + let lock = std::fs::read_to_string(self.cell.path("maven_install.json")).expect("the lock"); + let lock = Lock::parse(&lock).unwrap_or_else(|why| panic!("{test}: {why}:\n{lock}")); + let pinned = lock + .plain_jar(GROUP, VICTIM) + .map(|jar| jar.version.as_str()); + assert_eq!(pinned, Some(version), "{test}: {lock:?}"); + format!("OUT: {marker}") } } -/// 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. +/// A Maven build and a Bazel build of one checkout: the one command pins +/// both, the Bazel build takes the patched jar, and the undo restores +/// every file. #[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 { + let Some(flow) = Pinned::open(test, true, &|_, _| {}) else { return; }; - let before = flow.builds_upstream(); + flow.builds_upstream(); + let before = flow.names_its_bazel(); - // 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); + // The three files of a Maven pin, and the block for the hub. + let pinned = flow.pins(&before, &PINNED); + flow.builds_patched(&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; {:?}", + "{test}: Bazel {} built {:?}, then {:?} after `get --mode hosted` pinned {PURL} in \ + pom.xml and in MODULE.bazel; `rollback` restored all {} files and the first build; {:?}", flow.cell.release(), flow.upstream, + flow.patch.marker, + before.len(), 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. +/// The same checkout without a `pom.xml`: the command writes the block, +/// the build is patched from the patch host at the sha256 of the entry, +/// and the undo puts `MODULE.bazel` back byte for byte. #[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 { + let Some(flow) = Pinned::open(test, false, &|_, _| {}) else { return; }; let before = flow.builds_upstream(); + // Nothing in the checkout of a Bazel before 7.5.0 says that it has + // `override_repo`: the command writes nothing until a file does. + let unnamed = flow.cell.numbers() < (7, 5, 0); + if unnamed { + flow.declines(&before, "maven_bazel_release", NO_RELEASE); + } + let before = flow.names_its_bazel(); - 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 })], + let pinned = flow.pins(&before, &[MODULE]); + flow.builds_patched(&pinned); + flow.relock_keeps_the_lock(); + flow.tidy_keeps_the_module_file(); + + // The undo: every file is the one of before, `MODULE.bazel` to the + // byte, and so is the build. + let undo = flow.socket_patch(&["rollback", "--yes"]); + flow.cell + .undone(&undo, "rolledBack", &before, &flow.upstream); + + let refusal = flow.a_second_machine_refuses_other_bytes(); + println!( + "{test}: Bazel {} built {:?}, then {:?} from the patch host after `get --mode hosted` \ + appended the block to MODULE.bazel{}; a `--lockfile_mode=error` build passed, the \ + relock left the lock and `bazel mod tidy` the file as it was; `rollback` restored \ + all {} files and the \ + first build; other bytes at the patch host failed a second machine's build \ + ({refusal}); {:?}", + flow.cell.release(), + flow.upstream, + flow.patch.marker, + if unnamed { + ", which it declined (maven_bazel_release) until the checkout had a .bazelversion" + } else { + "" + }, + before.len(), + flow.started.elapsed() ); - assert_eq!( - changed(&before, &flow.cell.tree()), - NOTHING, - "{test}: {said}" +} + +/// The checkout moves the artifact one version up after the command: the +/// relock passes, the build stops at the line of the entry, and the +/// command the block names there takes the entry out. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn a_version_bump_of_the_patched_artifact() { + let test = "maven::a_version_bump_of_the_patched_artifact"; + let Some(flow) = Pinned::open(test, false, &|_, _| {}) else { + return; + }; + flow.builds_upstream(); + let before = flow.names_its_bazel(); + flow.pins(&before, &[MODULE]); + + // The relock evaluates the hub with the entry in place, and passes. + let bumped = flow.bump("1.11.0"); + let module = std::fs::read_to_string(flow.cell.path(MODULE)).expect("MODULE.bazel"); + let entry = module.lines().position(|line| line == "override_repo("); + let line = entry.expect("the entry's override_repo") + 1; + // The lock no longer pins what the entry replaces: Bazel stops at the + // entry's line, under which the block says what to run. + let build = flow.cell.bazel("build", &[CONSUMER]); + let stderr = build.stderr(); + let stops = format!("does not generate repository \"{REPOSITORY}\""); + let at = format!("{MODULE}:{line}:"); + assert!( + !build.ok() && stderr.contains(&stops) && stderr.contains(&at), + "{test}: the build did not stop at {at} ({stops}):\n{}", + build.dump() ); - flow.still_builds_upstream(&before); + let remedy = format!("run `socket-patch rollback {PURL}`."); + let named = module + .lines() + .take(line) + .any(|line| line.ends_with(&remedy)); + assert!(named, "{test}: {module}"); + + let undo = flow.socket_patch(&["rollback", PURL, "--yes"]); + let said = &undo.dump; + assert_eq!(undo.code, 0, "{test}: {said}"); + assert_eq!(undo.envelope["summary"]["rolledBack"], 1, "{test}: {said}"); + // The file is the one the checkout had after its bump, without the + // block and the blank line before it. + let (start, _) = module.split_once(&block(&flow.patch)).expect("the block"); + let unpatched = start.strip_suffix('\n').expect("the blank line"); + let after = std::fs::read_to_string(flow.cell.path(MODULE)).expect("MODULE.bazel"); + assert_eq!(after, unpatched, "{test}: {said}"); + flow.cell.builds(&bumped); println!( - "{test}: Bazel {} built {:?} before and after `get --mode hosted` skipped {PURL} \ - and named the hub; {:?}", + "{test}: Bazel {} built {:?}; after `get --mode hosted` and the checkout's bump to \ + 1.11.0 the relock passed and the build stopped at {at} ({stops}); `rollback {PURL}` \ + took the entry out and the build printed {bumped:?}; {:?}", flow.cell.release(), flow.upstream, flow.started.elapsed() ); } +/// What the checkout builds in the artifact's place, and its package. +const OWN_MARKER: &str = "OUT: OWN of the checkout"; +const OWN_BUILD: &str = r#"load("@rules_java//java:defs.bzl", "java_library") + +java_library( + name = "victim", + resource_strip_prefix = "own", + resources = ["dev/socket/fixture/victim/marker.txt"], + visibility = ["//visibility:public"], +) +"#; + +/// A hub whose `maven.override` gives the artifact a target of the +/// checkout: an entry would change nothing that Bazel builds, so the +/// command writes none and says where the override is, and the build +/// prints that target's marker before and after. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn the_users_own_override_of_the_artifact() { + let test = "maven::the_users_own_override_of_the_artifact"; + let own = |cell: &Cell, module: &mut String| { + cell.write("own/BUILD.bazel", OWN_BUILD); + let marker = OWN_MARKER.trim_start_matches("OUT: "); + cell.write(&format!("own/{MARKER}"), format!("{marker}\n")); + module.push_str(&format!( + "maven.override(\n name = \"{HUB}\",\n coordinates = \"{GROUP}:{VICTIM}\",\n \ + target = \"//own:victim\",\n)\n" + )); + }; + let Some(flow) = Pinned::open(test, false, &own) else { + return; + }; + let before = flow.cell.builds_unpatched(OWN_MARKER); + + let before = match flow.cell.numbers() < (7, 5, 0) { + true => flow.names_its_bazel(), + false => before, + }; + + let module = std::fs::read_to_string(flow.cell.path(MODULE)).expect("MODULE.bazel"); + let line = module.lines().position(|line| line == "maven.override("); + let line = line.expect("the override") + 1; + let why = format!( + "{MODULE}:{line}: a `maven.override` gives this artifact another target, so Bazel would \ + not build a patched jar: patch that target, or remove the override" + ); + flow.declines(&before, "maven_bazel_no_effect", &why); + + flow.cell.builds(OWN_MARKER); + assert_eq!(changed(&before, &flow.cell.tree()), NOTHING, "{test}"); + let asked = flow.standin.asked(&flow.patch.route); + assert_eq!(asked, 0, "{test}: something fetched the patched jar"); + println!( + "{test}: Bazel {} built {OWN_MARKER:?} before and after `get --mode hosted` declined \ + {PURL} (maven_bazel_no_effect) and named the override at {MODULE}:{line}; {:?}", + flow.cell.release(), + 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 diff --git a/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs b/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs index 0eb89632c..c494e7a0a 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs @@ -1,15 +1,22 @@ //! 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. +//! `socket-patch` says about a rules_jvm_external hub and writes for it, +//! 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`. +//! that no hub builds gets. +//! +//! The others hold what a hub that builds the artifact changes. A hosted +//! run writes one block at the end of the root `MODULE.bazel`, beside +//! whatever it pins for a Maven build, and `rollback` takes it out to the +//! byte; where it cannot show that the block would work it writes nothing +//! for the hub and gives one warning with the reason, in the place of "no +//! pom.xml" in a tree that only Bazel builds. An agent run patches no hub +//! and says so, unless the block already does. A `--global` run says +//! nothing. //! //! 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 @@ -141,6 +148,12 @@ struct Machine { impl Machine { fn start() -> Machine { + Machine::serving(PURL) + } + + /// A machine whose API has the patch under `purl`: the artifact's own, + /// or the one of a jar of it with a classifier. + fn serving(purl: &str) -> 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"); @@ -153,7 +166,7 @@ impl Machine { let reference = json!({ "status": "granted", "url": url, - "purl": PURL, + "purl": purl, "artifacts": [{ "kind": "tarball", "url": url, "integrity": { "sha256": "a".repeat(64) } }], "registryOverride": { "kind": "maven2", "indexUrl": index, "identifiers": { "name": "dev.socket.fixture/victim", @@ -165,7 +178,7 @@ impl Machine { } }, }); let patch = Patch { - purl: PURL.to_string(), + purl: purl.to_string(), uuid: UUID.to_string(), reference, }; @@ -178,11 +191,18 @@ impl Machine { } } - /// 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. + /// Makes the checkout anew ([`Machine::make`]) and runs `socket-patch + /// ` there. fn run(&self, bazel: &[(&str, String)], maven: bool, args: &[&str]) -> Ran { + self.make(bazel, maven, true); + self.step(args) + } + + /// Makes the checkout anew, with the Bazel files `bazel` and, when + /// `maven` is set, its `pom.xml`; when `agent` is set, a manifest of + /// an agent patch of the artifact's pom; and the Maven local + /// repository as a build of the checkout leaves it. + fn make(&self, bazel: &[(&str, String)], maven: bool, agent: bool) { 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); @@ -211,14 +231,26 @@ impl Machine { "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); + if agent { + 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(), ); + } + + /// Runs `socket-patch ` in the checkout as it is. + fn step(&self, args: &[&str]) -> Ran { + self.step_in(&self.root.join("proj"), args) + } + + /// Runs `socket-patch ` in the directory `proj` of the checkout. + fn step_in(&self, proj: &std::path::Path, args: &[&str]) -> Ran { + let m2 = self.root.join("m2"); let before = self.files(); // Nothing of the machine reaches the child: no tool on PATH, an @@ -242,7 +274,7 @@ impl Machine { } let home = self.root.join("home"); std::fs::create_dir_all(&home).expect("a home"); - cmd.current_dir(&proj) + cmd.current_dir(proj) .env("PATH", "") .env("HOME", &home) .env("USERPROFILE", &home) @@ -295,11 +327,70 @@ const COMMANDS: [&[&str]; 6] = [ &["apply", "--offline", "--dry-run", "--json"], ]; -/// The warning of a run in the checkout whose hub builds the artifact. +/// The warning of an agent 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"; + upstream jar, and this command does not patch a rules_jvm_external hub: the Bazel build stays \ + unpatched whatever it did for another build of the checkout. `socket-patch get \ + pkg:maven/dev.socket.fixture/victim@1.10.0 --mode hosted` at the Bazel root patches a pinned \ + hub"; + +/// What a hosted run says after its reason when it writes no entry for a +/// hub. +const KEEPS: &str = "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps \ + the upstream jar"; +/// Its reason in a checkout that names no Bazel release and has no +/// `MODULE.bazel.lock`. +const NO_RELEASE: &str = "no file of the checkout says that Bazel 7.4.0 or later builds it, and \ + an older Bazel fails on the `override_repo` an entry needs: name the \ + release in `.bazelversion`"; + +/// The warning of a hosted run that writes no entry, for the reason `why`. +fn declined(why: &str) -> String { + format!("{PURL}: {why}. {KEEPS}") +} + +/// The block a hosted run keeps at the end of `MODULE.bazel` for the +/// patch of the stand-in API, with its last line break. +const BLOCK: &str = r#"# >>> socket-patch: Maven patches for Bazel (managed block: socket-patch writes and removes it) >>> +socket_patch_http_file = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") + +socket_patch_maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") + +# pkg:maven/dev.socket.fixture/victim@1.10.0, Socket patch 5e0a7c1d-7b4e-4c1a-9f0e-2a3b4c5d6e7f +socket_patch_http_file( + name = "socket_patch_dev_socket_fixture_victim_1_10_0", + downloaded_file_path = "v1/dev/socket/fixture/victim/1.10.0/victim-1.10.0.jar", + sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + urls = ["https://patch.socket.dev/patch-registry/maven/token/5e0a7c1d-7b4e-4c1a-9f0e-2a3b4c5d6e7f/maven2/dev/socket/fixture/victim/1.10.0-socket.5e0a7c1d/victim-1.10.0-socket.5e0a7c1d.jar"], +) + +# If Bazel stops at the next line ("does not generate repository"), the hub's lock no longer pins +# dev.socket.fixture:victim at 1.10.0: run `socket-patch rollback pkg:maven/dev.socket.fixture/victim@1.10.0`. +# Do not change it to inject_repo(): the build would pass without the patch. +override_repo( + socket_patch_maven, + dev_socket_fixture_victim_1_10_0 = "socket_patch_dev_socket_fixture_victim_1_10_0", +) +# <<< socket-patch <<< +"#; + +/// The workspace whose pinned hub builds the artifact, with what says +/// which Bazel builds it and which release of the ruleset Bazel selected: +/// the one a hosted run writes its block for. +fn pinned() -> Files { + let [.., mut hub] = checkouts(); + let bcr = "https://bcr.bazel.build/modules/rules_jvm_external"; + let lock = json!({ "lockFileVersion": 13, "registryFileHashes": { + format!("{bcr}/6.5/MODULE.bazel"): "0", + format!("{bcr}/7.2/MODULE.bazel"): "1", + format!("{bcr}/7.2/source.json"): "2", + } }); + hub.push((".bazelversion", "7.7.2\n".to_string())); + hub.push(("MODULE.bazel.lock", format!("{lock:#}\n"))); + hub +} #[test] fn a_maven_project_no_hub_builds_reports_as_without_bazel() { @@ -340,9 +431,15 @@ fn a_hub_that_pins_the_artifact_adds_one_warning_and_nothing_else() { (without.code, &without.wrote), "{args:?}: {beside:?}" ); + // An agent run patches no hub. A hosted run would, and says why it + // does not here: nothing in this checkout names its Bazel. + let (code, detail) = match args[0] { + "get" => ("maven_bazel_release", declined(NO_RELEASE)), + _ => ("maven_bazel_hub_unpatched", HUB_WARNING.to_string()), + }; 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 warning = json!({ "code": code, "detail": detail }); let warnings = expected["warnings"].as_array().cloned().unwrap_or_default(); assert_eq!( said["warnings"].take(), @@ -361,7 +458,7 @@ fn a_hub_that_pins_the_artifact_adds_one_warning_and_nothing_else() { } 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 line = format!("Warning: {detail}"); 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:?}"); @@ -375,21 +472,20 @@ fn a_hub_that_pins_the_artifact_adds_one_warning_and_nothing_else() { } #[test] -fn a_hub_only_tree_names_the_lock_beside_the_missing_pom() { +fn a_hub_only_tree_says_why_the_hub_is_not_patched() { 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 unpinned = 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"]), + // What a hub builds has its own answer, in the place of that one. + (&hub, &["maven_bazel_release"]), + (&unpinned, &["maven_bazel_not_pinned"]), ] { let ran = machine.run(bazel, false, json); let envelope = ran.envelope(); @@ -402,28 +498,592 @@ fn a_hub_only_tree_names_the_lock_beside_the_missing_pom() { 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. + // A person is pointed at the one warning, which says why nothing was + // pinned and what the Bazel build keeps. 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")), + let not_pinned = + "MODULE.bazel:4: hub \"maven\" has no `lock_file`, so Bazel resolves its jars \ + when it builds and none can be replaced: give the hub a `lock_file` and \ + pin it (`REPIN=1 bazel run @maven//:pin`)"; + for (bazel, why) in [(&hub, NO_RELEASE), (&unpinned, not_pinned)] { + let ran = machine.run(bazel, false, COMMANDS[1]); + let warning = format!("Warning: {}\n", declined(why)); + let at = [pointed, &warning].map(|line| ran.stderr.find(line)); + assert!(at[0].is_some() && at[0] < at[1], "{ran:?}"); + assert_eq!( + ran.stderr.matches("Warning: pkg:maven").count(), + 1, + "{ran:?}" + ); + assert!(!ran.stderr.contains("pom.xml"), "{ran:?}"); + } +} + +/// The files of a Maven pin, and the block's. +const POM_FILES: [&str; 3] = [ + "proj/.mvn/checksums/checksums.sha256", + "proj/.mvn/maven.config", + "proj/pom.xml", +]; +const MODULE: &str = "proj/MODULE.bazel"; + +#[test] +fn a_pinned_hub_gets_its_block_and_the_undo_takes_it_out() { + let machine = Machine::start(); + let with_block = format!("{HUB}\n{BLOCK}"); + for maven in [false, true] { + let mut files = vec![MODULE]; + if maven { + files.extend(POM_FILES); + } + files.sort_unstable(); + let rewritten: Vec<&str> = files.iter().map(|file| &file["proj/".len()..]).collect(); + // A dry run says what the run will do, and writes nothing. + machine.make(&pinned(), maven, false); + let dry = machine.step(COMMANDS[4]); + let envelope = dry.envelope(); + assert_eq!(event_for(&envelope, PURL)["action"], "verified", "{dry:?}"); + assert_eq!( + envelope["redirect"]["rewrittenFiles"], + json!(rewritten), + "{dry:?}" + ); + assert_eq!( + (dry.code, &dry.wrote), + (Some(0), &BTreeMap::new()), + "{dry:?}" + ); + + // The run: applied, no warning, the block after one blank line. + let get = machine.step(COMMANDS[0]); + let envelope = get.envelope(); + assert_eq!(get.code, Some(0), "{get:?}"); + assert_eq!(event_for(&envelope, PURL)["action"], "applied", "{get:?}"); + assert_eq!( + envelope["redirect"]["rewrittenFiles"], + json!(rewritten), + "{get:?}" + ); + assert_eq!(envelope["warnings"], Value::Null, "{get:?}"); + assert_eq!(get.wrote.keys().collect::>(), files, "{get:?}"); + assert_eq!( + String::from_utf8_lossy(&get.wrote[MODULE]), + with_block, + "{get:?}" + ); + + // Again: still applied, and nothing to write. + let again = machine.step(COMMANDS[0]); + let envelope = again.envelope(); + assert_eq!(event_for(&envelope, PURL)["action"], "applied", "{again:?}"); + assert_eq!( + envelope["redirect"]["rewrittenFiles"], + json!([]), + "{again:?}" + ); + assert_eq!( + (again.code, &again.wrote), + (Some(0), &BTreeMap::new()), + "{again:?}" + ); + + // A scan keeps the pin it finds in the file. + let scan = machine.step(&["scan", "--mode", "hosted", "--yes", "--json"]); + assert_eq!( + (scan.code, &scan.wrote), + (Some(0), &BTreeMap::new()), + "{scan:?}" + ); + + // `list` reads the pin from the file, and `vex` attests it. + let list = machine.step(&["list", "--json"]).envelope(); + let listed = event_for(&list, PURL); + assert_eq!(listed["details"]["mode"], "hosted", "{list:#}"); + let pinned_in = listed["details"]["lockfiles"] + .as_array() + .expect("the files"); + assert!(pinned_in.contains(&json!("MODULE.bazel")), "{list:#}"); + let product = ["--product", "pkg:generic/proj"]; + let vex = + machine.step(&[&["vex", "--json", "--output", "vex.json"], &product[..]].concat()); + let attested = vex.envelope(); + assert_eq!( + event_for(&attested, PURL)["details"]["status"], + "not_affected", + "{vex:?}" + ); + std::fs::remove_file(machine.root.join("proj/vex.json")).expect("the document"); + + // The undo: every file is the one of before, to the byte. + let undo = machine.step(&["rollback", "--yes", "--json"]); + assert_eq!(undo.code, Some(0), "{undo:?}"); + assert_eq!(undo.envelope()["summary"]["rolledBack"], 1, "{undo:?}"); + let restored = |path: &str| String::from_utf8_lossy(&undo.wrote[path]).into_owned(); + assert_eq!(restored(MODULE), HUB, "{undo:?}"); + if maven { + assert_eq!(restored("proj/pom.xml"), PROJECT_POM, "{undo:?}"); + } + assert_eq!(undo.wrote.len(), 1 + usize::from(maven), "{undo:?}"); + let left = machine.files(); + let mvn = left.keys().any(|path| path.starts_with("proj/.mvn/")); + assert!(!mvn, "{left:?}"); + } + // `remove` takes the entry out as `rollback` does. + machine.make(&pinned(), false, false); + assert_eq!(machine.step(COMMANDS[0]).wrote.len(), 1); + let removed = machine.step(&["remove", PURL, "--yes", "--json"]); + assert_eq!(removed.code, Some(0), "{removed:?}"); + let restored = String::from_utf8_lossy(&removed.wrote[MODULE]); + assert_eq!((removed.wrote.len(), &*restored), (1, HUB), "{removed:?}"); + + // A person is told which file to commit. + machine.make(&pinned(), false, false); + let person = machine.step(COMMANDS[1]); + assert!(person.stdout.contains("rewrote 1 file"), "{person:?}"); + assert!(person.stdout.contains("Commit MODULE.bazel"), "{person:?}"); + assert!(!person.stderr.contains("Warning: pkg:maven"), "{person:?}"); +} + +/// The Bazel files of a checkout, each with its text. +type Files = Vec<(&'static str, String)>; + +/// A Maven pin is not always one edit of the root `pom.xml`. In a reactor +/// it goes to the module that selects the version, with the repository in +/// the root; a version that a property sets is pinned through the +/// property; and behind a mirror of the machine's Maven settings that +/// would take the Socket repository there is no pin at all, and the run +/// says so. Beside a pinned hub each of those runs still writes the hub's +/// block: Bazel fetches the jar of an entry by its URL, through no mirror +/// of Maven's. The pin is one, in the block and in every pom that holds +/// part of it, and the undo takes all of it out, to the byte. +#[test] +fn the_hub_gets_its_block_whatever_the_maven_pin_is() { + let machine = Machine::start(); + let root = "\n 4.0.0\n \ + com.example\n root\n \ + 1\n pom\n \n \ + app\n \n\n"; + let module = PROJECT_POM.replace( + " com.example\n app\n 1\n", + " \n com.example\n root\n \ + 1\n \n app\n", + ); + let property = PROJECT_POM + .replace("1.10.0<", "${victim.version}<") + .replace( + " \n", + " \n 1.10.0\n \n \ + \n", + ); + assert!(module.contains("") && property.contains("")); + let mirror = "\n \n \n corp\n \ + *\n https://repo.example/maven2\n \ + \n \n\n"; + // The poms of the checkout, those of them that take part of the pin, + // the settings of the machine, and what the run warns of. + let rows: [(&str, Files, &[&str], Option<&str>, &[&str]); 3] = [ + ( + "a reactor", + vec![("pom.xml", root.to_string()), ("app/pom.xml", module)], + &["app/pom.xml", "pom.xml"], + None, + &[], + ), ( - &unreadable, - format!("Warning: {PURL}: socket-patch could not tell"), + "a property", + vec![("pom.xml", property)], + &["pom.xml"], + None, + &[], ), + ( + "a mirror", + vec![("pom.xml", PROJECT_POM.to_string())], + &[], + Some(mirror), + &["redirect_maven_mirror_captures_repository"], + ), + ]; + for (shape, poms, pinned_poms, settings, warns) in rows { + machine.make(&[pinned(), poms].concat(), false, false); + if let Some(settings) = settings { + let m2 = machine.root.join("home/.m2"); + std::fs::create_dir_all(&m2).expect("the user's Maven directory"); + std::fs::write(m2.join("settings.xml"), settings).expect("the settings"); + } + let before = machine.files(); + + let get = machine.step(COMMANDS[0]); + let envelope = get.envelope(); + assert_eq!(get.code, Some(0), "{shape}: {get:?}"); + assert_eq!( + event_for(&envelope, PURL)["action"], + "applied", + "{shape}: {get:?}" + ); + assert_eq!(warning_codes(&envelope), warns, "{shape}: {get:?}"); + // The block, the poms of the pin, and the checksum files of a + // Maven pin when there is one. + let pin: Vec<&str> = [&["MODULE.bazel"], pinned_poms].concat(); + let mut wrote: Vec = pin.iter().map(|file| format!("proj/{file}")).collect(); + let checksums = &POM_FILES[..2 * usize::from(!pinned_poms.is_empty())]; + wrote.extend(checksums.iter().map(|file| file.to_string())); + wrote.sort_unstable(); + assert_eq!( + get.wrote.keys().collect::>(), + wrote.iter().collect::>(), + "{shape}: {get:?}" + ); + assert_eq!( + String::from_utf8_lossy(&get.wrote[MODULE]), + format!("{HUB}\n{BLOCK}"), + "{shape}" + ); + + // `list` shows one pin, in those files, and `vex` states it once. + let of_the_patch = |envelope: &Value| -> Vec { + let events = envelope::events(envelope).iter(); + events + .filter(|event| event["purl"] == PURL) + .cloned() + .collect() + }; + let listed = of_the_patch(&machine.step(&["list", "--json"]).envelope()); + assert_eq!(listed.len(), 1, "{shape}: {listed:?}"); + assert_eq!( + listed[0]["details"]["lockfiles"], + json!(pin), + "{shape}: {listed:?}" + ); + let vex = ["vex", "--json", "--output", "vex.json"]; + let vex = machine.step(&[&vex[..], &["--product", "pkg:generic/proj"]].concat()); + let stated = of_the_patch(&vex.envelope()); + assert_eq!(stated.len(), 1, "{shape}: {vex:?}"); + assert_eq!( + stated[0]["details"]["status"], "not_affected", + "{shape}: {vex:?}" + ); + std::fs::remove_file(machine.root.join("proj/vex.json")).expect("the document"); + + // A second run finds all of it in place, and the undo leaves none. + let again = machine.step(COMMANDS[0]); + assert_eq!( + (again.code, &again.wrote), + (Some(0), &BTreeMap::new()), + "{shape}: {again:?}" + ); + let undo = machine.step(&["rollback", "--yes", "--json"]); + assert_eq!(undo.code, Some(0), "{shape}: {undo:?}"); + assert_eq!( + undo.envelope()["summary"]["rolledBack"], + 1, + "{shape}: {undo:?}" + ); + assert_eq!(machine.files(), before, "{shape}: {undo:?}"); + } +} + +/// Where the block cannot be shown to work the run writes nothing for +/// the hub and says why: alone in a tree only Bazel builds, and beside +/// the Maven pin, which still lands, in a tree that Maven builds too. +#[test] +fn a_decline_writes_nothing_for_the_hub_and_says_why() { + let machine = Machine::start(); + let with = |change: &dyn Fn(&mut Files)| { + let mut files = pinned(); + change(&mut files); + files + }; + let module = |text: String| move |files: &mut Files| files[0].1 = text.clone(); + let over = format!( + "{HUB}maven.override(coordinates = \"dev.socket.fixture:victim\", target = \"//:own\")\n" + ); + let edited = format!("{HUB}\n{}", BLOCK.replace("# Do not", "# Do")); + let rows = [ + ( + with(&|files| files.truncate(2)), + "maven_bazel_release", + "name the release in `.bazelversion`", + ), + ( + with(&|files| files[2].1 = "7.3.1\n".to_string()), + "maven_bazel_release", + "the checkout names Bazel 7.3.1", + ), + ( + with(&|files| files.push((".bazelrc", "common --noenable_bzlmod\n".to_string()))), + "maven_bazel_no_effect", + ".bazelrc:1 names `--noenable_bzlmod`", + ), + ( + with(&|files| files.push((".bazelrc", "common --vendor_dir=v\n".to_string()))), + "maven_bazel_download", + ".bazelrc:1 names `--vendor_dir=v`", + ), + ( + with(&module(over)), + "maven_bazel_no_effect", + "MODULE.bazel:9: a `maven.override` gives", + ), + ( + with(&module(edited)), + "maven_bazel_unreadable", + "MODULE.bazel:10: the block that socket-patch keeps there was changed by hand", + ), + ]; + for (bazel, code, why) in &rows { + for maven in [false, true] { + let ran = machine.run(bazel, maven, COMMANDS[0]); + let envelope = ran.envelope(); + let (action, files) = match maven { + true => ("applied", POM_FILES.to_vec()), + false => ("skipped", Vec::new()), + }; + assert_eq!(ran.code, Some(0), "{code}: {ran:?}"); + assert_eq!( + event_for(&envelope, PURL)["action"], + action, + "{code}: {ran:?}" + ); + assert_eq!( + ran.wrote.keys().collect::>(), + files, + "{code}: {ran:?}" + ); + assert_eq!(warning_codes(&envelope), [*code], "{ran:?}"); + let detail = envelope["warnings"][0]["detail"] + .as_str() + .expect("its text"); + let said = detail.starts_with(PURL) && detail.contains(why) && detail.ends_with(KEEPS); + assert!(said, "{code}: {detail}"); + } + } + // A project below the root of its workspace: the file is not its own. + machine.make(&pinned(), false, false); + let below = machine.root.join("proj/services/billing"); + std::fs::create_dir_all(&below).expect("a project"); + let ran = machine.step_in(&below, COMMANDS[0]); + assert_eq!( + warning_codes(&ran.envelope()), + ["maven_bazel_not_at_root"], + "{ran:?}" + ); + assert_eq!(ran.wrote, BTreeMap::new(), "{ran:?}"); +} + +/// A run that can no longer show that the block works leaves the entry +/// of an earlier run where it is, and says so: the patch is still pinned. +#[test] +fn a_decline_leaves_the_entry_of_an_earlier_run_in_place() { + let machine = Machine::start(); + for maven in [false, true] { + machine.make(&pinned(), maven, false); + assert_eq!(machine.step(COMMANDS[0]).code, Some(0)); + for names_bazel in [".bazelversion", "MODULE.bazel.lock"] { + std::fs::remove_file(machine.root.join("proj").join(names_bazel)).expect("the file"); + } + let again = machine.step(COMMANDS[0]); + let envelope = again.envelope(); + assert_eq!( + (again.code, &again.wrote), + (Some(0), &BTreeMap::new()), + "{again:?}" + ); + assert_eq!(event_for(&envelope, PURL)["action"], "applied", "{again:?}"); + assert_eq!( + warning_codes(&envelope), + ["maven_bazel_release"], + "{again:?}" + ); + let left = "socket-patch left the entry that MODULE.bazel holds for it as it is"; + assert_eq!( + envelope["warnings"][0]["detail"], + format!("{PURL}: {NO_RELEASE}. {left}"), + "{again:?}" + ); + } +} + +/// A run below the Bazel root writes nothing. When the block of the root +/// already holds the entry of the patch, the Bazel build takes the patched +/// jar: the run says that the entry stands, and reports the patch as a +/// decline beside its own entry at the root does. +#[test] +fn a_run_below_the_root_says_that_the_entry_at_the_root_stands() { + let machine = Machine::start(); + machine.make(&pinned(), false, false); + assert_eq!(machine.step(COMMANDS[0]).wrote.len(), 1); + let below = machine.root.join("proj/services/billing"); + std::fs::create_dir_all(&below).expect("a project"); + let ran = machine.step_in(&below, COMMANDS[0]); + let envelope = ran.envelope(); + assert_eq!( + (ran.code, &ran.wrote), + (Some(0), &BTreeMap::new()), + "{ran:?}" + ); + assert_eq!(event_for(&envelope, PURL)["action"], "applied", "{ran:?}"); + assert_eq!( + warning_codes(&envelope), + ["maven_bazel_not_at_root"], + "{ran:?}" + ); + let detail = envelope["warnings"][0]["detail"] + .as_str() + .expect("its text"); + let stands = "run the command there. socket-patch left the entry that the MODULE.bazel at \ + the root holds for it as it is"; + assert!( + detail.starts_with(PURL) && detail.ends_with(stands), + "{detail}" + ); +} + +/// A decline beside the entry of another patch of the same jar: that entry +/// is not this run's to replace, so it remains, and the warning names it +/// in the place of "keeps the upstream jar". +#[test] +fn a_decline_names_the_entry_of_another_patch_that_remains() { + let machine = Machine::start(); + let other = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; + let mut files = pinned(); + files[0].1 = format!("{HUB}\n{}", BLOCK.replace(UUID, other)); + files.truncate(2); + for maven in [false, true] { + let ran = machine.run(&files, maven, COMMANDS[0]); + let envelope = ran.envelope(); + let (action, wrote) = match maven { + true => ("applied", POM_FILES.to_vec()), + false => ("skipped", Vec::new()), + }; + assert_eq!(ran.code, Some(0), "{ran:?}"); + assert_eq!(event_for(&envelope, PURL)["action"], action, "{ran:?}"); + assert_eq!(ran.wrote.keys().collect::>(), wrote, "{ran:?}"); + assert_eq!(warning_codes(&envelope), ["maven_bazel_release"], "{ran:?}"); + let remains = format!( + "{PURL}: {NO_RELEASE}. socket-patch wrote nothing to MODULE.bazel for it: the entry \ + of patch {other} remains there, and where the block is in effect the Bazel build \ + takes that patch's jar" + ); + assert_eq!(envelope["warnings"][0]["detail"], remains, "{ran:?}"); + } +} + +/// A block that was changed by hand, also in its first line alone, is no +/// pin that a command manages: `get` writes nothing to it, and `rollback` +/// and `list` refuse and name the file to restore. +#[test] +fn a_block_that_was_changed_by_hand_is_refused_by_the_undo() { + let machine = Machine::start(); + let changed = "MODULE.bazel:10: the block that socket-patch keeps there was changed by hand"; + for edited in [ + BLOCK.replace("# Do not", "# Do"), + BLOCK.replacen(") >>>\n", ") >>> \n", 1), ] { - 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:?}"); + assert_ne!(edited, BLOCK); + let mut files = pinned(); + files[0].1 = format!("{HUB}\n{edited}"); + machine.make(&files, false, false); + let get = machine.step(COMMANDS[0]); + let envelope = get.envelope(); + assert_eq!( + warning_codes(&envelope), + ["maven_bazel_unreadable"], + "{get:?}" + ); + let detail = envelope["warnings"][0]["detail"] + .as_str() + .expect("its text"); + assert!(detail.contains(changed), "{detail}"); + assert_eq!(get.wrote, BTreeMap::new(), "{get:?}"); + for args in [&["rollback", "--yes", "--json"][..], &["list", "--json"]] { + let ran = machine.step(args); + let error = &ran.envelope()["error"]; + let message = error["message"].as_str().unwrap_or_default(); + assert_eq!( + (ran.code, &error["code"]), + (Some(1), &json!("hosted_wiring_contested")), + "{args:?}: {ran:?}" + ); + let named = + message.contains(changed) && message.contains("git checkout -- MODULE.bazel"); + assert!(named, "{args:?}: {message}"); + assert_eq!(ran.wrote, BTreeMap::new(), "{args:?}"); + } + } +} + +/// A patch of a jar with a classifier is not the jar that a hub's lock +/// names by group and artifact. Beside a pinned hub that builds the plain +/// jar, a hosted run for it is the run without Bazel: nothing is written +/// to `MODULE.bazel`, and nothing is said of the hub. +#[test] +fn a_patch_of_a_classifier_jar_gets_nothing_of_the_hub() { + let purl = format!("{PURL}?classifier=tests"); + let machine = Machine::serving(&purl); + let [plain, ..] = checkouts(); + for maven in [false, true] { + for json in [true, false] { + let mut args = vec!["get", purl.as_str(), "--mode", "hosted", "--yes"]; + args.extend(json.then_some("--json")); + let without = machine.run(&plain, maven, &args); + assert_eq!(without.code, Some(0), "{without:?}"); + assert_eq!(machine.run(&pinned(), maven, &args), without, "{args:?}"); + } + } +} + +/// The hub's lock moves on after the pin: Bazel then stops at the entry, +/// `vex` attests nothing for it, and the command the block names there +/// takes it out. +#[test] +fn an_entry_whose_jar_the_lock_no_longer_pins_is_undone_and_not_attested() { + let machine = Machine::start(); + machine.make(&pinned(), false, false); + assert_eq!(machine.step(COMMANDS[0]).wrote.len(), 1); + let moved = lock(&[("consumer", "2.0"), ("victim", "1.11.0")]); + std::fs::write(machine.root.join("proj/maven_install.json"), moved).expect("the lock"); + + let vex = ["vex", "--json", "--output", "vex.json"]; + let vex = machine.step(&[&vex[..], &["--product", "pkg:generic/proj"]].concat()); + let said = vex.envelope(); + assert_eq!(said["events"], json!([]), "{vex:?}"); + assert_eq!( + warning_codes(&said), + ["patched_ref_unattributable"], + "{vex:?}" + ); + assert_eq!(vex.wrote, BTreeMap::new(), "{vex:?}"); + let list = machine.step(&["list", "--json"]).envelope(); + assert_eq!( + event_for(&list, PURL)["details"]["mode"], + "hosted", + "{list:#}" + ); + + let undo = machine.step(&["rollback", PURL, "--yes", "--json"]); + assert_eq!(undo.code, Some(0), "{undo:?}"); + assert_eq!(undo.envelope()["summary"]["rolledBack"], 1, "{undo:?}"); + assert_eq!( + String::from_utf8_lossy(&undo.wrote[MODULE]), + HUB, + "{undo:?}" + ); +} + +/// An agent run beside a hub that hosted mode has patched: the Bazel +/// build takes the block's jar, and nothing is said of the hub. +#[test] +fn an_agent_run_says_nothing_of_a_hub_the_block_patches() { + let machine = Machine::start(); + let [plain, ..] = checkouts(); + for args in [COMMANDS[2], COMMANDS[3]] { + let without = machine.run(&plain, true, args); + let mut patched = pinned(); + patched[0].1 = format!("{HUB}\n{BLOCK}"); + let beside = machine.run(&patched, true, args); + assert_eq!(beside, without, "{args:?}"); } - 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] 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 index 4bb7babc0..b2258ade8 100644 --- 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 @@ -1,8 +1,15 @@ -module(name = "socket_fixture", version = "0.0.0") +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") + +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 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 index 22b5643f5..814fc2b93 100644 --- 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 @@ -1,8 +1,15 @@ -module(name = "socket_fixture", version = "0.0.0") +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") + +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 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 index 4063472d3..5bd1a3765 100644 --- 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 @@ -1,8 +1,15 @@ -module(name = "socket_fixture", version = "0.0.0") +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") + +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 diff --git a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs index f873d505b..95ef1de0e 100644 --- a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs +++ b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs @@ -1742,10 +1742,11 @@ fn a_bazel_hub_that_builds_a_vendored_jar_adds_one_warning_and_nothing_else() { 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", + "{0}: Bazel takes this artifact from maven_install.json (hub \"maven\", `maven.install` \ + at MODULE.bazel:3), which pins the upstream jar, and this command does not patch a \ + rules_jvm_external hub: the Bazel build stays unpatched whatever it did for another \ + build of the checkout. `socket-patch get {0} --mode hosted` at the Bazel root patches \ + a pinned hub", purl("foo") ); let warning = serde_json::json!({ "code": "maven_bazel_hub_unpatched", "detail": detail }); @@ -1798,3 +1799,147 @@ fn a_bazel_hub_that_builds_a_vendored_jar_adds_one_warning_and_nothing_else() { }; assert_eq!(others(Some(lock("foo"))), others(None)); } + +/// Vendored mode patches no rules_jvm_external hub, and takes none over. +/// The entry that hosted mode keeps for a jar in the block of +/// `MODULE.bazel` is a hosted pin of that jar, and `vendor` and `vendor +/// --revert` leave it as it is: the Bazel build keeps the patched jar. +/// Everything else is the run without the workspace, and nothing is said +/// of a hub that the block patches. That holds for an entry alone, and +/// for one whose patch a hosted run also pinned in the poms of the +/// reactor: `vendor` takes the poms' part of that pin over, as it does +/// without the workspace. +#[test] +fn vendor_leaves_the_hosted_entry_of_a_bazel_hub_in_place() { + let module = format!( + r#"bazel_dep(name = "rules_jvm_external", version = "7.2") +maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") +maven.install(lock_file = "//:maven_install.json") + +# >>> socket-patch: Maven patches for Bazel (managed block: socket-patch writes and removes it) >>> +socket_patch_http_file = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") + +socket_patch_maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") + +# pkg:maven/org.example/foo@1.0, Socket patch {FOO_UUID} +socket_patch_http_file( + name = "socket_patch_org_example_foo_1_0", + downloaded_file_path = "v1/org/example/foo/1.0/foo-1.0.jar", + sha256 = "{sum}", + urls = ["https://patch.socket.dev/patch-registry/maven/token/{FOO_UUID}/maven2/org/example/foo/1.0-socket.1d3c1fd2/foo-1.0-socket.1d3c1fd2.jar"], +) + +# If Bazel stops at the next line ("does not generate repository"), the hub's lock no longer pins +# org.example:foo at 1.0: run `socket-patch rollback pkg:maven/org.example/foo@1.0`. +# Do not change it to inject_repo(): the build would pass without the patch. +override_repo( + socket_patch_maven, + org_example_foo_1_0 = "socket_patch_org_example_foo_1_0", +) +# <<< socket-patch <<< +"#, + sum = "a".repeat(64) + ); + let lock = "{\"artifacts\": {\"org.example:foo\": {\"shasums\": {\"jar\": \"00\"}, \ + \"version\": \"1.0\"}}, \"repositories\": {\"https://repo1.maven.org/maven2/\": \ + [\"org.example:foo\"]}, \"version\": \"3\"}\n"; + // The pin `list` reads from the block, when there is one. + let hosted = |root: &Path| { + let (code, list) = socket(root, &["list"]); + assert_eq!(code, Some(0), "{list}"); + let events = list["events"].as_array().unwrap().iter(); + let pin = |event: &&serde_json::Value| { + event["purl"] == purl("foo") && event["details"]["mode"] == "hosted" + }; + events + .filter(pin) + .map(|event| event["details"]["lockfiles"].clone()) + .collect::>() + }; + // The pin of a hosted run in the poms of the reactor: the version in + // the module, the repository in the root. + let repository = format!( + " \n \n socket-patch-{FOO_UUID}\n \ + https://patch.socket.dev/patch-registry/maven/token/{FOO_UUID}/maven2\n \ + \n true\n \ + fail\n \n \n \ + false\n \n \n \ + \n" + ); + let pin_poms = |root: &Path| { + for (pom, from, to) in [ + ( + "proj/a/pom.xml", + "1.0<", + "1.0-socket.1d3c1fd2<", + ), + ("proj/pom.xml", "", repository.as_str()), + ] { + let text = std::fs::read_to_string(root.join(pom)).unwrap(); + assert_eq!(text.matches(from).count(), 1, "{pom}"); + write(root, pom, text.replace(from, to).as_bytes()); + } + }; + // The API of the patch record, which the eject of a hosted pin asks + // for. Without a pin in the poms no record is asked for: an eject + // would ask the port of `nowhere` for one. + let runtime = tokio::runtime::Runtime::new().unwrap(); + let api = runtime.block_on(wiremock::MockServer::start()); + let serve_record = |root: &Path| { + let manifest = std::fs::read(root.join("proj/.socket/manifest.json")).unwrap(); + let manifest: serde_json::Value = serde_json::from_slice(&manifest).unwrap(); + let mut view = manifest["patches"][purl("foo")].clone(); + view["purl"] = purl("foo").into(); + view["publishedAt"] = view["exportedAt"].clone(); + let record = wiremock::ResponseTemplate::new(200).set_body_json(view); + let asked = wiremock::Mock::given(wiremock::matchers::method("GET")).respond_with(record); + runtime.block_on(asked.mount(&api)); + api.uri() + }; + let nowhere = "http://127.0.0.1:9".to_string(); + let run = |bazel: bool, in_poms: bool| { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fixture(root, Shape::Reactor, &[("foo", FOO_UUID)]); + let mut pinned_in = Vec::new(); + if bazel { + write(root, "proj/MODULE.bazel", module.as_bytes()); + write(root, "proj/maven_install.json", lock.as_bytes()); + pinned_in.push("MODULE.bazel"); + } + let records = if in_poms { + pin_poms(root); + pinned_in.extend(["a/pom.xml", "pom.xml"]); + serve_record(root) + } else { + nowhere.clone() + }; + let pins = usize::from(bazel || in_poms); + assert_eq!(hosted(root), [serde_json::json!(pinned_in)][..pins]); + let mut steps = Vec::new(); + for args in [&["vendor"][..], &["vendor", "--revert"]] { + let env = ok(root, &[args, &["--proxy-url", &records]].concat()); + let mut tree = snapshot(root); + let module = tree.remove("MODULE.bazel").flatten(); + tree.remove("maven_install.json"); + steps.push((events(&env), env["warnings"].clone(), tree, module)); + // The entry is the hosted pin that is left, and all of it. + let entry = [serde_json::json!(["MODULE.bazel"])]; + assert_eq!(hosted(root), entry[..usize::from(bazel)], "{args:?}"); + } + steps + }; + for in_poms in [false, true] { + let (without, beside) = (run(false, in_poms), run(true, in_poms)); + let vendored = (purl("foo"), "applied".to_string(), String::new()); + assert!(without[0].0.contains(&vendored), "{:?}", without[0].0); + for (beside, without) in beside.iter().zip(&without) { + assert_eq!( + (&beside.0, &beside.1, &beside.2), + (&without.0, &without.1, &without.2), + "{in_poms}" + ); + assert_eq!(beside.3.as_deref(), Some(module.as_bytes()), "{in_poms}"); + } + } +} diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index b1d831d6a..188c8b8d4 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -11,25 +11,49 @@ //! reach what Bazel builds, and [`notices`] says so for each artifact a //! hub builds. //! +//! Hosted mode patches a pinned hub. The hub fetches each jar through a +//! repository of its own, named after the group, the artifact and the +//! version, and Bazel's `override_repo` (7.4.0 and later) puts another +//! repository in its place. So socket-patch keeps one block at the end of +//! the root `MODULE.bazel` ([`BEGIN`]): per patch a repository that +//! downloads the patched jar at its sha256, and an `override_repo` of the +//! hub's one. The hub, its lock, every label and `MODULE.bazel.lock` stay +//! as they are. [`jars`] are the patches of a run that a hub can take, +//! [`site`] says for each whether its entry may be written, [`rewrite`] +//! writes it, [`pins`] reads the block for `list`, `rollback`, `remove` +//! and `vex`, and [`without`] takes an entry out. +//! The block is recognised by its text alone: one that is not, byte for +//! byte, what socket-patch writes for its entries was changed by hand, and +//! is neither written to nor trusted. +//! //! 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. +//! name, the `WORKSPACE` file, what names the Bazel release and the rc +//! files. Nothing is evaluated and no Bazel is run. What cannot be read +//! with certainty is said as such ([`UNREADABLE`]) and never guessed: a +//! jar whose entry cannot be shown to work is declined with a reason. //! //! 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. +//! Bazel without a hub, and what a flag or an rc file outside the checkout +//! tells Bazel. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ops::Range; use std::path::Path; -use super::rc::declared_release; -use super::starlark::{Call, How, Value}; +use super::rc::{declared_release, mentions, ModuleLock}; +use super::starlark::{Bound, Call, How, Value}; use super::workspace::{disk, disk_up_to, Doubt, Entry, Extension, Repo, Tag, Workspace}; use crate::formats::maven::is_variant; +use crate::patch::redirect::{ + bare_sha256_hex, maven_coordinates, DepOverride, RewriteResult, RewriteWarning, +}; +use crate::utils::digest::is_hex64_lower; use crate::utils::fs::run_blocking; +use crate::utils::line_endings::terminator; use crate::utils::purl::{parse_maven_purl, purl_qualifier}; +use crate::vendor::jvm::layout::artifact_path; /// The extension whose tags make a hub. pub const EXTENSION: Extension<'static> = Extension { @@ -45,6 +69,51 @@ pub const HUB_UNPATCHED: &str = "maven_bazel_hub_unpatched"; /// read: a hub may build it. pub const UNREADABLE: &str = "maven_bazel_unreadable"; +/// The warnings of a hosted run for a jar that a hub builds, or may +/// build, and whose entry it does not write. Each says why, and that the +/// Bazel build keeps the upstream jar. With [`UNREADABLE`]: +/// +/// - the project is below the root of its Bazel workspace, where the +/// block belongs; +pub const NOT_AT_ROOT: &str = "maven_bazel_not_at_root"; +/// - a hub has no lock, so Bazel resolves its jars when it builds; +pub const NOT_PINNED: &str = "maven_bazel_not_pinned"; +/// - the Bazel that builds the checkout may have no `override_repo`, or +/// the release of the ruleset, which names the repository, is not known; +pub const RELEASE: &str = "maven_bazel_release"; +/// - the repository of this jar cannot be named, or the patch lacks what +/// an entry holds; +pub const ARTIFACT: &str = "maven_bazel_artifact"; +/// - the build would pass on the upstream jar with the entry in place; +pub const NO_EFFECT: &str = "maven_bazel_no_effect"; +/// - Bazel may not be able to download the patched jar. +pub const DOWNLOAD: &str = "maven_bazel_download"; + +/// The file of the block, and the key under which a hosted run hands +/// [`Site`] to [`rewrite`] among its candidate files: no path of a file. +pub const FILE: &str = "MODULE.bazel"; +pub const SITE_KEY: &str = ""; + +/// The first and the last line of the block. +pub const BEGIN: &str = "# >>> socket-patch: Maven patches for Bazel (managed block: socket-patch \ + writes and removes it) >>>"; +const END: &str = "# <<< socket-patch <<<"; + +/// The releases of rules_jvm_external whose way to name the repository of +/// a jar was read: `escape(coordinates)` in +/// `private/extensions/download_pinned_deps.bzl` from 6.4 to 6.7 and +/// `to_repository_name` in `private/coursier_utilities.bzl` from 6.8 on. +/// No older release is here: none was read for the name or built. The +/// extension is marked reproducible, which keeps it out of +/// `MODULE.bazel.lock`, from 6.2 (`private/extensions/maven.bzl`), and +/// not at 6.0 and 6.1. +const RULESETS: [&str; 10] = [ + "6.4", "6.5", "6.6", "6.7", "6.8", "6.9", "6.10", "7.0", "7.1", "7.2", +]; + +/// What a doubt about a hub without a lock ends with. +const NO_LOCK: &str = "has no `lock_file`"; + /// The largest lock that is read. const MAX_LOCK: usize = 16 << 20; @@ -65,6 +134,33 @@ pub struct Hub { /// 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, + /// The label of the `use_extension` that its first tag is called on, + /// as it is written there. `None` when one of its tags is called on a + /// usage that cannot be read or is isolated: an `override_repo` on + /// another usage does not reach the repositories of that one. + pub proxy: Option, +} + +/// The label of the `use_extension` call behind the proxy that `tag` is +/// called on, when that usage is shared with every other one of the +/// extension (`isolate` is not given, or is `False`) and its label holds +/// nothing a string of the block would have to escape. +fn proxy(ws: &Workspace, tag: &Tag) -> Option { + let (_, file) = ws.files.iter().find(|(path, _)| path == tag.file)?; + let Bound::Call(made) = file.binds.get(tag.call.bind?)?.to else { + return None; + }; + let made = file.calls.get(made)?; + let shared = match made.arg("isolate") { + None => true, + Some(Value::Name(isolate)) => isolate == "False", + Some(_) => false, + }; + let plain = |b: u8| b.is_ascii_alphanumeric() || b"@/:._-+~".contains(&b); + match made.positional(0) { + Some(Value::Str(label)) if shared && label.bytes().all(plain) => Some(label.clone()), + _ => None, + } } const NOT_A_FILE: &str = "the `lock_file` of this hub is not a file of this repository"; @@ -125,15 +221,18 @@ pub fn hubs(ws: &Workspace) -> (Vec, Vec) { continue; } }; - let Some(hub) = hubs.iter().find(|hub| hub.name == name) else { + let proxy = proxy(ws, tag); + let Some(hub) = hubs.iter_mut().find(|hub| hub.name == name) else { hubs.push(Hub { name, file, line, lock, + proxy, }); continue; }; + hub.proxy = hub.proxy.take().filter(|_| proxy.is_some()); 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"); @@ -164,6 +263,11 @@ pub struct Lock { pub format: u8, /// The jar without a classifier of each `group:artifact`. jars: HashMap, + /// The `group:artifact` that a repository of the lock lists. For a jar + /// that only `m2local` gives, the ruleset makes a repository on a + /// machine whose Maven local repository holds the jar, and none on + /// another (`download_pinned_deps` at 6.5 and 7.2). + listed: HashSet, } impl Lock { @@ -212,7 +316,12 @@ impl Lock { (key.matches(':').count() == 1).then_some((key, pinned)) }; let jars = raw.artifacts.into_iter().filter_map(jar).collect(); - Ok(Lock { format, jars }) + let listed = raw.repositories.into_values().flatten().collect(); + Ok(Lock { + format, + jars, + listed, + }) } /// The jar of `group:artifact` without a classifier, when the lock @@ -235,6 +344,18 @@ fn target(coordinates: &str) -> String { /// Why a hub that fetches a jar may not build it. const OVERRIDDEN: &str = "a `maven.override` gives this artifact another target"; +/// What kind of doubt one is: a hosted run gives its warning by it. What +/// the reader itself doubts is [`Kind::Unread`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind<'a> { + /// Something could not be read. + Unread, + /// The hub of this name has no lock. + Unpinned(&'a str), + /// A `maven.override` may put another target in the jar's place. + Overridden, +} + /// Whether Bazel builds an artifact through a hub of the workspace. #[derive(Debug, PartialEq, Eq)] pub enum Built<'a> { @@ -245,7 +366,80 @@ pub enum Built<'a> { /// 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), + Unknown(&'a Doubt, Kind<'a>), +} + +/// What the root module says of the release of the ruleset that Bazel +/// builds with. Bazel takes an override from the root module alone, and +/// before any `bazel_dep` (`applyOverrides`: InterimModule.java at 7.4.0, +/// Discovery.java lines 158 and 159 at 7.7.2, 178 and 179 at 8.8.2 and +/// 9.3.2). +#[derive(Debug, PartialEq, Eq)] +enum Asked { + /// No version is given. + Nothing, + /// A `bazel_dep` asks for this release: Bazel selects it or a newer + /// one that another module asks for. + AtLeast(String), + /// A `single_version_override` pins this release, whatever is asked. + Exactly(String), + /// An override takes the ruleset from no registry (`archive_override`, + /// `git_override`, `local_path_override`), keeps more than one release + /// of it (`multiple_version_override`) or pins a version that is no + /// string: where it is, for a warning. + Unknown(String), +} + +/// A version of a Bazel module in the order Bazel has for them +/// (`Version.java` of `bazel/bzlmod`, the same order at 7.4.0, 7.7.2, +/// 8.8.2 and 9.3.2): by the identifiers between the dots of its release, +/// a number before a word and by its value; a release before a longer one +/// that starts with it; a prerelease before its release; and nothing of +/// what follows a `+`. +fn ordered(version: &str) -> impl Ord + '_ { + fn identifiers(part: &str) -> Vec<(bool, u64, &str)> { + let parts = part.split('.').filter(|id| !id.is_empty()); + let identifier = |id| match str::parse::(id) { + Ok(number) => (false, number, id), + Err(_) => (true, 0, id), + }; + parts.map(identifier).collect() + } + let version = version.split('+').next().unwrap_or(version); + let (release, pre) = version.split_once('-').unwrap_or((version, "")); + (identifiers(release), pre.is_empty(), identifiers(pre)) +} + +/// What the root module of `ws` says of the ruleset's release: by its +/// calls that name the ruleset, a `bazel_dep` and the overrides, which are +/// the functions whose name ends in `_override`. +fn asked(ws: &Workspace) -> Asked { + let named = Some(&Value::Str(EXTENSION.module.to_string())); + let names = |call: &&Call| { + call.bind.is_none() && [call.arg("name"), call.arg("module_name")].contains(&named) + }; + let mut calls = Vec::new(); + for (file, read) in &ws.files { + calls.extend(read.calls.iter().filter(names).map(|call| (file, call))); + } + let version = |callee: &str| { + let call = calls.iter().find(|(_, call)| call.callee == callee); + call.and_then(|(_, call)| call.arg("version")) + }; + let pin = "single_version_override"; + let unknown = |(_, call): &&(&String, &Call)| { + let read = matches!(call.arg("version"), None | Some(Value::Str(_))); + call.callee.ends_with("_override") && (call.callee != pin || !read) + }; + if let Some((file, call)) = calls.iter().find(unknown) { + let at = format!("{file}:{}: with this `{}`", call.line, call.callee); + return Asked::Unknown(at); + } + match (version(pin), version("bazel_dep")) { + (Some(Value::Str(pinned)), _) if !pinned.is_empty() => Asked::Exactly(pinned.clone()), + (_, Some(Value::Str(least))) if !least.is_empty() => Asked::AtLeast(least.clone()), + _ => Asked::Nothing, + } } /// What the hubs of a workspace build: read once, asked per artifact. @@ -259,6 +453,15 @@ pub struct Hubs { overrides: Vec<(Option, Doubt)>, /// The first thing that could not be read. doubt: Option, + /// The hub whose missing lock that doubt is, when it is one. + lockless: Option, + /// The patches of the block in the root `MODULE.bazel`. None when the + /// block was changed by hand, which is a doubt. + pub block: Vec, + /// The line of a block that was changed by hand. + edited: Option, + /// What the root says of the release of the ruleset. + asked: Asked, } impl Hubs { @@ -269,8 +472,38 @@ impl Hubs { /// `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 { + // The block is socket-patch's own: the workspace is read without + // it, as the user wrote it, and with every line where it was. A + // block that was changed by hand is read like any other text. + let (mut block, mut edited, mut hidden) = (Vec::new(), None, None); + if let Entry::Text(module) = view(FILE) { + match find(&module) { + Block::None => {} + Block::Edited(line) => edited = Some(line), + Block::Ours(at, _, patches) => { + let lines = "\n".repeat(module[at.clone()].matches('\n').count()); + let (head, tail) = (&module[..at.start], &module[at.end..]); + hidden = Some(format!("{head}{lines}{tail}")); + block = patches; + } + } + } + let view = |path: &str| match &hidden { + Some(module) if path == FILE => Entry::Text(module.clone()), + _ => view(path), + }; + let view: &dyn Fn(&str) -> Entry = &view; let ws = Workspace::read(view); let (hubs, mut doubts) = hubs(&ws); + doubts.splice( + 0..0, + edited.map(|line| Doubt { + file: FILE.to_string(), + line, + why: "the block that socket-patch keeps there was changed by hand".to_string(), + }), + ); + let asked = asked(&ws); let overrides = ws.tags(&EXTENSION, "override").calls.into_iter(); let overrides = overrides.map(|Tag { file, call, .. }| { let (replaced, why) = match call.arg("coordinates") { @@ -281,7 +514,7 @@ impl Hubs { (replaced, Doubt { file, line, why }) }); let overrides = overrides.collect(); - let mut pinned = Vec::new(); + let (mut pinned, mut lockless) = (Vec::new(), None); for hub in hubs { // Where a doubt about its lock is: the lock, or the tag. let (file, line) = match &hub.lock { @@ -289,14 +522,18 @@ impl Hubs { 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)), + None => Err(format!("hub \"{}\" {NO_LOCK}", 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 }), + Err(why) => { + let first = hub.lock.is_none() && doubts.is_empty(); + lockless = lockless.or(first.then(|| hub.name.clone())); + doubts.push(Doubt { file, line, why }); + } } } let before_9 = || declared_release(view).is_none_or(|release| release < (9, 0, 0)); @@ -324,6 +561,10 @@ impl Hubs { pinned, overrides, doubt: doubts.into_iter().next(), + lockless, + block, + edited, + asked, } } @@ -340,11 +581,704 @@ impl Hubs { 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), + _ if by.is_empty() => self + .doubt() + .map_or(Built::No, |(doubt, kind)| Built::Unknown(doubt, kind)), + Some((Some(_), tag)) => Built::Unknown(tag, Kind::Overridden), + Some((None, tag)) => Built::Unknown(tag, Kind::Unread), None => Built::Yes(by), } } + + /// The first thing that could not be read, and its kind. + fn doubt(&self) -> Option<(&Doubt, Kind<'_>)> { + let unpinned = self.lockless.as_deref().map(Kind::Unpinned); + Some((self.doubt.as_ref()?, unpinned.unwrap_or(Kind::Unread))) + } + + /// [`Hubs::built`] for a run that writes an entry or trusts one: not + /// known either beside a hub that fetches the jar, when anything was + /// not read. That may be another hub that builds the upstream one. + fn sure(&self, group: &str, artifact: &str, version: &str) -> Built<'_> { + match (self.built(group, artifact, version), self.doubt()) { + (Built::Yes(_), Some((doubt, kind))) => Built::Unknown(doubt, kind), + (built, _) => built, + } + } +} + +/// One patch in the block: the jar that takes the place of the one a hub +/// fetches for `group:artifact` at `version`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Patch { + pub group: String, + pub artifact: String, + pub version: String, + pub uuid: String, + /// The sha256 of the patched jar, which Bazel checks its download by. + pub sha256: String, + pub url: String, +} + +impl Patch { + pub fn purl(&self) -> String { + let (group, artifact) = (&self.group, &self.artifact); + format!("pkg:maven/{group}/{artifact}@{}", self.version) + } + + fn repository(&self) -> String { + repository_name(&self.group, &self.artifact, &self.version).unwrap_or_default() + } +} + +/// The name of the repository through which a hub fetches the jar of +/// `group:artifact` at `version`, on every release of [`RULESETS`]: the +/// three joined by `_`, with `_` for each `.` and `-`. `None` for a +/// coordinate with any character but letters, digits, `.`, `_` and `-`: +/// the ruleset's two functions agree, and were read, for those alone. +pub fn repository_name(group: &str, artifact: &str, version: &str) -> Option { + let plain = |b: u8| b.is_ascii_alphanumeric() || b"._-".contains(&b); + let parts = [group, artifact, version]; + let named = |part: &&str| !part.is_empty() && part.bytes().all(plain); + let named = parts.iter().all(named); + named.then(|| parts.join("_").replace(['.', '-'], "_")) +} + +/// The block for `patches` under the label of the hub's `use_extension`, +/// from [`BEGIN`] to [`END`], with a line feed between its lines: the +/// patches by the name of their repository, each with an `override_repo` +/// of its own, so that Bazel names the line of the one entry whose jar +/// the hub's lock no longer pins. `bazel mod tidy` keeps this text. +fn render(label: &str, patches: &[Patch]) -> String { + let entry = |patch: &Patch| { + let (group, artifact, version) = (&patch.group, &patch.artifact, &patch.version); + let (name, purl, uuid) = (patch.repository(), patch.purl(), &patch.uuid); + let (sha256, url) = (&patch.sha256, &patch.url); + let file = artifact_path(group, artifact, version, None, "jar"); + format!( + "# {purl}, Socket patch {uuid}\n\ + socket_patch_http_file(\n \ + name = \"socket_patch_{name}\",\n \ + downloaded_file_path = \"v1/{file}\",\n \ + sha256 = \"{sha256}\",\n \ + urls = [\"{url}\"],\n)\n\n\ + # If Bazel stops at the next line (\"does not generate repository\"), the hub's \ + lock no longer pins\n\ + # {group}:{artifact} at {version}: run `socket-patch rollback {purl}`.\n\ + # Do not change it to inject_repo(): the build would pass without the patch.\n\ + override_repo(\n socket_patch_maven,\n \ + {name} = \"socket_patch_{name}\",\n)\n" + ) + }; + let mut patches: Vec<&Patch> = patches.iter().collect(); + patches.sort_by_key(|patch| patch.repository()); + let entries: Vec = patches.into_iter().map(entry).collect(); + format!( + "{BEGIN}\nsocket_patch_http_file = use_repo_rule(\ + \"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_file\")\n\n\ + socket_patch_maven = use_extension(\"{label}\", \"maven\")\n\n{}{END}", + entries.join("\n") + ) +} + +/// The label and the patches that the lines of a block name, when each +/// patch has every field. +fn parse(body: &str) -> Option<(String, Vec)> { + let lines: Vec<&str> = body.lines().collect(); + let between = |line: &str, open: &str, close: &str| { + Some(line.strip_prefix(open)?.strip_suffix(close)?.to_string()) + }; + let proxy = ("socket_patch_maven = use_extension(\"", "\", \"maven\")"); + let label = lines + .iter() + .find_map(|line| between(line, proxy.0, proxy.1))?; + let mut patches = Vec::new(); + for (at, line) in lines.iter().enumerate() { + let Some(named) = line.strip_prefix("# pkg:maven/") else { + continue; + }; + let (coordinates, uuid) = named.split_once(", Socket patch ")?; + let (name, version) = coordinates.rsplit_once('@')?; + let (group, artifact) = name.split_once('/')?; + let field = |open: &str, close: &str| { + let below = lines.get(at + 1..)?.iter().take(6); + below.copied().find_map(|line| between(line, open, close)) + }; + patches.push(Patch { + group: group.to_string(), + artifact: artifact.to_string(), + version: version.to_string(), + uuid: uuid.to_string(), + sha256: field(" sha256 = \"", "\",")?, + url: field(" urls = [\"", "\"],")?, + }); + } + Some((label, patches)) +} + +/// What a `MODULE.bazel` holds of the block. +#[derive(Debug, PartialEq, Eq)] +enum Block { + None, + /// The block as socket-patch writes it: where it is, from the first + /// byte of [`BEGIN`] to the last of [`END`], its label and its patches. + Ours(Range, String, Vec), + /// A block that is not what socket-patch writes for the patches it + /// names: the line of its [`BEGIN`]. + Edited(usize), +} + +/// Whether `line` is the first line of a block, as it is written or +/// touched (a blank after it, another end): [`BEGIN`] up to its bracket. +/// A file without such a line holds no block. +pub fn begins(line: &str) -> bool { + let mark = BEGIN.split(" (").next().unwrap_or(BEGIN); + line.trim_start().starts_with(mark) +} + +fn find(text: &str) -> Block { + let (mut at, mut begin, mut end) = (0, None, None); + for (line, whole) in text.split_inclusive('\n').enumerate() { + let bare = whole.strip_suffix('\n').unwrap_or(whole); + let bare = bare.strip_suffix('\r').unwrap_or(bare); + match (bare, begin, end) { + (BEGIN, None, _) => begin = Some((at, line + 1)), + // A second first line, or one that is not as it is written. + _ if begins(bare) => { + return Block::Edited(begin.map_or(line + 1, |(_, first)| first)); + } + (END, Some(_), None) => end = Some(at + bare.len()), + _ => {} + } + at += whole.len(); + } + let Some((start, line)) = begin else { + return Block::None; + }; + // In the line break of its own lines, whatever the rest of a file + // with both has. + let ours = end.and_then(|end| { + let (label, entries) = parse(&text[start..end])?; + let written = render(&label, &entries).replace('\n', terminator(&text[start..end])); + (written == text[start..end]).then_some((start..end, label, entries)) + }); + ours.map_or(Block::Edited(line), |(at, label, patches)| { + Block::Ours(at, label, patches) + }) +} + +/// `module` with `patch` in its block, in the place of any patch for the +/// same repository: in the block that is there, in the line break of its +/// lines, or in a new one at the end of the file, after one blank line, +/// in the line break of the file ([`terminator`]: the more frequent one +/// of a file with both). A file whose last line has no line break gets a +/// block without one, so that [`without`] can tell. `None` when the block +/// that is there was changed by hand. +fn with_patch(module: &str, label: &str, patch: Patch) -> Option { + let (at, mut patches) = match find(module) { + Block::Edited(_) => return None, + Block::None => (None, Vec::new()), + Block::Ours(at, _, patches) => (Some(at), patches), + }; + patches.retain(|other| other.repository() != patch.repository()); + patches.push(patch); + let ended = module.is_empty() || module.ends_with('\n'); + let eol = terminator(at.as_ref().map_or(module, |at| &module[at.clone()])); + let block = render(label, &patches).replace('\n', eol); + Some(match at { + Some(at) => format!("{}{block}{}", &module[..at.start], &module[at.end..]), + None if ended => format!("{module}{eol}{block}{eol}"), + None => format!("{module}{eol}{eol}{block}"), + }) +} + +/// `module` without the patches of its block that `gone` names. With the +/// last one the block goes, and what [`with_patch`] put before it: the +/// file is then byte for byte what it was before its first patch. `None` +/// when the block is not there as socket-patch writes it. +pub fn without(module: &str, gone: &mut dyn FnMut(&Patch) -> bool) -> Option { + let Block::Ours(at, label, mut entries) = find(module) else { + return None; + }; + entries.retain(|patch| !gone(patch)); + let (head, tail) = (&module[..at.start], &module[at.end..]); + if !entries.is_empty() { + let block = render(&label, &entries).replace('\n', terminator(&module[at])); + return Some(format!("{head}{block}{tail}")); + } + // The line break before the block and, when it ends a blank line, that + // line; then the block's own line break or, for a block that ends the + // file without one, the one that was added to the last line. A line + // break is one of either kind: a file can have both. + let cut = + |text: &str| text.len() - text.ends_with('\n') as usize - text.ends_with("\r\n") as usize; + let blank = |head: &str| cut(head) == 0 || head[..cut(head)].ends_with('\n'); + let after = tail.strip_prefix('\r').unwrap_or(tail).strip_prefix('\n'); + let (head, tail) = match after { + Some(tail) if blank(head) => (&head[..cut(head)], tail), + None if tail.is_empty() && blank(head) => (&head[..cut(&head[..cut(head)])], tail), + Some(tail) => (head, tail), + None => (head, tail), + }; + Some(format!("{head}{tail}")) +} + +/// What a hosted run does in the root `MODULE.bazel` for one patch. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Verdict { + /// Its entry is written, under this label for the block's + /// `use_extension`; or nothing is written: the code of the warning, + /// and why. + pub entry: Result, + /// The id of the patch whose entry the block of the root holds for + /// the jar of this one, when it holds one. + pub held: Option, +} + +/// The verdict for each patch whose jar a hub builds or may build, by the +/// id of the patch. A patch whose jar no hub builds has none, and neither +/// has one that is not among the [`jars`] of the run. +pub type Site = BTreeMap; + +/// A patch of the plain jar of an artifact: its id, and the group, the +/// artifact and the version of the jar. +pub type Jar = (String, String, String, String); + +/// A code of this module, and why. +type Declined = (&'static str, String); + +/// What a warning says after the reason, when the block holds no entry +/// for the jar. +const KEEPS: &str = "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps \ + the upstream jar"; + +/// Why no entry is written for a jar that a hub may build. +fn unknown(doubt: &Doubt, kind: Kind) -> Declined { + let Doubt { file, line, why } = doubt; + let at = match line { + 0 => file.clone(), + line => format!("{file}:{line}"), + }; + match kind { + Kind::Unpinned(hub) => { + let why = format!( + "{at}: {why}, so Bazel resolves its jars when it builds and none can be \ + replaced: give the hub a `lock_file` and pin it (`REPIN=1 bazel run \ + @{hub}//:pin`)" + ); + (NOT_PINNED, why) + } + Kind::Overridden => { + let remedy = "patch that target, or remove the override"; + let why = format!("{at}: {why}, so Bazel would not build a patched jar: {remedy}"); + (NO_EFFECT, why) + } + Kind::Unread => { + let why = format!( + "socket-patch could not tell whether Bazel takes this artifact from a \ + rules_jvm_external hub: {at}: {why}" + ); + (UNREADABLE, why) + } + } +} + +/// What in the rc files of the checkout stands against an entry, for the +/// Bazel `release` the checkout names, in the order it is read: an option +/// that leaves the entry without effect ([`NO_EFFECT`]) or its jar out of +/// reach ([`DOWNLOAD`]), or an rc file that cannot be read +/// ([`UNREADABLE`]), which may hold either. +fn rc(view: &dyn Fn(&str) -> Entry, release: Option) -> Vec { + let flags = [ + "ignore_dev_dependency", + "enable_bzlmod", + "downloader_config", + "repository_disable_download", + "vendor_dir", + ]; + let against = |(file, line, word): (String, usize, String)| { + // On or off as Bazel reads a boolean option (`BooleanConverter` + // in Converters.java at 7.4.0, 7.7.2, 8.8.2 and 9.3.2): by a `no` + // before its name, or by a value, in any case. + let (name, value) = word.split_once('=').unwrap_or((&word, "")); + let (given, value) = (word.contains('='), value.to_ascii_lowercase()); + let is = |values: [&str; 5]| values.contains(&&*value); + let no = name.starts_with("--no"); + let on = name.starts_with("--") && !no && (!given || is(["true", "1", "yes", "t", "y"])); + let off = (no && !given) || (!no && is(["false", "0", "no", "f", "n"])); + let bzlmod = word.contains(flags[1]); + let valued = word.contains(flags[2]) || word.contains(flags[4]); + // What changes nothing: Bzlmod switched on, which Bazel 9 always + // has, and another option switched off. A word that is neither + // for certain is taken for the one that does harm. + let always = release.is_some_and(|r| r >= (9, 0, 0)); + if (bzlmod && (on || always)) || (!bzlmod && !valued && off) { + return None; + } + let (code, why) = match (bzlmod, word.contains(flags[0])) { + (true, _) => ( + NO_EFFECT, + "which switches off the file an entry is written to", + ), + (_, true) => (NO_EFFECT, "under which Bazel can drop the tags of a hub"), + _ => ( + DOWNLOAD, + "under which Bazel may not download the patched jar from the Socket patch host", + ), + }; + Some((code, format!("{file}:{line} names `{word}`, {why}"))) + }; + match mentions(view, &flags) { + Ok(found) => found.into_iter().filter_map(against).collect(), + Err(file) => { + let why = format!("the rc file {file} cannot be read, and may switch an entry off"); + vec![(UNREADABLE, why)] + } + } +} + +/// What must hold of the workspace at `root` for any entry: the file can +/// be written, Bazel has `override_repo`, the release of the ruleset is +/// one of [`RULESETS`], and no rc file switches an entry off. +fn settings( + root: &Path, + view: &dyn Fn(&str) -> Entry, + locks: &dyn Fn(&str) -> Entry, + asked: &Asked, +) -> Result<(), Declined> { + let link = std::fs::symlink_metadata(root.join(FILE)).is_ok_and(|meta| meta.is_symlink()); + if link { + let why = format!("{FILE} is a symbolic link, which socket-patch does not write through"); + return Err((UNREADABLE, why)); + } + let lock = match locks("MODULE.bazel.lock") { + Entry::Text(lock) => ModuleLock::parse(&lock), + _ => ModuleLock::default(), + }; + let release = declared_release(view); + match release { + Some((major, minor, patch)) if (major, minor, patch) < (7, 4, 0) => { + let why = format!( + "the checkout names Bazel {major}.{minor}.{patch} (`.bazeliskrc` or \ + `.bazelversion`), and an entry needs `override_repo`, which Bazel has from 7.4.0" + ); + return Err((RELEASE, why)); + } + None if lock.version.is_none_or(|version| version < 13) => { + let why = "no file of the checkout says that Bazel 7.4.0 or later builds it, and an \ + older Bazel fails on the `override_repo` an entry needs: name the release \ + in `.bazelversion`"; + return Err((RELEASE, why.to_string())); + } + _ => {} + } + // A lock that holds another release than the root now takes is one + // that Bazel has not written since: older than what is asked for, or + // any other than the one a `single_version_override` pins. + let module = EXTENSION.module; + let stale = |selected: &str| match asked { + Asked::Exactly(pinned) => ordered(pinned) != ordered(selected), + Asked::AtLeast(least) => ordered(least) > ordered(selected), + Asked::Nothing | Asked::Unknown(_) => false, + }; + let wanted = match asked { + Asked::Exactly(wanted) | Asked::AtLeast(wanted) => wanted.as_str(), + Asked::Nothing | Asked::Unknown(_) => "", + }; + let why = match (asked, &lock.selected(module)[..]) { + (Asked::Unknown(at), _) => format!( + "{at} of {module} socket-patch cannot tell which release of the ruleset Bazel \ + builds with, and the name of a jar's repository depends on it" + ), + (_, [selected]) if !RULESETS.contains(selected) => format!( + "Bazel selected {module} {selected}, and how the ruleset names the repository of a \ + jar is known for its releases 6.4 to 7.2: update socket-patch" + ), + (_, [selected]) if stale(selected) => format!( + "{FILE} asks for {module} {wanted} and MODULE.bazel.lock holds {selected}: build once \ + so that Bazel updates its lock" + ), + (_, [_]) => return rc(view, release).into_iter().next().map_or(Ok(()), Err), + _ => format!( + "MODULE.bazel.lock does not say which release of {module} Bazel selected, and the \ + name of a jar's repository depends on it: build once so that Bazel writes its lock" + ), + }; + Err((RELEASE, why)) +} + +impl Hubs { + /// The label for the block of the jar of `group:artifact` at + /// `version`, which a pinned hub fetches, or why no entry for it can + /// be written. + fn label(&self, group: &str, artifact: &str, version: &str) -> Result { + let (key, mut label) = (format!("{group}:{artifact}"), None); + if repository_name(group, artifact, version).is_none() { + let why = format!( + "the repository a hub fetches {key}:{version} through has a name socket-patch \ + knows only for coordinates of letters, digits, `.`, `_` and `-`" + ); + return Err((ARTIFACT, why)); + } + let fetches = |lock: &Lock| { + let jar = lock.plain_jar(group, artifact); + jar.is_some_and(|jar| jar.fetched && jar.version == version) + }; + for (hub, lock) in self.pinned.iter().filter(|(_, lock)| fetches(lock)) { + let from = hub.lock.as_deref().unwrap_or_default(); + if !lock.listed.contains(&key) { + let why = format!( + "{from} lists no repository for {key}: the hub takes the jar from the Maven \ + local repository, and on a machine without it there is no repository for \ + an entry to replace" + ); + return Err((ARTIFACT, why)); + } + let Some(proxy) = &hub.proxy else { + let why = format!( + "{}:{}: a tag of hub \"{}\" is called on a `use_extension` that is isolated \ + or cannot be read, which no `override_repo` of another usage reaches", + hub.file, hub.line, hub.name + ); + return Err((UNREADABLE, why)); + }; + label.get_or_insert_with(|| proxy.clone()); + } + label.ok_or_else(|| (UNREADABLE, format!("no hub that fetches {key} was read"))) + } +} + +/// Whether the Maven purl names the jar a lock names by group and +/// artifact alone: one without a classifier, of no other packaging. +fn plain(purl: &str) -> bool { + !is_variant( + purl_qualifier(purl, "type"), + purl_qualifier(purl, "classifier"), + ) +} + +/// The plain jars among the patches of a hosted run, each given by its +/// purl and its grant, under the group and the artifact the pom lane pins +/// ([`maven_coordinates`]). A patch of a jar with a classifier, or of +/// another packaging, is none: [`site`] has no verdict for it, so +/// [`rewrite`] writes no entry for it and the hub confirms nothing of it, +/// whatever patch of the plain jar runs beside it. +pub fn jars<'a>(patches: impl Iterator) -> Vec { + let jar = |(purl, dep): (&str, &DepOverride)| { + let (_, group, artifact) = maven_coordinates(dep); + let jar = (dep.patch_uuid.clone(), group, artifact, dep.version.clone()); + (dep.ecosystem == "maven" && plain(purl)).then_some(jar) + }; + patches.filter_map(jar).collect() +} + +/// What a hosted run in `project` may write for each of `jars`: read once +/// per run from the checkout. `module` is the text of the project's own +/// `MODULE.bazel` as the run has it, when it has read it. Empty for a +/// project in no Bazel workspace and when no hub builds, or may build, +/// any of the jars: nothing changes for such a run. An entry is written +/// only when nothing of the workspace's hubs is in doubt: a hub without a +/// lock, or one that could not be read, may build the upstream jar beside +/// the hub that would get the patched one. A project below the root gets +/// no entry: the root is read all the same, for what its block holds. +pub fn site(project: &Path, module: Option<&str>, jars: &[Jar]) -> Site { + let mut site = Site::new(); + let Some(root) = super::bazel_root(project) else { + return site; + }; + let at_root = root.project.as_os_str().is_empty(); + let on_disk = disk(&root.dir); + let view = |path: &str| match module { + Some(module) if at_root && path == FILE => Entry::Text(module.to_string()), + _ => on_disk(path), + }; + let locks = disk_up_to(&root.dir, MAX_LOCK); + let hubs = Hubs::read(&view, &locks); + // What holds for every jar is asked once, and only for a jar a hub builds. + let mut workspace = None; + for (uuid, group, artifact, version) in jars { + let entry = match hubs.sure(group, artifact, version) { + Built::No => continue, + Built::Unknown(doubt, kind) => Err(unknown(doubt, kind)), + Built::Yes(_) if !at_root => { + let why = format!( + "a hub of the Bazel workspace at {} builds this artifact, and this project \ + is not its root, where the patch of a hub is written: run the command there", + root.dir.display() + ); + Err((NOT_AT_ROOT, why)) + } + Built::Yes(_) => hubs.label(group, artifact, version).and_then(|label| { + let all = workspace + .get_or_insert_with(|| settings(&root.dir, &view, &locks, &hubs.asked)); + all.clone().map(|()| label) + }), + }; + let jar = |patch: &&Patch| { + (&patch.group, &patch.artifact, &patch.version) == (group, artifact, version) + }; + let verdict = Verdict { + entry: entry.map_err(|(code, why)| (code.to_string(), why)), + held: hubs.block.iter().find(jar).map(|patch| patch.uuid.clone()), + }; + site.insert(uuid.clone(), verdict); + } + site +} + +/// The [`Site`] among the candidate files of a hosted run: empty without +/// one. The pom lane asks it which patches a hub decides, and says "no +/// pom.xml" of the others alone. +pub fn handed(files: &BTreeMap) -> Site { + let site = files.get(SITE_KEY).map(|site| serde_json::from_str(site)); + site.and_then(Result::ok).unwrap_or_default() +} + +/// The hosted lane for the hubs of a Bazel workspace, after the pom lane: +/// for each patch of `overrides` that the [`Site`] among `files` has a +/// verdict for, its entry in the block of `MODULE.bazel`, or the warning +/// that says why there is none and what the block holds for the jar. A +/// patch whose entry is in the block, written now or before, is +/// confirmed. Without a site nothing is done. +pub fn rewrite( + files: &BTreeMap, + overrides: &[DepOverride], + result: &mut RewriteResult, +) { + let site = handed(files); + let mut module = files.get(FILE).cloned(); + // The file of the block: not the project's own below the Bazel root. + let file = match module { + Some(_) => FILE.to_string(), + None => format!("the {FILE} at the root"), + }; + for dep in overrides { + let Some(verdict) = site.get(&dep.patch_uuid) else { + continue; + }; + let (maven2, group, artifact) = maven_coordinates(dep); + let purl = format!("pkg:maven/{group}/{artifact}@{}", dep.version); + let written = verdict.entry.clone().and_then(|label| { + let incomplete = |what: &str| (ARTIFACT.to_string(), what.to_string()); + let suffixed = maven2.and_then(|ov| ov.identifiers.maven_suffixed_version.as_deref()); + let sha256 = dep.integrity.sha256.as_deref().map(bare_sha256_hex); + let sha256 = sha256.filter(|sum| is_hex64_lower(sum)); + let (Some(ov), Some(suffixed), Some(sha256)) = (maven2, suffixed, sha256) else { + let what = "the patch comes without the version its jar is served under, or \ + without the jar's sha256"; + return Err(incomplete(what)); + }; + let file = artifact_path(&group, &artifact, suffixed, None, "jar"); + let url = format!("{}/{file}", ov.index_url.trim_end_matches('/')); + let quoted = |b: u8| !b.is_ascii_graphic() || b == b'"' || b == b'\\'; + if url.bytes().chain(dep.patch_uuid.bytes()).any(quoted) { + return Err(incomplete( + "the URL of the patched jar cannot stand in a string", + )); + } + let patch = Patch { + group: group.clone(), + artifact: artifact.clone(), + version: dep.version.clone(), + uuid: dep.patch_uuid.clone(), + sha256, + url, + }; + let module = module + .as_deref() + .and_then(|module| with_patch(module, &label, patch)); + module.ok_or_else(|| incomplete("the block there cannot be written to")) + }); + let (code, why) = match written { + Ok(text) => { + module = Some(text); + result + .confirmed_bazel_maven_uuids + .insert(dep.patch_uuid.clone()); + continue; + } + Err(declined) => declined, + }; + // What the Bazel build has of the jar: nothing of socket-patch's, + // the entry of this patch from an earlier run, which is still its + // pin, or the entry of another patch, which is not this run's to + // take out. An entry that the reason of the decline leaves without + // effect is no pin: the patch is not reported as applied for it. + let ends = match verdict.held.as_deref() { + None => KEEPS.to_string(), + Some(held) if held == dep.patch_uuid && code == NO_EFFECT => format!( + "socket-patch left the entry that {file} holds for it as it is, and while that \ + stands the entry has no effect: the Bazel build keeps the upstream jar" + ), + Some(held) if held == dep.patch_uuid => { + let uuid = dep.patch_uuid.clone(); + result.confirmed_bazel_maven_uuids.insert(uuid); + format!("socket-patch left the entry that {file} holds for it as it is") + } + Some(held) => format!( + "socket-patch wrote nothing to {file} for it: the entry of patch {held} remains \ + there, and where the block is in effect the Bazel build takes that patch's jar" + ), + }; + let detail = format!("{purl}: {why}. {ends}"); + result.warnings.push(RewriteWarning { code, detail }); + } + if let Some(module) = module.filter(|module| Some(module) != files.get(FILE)) { + result.files.insert(FILE.to_string(), module); + } +} + +/// A patch of the block, as lockfile discovery reads it. +#[derive(Debug, PartialEq, Eq)] +pub struct Pin { + pub patch: Patch, + /// Why a Bazel build may pass without the jar of this entry: no pinned + /// hub fetches the artifact at that version any more (Bazel then + /// stops at the entry), it cannot be read whether one does, or an rc + /// file switches the entry off, or cannot be read and so may. `None`: + /// a build takes the patched jar, or fails. + pub unbuilt: Option, +} + +/// The patches in the block of `module`, the text of the `MODULE.bazel` +/// at the Bazel root `root`, or why the block is no record of any: it was +/// changed by hand. +pub fn pins(root: &Path, module: &str) -> Result, String> { + let on_disk = disk(root); + let view = |path: &str| match path { + FILE => Entry::Text(module.to_string()), + _ => on_disk(path), + }; + let hubs = Hubs::read(&view, &disk_up_to(root, MAX_LOCK)); + if let Some(line) = hubs.edited { + return Err(format!( + "{FILE}:{line}: the block that socket-patch keeps there was changed by hand" + )); + } + // Everything the rc files hold is read: an option under which a + // download may fail leaves a build that takes the patched jar or + // fails, and the first of the others is why an entry is not built. + let against = rc(&view, declared_release(&view)).into_iter(); + let off = { against }.find_map(|(code, why)| (code != DOWNLOAD).then_some(why)); + let pin = |patch: &Patch| { + let Patch { + group, + artifact, + version, + .. + } = patch; + let unbuilt = match hubs.sure(group, artifact, version) { + Built::Yes(_) => off.clone(), + Built::Unknown(doubt, kind) => Some(unknown(doubt, kind).1), + Built::No => Some(format!( + "no pinned hub takes {group}:{artifact} at {version} any more, so Bazel stops \ + at its entry" + )), + }; + let patch = patch.clone(); + Pin { patch, unbuilt } + }; + Ok(hubs.block.iter().map(pin).collect()) } /// The warnings for the patches `purls` of a command that ran in @@ -360,15 +1294,7 @@ pub async fn notices(project: &Path, purls: Vec) -> Vec<(&'static str, S 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 jar = |purl| Some((purl, parse_maven_purl(purl).filter(|_| plain(purl))?)); 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 { @@ -377,8 +1303,13 @@ fn notices_blocking(project: &Path, mut purls: Vec) -> Vec<(&'static str let hubs = Hubs::read(&disk(&root.dir), &disk_up_to(&root.dir, MAX_LOCK)); let mut said = Vec::new(); for (purl, (group, artifact, version)) in jars { + let in_block = |patch: &Patch| { + (&*patch.group, &*patch.artifact, &*patch.version) == (&*group, &*artifact, &*version) + }; let (code, detail) = match hubs.built(&group, &artifact, &version) { Built::No => continue, + // Bazel takes the jar of the block's entry. + Built::Yes(_) if hubs.block.iter().any(in_block) => continue, Built::Yes(by) => { let from = |(hub, _): &(&Hub, &Pinned)| { let (lock, name) = (hub.lock.as_deref().unwrap_or_default(), &hub.name); @@ -387,14 +1318,15 @@ fn notices_blocking(project: &Path, mut purls: Vec) -> Vec<(&'static str }; 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" + "Bazel takes this artifact from {from}, which pins the upstream jar, and \ + this command does not patch a rules_jvm_external hub: the Bazel build \ + stays unpatched whatever it did for another build of the checkout. \ + `socket-patch get {purl} --mode hosted` at the Bazel root patches a \ + pinned hub" ); (HUB_UNPATCHED, detail) } - Built::Unknown(Doubt { file, line, why }) => { + Built::Unknown(Doubt { file, line, why }, _) => { let at = match line { 0 => file.clone(), line => format!("{file}:{line}"), @@ -412,9 +1344,19 @@ fn notices_blocking(project: &Path, mut purls: Vec) -> Vec<(&'static str } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; + /// For the tests of what reads the block elsewhere: the `MODULE.bazel` + /// of a checkout whose pinned hub fetches netty's jar, the lock of + /// that hub, and the same `MODULE.bazel` with the block for a patch + /// `uuid` of that jar. + pub(crate) fn sample(uuid: &str) -> [String; 3] { + let patch = patch("netty-tcnative-classes", uuid); + let ours = with_patch(PINNED, LABEL, patch).expect("a block"); + [PINNED.to_string(), lock_72(), ours] + } + /// A pinned hub, as teams write one. const PINNED: &str = r#"bazel_dep(name = "rules_jvm_external", version = "7.2") @@ -546,7 +1488,7 @@ use_repo(maven, "maven") 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), + Built::Unknown(doubt, _) => format!("{}:{}: {}", doubt.file, doubt.line, doubt.why), }; said } @@ -1027,7 +1969,7 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") 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) = + let Built::Unknown(doubt, Kind::Unread) = hubs.built("io.netty", "netty-tcnative-classes", "2.0.61.Final") else { panic!("read"); @@ -1126,9 +2068,10 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") 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" + `maven.install` at MODULE.bazel:4), which pins the upstream jar, and this command \ + does not patch a rules_jvm_external hub: the Bazel build stays unpatched whatever \ + it did for another build of the checkout. `socket-patch get {NETTY_PURL} --mode \ + hosted` at the Bazel root patches a pinned hub" ); assert_eq!(said, [(HUB_UNPATCHED, detail.clone())]); // The same for a project below the Bazel root of its checkout. @@ -1228,4 +2171,1229 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") assert_eq!(notices_blocking(broken.path(), others), []); assert_eq!(notices_blocking(broken.path(), Vec::new()), []); } + + // The block, and what a hosted run writes of it. + + const NETTY_UUID: &str = "0e77a000-0000-4000-8000-0000000000a1"; + const OTHER_UUID: &str = "0e77a000-0000-4000-8000-0000000000b2"; + + /// A patch of `io.netty:` at the version of the locks. + fn patch(artifact: &str, uuid: &str) -> Patch { + let served = format!("2.0.61.Final-socket.{}", &uuid[..8]); + Patch { + group: "io.netty".to_string(), + artifact: artifact.to_string(), + version: "2.0.61.Final".to_string(), + uuid: uuid.to_string(), + sha256: "5".repeat(64), + url: format!( + "https://patch.socket.dev/patch-registry/maven/token/{uuid}/maven2/io/netty/\ + {artifact}/{served}/{artifact}-{served}.jar" + ), + } + } + + fn netty() -> Patch { + patch("netty-tcnative-classes", NETTY_UUID) + } + + /// The block of [`netty`], as it stands in a file: the measured text, + /// with the remedy that this release has for a stale entry. + const BLOCK: &str = r#"# >>> socket-patch: Maven patches for Bazel (managed block: socket-patch writes and removes it) >>> +socket_patch_http_file = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") + +socket_patch_maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") + +# pkg:maven/io.netty/netty-tcnative-classes@2.0.61.Final, Socket patch 0e77a000-0000-4000-8000-0000000000a1 +socket_patch_http_file( + name = "socket_patch_io_netty_netty_tcnative_classes_2_0_61_Final", + downloaded_file_path = "v1/io/netty/netty-tcnative-classes/2.0.61.Final/netty-tcnative-classes-2.0.61.Final.jar", + sha256 = "5555555555555555555555555555555555555555555555555555555555555555", + urls = ["https://patch.socket.dev/patch-registry/maven/token/0e77a000-0000-4000-8000-0000000000a1/maven2/io/netty/netty-tcnative-classes/2.0.61.Final-socket.0e77a000/netty-tcnative-classes-2.0.61.Final-socket.0e77a000.jar"], +) + +# If Bazel stops at the next line ("does not generate repository"), the hub's lock no longer pins +# io.netty:netty-tcnative-classes at 2.0.61.Final: run `socket-patch rollback pkg:maven/io.netty/netty-tcnative-classes@2.0.61.Final`. +# Do not change it to inject_repo(): the build would pass without the patch. +override_repo( + socket_patch_maven, + io_netty_netty_tcnative_classes_2_0_61_Final = "socket_patch_io_netty_netty_tcnative_classes_2_0_61_Final", +) +# <<< socket-patch <<<"#; + + const LABEL: &str = "@rules_jvm_external//:extensions.bzl"; + + /// `escape` of the ruleset's `download_pinned_deps.bzl` (6.4 to 6.7) + /// and `to_repository_name` of `coursier_utilities.bzl` (6.8 to 7.2) + /// give one name for a jar whose coordinates hold letters, digits, + /// `.`, `_` and `-`. Another character has no name here: the two + /// differ over `$`, and none was read for the rest. + #[test] + fn a_repository_is_named_only_where_every_ruleset_release_agrees() { + for ((group, artifact, version), name) in [ + ( + ("dev.socket.fixture", "victim", "1.10.0"), + Some("dev_socket_fixture_victim_1_10_0"), + ), + ( + ("com.google.guava", "guava", "31.1-jre"), + Some("com_google_guava_guava_31_1_jre"), + ), + ( + ("org.scala-lang", "scala_library", "2.13.12"), + Some("org_scala_lang_scala_library_2_13_12"), + ), + (("g", "a$b", "1"), None), + (("g", "a", "1+build.2"), None), + (("g", "a", "[1,2)"), None), + (("g", "a:jar:tests", "1"), None), + (("g", "a b", "1"), None), + (("g\u{e9}", "a", "1"), None), + (("g", "", "1"), None), + (("", "a", "1"), None), + (("g", "a", ""), None), + ] { + let named = repository_name(group, artifact, version); + assert_eq!(named.as_deref(), name, "{group}:{artifact}:{version}"); + } + } + + /// The text of the block is fixed: it is how the block is recognised. + #[test] + fn the_block_is_written_as_it_was_measured() { + assert_eq!(render(LABEL, &[netty()]), BLOCK); + assert_eq!( + parse(BLOCK), + Some((LABEL.to_string(), vec![netty()])), + "what is written is what is read" + ); + // Each patch has its own `override_repo`, and they stand by the + // name of their repository whatever the order they came in. + let other = patch("netty-tcnative-boringssl-static", OTHER_UUID); + let both = render("@rje//:extensions.bzl", &[netty(), other.clone()]); + assert_eq!(both, render("@rje//:extensions.bzl", &[other, netty()])); + let at = |text: &str| both.find(text).expect(text); + assert!(at(OTHER_UUID) < at(NETTY_UUID), "{both}"); + assert_eq!(both.matches("\noverride_repo(\n").count(), 2, "{both}"); + assert_eq!(both.matches("use_repo_rule(").count(), 1, "{both}"); + assert!( + both.contains("use_extension(\"@rje//:extensions.bzl\", \"maven\")"), + "{both}" + ); + } + + /// The files a block is added to: with and without a last line break, + /// with blank lines at the end, with either line break, and with + /// both: the other one on the first line, or on the last. + fn modules() -> Vec { + let ends = ["\n", "", "\n\n\n"].map(|end| format!("{}{end}", PINNED.trim_end())); + let crlf = ends.iter().map(|module| module.replace('\n', "\r\n")); + let first = ends[..2] + .iter() + .map(|module| module.replacen('\n', "\r\n", 1)); + let last = [format!("{}\r\n", PINNED.trim_end())]; + let both = first.chain(last); + ends.iter().cloned().chain(crlf).chain(both).collect() + } + + #[test] + fn a_patch_is_added_once_and_taken_out_to_the_byte() { + for module in modules() { + let eol = terminator(&module); + let one = with_patch(&module, LABEL, netty()).expect("a block"); + // After one blank line, in the line break of the file: the + // more frequent one of a file with both. + let block = BLOCK.replace('\n', eol); + let ended = module.ends_with('\n'); + let expected = match ended { + true => format!("{module}{eol}{block}{eol}"), + false => format!("{module}{eol}{eol}{block}"), + }; + assert_eq!(one, expected, "{module:?}"); + let crlf = module.matches("\r\n").count(); + let more = crlf > module.matches('\n').count() - crlf; + assert_eq!(more, eol == "\r\n", "{module:?}"); + let added = &one[module.len()..]; + assert_eq!( + added.matches('\n').count(), + added.matches(eol).count(), + "{module:?}" + ); + // Again, and with the same patch under a newer id: one entry. + assert_eq!(with_patch(&one, LABEL, netty()), Some(one.clone())); + let newer = with_patch(&one, LABEL, patch("netty-tcnative-classes", OTHER_UUID)); + let newer = newer.expect("a block"); + assert!( + !newer.contains(NETTY_UUID) && newer.contains(OTHER_UUID), + "{newer}" + ); + assert_eq!(newer.matches(BEGIN).count(), 1, "{newer}"); + // A second patch, then out again in either order. + let other = patch("netty-tcnative-boringssl-static", OTHER_UUID); + let two = with_patch(&one, LABEL, other.clone()).expect("a block"); + let gone = |uuid: &'static str| move |patch: &Patch| patch.uuid == uuid; + assert_eq!( + without(&two, &mut gone(OTHER_UUID)), + Some(one.clone()), + "{module:?}" + ); + let left = without(&two, &mut gone(NETTY_UUID)).expect("a block"); + assert_eq!( + Some(left.clone()), + with_patch(&module, LABEL, other), + "{module:?}" + ); + for last in [ + without(&left, &mut gone(OTHER_UUID)), + without(&one, &mut gone(NETTY_UUID)), + without(&two, &mut |_| true), + ] { + assert_eq!(last.as_deref(), Some(module.as_str()), "{module:?}"); + } + // Nothing to take out leaves the file as it is. + assert_eq!(without(&one, &mut |_| false), Some(one.clone())); + // What the user wrote below the block stays below it. + let below = format!("{one}{}bazel_dep(name = \"x\", version = \"1\"){eol}", { + match ended { + true => "", + false => eol, + } + }); + let kept = without(&below, &mut |_| true).expect("a block"); + assert!( + kept.starts_with(module.trim_end()) && kept.ends_with(&format!("\"1\"){eol}")), + "{kept:?}" + ); + assert!(!kept.contains("socket"), "{kept:?}"); + } + assert_eq!(without(PINNED, &mut |_| true), None, "no block"); + // A block keeps its own line break in a file that gets the other + // one on another line afterwards. + let one = with_patch(PINNED, LABEL, netty()).expect("a block"); + let (other, plain) = ( + one.replacen('\n', "\r\n", 1), + PINNED.replacen('\n', "\r\n", 1), + ); + assert_eq!(with_patch(&other, LABEL, netty()), Some(other.clone())); + assert_eq!(without(&other, &mut |_| true), Some(plain)); + } + + /// A block that is not what socket-patch writes for the patches it + /// names is never written to, and is a doubt about what a hub builds. + #[test] + fn a_block_that_was_changed_by_hand_is_left_alone() { + let lock = lock_72(); + let ours = with_patch(PINNED, LABEL, netty()).expect("a block"); + let line = PINNED.lines().count() + 2; + // The first thing that could not be read of a workspace. + let doubt = |module: &str| { + let files = [("MODULE.bazel", module), ("maven_install.json", &lock)]; + let doubt = read(&files).doubt; + doubt.map(|Doubt { file, line, why }| format!("{file}:{line}: {why}")) + }; + assert_eq!(doubt(&ours), None); + for (edited, what) in [ + ( + ours.replace("override_repo(", "inject_repo("), + "another call", + ), + ( + ours.replace("# Do not change it", "# do not change it"), + "a comment", + ), + (ours.replace(END, "# <<< socket-patch"), "no last line"), + (ours.replace(" socket_patch_maven,\n", ""), "a line less"), + (format!("{ours}{BEGIN}\n{END}\n"), "a second block"), + ( + ours.replace(".jar\"],\n)", ".jar\"],\n integrity = \"\",\n)"), + "a line more", + ), + (ours.replace("\n# <<<", "\n\n# <<<"), "a blank line"), + ( + ours.replace(BEGIN, &format!("{BEGIN} ")), + "a blank after the first line", + ), + ( + ours.replace(BEGIN, &BEGIN.replace("(managed", "(my")), + "another first line", + ), + ] { + assert_ne!(edited, ours, "{what}"); + assert_eq!(find(&edited), Block::Edited(line), "{what}"); + assert_eq!(with_patch(&edited, LABEL, netty()), None, "{what}"); + assert_eq!(without(&edited, &mut |_| true), None, "{what}"); + let why = "the block that socket-patch keeps there was changed by hand"; + let said = Some(format!("MODULE.bazel:{line}: {why}")); + assert_eq!(doubt(&edited), said, "{what}"); + } + // Without its first line it is no block: text of the user's, which + // hands a proxy to `override_repo`. + let unmarked = ours.replace(BEGIN, "# mine now"); + assert_eq!(find(&unmarked), Block::None); + let said = doubt(&unmarked).unwrap_or_default(); + assert!(said.ends_with("is used other than to call a tag"), "{said}"); + } + + /// With the block in place the workspace reads as the user wrote it: + /// the same hubs on the same lines, and no doubt about a proxy that is + /// handed to `override_repo`. + #[test] + fn the_workspace_reads_as_it_did_before_the_block() { + let lock = lock_72(); + let below = "\nmaven.install(name = \"tools\", lock_file = \"//:maven_install.json\")\n"; + let ours = with_patch(PINNED, LABEL, netty()).expect("a block") + below; + let plain = format!("{PINNED}{}{below}", "\n".repeat(BLOCK.lines().count() + 1)); + let hubs = |module: &str| { + let files = [("MODULE.bazel", module), ("maven_install.json", &lock)]; + let read = read(&files); + let hub = |(hub, _): &(Hub, Lock)| format!("{} {}:{}", hub.name, hub.file, hub.line); + let hubs: Vec = read.pinned.iter().map(hub).collect(); + (hubs, read.doubt, built(&files)) + }; + let line = PINNED.lines().count() + BLOCK.lines().count() + 3; + let both = [ + "maven MODULE.bazel:4".to_string(), + format!("tools MODULE.bazel:{line}"), + ]; + assert_eq!(hubs(&ours), (both.to_vec(), None, "yes, 2".to_string())); + assert_eq!(hubs(&ours), hubs(&plain)); + assert_eq!(read(&[("MODULE.bazel", ours.as_str())]).block, [netty()]); + assert_eq!(read(&[("MODULE.bazel", PINNED)]).block, []); + } + + /// A checkout with the files `files`, where a hosted run may write. + fn checkout(files: &[(&str, &str)]) -> tempfile::TempDir { + let lock = lock_72(); + let bcr = "https://bcr.bazel.build/modules/rules_jvm_external"; + let module_lock = format!( + "{{\"lockFileVersion\": 13, \"registryFileHashes\": {{\"{bcr}/6.5/MODULE.bazel\": \ + \"0\", \"{bcr}/7.2/MODULE.bazel\": \"1\", \"{bcr}/7.2/source.json\": \"2\"}}}}" + ); + let base = [ + ("MODULE.bazel", PINNED), + ("maven_install.json", &lock), + ("MODULE.bazel.lock", &module_lock), + ]; + let dir = project(&base); + for (path, text) in files { + let path = dir.path().join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + dir + } + + /// The patch [`NETTY_UUID`] of the jar `io.netty:` at + /// `version`. + fn jar(artifact: &str, version: &str) -> Vec { + let jar = [NETTY_UUID, "io.netty", artifact, version].map(String::from); + vec![jar.into()] + } + + fn netty_jar() -> Vec { + jar("netty-tcnative-classes", "2.0.61.Final") + } + + /// What [`site`] says of netty's jar in the checkout: `write