From fd064219b7e69e58d38ef9ab68625e9ff8f0f6c5 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 15:51:20 -0500 Subject: [PATCH 01/18] Pin a Maven patch only where Maven selects its base version A hosted or vendored scan could change which version of a dependency a Maven build resolves and exit 0 without saying so. The candidates were a superset of the build (every version any pom of the graph declares, and every cached version behind a range or an undefined property), and a pin makes every occurrence of the artifact one version. A patch for a version that lost mediation, was excluded, or was only cached by another project therefore replaced the version that won: a downgrade when the winner was newer, an upgrade when it was older. A pin is now written only where Maven selects the patch's base version already. - crawlers/maven_selection reads what Maven selects in each module from the project's poms and the poms the local repository holds, without running Maven: own and inherited dependencies, compile/runtime non-optional transitives, exclusions, declared or managed versions (the module's management over every transitive one), ranges through the cached maven-metadata files, and mediation with parents settled first (nearest wins, first declared on a tie, what a losing version depends on leaves the graph). formats/maven/version holds Maven's version order and range grammar. - Every answer is certain or not. A missing pom, a property that is undefined or that a profile redefines, a profile with dependencies or management, a relocation, a cycle, an unread module and a Maven 4 build are not certain, and nothing is pinned on them. - Hosted: redirect_maven_version_not_selected when the build selects another version (or none), redirect_maven_selection_undetermined when it cannot be told and no declaration names the base version. - Vendored: vendor_maven_version_not_selected, a skip decided before any download; the planner pins a local root only when every module under it selects the base version or does not resolve the artifact, and leaves a pin alone when it cannot tell. vendor --check accepts either answer. - A declaration that already names the base version is rewritten under any answer: that replaces a version where it stands. - Agent mode patches cached jars in place and is unchanged, except that a version directory holding a pom and no artifact is left out of an agent scan instead of failing it as a targeted patch not found on disk. - The nothing_wired refusal no longer says Maven keeps resolving the base version. Outcomes that change: the six shapes above exit 0 with nothing written and one line naming the version Maven selects; vendored used to exit 1 on a project that declares another version itself; agent mode used to exit 1 on a pom-only version; a transitive-only dependency of a project whose poms are not in the local repository is reported as undetermined instead of pinned. Refs #595, #882. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 60 +- .../src/commands/scan/hosted.rs | 16 + .../socket-patch-cli/src/commands/scan/mod.rs | 17 + .../tests/e2e_redirect_maven_build.rs | 213 +++ .../tests/e2e_vendor_maven_build.rs | 295 ++++ .../tests/maven_mediation_common/mod.rs | 419 +++++ .../src/crawlers/maven_crawler.rs | 65 + .../src/crawlers/maven_scope.rs | 137 +- .../src/crawlers/maven_selection.rs | 1380 +++++++++++++++++ .../src/crawlers/maven_selection/tests.rs | 759 +++++++++ crates/socket-patch-core/src/crawlers/mod.rs | 1 + .../src/formats/maven/mod.rs | 1 + .../src/formats/maven/version.rs | 469 ++++++ crates/socket-patch-core/src/hosted/engine.rs | 29 + .../src/hosted/memory/stages.rs | 2 + .../patch/redirect/group_equivalence_tests.rs | 3 +- .../src/patch/redirect/mod.rs | 156 +- .../socket-patch-core/src/vendor/jvm/apply.rs | 34 +- .../src/vendor/jvm/maven_reactor.rs | 417 ++++- .../socket-patch-core/src/vendor/jvm/mod.rs | 25 +- .../src/vendor/jvm/sbt_gate.rs | 70 +- .../src/vendor/maven_repo.rs | 175 ++- .../socket-patch-core/src/vendor/refusals.rs | 31 +- docs/design/maven-vendoring.md | 18 + docs/ecosystems.md | 23 + 25 files changed, 4699 insertions(+), 116 deletions(-) create mode 100644 crates/socket-patch-cli/tests/maven_mediation_common/mod.rs create mode 100644 crates/socket-patch-core/src/crawlers/maven_selection.rs create mode 100644 crates/socket-patch-core/src/crawlers/maven_selection/tests.rs create mode 100644 crates/socket-patch-core/src/formats/maven/version.rs diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 05c3caf77..172e105bd 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -402,7 +402,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Grant gate (additive).** A reference grant is the patch API's answer, and its fields are written into files the project commits. Each granted reference is therefore checked once, before anything is planned for it (no takeover, no artifact fetch, no rewriter sees one that fails): the patch uuid is a canonical lowercase uuid; the artifact URL and a registry override's index URL are `https` URLs of plain URL characters (no whitespace or control character, no quote, backslash, `$`, `{`, `}`, `<`, `>`, `&`, `#`, `;`, `|` or `^`; cargo's `sparse+` prefix is kept); `sha1` is 40 hex digits, `sha256` 64, `sha512` exactly one `sha512-` token, the Go hashes `h1:` hashes, the yarn berry checksum `/`, the cargo and gem checksums 64 hex digits; the package's name and version, and every identifier of a registry override, are in their ecosystem's coordinate grammar (letters, digits and that ecosystem's punctuation; Maven coordinates as the JVM backends accept them). A Maven grant's sha256 digests may also be spelled `sha256-…` / `sha256:…`: the pom, Gradle and sbt planners read those, and a digest that is still not 64 hex digits writes no checksum pin (`redirect_maven_trusted_checksums_invalid_hash`). An absent or empty optional field is not checked. A grant that fails is refused for that package only: a `skipped` event whose `errorCode` is `redirect_grant_malformed` and whose `reason` names the field (never its value), the same code and detail in `warnings[]`, nothing written for it, the rest of the run and the exit code unchanged. A plain-`http` artifact or index URL is refused the same way with `redirect_grant_insecure_url` (every later install would send the grant token in clear text), unless its origin is the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin (scheme, host and port) or a loopback address (`localhost`, `127.0.0.0/8`, `::1`). The in-memory engine applies the same gate; it has no configured origin. -The rewriter reads a fixed set of candidate files from the project root: the npm-family locks (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `shrinkwrap.yaml`, `yarn.lock`, plus `.yarnrc.yml` for the berry cache-config gate, `bun.lock` / `bun.lockb`, and `vlt-lock.json` with `vlt.json` and `node_modules/.vlt-lock.json` read only), `requirements.txt` / `uv.lock` / `Pipfile.lock` (pipfile-spec 6; see the Pipenv section below) / `poetry.lock` (every Poetry lock generation from 1.0 on — the 0.12 `[metadata.hashes]` layout is refused because that installer ignores URL sources; a Poetry < 1.4 writer additionally gets `redirect_poetry_stale_install_risk`, see `docs/testing/poetry-compatibility.md`) / `pdm.lock` (PDM lock formats `2` and `4.3`–`4.5.1`; the identity-losing `3.1` / `4.0`–`4.2` formats and unknown future formats are refused with `redirect_pdm_refused`, and a lock-format-`2` writer additionally gets `redirect_pdm_legacy_sync_required`, see `docs/testing/pdm-compatibility.md`; when `uv.lock` or `poetry.lock` sits beside it they drive and `pdm.lock` is left alone), `Cargo.toml` / `Cargo.lock` / `.cargo/config.toml` (plus the legacy extensionless `.cargo/config` — cargo reads that spelling in preference when both exist, so the managed `[registries.…]` block is written into whichever one is present; the hosted redirect is a `sparse+` registry, which cargo loads only from **1.68**, so `rust-toolchain.toml` / `rust-toolchain` are read too (never edited) and a project whose declared floor — the lowest `rust-version` of the root and the member manifests read here (a `rust-version.workspace = true` inheritor reads `[workspace.package]`), else the channel rustup picks from the root (the legacy `rust-toolchain` over `rust-toolchain.toml`; a dated `nightly-`/`beta-YYYY-MM-DD` maps to its release train) — is below 1.68 is refused `redirect_cargo_old_cargo` per crate (nothing written, an earlier run's pins left in place with the `rollback` that drops them named; `--mode vendored` builds on cargo 1.41+), while an undeclared or rolling-channel floor still redirects (toolchain files in ancestor directories are not read); **cargo also reads every workspace-member manifest** — the `[workspace] members` globs minus `exclude` — and every in-root path-dependency manifest, recursively, reached without crossing a symbolic link and never under `.socket/`, and pins the crate in each one that declares it, so those `/Cargo.toml` files can appear in `rewrittenFiles`. A crate is redirected only when every declaration pins and every other `Cargo.lock` package depending on it is a planned member: one a registry or git crate — or a path package outside the root or behind a link — also depends on is refused `redirect_cargo_transitive_dependents` (a pin reaches only the declarations it sits on), a crate no manifest declares keeps `redirect_cargo_toml_dep_not_found` with a transitive-only detail naming `--mode vendored`, a crate every declaration of which requires another version (no requirement accepts the patched version) is refused `redirect_cargo_toml_dep_unrewritable`, and so is a requirement that also matches another locked version of the crate — each a transactional skip, never recorded or attested. With NO `Cargo.lock` there is no resolved graph to ask, so the dependents question is answered from the manifests instead: a crate declared beside any other dependency — anything but a path dependency on a manifest this run also pins, or a `workspace = true` inheritor of a table it scans — or beside a workspace member this run did not read (a `members` glob, or a member outside the project or behind a symbolic link, which member discovery drops) is refused `redirect_cargo_lockless_dependents`, whose detail names the remedies (commit a lockfile, or `--mode vendored`); a project whose only dependency is the patched crate has nothing that could pull it in and still redirects. All-CRLF manifests, locks and configs are rewritten with CRLF kept (mixed endings keep refusing where the grammar does not match), and `remove` / rollback match the recorded fragments across a later CRLF↔LF checkout conversion), `composer.lock`, `nuget.config` / `packages.lock.json` (plus, v5.0 #353/#514, every lock a project under the root restores into: a member project's `packages.lock.json`, a per-project `packages..lock.json`, a literal `NuGetLockFilePath` — each pinned with the root config; a `NuGetLockFilePath` it cannot evaluate warns `redirect_nuget_lock_path_unresolved` and a project tree it cannot list warns `redirect_nuget_lock_unreadable`, both skipping the nuget redirect with nothing written), `Gemfile` / `Gemfile.lock`, `pom.xml` (+ `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` for maven Trusted Checksums merge, and, for a Gradle build, every settings, build, `buildSrc`, included-build, applied and plugin-source script, version catalog and lock file the script graph reaches, plus `gradle/verification-metadata.xml`, `gradle/wrapper/gradle-wrapper.properties` and the owned `.socket/gradle/` files), and the sbt build files (`socket-patch.sbt`, `socket-patch-vendor.sbt`, `build.sbt`, `project/build.properties`, `.sbtopts`, `.jvmopts`; `build.sbt.lock` and the Mill / scala-cli build files `build.mill`, `build.mill.yaml`, `build.sc`, `.mill-version`, `project.scala` for their presence only) — read, never edited; `socket-patch.sbt` is the only sbt file hosted mode writes (see **Hosted sbt** below). **npm-family flavor coverage**: package-lock / npm-shrinkwrap (a package the project patches itself with npm ≥ 12.1's native `npm patch` — a root `patchedDependencies` key, or the lock entry's `patched` record — is left on its registry entry in every npm lock, `redirect_npm_patched_dependency_skipped`), pnpm (root OR any nested `*/pnpm-lock.yaml`), yarn classic (a yarn 2+ install migrates a v1 `yarn.lock` and drops its pins, so a run whose v1 lock carries a hosted pin warns `redirect_yarn_classic_berry_migration_risk` — the hosted twin of the vendored `yarn_classic_berry_migration_risk` — unless the root `package.json`, read as advisory input, declares `"packageManager": "yarn@1…"`), **yarn berry** (the pin yarn writes for a root `resolutions` entry: the root `package.json` — edited only beside a berry `yarn.lock` — gains one `"@npm:": ""` selector per locked range (`redirect_yarn_berry_resolution` edits), and only that `yarn.lock` entry is re-keyed `"@"` with the same `resolution:` + `yarnBerry10c0` checksum (`redirect_yarn_berry_entry`), moved to yarn's key order; never an `npm:` locator, whose fetcher sends npm registry auth to the patch host, nor a tarball locator under an `npm:` key, which hardened mode rejects (YN0078). An older release's `npm:::__archiveUrl=` pin is still recognized and is re-pinned on the next run; rollback rebuilds the key from the selectors and drops them. Refused, nothing written: a user-authored `resolutions` entry for the package `redirect_yarn_berry_resolutions_conflict`, no root manifest `redirect_yarn_berry_manifest_missing`, a builtin `patch:` entry wrapping the same descriptor `redirect_yarn_berry_shared_descriptor`, an artifact URL yarn cannot fetch as a tarball `redirect_yarn_berry_artifact_url_unsupported`; cacheKey `10c0` and `.yarnrc.yml compressionLevel 0` gated by `redirect_yarn_berry_cache_unsupported`), and **bun** (text `bun.lock` lockfileVersion 0, 1 or 2 — 0 is the `--save-text-lockfile` opt-in lock of Bun 1.1.39–1.1.45, 1 the 1.2–1.3 default, 2 the 1.4+ default; all three emit one `packages` grammar, so the registry 4-tuple → URL 3-tuple rewrite is version-independent and the lock's own version line is kept. Any other or missing version, or a `packages` section outside bun's single-line grammar, is refused `redirect_bun_lock_unsupported` — the detail is the shared version gate's text (a newer version: update socket-patch, re-locking would reproduce it; no integer: re-lock with Bun ≥ 1.2), identical to the vendored refusal. A version-0 lock holding `workspace:` packages is refused `redirect_bun_workspace_unsupported` (its 2-tuple workspace grammar cannot keep the hosted tuple through a frozen install); the remedy is to delete `bun.lock` and re-run `bun install` with Bun ≥ 1.2, which writes lockfileVersion 1 (accepted). A plain in-place `bun install` bumps the version only when a workspace depends on another workspace (e.g. root → member — the shape the matrix measured); otherwise Bun 1.2.0 keeps version 0 and Bun 1.2.23+ fail to resolve, so the in-place bump is not the documented remedy. Bun lock version, grammar and workspace compatibility are checked before a vendored takeover, including during dry-run: these refusals preserve the existing lock, artifact and vendor ledger. Version-1 and version-2 workspace locks are rewritten, nested versions included. A granted dep with no rewritable entry warns `redirect_bun_entry_not_found` (or `redirect_bun_non_registry_entry_skipped` when the only same-version entry is a user URL / `file:` tarball, #497), a grant without a sha512 `redirect_bun_missing_sha512`; a CRLF lock keeps `\r\n` on the rewritten line, and a hosted URL left by an earlier grant of the same `name@version` is re-pinned in place. **Digest-less re-saves (Bun 1.1.39–1.3.9)**: every text-lock Bun below 1.3.10 re-saves a URL tuple WITHOUT its `sha512` whenever the lock is re-saved for another reason (`bun add`, `bun install` after a package.json or workspace change), leaving the 2-tuple `["name@", {meta}]` — the spec Bun installs from is intact. The CLI treats that spelling as its own wiring: a repeat hosted run counts the dep as redirected (no `redirect_bun_entry_not_found`) and HEALS the line back to the 3-tuple with the current `sha512`, recording the heal as a further `redirect_bun_lock_package` edit whose `original` is the 2-tuple (a stale URL is re-pinned from either spelling); `rollback`, scoped `rollback ` / `remove ` and the vendored takeover accept the digest-less spelling of a recorded `new` line (same key, spec and meta, only the trailing `"sha512-…"` missing) and restore the recorded original over it, so the chain always unwinds to the pristine registry line. Anything else — another uuid/token, another version, a re-laid meta object — is still drift. **Native `bun.lockb`**: when no text `bun.lock` exists, binary format versions 1, 2 and 3 are read and rewritten directly. Socket Patch does not invoke Bun or convert the project to a text lockfile. Exact matching package records are rewritten to hosted tarballs with the granted integrity, preserving dependency resolution IDs, workspace/dependency topology and unrelated package metadata; binary pointers and the package metadata hash are updated. Per-package `redirect_bun_lockb_package` snapshots support scoped rollback, repeat runs, superseding grants and hosted ↔ vendored takeover. A regular binary lock is discoverable even with no Bun runtime or `node_modules`; a dry run previews the same binary edits without writing them. A malformed, unreadable, unsupported or unverified binary structure is `redirect_bun_lockb_invalid` (exit 0, `redirected: 0`), and it refuses the npm rewrite before any takeover or sibling npm-family lock mutation. A symlinked binary write target is `redirect_symlinked_file_unsupported` (exit 1, including dry-run). `bun.lock` wins when both spellings exist. Binary-only projects do not receive `redirect_npm_no_lockfile`. Measured boundaries and the real-Bun matrix: `docs/testing/bun-compatibility.md`), and **vlt** (`vlt-lock.json` without `lockfileVersion`, `0` or `1`; see the vlt hosted-mode contract below). **Rush monorepos**: when `rush.json` is present the rewriter also reads `common/config/rush/pnpm-lock.yaml` and each `common/config/subspaces//pnpm-lock.yaml` (sorted for determinism) under their repo-relative keys and repoints them in place; editing them emits `redirect_rush_repo_state_stale` when the `repo-state.json` beside a rewritten lock exists (`common/config/rush/repo-state.json` for the common lock, `common/config/subspaces//repo-state.json` for a subspace lock; the `pnpmShrinkwrapHash` desync is refreshed by `rush update`, which the redirect survives), and `redirect_pnpm_trust_lockfile` carries the Rush pnpm >=11 install remedy (see the trust paragraph above). **maven** is fail-closed via version suffixing: a `mavenSuffixedVersion` + `mavenPomSha256` override pins the Socket-only `-socket.` by rewriting the literal `` (`redirect_maven_dep_version`) or adding a `` entry (`redirect_maven_dep_management_added`), plus optional Trusted Checksums (`redirect_maven_trusted_checksums`, conflicts as `redirect_maven_trusted_checksums_conflict`; when `.mvn/wrapper/maven-wrapper.properties` pins a Maven older than 3.9.4, which ignores those files, the additive warning `redirect_maven_trusted_checksums_unenforced`; a grant sha256 that is not 64 hex digits writes no checksum line, `redirect_maven_trusted_checksums_invalid_hash`); a `${property}` version is refused (`redirect_maven_dep_unpinned`), a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`; each such subdirectory's `pom.xml` is read for this, never edited) is refused whole with `redirect_maven_multimodule_unsupported`: `pom.xml` and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the pom pins it too), since a module's own literal `` would shadow a root pin (use `--mode vendored`; `vex` omits a hosted pin in a reactor root as `vex_maven_reactor_root`), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped, with nothing written, when a variant other than `sources` / `javadoc`, live or inside ``, may resolve any version but the suffixed pin — the patched release, another one, a `${property}` a profile moves, or no version in the pom once its classifier-keyed `` (a profile's too) is consulted — since `vex` would never attest that pin: `vex_maven_classifier_unpatched`), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`): when any version it may resolve — its own, or what its own profile's or any combination of profiles' `` make of it, read as `vex` reads it — is not the suffixed pin, the dep is refused with nothing written, since it overrides the pin whenever that profile is active and `vex` would never attest it (a profile `` entry only when management governs the pin, i.e. no live direct declaration carries a version); a versionless one takes the pin, and the dep is also skipped when a profile holds its only declaration, a `${property}` groupId / artifactId resolved from the pom's own `` before matching (one the pom does not define, which may be the patched GA and whose own version would then win, refuses the dep with nothing written: `redirect_maven_coordinate_unresolved`), and a `${property}` groupId / artifactId some profile's `` (or several profiles' together) redefine so that the declaration a pin would go into names another package, or another declaration names the GA's main jar at another version (or one of its executable classifier copies, a `test-jar` included), refuses the dep with nothing written too (`redirect_maven_profile_coordinates_unpatched`): `vex` would never attest that pin (`vex_maven_profile_unpatched`), and a pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). **gradle** (v5.0) is automated wiring, no longer a pasted snippet: the owned settings script `.socket/gradle/socket-patch.hosted.settings.gradle` with its index `.socket/gradle/hosted-index.tsv`, one apply line per build's settings file, every lock entry of the GA moved to the suffixed version, and the suffixed component in an existing `gradle/verification-metadata.xml`. A refused dep writes nothing and keeps `redirect_gradle_manual_snippet` as its fallback; same-GAV grants are refused (`redirect_gradle_same_gav_unsupported`). Rules, refusals and codes: [Gradle builds](#gradle-builds-v50). +The rewriter reads a fixed set of candidate files from the project root: the npm-family locks (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `shrinkwrap.yaml`, `yarn.lock`, plus `.yarnrc.yml` for the berry cache-config gate, `bun.lock` / `bun.lockb`, and `vlt-lock.json` with `vlt.json` and `node_modules/.vlt-lock.json` read only), `requirements.txt` / `uv.lock` / `Pipfile.lock` (pipfile-spec 6; see the Pipenv section below) / `poetry.lock` (every Poetry lock generation from 1.0 on — the 0.12 `[metadata.hashes]` layout is refused because that installer ignores URL sources; a Poetry < 1.4 writer additionally gets `redirect_poetry_stale_install_risk`, see `docs/testing/poetry-compatibility.md`) / `pdm.lock` (PDM lock formats `2` and `4.3`–`4.5.1`; the identity-losing `3.1` / `4.0`–`4.2` formats and unknown future formats are refused with `redirect_pdm_refused`, and a lock-format-`2` writer additionally gets `redirect_pdm_legacy_sync_required`, see `docs/testing/pdm-compatibility.md`; when `uv.lock` or `poetry.lock` sits beside it they drive and `pdm.lock` is left alone), `Cargo.toml` / `Cargo.lock` / `.cargo/config.toml` (plus the legacy extensionless `.cargo/config` — cargo reads that spelling in preference when both exist, so the managed `[registries.…]` block is written into whichever one is present; the hosted redirect is a `sparse+` registry, which cargo loads only from **1.68**, so `rust-toolchain.toml` / `rust-toolchain` are read too (never edited) and a project whose declared floor — the lowest `rust-version` of the root and the member manifests read here (a `rust-version.workspace = true` inheritor reads `[workspace.package]`), else the channel rustup picks from the root (the legacy `rust-toolchain` over `rust-toolchain.toml`; a dated `nightly-`/`beta-YYYY-MM-DD` maps to its release train) — is below 1.68 is refused `redirect_cargo_old_cargo` per crate (nothing written, an earlier run's pins left in place with the `rollback` that drops them named; `--mode vendored` builds on cargo 1.41+), while an undeclared or rolling-channel floor still redirects (toolchain files in ancestor directories are not read); **cargo also reads every workspace-member manifest** — the `[workspace] members` globs minus `exclude` — and every in-root path-dependency manifest, recursively, reached without crossing a symbolic link and never under `.socket/`, and pins the crate in each one that declares it, so those `/Cargo.toml` files can appear in `rewrittenFiles`. A crate is redirected only when every declaration pins and every other `Cargo.lock` package depending on it is a planned member: one a registry or git crate — or a path package outside the root or behind a link — also depends on is refused `redirect_cargo_transitive_dependents` (a pin reaches only the declarations it sits on), a crate no manifest declares keeps `redirect_cargo_toml_dep_not_found` with a transitive-only detail naming `--mode vendored`, a crate every declaration of which requires another version (no requirement accepts the patched version) is refused `redirect_cargo_toml_dep_unrewritable`, and so is a requirement that also matches another locked version of the crate — each a transactional skip, never recorded or attested. With NO `Cargo.lock` there is no resolved graph to ask, so the dependents question is answered from the manifests instead: a crate declared beside any other dependency — anything but a path dependency on a manifest this run also pins, or a `workspace = true` inheritor of a table it scans — or beside a workspace member this run did not read (a `members` glob, or a member outside the project or behind a symbolic link, which member discovery drops) is refused `redirect_cargo_lockless_dependents`, whose detail names the remedies (commit a lockfile, or `--mode vendored`); a project whose only dependency is the patched crate has nothing that could pull it in and still redirects. All-CRLF manifests, locks and configs are rewritten with CRLF kept (mixed endings keep refusing where the grammar does not match), and `remove` / rollback match the recorded fragments across a later CRLF↔LF checkout conversion), `composer.lock`, `nuget.config` / `packages.lock.json` (plus, v5.0 #353/#514, every lock a project under the root restores into: a member project's `packages.lock.json`, a per-project `packages..lock.json`, a literal `NuGetLockFilePath` — each pinned with the root config; a `NuGetLockFilePath` it cannot evaluate warns `redirect_nuget_lock_path_unresolved` and a project tree it cannot list warns `redirect_nuget_lock_unreadable`, both skipping the nuget redirect with nothing written), `Gemfile` / `Gemfile.lock`, `pom.xml` (+ `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` for maven Trusted Checksums merge, and, for a Gradle build, every settings, build, `buildSrc`, included-build, applied and plugin-source script, version catalog and lock file the script graph reaches, plus `gradle/verification-metadata.xml`, `gradle/wrapper/gradle-wrapper.properties` and the owned `.socket/gradle/` files), and the sbt build files (`socket-patch.sbt`, `socket-patch-vendor.sbt`, `build.sbt`, `project/build.properties`, `.sbtopts`, `.jvmopts`; `build.sbt.lock` and the Mill / scala-cli build files `build.mill`, `build.mill.yaml`, `build.sc`, `.mill-version`, `project.scala` for their presence only) — read, never edited; `socket-patch.sbt` is the only sbt file hosted mode writes (see **Hosted sbt** below). **npm-family flavor coverage**: package-lock / npm-shrinkwrap (a package the project patches itself with npm ≥ 12.1's native `npm patch` — a root `patchedDependencies` key, or the lock entry's `patched` record — is left on its registry entry in every npm lock, `redirect_npm_patched_dependency_skipped`), pnpm (root OR any nested `*/pnpm-lock.yaml`), yarn classic (a yarn 2+ install migrates a v1 `yarn.lock` and drops its pins, so a run whose v1 lock carries a hosted pin warns `redirect_yarn_classic_berry_migration_risk` — the hosted twin of the vendored `yarn_classic_berry_migration_risk` — unless the root `package.json`, read as advisory input, declares `"packageManager": "yarn@1…"`), **yarn berry** (the pin yarn writes for a root `resolutions` entry: the root `package.json` — edited only beside a berry `yarn.lock` — gains one `"@npm:": ""` selector per locked range (`redirect_yarn_berry_resolution` edits), and only that `yarn.lock` entry is re-keyed `"@"` with the same `resolution:` + `yarnBerry10c0` checksum (`redirect_yarn_berry_entry`), moved to yarn's key order; never an `npm:` locator, whose fetcher sends npm registry auth to the patch host, nor a tarball locator under an `npm:` key, which hardened mode rejects (YN0078). An older release's `npm:::__archiveUrl=` pin is still recognized and is re-pinned on the next run; rollback rebuilds the key from the selectors and drops them. Refused, nothing written: a user-authored `resolutions` entry for the package `redirect_yarn_berry_resolutions_conflict`, no root manifest `redirect_yarn_berry_manifest_missing`, a builtin `patch:` entry wrapping the same descriptor `redirect_yarn_berry_shared_descriptor`, an artifact URL yarn cannot fetch as a tarball `redirect_yarn_berry_artifact_url_unsupported`; cacheKey `10c0` and `.yarnrc.yml compressionLevel 0` gated by `redirect_yarn_berry_cache_unsupported`), and **bun** (text `bun.lock` lockfileVersion 0, 1 or 2 — 0 is the `--save-text-lockfile` opt-in lock of Bun 1.1.39–1.1.45, 1 the 1.2–1.3 default, 2 the 1.4+ default; all three emit one `packages` grammar, so the registry 4-tuple → URL 3-tuple rewrite is version-independent and the lock's own version line is kept. Any other or missing version, or a `packages` section outside bun's single-line grammar, is refused `redirect_bun_lock_unsupported` — the detail is the shared version gate's text (a newer version: update socket-patch, re-locking would reproduce it; no integer: re-lock with Bun ≥ 1.2), identical to the vendored refusal. A version-0 lock holding `workspace:` packages is refused `redirect_bun_workspace_unsupported` (its 2-tuple workspace grammar cannot keep the hosted tuple through a frozen install); the remedy is to delete `bun.lock` and re-run `bun install` with Bun ≥ 1.2, which writes lockfileVersion 1 (accepted). A plain in-place `bun install` bumps the version only when a workspace depends on another workspace (e.g. root → member — the shape the matrix measured); otherwise Bun 1.2.0 keeps version 0 and Bun 1.2.23+ fail to resolve, so the in-place bump is not the documented remedy. Bun lock version, grammar and workspace compatibility are checked before a vendored takeover, including during dry-run: these refusals preserve the existing lock, artifact and vendor ledger. Version-1 and version-2 workspace locks are rewritten, nested versions included. A granted dep with no rewritable entry warns `redirect_bun_entry_not_found` (or `redirect_bun_non_registry_entry_skipped` when the only same-version entry is a user URL / `file:` tarball, #497), a grant without a sha512 `redirect_bun_missing_sha512`; a CRLF lock keeps `\r\n` on the rewritten line, and a hosted URL left by an earlier grant of the same `name@version` is re-pinned in place. **Digest-less re-saves (Bun 1.1.39–1.3.9)**: every text-lock Bun below 1.3.10 re-saves a URL tuple WITHOUT its `sha512` whenever the lock is re-saved for another reason (`bun add`, `bun install` after a package.json or workspace change), leaving the 2-tuple `["name@", {meta}]` — the spec Bun installs from is intact. The CLI treats that spelling as its own wiring: a repeat hosted run counts the dep as redirected (no `redirect_bun_entry_not_found`) and HEALS the line back to the 3-tuple with the current `sha512`, recording the heal as a further `redirect_bun_lock_package` edit whose `original` is the 2-tuple (a stale URL is re-pinned from either spelling); `rollback`, scoped `rollback ` / `remove ` and the vendored takeover accept the digest-less spelling of a recorded `new` line (same key, spec and meta, only the trailing `"sha512-…"` missing) and restore the recorded original over it, so the chain always unwinds to the pristine registry line. Anything else — another uuid/token, another version, a re-laid meta object — is still drift. **Native `bun.lockb`**: when no text `bun.lock` exists, binary format versions 1, 2 and 3 are read and rewritten directly. Socket Patch does not invoke Bun or convert the project to a text lockfile. Exact matching package records are rewritten to hosted tarballs with the granted integrity, preserving dependency resolution IDs, workspace/dependency topology and unrelated package metadata; binary pointers and the package metadata hash are updated. Per-package `redirect_bun_lockb_package` snapshots support scoped rollback, repeat runs, superseding grants and hosted ↔ vendored takeover. A regular binary lock is discoverable even with no Bun runtime or `node_modules`; a dry run previews the same binary edits without writing them. A malformed, unreadable, unsupported or unverified binary structure is `redirect_bun_lockb_invalid` (exit 0, `redirected: 0`), and it refuses the npm rewrite before any takeover or sibling npm-family lock mutation. A symlinked binary write target is `redirect_symlinked_file_unsupported` (exit 1, including dry-run). `bun.lock` wins when both spellings exist. Binary-only projects do not receive `redirect_npm_no_lockfile`. Measured boundaries and the real-Bun matrix: `docs/testing/bun-compatibility.md`), and **vlt** (`vlt-lock.json` without `lockfileVersion`, `0` or `1`; see the vlt hosted-mode contract below). **Rush monorepos**: when `rush.json` is present the rewriter also reads `common/config/rush/pnpm-lock.yaml` and each `common/config/subspaces//pnpm-lock.yaml` (sorted for determinism) under their repo-relative keys and repoints them in place; editing them emits `redirect_rush_repo_state_stale` when the `repo-state.json` beside a rewritten lock exists (`common/config/rush/repo-state.json` for the common lock, `common/config/subspaces//repo-state.json` for a subspace lock; the `pnpmShrinkwrapHash` desync is refreshed by `rush update`, which the redirect survives), and `redirect_pnpm_trust_lockfile` carries the Rush pnpm >=11 install remedy (see the trust paragraph above). **maven** is fail-closed via version suffixing: a `mavenSuffixedVersion` + `mavenPomSha256` override pins the Socket-only `-socket.` by rewriting the literal `` (`redirect_maven_dep_version`) or adding a `` entry (`redirect_maven_dep_management_added`), plus optional Trusted Checksums (`redirect_maven_trusted_checksums`, conflicts as `redirect_maven_trusted_checksums_conflict`; when `.mvn/wrapper/maven-wrapper.properties` pins a Maven older than 3.9.4, which ignores those files, the additive warning `redirect_maven_trusted_checksums_unenforced`; a grant sha256 that is not 64 hex digits writes no checksum line, `redirect_maven_trusted_checksums_invalid_hash`); a `${property}` version is refused (`redirect_maven_dep_unpinned`), a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`; each such subdirectory's `pom.xml` is read for this, never edited) is refused whole with `redirect_maven_multimodule_unsupported`: `pom.xml` and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the pom pins it too), since a module's own literal `` would shadow a root pin (use `--mode vendored`; `vex` omits a hosted pin in a reactor root as `vex_maven_reactor_root`), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped, with nothing written, when a variant other than `sources` / `javadoc`, live or inside ``, may resolve any version but the suffixed pin — the patched release, another one, a `${property}` a profile moves, or no version in the pom once its classifier-keyed `` (a profile's too) is consulted — since `vex` would never attest that pin: `vex_maven_classifier_unpatched`), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`): when any version it may resolve — its own, or what its own profile's or any combination of profiles' `` make of it, read as `vex` reads it — is not the suffixed pin, the dep is refused with nothing written, since it overrides the pin whenever that profile is active and `vex` would never attest it (a profile `` entry only when management governs the pin, i.e. no live direct declaration carries a version); a versionless one takes the pin, and the dep is also skipped when a profile holds its only declaration, a `${property}` groupId / artifactId resolved from the pom's own `` before matching (one the pom does not define, which may be the patched GA and whose own version would then win, refuses the dep with nothing written: `redirect_maven_coordinate_unresolved`), and a `${property}` groupId / artifactId some profile's `` (or several profiles' together) redefine so that the declaration a pin would go into names another package, or another declaration names the GA's main jar at another version (or one of its executable classifier copies, a `test-jar` included), refuses the dep with nothing written too (`redirect_maven_profile_coordinates_unpatched`): `vex` would never attest that pin (`vex_maven_profile_unpatched`), and a pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). A pin is written only where Maven selects the patch's base version already (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`): see [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). **gradle** (v5.0) is automated wiring, no longer a pasted snippet: the owned settings script `.socket/gradle/socket-patch.hosted.settings.gradle` with its index `.socket/gradle/hosted-index.tsv`, one apply line per build's settings file, every lock entry of the GA moved to the suffixed version, and the suffixed component in an existing `gradle/verification-metadata.xml`. A refused dep writes nothing and keeps `redirect_gradle_manual_snippet` as its fallback; same-GAV grants are refused (`redirect_gradle_same_gav_unsupported`). Rules, refusals and codes: [Gradle builds](#gradle-builds-v50). **Hosted sbt (v5.0, additive)**: an sbt build root (`project/build.properties` naming an `sbt.version`, 0.13.18 or later) is wired through ONE generated root file, `socket-patch.sbt` — no user file is edited. It pins every granted Maven patch build-wide (a `ThisBuild` `dependencyOverrides +=` of the Socket-only `-socket.` version plus a `file:` resolver over `.socket/sbt-hosted/maven2/`, moved ahead of the default repositories on sbt 0.13 / 1.x so an unreachable one never blocks it offline), downloads the pinned pom and jar there on the first sbt load (sha256-checked, gitignored by the file itself), and installs a load-time verifier that fails `update` when any project resolves another version or a pinned artifact whose bytes are not pinned. Edits: `redirect_sbt_pin` (added), `redirect_sbt_pin_updated` (an existing row replaced: same GA and base under a new uuid, or the same uuid with new served values; `original` names the previous uuid and version), `redirect_sbt_pin_rechecked` (an existing row re-verified after the build's dependencies changed: its dependency digest is recorded anew, `original`/`new` are `{deps}`). The load-time verifier also fails `update` when a project declares a pinned GA at a version newer than the pin's base (the build-wide override would otherwise force it back down). A new pin is gated on sbt's own resolution records under `target/` (never the machine-wide cache): run-level stops wire nothing, warn once and exit 0 — `redirect_sbt_no_resolution_evidence` (none; run `sbt update` first; always the in-memory engine's answer), `redirect_sbt_resolution_incomplete` (a declared project left no evidence, or the project definitions cannot be read statically), `redirect_sbt_resolution_stale` (a build source is newer than some project's evidence: each project is dated by its own newest record, so a partial `sbt /update` does not vouch for the others). Per-patch refusals (never confirmed): `redirect_sbt_missing_override` (no `maven2` override or no suffixed version), `redirect_sbt_integrity_missing` (jar or pom sha256 missing), `redirect_sbt_unsafe_value` (a value unsafe in a Scala literal, or an index URL not naming the uuid), `redirect_sbt_version_conflict` (some project resolves another version, or a build source declares the GA newer than the patch's base), `redirect_sbt_override_conflict` (two patches for one GA in a run, or another base already pinned), `redirect_sbt_vendored_conflict` (the GA is pinned by `socket-patch-vendor.sbt`, or that file cannot be parsed — then every Maven patch), `redirect_sbt_owned_file_modified` / `redirect_sbt_owned_file_foreign` (`socket-patch.sbt` edited, or not socket-patch's — every Maven patch), `redirect_sbt_owned_file_unreadable` (a whole-run refusal: `socket-patch.sbt` is on disk but cannot be read as UTF-8 text, so writing it would replace it; nothing is written), `redirect_sbt_unsupported_version`, `redirect_sbt_build_root_unknown` (sbt files but no versioned build root — every Maven patch), `redirect_sbt_overrides_assignment` / `redirect_sbt_resolvers_assignment` (a build source reassigns `dependencyOverrides` / `resolvers` with `:=`, `~=`, `--=` or `<<=`), `redirect_sbt_onload_assignment` (a build source reassigns `onLoad`, in any scope, with `:=`, `~=`, `--=` or `<<=` without keeping its previous value — a `:=` reading `(Global / onLoad).value`, or a `~=` that composes with `andThen` / `compose`, keeps it — which drops the generated file's load-time verifier and resolver order), `redirect_sbt_dependency_lock_present` (a `build.sbt.lock`), `redirect_sbt_scala_runtime_unsupported` (`org.scala-lang`), `redirect_sbt_classifier_unsupported`; a GA no library configuration resolves is skipped silently (`redirect_sbt_meta_build_only` when only the meta-build resolves it). Advisories: `redirect_sbt_version_untested` (sbt 2.1+, still wired), `redirect_sbt_override_build_repos` (`sbt.override.build.repos=true`), `redirect_maven_pom_ignored_sbt_build` (a `pom.xml` beside the sbt build, which sbt never reads; the Maven rewriter still edits it for the Maven build). A re-run keeps an existing row and re-checks it. When the build's dependency digest changed since the pin, evidence resolved after the change (fresh, newer than the generated file) re-verifies it and the row's digest is refreshed (`redirect_sbt_pin_rechecked`); the uuid is NOT confirmed on `redirect_sbt_pin_declared_newer` (a build source now declares the GA newer than the pin's base; the row stays, sbt's load-time verifier fails the build, and the remedy is `socket-patch rollback` or declaring the base again), `redirect_sbt_pin_unverifiable` (the digest changed and the evidence predates the change, or the digest cannot be computed: run `sbt update`, then re-run socket-patch), `redirect_sbt_override_shadowed` (the evidence still resolves the base version) or `redirect_sbt_resolved_elsewhere` (the pinned version resolves from outside the pin repository from a file whose sha256 is not the pinned jar's; a copy holding the pinned bytes, such as the Ivy cache a second checkout reads, is fine — at most 64 pinned artifact files of up to 256 MiB are hashed, anything else counts as elsewhere), and also when a build source now reassigns `dependencyOverrides` / `resolvers` / `onLoad` or a `build.sbt.lock` appeared (the same `redirect_sbt_overrides_assignment` / `redirect_sbt_resolvers_assignment` / `redirect_sbt_onload_assignment` / `redirect_sbt_dependency_lock_present` codes; the row stays and sbt's load-time verifier fails the build). For a pure sbt root (no `pom.xml` / Gradle script beside it), maven confirmation is decided only by the sbt rewriter's report; on a mixed root a uuid the sbt rewriter refused is still confirmed by the Maven rewriter's own `pom.xml` pin (the generated sbt files never prove a pin by substring). **Mill and scala-cli** are guidance only: per Maven patch `redirect_mill_manual_snippet` / `redirect_scala_cli_manual_snippet` carry a paste-able snippet (repository + forced suffixed version), nothing is written or confirmed, and a pure Mill / scala-cli root gets no `redirect_maven_no_pom`; there, a Maven patch the server sent without a `maven2` registry override gets `redirect_maven_missing_override` instead of a snippet (with a `pom.xml` beside the Mill / scala-cli files the pom rewriter reports it). `rollback` / `remove` restore `socket-patch.sbt` offline (the rows removed, the file deleted with its last pin; the gitignored downloads are left). Manifest-less VEX reads every strictly parsed pin as a hosted reference but grants it the lockfile basis only when the local evidence shows every recorded version of the GA is the pinned one and every recorded artifact hashes to a pinned sha256 (else `sbt_resolution_unverified`, and the suffixed copy sbt downloaded into `.socket/sbt-hosted` is its only basis). Where the build provably does not use the pinned bytes, that copy proves nothing and the patch is omitted (`vex_sbt_pin_bypassed`): a build source reassigns `dependencyOverrides` (`:=`, `~=`, `--=`; replacing the generated override) or reassigns `onLoad` without keeping its previous value (dropping the installer that holds the load-time verifier and resolver order), whether or not any evidence exists, or a resolution record dated after the generated files and every build source shows the GA's base version (the override shadowed), or the pinned version from outside the pin repository with bytes that are not pinned (judged exactly as the hosted rewriter re-checks a pin, `redirect_sbt_override_shadowed` / `redirect_sbt_resolved_elsewhere`). A record older than the wiring (a project or cross build not re-resolved since) proves nothing, and current records that verify the pin always keep it. A `resolvers` reassignment or `sbt.override.build.repos=true` alone is no bypass: the override still forces the Socket-only version and the load-time verifier checks its bytes, so the build runs the pinned bytes or fails (which is why an `onLoad` reassignment dropping that verifier is one). Stale or partial evidence, project definitions that cannot be read statically and a `build.sbt.lock` only withhold the lockfile basis. A file under a generated name without socket-patch's header is read as the root build definition sbt loads it as. @@ -1996,6 +1996,8 @@ command's integration tests check its output. | `vendor_unsupported_ecosystem` | `skipped` | vendor: no vendor backend for this purl's ecosystem (jsr). | | `already_vendored` | `skipped` | vendor: artifact + wiring already in sync for this patch uuid. | | `vendor_gem_version_not_locked` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (gem): no section of the project's `Gemfile.lock` resolves the gem at this version (typically a gem Ruby ships in the gem home, or another project's copy in a shared gem home, which the crawl of that gem home returns). Decided before any download: the patch is not fetched, the Gemfile and lock stay byte-identical, and nothing is written. Human: `[skip] (vendor_gem_version_not_locked): …` in the download phase of `scan` / `get` (both identifier paths) and in their dry run, `Skipping : …` in `vendor`. The vendored twin of `redirect_gem_version_not_locked`. | +| `vendor_maven_version_not_selected` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): no module of the build resolves the artifact at the patch's base version; the reason names the versions Maven selects instead (a nearer declaration, the project's own declaration or management, an ``, a version range), or says that no module resolves the artifact. Decided before any download: the patch is not fetched and no file is written. Human: `[skip] (vendor_maven_version_not_selected): …` in the download phase of `scan` / `get` and in their dry run, `Skipping : …` in `vendor`. The vendored twin of `redirect_maven_version_not_selected`. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). | +| `vendor_maven_selection_undetermined` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): what the build selects for the artifact cannot be read (the reason says why: typically a pom the local repository does not hold, because the project was never resolved) and no declaration names the patch's base version, so nothing is pinned on a guess and no file is written. The reason carries the remedy: resolve the project once (`mvn -q dependency:resolve`) and re-run, or declare the artifact at the base version. The vendored twin of `redirect_maven_selection_undetermined`. | | `vendor_prebuilt_pending` / `vendor_prebuilt_unavailable` | `skipped` | vendor / scan / get `--mode vendored` (every ecosystem, #954, #1235): the package is already vendored at another patch uuid, and the patch service has no prebuilt artifact for the selected (superseding) uuid — still building (`pending_build`) / not served (`build_failed`, `not_found`, `withdrawn`, no usable artifact). Nothing is touched: the older patch's artifact, wiring and ledger entry stay in force, the detail names both uuids (`kept the vendored patch : prebuilt is still building for patch `, where `` is the backend's artifact kind: `artifact` for the npm family, `.gem`, `crate`, `module zip`, `dist zip`, `wheel`, `.jar`, `.nupkg`, …), and the run does not fail (exit 0), the way hosted mode keeps its pin and lists the upgrade in `redirect.skipped[]`. A re-run picks the new patch up once the service serves it. A package with no vendored patch to keep still fails (`failed`, error `prebuilt is still building` / `prebuilt unavailable: `; outside the npm family under `vendor_prebuilt_required`), as does a request/transport failure. | | `unsafe_coordinates` | `failed` | vendor: purl/uuid would escape `.socket/vendor/` (tampered manifest/state); refused before any write. | | `revert_failed` | `failed` | vendor --revert: a recorded entry could not be reverted. | @@ -2099,6 +2101,8 @@ command's integration tests check its output. | `upstream_gem_install_refreshed` | `warnings[]` (note) | rollback / remove / a withdrawn-patch restore (gem): an installed copy or cache-dir archive the unwind replaced with the sha256-verified upstream gem. A human run prints a progress line instead. | | `upstream_gem_install_would_refresh` | `warnings[]` (note) | the same on `--dry-run`: what a wet unwind would replace. | | `redirect_gem_version_not_locked` | `warnings[]` (warning) | scan `--mode hosted` (gem): the crawled gem version is installed on the machine but no `GEM` section of the project's lock resolves it (another project's copy in the shared gem home). The gem is skipped and the Gemfile and lock stay byte-identical. | +| `redirect_maven_version_not_selected` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the build does not resolve the artifact at the patch's base version; the detail names the version Maven selects instead, or says that the build does not resolve the artifact. `pom.xml` and `.mvn/` stay byte-identical and the dep is not counted as redirected. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). | +| `redirect_maven_selection_undetermined` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): what the build selects for the artifact cannot be read and `pom.xml` declares no version of it to replace, so no `` pin is written on a guess. `pom.xml` and `.mvn/` stay byte-identical; the detail carries the reason and the remedy (resolve the project once and re-run, or declare the artifact at the base version). | | `redirect_gem_no_checksums_section` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock has no `CHECKSUMS` section (Bundler < 2.6 does not write one), so it cannot record the sha256 of the patched gems. They are redirected all the same (manifest and lock converged, frozen installs accept the pair) and pinned by source alone. Reported once per run, naming the gems; relock with Bundler ≥ 2.6 (`bundle lock --add-checksums`) and re-run to pin the checksums too. | | `redirect_gem_merged_lock_layout` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock was written by Bundler < 2.2 (`BUNDLED WITH`), which lists every gem source in ONE `GEM` section, so this run added the patch registry to that section's `remote:` lines. The pair installs with that Bundler, frozen / deployment mode included. Newer Bundlers deprecate such a section and from 2.5 on refuse the pair under frozen / deployment mode: if a newer Bundler installs the project, run `bundle lock` with it, commit the lock and re-run the hosted scan. Raised only by a run that wrote the lock. | | `redirect_gem_unrecognized_declaration` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the gem's declaration cannot take a `source:` option in place (the detail gives the reason). The gem is skipped and the manifest and lock stay byte-identical for it; write the declaration as one `gem "", …` call with literal arguments on a line of its own, or use `--mode vendored` / `--mode agent`. | @@ -2702,6 +2706,58 @@ vendoring option so scan/get/repair receive it too; omission preserves the ledger's recorded choice. Switching existing auto-config wiring to `none` requires reverting it first. `none` cannot be combined with a repository ban. +### Maven version selection (hosted and vendored Maven) + +A `` pin makes every occurrence of an artifact one +version. Written where Maven selects another version, it changes what the +build resolves: a silent downgrade when a newer version is nearer the root, an +upgrade when an older one is. Hosted and vendored mode therefore pin a patch of +`g:a:v` only where Maven selects `v` already, so the artifacts a build resolves +after a scan are the ones it resolved before, each patched one in its patched +build. + +What Maven selects is read, never run: from the project's poms and the poms +the Maven local repository holds (Maven caches the pom of every artifact, +parent and BOM it reads). The model follows Maven 3's resolver per module: the +module's own and inherited ``, then each artifact's `compile` / +`runtime`, non-optional dependencies, less what an `` removes; a +declared version, else the managed one (parent chain, then imported BOMs), the +module's management overriding every transitive version; a version range as +the highest version in it that the cached `maven-metadata-*.xml` lists; and +mediation: the nearest declaration wins, the first declared on a tie, and what +a losing version depends on leaves the graph. A `-socket.` version +an earlier run wrote reads as its base version, and a pin vendoring wrote is +not read as the project's management. + +Each answer is certain or not. It is not certain when something it depends on +could not be read: a pom missing from the local repository (the project was +never resolved there), a version or coordinate through a property that is +undefined or that a profile redefines, a profile that declares dependencies or +management, a relocated artifact, a dependency cycle, a range the cached +metadata does not resolve, or a Maven 4 build (a wrapper that pins Maven 4, or +a model 4.1.0 pom: its dependency management differs). A version selected as +the highest of a range is never pinned either, since a pin would freeze the +range. + +| Mode | The build selects another version, or does not resolve the artifact | The selection is not certain | +|---|---|---| +| hosted | `redirect_maven_version_not_selected` (warning); nothing written | a declaration that names the base version is rewritten where it stands (that replaces the version in place and moves nothing); otherwise `redirect_maven_selection_undetermined` (warning), nothing written | +| vendored | `vendor_maven_version_not_selected` (`skipped`, exit 0), decided before any download; nothing written | a declaration that names the base version is rewritten; no root is pinned (`vendor_jvm_degraded`, `reason: selection_undetermined`), and a pin already there is kept. With no such declaration: `vendor_maven_selection_undetermined` (`skipped`, exit 0), nothing written | +| agent | not applicable: the cached jar is patched in place under its own coordinates, which cannot change what a build resolves. A version whose directory in the local repository holds its pom and no jar (Maven read the pom while mediating and never downloaded the artifact) is not a package agent mode can patch: the scan leaves it out instead of failing it as a targeted patch that matched no installed package | | + +In a vendored reactor a local root is pinned only when every module that +inherits it resolves the artifact at the base version or not at all. A module +that resolves another version leaves the root unpinned (`vendor_jvm_degraded`, +`reason: version_not_selected`, naming the module and its version); a patch +that then reaches no pom is refused as `nothing_wired` with that reason. +`vendor --check` accepts the pins a run with the local repository's current +answer writes and the pins a run with no such answer writes. + +The not-selected line reads `Maven selects : in this build, +not , so the patch for has nothing to patch here` (or `no module +of this build resolves :, …`). The scan still looks up and applies a +patch for the version that is selected. + ### sbt resolution evidence (hosted and vendored sbt) Hosted and vendored sbt pins are gated on sbt's own resolution records under @@ -3046,7 +3102,7 @@ with `reason: : `: |---|---|---| | `vendor_jvm_shape_unsupported` | refusal, nothing written | `gradle_below_6_8`, `android_or_kmp` (also `available-at` module redirects), `gradle_exclusive_content_conflict` (a user rule claiming the module, in any script), `gradle_range_excludes_vendored` (no declared selector admits the vendored version), `gradle_classifier_computed` (a declaration of the module names its classifier through a variable, such as `${osdetector.classifier}`: the vendored repository would claim that jar without holding it), `gradle_verification_unparseable`, `gradle_index_unreadable`, `build_file_unreadable` (including a non-UTF-8 settings file), `build_file_outside_root`, `not_build_root` (run from a directory an ancestor settings file includes or may include, from a project with no settings file of its own below one, or below an ancestor settings file that is not UTF-8; `repair` refuses there too), `no_build_file` (no `pom.xml`, Gradle, sbt or scala-cli build at the root), `legacy_maven_root` (the root's ledger still holds a pre-v5 single-POM `maven_pom_repository` entry; the whole root is refused until `vendor --revert`, then vendor again) | | `vendor_jvm_upstream_unavailable` | refusal | `classifier_unavailable` (a declared classifier jar no cache or registry has), `module_unavailable` (the pom declares Gradle module metadata that cannot be sourced), `pom_unavailable`, `verification_metadata_unavailable`; for a suffixed Maven / sbt pom also `suffix_unavailable` (the upstream pom computes its own version), `parent_unavailable` (a first vendoring whose upstream parent poms are in no local cache and cannot be fetched, so the suffixed pom cannot be checked) and `inherited_version_unresolvable` (a parent pom names `${project.version}` where the suffixed pom cannot declare the base version instead: in a profile, a management key or a repository URL) | -| `vendor_jvm_degraded` | applied, VEX withheld | `gradle_unscanned_build_logic`, `unwired_build_logic` (a nonliteral included build), `settings_plugins_unwired`, `classifier_unpatched_copy` (a classifier jar carries an unpatched copy of a patched member), `verification_parent_chain_unhandled`, `gradle_lock_overrides_vendored` (a dependency lock of the build, buildscript and settings classpath locks included, pins the module at a version no vendored row serves), `gradle_settings_lock_unrouted` (a `settings-gradle.lockfile` locks the module but that build's settings script does not hold the in-block repository entry for it), `gradle_lock_unreadable` (a lock file, or a followed custom `lockFile`, is missing, unreadable, outside the checkout or not UTF-8), `gradle_custom_lock_file` (a `lockFile` location that cannot be followed statically: anything but a literal `file(…)` in a project's own build script), `gradle_wiring_uncommitted` (VEX liveness only, never reported by `vendor`: the committed settings files, index, derived `maven-metadata.xml`, script or verification file lack wiring a re-plan would write, such as a removed apply line or in-block entry; the git hygiene files do not count), `conflicting_managed_version` / `management_unresolved` (Maven reactor: an imported BOM or an out-of-checkout parent manages the artifact at another version, or its POM is unavailable; that local root is not pinned) | +| `vendor_jvm_degraded` | applied, VEX withheld | `gradle_unscanned_build_logic`, `unwired_build_logic` (a nonliteral included build), `settings_plugins_unwired`, `classifier_unpatched_copy` (a classifier jar carries an unpatched copy of a patched member), `verification_parent_chain_unhandled`, `gradle_lock_overrides_vendored` (a dependency lock of the build, buildscript and settings classpath locks included, pins the module at a version no vendored row serves), `gradle_settings_lock_unrouted` (a `settings-gradle.lockfile` locks the module but that build's settings script does not hold the in-block repository entry for it), `gradle_lock_unreadable` (a lock file, or a followed custom `lockFile`, is missing, unreadable, outside the checkout or not UTF-8), `gradle_custom_lock_file` (a `lockFile` location that cannot be followed statically: anything but a literal `file(…)` in a project's own build script), `gradle_wiring_uncommitted` (VEX liveness only, never reported by `vendor`: the committed settings files, index, derived `maven-metadata.xml`, script or verification file lack wiring a re-plan would write, such as a removed apply line or in-block entry; the git hygiene files do not count), `conflicting_managed_version` / `management_unresolved` (Maven reactor: an imported BOM or an out-of-checkout parent manages the artifact at another version, or its POM is unavailable; that local root is not pinned), `version_not_selected` / `selection_undetermined` (Maven reactor: a module under that local root resolves the artifact at another version than the patch's base, so the root is not pinned; or what a module resolves cannot be read, so the root's pin is left as it is. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven)) | | `vendor_jvm_note` | applied, informational | `range_declared` (a range, prefix or rich selector lists versions from the derived `maven-metadata.xml`), `ide_sources_unavailable` | | `vendor_jvm_upstream_unverified` | warning | Upstream metadata was taken offline, or from a local cache while the registry published no checksum for it (a parent pom from a corporate repository), and not authenticated against registry checksums. | | `vendor_jvm_unattested` | warning (`vendor --check`) | A Maven reactor entry is intact and wired, but a declaration may still build the base release (an executable classifier or type copy, a version a property, profile or unpinned local root may move), so `vex` does not attest it. The entry stays `verified`; the detail names the purl and the declarations (`:`). | diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 8934e26f5..d695b5a2e 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -1527,6 +1527,21 @@ async fn run_redirect_selected_untracked( // parent directory's and `$CARGO_HOME`'s): a directory source or local // registry in any of them refuses the cargo rewrite like a project one. let cargo_outer = || CargoCrawler::crates_io_source_for(&common.cwd); + // What Maven selects in each module, from the poms its local repository + // holds: a pin is written only where that is the patch's base version. + // Read once: the rewrite may run several times. + let maven_selection_once = std::sync::OnceLock::new(); + let maven_selection = || { + Some( + maven_selection_once + .get_or_init(|| { + socket_patch_core::crawlers::maven_selection::MavenSelection::for_project( + &common.cwd, + ) + }) + .clone(), + ) + }; // The scan runs in the install's environment: a pnpm setting there // (`pnpm_config_trust_lockfile`) overrides the project's files. let pnpm_env = |var: &str| std::env::var(var).ok(); @@ -1544,6 +1559,7 @@ async fn run_redirect_selected_untracked( npm_outer: &npm_outer, yarn_classic_outer: &yarn_classic_outer, cargo_outer: &cargo_outer, + maven_selection: &maven_selection, pnpm_env: &pnpm_env, blocking: true, takeover_uuids: takeover_uuids.clone(), diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 7e96d79c7..fd073246b 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2454,6 +2454,23 @@ async fn scan_project( args.common.allow_patch_conflicts }); + // Agent mode patches the installed jar where it lies. A version whose + // directory in the Maven local repository holds only its pom was never + // downloaded (Maven reads the pom of every version it weighs, and + // fetches the jar of the one it selects): there is nothing to patch, + // and it must not end the run as a targeted patch that matched no + // installed package. + if apply { + filtered_crawled.retain(|package| { + Ecosystem::from_purl(&package.purl) != Some(Ecosystem::Maven) + || !socket_patch_core::crawlers::maven_crawler::pom_only_version_dir( + &package.path, + &package.name, + &package.version, + ) + }); + } + // Gradle discovery notes (m2 gating, the user home) ride the run-level // warnings; the lock set only annotates `packages[]` below. let gradle = gradle_scan( diff --git a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs index a2f6b2b0b..525112fae 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs @@ -61,6 +61,8 @@ mod rollback_json; mod hosted_maven_common; #[path = "maven_build_common/mod.rs"] mod maven_build_common; +#[path = "maven_mediation_common/mod.rs"] +mod maven_mediation_common; #[path = "vex_e2e_common/mod.rs"] mod vex_e2e_common; @@ -519,3 +521,214 @@ fn maven_scan_hosted_fresh_checkout_install_and_manifestless_vex() { } assert!(!proj.join(".socket/vendor/redirect-state.json").exists()); } + +// ── a pin follows the version Maven selects ───────────────────────────── + +mod mediation { + use super::maven_mediation_common::{self as fixture, Shape}; + use super::*; + + const UUID: &str = "6f708192-a3b4-4c5d-8e6f-708192a3b4c5"; + const PATCH: Hosted = Hosted { + org: ORG, + uuid: UUID, + hex8: "6f708192", + token: "33333333-4444-4555-8666-777777777777", + ghsa: "GHSA-mediation-maven-hosted", + cve: "CVE-2026-7203", + group: fixture::GROUP, + artifact: fixture::VICTIM, + version: fixture::BASE, + title: "maven mediation capstone", + }; + + fn warning<'e>(env: &'e serde_json::Value, code: &str) -> Option<&'e serde_json::Value> { + env["warnings"] + .as_array() + .into_iter() + .flatten() + .find(|w| w["code"] == code) + } + + /// A hosted scan never changes which version of an artifact a Maven + /// build resolves. For each shape of the bug (a nearer version, an + /// excluded path, a declaration of another version, a range, with the + /// patch's base version elsewhere in the graph or only in the local + /// repository) the scan leaves the project byte for byte as it was, + /// exits 0 and says which version Maven selects; the jars Maven + /// resolves afterwards are the jars it resolved before. Where the base + /// version is the one selected, two levels down, the scan pins it and + /// Maven resolves the patched jar in its place. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_pins_follow_the_version_maven_selects() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().canonicalize().unwrap(); + let m2 = root.join("m2"); + let plain = root.join("settings-plain.xml"); + write_settings(&plain, &[]); + + let server = Server::start(); + fixture::publish(&server); + let patched_jar = fixture::patched_victim_jar(); + let suffixed = PATCH.suffixed(); + let served_pom = fixture::served_victim_pom(&suffixed).into_bytes(); + let view = patch_view( + UUID, + &fixture::purl(), + &[( + &fixture::victim_jar_name(fixture::BASE), + &git_sha256(&patched_jar), + )], + &[(PATCH.ghsa, &[PATCH.cve])], + ); + hosted_maven_common::mount_api(&server, &PATCH, &patched_jar, &served_pom, &view); + fixture::answer_lookups_only_for(&server, ORG, &fixture::purl()["pkg:maven/".len()..]); + server.serve_repo(&PATCH, &patched_jar, &served_pom, None); + let scan = |proj: &Path| { + socket( + proj, + &m2, + &[ + "scan", + "--mode", + "hosted", + "--json", + "--yes", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + &server.uri(), + "--org", + ORG, + "--api-token", + "fake", + ], + ) + }; + + // The base version is not the one selected: nothing may move. The + // first shape runs against a local repository that holds nothing + // else, where Maven reads the base version's pom and never fetches + // its jar (the table's V5). + let unselected = |shape: Shape| -> Option<()> { + let proj = root.join(shape.name()); + fixture::write_project(&proj, shape, &server); + let before = fixture::resolve(SUITE, &mvn, &proj, &m2, &plain, "target/before")?; + assert!( + before.contains_key(&fixture::victim_jar_name(shape.selects())), + "{shape:?}: Maven selects {}: {:?}", + shape.selects(), + before.keys() + ); + let pristine = fixture::snapshot(&proj); + let (code, env, stderr) = scan(&proj); + assert_eq!(code, Some(0), "{shape:?}: {env}\n{stderr}"); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "{shape:?}: the scan must write nothing: {env}" + ); + // The line is owed whenever the scan saw the base version, which + // it does once Maven has cached its pom. + let base_pom = fixture::victim_dir(&m2, fixture::BASE).join(format!( + "{}-{}.pom", + fixture::VICTIM, + fixture::BASE + )); + if base_pom.is_file() { + let line = warning(&env, "redirect_maven_version_not_selected") + .unwrap_or_else(|| panic!("{shape:?}: no not-selected line: {env}")); + let detail = line["detail"].as_str().unwrap_or_default(); + assert!( + detail.contains(&format!( + "Maven selects {}:{} {}", + fixture::GROUP, + fixture::VICTIM, + shape.selects() + )) && detail.contains(&format!("not {}", fixture::BASE)), + "{shape:?}: the line names the selected version: {detail}" + ); + } + assert_eq!(env["summary"]["failed"], 0, "{shape:?}: {env}"); + let after = fixture::resolve_warm(&mvn, &proj, &m2, &plain, "target/after", &[]); + assert_eq!( + after, before, + "{shape:?}: Maven resolves what it resolved before" + ); + Some(()) + }; + if unselected(Shape::NearerNewer).is_none() { + return; + } + let base_dir = fixture::victim_dir(&m2, fixture::BASE); + assert!( + !base_dir + .join(fixture::victim_jar_name(fixture::BASE)) + .exists(), + "Maven never fetched the jar of the version that lost: {:?}", + std::fs::read_dir(&base_dir) + .map(|d| d.flatten().map(|e| e.file_name()).collect::>()) + ); + for shape in [Shape::NearerOlder, Shape::DirectOther, Shape::Excluded] { + unselected(shape).expect("the local repository is warm"); + } + + // The base version is the one selected: the patched build takes its + // place, and nothing else moves. + let proj = root.join(Shape::Selected.name()); + fixture::write_project(&proj, Shape::Selected, &server); + let before = fixture::resolve(SUITE, &mvn, &proj, &m2, &plain, "target/before") + .expect("the local repository is warm"); + assert!(before.contains_key(&fixture::victim_jar_name(fixture::BASE))); + let (code, env, stderr) = scan(&proj); + assert_eq!(code, Some(0), "selected: {env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + assert!( + warning(&env, "redirect_maven_version_not_selected").is_none(), + "{env}" + ); + let wired = std::fs::read_to_string(proj.join("pom.xml")).unwrap(); + assert!( + wired.contains(&format!("{suffixed}")) + && wired.contains(&format!("socket-patch-{UUID}")), + "the pinned pom:\n{wired}" + ); + let mirrored = root.join("settings-socket.xml"); + let mirror_url = format!("{}{}", server.uri(), PATCH.repo_path()); + write_settings(&mirrored, &[(&format!("socket-patch-{UUID}"), &mirror_url)]); + let after = fixture::resolve_warm(&mvn, &proj, &m2, &mirrored, "target/after", &[]); + assert_eq!( + fixture::unsuffixed(after.keys()), + before.keys().cloned().collect(), + "the same artifacts, the victim in its patched build" + ); + assert_eq!( + after.get(&fixture::victim_jar_name(&suffixed)), + Some(&patched_jar), + "Maven resolves the patched jar: {:?}", + after.keys() + ); + for (name, bytes) in &before { + if *name != fixture::victim_jar_name(fixture::BASE) { + assert_eq!(after.get(name), Some(bytes), "{name} is untouched"); + } + } + // A second scan finds its pin and changes nothing. + let pinned = fixture::snapshot(&proj); + let (code, env, stderr) = scan(&proj); + assert_eq!(code, Some(0), "rescan: {env}\n{stderr}"); + assert_eq!( + fixture::snapshot(&proj), + pinned, + "a rescan is a no-op: {env}" + ); + + // The base version now sits in the local repository, jar and all, + // and no pom of this project names it: a range selects another. + unselected(Shape::Ranged).expect("the local repository is warm"); + } +} diff --git a/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs index 21e67d5b9..f22f81f0f 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs @@ -43,8 +43,12 @@ //! `SOCKET_PATCH_MAVEN_E2E_{MVN,VERSION,REQUIRED}` gates in //! `maven_build_common`. +#[path = "hosted_maven_common/mod.rs"] +mod hosted_maven_common; #[path = "maven_build_common/mod.rs"] mod maven_build_common; +#[path = "maven_mediation_common/mod.rs"] +mod maven_mediation_common; #[path = "prebuilt_common/mod.rs"] mod prebuilt_common; #[path = "vex_e2e_common/mod.rs"] @@ -632,3 +636,294 @@ fn maven_vendor_keeps_a_sibling_the_parent_manages_at_the_base_version() { "Maven consumes the committed, patched jar" ); } + +// ── a pin follows the version Maven selects ───────────────────────────── + +mod mediation { + use super::hosted_maven_common::Server; + use super::maven_mediation_common::{self as fixture, Shape}; + use super::*; + + const UUID: &str = "708192a3-b4c5-4d6e-8f70-8192a3b4c5d6"; + const ORG: &str = "test-org"; + + /// The base victim's version as vendoring pins it. + fn suffixed() -> String { + format!("{}-socket.{}", fixture::BASE, &UUID[..8]) + } + + /// What `get` saves for the patch of the base victim: the manifest + /// record and the after-hash blob. + fn stage(proj: &Path) { + let (before, after) = ( + fixture::pristine_member(fixture::VICTIM, fixture::BASE), + fixture::patched_member(), + ); + let record = serde_json::json!({ + "uuid": UUID, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { fixture::MEMBER: { + "beforeHash": git_sha256(&before), + "afterHash": git_sha256(&after), + } }, + "vulnerabilities": { "GHSA-mediation-maven-vendored": { + "cves": ["CVE-2026-7204"], "summary": "s", "severity": "high", "description": "d" + } }, + "description": "maven mediation capstone", + "license": "MIT", + "tier": "free", + }); + let manifest = serde_json::json!({ "patches": { fixture::purl(): record } }); + std::fs::create_dir_all(proj.join(".socket/blobs")).unwrap(); + std::fs::write( + proj.join(".socket/manifest.json"), + serde_json::to_string_pretty(&manifest).unwrap(), + ) + .unwrap(); + std::fs::write(proj.join(".socket/blobs").join(git_sha256(&after)), after).unwrap(); + } + + fn skip_of<'e>(env: &'e serde_json::Value) -> Option<&'e serde_json::Value> { + env["events"] + .as_array() + .into_iter() + .flatten() + .find(|e| e["action"] == "skipped") + } + + /// Vendoring never changes which version of an artifact a Maven build + /// resolves, and agent mode never fails on a version Maven did not + /// download. For each shape of the bug the patch of the base version is + /// skipped with `vendor_maven_version_not_selected` (exit 0, the + /// selected version named), the project is byte for byte what it was, + /// and Maven resolves the jars it resolved before. Where the base + /// version is the one selected, two levels down, it is vendored and + /// Maven resolves the patched jar in its place. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_vendored_pins_follow_the_version_maven_selects() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().canonicalize().unwrap(); + let m2 = root.join("m2"); + let settings = root.join("settings.xml"); + write_settings(&settings, &[]); + let server = Server::start(); + fixture::publish(&server); + let vendor = |proj: &Path| { + socket( + proj, + &m2, + &[ + "vendor", + "--json", + "--offline", + "--cwd", + proj.to_str().unwrap(), + ], + ) + }; + + let unselected = |shape: Shape| -> Option<()> { + let proj = root.join(shape.name()); + fixture::write_project(&proj, shape, &server); + let before = fixture::resolve(SUITE, &mvn, &proj, &m2, &settings, "target/before")?; + assert!( + before.contains_key(&fixture::victim_jar_name(shape.selects())), + "{shape:?}: Maven selects {}: {:?}", + shape.selects(), + before.keys() + ); + stage(&proj); + let pristine = fixture::snapshot(&proj); + let (code, env, stderr) = vendor(&proj); + assert_eq!(code, Some(0), "{shape:?}: {env}\n{stderr}"); + assert_eq!(env["status"], "success", "{shape:?}: {env}"); + assert_eq!(env["summary"]["applied"], 0, "{shape:?}: {env}"); + assert_eq!(env["summary"]["failed"], 0, "{shape:?}: {env}"); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "{shape:?}: vendoring must write nothing: {env}" + ); + let skip = skip_of(&env).unwrap_or_else(|| panic!("{shape:?}: no skip: {env}")); + // Without the base version's pom in the local repository the + // package is not installed at all, which is a skip of its own. + let base_pom = fixture::victim_dir(&m2, fixture::BASE).join(format!( + "{}-{}.pom", + fixture::VICTIM, + fixture::BASE + )); + if base_pom.is_file() { + assert_eq!( + skip["errorCode"], "vendor_maven_version_not_selected", + "{shape:?}: {env}" + ); + let reason = skip["reason"].as_str().unwrap_or_default(); + assert!( + reason.contains(&format!( + "Maven selects {}:{} {}", + fixture::GROUP, + fixture::VICTIM, + shape.selects() + )), + "{shape:?}: the skip names the selected version: {reason}" + ); + } + let after = fixture::resolve_warm(&mvn, &proj, &m2, &settings, "target/after", &[]); + assert_eq!( + after, before, + "{shape:?}: Maven resolves what it resolved before" + ); + Some(()) + }; + + // The first shape runs against a local repository that holds + // nothing else: Maven read the pom of the base version, which lost, + // and never fetched its jar (the table's V5). + if unselected(Shape::NearerNewer).is_none() { + return; + } + let base_dir = fixture::victim_dir(&m2, fixture::BASE); + let base_jar = base_dir.join(fixture::victim_jar_name(fixture::BASE)); + assert!(!base_jar.exists(), "Maven never fetched the losing jar"); + + // Agent mode patches jars where they lie: a version with no jar is + // not a package it can patch, and not a failure either. + if base_dir.is_dir() { + let proj = root.join(Shape::NearerNewer.name()); + std::fs::remove_dir_all(proj.join(".socket")).unwrap(); + let patched_jar = fixture::patched_victim_jar(); + let view = patch_view( + UUID, + &fixture::purl(), + &[(fixture::MEMBER, &git_sha256(&fixture::patched_member()))], + &[("GHSA-mediation-maven-vendored", &["CVE-2026-7204"])], + ); + let patch = hosted_maven_common::Hosted { + org: ORG, + uuid: UUID, + hex8: "708192a3", + token: "44444444-5555-4666-8777-888888888888", + ghsa: "GHSA-mediation-maven-vendored", + cve: "CVE-2026-7204", + group: fixture::GROUP, + artifact: fixture::VICTIM, + version: fixture::BASE, + title: "maven mediation capstone", + }; + hosted_maven_common::mount_api(&server, &patch, &patched_jar, b"", &view); + fixture::answer_lookups_only_for(&server, ORG, &fixture::purl()["pkg:maven/".len()..]); + let repository = fixture::snapshot(&m2); + let pristine = std::fs::read(proj.join("pom.xml")).unwrap(); + let (code, env, stderr) = socket( + &proj, + &m2, + &[ + "scan", + "--mode", + "agent", + "--json", + "--yes", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + &server.uri(), + "--org", + ORG, + "--api-token", + "fake", + ], + ); + assert_eq!(code, Some(0), "agent scan: {env}\n{stderr}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + assert!( + !stderr.contains("not found on disk") && !stderr.contains("no matching variant"), + "a version with no jar is not a failed patch: {stderr}" + ); + assert_eq!( + fixture::snapshot(&m2), + repository, + "the local repository is untouched" + ); + assert_eq!(std::fs::read(proj.join("pom.xml")).unwrap(), pristine); + let _ = std::fs::remove_dir_all(proj.join(".socket")); + } + + for shape in [Shape::NearerOlder, Shape::DirectOther, Shape::Excluded] { + unselected(shape).expect("the local repository is warm"); + } + + // The base version is the one selected: the patched build takes its + // place, and nothing else moves. + let proj = root.join(Shape::Selected.name()); + fixture::write_project(&proj, Shape::Selected, &server); + let before = fixture::resolve(SUITE, &mvn, &proj, &m2, &settings, "target/before") + .expect("the local repository is warm"); + assert!(before.contains_key(&fixture::victim_jar_name(fixture::BASE))); + stage(&proj); + let pristine = fixture::snapshot(&proj); + let (code, env, stderr) = vendor(&proj); + assert_eq!(code, Some(0), "selected: {env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + let sv = suffixed(); + let wired = std::fs::read_to_string(proj.join("pom.xml")).unwrap(); + assert!( + wired.contains(&format!("{sv}")), + "the pinned pom:\n{wired}" + ); + let after = fixture::resolve_warm(&mvn, &proj, &m2, &settings, "target/after", &[]); + assert_eq!( + fixture::unsuffixed(after.keys()), + before.keys().cloned().collect(), + "the same artifacts, the victim in its patched build" + ); + let resolved = after + .get(&fixture::victim_jar_name(&sv)) + .unwrap_or_else(|| panic!("Maven resolves the vendored jar: {:?}", after.keys())); + assert_eq!( + jar_member(resolved, fixture::MEMBER), + Some(fixture::patched_member()), + "the resolved jar is the patched one" + ); + for (name, bytes) in &before { + if *name != fixture::victim_jar_name(fixture::BASE) { + assert_eq!(after.get(name), Some(bytes), "{name} is untouched"); + } + } + // A second run is in sync, and the revert restores every byte. + let vendored = fixture::snapshot(&proj); + let (code, env, stderr) = vendor(&proj); + assert_eq!(code, Some(0), "re-vendor: {env}\n{stderr}"); + assert_eq!( + fixture::snapshot(&proj), + vendored, + "a second run is a no-op: {env}" + ); + let (code, env, stderr) = socket( + &proj, + &m2, + &[ + "vendor", + "--revert", + "--json", + "--cwd", + proj.to_str().unwrap(), + ], + ); + assert_eq!(code, Some(0), "revert: {env}\n{stderr}"); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "the revert restores every byte" + ); + + // The base version now sits in the local repository, jar and all, + // and no pom of this project names it: a range selects another. + unselected(Shape::Ranged).expect("the local repository is warm"); + } +} diff --git a/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs new file mode 100644 index 000000000..097e67ef5 --- /dev/null +++ b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs @@ -0,0 +1,419 @@ +//! The dependency graphs the mediation capstones build with a real Maven +//! (`e2e_redirect_maven_build` hosted, `e2e_vendor_maven_build` vendored +//! and agent): a pin must follow the version Maven selects, never move it. +//! +//! Every artifact is generated here and served by the test's own wiremock +//! server as a plain maven2 repository the project pom names (`fixture`), +//! so no shape needs Maven Central for anything but the dependency plugin +//! the suites already fetch: +//! +//! * `victim:{1.9,1.10.0,1.11.0}`: the patched artifact; the patch is for +//! [`BASE`] and rewrites [`MEMBER`]. +//! * `lib-base:1.0` → `victim:1.10.0`, `lib-new:1.0` → `victim:1.11.0`, +//! `lib-old:1.0` → `victim:1.9`, `lib-deep:1.0` → `lib-base:1.0`, +//! `lib-range:1.0` → `victim:[1.10.5,1.11.0]`. +//! * the artifact-level `maven-metadata.xml` of `victim`, which resolves +//! the range. +//! +//! One [`Shape`] per row of the bug: which version Maven selects for the +//! victim, with the base version somewhere else in the graph (deeper, +//! excluded, or only in the local repository). + +#![allow(dead_code)] + +use std::collections::{BTreeMap, BTreeSet}; +use std::io::Write as _; +use std::path::Path; +use std::process::Output; + +use crate::hosted_maven_common::{sha1_hex, Server}; +use crate::maven_build_common::{ + dump, ok, with_central_fallback, write_settings, Mvn, DEPENDENCY_PLUGIN, +}; + +pub const GROUP: &str = "com.socketfixture.mediation"; +pub const GROUP_PATH: &str = "com/socketfixture/mediation"; +pub const VICTIM: &str = "victim"; +/// The version the patch is for. +pub const BASE: &str = "1.10.0"; +pub const OLDER: &str = "1.9"; +pub const NEWER: &str = "1.11.0"; +/// The jar member the patch rewrites. +pub const MEMBER: &str = "META-INF/NOTICE.txt"; +pub const MARKER: &str = "SOCKET-PATCH-MEDIATION-MARKER"; +/// Where the server serves the fixture repository. +const REPO_ROUTE: &str = "/fixture-repo"; + +pub fn purl() -> String { + format!("pkg:maven/{GROUP}/{VICTIM}@{BASE}") +} + +/// How a project reaches the victim. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Shape { + /// The base version is the only one in the graph, two levels down. + Selected, + /// V1: a newer version is nearer the root, the base version deeper. + NearerNewer, + /// V2: an older version is nearer the root, the base version deeper. + NearerOlder, + /// V4: the project declares another version itself. + DirectOther, + /// V6: the only path to the base version is excluded. + Excluded, + /// V7: no pom of the build names the base version; a range selects + /// another one, and the base is merely in the local repository. + Ranged, +} + +impl Shape { + pub fn name(self) -> &'static str { + match self { + Shape::Selected => "selected", + Shape::NearerNewer => "nearer-newer", + Shape::NearerOlder => "nearer-older", + Shape::DirectOther => "direct-other", + Shape::Excluded => "excluded", + Shape::Ranged => "ranged", + } + } + + /// The victim version Maven selects. + pub fn selects(self) -> &'static str { + match self { + Shape::Selected => BASE, + Shape::NearerOlder => OLDER, + _ => NEWER, + } + } + + fn dependencies(self) -> String { + let exclusion = format!( + "\n \n \n {GROUP}\n \ + {VICTIM}\n \n " + ); + match self { + Shape::Selected => dependency("lib-deep", "1.0", ""), + Shape::NearerNewer => [ + dependency("lib-new", "1.0", ""), + dependency("lib-deep", "1.0", ""), + ] + .concat(), + Shape::NearerOlder => [ + dependency("lib-old", "1.0", ""), + dependency("lib-deep", "1.0", ""), + ] + .concat(), + Shape::DirectOther => [ + dependency("lib-base", "1.0", ""), + dependency(VICTIM, NEWER, ""), + ] + .concat(), + // Declared first: without the exclusion the base version would + // win the tie with lib-new's. + Shape::Excluded => [ + dependency("lib-base", "1.0", &exclusion), + dependency("lib-new", "1.0", ""), + ] + .concat(), + Shape::Ranged => dependency("lib-range", "1.0", ""), + } + } +} + +fn dependency(artifact: &str, version: &str, extra: &str) -> String { + format!( + " \n {GROUP}\n \ + {artifact}\n {version}{extra}\n \ + \n" + ) +} + +/// The pom of fixture artifact `artifact:version` depending on `deps`. +fn fixture_pom(artifact: &str, version: &str, deps: &[(&str, &str)]) -> String { + let deps: String = deps.iter().map(|(a, v)| dependency(a, v, "")).collect(); + let deps = match deps.is_empty() { + true => String::new(), + false => format!(" \n{deps} \n"), + }; + format!( + "\n\ + \n \ + 4.0.0\n {GROUP}\n \ + {artifact}\n {version}\n{deps}\n" + ) +} + +/// The upstream pom of the victim at `version`. +pub fn victim_pom(version: &str) -> String { + fixture_pom(VICTIM, version, &[]) +} + +/// The pom the Socket repository serves for the patched victim: the +/// upstream pom at the suffixed version. +pub fn served_victim_pom(suffixed: &str) -> String { + victim_pom(BASE).replace( + &format!("{BASE}"), + &format!("{suffixed}"), + ) +} + +/// What [`MEMBER`] holds in the pristine jar of `artifact:version`. +pub fn pristine_member(artifact: &str, version: &str) -> Vec { + format!("Socket mediation fixture: {GROUP}:{artifact}:{version}\n").into_bytes() +} + +/// What the patch makes of the base victim's [`MEMBER`]. +pub fn patched_member() -> Vec { + let mut out = pristine_member(VICTIM, BASE); + out.extend_from_slice(format!("{MARKER}\n").as_bytes()); + out +} + +/// A jar holding [`MEMBER`] with `member` (stored, fixed timestamp). +pub fn jar(member: &[u8]) -> Vec { + let mut out = std::io::Cursor::new(Vec::new()); + { + let mut writer = zip::ZipWriter::new(&mut out); + let opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Stored) + .last_modified_time(zip::DateTime::from_date_and_time(2026, 1, 1, 0, 0, 0).unwrap()); + writer.start_file(MEMBER, opts).unwrap(); + writer.write_all(member).unwrap(); + writer.finish().unwrap(); + } + out.into_inner() +} + +/// The pristine jar of the victim at `version`. +pub fn victim_jar(version: &str) -> Vec { + jar(&pristine_member(VICTIM, version)) +} + +/// The patched jar of the base victim. +pub fn patched_victim_jar() -> Vec { + jar(&patched_member()) +} + +fn serve(server: &Server, rel: &str, bytes: &[u8]) { + let route = format!("{REPO_ROUTE}/{rel}"); + server.get(&route, 200, bytes.to_vec()); + server.get(&format!("{route}.sha1"), 200, sha1_hex(bytes).into_bytes()); +} + +/// Serve the fixture repository from `server`. +pub fn publish(server: &Server) { + let artifacts: [(&str, &str, &[(&str, &str)]); 8] = [ + (VICTIM, OLDER, &[]), + (VICTIM, BASE, &[]), + (VICTIM, NEWER, &[]), + ("lib-base", "1.0", &[(VICTIM, BASE)]), + ("lib-new", "1.0", &[(VICTIM, NEWER)]), + ("lib-old", "1.0", &[(VICTIM, OLDER)]), + ("lib-deep", "1.0", &[("lib-base", "1.0")]), + ("lib-range", "1.0", &[(VICTIM, "[1.10.5,1.11.0]")]), + ]; + for (artifact, version, deps) in artifacts { + let dir = format!("{GROUP_PATH}/{artifact}/{version}"); + serve( + server, + &format!("{dir}/{artifact}-{version}.pom"), + fixture_pom(artifact, version, deps).as_bytes(), + ); + serve( + server, + &format!("{dir}/{artifact}-{version}.jar"), + &jar(&pristine_member(artifact, version)), + ); + } + let versions: String = [OLDER, BASE, NEWER] + .iter() + .map(|v| format!(" {v}\n")) + .collect(); + serve( + server, + &format!("{GROUP_PATH}/{VICTIM}/maven-metadata.xml"), + format!( + "\n\n {GROUP}\n \ + {VICTIM}\n \n {NEWER}\n \ + {NEWER}\n \n{versions} \n \ + 20260101000000\n \n\n" + ) + .as_bytes(), + ); +} + +/// The `pom.xml` of a project of `shape` resolving from `server`. +pub fn project_pom(shape: Shape, server: &Server) -> String { + format!( + "\n\ + \n \ + 4.0.0\n com.example\n \ + app\n 1.0.0\n jar\n \ + \n \n fixture\n \ + {}{REPO_ROUTE}\n \n \n \ + \n{} \n\n", + server.uri(), + shape.dependencies() + ) +} + +/// Write the project of `shape` into `dir`. +pub fn write_project(dir: &Path, shape: Shape, server: &Server) { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join("pom.xml"), project_pom(shape, server)).unwrap(); +} + +fn copy_dependencies( + mvn: &Mvn, + proj: &Path, + m2: &Path, + settings: &Path, + out_rel: &str, + extra: &[&str], +) -> Output { + let _ = std::fs::remove_dir_all(proj.join(out_rel)); + let goal = format!("{DEPENDENCY_PLUGIN}:copy-dependencies"); + let out_dir = format!("-DoutputDirectory={out_rel}"); + let mut args = vec![goal.as_str(), out_dir.as_str()]; + args.extend_from_slice(extra); + mvn.run(proj, m2, settings, &args) +} + +/// The jars Maven resolves for the project at `proj`, by file name +/// (`-.jar`). `None` when Maven Central, which holds the +/// dependency plugin, cannot be reached (skip printed; a failure on a +/// required leg). `settings` must hold no mirror. +pub fn resolve( + suite: &str, + mvn: &Mvn, + proj: &Path, + m2: &Path, + settings: &Path, + out_rel: &str, +) -> Option>> { + let out = with_central_fallback(suite, "dependency resolution", settings, |s, extra| { + copy_dependencies(mvn, proj, m2, s, out_rel, extra) + }); + if !ok(&out) { + crate::maven_build_common::skip( + suite, + &format!("resolving {} failed:\n{}", proj.display(), dump(&out)), + ); + return None; + } + Some(copied(proj, out_rel)) +} + +/// [`resolve`] once the local repository is warm, with any `settings` +/// (a mirror for the Socket repository) and extra Maven flags. +pub fn resolve_warm( + mvn: &Mvn, + proj: &Path, + m2: &Path, + settings: &Path, + out_rel: &str, + extra: &[&str], +) -> BTreeMap> { + let out = copy_dependencies(mvn, proj, m2, settings, out_rel, extra); + assert!(ok(&out), "{}:\n{}", proj.display(), dump(&out)); + copied(proj, out_rel) +} + +fn copied(proj: &Path, out_rel: &str) -> BTreeMap> { + let dir = proj.join(out_rel); + let jars = std::fs::read_dir(&dir) + .unwrap_or_else(|e| panic!("{}: {e}", dir.display())) + .flatten() + .map(|e| { + ( + e.file_name().to_string_lossy().into_owned(), + std::fs::read(e.path()).unwrap(), + ) + }) + .collect(); + let _ = std::fs::remove_dir_all(proj.join("target")); + jars +} + +/// `names` with every `-socket.` version suffix dropped: the +/// artifacts a build resolves, whether or not a patched build replaced +/// one. +pub fn unsuffixed<'a>(names: impl IntoIterator) -> BTreeSet { + names + .into_iter() + .map(|name| match name.find("-socket.") { + Some(at) + if name[at + 8..] + .chars() + .take(8) + .all(|c| c.is_ascii_hexdigit()) => + { + format!("{}{}", &name[..at], &name[at + 16..]) + } + _ => name.clone(), + }) + .collect() +} + +/// A batch lookup that does not ask about `needle`. +struct Lacks(String); + +impl wiremock::Match for Lacks { + fn matches(&self, request: &wiremock::Request) -> bool { + !String::from_utf8_lossy(&request.body).contains(&self.0) + } +} + +/// Make the patch lookup of `org` on `server` answer like the service: a +/// patch only for a package the scan asked about. (The shared hosted mock +/// answers every lookup with its one patch, so a package the crawl left +/// out would still come back patched.) +pub fn answer_lookups_only_for(server: &Server, org: &str, needle: &str) { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, ResponseTemplate}; + server.rt.block_on( + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{org}/patches/batch"))) + .and(Lacks(needle.to_string())) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(&server.server), + ); +} + +/// The victim's jar name at `version`. +pub fn victim_jar_name(version: &str) -> String { + format!("{VICTIM}-{version}.jar") +} + +/// `//victim//`. +pub fn victim_dir(m2: &Path, version: &str) -> std::path::PathBuf { + m2.join(GROUP_PATH).join(VICTIM).join(version) +} + +/// A settings file that shields the run from `~/.m2` and mirrors nothing. +pub fn plain_settings(path: &Path) { + write_settings(path, &[]); +} + +/// Every file under `dir` (relative, forward slashes) with its bytes. +pub fn snapshot(dir: &Path) -> BTreeMap> { + fn walk(base: &Path, dir: &Path, out: &mut BTreeMap>) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + walk(base, &path, out); + } else { + let rel = path.strip_prefix(base).unwrap().to_string_lossy(); + out.insert(rel.replace('\\', "/"), std::fs::read(&path).unwrap()); + } + } + } + let mut out = BTreeMap::new(); + walk(dir, dir, &mut out); + out +} diff --git a/crates/socket-patch-core/src/crawlers/maven_crawler.rs b/crates/socket-patch-core/src/crawlers/maven_crawler.rs index 20acf2921..8b7e3df04 100644 --- a/crates/socket-patch-core/src/crawlers/maven_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/maven_crawler.rs @@ -862,6 +862,44 @@ fn holds_artifact(dir: &Path) -> bool { }) } +/// Whether `dir`, the version directory of `artifact`:`version`, is one of +/// a Maven local repository that holds the pom and no artifact: Maven read +/// the version's pom (every version it weighs during mediation, every +/// parent and BOM) and never downloaded a jar, so there is no installed +/// copy to patch in place. +pub fn pom_only_version_dir(dir: &Path, artifact: &str, version: &str) -> bool { + // What Maven keeps beside an artifact: poms and Gradle modules, their + // checksum and signature sidecars, its own bookkeeping, and the marks + // of a failed or unfinished download. + const NOT_ARTIFACTS: &[&str] = &[ + ".pom", + ".module", + ".sha1", + ".md5", + ".sha256", + ".sha512", + ".asc", + ".lastUpdated", + ".part", + ".lock", + ".repositories", + ".properties", + ]; + if !dir.join(format!("{artifact}-{version}.pom")).is_file() { + return false; + } + !std::fs::read_dir(dir).is_ok_and(|entries| { + entries.flatten().any(|e| { + let name = e.file_name(); + let name = name.to_string_lossy(); + !name.starts_with('.') + && !name.starts_with("maven-metadata") + && !NOT_ARTIFACTS.iter().any(|ext| name.ends_with(ext)) + && e.file_type().is_ok_and(|t| t.is_file()) + }) + }) +} + /// Maven/Java ecosystem crawler for discovering packages in the JVM /// artifact caches: the local Maven repository (`~/.m2/repository/`), /// Gradle's module cache (`~/.gradle/caches/modules-2/files-2.1`, plus the @@ -2504,6 +2542,33 @@ mod tests { ); } + /// A version Maven only read the pom of (beside its tracking files) is + /// no installed copy; a jar of any classifier is one. + #[test] + fn a_version_dir_with_only_its_pom_holds_no_artifact() { + let dir = tempfile::tempdir().unwrap(); + let version = dir.path().join("org/x/lib/1.0"); + std::fs::create_dir_all(&version).unwrap(); + assert!(!pom_only_version_dir(&version, "lib", "1.0"), "no pom"); + for name in [ + "lib-1.0.pom", + "lib-1.0.pom.sha1", + "lib-1.0.jar.lastUpdated", + "_remote.repositories", + "resolver-status.properties", + "m2e-lastUpdated.properties", + "maven-metadata-central.xml", + ] { + std::fs::write(version.join(name), b"x").unwrap(); + } + assert!(pom_only_version_dir(&version, "lib", "1.0")); + std::fs::write(version.join("lib-1.0-tests.jar"), b"x").unwrap(); + assert!(!pom_only_version_dir(&version, "lib", "1.0")); + std::fs::remove_file(version.join("lib-1.0-tests.jar")).unwrap(); + std::fs::write(version.join("lib-1.0.jar"), b"x").unwrap(); + assert!(!pom_only_version_dir(&version, "lib", "1.0")); + } + // ---- m2_repo_path env tests ---- use crate::test_env::EnvGuard; diff --git a/crates/socket-patch-core/src/crawlers/maven_scope.rs b/crates/socket-patch-core/src/crawlers/maven_scope.rs index 4c0269cac..1228f44f4 100644 --- a/crates/socket-patch-core/src/crawlers/maven_scope.rs +++ b/crates/socket-patch-core/src/crawlers/maven_scope.rs @@ -25,7 +25,10 @@ //! the project names, never across artifacts it does not. //! //! Exclusions and mediation are not modelled (both only narrow what Maven -//! resolves), so the scope is a superset of the resolved graph. +//! resolves), so the scope is a superset of the resolved graph: what a +//! crawl may patch in place. Which version of an artifact each module +//! selects from it, and so where a pin is safe, is +//! [`maven_selection`](super::maven_selection)'s to say. use std::collections::{HashMap, HashSet, VecDeque}; use std::path::{Path, PathBuf}; @@ -70,17 +73,7 @@ impl ProjectScope { /// `repo`; `None` when `cwd/pom.xml` is not a readable pom or the graph is /// too big to walk (the crawl then stays unscoped). pub(crate) fn project_scope(cwd: &Path, repo: &Path) -> Option { - let mut walk = Walk { - cwd, - repo, - models: HashMap::new(), - scope: ProjectScope::default(), - queue: VecDeque::new(), - queued: HashSet::new(), - reactor_chains: Vec::new(), - reactor_managed: HashMap::new(), - work: Work::new(), - }; + let mut walk = Walk::new(cwd, repo); let walked = walk.reactor().and_then(|()| walk.run()); if walk.work.spent() { super::jvm_cache::debug_log(&format!( @@ -96,20 +89,20 @@ pub(crate) fn project_scope(cwd: &Path, repo: &Path) -> Option { /// A pom and where it was read from. #[derive(Clone)] -struct Node { - model: Arc, +pub(super) struct Node { + pub(super) model: Arc, /// The pom's file (for relative parent paths of reactor poms). - path: PathBuf, + pub(super) path: PathBuf, /// Read from the checkout (a reactor pom or a local parent). - local: bool, + pub(super) local: bool, } /// A pom and its parents, nearest first. -type Chain = Vec; +pub(super) type Chain = Vec; -struct Walk<'w> { - cwd: &'w Path, - repo: &'w Path, +pub(super) struct Walk<'w> { + pub(super) cwd: &'w Path, + pub(super) repo: &'w Path, /// Parsed poms by path (`None`: missing or unreadable). models: HashMap>>, scope: ProjectScope, @@ -120,11 +113,29 @@ struct Walk<'w> { /// [`Walk::managed_version`] of each reactor chain, by artifact. reactor_managed: HashMap<(usize, String, String), Option>>, /// The property lookups left to this walk. - work: std::rc::Rc, + pub(super) work: std::rc::Rc, + /// Why [`Walk::reactor_poms`] could not read a module the reactor + /// names: that part of the build is unknown. + pub(super) unread_modules: Vec, } -impl Walk<'_> { - fn model(&mut self, path: &Path, include_profiles: bool) -> Option> { +impl<'w> Walk<'w> { + pub(super) fn new(cwd: &'w Path, repo: &'w Path) -> Walk<'w> { + Walk { + cwd, + repo, + models: HashMap::new(), + scope: ProjectScope::default(), + queue: VecDeque::new(), + queued: HashSet::new(), + reactor_chains: Vec::new(), + reactor_managed: HashMap::new(), + work: Work::new(), + unread_modules: Vec::new(), + } + } + + pub(super) fn model(&mut self, path: &Path, include_profiles: bool) -> Option> { if let Some(found) = self.models.get(path) { return found.clone(); } @@ -156,7 +167,7 @@ impl Walk<'_> { } } - fn repo_pom(&self, (g, a, v): &Gav) -> Option { + pub(super) fn repo_pom(&self, (g, a, v): &Gav) -> Option { let safe = |s: &str| { !s.is_empty() && s != "." @@ -179,7 +190,7 @@ impl Walk<'_> { /// `node` and its parents: a reactor pom's local parent by /// `relativePath` (default `../pom.xml`) when that pom is the declared /// one, else the parent's pom in the repository. - fn chain(&mut self, node: Node) -> Chain { + pub(super) fn chain(&mut self, node: Node) -> Chain { let work = std::rc::Rc::clone(&self.work); let mut chain = vec![node]; while chain.len() < MAX_DEPTH { @@ -238,6 +249,29 @@ impl Walk<'_> { /// Read the reactor and queue every declaration it makes. fn reactor(&mut self) -> Option<()> { + let chains = self.reactor_poms()?; + for chain in &chains { + for decl in chain.iter().flat_map(|n| n.model.deps.clone()) { + self.declare(&decl, chain, true); + } + // Imported BOMs and parents are part of the build too. + for decl in chain.iter().flat_map(|n| n.model.managed.clone()) { + if is_import(&decl) { + if let Some(gav) = decl_gav(&decl, chain, &self.work) { + self.admit(&gav); + } + } + } + } + self.reactor_chains = chains; + Some(()) + } + + /// The chain of every pom of the reactor: the root `pom.xml` and its + /// `` / ``, recursively (profiles' included, and + /// the subprojects Maven 4 discovers). `None` when the root pom is not + /// readable or the reactor is too big to read. + pub(super) fn reactor_poms(&mut self) -> Option> { let root = self.cwd.join("pom.xml"); let model = self.model(&root, true)?; let mut pending = vec![Node { @@ -246,6 +280,7 @@ impl Walk<'_> { local: true, }]; let mut seen: HashSet = HashSet::from([root]); + let mut chains = Vec::new(); let config = crate::utils::fs::read_regular_to_bytes_sync(&self.cwd.join(MAVEN_CONFIG)) .ok() .map(|b| String::from_utf8_lossy(&b).into_owned()); @@ -257,43 +292,41 @@ impl Walk<'_> { let mut modules = node.model.modules.clone(); modules.extend(discovered_subprojects(&node.path, &dir, config.as_deref())); for module in modules { - if module.is_empty() || module.contains("${") { + if module.is_empty() { + continue; + } + if module.contains("${") { + self.unread_modules + .push(format!("the module {module} is named through a property")); continue; } let mut path = dir.join(&module); if !module.ends_with(".xml") { path = path.join("pom.xml"); } - if !self.inside(&path) || !seen.insert(path.clone()) { + if !self.inside(&path) { + self.unread_modules + .push(format!("the module {module} is outside the project")); + continue; + } + if !seen.insert(path.clone()) { continue; } - if let Some(model) = self.model(&path, true) { - pending.push(Node { + match self.model(&path, true) { + Some(model) => pending.push(Node { model, path, local: true, - }); + }), + None => self + .unread_modules + .push(format!("the pom of the module {module} cannot be read")), } } let chain = self.chain(node); - self.reactor_chains.push(chain); - } - let chains = std::mem::take(&mut self.reactor_chains); - for chain in &chains { - for decl in chain.iter().flat_map(|n| n.model.deps.clone()) { - self.declare(&decl, chain, true); - } - // Imported BOMs and parents are part of the build too. - for decl in chain.iter().flat_map(|n| n.model.managed.clone()) { - if is_import(&decl) { - if let Some(gav) = decl_gav(&decl, chain, &self.work) { - self.admit(&gav); - } - } - } + chains.push(chain); } - self.reactor_chains = chains; - Some(()) + Some(chains) } /// Queue `decl` read in `chain`'s context. A transitive edge also takes @@ -539,7 +572,7 @@ fn read_model(path: &Path, include_profiles: bool, work: &Work) -> Option bool { +pub(super) fn is_import(decl: &PomDecl) -> bool { decl.scope.as_deref() == Some("import") && decl.kind.as_deref() == Some("pom") } @@ -595,7 +628,7 @@ fn interpolate(value: &str, chain: &Chain, work: &Work) -> Option { /// The property lookups one walk may still make. A project's poms name a /// property a few times per declaration; a walk that runs out was fed poms /// built to make it spin, and is abandoned ([`project_scope`] is `None`). -struct Work(std::cell::Cell); +pub(super) struct Work(std::cell::Cell); impl Work { fn new() -> std::rc::Rc { @@ -609,7 +642,7 @@ impl Work { } /// Take one lookup; `false` once none is left. - fn spend(&self) -> bool { + pub(super) fn spend(&self) -> bool { match self.0.get().checked_sub(1) { Some(left) => { self.0.set(left); @@ -619,14 +652,14 @@ impl Work { } } - fn spent(&self) -> bool { + pub(super) fn spent(&self) -> bool { self.0.get() == 0 } } /// `path` with `.` / `..` components folded (no filesystem access); /// `None` when it climbs above its root. -fn normalize(path: &Path) -> Option { +pub(super) fn normalize(path: &Path) -> Option { use std::path::Component; let mut out = PathBuf::new(); for c in path.components() { diff --git a/crates/socket-patch-core/src/crawlers/maven_selection.rs b/crates/socket-patch-core/src/crawlers/maven_selection.rs new file mode 100644 index 000000000..30f2a99f0 --- /dev/null +++ b/crates/socket-patch-core/src/crawlers/maven_selection.rs @@ -0,0 +1,1380 @@ +//! Which version of each artifact Maven puts on the classpath of each +//! module of a project, read from the project's poms and the poms the +//! Maven local repository already holds (Maven caches the pom of every +//! artifact, parent and BOM it reads). Nothing is executed. +//! +//! A `` pin makes every occurrence of an artifact +//! one version, so a pin of `g:a:v` is only safe in a module where Maven +//! selects `v` already: anywhere else it changes what the build resolves. +//! Hosted and vendored mode ask this model before they pin. +//! +//! The model follows Maven 3's resolver: +//! +//! - **The graph**: a module's `` (its own and its parents', +//! a child's declaration first), then each artifact's own `compile` / +//! `runtime`, non-optional dependencies. An `` removes an +//! artifact below the declaration that carries it. A dependency on a +//! module of the reactor reads that module's pom. +//! - **Versions**: a declared version, else the managed one (the pom's +//! parent chain, then its imported BOMs, first declared first). The +//! module's own management also overrides the version of every +//! transitive dependency. A range is every version in it that the +//! `maven-metadata-*.xml` files beside the artifact list. +//! - **Mediation**: artifacts are settled parents first; among the +//! surviving declarations of one artifact the nearest wins, the first +//! declared on a tie, the highest of one range. What a losing version +//! depends on leaves the graph. Ranges are hard requirements: a winner +//! outside one gives way to the nearest version every range admits. +//! +//! Every answer says whether it is certain. It is not when something the +//! selection depends on could not be read: a pom missing from the local +//! repository (the project was never resolved), a version or coordinate +//! through a property that is undefined or that a profile redefines, a +//! profile that declares dependencies or management, a relocation, or a +//! dependency cycle. A caller never pins on an uncertain answer. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; +use std::path::{Path, PathBuf}; +use std::rc::Rc; + +use super::maven_scope::{is_import, normalize, Chain, Node, Walk}; +use crate::formats::maven::version::{MavenVersion, VersionRange}; +use crate::formats::maven::{interpolate_strict, maven_config_properties, split_socket_version}; +use crate::vendor::jvm::maven_reactor::MAVEN_CONFIG; + +/// Most distinct nodes one module's graph may hold; a bigger one is left +/// undetermined. +const MAX_GRAPH: usize = 50_000; +/// Deepest BOM import nesting followed. +const MAX_IMPORT_DEPTH: usize = 32; +/// The Maven Wrapper's settings file. +const WRAPPER_PROPERTIES: &str = ".mvn/wrapper/maven-wrapper.properties"; + +type Ga = (String, String); +type Gav = (String, String, String); + +/// What Maven selects for one artifact in one module, as far as a patch +/// of `base` is concerned. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + /// The module resolves the artifact at the patch's base version. + Selected, + /// The module resolves the artifact at this other version. + Other(String), + /// The module does not resolve the artifact. + Absent, + /// The model cannot tell, and why. + Undetermined(String), +} + +/// A patch's standing across every module of the build. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Standing { + /// At least one module selects the base version. + Selected, + /// No module selects it, and each one's answer is certain: the other + /// versions the modules select instead (none when no module resolves + /// the artifact at all). + NotSelected(Vec), + /// No module is known to select it and some cannot be told, and why. + Undetermined(String), +} + +/// The versions Maven selects in each module of a project. +#[derive(Debug, Clone, Default)] +pub struct MavenSelection { + modules: Vec, + /// Why nothing could be modelled. + unavailable: Option, + /// Why some module of the build was not read: no answer covers the + /// whole build then. + incomplete: Option, +} + +#[derive(Debug, Clone)] +struct Module { + /// The module's pom, relative to the project root (`pom.xml`, + /// `core/pom.xml`). + pom: String, + /// The main jar of each artifact the module resolves. + picks: HashMap, + /// The depth from which the module's graph may hold artifacts that + /// were not read, and why. + unknown: Option<(usize, String)>, +} + +#[derive(Debug, Clone)] +struct Pick { + /// `None`: declared, at a version that cannot be told. + version: Option, + depth: usize, + /// Why another version may be the one selected. + doubt: Option, + /// Selected as the highest version of a range. + ranged: bool, +} + +impl MavenSelection { + /// A selection that answers [`Verdict::Undetermined`] everywhere. + pub fn unavailable(why: impl Into) -> Self { + MavenSelection { + modules: Vec::new(), + unavailable: Some(why.into()), + incomplete: None, + } + } + + /// The selection of the project at `project_root` over the Maven local + /// repository this process resolves against. + pub fn for_project(project_root: &Path) -> Self { + match super::maven_crawler::JvmEnv::from_process().m2_repo { + Some(repo) => Self::of(project_root, &repo), + None => Self::unavailable("no Maven local repository is configured"), + } + } + + /// The selection of the project at `project_root` over the local + /// repository `repo`. + pub fn of(project_root: &Path, repo: &Path) -> Self { + select(project_root, repo) + } + + /// The poms of the modules that were modelled. + pub fn modules(&self) -> impl Iterator { + self.modules.iter().map(|m| m.pom.as_str()) + } + + /// What the module whose pom is `pom` (project-relative, forward + /// slashes) resolves `group:artifact` at, for a patch of `base`. A + /// `-socket.` version, which an earlier pin wrote, is the + /// base version. + pub fn verdict(&self, pom: &str, group: &str, artifact: &str, base: &str) -> Verdict { + if let Some(why) = &self.unavailable { + return Verdict::Undetermined(why.clone()); + } + let Some(module) = self.modules.iter().find(|m| m.pom == pom) else { + return Verdict::Undetermined(format!("{pom} was not read as a module of the build")); + }; + let unread = |depth: usize| { + module + .unknown + .as_ref() + .filter(|(from, _)| *from <= depth) + .map(|(_, why)| why.clone()) + }; + let Some(pick) = module.picks.get(&(group.to_string(), artifact.to_string())) else { + return match unread(usize::MAX) { + Some(why) => Verdict::Undetermined(why), + None => Verdict::Absent, + }; + }; + if let Some(why) = pick.doubt.clone().or_else(|| unread(pick.depth)) { + return Verdict::Undetermined(why); + } + let Some(version) = &pick.version else { + return Verdict::Undetermined(format!( + "the version {pom} declares for {group}:{artifact} cannot be read" + )); + }; + let selected = + version == base || split_socket_version(version).is_some_and(|(of, _)| of == base); + match (selected, pick.ranged) { + (false, _) => Verdict::Other(version.clone()), + (true, false) => Verdict::Selected, + // A pin would turn the range into one version for good. + (true, true) => Verdict::Undetermined(format!( + "{pom} selects {group}:{artifact} {base} as the highest version of a version \ + range, which a pin would freeze" + )), + } + } + + /// [`Self::verdict`] over every module. + pub fn standing(&self, group: &str, artifact: &str, base: &str) -> Standing { + if let Some(why) = &self.unavailable { + return Standing::Undetermined(why.clone()); + } + let mut others = BTreeSet::new(); + let mut undetermined = None; + for module in &self.modules { + match self.verdict(&module.pom, group, artifact, base) { + Verdict::Selected => return Standing::Selected, + Verdict::Other(version) => { + others.insert(version); + } + Verdict::Absent => {} + Verdict::Undetermined(why) => { + undetermined.get_or_insert(why); + } + } + } + match undetermined.or_else(|| self.incomplete.clone()) { + Some(why) => Standing::Undetermined(why), + None => { + let mut others: Vec = others.into_iter().collect(); + others.sort_by_key(|v| MavenVersion::parse(v)); + Standing::NotSelected(others) + } + } + } +} + +#[cfg(test)] +impl MavenSelection { + /// A selection of `modules` that answers with `picks`: `(pom, group, + /// artifact, version or why it cannot be told)`. A module resolves no + /// artifact it has no pick for. + pub(crate) fn answering( + modules: &[&str], + picks: &[(&str, &str, &str, Result<&str, &str>)], + ) -> Self { + let modules = modules + .iter() + .map(|pom| Module { + pom: pom.to_string(), + picks: picks + .iter() + .filter(|(of, ..)| of == pom) + .map(|(_, g, a, version)| { + let pick = Pick { + version: version.ok().map(str::to_string), + depth: 2, + doubt: version.err().map(str::to_string), + ranged: false, + }; + ((g.to_string(), a.to_string()), pick) + }) + .collect(), + unknown: None, + }) + .collect(); + MavenSelection { + modules, + unavailable: None, + incomplete: None, + } + } +} + +/// The one line that says a patch's base version is not part of the +/// build: which versions Maven selects instead. +pub fn not_selected_detail(group: &str, artifact: &str, base: &str, others: &[String]) -> String { + if others.is_empty() { + format!( + "no module of this build resolves {group}:{artifact}, so the patch for {base} has \ + nothing to patch here" + ) + } else { + format!( + "Maven selects {group}:{artifact} {} in this build, not {base}, so the patch for \ + {base} has nothing to patch here", + others.join(" and ") + ) + } +} + +/// The one line that says the selection of an artifact could not be told, +/// with its remedy. +pub fn undetermined_detail(group: &str, artifact: &str, base: &str, why: &str) -> String { + format!( + "which version of {group}:{artifact} Maven selects cannot be told ({why}), so nothing \ + was pinned for {base}: resolve the project once (`mvn -q dependency:resolve`) and \ + re-run, or declare {group}:{artifact} {base} in the pom" + ) +} + +// ── the model ─────────────────────────────────────────────────────── + +/// One conflict group: Maven mediates the versions of a +/// `group:artifact:extension:classifier`. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +struct Key { + group: String, + artifact: String, + extension: String, + classifier: String, +} + +impl Key { + fn new(group: String, artifact: String, kind: Option<&str>, classifier: Option<&str>) -> Key { + // Maven's default artifact handlers. + let (extension, implied) = match kind.filter(|k| !k.is_empty()).unwrap_or("jar") { + "jar" | "ejb" | "maven-plugin" => ("jar", ""), + "test-jar" => ("jar", "tests"), + "ejb-client" => ("jar", "client"), + "java-source" => ("jar", "sources"), + "javadoc" => ("jar", "javadoc"), + other => (other, ""), + }; + Key { + group, + artifact, + extension: extension.to_string(), + classifier: classifier + .filter(|c| !c.is_empty()) + .unwrap_or(implied) + .to_string(), + } + } + + fn is_main_jar(&self) -> bool { + self.extension == "jar" && self.classifier.is_empty() + } + + /// An archive that bundles its dependencies: Maven does not follow + /// them. + fn bundles_dependencies(&self) -> bool { + matches!(self.extension.as_str(), "war" | "ear" | "rar") + } +} + +/// A declared version, or why it cannot be read. +#[derive(Debug, Clone)] +enum Ver { + Known(String), + Unknown(String), +} + +/// One `` entry of an effective model. +#[derive(Debug, Clone)] +struct Managed { + version: Ver, + scope: Option, + exclusions: Vec, +} + +/// The effective `` of a pom: its parent chain's +/// entries, then its imported BOMs'. +#[derive(Debug, Default)] +struct Management { + entries: HashMap, + /// Why entries may be missing or different. + incomplete: Option, + /// What a profile manages: its version depends on the active profiles. + profile_keys: HashSet, +} + +/// One effective `` of a pom, its own management applied. +#[derive(Debug)] +struct Dep { + key: Key, + version: Ver, + scope: String, + optional: bool, + exclusions: Vec, +} + +/// The effective `` of a pom. +#[derive(Debug, Default)] +struct Deps { + deps: Vec, + /// Why the pom may declare dependencies that were not read. + unknown: Option, + /// The same for declarations Maven follows only from the module that + /// makes them (optional, `test` or `provided`). + unknown_own: Option, +} + +/// A hard version requirement, as written. +#[derive(Debug)] +struct Range { + raw: String, + set: VersionRange, +} + +/// One edge of a module's graph: a dependency of a node, resolved to a +/// version (one edge per version of a range). +#[derive(Debug, Clone)] +struct Edge { + /// The declaration's place among its pom's dependencies, then the + /// version's place in its range: the order Maven visits children in. + slot: (u32, u32), + key: u32, + version: Ver, + range: Option>, + /// The exclusions in force below this dependency. + exclusions: u32, + /// A `system` dependency: a file on the machine, with no pom to follow. + leaf: bool, +} + +/// A node's dependencies. +#[derive(Debug, Default)] +struct Expanded { + edges: Vec, + /// Why the node may bring in artifacts that were not read, and how far + /// below it they start (0: the node itself may be another artifact). + unknown: Option<(usize, String)>, +} + +/// One surviving declaration of an artifact. +#[derive(Debug, Clone)] +struct Item { + /// The slots from the module down to this declaration. + path: Vec<(u32, u32)>, + version: Ver, + range: Option>, + exclusions: u32, + leaf: bool, +} + +impl Item { + fn below(path: &[(u32, u32)], edge: &Edge) -> Item { + let mut path = path.to_vec(); + path.push(edge.slot); + Item { + path, + version: edge.version.clone(), + range: edge.range.clone(), + exclusions: edge.exclusions, + leaf: edge.leaf, + } + } +} + +struct Selector<'w> { + walk: Walk<'w>, + /// `-D` user properties of `.mvn/maven.config`. + user: BTreeMap, + /// The reactor's modules by their own coordinates. + reactor: HashMap, + management: HashMap>, + managing: HashSet, + deps: HashMap>, + keys: Vec, + key_ids: HashMap, + exclusion_sets: Vec>, + exclusion_ids: HashMap, u32>, + /// The versions each artifact's cached metadata lists. + listed: HashMap>>, +} + +fn select(cwd: &Path, repo: &Path) -> MavenSelection { + let read = |rel: &str| { + crate::utils::fs::read_regular_to_bytes_sync(&cwd.join(rel)) + .ok() + .map(|b| String::from_utf8_lossy(&b).into_owned()) + }; + // Maven 4 also applies the management of each dependency's own pom to + // what that dependency brings in, which this model does not follow. + let wrapper = read(WRAPPER_PROPERTIES).and_then(|props| { + super::gradle_cache::wrapper_distribution_version(props.as_bytes(), "maven") + }); + if wrapper.is_some_and(|(major, _, _)| major >= 4) + || read("pom.xml").is_some_and(|pom| pom.contains("maven.apache.org/POM/4.1.0")) + { + return MavenSelection::unavailable( + "the project builds with Maven 4, whose dependency management is not modelled", + ); + } + let mut selector = Selector { + walk: Walk::new(cwd, repo), + user: read(MAVEN_CONFIG) + .map(|config| maven_config_properties(&config)) + .unwrap_or_default(), + reactor: HashMap::new(), + management: HashMap::new(), + managing: HashSet::new(), + deps: HashMap::new(), + keys: Vec::new(), + key_ids: HashMap::new(), + exclusion_sets: Vec::new(), + exclusion_ids: HashMap::new(), + listed: HashMap::new(), + }; + let Some(chains) = selector.walk.reactor_poms() else { + return MavenSelection::unavailable("the project's pom.xml could not be read"); + }; + for chain in &chains { + if let Some(gav) = selector.own_gav(chain) { + selector.reactor.entry(gav).or_insert(chain[0].clone()); + } + } + let root = normalize(cwd); + let mut modules = Vec::new(); + for chain in &chains { + let rel = normalize(&chain[0].path) + .zip(root.as_ref()) + .and_then(|(path, root)| { + let rel = path.strip_prefix(root).ok()?; + let parts: Option> = + rel.components().map(|c| c.as_os_str().to_str()).collect(); + Some(parts?.join("/")) + }); + let Some(pom) = rel else { continue }; + let module = selector.module(pom, chain); + if selector.walk.work.spent() { + return MavenSelection::unavailable( + "the project's poms interpolate more than their size allows", + ); + } + modules.push(module); + } + modules.sort_by(|a, b| a.pom.cmp(&b.pom)); + MavenSelection { + modules, + unavailable: None, + incomplete: selector.walk.unread_modules.first().cloned(), + } +} + +impl Selector<'_> { + fn key_id(&mut self, key: &Key) -> u32 { + if let Some(id) = self.key_ids.get(key) { + return *id; + } + let id = self.keys.len() as u32; + self.keys.push(key.clone()); + self.key_ids.insert(key.clone(), id); + id + } + + fn exclusions_id(&mut self, set: BTreeSet) -> u32 { + if let Some(id) = self.exclusion_ids.get(&set) { + return *id; + } + let id = self.exclusion_sets.len() as u32; + self.exclusion_sets.push(set.clone()); + self.exclusion_ids.insert(set, id); + id + } + + /// `${name}` interpolation of `text` as `chain`'s head reads it, or + /// why its value cannot be told: a name nothing defines, or one a + /// profile on the chain redefines (its value then depends on which + /// profiles are active). + fn interpolate(&self, text: &str, chain: &Chain) -> Result { + if !text.contains("${") { + return Ok(text.to_string()); + } + let Some(head) = chain.first() else { + return Err(format!("{text} is not defined")); + }; + let own = &head.model; + let parent_field = |i: usize| -> Option { + let (g, a, v, _) = own.parent.as_ref()?; + [g, a, v][i].clone() + }; + let moved = std::cell::RefCell::new(None::); + let lookup = |name: &str| -> Option { + if !self.walk.work.spend() { + return None; + } + let model = match name { + "project.version" | "pom.version" | "version" => { + own.version.clone().or_else(|| parent_field(2)) + } + "project.groupId" | "pom.groupId" | "groupId" => { + own.group.clone().or_else(|| parent_field(0)) + } + "project.artifactId" | "pom.artifactId" | "artifactId" => own.artifact.clone(), + "project.parent.version" | "parent.version" => parent_field(2), + "project.parent.groupId" | "parent.groupId" => parent_field(0), + _ => None, + }; + if model.is_some() { + return model; + } + if chain.iter().any(|n| n.model.profiles.props.contains(name)) { + moved.borrow_mut().get_or_insert(name.to_string()); + } + let declared = || chain.iter().find_map(|n| n.model.props.get(name).cloned()); + // The command line's properties win in the project's own poms; + // a dependency's pom reads them after its own. + if head.local { + self.user.get(name).cloned().or_else(declared) + } else { + declared().or_else(|| self.user.get(name).cloned()) + } + }; + let value = interpolate_strict(text, &lookup); + if let Some(name) = moved.into_inner() { + return Err(format!("a profile redefines ${{{name}}}")); + } + value.ok_or_else(|| format!("{text} is not defined")) + } + + fn version_of(&self, raw: Option<&str>, chain: &Chain) -> Option { + Some(match self.interpolate(raw?, chain) { + Ok(version) => Ver::Known(version), + Err(why) => Ver::Unknown(why), + }) + } + + /// The coordinates the head of `chain` is published at. + fn own_gav(&self, chain: &Chain) -> Option { + let own = &chain.first()?.model; + let parent = own.parent.as_ref(); + let group = own.group.clone().or_else(|| parent?.0.clone())?; + let version = own.version.clone().or_else(|| parent?.2.clone())?; + Some(( + self.interpolate(&group, chain).ok()?, + self.interpolate(own.artifact.as_deref()?, chain).ok()?, + self.interpolate(&version, chain).ok()?, + )) + } + + /// The pom of `gav`: a module of the reactor, else the local + /// repository's copy. A `-socket.` version no repository + /// holds reads its base version's pom, which it is a copy of. + fn pom_of(&mut self, gav: &Gav) -> Option { + if let Some(node) = self.reactor.get(gav) { + return Some(node.clone()); + } + let found = self.walk.repo_pom(gav).and_then(|path| { + let model = self.walk.model(&path, false)?; + Some(Node { + model, + path, + local: false, + }) + }); + if found.is_some() { + return found; + } + let (base, _) = split_socket_version(&gav.2)?; + let base = (gav.0.clone(), gav.1.clone(), base.to_string()); + self.pom_of(&base) + } + + /// Why `chain` is not the whole parent chain of its head. + fn chain_gap(chain: &Chain) -> Option { + let last = chain.last()?; + let (g, a, v, _) = last.model.parent.as_ref()?; + let part = |p: &Option| p.clone().unwrap_or_else(|| "?".to_string()); + Some(format!( + "the parent pom {}:{}:{} is not in the local Maven repository", + part(g), + part(a), + part(v) + )) + } + + fn key_of( + &self, + decl: &crate::vendor::jvm::maven_reactor::PomDecl, + chain: &Chain, + ) -> Result { + let part = |text: &Option| -> Result, String> { + text.as_deref() + .map(|t| self.interpolate(t, chain)) + .transpose() + }; + Ok(Key::new( + self.interpolate(&decl.group, chain)?, + self.interpolate(&decl.artifact, chain)?, + part(&decl.kind)?.as_deref(), + part(&decl.classifier)?.as_deref(), + )) + } + + fn exclusions_of( + &self, + decl: &crate::vendor::jvm::maven_reactor::PomDecl, + chain: &Chain, + ) -> Vec { + let read = |text: &str| { + self.interpolate(text, chain) + .unwrap_or_else(|_| text.to_string()) + }; + decl.exclusions + .iter() + .map(|(g, a)| (read(g), read(a))) + .collect() + } + + /// The effective `` of `chain`'s head. + fn management(&mut self, chain: &Chain, depth: usize) -> Rc { + let Some(head) = chain.first() else { + return Rc::default(); + }; + let path = head.path.clone(); + if let Some(found) = self.management.get(&path) { + return Rc::clone(found); + } + let mut out = Management { + incomplete: Self::chain_gap(chain), + ..Management::default() + }; + // A BOM that imports itself, or imports nested too deep. + if depth > MAX_IMPORT_DEPTH || !self.managing.insert(path.clone()) { + out.incomplete = Some("its BOM imports nest too deep".to_string()); + return Rc::new(out); + } + let mut imports = Vec::new(); + for node in chain { + for decl in node.model.own_managed() { + // A pin vendoring wrote is not the project's management: + // the question is what Maven selects without it. + if decl.pinned { + continue; + } + if is_import(decl) { + imports.push(decl.clone()); + continue; + } + match self.key_of(decl, chain) { + Ok(key) => { + let managed = Managed { + version: self + .version_of(decl.version.as_deref(), chain) + .unwrap_or_else(|| Ver::Unknown("it manages no version".into())), + scope: decl.scope.clone(), + exclusions: self.exclusions_of(decl, chain), + }; + out.entries.entry(key).or_insert(managed); + } + Err(why) => out.incomplete = Some(why), + } + } + for decl in &node.model.profiles.managed { + if is_import(decl) { + out.incomplete = Some("a profile imports a BOM".to_string()); + continue; + } + match self.key_of(decl, chain) { + Ok(key) => { + out.profile_keys.insert(key); + } + Err(why) => out.incomplete = Some(why), + } + } + } + for decl in imports { + let gav = self + .interpolate(&decl.group, chain) + .and_then(|g| Ok((g, self.interpolate(&decl.artifact, chain)?))) + .and_then(|(g, a)| { + let version = decl.version.as_deref().unwrap_or_default(); + Ok((g, a, self.interpolate(version, chain)?)) + }); + let gav = match gav { + Ok(gav) => gav, + Err(why) => { + out.incomplete = Some(why); + continue; + } + }; + let Some(node) = self.pom_of(&gav) else { + out.incomplete = Some(format!( + "the BOM {}:{}:{} is not in the local Maven repository", + gav.0, gav.1, gav.2 + )); + continue; + }; + let bom = self.walk.chain(node); + let imported = self.management(&bom, depth + 1); + for (key, managed) in &imported.entries { + out.entries + .entry(key.clone()) + .or_insert_with(|| managed.clone()); + } + out.profile_keys + .extend(imported.profile_keys.iter().cloned()); + if out.incomplete.is_none() { + out.incomplete = imported.incomplete.clone(); + } + } + self.managing.remove(&path); + let out = Rc::new(out); + self.management.insert(path, Rc::clone(&out)); + out + } + + /// The effective `` of `chain`'s head: its own first, + /// then each parent's that it does not redeclare, with the versions, + /// scopes and exclusions its own management supplies. + fn dependencies(&mut self, chain: &Chain) -> Rc { + let Some(head) = chain.first() else { + return Rc::default(); + }; + let path = head.path.clone(); + if let Some(found) = self.deps.get(&path) { + return Rc::clone(found); + } + let management = self.management(chain, 0); + let mut out = Deps { + deps: Vec::new(), + unknown: Self::chain_gap(chain), + unknown_own: None, + }; + let mut seen = HashSet::new(); + for node in chain { + if node.model.profiles.deps { + out.unknown = Some(format!( + "a profile of {} declares dependencies", + describe(node) + )); + } + for decl in node.model.own_deps() { + let key = match self.key_of(decl, chain) { + Ok(key) => key, + Err(why) => { + let own_only = decl.optional + || matches!(decl.scope.as_deref(), Some("test" | "provided")); + match own_only { + true => out.unknown_own = Some(why), + false => out.unknown = Some(why), + } + continue; + } + }; + if !seen.insert(key.clone()) { + continue; + } + let managed = management.entries.get(&key); + let by_profile = management.profile_keys.contains(&key); + let version = self + .version_of(decl.version.as_deref(), chain) + .unwrap_or_else(|| match managed { + _ if by_profile => Ver::Unknown("a profile manages its version".into()), + Some(managed) => managed.version.clone(), + None => Ver::Unknown( + management + .incomplete + .clone() + .unwrap_or_else(|| "it declares no version".to_string()), + ), + }); + let scope = decl + .scope + .clone() + .or_else(|| managed.and_then(|m| m.scope.clone())) + .map(|s| self.interpolate(&s, chain).unwrap_or(s)) + .unwrap_or_else(|| "compile".to_string()); + let mut exclusions = self.exclusions_of(decl, chain); + if exclusions.is_empty() { + exclusions = managed.map(|m| m.exclusions.clone()).unwrap_or_default(); + } + out.deps.push(Dep { + key, + version, + scope, + optional: decl.optional, + exclusions, + }); + } + } + let out = Rc::new(out); + self.deps.insert(path, Rc::clone(&out)); + out + } + + /// The versions the local repository's metadata lists for `ga`, and + /// the reactor's own; `None` when no metadata file is cached. + fn listed_versions(&mut self, ga: &Ga) -> Option> { + if let Some(found) = self.listed.get(ga) { + return found.clone(); + } + let safe = + |s: &str| !s.is_empty() && !s.contains(['/', '\\', '$', '{', '}']) && !s.contains(".."); + let mut versions: Option> = None; + if safe(&ga.0) && safe(&ga.1) { + let dir = self.walk.repo.join(ga.0.replace('.', "/")).join(&ga.1); + for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() { + let name = entry.file_name(); + let name = name.to_string_lossy(); + if !(name.starts_with("maven-metadata") && name.ends_with(".xml")) { + continue; + } + let Ok(bytes) = crate::utils::fs::read_regular_to_bytes_sync(&entry.path()) else { + continue; + }; + versions + .get_or_insert_with(Vec::new) + .extend(metadata_versions(&String::from_utf8_lossy(&bytes))); + } + } + if let Some(versions) = versions.as_mut() { + versions.extend( + self.reactor + .keys() + .filter(|(g, a, _)| *g == ga.0 && *a == ga.1) + .map(|(_, _, v)| v.clone()), + ); + versions.sort_by_key(|v| MavenVersion::parse(v)); + versions.dedup(); + } + self.listed.insert(ga.clone(), versions.clone()); + versions + } + + /// The edges a declaration of `key` at `version` makes: one, or one + /// per version of a range. + fn edges(&mut self, slot: u32, dep: &Dep, version: Ver, exclusions: u32) -> Vec { + let key = &dep.key; + let id = self.key_id(key); + let leaf = dep.scope == "system"; + let edge = |at: u32, version: Ver, range: Option>| Edge { + slot: (slot, at), + key: id, + version, + range, + exclusions, + leaf, + }; + let raw = match version { + Ver::Unknown(why) => return vec![edge(0, Ver::Unknown(why), None)], + Ver::Known(raw) => raw, + }; + if matches!(raw.as_str(), "LATEST" | "RELEASE") { + let why = format!("{}:{} is declared at {raw}", key.group, key.artifact); + return vec![edge(0, Ver::Unknown(why), None)]; + } + let Some(set) = VersionRange::parse(&raw) else { + if raw.starts_with(['[', '(']) || raw.contains(',') { + let why = format!("the version range {raw} cannot be read"); + return vec![edge(0, Ver::Unknown(why), None)]; + } + return vec![edge(0, Ver::Known(raw), None)]; + }; + if let Some(exact) = set.exact() { + let exact = exact.to_string(); + let range = Rc::new(Range { raw, set }); + return vec![edge(0, Ver::Known(exact), Some(range))]; + } + let ga = (key.group.clone(), key.artifact.clone()); + let Some(listed) = self.listed_versions(&ga) else { + let why = format!( + "{}:{} is declared as the range {raw} and the local Maven repository lists no \ + versions of it", + ga.0, ga.1 + ); + return vec![edge(0, Ver::Unknown(why), None)]; + }; + let range = Rc::new(Range { raw, set }); + let within: Vec = listed + .into_iter() + .filter(|v| range.set.contains(v)) + .collect(); + if within.is_empty() { + let why = format!( + "no version of {}:{} the local Maven repository lists is in the range {}", + ga.0, ga.1, range.raw + ); + return vec![edge(0, Ver::Unknown(why), None)]; + } + within + .into_iter() + .enumerate() + .map(|(at, v)| edge(at as u32, Ver::Known(v), Some(Rc::clone(&range)))) + .collect() + } + + /// The dependencies of the module itself: every scope, optional ones + /// too, each with the exclusions it declares. + fn direct(&mut self, chain: &Chain, root: &Management) -> Expanded { + let deps = self.dependencies(chain); + let mut out = Expanded { + edges: Vec::new(), + unknown: deps + .unknown + .clone() + .or_else(|| deps.unknown_own.clone()) + .or_else(|| root.incomplete.clone()) + .map(|why| (1, why)), + }; + for (slot, dep) in deps.deps.iter().enumerate() { + let mut exclusions: BTreeSet = dep.exclusions.iter().cloned().collect(); + if let Some(managed) = root.entries.get(&dep.key) { + exclusions.extend(managed.exclusions.iter().cloned()); + } + let exclusions = self.exclusions_id(exclusions); + out.edges + .extend(self.edges(slot as u32, dep, dep.version.clone(), exclusions)); + } + out + } + + /// The dependencies of `key` at `version` that Maven follows below a + /// module managing `root`, with `exclusions` in force. + fn expand(&mut self, key: u32, version: &str, exclusions: u32, root: &Management) -> Expanded { + let key = self.keys[key as usize].clone(); + if key.bundles_dependencies() { + return Expanded::default(); + } + let gav = (key.group.clone(), key.artifact.clone(), version.to_string()); + let Some(node) = self.pom_of(&gav) else { + return Expanded { + edges: Vec::new(), + unknown: Some(( + 1, + format!( + "the pom of {}:{}:{version} is not in the local Maven repository", + key.group, key.artifact + ), + )), + }; + }; + // Maven builds the artifact the stub names in its place. + if node.model.relocation.is_some() { + return Expanded { + edges: Vec::new(), + unknown: Some(( + 0, + format!( + "{}:{}:{version} is relocated to other coordinates", + key.group, key.artifact + ), + )), + }; + } + let chain = self.walk.chain(node); + let deps = self.dependencies(&chain); + let in_force = self.exclusion_sets[exclusions as usize].clone(); + let excluded = |dep: &Dep| { + in_force.iter().any(|(g, a)| { + (g == "*" || *g == dep.key.group) && (a == "*" || *a == dep.key.artifact) + }) + }; + let mut out = Expanded { + edges: Vec::new(), + unknown: deps.unknown.clone().map(|why| (1, why)), + }; + for (slot, dep) in deps.deps.iter().enumerate() { + if matches!(dep.scope.as_str(), "test" | "provided") || dep.optional || excluded(dep) { + continue; + } + let managed = root.entries.get(&dep.key); + let version = if root.profile_keys.contains(&dep.key) { + Ver::Unknown("a profile manages its version".to_string()) + } else { + managed.map_or_else(|| dep.version.clone(), |m| m.version.clone()) + }; + let mut below = in_force.clone(); + below.extend(dep.exclusions.iter().cloned()); + if let Some(managed) = managed { + below.extend(managed.exclusions.iter().cloned()); + } + let below = self.exclusions_id(below); + out.edges + .extend(self.edges(slot as u32, dep, version, below)); + } + out + } + + /// What Maven selects in the module whose pom heads `chain`. + fn module(&mut self, pom: String, chain: &Chain) -> Module { + let root = self.management(chain, 0); + let direct = self.direct(chain, &root); + let mut module = Module { + pom, + picks: HashMap::new(), + unknown: direct.unknown.clone(), + }; + + // Every distinct node, for the order artifacts are settled in: an + // artifact after every artifact that may depend on it. + let mut graph = Graph::default(); + for edge in &direct.edges { + graph.reach(edge, None); + } + while let Some(node) = graph.queue.pop_front() { + if graph.expanded.len() >= MAX_GRAPH || self.walk.work.spent() { + module.unknown = Some((1, "its dependency graph is too large to read".into())); + return module; + } + let children = Rc::new(self.expand(node.0, &node.1, node.2, &root)); + for edge in &children.edges { + graph.reach(edge, Some(node.0)); + } + graph.expanded.insert(node, children); + } + + let mut pending: HashMap> = HashMap::new(); + for edge in &direct.edges { + pending + .entry(edge.key) + .or_default() + .push(Item::below(&[], edge)); + } + let (sorted, mut held) = graph.parents_first(); + for key in sorted { + self.settle(key, None, &graph, &root, &mut pending, &mut module); + } + // What a cycle holds back has no parents-first order: settled as + // its declarations turn up, and in doubt. + while let Some(at) = held.iter().position(|key| pending.contains_key(key)) { + let key = held.remove(at); + let named = &self.keys[key as usize]; + let why = format!( + "{}:{} is part of a dependency cycle", + named.group, named.artifact + ); + self.settle(key, Some(why), &graph, &root, &mut pending, &mut module); + } + for key in held { + let key = &self.keys[key as usize]; + if key.is_main_jar() { + module.picks.insert( + (key.group.clone(), key.artifact.clone()), + Pick { + version: None, + depth: 1, + doubt: Some(format!( + "{}:{} is part of a dependency cycle", + key.group, key.artifact + )), + ranged: false, + }, + ); + } + } + module + } + + /// Choose among the surviving declarations of `key` and put what the + /// winner depends on in line; `doubt` is why the choice is not certain + /// already. + fn settle( + &mut self, + key: u32, + mut doubt: Option, + graph: &Graph, + root: &Management, + pending: &mut HashMap>, + module: &mut Module, + ) { + let mut items = pending.remove(&key).unwrap_or_default(); + if items.is_empty() { + return; + } + items.sort_by(|a, b| a.path.cmp(&b.path)); + let note = |module: &mut Module, depth: usize, why: &str| { + if module.unknown.as_ref().is_none_or(|(at, _)| depth < *at) { + module.unknown = Some((depth, why.to_string())); + } + }; + // A declaration at a version that cannot be read may be the one + // Maven selects, and brings in whatever that version depends on. + let mut unread: Option<(usize, String)> = None; + for item in &items { + if let Ver::Unknown(why) = &item.version { + note(module, item.path.len() + 1, why); + if unread.as_ref().is_none_or(|(at, _)| item.path.len() < *at) { + unread = Some((item.path.len(), why.clone())); + } + } + } + let readable: Vec<(&Item, &str)> = items + .iter() + .filter_map(|item| match &item.version { + Ver::Known(version) => Some((item, version.as_str())), + Ver::Unknown(_) => None, + }) + .collect(); + let pick = match nearest(&readable) { + Ok(Some(at)) => { + let (item, version) = readable[at]; + let depth = item.path.len(); + if let Some((unread_depth, why)) = &unread { + if *unread_depth <= depth { + doubt.get_or_insert_with(|| why.clone()); + } + } + let node = (key, version.to_string(), item.exclusions); + let below = match graph.expanded.get(&node) { + _ if item.leaf => Rc::default(), + Some(found) => Rc::clone(found), + None => Rc::new(self.expand(key, version, item.exclusions, root)), + }; + if let Some((offset, why)) = &below.unknown { + note(module, depth + offset, why); + } + for edge in &below.edges { + pending + .entry(edge.key) + .or_default() + .push(Item::below(&item.path, edge)); + } + Pick { + version: Some(version.to_string()), + depth, + doubt, + ranged: item.range.as_ref().is_some_and(|r| r.set.exact().is_none()), + } + } + Ok(None) => { + let (depth, why) = unread.unwrap_or((1, "its version cannot be read".into())); + Pick { + version: None, + depth, + doubt: Some(why), + ranged: false, + } + } + Err(()) => Pick { + version: None, + depth: 1, + doubt: Some("its version ranges admit no common version".to_string()), + ranged: false, + }, + }; + let key = &self.keys[key as usize]; + if key.is_main_jar() { + module + .picks + .insert((key.group.clone(), key.artifact.clone()), pick); + } + } +} + +/// One node of a module's graph: an artifact at a version, with the +/// exclusions in force below it. +type GraphNode = (u32, String, u32); + +/// Every distinct node a module's declarations reach, before mediation. +#[derive(Default)] +struct Graph { + expanded: HashMap>, + seen: HashSet, + queue: VecDeque, + /// The artifacts, in the order they were first reached. + order: Vec, + known: HashSet, + /// `(a, b)`: some version of `a` depends on `b`. + below: BTreeSet<(u32, u32)>, +} + +impl Graph { + fn reach(&mut self, edge: &Edge, from: Option) { + if self.known.insert(edge.key) { + self.order.push(edge.key); + } + if let Some(from) = from { + self.below.insert((from, edge.key)); + } + if let (Ver::Known(version), false) = (&edge.version, edge.leaf) { + let node = (edge.key, version.clone(), edge.exclusions); + if self.seen.insert(node.clone()) { + self.queue.push_back(node); + } + } + } + + /// The artifacts ordered so that each comes after every artifact that + /// may depend on it, and those a dependency cycle keeps from any such + /// order (the cycle's own and everything below it). + fn parents_first(&self) -> (Vec, Vec) { + let mut waiting: HashMap = self.order.iter().map(|k| (*k, 0)).collect(); + let mut children: HashMap> = HashMap::new(); + for (from, to) in &self.below { + *waiting.entry(*to).or_default() += 1; + children.entry(*from).or_default().push(*to); + } + let mut ready: VecDeque = self + .order + .iter() + .copied() + .filter(|k| waiting[k] == 0) + .collect(); + let mut sorted = Vec::new(); + while let Some(key) = ready.pop_front() { + sorted.push(key); + for to in children.get(&key).into_iter().flatten() { + let left = waiting.get_mut(to).expect("counted above"); + *left -= 1; + if *left == 0 { + ready.push_back(*to); + } + } + } + let settled: HashSet = sorted.iter().copied().collect(); + let held = self + .order + .iter() + .copied() + .filter(|k| !settled.contains(k)) + .collect(); + (sorted, held) + } +} + +/// Maven's nearest-wins choice among the declarations of one artifact, in +/// the order it visits them: the nearest wins, the first on a tie, the +/// highest among the versions of one range. A range is a hard requirement: +/// once a winner falls outside one, the nearest declaration every range +/// admits takes over. `Ok(None)` for no declaration, `Err` when the ranges +/// admit none (Maven fails the build). +fn nearest(items: &[(&Item, &str)]) -> Result, ()> { + let parsed: Vec = items.iter().map(|(_, v)| MavenVersion::parse(v)).collect(); + let nearer = |a: usize, b: usize| { + let (pa, pb) = (&items[a].0.path, &items[b].0.path); + if pa.len() == pb.len() && pa[..pa.len() - 1] == pb[..pb.len() - 1] { + parsed[a] > parsed[b] + } else { + pa.len() < pb.len() + } + }; + let mut ranges: Vec<&Rc> = Vec::new(); + let mut candidates: Vec = Vec::new(); + let mut winner: Option = None; + for (at, (item, version)) in items.iter().enumerate() { + let mut backtrack = false; + if let Some(range) = &item.range { + if !ranges.iter().any(|r| r.raw == range.raw) { + ranges.push(range); + backtrack = winner.is_some_and(|w| !range.set.contains(items[w].1)); + } + } + let acceptable = ranges.iter().all(|r| r.set.contains(version)); + if acceptable { + candidates.push(at); + } + if backtrack { + winner = None; + candidates.retain(|c| ranges.iter().all(|r| r.set.contains(items[*c].1))); + for &candidate in &candidates { + if winner.is_none_or(|w| nearer(candidate, w)) { + winner = Some(candidate); + } + } + if winner.is_none() { + return Err(()); + } + } else if acceptable && winner.is_none_or(|w| nearer(at, w)) { + winner = Some(at); + } + } + Ok(winner) +} + +/// The `` entries of a `maven-metadata*.xml`. +fn metadata_versions(text: &str) -> Vec { + let Some(start) = text.find("") else { + return Vec::new(); + }; + let end = text[start..] + .find("") + .map_or(text.len(), |n| start + n); + let mut out = Vec::new(); + let mut rest = &text[start..end]; + while let Some(at) = rest.find("") { + rest = &rest[at + "".len()..]; + let Some(close) = rest.find("") else { + break; + }; + let version = rest[..close].trim(); + if !version.is_empty() { + out.push(version.to_string()); + } + rest = &rest[close..]; + } + out +} + +/// A pom as a message names it. +fn describe(node: &Node) -> String { + match (&node.model.artifact, node.local) { + (_, true) => node + .path + .file_name() + .map(|_| node.path.display().to_string()) + .unwrap_or_default(), + (Some(artifact), false) => artifact.clone(), + (None, false) => node.path.display().to_string(), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/socket-patch-core/src/crawlers/maven_selection/tests.rs b/crates/socket-patch-core/src/crawlers/maven_selection/tests.rs new file mode 100644 index 000000000..7eb47f223 --- /dev/null +++ b/crates/socket-patch-core/src/crawlers/maven_selection/tests.rs @@ -0,0 +1,759 @@ +use super::*; + +const G: &str = "org.x"; +const A: &str = "victim"; + +fn write(root: &Path, rel: &str, body: &str) { + let p = root.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, body).unwrap(); +} + +fn dep(g: &str, a: &str, v: Option<&str>, extra: &str) -> String { + let v = v.map_or(String::new(), |v| format!("{v}")); + format!("{g}{a}{v}{extra}") +} + +/// `org.x::`. +fn x(a: &str, v: &str) -> String { + dep(G, a, Some(v), "") +} + +fn pom(g: &str, a: &str, v: &str, body: &str) -> String { + format!( + "4.0.0{g}\ + {a}{v}{body}" + ) +} + +fn deps(list: &[String]) -> String { + format!("{}", list.concat()) +} + +fn managed(list: &[String]) -> String { + format!( + "{}", + list.concat() + ) +} + +/// Cache `org.x::` in `repo` with `body` as its pom's extra content. +fn cache(repo: &Path, a: &str, v: &str, body: &str) { + write( + repo, + &format!("org/x/{a}/{v}/{a}-{v}.pom"), + &pom(G, a, v, body), + ); +} + +/// The versions the repository's metadata lists for `org.x:`. +fn list(repo: &Path, a: &str, versions: &[&str]) { + let versions: String = versions + .iter() + .map(|v| format!("{v}")) + .collect(); + write( + repo, + &format!("org/x/{a}/maven-metadata-central.xml"), + &format!( + "{G}{a}\ + {versions}" + ), + ); +} + +struct Fixture { + _dir: tempfile::TempDir, + cwd: PathBuf, + repo: PathBuf, +} + +impl Fixture { + fn new() -> Fixture { + let dir = tempfile::tempdir().unwrap(); + let (cwd, repo) = (dir.path().join("p"), dir.path().join("m2")); + std::fs::create_dir_all(&cwd).unwrap(); + std::fs::create_dir_all(&repo).unwrap(); + Fixture { + _dir: dir, + cwd, + repo, + } + } + + /// The single-module project `com.example:app:1` with `body`. + fn app(&self, body: &str) -> &Fixture { + write(&self.cwd, "pom.xml", &pom("com.example", "app", "1", body)); + self + } + + fn cache(&self, a: &str, v: &str, list: &[String]) -> &Fixture { + cache(&self.repo, a, v, &deps(list)); + self + } + + fn select(&self) -> MavenSelection { + MavenSelection::of(&self.cwd, &self.repo) + } + + /// The verdict of the root module on the victim at `base`. + fn verdict(&self, base: &str) -> Verdict { + self.select().verdict("pom.xml", G, A, base) + } +} + +fn other(version: &str) -> Verdict { + Verdict::Other(version.to_string()) +} + +fn undetermined(verdict: &Verdict) -> &str { + match verdict { + Verdict::Undetermined(why) => why, + other => panic!("expected an undetermined verdict, got {other:?}"), + } +} + +/// The table's V1 and V2: the nearer declaration wins, older or newer. +#[test] +fn the_nearest_declaration_wins_whatever_its_version() { + for nearer in ["2.9.10", "2.6.0"] { + let f = Fixture::new(); + f.app(&deps(&[x("lib-x", "1.0"), x("lib-y", "1.0")])) + .cache("lib-x", "1.0", &[x(A, nearer)]) + .cache("lib-y", "1.0", &[x("lib-a", "1.0")]) + .cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache(A, nearer, &[]) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), other(nearer)); + assert_eq!(f.verdict(nearer), Verdict::Selected); + assert_eq!( + f.select().standing(G, A, "2.7.9.2"), + Standing::NotSelected(vec![nearer.to_string()]) + ); + } +} + +#[test] +fn the_first_declaration_wins_a_tie() { + for (first, second, wins) in [("lib-x", "lib-a", "2.9.10"), ("lib-a", "lib-x", "2.7.9.2")] { + let f = Fixture::new(); + f.app(&deps(&[x(first, "1.0"), x(second, "1.0")])) + .cache("lib-x", "1.0", &[x(A, "2.9.10")]) + .cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache(A, "2.9.10", &[]) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict(wins), Verdict::Selected, "{first} first"); + } +} + +/// The table's V4: a direct declaration is the nearest there is, and +/// management does not override it. +#[test] +fn a_direct_declaration_beats_management_and_transitives() { + let f = Fixture::new(); + f.app(&format!( + "{}{}", + managed(&[x(A, "2.8.0")]), + deps(&[x("lib-a", "1.0"), x(A, "2.9.10")]) + )) + .cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache(A, "2.9.10", &[]) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.9.10"), Verdict::Selected); + assert_eq!(f.verdict("2.7.9.2"), other("2.9.10")); +} + +#[test] +fn management_sets_a_versionless_declaration_and_every_transitive() { + // The module's own management. + let f = Fixture::new(); + f.app(&format!( + "{}{}", + managed(&[x(A, "2.9.10")]), + deps(&[x("lib-a", "1.0")]) + )) + .cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache(A, "2.9.10", &[]); + assert_eq!(f.verdict("2.7.9.2"), other("2.9.10")); + + // A version-less direct declaration. + let f = Fixture::new(); + f.app(&format!( + "{}{}", + managed(&[x(A, "2.7.9.2")]), + deps(&[dep(G, A, None, "")]) + )) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + + // An imported BOM, and a parent from the repository; the parent's own + // entry beats the import. + let f = Fixture::new(); + write( + &f.cwd, + "pom.xml", + &format!( + "4.0.0{G}\ + corp-parent3\ + app{}{}", + managed(&[dep( + G, + "bom", + Some("1"), + "pomimport" + )]), + deps(&[x("lib-a", "1.0"), x("lib-b", "1.0")]) + ), + ); + cache(&f.repo, "corp-parent", "3", &managed(&[x(A, "2.9.10")])); + cache( + &f.repo, + "bom", + "1", + &managed(&[x(A, "2.8.0"), x("other", "5")]), + ); + f.cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache("lib-b", "1.0", &[x("other", "4")]) + .cache(A, "2.9.10", &[]) + .cache("other", "5", &[]); + let selection = f.select(); + assert_eq!( + selection.verdict("pom.xml", G, A, "2.7.9.2"), + other("2.9.10") + ); + assert_eq!( + selection.verdict("pom.xml", G, "other", "5"), + Verdict::Selected + ); +} + +/// The table's V6: what an `` removes is not a declaration. +#[test] +fn an_excluded_declaration_does_not_count() { + for exclusion in [ + format!("{G}{A}"), + "**".to_string(), + ] { + let excluded = dep( + G, + "lib-y", + Some("1.0"), + &format!("{exclusion}"), + ); + // Another path still brings the artifact in, deeper. + let f = Fixture::new(); + f.app(&deps(&[excluded.clone(), x("lib-w", "1.0")])) + .cache("lib-y", "1.0", &[x(A, "2.7.9.2")]) + .cache("lib-w", "1.0", &[x("lib-x", "1.0")]) + .cache("lib-x", "1.0", &[x(A, "2.9.10")]) + .cache(A, "2.9.10", &[]) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), other("2.9.10")); + + // No other path: the module does not resolve it at all. + let f = Fixture::new(); + f.app(&deps(&[excluded])) + .cache("lib-y", "1.0", &[x(A, "2.7.9.2")]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Absent); + assert_eq!( + f.select().standing(G, A, "2.7.9.2"), + Standing::NotSelected(Vec::new()) + ); + } +} + +#[test] +fn an_exclusion_holds_for_everything_below_its_declaration() { + let f = Fixture::new(); + f.app(&deps(&[dep( + G, + "lib-y", + Some("1.0"), + &format!( + "{G}{A}\ + " + ), + )])) + .cache("lib-y", "1.0", &[x("lib-a", "1.0")]) + .cache("lib-a", "1.0", &[x("lib-b", "1.0"), x(A, "2.7.9.2")]) + .cache("lib-b", "1.0", &[x(A, "2.7.9.2")]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Absent); +} + +#[test] +fn optional_test_and_provided_transitives_are_not_followed() { + for extra in [ + "true", + "test", + "provided", + ] { + let f = Fixture::new(); + f.app(&deps(&[x("lib-a", "1.0")])).cache( + "lib-a", + "1.0", + &[dep(G, A, Some("2.7.9.2"), extra)], + ); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Absent, "{extra}"); + + // The module's own declaration of any scope is resolved. + let f = Fixture::new(); + f.app(&deps(&[dep(G, A, Some("2.7.9.2"), extra)])) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected, "{extra}"); + } + // A scope the artifact's own management gives a version-less + // declaration counts too. + let f = Fixture::new(); + f.app(&deps(&[x("lib-a", "1.0")])); + cache( + &f.repo, + "lib-a", + "1.0", + &format!( + "{}{}", + managed(&[dep(G, A, Some("2.7.9.2"), "test")]), + deps(&[dep(G, A, None, "")]) + ), + ); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Absent); +} + +/// What a losing version depends on is not part of the graph: `lib-c` +/// 1.0 sits nearer, but under the `lib-b` version that lost. +#[test] +fn what_a_losing_version_depends_on_leaves_the_graph() { + let f = Fixture::new(); + f.app(&deps(&[ + x("lib-a", "1.0"), + x("lib-b", "2.0"), + x("lib-e", "1.0"), + ])) + .cache("lib-a", "1.0", &[x("lib-b", "1.0")]) + .cache("lib-b", "1.0", &[x(A, "2.7.9.2")]) + .cache("lib-b", "2.0", &[]) + .cache("lib-e", "1.0", &[x("lib-f", "1.0")]) + .cache("lib-f", "1.0", &[x("lib-g", "1.0")]) + .cache("lib-g", "1.0", &[x(A, "2.9.10")]) + .cache(A, "2.9.10", &[]) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), other("2.9.10")); + assert_eq!(f.verdict("2.9.10"), Verdict::Selected); +} + +/// The table's V7: a range selects the highest version in it the cached +/// metadata lists, whatever else the local repository holds. +#[test] +fn a_range_selects_the_highest_listed_version_in_it() { + let f = Fixture::new(); + f.app(&deps(&[x("lib-r", "1.0")])) + .cache("lib-r", "1.0", &[x(A, "[2.9.0,2.9.10]")]) + .cache(A, "2.7.9.2", &[]) + .cache(A, "2.9.0", &[]) + .cache(A, "2.9.10", &[]); + // No metadata: the range cannot be resolved. + undetermined(&f.verdict("2.7.9.2")); + list(&f.repo, A, &["2.7.9.2", "2.9.0", "2.9.10", "2.10.0"]); + assert_eq!(f.verdict("2.7.9.2"), other("2.9.10")); + assert_eq!(f.verdict("2.9.0"), other("2.9.10")); + // A pin of the selected version would freeze the range: never certain. + assert!(undetermined(&f.verdict("2.9.10")).contains("version range")); +} + +#[test] +fn an_exact_requirement_is_one_version() { + let f = Fixture::new(); + f.app(&deps(&[x("lib-r", "1.0")])) + .cache("lib-r", "1.0", &[x(A, "[2.7.9.2]")]) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); +} + +/// A range is a hard requirement: the nearer plain version outside it +/// gives way to the nearest version every range admits. +#[test] +fn a_range_overrules_a_nearer_version_outside_it() { + let f = Fixture::new(); + f.app(&deps(&[x("lib-a", "1.0"), x("lib-y", "1.0")])) + .cache("lib-a", "1.0", &[x(A, "1.0")]) + .cache("lib-y", "1.0", &[x("lib-r", "1.0")]) + .cache("lib-r", "1.0", &[x(A, "[2.0,3.0)")]) + .cache(A, "1.0", &[]) + .cache(A, "2.5", &[]); + list(&f.repo, A, &["1.0", "2.5", "3.0"]); + assert_eq!(f.verdict("1.0"), other("2.5")); + + // Two ranges with nothing in common: Maven fails the build. + let f = Fixture::new(); + f.app(&deps(&[x("lib-a", "1.0"), x("lib-r", "1.0")])) + .cache("lib-a", "1.0", &[x(A, "[1.0]")]) + .cache("lib-r", "1.0", &[x(A, "[2.0,3.0)")]) + .cache(A, "1.0", &[]) + .cache(A, "2.5", &[]); + list(&f.repo, A, &["1.0", "2.5"]); + undetermined(&f.verdict("1.0")); +} + +/// The table's V5 for a project that was never resolved: a pom missing +/// from the local repository leaves everything at its depth or deeper +/// undetermined, and nothing nearer. +#[test] +fn a_missing_pom_leaves_only_what_it_could_change_undetermined() { + let f = Fixture::new(); + f.app(&deps(&[ + x("lib-x", "1.0"), + x("never-resolved", "1.0"), + x("direct", "1.0"), + ])) + .cache("lib-x", "1.0", &[x(A, "2.9.10")]) + .cache(A, "2.9.10", &[]) + .cache("direct", "1.0", &[]); + let why = f.verdict("2.9.10"); + assert!( + undetermined(&why).contains("never-resolved"), + "names the missing pom: {why:?}" + ); + let selection = f.select(); + assert_eq!( + selection.verdict("pom.xml", G, "direct", "1.0"), + Verdict::Selected + ); + undetermined(&selection.verdict("pom.xml", G, "absent", "1.0")); + assert!(matches!( + selection.standing(G, A, "2.7.9.2"), + Standing::Undetermined(_) + )); +} + +#[test] +fn a_version_the_poms_do_not_define_is_undetermined() { + // The nearest declaration reads an undefined property. + let f = Fixture::new(); + f.app(&deps(&[x("lib-a", "1.0")])) + .cache("lib-a", "1.0", &[x(A, "${nowhere}")]); + assert!(undetermined(&f.verdict("2.7.9.2")).contains("${nowhere}")); + + // A nearer declaration at a known version is certain all the same. + let f = Fixture::new(); + f.app(&deps(&[x(A, "2.9.10"), x("lib-a", "1.0")])) + .cache("lib-a", "1.0", &[x(A, "${nowhere}")]) + .cache(A, "2.9.10", &[]); + assert_eq!(f.verdict("2.7.9.2"), other("2.9.10")); +} + +#[test] +fn what_a_profile_may_change_is_undetermined() { + // A profile redefines the property the version reads. + let f = Fixture::new(); + f.app(&format!( + "2.7.9.2{}p\ + 2.9.10", + deps(&[x(A, "${v}")]) + )) + .cache(A, "2.7.9.2", &[]); + assert!(undetermined(&f.verdict("2.7.9.2")).contains("profile")); + + // A profile declares dependencies of its own. + let f = Fixture::new(); + f.app(&format!( + "{}p{}", + deps(&[x("lib-a", "1.0")]), + deps(&[x("lib-x", "1.0")]) + )) + .cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache(A, "2.7.9.2", &[]); + assert!(undetermined(&f.verdict("2.7.9.2")).contains("profile")); + + // A profile manages the artifact. + let f = Fixture::new(); + f.app(&format!( + "{}p{}", + deps(&[x("lib-a", "1.0"), x("lib-b", "1.0")]), + managed(&[x(A, "2.9.10")]) + )) + .cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache("lib-b", "1.0", &[x("other", "1")]) + .cache(A, "2.7.9.2", &[]) + .cache("other", "1", &[]); + let selection = f.select(); + undetermined(&selection.verdict("pom.xml", G, A, "2.7.9.2")); + assert_eq!( + selection.verdict("pom.xml", G, "other", "1"), + Verdict::Selected + ); +} + +/// The table's V3: each module of a reactor has its own answer, and a +/// dependency on a sibling module reads the sibling's pom. +#[test] +fn each_module_of_a_reactor_has_its_own_selection() { + let f = Fixture::new(); + write( + &f.cwd, + "pom.xml", + &pom( + "com.example", + "parent", + "1", + "pomab\ + c", + ), + ); + let module = |name: &str, list: &[String]| { + format!( + "4.0.0com.example\ + parent1\ + {name}{}", + deps(list) + ) + }; + write(&f.cwd, "a/pom.xml", &module("a", &[x(A, "2.7.9.2")])); + write(&f.cwd, "b/pom.xml", &module("b", &[x("lib-x", "1.0")])); + write( + &f.cwd, + "c/pom.xml", + &module( + "c", + &[ + dep("com.example", "a", Some("${project.version}"), ""), + x("lib-w", "1.0"), + ], + ), + ); + f.cache("lib-x", "1.0", &[x(A, "2.9.10")]) + .cache("lib-w", "1.0", &[x("lib-x", "1.0")]) + .cache(A, "2.9.10", &[]) + .cache(A, "2.7.9.2", &[]); + let selection = f.select(); + assert_eq!( + selection.modules().collect::>(), + ["a/pom.xml", "b/pom.xml", "c/pom.xml", "pom.xml"] + ); + assert_eq!( + selection.verdict("a/pom.xml", G, A, "2.7.9.2"), + Verdict::Selected + ); + assert_eq!( + selection.verdict("b/pom.xml", G, A, "2.7.9.2"), + other("2.9.10") + ); + // Through the sibling module, nearer than lib-w's path. + assert_eq!( + selection.verdict("c/pom.xml", G, A, "2.7.9.2"), + Verdict::Selected + ); + assert_eq!( + selection.verdict("pom.xml", G, A, "2.7.9.2"), + Verdict::Absent + ); + assert_eq!(selection.standing(G, A, "2.7.9.2"), Standing::Selected); + assert_eq!(selection.standing(G, A, "2.9.10"), Standing::Selected); + undetermined(&selection.verdict("d/pom.xml", G, A, "2.7.9.2")); +} + +/// An earlier run's wiring reads as the version it replaced: a suffixed +/// literal is its base version (its pom is the base's), and a pin +/// vendoring wrote is not the project's management. +#[test] +fn earlier_wiring_reads_as_the_project_without_it() { + let f = Fixture::new(); + f.app(&deps(&[x(A, "2.7.9.2-socket.8e82692a")])) + .cache(A, "2.7.9.2", &[x("below", "1")]) + .cache("below", "1", &[]); + let selection = f.select(); + assert_eq!( + selection.verdict("pom.xml", G, A, "2.7.9.2"), + Verdict::Selected + ); + assert_eq!( + selection.verdict("pom.xml", G, "below", "1"), + Verdict::Selected + ); + + let f = Fixture::new(); + f.app(&format!( + "\n\ + \n\ + {}{}", + x(A, "2.7.9.2-socket.8e82692a"), + deps(&[x("lib-x", "1.0"), x("lib-y", "1.0")]) + )) + .cache("lib-x", "1.0", &[x(A, "2.9.10")]) + .cache("lib-y", "1.0", &[x("lib-a", "1.0")]) + .cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache(A, "2.9.10", &[]) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), other("2.9.10")); +} + +#[test] +fn a_dependency_cycle_is_undetermined_and_only_below_it() { + let f = Fixture::new(); + f.app(&deps(&[x("free", "1"), x("lib-a", "1.0")])) + .cache("free", "1", &[]) + .cache("lib-a", "1.0", &[x("lib-b", "1.0")]) + .cache("lib-b", "1.0", &[x("lib-a", "2.0"), x(A, "2.7.9.2")]) + .cache("lib-a", "2.0", &[]) + .cache(A, "2.7.9.2", &[]); + let selection = f.select(); + assert!(undetermined(&selection.verdict("pom.xml", G, A, "2.7.9.2")).contains("cycle")); + assert_eq!( + selection.verdict("pom.xml", G, "free", "1"), + Verdict::Selected + ); +} + +#[test] +fn a_relocated_artifact_is_undetermined() { + let f = Fixture::new(); + f.app(&deps(&[x(A, "2.7.9.2")])); + cache( + &f.repo, + A, + "2.7.9.2", + "victim-ng\ + ", + ); + assert!(undetermined(&f.verdict("2.7.9.2")).contains("relocated")); +} + +#[test] +fn command_line_properties_win_in_the_projects_own_poms() { + let f = Fixture::new(); + f.app(&format!( + "2.7.9.2{}", + deps(&[x(A, "${v}")]) + )) + .cache(A, "2.9.10", &[]) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + write(&f.cwd, ".mvn/maven.config", "-Dv=2.9.10\n"); + assert_eq!(f.verdict("2.7.9.2"), other("2.9.10")); +} + +#[test] +fn a_project_that_cannot_be_modelled_is_undetermined_everywhere() { + // No readable root pom. + let f = Fixture::new(); + undetermined(&f.verdict("2.7.9.2")); + assert!(matches!( + f.select().standing(G, A, "2.7.9.2"), + Standing::Undetermined(_) + )); + + // A Maven 4 build. + let f = Fixture::new(); + f.app(&deps(&[x(A, "2.7.9.2")])).cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + write( + &f.cwd, + ".mvn/wrapper/maven-wrapper.properties", + "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/4.0.0/apache-maven-4.0.0-bin.zip\n", + ); + assert!(undetermined(&f.verdict("2.7.9.2")).contains("Maven 4")); + + assert!(matches!( + MavenSelection::unavailable("why").verdict("pom.xml", G, A, "1"), + Verdict::Undetermined(why) if why == "why" + )); +} + +#[test] +fn the_lines_name_what_maven_selects() { + assert_eq!( + not_selected_detail(G, A, "2.7.9.2", &["2.9.10".to_string()]), + "Maven selects org.x:victim 2.9.10 in this build, not 2.7.9.2, so the patch for 2.7.9.2 \ + has nothing to patch here" + ); + assert!(not_selected_detail(G, A, "2.7.9.2", &[]).starts_with("no module of this build")); + assert!(undetermined_detail(G, A, "2.7.9.2", "why").contains("mvn -q dependency:resolve")); +} + +#[test] +fn metadata_lists_its_versions() { + assert_eq!( + metadata_versions( + "92\n\ + 1.0\n 2 " + ), + ["1.0", "2"] + ); + assert!(metadata_versions("").is_empty()); +} + +/// A `system` dependency is a file on the machine: Maven reads no pom for +/// it, so its missing pom leaves nothing undetermined. +#[test] +fn a_system_dependency_has_nothing_below_it() { + let f = Fixture::new(); + f.app(&deps(&[ + dep( + "com.sun", + "tools", + Some("1.8"), + "system${java.home}/../lib/tools.jar", + ), + x("lib-a", "1.0"), + ])) + .cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); +} + +/// A declaration Maven follows only from the module that makes it (an +/// optional or test one) says nothing about a build that merely depends on +/// that artifact, even when its coordinates cannot be read. +#[test] +fn an_unreadable_optional_declaration_matters_only_to_its_own_module() { + let unreadable = dep( + G, + "native", + Some("1"), + "${os.detected.classifier}true", + ); + let f = Fixture::new(); + f.app(&deps(&[x("lib-a", "1.0")])) + .cache("lib-a", "1.0", &[unreadable.clone(), x(A, "2.7.9.2")]) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + + let f = Fixture::new(); + f.app(&deps(&[unreadable, x("lib-a", "1.0")])) + .cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache(A, "2.7.9.2", &[]); + undetermined(&f.verdict("2.7.9.2")); +} + +/// A module the reactor names and that cannot be read is a part of the +/// build nothing is known about: the modules that were read keep their +/// answers, and no answer covers the whole build. +#[test] +fn a_module_that_cannot_be_read_leaves_the_build_undetermined() { + let f = Fixture::new(); + write( + &f.cwd, + "pom.xml", + &pom( + "com.example", + "parent", + "1", + "pomagone", + ), + ); + write( + &f.cwd, + "a/pom.xml", + &pom("com.example", "a", "1", &deps(&[x("lib-x", "1.0")])), + ); + f.cache("lib-x", "1.0", &[x(A, "2.9.10")]) + .cache(A, "2.9.10", &[]); + let selection = f.select(); + assert_eq!( + selection.verdict("a/pom.xml", G, A, "2.7.9.2"), + other("2.9.10") + ); + assert_eq!(selection.standing(G, A, "2.9.10"), Standing::Selected); + match selection.standing(G, A, "2.7.9.2") { + Standing::Undetermined(why) => assert!(why.contains("gone"), "{why}"), + other => panic!("{other:?}"), + } +} diff --git a/crates/socket-patch-core/src/crawlers/mod.rs b/crates/socket-patch-core/src/crawlers/mod.rs index b657910e5..c2f944e20 100644 --- a/crates/socket-patch-core/src/crawlers/mod.rs +++ b/crates/socket-patch-core/src/crawlers/mod.rs @@ -13,6 +13,7 @@ pub mod maven_crawler; #[cfg(test)] mod maven_pom_equivalence_tests; pub(crate) mod maven_scope; +pub mod maven_selection; pub mod npm_crawler; pub mod nuget_crawler; #[cfg(test)] diff --git a/crates/socket-patch-core/src/formats/maven/mod.rs b/crates/socket-patch-core/src/formats/maven/mod.rs index bb8b3cf95..c78762c15 100644 --- a/crates/socket-patch-core/src/formats/maven/mod.rs +++ b/crates/socket-patch-core/src/formats/maven/mod.rs @@ -18,6 +18,7 @@ pub(crate) use properties::{ use super::xml::{blank_non_markup, child_text, elements, open_tags, Element}; pub(crate) mod trusted_checksums; +pub(crate) mod version; // ── pure reader ── diff --git a/crates/socket-patch-core/src/formats/maven/version.rs b/crates/socket-patch-core/src/formats/maven/version.rs new file mode 100644 index 000000000..bfb5544a2 --- /dev/null +++ b/crates/socket-patch-core/src/formats/maven/version.rs @@ -0,0 +1,469 @@ +//! Maven's version order and version ranges, as its resolver reads them +//! (`GenericVersion` / `GenericVersionRange` of maven-resolver-util): what +//! decides which version a range selects and which of two siblings wins. + +use std::cmp::Ordering; + +/// One token of a version. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Item { + /// The `min` a `[1.*]` range ends its lower bound with. + Min, + /// `alpha` (-5) … `sp` (1); `ga` / `final` / `release` are 0. + Qualifier(i32), + /// Any other word, lowercased. + Word(String), + /// A number of fewer than ten digits. + Int(u32), + /// A longer number: its digits, without leading zeros. + Big(String), + /// The `max` a `[1.*]` range ends its upper bound with. + Max, +} + +impl Item { + fn kind(&self) -> u8 { + match self { + Item::Min => 0, + Item::Qualifier(_) => 2, + Item::Word(_) => 3, + Item::Int(_) => 4, + Item::Big(_) => 5, + Item::Max => 8, + } + } + + fn is_number(&self) -> bool { + !matches!(self, Item::Qualifier(_) | Item::Word(_)) + } + + /// Against the padding item (`0`, or the empty qualifier). + fn cmp_padding(&self) -> Ordering { + match self { + Item::Min => Ordering::Less, + Item::Max | Item::Big(_) | Item::Word(_) => Ordering::Greater, + Item::Int(n) => n.cmp(&0), + Item::Qualifier(q) => q.cmp(&0), + } + } + + fn cmp_item(&self, other: &Item) -> Ordering { + match (self, other) { + (Item::Qualifier(a), Item::Qualifier(b)) => a.cmp(b), + (Item::Int(a), Item::Int(b)) => a.cmp(b), + (Item::Word(a), Item::Word(b)) => a.cmp(b), + (Item::Big(a), Item::Big(b)) => a.len().cmp(&b.len()).then_with(|| a.cmp(b)), + _ => self.kind().cmp(&other.kind()), + } + } +} + +/// A version in Maven's order. +#[derive(Debug, Clone)] +pub(crate) struct MavenVersion { + items: Vec, +} + +impl MavenVersion { + pub(crate) fn parse(version: &str) -> MavenVersion { + let text: Vec = if version.is_empty() { + vec!['0'] + } else { + version.chars().collect() + }; + let mut items = Vec::new(); + let mut index = 0; + while index < text.len() { + // -2: nothing read, -1: a word, 0: leading zeros, 1: a number. + let mut state = -2; + let mut start = index; + let mut end = text.len(); + let mut terminated_by_number = false; + while index < text.len() { + let c = text[index]; + if matches!(c, '.' | '-' | '_') { + end = index; + index += 1; + break; + } + if let Some(digit) = c.to_digit(10) { + if state == -1 { + end = index; + terminated_by_number = true; + break; + } + if state == 0 { + start += 1; + } + state = i32::from(state > 0 || digit > 0); + } else { + if state >= 0 { + end = index; + break; + } + state = -1; + } + index += 1; + } + let (token, number): (String, bool) = if end > start { + (text[start..end].iter().collect(), state >= 0) + } else { + ("0".to_string(), true) + }; + items.push(if number { + // Unicode digits other than 0-9 do not parse: such a + // version only ever compares with itself here. + match (token.len() < 10) + .then(|| token.parse::().ok()) + .flatten() + { + Some(n) => Item::Int(n), + None => Item::Big(token), + } + } else { + let lower = token.to_lowercase(); + let last = index >= text.len(); + match lower.as_str() { + "min" if last => Item::Min, + "max" if last => Item::Max, + "a" if terminated_by_number => Item::Qualifier(-5), + "b" if terminated_by_number => Item::Qualifier(-4), + "m" if terminated_by_number => Item::Qualifier(-3), + "alpha" => Item::Qualifier(-5), + "beta" => Item::Qualifier(-4), + "milestone" => Item::Qualifier(-3), + "cr" | "rc" => Item::Qualifier(-2), + "snapshot" => Item::Qualifier(-1), + "ga" | "final" | "release" => Item::Qualifier(0), + "sp" => Item::Qualifier(1), + _ => Item::Word(lower), + } + }); + } + trim_padding(&mut items); + MavenVersion { items } + } +} + +/// Drop the trailing run of padding items of each kind (`1.0.0` is `1`, +/// `1-ga` is `1`). +fn trim_padding(items: &mut Vec) { + let mut number: Option = None; + let mut end = items.len().saturating_sub(1); + let mut i = end; + while i > 0 { + let is_number = items[i].is_number(); + if number != Some(is_number) { + end = i; + number = Some(is_number); + } + if end == i + && (i == items.len() - 1 || items[i - 1].is_number() == is_number) + && items[i].cmp_padding() == Ordering::Equal + { + items.remove(i); + end = end.saturating_sub(1); + } + i -= 1; + } +} + +/// How the items of `items` from `index` on compare with padding; with +/// `number`, only the items of that kind are read. +fn compare_padding(items: &[Item], index: usize, number: Option) -> Ordering { + for item in &items[index..] { + if number.is_some_and(|n| n != item.is_number()) { + continue; + } + let rel = item.cmp_padding(); + if rel != Ordering::Equal { + return rel; + } + } + Ordering::Equal +} + +impl Ord for MavenVersion { + fn cmp(&self, other: &Self) -> Ordering { + let (these, those) = (&self.items, &other.items); + let mut number = true; + let mut index = 0; + loop { + match (these.get(index), those.get(index)) { + (None, None) => return Ordering::Equal, + (None, Some(_)) => return compare_padding(those, index, None).reverse(), + (Some(_), None) => return compare_padding(these, index, None), + (Some(this), Some(that)) => { + if this.is_number() != that.is_number() { + return if number == this.is_number() { + compare_padding(these, index, Some(number)) + } else { + compare_padding(those, index, Some(number)).reverse() + }; + } + let rel = this.cmp_item(that); + if rel != Ordering::Equal { + return rel; + } + number = this.is_number(); + } + } + index += 1; + } + } +} + +impl PartialOrd for MavenVersion { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl PartialEq for MavenVersion { + fn eq(&self, other: &Self) -> bool { + self.cmp(other) == Ordering::Equal + } +} + +impl Eq for MavenVersion {} + +/// One `[a,b)` of a version requirement. +#[derive(Debug, Clone)] +struct Bounds { + lower: Option<(MavenVersion, bool)>, + upper: Option<(MavenVersion, bool)>, +} + +impl Bounds { + fn contains(&self, version: &MavenVersion) -> bool { + if let Some((bound, inclusive)) = &self.lower { + match bound.cmp(version) { + Ordering::Greater => return false, + Ordering::Equal if !inclusive => return false, + _ => {} + } + } + if let Some((bound, inclusive)) = &self.upper { + match bound.cmp(version) { + Ordering::Less => return false, + Ordering::Equal if !inclusive => return false, + _ => {} + } + } + true + } +} + +/// A hard version requirement: the union of one or more ranges +/// (`[1.0,2.0)`, `(,1.0],[1.2,)`, `[1.5]`, `[1.*]`). +#[derive(Debug, Clone)] +pub(crate) struct VersionRange { + ranges: Vec, + /// The one version of `[1.5]`, which Maven resolves without listing + /// the artifact's versions. + exact: Option, +} + +impl VersionRange { + /// `spec` as a range; `None` when it is a plain (soft) version or not + /// a requirement Maven accepts. + pub(crate) fn parse(spec: &str) -> Option { + let mut rest = spec.trim(); + if !rest.starts_with(['[', '(']) { + return None; + } + let mut ranges = Vec::new(); + let mut exact = None; + while rest.starts_with(['[', '(']) { + let close = rest.find([')', ']'])?; + let (bounds, single) = parse_bounds(&rest[..=close])?; + exact = single; + ranges.push(bounds); + rest = rest[close + 1..].trim(); + if let Some(more) = rest.strip_prefix(',') { + rest = more.trim(); + } + } + if !rest.is_empty() { + return None; + } + let exact = exact.filter(|_| ranges.len() == 1); + Some(VersionRange { ranges, exact }) + } + + pub(crate) fn contains(&self, version: &str) -> bool { + let version = MavenVersion::parse(version); + self.ranges.iter().any(|r| r.contains(&version)) + } + + /// The single version of an exact requirement (`[1.5]`). + pub(crate) fn exact(&self) -> Option<&str> { + self.exact.as_deref() + } +} + +/// One bracketed range and, for `[v]`, that version. +fn parse_bounds(range: &str) -> Option<(Bounds, Option)> { + let lower_inclusive = range.starts_with('['); + let upper_inclusive = range.ends_with(']'); + let inner = range.get(1..range.len() - 1)?; + let Some((low, high)) = inner.split_once(',') else { + if !lower_inclusive || !upper_inclusive { + return None; + } + let version = inner.trim(); + if let Some(prefix) = version.strip_suffix('*').filter(|p| p.ends_with('.')) { + return Some(( + Bounds { + lower: Some((MavenVersion::parse(&format!("{prefix}min")), true)), + upper: Some((MavenVersion::parse(&format!("{prefix}max")), true)), + }, + None, + )); + } + let bound = MavenVersion::parse(version); + return Some(( + Bounds { + lower: Some((bound.clone(), true)), + upper: Some((bound, true)), + }, + Some(version.to_string()), + )); + }; + let (low, high) = (low.trim(), high.trim()); + if high.contains(',') { + return None; + } + let lower = (!low.is_empty()).then(|| MavenVersion::parse(low)); + let upper = (!high.is_empty()).then(|| MavenVersion::parse(high)); + if let (Some(l), Some(u)) = (&lower, &upper) { + if u < l { + return None; + } + } + Some(( + Bounds { + lower: lower.map(|v| (v, lower_inclusive)), + upper: upper.map(|v| (v, upper_inclusive)), + }, + None, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cmp(a: &str, b: &str) -> Ordering { + MavenVersion::parse(a).cmp(&MavenVersion::parse(b)) + } + + #[test] + fn versions_order_as_maven_orders_them() { + // Ascending, each strictly below the next. + let ascending = [ + "1.0-alpha-1", + "1.0-alpha-2", + "1.0-beta-1", + "1.0-milestone-1", + "1.0-rc-1", + "1.0-SNAPSHOT", + "1.0", + "1.0-sp", + "1.0-abc", + "1.0.1", + "1.1", + "1.2", + "1.10", + "2.0", + "2.7.9.2", + "2.9.0", + "2.9.10", + "2.9.10.8", + "2.10.0", + "10.0", + ]; + for pair in ascending.windows(2) { + assert_eq!(cmp(pair[0], pair[1]), Ordering::Less, "{pair:?}"); + assert_eq!(cmp(pair[1], pair[0]), Ordering::Greater, "{pair:?}"); + } + } + + #[test] + fn equal_spellings_compare_equal() { + for (a, b) in [ + ("1", "1.0"), + ("1.0", "1.0.0"), + ("1.0", "1-ga"), + ("1.0", "1.0-final"), + ("1.0-rc1", "1.0-cr1"), + ("1.0a1", "1.0-alpha-1"), + ("1.0b2", "1.0-beta-2"), + ("1.0m3", "1.0-milestone-3"), + ("1.0-RC1", "1.0-rc1"), + ("1.0.0-RELEASE", "1"), + ("01.2", "1.2"), + ] { + assert_eq!(cmp(a, b), Ordering::Equal, "{a} vs {b}"); + } + } + + #[test] + fn suffixed_versions_sort_above_their_base() { + assert_eq!(cmp("2.7.9.2-socket.8e82692a", "2.7.9.2"), Ordering::Greater); + assert_eq!(cmp("2.7.9.2-socket.8e82692a", "2.7.9.3"), Ordering::Less); + } + + #[test] + fn long_numbers_compare_by_value() { + assert_eq!( + cmp("1.20260101000000", "1.20250101000000"), + Ordering::Greater + ); + assert_eq!(cmp("1.20260101000000", "1.999999999"), Ordering::Greater); + } + + #[test] + fn ranges_admit_what_maven_admits() { + let range = VersionRange::parse("[2.9.0,2.9.10]").unwrap(); + for v in ["2.9.0", "2.9.5", "2.9.10"] { + assert!(range.contains(v), "{v}"); + } + for v in ["2.7.9.2", "2.8.11", "2.9.10.1", "2.10.0", "2.9.0-rc1"] { + assert!(!range.contains(v), "{v}"); + } + let half_open = VersionRange::parse("[1.9,1.11)").unwrap(); + assert!(half_open.contains("1.9") && half_open.contains("1.10.0")); + assert!(!half_open.contains("1.11") && !half_open.contains("1.8")); + let unbounded = VersionRange::parse("(,1.0],[1.2,)").unwrap(); + assert!(unbounded.contains("0.5") && unbounded.contains("1.0") && unbounded.contains("3")); + assert!(!unbounded.contains("1.1")); + let prefix = VersionRange::parse("[1.2.*]").unwrap(); + assert!(prefix.contains("1.2.0") && prefix.contains("1.2.99")); + assert!(!prefix.contains("1.3") && !prefix.contains("1.1.9")); + } + + #[test] + fn an_exact_requirement_names_its_version() { + let exact = VersionRange::parse("[1.5]").unwrap(); + assert_eq!(exact.exact(), Some("1.5")); + assert!(exact.contains("1.5") && !exact.contains("1.5.1")); + assert_eq!(VersionRange::parse("[1.0,2.0)").unwrap().exact(), None); + } + + #[test] + fn plain_versions_and_malformed_ranges_are_not_ranges() { + for spec in [ + "1.0", + "", + "LATEST", + "[1.0", + "(1.0)", + "[2.0,1.0]", + "[1,2,3]", + "[1,2) x", + ] { + assert!(VersionRange::parse(spec).is_none(), "{spec}"); + } + } +} diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index dd907a2a1..73c68721d 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -25,6 +25,7 @@ use serde::{Deserialize, Serialize}; use crate::api::types::PackageVendorResult; use crate::constants::npm_family::VLT_HIDDEN_LOCK_REL; +use crate::crawlers::maven_selection::MavenSelection; use crate::formats::cargo::source_replacement::CratesIoSource; use crate::formats::governing_locks::PYPI_REQUIREMENTS; use crate::patch::redirect::npmrc::{ @@ -1988,6 +1989,13 @@ pub struct RewriteOptions<'a> { /// resolved only when a cargo dep is rewritten (the cargo rewriter's /// offline-source refusal). pub cargo_outer: &'a (dyn Fn() -> CratesIoSource + Send + Sync), + /// What Maven selects in each module of the project, read from the + /// poms the Maven local repository holds; resolved only when a maven + /// dep is rewritten. The pom rewriter pins a patch only where Maven + /// selects its base version already (a pin anywhere else would change + /// the version the build resolves). `None` from a host with no local + /// repository to read: the rewriter then pins without that check. + pub maven_selection: &'a (dyn Fn() -> Option + Send + Sync), /// A variable of the environment pnpm installs the project in, by /// name: a `pnpm_config_trust_lockfile` there beats the /// pnpm-workspace.yaml key the trust auto-config writes (#1514). @@ -2703,6 +2711,10 @@ async fn rewrite_once( } else { CratesIoSource::Registry }; + let maven_selection = (rewrite_overrides.iter().any(|o| o.ecosystem == "maven") + && files.contains_key("pom.xml")) + .then(|| (options.maven_selection)()) + .flatten(); let (files, mut rewrite) = if options.blocking { // Pure CPU over every lock text (the independent rewriter groups // run concurrently inside), so it runs on the blocking pool rather @@ -2717,6 +2729,7 @@ async fn rewrite_once( &gradle_unreadable, &yarn_outer, &cargo_outer, + maven_selection.as_ref(), ); (files, rewrite) }) @@ -2735,6 +2748,7 @@ async fn rewrite_once( &gradle_unreadable, &yarn_outer, &cargo_outer, + maven_selection.as_ref(), ); (files, rewrite) }; @@ -4123,6 +4137,10 @@ mod tests { ); } + fn no_maven_selection() -> Option { + None + } + fn no_cargo_outer() -> CratesIoSource { CratesIoSource::Registry } @@ -4539,6 +4557,7 @@ mod tests { npm_outer: &outer, yarn_classic_outer: &OuterYarnMirror::default, cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, pnpm_env: &no_env, blocking: false, takeover_uuids: Default::default(), @@ -4602,6 +4621,7 @@ mod tests { npm_outer: &outer, yarn_classic_outer: &OuterYarnMirror::default, cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, pnpm_env: &no_env, blocking: false, takeover_uuids: Default::default(), @@ -4895,6 +4915,7 @@ mod tests { npm_outer: &outer, yarn_classic_outer: &OuterYarnMirror::default, cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, pnpm_env: env, blocking: false, takeover_uuids: Default::default(), @@ -5583,6 +5604,7 @@ snapshots: npm_outer: &outer, yarn_classic_outer: &OuterYarnMirror::default, cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, pnpm_env: &no_env, blocking: false, takeover_uuids: Default::default(), @@ -5680,6 +5702,7 @@ snapshots: npm_outer: &outer, yarn_classic_outer: &OuterYarnMirror::default, cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, pnpm_env: &no_env, blocking: false, takeover_uuids: Default::default(), @@ -5850,6 +5873,7 @@ snapshots: npm_outer: &outer, yarn_classic_outer: &OuterYarnMirror::default, cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, pnpm_env: &no_env, blocking: false, takeover_uuids: Default::default(), @@ -6246,6 +6270,7 @@ snapshots: npm_outer: &outer, yarn_classic_outer: &OuterYarnMirror::default, cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, pnpm_env: &no_env, blocking: false, takeover_uuids: Default::default(), @@ -6454,6 +6479,7 @@ snapshots: npm_outer: &outer, yarn_classic_outer: &OuterYarnMirror::default, cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, pnpm_env: &no_env, blocking: false, takeover_uuids: Default::default(), @@ -6501,6 +6527,7 @@ snapshots: npm_outer: &outer, yarn_classic_outer: &OuterYarnMirror::default, cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, pnpm_env: &no_env, blocking: false, takeover_uuids: Default::default(), @@ -6691,6 +6718,7 @@ snapshots: npm_outer: &outer, yarn_classic_outer: &OuterYarnMirror::default, cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, pnpm_env: &no_env, blocking: false, takeover_uuids: Default::default(), @@ -7094,6 +7122,7 @@ snapshots: npm_outer: &outer, yarn_classic_outer: &OuterYarnMirror::default, cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, pnpm_env: &no_env, blocking: false, takeover_uuids: Default::default(), diff --git a/crates/socket-patch-core/src/hosted/memory/stages.rs b/crates/socket-patch-core/src/hosted/memory/stages.rs index 54883bc5e..345ad98b2 100644 --- a/crates/socket-patch-core/src/hosted/memory/stages.rs +++ b/crates/socket-patch-core/src/hosted/memory/stages.rs @@ -362,6 +362,8 @@ pub(crate) async fn rewrite( yarn_classic_outer: &yarn_classic_outer, // The in-memory engine has no project on disk to read. cargo_outer: &|| CratesIoSource::Registry, + // Maven is not rewritten in memory (no local repository). + maven_selection: &|| None, // Nor the environment the project's installs run in. pnpm_env: &|_| None, blocking: false, diff --git a/crates/socket-patch-core/src/patch/redirect/group_equivalence_tests.rs b/crates/socket-patch-core/src/patch/redirect/group_equivalence_tests.rs index e012bc418..16808d824 100644 --- a/crates/socket-patch-core/src/patch/redirect/group_equivalence_tests.rs +++ b/crates/socket-patch-core/src/patch/redirect/group_equivalence_tests.rs @@ -39,7 +39,7 @@ fn serial_oracle( rewrite_composer_lock(files, overrides, &mut result); rewrite_nuget(files, overrides, &mut result); rewrite_gem(files, overrides, &mut result); - rewrite_maven_pom(files, overrides, &mut result); + rewrite_maven_pom(files, overrides, None, &mut result); rewrite_golang(files, overrides, &mut result); result } @@ -138,6 +138,7 @@ fn assert_same_with_metadata( &no_gradle_unreadable, &no_yarn_outer, &CratesIoSource::Registry, + None, ); let merged = merge_group_outputs(&prefix, run_groups_concurrently(&prefix, &groups)).map( |mut merged| { diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 73cae946e..0034b926c 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -57,6 +57,7 @@ mod pipenv; mod pipenv_pylock_tests; pub mod presence; // The pnpm hosted planner lives with the format's model. +use crate::crawlers::maven_selection::{MavenSelection, Verdict}; use crate::formats::cargo::hosted::CargoLockPlan; #[cfg(test)] use crate::formats::cargo::hosted::CARGO_LOCK_REFERENCE_KIND; @@ -605,6 +606,7 @@ pub fn rewrite_registry_redirect_with_pipenv_version( &std::collections::BTreeSet::new(), &yarnrc::OuterYarnMirror::default(), &CratesIoSource::Registry, + None, ) } @@ -671,7 +673,10 @@ fn withhold_pypi_platform_wheels<'a>( /// [`rewrite_registry_redirect_with_pipenv_version`] with the inputs only /// the host can resolve. `gradle_unreadable` are the Gradle build files /// the host found but could not read as text: the Gradle planner refuses -/// the build rather than take them for absent. +/// the build rather than take them for absent. `maven` is what Maven +/// selects in each module of the project, read from the local repository: +/// the pom rewriter pins a patch only where that is its base version +/// (`None`: no such answer, and it pins as it did before there was one). #[allow(clippy::too_many_arguments)] pub fn rewrite_registry_redirect_with_host( files: &BTreeMap, @@ -682,6 +687,7 @@ pub fn rewrite_registry_redirect_with_host( gradle_unreadable: &std::collections::BTreeSet, yarn_outer: &yarnrc::OuterYarnMirror, cargo_outer: &CratesIoSource, + maven: Option<&MavenSelection>, ) -> RewriteResult { let mut result = RewriteResult::default(); let overrides = withhold_pypi_platform_wheels(overrides, &mut result); @@ -707,6 +713,7 @@ pub fn rewrite_registry_redirect_with_host( gradle_unreadable, yarn_outer, cargo_outer, + maven, ); let mut result = rewrite_groups_parallel(result, &groups); result.vlt_drives = vlt::vlt_drives(files, bun_lockb_present); @@ -733,6 +740,7 @@ fn rewriter_groups<'a>( gradle_unreadable: &'a std::collections::BTreeSet, yarn_outer: &'a yarnrc::OuterYarnMirror, cargo_outer: &'a CratesIoSource, + maven: Option<&'a MavenSelection>, ) -> Vec> { vec![ Box::new(move |result| { @@ -754,7 +762,7 @@ fn rewriter_groups<'a>( Box::new(move |result| rewrite_composer_lock(files, overrides, result)), Box::new(move |result| rewrite_nuget(files, overrides, result)), Box::new(move |result| rewrite_gem(files, overrides, result)), - Box::new(move |result| rewrite_maven_pom(files, overrides, result)), + Box::new(move |result| rewrite_maven_pom(files, overrides, maven, result)), Box::new(move |result| { gradle::rewrite_gradle_hosted(files, gradle_unreadable, overrides, result) }), @@ -8905,6 +8913,7 @@ fn find_maven_dependency_matches( fn rewrite_maven_pom( files: &BTreeMap, overrides: &[DepOverride], + selection: Option<&MavenSelection>, result: &mut RewriteResult, ) { let maven: Vec<&DepOverride> = overrides @@ -9073,6 +9082,33 @@ fn rewrite_maven_pom( continue; } }; + // A `` pin makes every occurrence of the GA + // one version, so it is safe only where Maven selects the patch's + // base version already. A build that selects another version (or + // does not resolve the GA at all) has nothing for this patch to + // replace: it is left exactly as it is, and the line says which + // version Maven selects instead. + let verdict = + selection.map(|s| s.verdict("pom.xml", &group_id, &artifact_id, &dep.version)); + if let Some(Verdict::Other(_) | Verdict::Absent) = &verdict { + let others = match verdict { + Some(Verdict::Other(version)) => vec![version], + _ => Vec::new(), + }; + result.warnings.push(RewriteWarning { + code: "redirect_maven_version_not_selected".into(), + detail: format!( + "{}; pom.xml was left as it is", + crate::crawlers::maven_selection::not_selected_detail( + &group_id, + &artifact_id, + &dep.version, + &others + ) + ), + }); + continue; + } let all_matches = find_maven_dependency_matches(idx, &group_id, &artifact_id); // Only the GA's main jar is granted: the served maven2 tail holds // `-.jar/.pom` and nothing else. A classifier variant @@ -9458,6 +9494,24 @@ fn rewrite_maven_pom( // as a versioned match, so `versioned` is non-empty and this branch is // skipped (idempotent). if versioned.is_empty() { + // Nothing in this pom names a version to replace, and what + // Maven selects cannot be told: a pin would be a guess that + // may change the version the build resolves. + if let Some(Verdict::Undetermined(why)) = &verdict { + result.warnings.push(RewriteWarning { + code: "redirect_maven_selection_undetermined".into(), + detail: format!( + "{}; pom.xml was left as it is", + crate::crawlers::maven_selection::undetermined_detail( + &group_id, + &artifact_id, + &dep.version, + why + ) + ), + }); + continue; + } idx.insert_dependency_management(pom_text, &group_id, &artifact_id, &suffixed_version); pom_changed = true; pin_landed = true; @@ -11450,6 +11504,103 @@ mod tests { ); } + /// Hosted-redirects slf4j-api in a lone `pom.xml` whose module selects + /// `pick` for it (`None`: does not resolve it). + fn rewrite_pom_selecting(pom: &str, pick: Option>) -> RewriteResult { + let picks: Vec<_> = pick + .into_iter() + .map(|pick| ("pom.xml", "org.slf4j", "slf4j-api", pick)) + .collect(); + let selection = MavenSelection::answering(&["pom.xml"], &picks); + let files = BTreeMap::from([("pom.xml".to_string(), pom.to_string())]); + rewrite_registry_redirect_with_host( + &files, + &[maven_override()], + &BTreeMap::new(), + None, + false, + &std::collections::BTreeSet::new(), + &yarnrc::OuterYarnMirror::default(), + &CratesIoSource::Registry, + Some(&selection), + ) + } + + const TRANSITIVE_ONLY_POM: &str = "\n \n \n \ + ch.qos.logback\n logback-classic\n \ + 1.4.14\n \n \n\n"; + + /// A `` pin makes every occurrence of the GA one + /// version, so it is written only where Maven selects the patch's + /// base version already. + #[test] + fn maven_pin_is_written_only_where_maven_selects_the_base_version() { + // Selected through another artifact: pinned, as before. + let r = rewrite_pom_selecting(TRANSITIVE_ONLY_POM, Some(Ok("1.7.36"))); + let out = r.files.get("pom.xml").expect("pom rewritten"); + assert!( + out.contains(&format!("{MAVEN_SUFFIXED}")), + "{out}" + ); + assert!(warning_codes(&r).contains(&"redirect_maven_dep_management_added")); + + // Maven selects another version, or does not resolve the GA: + // nothing is written, and the line says what Maven selects. + for (pick, says) in [ + ( + Some(Ok("2.0.9")), + "Maven selects org.slf4j:slf4j-api 2.0.9 in this build, not 1.7.36", + ), + (None, "no module of this build resolves org.slf4j:slf4j-api"), + ] { + let r = rewrite_pom_selecting(TRANSITIVE_ONLY_POM, pick); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.files); + assert_eq!( + warning_codes(&r), + vec!["redirect_maven_version_not_selected"] + ); + assert!( + r.warnings[0].detail.contains(says), + "{}", + r.warnings[0].detail + ); + } + } + + /// What Maven selects cannot be told: no pin is written on a guess, + /// but a declaration that names the base version is still rewritten + /// where it stands. + #[test] + fn maven_undetermined_selection_pins_nothing_new() { + let unread = Some(Err( + "the pom of ch.qos.logback:logback-classic:1.4.14 is not cached", + )); + let r = rewrite_pom_selecting(TRANSITIVE_ONLY_POM, unread); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.files); + assert_eq!( + warning_codes(&r), + vec!["redirect_maven_selection_undetermined"] + ); + let detail = &r.warnings[0].detail; + assert!( + detail.contains("logback-classic:1.4.14 is not cached") + && detail.contains("mvn -q dependency:resolve"), + "{detail}" + ); + + let direct = "\n \n \n \ + org.slf4j\n slf4j-api\n \ + 1.7.36\n \n \n\n"; + let r = rewrite_pom_selecting(direct, unread); + let out = r.files.get("pom.xml").expect("pom rewritten"); + assert!( + out.contains(&format!("{MAVEN_SUFFIXED}")), + "{out}" + ); + assert!(!out.contains(""), "{out}"); + assert!(!warning_codes(&r).contains(&"redirect_maven_selection_undetermined")); + } + /// Fail-closed refusals: a `${property}` version refuses the whole dep (no /// repo/checksums); a mismatched literal version skips it; a non-jar /// `` skips it. @@ -14346,6 +14497,7 @@ mod tests { &std::collections::BTreeSet::new(), &refusing[3], &CratesIoSource::Registry, + None, ); assert!(!r.files.contains_key("yarn.lock")); assert!(r diff --git a/crates/socket-patch-core/src/vendor/jvm/apply.rs b/crates/socket-patch-core/src/vendor/jvm/apply.rs index 6d81f17cc..c24550512 100644 --- a/crates/socket-patch-core/src/vendor/jvm/apply.rs +++ b/crates/socket-patch-core/src/vendor/jvm/apply.rs @@ -1314,15 +1314,35 @@ pub fn check_entry_in( attempts.push((as_committed, None)); } } + // Likewise the pins: `vendor` writes one only where Maven selects the + // base version, as far as the local repository told it. What that + // repository says now, and the pins a run with no such answer writes, + // are both in sync. + let selection = matches!(shape, Shape::MavenReactor | Shape::Mixed).then(|| match local_repo { + Some(repo) => crate::crawlers::maven_selection::MavenSelection::of(root, repo), + None => crate::crawlers::maven_selection::MavenSelection::unavailable( + "no Maven local repository was read", + ), + }); + let attempts: Vec<_> = [selection.as_ref(), None] + .into_iter() + .take(if selection.is_some() { 2 } else { 1 }) + .flat_map(|selection| { + attempts + .iter() + .map(move |(patch, external)| (patch, *external, selection)) + }) + .collect(); let mut drift: Option = None; let mut in_sync: Option = None; - for (patch, external) in &attempts { - let outcome = super::plan_with_external(shape, &read, &list, patch, config, *external) - .map_err(|e| e.detail) - .and_then(|plan| match plan.writes.first() { - Some(w) => Err(format!("vendored wiring or metadata drifted: {}", w.rel)), - None => Ok(plan), - }); + for (patch, external, selection) in &attempts { + let outcome = + super::plan_with_selection(shape, &read, &list, patch, config, *external, *selection) + .map_err(|e| e.detail) + .and_then(|plan| match plan.writes.first() { + Some(w) => Err(format!("vendored wiring or metadata drifted: {}", w.rel)), + None => Ok(plan), + }); match outcome { Ok(plan) => { in_sync = Some(plan); diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs index e3b78c8f6..12e5efc34 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs @@ -11,6 +11,7 @@ use std::ops::Range; use serde_json::{json, Value}; +use crate::crawlers::maven_selection::{MavenSelection, Verdict}; use crate::formats::maven::{ classpath_copy, interpolate_keeping, interpolate_strict, is_executable_classifier, lookup_property, maven_config_properties as cli_properties, profile_combinations, Definitions, @@ -203,6 +204,28 @@ pub fn plan_with_external( patch: &JvmPatch<'_>, config_enabled: bool, external: Option<&ExternalPoms>, +) -> Result { + plan_with_selection(read, list, patch, config_enabled, external, None) +} + +/// [`plan_with_external`] that pins a local root only where Maven selects +/// the patch's base version already. A `` pin makes +/// every occurrence of the artifact that version, in the root and in every +/// module that inherits it, so it is written only when each of those +/// modules resolves the artifact at the base version (or not at all) by +/// `selection`. A module that resolves another version leaves the root +/// unpinned (`version_not_selected`); one whose answer is not certain +/// leaves the root as it is, pin or no pin (`selection_undetermined`). A +/// declaration that names the base version is rewritten either way: that +/// replaces the version where it stands, and moves nothing. `None` plans +/// without the check (callers that only probe a shape). +pub fn plan_with_selection( + read: ReadFn<'_>, + list: ListFn<'_>, + patch: &JvmPatch<'_>, + config_enabled: bool, + external: Option<&ExternalPoms>, + selection: Option<&MavenSelection>, ) -> Result { let (g, a, v) = (patch.group_id, patch.artifact_id, patch.version); if !safe_coordinates(g, a, v) { @@ -285,6 +308,55 @@ pub fn plan_with_external( } } + // Roots whose pin stays as it is: nothing says what their modules + // select. + let mut held: BTreeSet = BTreeSet::new(); + if let Some(selection) = selection { + for root in reactor.wired_roots() { + if unpinned.contains(&root) || managed_roots.contains(&root) { + continue; + } + let (mut selected, mut other, mut undetermined) = (false, None, None); + for rel in reactor + .reactor + .iter() + .filter(|rel| reactor.local_root(rel) == root) + { + match selection.verdict(rel, g, a, v) { + Verdict::Selected => selected = true, + Verdict::Other(version) => { + other.get_or_insert((rel.clone(), version)); + } + Verdict::Absent => {} + Verdict::Undetermined(why) => { + undetermined.get_or_insert((rel.clone(), why)); + } + } + } + if let Some((rel, version)) = other { + warnings.push(degraded( + "version_not_selected", + format!( + "{rel} resolves {g}:{a} at {version}, not {v}; {root} is not pinned, since a pin there would change the version {rel} resolves" + ), + )); + unpinned.insert(root); + } else if let Some((rel, why)) = undetermined { + warnings.push(degraded( + "selection_undetermined", + format!( + "which version of {g}:{a} {rel} resolves cannot be told ({why}); the pin of {root} is left as it is" + ), + )); + held.insert(root); + } else if !selected { + // No module under this root resolves the artifact: nothing + // would read a pin there. + unpinned.insert(root); + } + } + } + let banning = reactor .scope .iter() @@ -304,6 +376,7 @@ pub fn plan_with_external( let file_edits = edits.entry(root.clone()).or_default(); let pinned = !unpinned.contains(&root) && !managed_roots.contains(&root); match pin_of(doc, patch) { + _ if held.contains(&root) => {} Some(pin) if !pinned => file_edits.push(Edit::plain(pin.start, pin.end, "")), Some(pin) if pin.uuid == patch.uuid => {} Some(pin) => { @@ -574,11 +647,26 @@ pub fn references_checked( }) } +/// The degraded reasons that leave a declaration or a root alone; the +/// repository and config notes (and a mixed root's Gradle warnings) say +/// nothing about why a reactor is unwired. +const UNWIRING: [&str; 9] = [ + "property_unresolved", + "conflicting_literal_version", + "conflicting_managed_version", + "management_unresolved", + "version_not_selected", + "selection_undetermined", + "range", + "coordinates_overridden", + "classifier_declared", +]; + /// Refuse `plan` when, written over `read`, no pom of the reactor would /// name `c`'s suffixed version: every declaration was left as is and no /// root pinned (#513). Vendoring it would count the patch as applied while -/// the build keeps resolving the base; the refusal carries the degraded -/// reasons that left it unwired. +/// the build resolves what it resolved before; the refusal carries the +/// degraded reasons that left it unwired. pub fn refuse_unwired( read: ReadFn<'_>, list: ListFn<'_>, @@ -592,18 +680,6 @@ pub fn refuse_unwired( if wired_checked(&planned, list, c)? { return Ok(()); } - // Only the reasons that leave a declaration or a root alone; the - // repository and config notes (and a mixed root's Gradle warnings) - // say nothing about why the reactor is unwired. - const UNWIRING: [&str; 7] = [ - "property_unresolved", - "conflicting_literal_version", - "conflicting_managed_version", - "management_unresolved", - "range", - "coordinates_overridden", - "classifier_declared", - ]; let why: Vec<&str> = plan .warnings .iter() @@ -623,8 +699,8 @@ pub fn refuse_unwired( Err(JvmRefusal { code: SHAPE_UNSUPPORTED, detail: format!( - "reason: nothing_wired: no pom of the reactor would build {}:{}:{}, so Maven \ - keeps resolving {} ({why})", + "reason: nothing_wired: no pom of the reactor would build {}:{}:{}, so the patch \ + for {} is not applied ({why})", c.group_id, c.artifact_id, c.suffixed_version(), @@ -633,6 +709,20 @@ pub fn refuse_unwired( }) } +/// Whether the only thing that left `plan` without a pin is that what Maven +/// selects could not be told (`selection_undetermined`): no declaration +/// was passed over for a reason of its own. +pub fn unwired_by_selection_alone(plan: &JvmPlan) -> bool { + let reasons: Vec<&str> = plan + .warnings + .iter() + .filter(|w| w.code == DEGRADED) + .filter_map(|w| w.detail.strip_prefix("reason: ")?.split(':').next()) + .filter(|reason| UNWIRING.contains(reason)) + .collect(); + !reasons.is_empty() && reasons.iter().all(|r| *r == "selection_undetermined") +} + /// [`wired_checked`], and no declaration of `c`'s g:a is left at a version /// that may still read the base: the base itself, as a module or /// dependency added since vendoring declares it (#584), or a `${...}` the @@ -947,6 +1037,13 @@ pub(crate) struct PomDecl { pub scope: Option, pub optional: bool, pub kind: Option, + pub classifier: Option, + /// `(groupId, artifactId)` of each ``, as written (`*` is + /// Maven's wildcard). + pub exclusions: Vec<(String, String)>, + /// A `` pin vendoring wrote (its tag comment + /// precedes it): not a declaration of the project's own. + pub pinned: bool, } /// The parts of a pom a dependency-graph walk reads: coordinates, parent, @@ -968,6 +1065,35 @@ pub(crate) struct PomModel { /// ``: a missing part keeps the /// pom's own. pub relocation: Option<(Option, Option, Option)>, + /// How many trailing entries of `deps` and of `managed` come from + /// profiles (none unless they were asked for). + pub profile_deps: usize, + pub profile_managed: usize, + /// What the pom's profiles declare, whether or not it was added above. + pub profiles: PomProfiles, +} + +/// What the `` of a pom may change in its model when active. +#[derive(Debug, Clone, Default)] +pub(crate) struct PomProfiles { + /// A profile declares ``. + pub deps: bool, + /// A profile's `` entries. + pub managed: Vec, + /// Every property name a profile defines. + pub props: BTreeSet, +} + +impl PomModel { + /// The `` of the project itself (no profile's). + pub(crate) fn own_deps(&self) -> &[PomDecl] { + &self.deps[..self.deps.len() - self.profile_deps] + } + + /// The `` of the project itself. + pub(crate) fn own_managed(&self) -> &[PomDecl] { + &self.managed[..self.managed.len() - self.profile_managed] + } } /// [`PomModel`] of `text`; `include_profiles` adds every profile's @@ -976,13 +1102,24 @@ pub(crate) struct PomModel { pub(crate) fn pom_model(text: &str, include_profiles: bool) -> Result { let doc = Doc::parse(text.to_string())?; let project = doc.project; - let mut roots = vec![project]; - if include_profiles { - if let Some(profiles) = doc.child(project, "profiles") { - roots.extend(doc.children(profiles, "profile")); - } - } + let profile_roots: Vec = doc + .child(project, "profiles") + .map(|profiles| doc.children(profiles, "profile").collect()) + .unwrap_or_default(); let decl = |dep: usize| -> Option { + let exclusions = doc + .child(dep, "exclusions") + .into_iter() + .flat_map(|list| doc.children(list, "exclusion")) + .map(|e| { + let part = |name| { + doc.child_text(e, name) + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| "*".to_string()) + }; + (part("groupId"), part("artifactId")) + }) + .collect(); Some(PomDecl { group: doc.child_text(dep, "groupId")?, artifact: doc.child_text(dep, "artifactId")?, @@ -990,24 +1127,55 @@ pub(crate) fn pom_model(text: &str, include_profiles: bool) -> Result Vec { + doc.child(root, "dependencies") + .into_iter() + .flat_map(|list| doc.children(list, "dependency")) + .filter_map(decl) + .collect() + }; + let managed_of = |root: usize| -> Vec { + doc.child(root, "dependencyManagement") .and_then(|dm| doc.child(dm, "dependencies")) - { - managed.extend(doc.children(list, "dependency").filter_map(decl)); - } + .into_iter() + .flat_map(|list| doc.children(list, "dependency")) + .filter_map(decl) + .collect() + }; + let modules_of = |root: usize, out: &mut Vec| { for (list, item) in [("modules", "module"), ("subprojects", "subproject")] { if let Some(list) = doc.child(root, list) { - modules.extend(doc.children(list, item).map(|m| doc.text_of(m))); + out.extend(doc.children(list, item).map(|m| doc.text_of(m))); + } + } + }; + let (mut deps, mut managed, mut modules) = (deps_of(project), managed_of(project), Vec::new()); + modules_of(project, &mut modules); + let mut profiles = PomProfiles::default(); + let (mut profile_deps, mut profile_managed) = (0, 0); + for &root in &profile_roots { + let (profile_dep_list, profile_managed_list) = (deps_of(root), managed_of(root)); + profiles.deps |= !profile_dep_list.is_empty(); + profiles + .managed + .extend(profile_managed_list.iter().cloned()); + if let Some(p) = doc.child(root, "properties") { + for &c in &doc.nodes[p].children { + profiles.props.insert(doc.nodes[c].name.clone()); } } + if include_profiles { + profile_deps += profile_dep_list.len(); + profile_managed += profile_managed_list.len(); + deps.extend(profile_dep_list); + managed.extend(profile_managed_list); + modules_of(root, &mut modules); + } } let mut props = BTreeMap::new(); if let Some(p) = doc.child(project, "properties") { @@ -1038,6 +1206,9 @@ pub(crate) fn pom_model(text: &str, include_profiles: bool) -> Result String { + format!( + "\n 4.0.0\n \n \ + t\n root\n 1\n \ + \n {name}\n\n" + ) + } + + /// A parent and two modules that reach commons-text only through + /// other artifacts: nothing but a pin can wire the patch. + fn two_modules() -> Fs { + fs(&[ + ("pom.xml", PARENT_OF_TWO), + ("a/pom.xml", &inheriting("a")), + ("b/pom.xml", &inheriting("b")), + ]) + } + + /// The selection of the two modules: `Ok(version)`, `Err(why)` or + /// `None` for a module that does not resolve the artifact. + fn selecting(a: Option>, b: Option>) -> MavenSelection { + let picks: Vec<_> = [("a/pom.xml", a), ("b/pom.xml", b)] + .into_iter() + .filter_map(|(pom, pick)| Some((pom, GA.0, GA.1, pick?))) + .collect(); + MavenSelection::answering(&["pom.xml", "a/pom.xml", "b/pom.xml"], &picks) + } + + fn run_selecting(files: &Fs, selection: &MavenSelection) -> JvmPlan { + let read = |p: &str| files.get(p).cloned(); + plan_with_selection(&read, &lister(files), &patch(), true, None, Some(selection)) + .expect("plan") + } + + fn left_unwired(files: &Fs, plan: &JvmPlan) -> Option { + let read = |p: &str| files.get(p).cloned(); + refuse_unwired(&read, &lister(files), &patch().coords(), plan).err() + } + + #[test] + fn a_root_is_pinned_when_every_module_selects_the_base_or_nothing() { + for selection in [ + selecting(Some(Ok("1.10.0")), Some(Ok("1.10.0"))), + selecting(Some(Ok("1.10.0")), None), + // An earlier run's suffixed version is the base version. + selecting(Some(Ok(SV)), None), + ] { + let files = two_modules(); + let plan = run_selecting(&files, &selection); + let after = applied(&files, &plan); + assert!(text(&after, "pom.xml").contains(&format!("{SV}"))); + assert_eq!(after["a/pom.xml"], files["a/pom.xml"]); + assert_eq!(after["b/pom.xml"], files["b/pom.xml"]); + assert!(left_unwired(&files, &plan).is_none()); + // Planning the result again writes nothing. + assert!(run_selecting(&after, &selection).writes.is_empty()); + } + } + + /// The table's V3 at the root: a pin there would move the module that + /// resolves another version, so none is written. + #[test] + fn a_root_is_not_pinned_when_a_module_selects_another_version() { + let files = two_modules(); + let selection = selecting(Some(Ok("1.10.0")), Some(Ok("1.11.0"))); + let plan = run_selecting(&files, &selection); + let after = applied(&files, &plan); + for rel in ["pom.xml", "a/pom.xml", "b/pom.xml"] { + assert!(!text(&after, rel).contains(SV), "{rel}"); + } + assert!(reasons(&plan).contains(&"version_not_selected".to_string())); + let warning = plan + .warnings + .iter() + .find(|w| w.detail.starts_with("reason: version_not_selected: ")) + .unwrap(); + assert!( + warning + .detail + .contains("b/pom.xml resolves org.apache.commons:commons-text at 1.11.0"), + "{}", + warning.detail + ); + let refusal = left_unwired(&files, &plan).expect("nothing wired"); + assert_eq!(refusal_reason(&refusal), "nothing_wired"); + assert!( + refusal.detail.contains("version_not_selected"), + "{}", + refusal.detail + ); + assert!(!unwired_by_selection_alone(&plan)); + } + + /// No module resolves the artifact: a pin would be read by nothing. + #[test] + fn a_root_no_module_resolves_the_artifact_under_is_not_pinned() { + let files = two_modules(); + let plan = run_selecting(&files, &selecting(None, None)); + assert!(!text(&applied(&files, &plan), "pom.xml").contains(SV)); + assert!(!reasons(&plan).contains(&"version_not_selected".to_string())); + } + + /// What Maven selects cannot be told: no pin is written on a guess, + /// and a pin an earlier run wrote is left where it is. + #[test] + fn an_undetermined_selection_leaves_the_pin_as_it_is() { + let files = two_modules(); + let undetermined = selecting(Some(Err("the pom of x:y:1 is not cached")), None); + let plan = run_selecting(&files, &undetermined); + assert!(!text(&applied(&files, &plan), "pom.xml").contains(SV)); + assert_eq!( + reasons(&plan) + .iter() + .filter(|r| *r == "selection_undetermined") + .count(), + 1 + ); + assert!(left_unwired(&files, &plan).is_some()); + assert!(unwired_by_selection_alone(&plan)); + + let certain = selecting(Some(Ok("1.10.0")), None); + let pinned = applied(&files, &run_selecting(&files, &certain)); + assert!(text(&pinned, "pom.xml").contains(SV)); + let again = run_selecting(&pinned, &undetermined); + assert!(again.writes.is_empty(), "{:?}", pom_rels(&again)); + } + + /// A pin written before the selection was read (or before the build + /// moved on) goes once a module is known to resolve another version. + #[test] + fn a_pin_that_moves_a_module_is_removed() { + let files = two_modules(); + let (_, pinned) = vendor(&files); + assert!(text(&pinned, "pom.xml").contains(SV)); + let plan = run_selecting(&pinned, &selecting(Some(Ok("1.10.0")), Some(Ok("1.11.0")))); + let after = applied(&pinned, &plan); + assert!( + !text(&after, "pom.xml").contains(SV), + "{}", + text(&after, "pom.xml") + ); + } + + /// A declaration that names the base version is rewritten whatever + /// the selection says of the rest: that replaces a version in place. + #[test] + fn a_base_declaration_is_rewritten_under_any_selection() { + let mut files = two_modules(); + files.insert( + "a/pom.xml".to_string(), + inheriting("a") + .replace( + "", + &format!( + " {}\n", + dep("1.10.0") + ), + ) + .into_bytes(), + ); + for selection in [ + selecting(Some(Ok("1.10.0")), Some(Ok("1.11.0"))), + selecting(Some(Err("unread")), Some(Err("unread"))), + ] { + let plan = run_selecting(&files, &selection); + let after = applied(&files, &plan); + assert!(text(&after, "a/pom.xml").contains(&format!("{SV}"))); + assert!(!text(&after, "pom.xml").contains(SV)); + assert!(left_unwired(&files, &plan).is_none()); + } + } + fn pom_rels(plan: &JvmPlan) -> Vec<&str> { plan.writes .iter() diff --git a/crates/socket-patch-core/src/vendor/jvm/mod.rs b/crates/socket-patch-core/src/vendor/jvm/mod.rs index 1581a8acd..04263e350 100644 --- a/crates/socket-patch-core/src/vendor/jvm/mod.rs +++ b/crates/socket-patch-core/src/vendor/jvm/mod.rs @@ -394,15 +394,30 @@ pub fn plan_with_external( config_enabled: bool, external: Option<&maven_reactor::ExternalPoms>, ) -> Result { + plan_with_selection(shape, read, list, patch, config_enabled, external, None) +} + +/// [`plan_with_external`] that pins a Maven root only where Maven selects +/// the patch's base version already (see +/// [`maven_reactor::plan_with_selection`]). +pub fn plan_with_selection( + shape: Shape, + read: ReadFn<'_>, + list: ListFn<'_>, + patch: &JvmPatch<'_>, + config_enabled: bool, + external: Option<&maven_reactor::ExternalPoms>, + selection: Option<&crate::crawlers::maven_selection::MavenSelection>, +) -> Result { + let maven = |read: ReadFn<'_>, list: ListFn<'_>| { + maven_reactor::plan_with_selection(read, list, patch, config_enabled, external, selection) + }; match shape { - Shape::MavenReactor => { - maven_reactor::plan_with_external(read, list, patch, config_enabled, external) - } + Shape::MavenReactor => maven(read, list), Shape::Gradle => gradle::plan(read, list, patch), Shape::Mixed => { // Both halves or neither: a refusal of either writes nothing. - let maven = - maven_reactor::plan_with_external(read, list, patch, config_enabled, external)?; + let maven = maven(read, list)?; let gradle = gradle::plan(read, list, patch)?; Ok(compose(maven, gradle)) } diff --git a/crates/socket-patch-core/src/vendor/jvm/sbt_gate.rs b/crates/socket-patch-core/src/vendor/jvm/sbt_gate.rs index adb409f38..054b73d4a 100644 --- a/crates/socket-patch-core/src/vendor/jvm/sbt_gate.rs +++ b/crates/socket-patch-core/src/vendor/jvm/sbt_gate.rs @@ -31,6 +31,9 @@ use std::path::Path; use super::{JvmRefusal, JvmWarning, Shape}; use crate::crawlers::jvm_cache::debug_log; +use crate::crawlers::maven_selection::{ + not_selected_detail, undetermined_detail, MavenSelection, Standing, +}; use crate::formats::sbt::build::declared_newer; use crate::formats::sbt::evidence::ResolutionDoc; use crate::formats::sbt::gate::{self, GateRefusal, GateWarning}; @@ -52,8 +55,20 @@ pub const SKIP_CODES: &[&str] = &[ "vendor_scala_cli_resolution_missing", "vendor_scala_cli_resolution_stale", "vendor_scala_cli_not_resolved", + MAVEN_NOT_SELECTED, + MAVEN_UNDETERMINED, ]; +/// A Maven build that selects another version of the artifact than the +/// patch's base in every module (or resolves it in none): the base version +/// is not part of the build, so there is nothing to vendor. +pub const MAVEN_NOT_SELECTED: &str = "vendor_maven_version_not_selected"; + +/// A Maven build whose selection of the artifact cannot be told, with no +/// declaration naming the base version to rewrite: nothing is pinned on a +/// guess. +pub const MAVEN_UNDETERMINED: &str = "vendor_maven_selection_undetermined"; + /// The code of a [`GateStop::Silent`] outcome. pub const NOT_RESOLVED: &str = "vendor_jvm_not_resolved"; @@ -117,23 +132,50 @@ pub struct GatePass { pub(crate) struct ShapePass { pub warnings: Vec, pub deps_digest: Option, + /// What Maven selects in each module of a Maven root: the planner pins + /// only where that is the patch's base version. + pub maven: Option, } -/// The gate of a project of `shape` ([`check`] for sbt, -/// [`super::coursier_gate::check`] for scala-cli, none otherwise). +/// The gate of a project of `shape`: [`check`] for sbt, +/// [`super::coursier_gate::check`] for scala-cli, and for a Maven root what +/// Maven selects in each module ([`MavenSelection`], read over the local +/// repository `maven_repo`, or the one this process resolves against): a +/// patch whose base version no module selects is skipped +/// ([`MAVEN_NOT_SELECTED`]). pub(crate) fn for_shape( shape: Shape, project_root: &Path, g: &str, a: &str, base: &str, + maven_repo: Option<&Path>, ) -> Result { + let mut maven = None; let pass = match shape { Shape::Sbt => check(project_root, g, a, base)?, Shape::ScalaCli => GatePass { warnings: super::coursier_gate::check(project_root, g, a, base)?, deps_digest: None, }, + Shape::MavenReactor | Shape::Mixed => { + let selection = match maven_repo { + Some(repo) => MavenSelection::of(project_root, repo), + None => MavenSelection::for_project(project_root), + }; + // A mixed root's Gradle half may still resolve the base + // version: only the planner's pins follow the selection there. + if shape == Shape::MavenReactor { + if let Standing::NotSelected(others) = selection.standing(g, a, base) { + return Err(GateStop::Skip(warning( + MAVEN_NOT_SELECTED, + not_selected_detail(g, a, base, &others), + ))); + } + } + maven = Some(selection); + GatePass::default() + } _ => GatePass::default(), }; Ok(ShapePass { @@ -143,9 +185,33 @@ pub(crate) fn for_shape( .map(|w| VendorWarning::new(w.code, w.detail)) .collect(), deps_digest: pass.deps_digest, + maven, }) } +/// The skip of a Maven patch whose `plan` wired nothing only because +/// `selection` could not tell what the build selects. `None` when it +/// could, or when the plan passed a declaration over for a reason of its +/// own: the plan's refusal then stands. +pub(crate) fn maven_undetermined( + selection: Option<&MavenSelection>, + plan: &super::JvmPlan, + g: &str, + a: &str, + base: &str, +) -> Option { + if !super::maven_reactor::unwired_by_selection_alone(plan) { + return None; + } + match selection?.standing(g, a, base) { + Standing::Undetermined(why) => Some(refused( + MAVEN_UNDETERMINED, + undetermined_detail(g, a, base, &why), + )), + _ => None, + } +} + /// Gate vendoring `g:a` at upstream `base` into the sbt build at /// `project_root`. pub fn check(project_root: &Path, g: &str, a: &str, base: &str) -> Result { diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index e01925a41..3bdfdfdad 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -90,7 +90,9 @@ pub(crate) async fn service_preflight( if shape == super::jvm::Shape::Other { return None; } - jvm_prelude(shape, purl, project_root, record).await.ok()?; + jvm_prelude(shape, purl, project_root, record, None) + .await + .ok()?; (!record.files.is_empty()).then_some(())?; jvm_committed_patch(shape, purl, project_root, record) .await @@ -294,6 +296,37 @@ fn detect_shape(project_root: &Path) -> super::jvm::Shape { super::jvm::detect(&|rel: &str| reader.read(rel), &|dir: &str| reader.list(dir)) } +/// The skip of each of `purls` whose base version no module of the Maven +/// build at `project_root` selects (the gate [`jvm_prelude`] runs, +/// [`super::jvm::sbt_gate::MAVEN_NOT_SELECTED`]), for the refusals a run +/// decides before it downloads anything. Empty for any other build. +pub(super) fn maven_not_selected_refusals( + project_root: &Path, + purls: &[String], +) -> Vec<(String, (&'static str, String))> { + use crate::crawlers::maven_selection::{not_selected_detail, MavenSelection, Standing}; + if detect_shape(project_root) != super::jvm::Shape::MavenReactor { + return Vec::new(); + } + let selection = MavenSelection::for_project(project_root); + purls + .iter() + .filter_map(|purl| { + let (g, a, v) = parse_maven_purl(purl)?; + match selection.standing(&g, &a, &v) { + Standing::NotSelected(others) => Some(( + purl.clone(), + ( + super::jvm::sbt_gate::MAVEN_NOT_SELECTED, + not_selected_detail(&g, &a, &v, &others), + ), + )), + _ => None, + } + }) + .collect() +} + /// The root's ledger still holds a pre-v5 single-pom entry (a /// `maven_pom_repository` record). Its revert restores a whole-file pom /// snapshot, which planner edits on the same pom would make unsafe, and @@ -595,7 +628,7 @@ pub async fn jvm_gate_preflight( return Err(("vendor_jvm_shape_unsupported", legacy_root_detail())); } let shape = detect_shape(project_root); - super::jvm::sbt_gate::for_shape(shape, project_root, &g, &a, &v) + super::jvm::sbt_gate::for_shape(shape, project_root, &g, &a, &v, None) .map_err(|stop| stop.code_and_detail(purl))?; // Checked here too, so a hosted->vendored takeover keeps its pin // instead of restoring upstream and then refusing (#1061). @@ -701,6 +734,22 @@ async fn jvm_committed_patch( .then_some((committed, extras)) } +/// The Maven-layout repository `installed_dir` is a version directory of +/// (`///`), when it is one: the local +/// repository the installed copy of `purl` was found in, which holds the +/// poms of the build that resolved it. +fn maven2_root(installed_dir: &Path, purl: &str) -> Option { + let (g, a, v) = parse_maven_purl(purl)?; + let mut dir = installed_dir; + for part in [v.as_ref(), a.as_ref()].into_iter().chain(g.rsplit('.')) { + if dir.file_name()?.to_str()? != part { + return None; + } + dir = dir.parent()?; + } + dir.is_dir().then(|| dir.to_path_buf()) +} + /// What [`vendor_maven_jvm`] establishes before anything else: the /// coordinates, the ledger, and the sbt / scala-cli resolution gate's pass. struct JvmPrelude { @@ -720,6 +769,7 @@ async fn jvm_prelude( purl: &str, project_root: &Path, record: &PatchRecord, + maven_repo: Option<&Path>, ) -> Result { let Some((group_id, artifact_id, version)) = parse_maven_purl(purl) else { return Err(refused( @@ -748,9 +798,15 @@ async fn jvm_prelude( .await .map_err(|e| refused("vendor_state_unreadable", e.to_string()))?; // sbt / scala-cli pins are gated on the build's own resolution first. - let gate_pass = - super::jvm::sbt_gate::for_shape(shape, project_root, &group_id, &artifact_id, &version) - .map_err(|stop| stop.into_outcome(purl))?; + let gate_pass = super::jvm::sbt_gate::for_shape( + shape, + project_root, + &group_id, + &artifact_id, + &version, + maven_repo, + ) + .map_err(|stop| stop.into_outcome(purl))?; // The tree must survive the commit the vendored workflow ends with. if let Some((code, detail)) = ignored_tree_root(shape, project_root).await { return Err(refused(code, detail)); @@ -788,7 +844,15 @@ async fn vendor_maven_jvm( version, state, gate_pass, - } = match jvm_prelude(shape, purl, project_root, record).await { + } = match jvm_prelude( + shape, + purl, + project_root, + record, + maven2_root(installed_dir, purl).as_deref(), + ) + .await + { Ok(prelude) => prelude, Err(outcome) => return outcome, }; @@ -810,11 +874,14 @@ async fn vendor_maven_jvm( extra_artifacts: &[], patched_members: &[], }; - let plan = super::jvm::plan( + let plan = super::jvm::plan_with_selection( shape, &|rel| reader.read(rel), &|dir| reader.list(dir), &patch, + true, + None, + gate_pass.maven.as_ref(), ); if let Some(rel) = reader.escaped() { return refused( @@ -833,7 +900,14 @@ async fn vendor_maven_jvm( if let Err(e) = super::jvm::maven_reactor::refuse_unwired(&read, &list, &patch.coords(), &plan) { - return refused(e.code, e.detail); + return super::jvm::sbt_gate::maven_undetermined( + gate_pass.maven.as_ref(), + &plan, + &group_id, + &artifact_id, + &version, + ) + .unwrap_or_else(|| refused(e.code, e.detail)); } } _ => {} @@ -847,6 +921,7 @@ async fn vendor_maven_jvm( let local = LocalSources::new(project_root, installed_dir, &group_id); let gav = (group_id.clone(), artifact_id.clone(), version.clone()); + let selection = gate_pass.maven; let mut warnings: Vec = gate_pass.warnings; let committed = jvm_committed_patch(shape, purl, project_root, record).await; let was_committed = committed.is_some(); @@ -1047,13 +1122,14 @@ async fn vendor_maven_jvm( ), Shape::MavenReactor | Shape::Mixed => { let external = external_maven_poms(&read, &list, &patch, &local, service).await; - super::jvm::plan_with_external( + super::jvm::plan_with_selection( shape, &read, &list, &patch, config_enabled, Some(&external), + selection.as_ref(), ) } _ => super::jvm::plan_with_config(shape, &read, &list, &patch, config_enabled), @@ -1072,7 +1148,16 @@ async fn vendor_maven_jvm( if let Err(refusal) = super::jvm::maven_reactor::refuse_unwired(&read, &list, &patch.coords(), &plan) { - return refused(refusal.code, refusal.detail); + // Nothing names the base version to rewrite, and what the build + // selects cannot be told: nothing is pinned on a guess. + return super::jvm::sbt_gate::maven_undetermined( + selection.as_ref(), + &plan, + &group_id, + &artifact_id, + &version, + ) + .unwrap_or_else(|| refused(refusal.code, refusal.detail)); } } if gradle @@ -2205,6 +2290,52 @@ mod tests { Some(out) } + /// A build that declares another version of the artifact itself does + /// not select the patch's base version, whatever its local repository + /// holds: the patch is a skip decided before any download. A build + /// that declares the base version is none. + #[tokio::test] + #[serial_test::serial] + async fn a_version_the_build_does_not_select_is_skipped_before_any_download() { + let declaring = |version: &str| { + format!( + "\n 4.0.0\n com.example\n \ + app\n 1.0.0\n \n \ + \n org.apache.commons\n \ + commons-text\n {version}\n \ + \n \n\n" + ) + }; + let (dir, blobs, installed, record) = fixture(Some(&declaring("1.11.0")), true, true).await; + let root = dir.path(); + let refusals = maven_not_selected_refusals(root, &[PURL.to_string()]); + let [(purl, (code, detail))] = refusals.as_slice() else { + panic!("{refusals:?}"); + }; + assert_eq!( + (purl.as_str(), *code), + (PURL, "vendor_maven_version_not_selected") + ); + assert!( + detail.contains("Maven selects org.apache.commons:commons-text 1.11.0") + && detail.contains("not 1.10.0"), + "{detail}" + ); + assert!(crate::vendor::refusals::refusal_is_benign(code)); + // The backend stops at the same gate, and writes nothing. + let (code, _) = unwrap_refused(run_vendor(root, &blobs, &installed, &record, false).await); + assert_eq!(code, "vendor_maven_version_not_selected"); + assert!(service_preflight(PURL, root, &record).await.is_none()); + assert!(!root.join(".socket").exists()); + assert_eq!( + std::fs::read_to_string(root.join(PROJECT_POM)).unwrap(), + declaring("1.11.0") + ); + + std::fs::write(root.join(PROJECT_POM), declaring("1.10.0")).unwrap(); + assert!(maven_not_selected_refusals(root, &[PURL.to_string()]).is_empty()); + } + #[tokio::test] #[serial_test::serial] async fn missing_reactor_module_is_refused_without_writes() { @@ -2236,6 +2367,13 @@ mod tests { \x20 app\n\ \x20 1.0.0\n\ \x20 \n\ + \x20 \n\ + \x20 \n\ + \x20 org.apache.commons\n\ + \x20 commons-text\n\ + \x20 1.10.0\n\ + \x20 \n\ + \x20 \n\ \n"; let (dir, blobs, installed, record) = fixture(Some(commented), true, true).await; let root = dir.path(); @@ -3954,6 +4092,19 @@ mod tests { ", ) .unwrap(); + // The pom of what brings commons-text in: the pin is written only + // because Maven selects 1.10.0 through it. + let uses = root.join("m2/com/corp/uses-commons-text/1"); + std::fs::create_dir_all(&uses).unwrap(); + std::fs::write( + uses.join("uses-commons-text-1.pom"), + "4.0.0com.corp\ + uses-commons-text1\ + org.apache.commons\ + commons-text1.10.0\ + ", + ) + .unwrap(); let (result, entry, warnings) = unwrap_done(run_jvm(root, &blobs, &installed, &record, None).await); assert!(result.success, "{result:?}"); @@ -4228,7 +4379,9 @@ mod tests { module.join("pom.xml"), "4.0.0com.example\ parent1.0\ - app\n", + app\ + org.apache.commonscommons-text\ + 1.10.0\n", ) .unwrap(); let before = crate::vendor::test_support::tree_snapshot(root); diff --git a/crates/socket-patch-core/src/vendor/refusals.rs b/crates/socket-patch-core/src/vendor/refusals.rs index bec256a6c..d807ad297 100644 --- a/crates/socket-patch-core/src/vendor/refusals.rs +++ b/crates/socket-patch-core/src/vendor/refusals.rs @@ -20,7 +20,9 @@ //! ones the backend raises on the lock and manifest text alone; //! 5. a gem version the project's `Gemfile.lock` doesn't //! resolve (`vendor_gem_version_not_locked`, which the callers report -//! as a skip). +//! as a skip); +//! 6. a Maven version no module of the build selects +//! (`vendor_maven_version_not_selected`, a skip too). //! //! Each check lives in its backend's module; this one only dispatches and //! scopes them. @@ -165,9 +167,36 @@ pub async fn vendor_refusals( for (purl, (code, detail)) in gem_refusals(project_root, candidates).await { refuse(&mut out, &purl, code, &detail); } + for (purl, (code, detail)) in maven_refusals(project_root, candidates).await { + refuse(&mut out, &purl, code, &detail); + } out } +/// The Maven candidates whose base version no module of the build selects +/// ([`super::maven_repo::maven_not_selected_refusals`]): the backend skips +/// them before it asks the patch service for anything. +async fn maven_refusals( + project_root: &Path, + candidates: &[(&str, &str)], +) -> Vec<(String, (&'static str, String))> { + let maven: Vec = candidates + .iter() + .map(|(purl, _)| purl.to_string()) + .filter(|purl| Ecosystem::from_purl(purl) == Some(Ecosystem::Maven)) + .collect(); + if maven.is_empty() { + return Vec::new(); + } + let root = project_root.to_path_buf(); + // The walk reads a pom per artifact of the build: off the runtime. + tokio::task::spawn_blocking(move || { + super::maven_repo::maven_not_selected_refusals(&root, &maven) + }) + .await + .unwrap_or_default() +} + /// The gem candidates whose version `Gemfile.lock` doesn't resolve /// ([`gem::gem_version_not_locked_refusals`]), installed or not: the /// backend refuses either before it asks the patch service for anything. diff --git a/docs/design/maven-vendoring.md b/docs/design/maven-vendoring.md index b20c8b391..40ed9027e 100644 --- a/docs/design/maven-vendoring.md +++ b/docs/design/maven-vendoring.md @@ -142,6 +142,24 @@ project once and vendor again). A re-run after a BOM bump drops the pin the same way. `vendor --check` reads that metadata from the local repository only and accepts either decision when some of it is missing. +A pin makes every occurrence of the artifact one version, in the root and in +every module that inherits it, so a local root is pinned only when Maven +selects the patch's base version in each of those modules already (or the +module does not resolve the artifact). The selection is read from the +reactor's poms and the poms the Maven local repository holds: nearest +declaration first, the first declared on a tie, the module's own management +over every transitive version, ``, `optional`, scopes and version +ranges as Maven 3's resolver applies them. A module that resolves another +version leaves its root unpinned (`version_not_selected`); when no module of +the build selects the base version the patch is skipped before anything is +downloaded (`vendor_maven_version_not_selected`, exit 0, naming the version +Maven selects). When the selection cannot be read (a pom the local repository +lacks, a profile that may change the graph, a Maven 4 build), no root is +pinned and an existing pin is left alone (`selection_undetermined`); a +declaration that names the base version is rewritten either way, since that +replaces a version where it stands. `vendor --check` accepts the pins either +answer writes. + Maven 3.9.2+ can read the repository tail without copying jars into `~/.m2` and without routing through mirrors. Older Maven versions use the fallback file repository, which copies the suffixed artifact into the local cache. A diff --git a/docs/ecosystems.md b/docs/ecosystems.md index a2832425c..532db0067 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -886,6 +886,29 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: the classifier-less declarations. A `sources` / `javadoc` variant at the patched release only warns; any other variant there (tests, a native build) would keep unpatched code on a classpath, so the dep is not redirected. +* **A pin follows the version Maven selects (hosted and vendored Maven).** A + `` pin makes every occurrence of an artifact one version, so it + is written only where Maven selects the patch's base version already. The scan reads + what Maven selects from the project's poms and the poms the Maven local repository + holds, module by module, without running Maven: the nearest declaration wins, the + first declared on a tie; the project's own management overrides transitive versions; + an `` removes what is below it; a range takes the highest version the + cached `maven-metadata-*.xml` lists. When the build selects another version (a newer + or older one nearer the root, the project's own declaration, an excluded path, a + range), or does not resolve the artifact at all, the patch for that base version has + nothing to patch: nothing is written, the run exits 0, and one line names the version + Maven selects instead (`redirect_maven_version_not_selected`, vendored + `vendor_maven_version_not_selected`). A patch for the version that is selected is + still looked up and applied. When the selection cannot be read (most often because + the project was never resolved, so the local repository lacks its poms), a + declaration that already names the base version is still rewritten where it stands, + and no new pin is written (`redirect_maven_selection_undetermined`, vendored + `vendor_maven_selection_undetermined`): run `mvn -q dependency:resolve` once and scan + again. Agent mode patches a cached jar in place under its own coordinates, which + cannot change what a build resolves; a version Maven only read the pom of has no jar + to patch and is left out of an agent scan. Maven 4 builds, profiles that declare + dependencies or management, relocations and dependency cycles are not modelled: the + artifacts they touch count as not readable. * **Multi-module reactors are vendored-only (hosted Maven).** Hosted mode reads only the root `pom.xml`, and a module's own literal `` always beats a root `` pin, so a root pin would leave that module on the unpatched From abfabe019920624c3b806ad266cd921d79bc85fe Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 15:56:38 -0500 Subject: [PATCH 02/18] Restore the line breaks of two vendored Maven warnings The version_not_selected and selection_undetermined warnings lost the line continuation in their format strings and carried a run of spaces in the middle of the sentence. The planner test now compares the whole warning. Co-Authored-By: Claude Fable 5.2 --- .../src/vendor/jvm/maven_reactor.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs index 12e5efc34..cbc1a992a 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs @@ -337,7 +337,8 @@ pub fn plan_with_selection( warnings.push(degraded( "version_not_selected", format!( - "{rel} resolves {g}:{a} at {version}, not {v}; {root} is not pinned, since a pin there would change the version {rel} resolves" + "{rel} resolves {g}:{a} at {version}, not {v}; {root} is not pinned, \ + since a pin there would change the version {rel} resolves" ), )); unpinned.insert(root); @@ -345,7 +346,8 @@ pub fn plan_with_selection( warnings.push(degraded( "selection_undetermined", format!( - "which version of {g}:{a} {rel} resolves cannot be told ({why}); the pin of {root} is left as it is" + "which version of {g}:{a} {rel} resolves cannot be told ({why}); the \ + pin of {root} is left as it is" ), )); held.insert(root); @@ -5132,12 +5134,11 @@ mod tests { .iter() .find(|w| w.detail.starts_with("reason: version_not_selected: ")) .unwrap(); - assert!( - warning - .detail - .contains("b/pom.xml resolves org.apache.commons:commons-text at 1.11.0"), - "{}", - warning.detail + assert_eq!( + warning.detail, + "reason: version_not_selected: b/pom.xml resolves \ + org.apache.commons:commons-text at 1.11.0, not 1.10.0; pom.xml is not pinned, \ + since a pin there would change the version b/pom.xml resolves" ); let refusal = left_unwired(&files, &plan).expect("nothing wired"); assert_eq!(refusal_reason(&refusal), "nothing_wired"); From 6c1467a752151d68cd2e3522298789d925836102 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 16:15:30 -0500 Subject: [PATCH 03/18] Read a dependency a pom declares twice as Maven does Maven builds a pom that declares one dependency twice from its last declaration, in the place of the first (and warns). The selection model kept the first, which could call a version selected that Maven does not select. Co-Authored-By: Claude Fable 5.2 --- .../src/crawlers/maven_selection.rs | 20 ++++++++++--- .../src/crawlers/maven_selection/tests.rs | 29 +++++++++++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/crates/socket-patch-core/src/crawlers/maven_selection.rs b/crates/socket-patch-core/src/crawlers/maven_selection.rs index 30f2a99f0..db4b27303 100644 --- a/crates/socket-patch-core/src/crawlers/maven_selection.rs +++ b/crates/socket-patch-core/src/crawlers/maven_selection.rs @@ -806,6 +806,10 @@ impl Selector<'_> { describe(node) )); } + // Where this pom's own declarations stand: Maven reads a pom + // that declares one dependency twice as its last declaration, + // in the place of the first. + let mut own: HashMap = HashMap::new(); for decl in node.model.own_deps() { let key = match self.key_of(decl, chain) { Ok(key) => key, @@ -819,7 +823,7 @@ impl Selector<'_> { continue; } }; - if !seen.insert(key.clone()) { + if seen.contains(&key) { continue; } let managed = management.entries.get(&key); @@ -846,14 +850,22 @@ impl Selector<'_> { if exclusions.is_empty() { exclusions = managed.map(|m| m.exclusions.clone()).unwrap_or_default(); } - out.deps.push(Dep { - key, + let dep = Dep { + key: key.clone(), version, scope, optional: decl.optional, exclusions, - }); + }; + match own.get(&key) { + Some(&at) => out.deps[at] = dep, + None => { + own.insert(key, out.deps.len()); + out.deps.push(dep); + } + } } + seen.extend(own.into_keys()); } let out = Rc::new(out); self.deps.insert(path, Rc::clone(&out)); diff --git a/crates/socket-patch-core/src/crawlers/maven_selection/tests.rs b/crates/socket-patch-core/src/crawlers/maven_selection/tests.rs index 7eb47f223..d1060b3b8 100644 --- a/crates/socket-patch-core/src/crawlers/maven_selection/tests.rs +++ b/crates/socket-patch-core/src/crawlers/maven_selection/tests.rs @@ -757,3 +757,32 @@ fn a_module_that_cannot_be_read_leaves_the_build_undetermined() { other => panic!("{other:?}"), } } + +/// A pom that declares one dependency twice is read as its last +/// declaration (Maven warns and builds on); a parent's declaration never +/// replaces the module's own. +#[test] +fn a_dependency_declared_twice_reads_as_its_last_declaration() { + let f = Fixture::new(); + f.app(&deps(&[x(A, "2.9.10"), x("lib-a", "1.0"), x(A, "2.7.9.2")])) + .cache("lib-a", "1.0", &[]) + .cache(A, "2.9.10", &[]) + .cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + assert_eq!(f.verdict("2.9.10"), other("2.7.9.2")); + + let f = Fixture::new(); + write( + &f.cwd, + "pom.xml", + &format!( + "4.0.0{G}\ + corp-parent3\ + app{}", + deps(&[x(A, "2.7.9.2")]) + ), + ); + cache(&f.repo, "corp-parent", "3", &deps(&[x(A, "2.9.10")])); + f.cache(A, "2.7.9.2", &[]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); +} From d5eb740df44387a90ea5d16e8a175f299bcabf5b Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 16:08:09 -0500 Subject: [PATCH 04/18] Pin a vendored Maven patch in the modules that select its version A vendored pin was only ever written in a local root pom, which every module of the reactor inherits. Where the modules select different versions of one artifact, a root pin moved the ones that select another version (5.1.0), or no pin was written at all and a module that selects the base version only through other artifacts stayed unpatched (the previous commit). The pin now goes in the highest pom whose modules all select the patch's base version or do not resolve the artifact: the local root when every module that inherits it agrees, else the poms below it that do, down to one module's own pom.xml. A module that resolves another version is never reached by a pin, and patches for two versions of one artifact are each pinned in the modules that select them. A pin an earlier run wrote in a pom that would move a module is taken out and written where it belongs. A pom that manages the artifact itself takes no pin, and a module whose selection is not certain gets no new pin and keeps the one it has. The fallback repository stays in each local root. A literal -socket. of another patch of the same artifact is no longer reported as conflicting_literal_version when a second patch is planned, and the version_not_selected degraded reason is gone: a sibling that selects another version is not a degradation. Reactors whose modules agree and single-module projects are planned byte for byte as before. Refs #595, #882. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 22 +- .../tests/e2e_vendor_maven_build.rs | 200 ++++++++++ .../tests/maven_mediation_common/mod.rs | 86 ++++- .../src/vendor/jvm/maven_reactor.rs | 359 +++++++++++++----- docs/design/maven-vendoring.md | 42 +- 5 files changed, 582 insertions(+), 127 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 172e105bd..9303b5b06 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2742,16 +2742,20 @@ range. | Mode | The build selects another version, or does not resolve the artifact | The selection is not certain | |---|---|---| | hosted | `redirect_maven_version_not_selected` (warning); nothing written | a declaration that names the base version is rewritten where it stands (that replaces the version in place and moves nothing); otherwise `redirect_maven_selection_undetermined` (warning), nothing written | -| vendored | `vendor_maven_version_not_selected` (`skipped`, exit 0), decided before any download; nothing written | a declaration that names the base version is rewritten; no root is pinned (`vendor_jvm_degraded`, `reason: selection_undetermined`), and a pin already there is kept. With no such declaration: `vendor_maven_selection_undetermined` (`skipped`, exit 0), nothing written | +| vendored | `vendor_maven_version_not_selected` (`skipped`, exit 0), decided before any download; nothing written | a declaration that names the base version is rewritten; a module whose selection is not certain gets no new pin (`vendor_jvm_degraded`, `reason: selection_undetermined`, naming it), and a pin already there is kept. With no such declaration and no module that is certain: `vendor_maven_selection_undetermined` (`skipped`, exit 0), nothing written | | agent | not applicable: the cached jar is patched in place under its own coordinates, which cannot change what a build resolves. A version whose directory in the local repository holds its pom and no jar (Maven read the pom while mediating and never downloaded the artifact) is not a package agent mode can patch: the scan leaves it out instead of failing it as a targeted patch that matched no installed package | | -In a vendored reactor a local root is pinned only when every module that -inherits it resolves the artifact at the base version or not at all. A module -that resolves another version leaves the root unpinned (`vendor_jvm_degraded`, -`reason: version_not_selected`, naming the module and its version); a patch -that then reaches no pom is refused as `nothing_wired` with that reason. -`vendor --check` accepts the pins a run with the local repository's current -answer writes and the pins a run with no such answer writes. +In a vendored reactor the pin goes in the highest pom whose modules all +resolve the artifact at the base version or not at all: a local root when +every module that inherits it agrees, else the poms below it that do, down to +a single module's own `pom.xml`. A module that resolves another version is +never reached by a pin and resolves what it resolved before; patches for two +versions of one artifact are each pinned in the modules that select them. A +pin an earlier run wrote in a pom that would move a module is taken out and +written where it belongs. A pom that manages the artifact itself takes no pin +(its own entry is rewritten when it names the base version). `vendor --check` +accepts the pins a run with the local repository's current answer writes and +the pins a run with no such answer writes (every local root). The not-selected line reads `Maven selects : in this build, not , so the patch for has nothing to patch here` (or `no module @@ -3102,7 +3106,7 @@ with `reason: : `: |---|---|---| | `vendor_jvm_shape_unsupported` | refusal, nothing written | `gradle_below_6_8`, `android_or_kmp` (also `available-at` module redirects), `gradle_exclusive_content_conflict` (a user rule claiming the module, in any script), `gradle_range_excludes_vendored` (no declared selector admits the vendored version), `gradle_classifier_computed` (a declaration of the module names its classifier through a variable, such as `${osdetector.classifier}`: the vendored repository would claim that jar without holding it), `gradle_verification_unparseable`, `gradle_index_unreadable`, `build_file_unreadable` (including a non-UTF-8 settings file), `build_file_outside_root`, `not_build_root` (run from a directory an ancestor settings file includes or may include, from a project with no settings file of its own below one, or below an ancestor settings file that is not UTF-8; `repair` refuses there too), `no_build_file` (no `pom.xml`, Gradle, sbt or scala-cli build at the root), `legacy_maven_root` (the root's ledger still holds a pre-v5 single-POM `maven_pom_repository` entry; the whole root is refused until `vendor --revert`, then vendor again) | | `vendor_jvm_upstream_unavailable` | refusal | `classifier_unavailable` (a declared classifier jar no cache or registry has), `module_unavailable` (the pom declares Gradle module metadata that cannot be sourced), `pom_unavailable`, `verification_metadata_unavailable`; for a suffixed Maven / sbt pom also `suffix_unavailable` (the upstream pom computes its own version), `parent_unavailable` (a first vendoring whose upstream parent poms are in no local cache and cannot be fetched, so the suffixed pom cannot be checked) and `inherited_version_unresolvable` (a parent pom names `${project.version}` where the suffixed pom cannot declare the base version instead: in a profile, a management key or a repository URL) | -| `vendor_jvm_degraded` | applied, VEX withheld | `gradle_unscanned_build_logic`, `unwired_build_logic` (a nonliteral included build), `settings_plugins_unwired`, `classifier_unpatched_copy` (a classifier jar carries an unpatched copy of a patched member), `verification_parent_chain_unhandled`, `gradle_lock_overrides_vendored` (a dependency lock of the build, buildscript and settings classpath locks included, pins the module at a version no vendored row serves), `gradle_settings_lock_unrouted` (a `settings-gradle.lockfile` locks the module but that build's settings script does not hold the in-block repository entry for it), `gradle_lock_unreadable` (a lock file, or a followed custom `lockFile`, is missing, unreadable, outside the checkout or not UTF-8), `gradle_custom_lock_file` (a `lockFile` location that cannot be followed statically: anything but a literal `file(…)` in a project's own build script), `gradle_wiring_uncommitted` (VEX liveness only, never reported by `vendor`: the committed settings files, index, derived `maven-metadata.xml`, script or verification file lack wiring a re-plan would write, such as a removed apply line or in-block entry; the git hygiene files do not count), `conflicting_managed_version` / `management_unresolved` (Maven reactor: an imported BOM or an out-of-checkout parent manages the artifact at another version, or its POM is unavailable; that local root is not pinned), `version_not_selected` / `selection_undetermined` (Maven reactor: a module under that local root resolves the artifact at another version than the patch's base, so the root is not pinned; or what a module resolves cannot be read, so the root's pin is left as it is. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven)) | +| `vendor_jvm_degraded` | applied, VEX withheld | `gradle_unscanned_build_logic`, `unwired_build_logic` (a nonliteral included build), `settings_plugins_unwired`, `classifier_unpatched_copy` (a classifier jar carries an unpatched copy of a patched member), `verification_parent_chain_unhandled`, `gradle_lock_overrides_vendored` (a dependency lock of the build, buildscript and settings classpath locks included, pins the module at a version no vendored row serves), `gradle_settings_lock_unrouted` (a `settings-gradle.lockfile` locks the module but that build's settings script does not hold the in-block repository entry for it), `gradle_lock_unreadable` (a lock file, or a followed custom `lockFile`, is missing, unreadable, outside the checkout or not UTF-8), `gradle_custom_lock_file` (a `lockFile` location that cannot be followed statically: anything but a literal `file(…)` in a project's own build script), `gradle_wiring_uncommitted` (VEX liveness only, never reported by `vendor`: the committed settings files, index, derived `maven-metadata.xml`, script or verification file lack wiring a re-plan would write, such as a removed apply line or in-block entry; the git hygiene files do not count), `conflicting_managed_version` / `management_unresolved` (Maven reactor: an imported BOM or an out-of-checkout parent manages the artifact at another version, or its POM is unavailable; that local root is not pinned), `selection_undetermined` (Maven reactor: what a module resolves cannot be read, so no pin is written for it and one already there is left as it is. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven)) | | `vendor_jvm_note` | applied, informational | `range_declared` (a range, prefix or rich selector lists versions from the derived `maven-metadata.xml`), `ide_sources_unavailable` | | `vendor_jvm_upstream_unverified` | warning | Upstream metadata was taken offline, or from a local cache while the registry published no checksum for it (a parent pom from a corporate repository), and not authenticated against registry checksums. | | `vendor_jvm_unattested` | warning (`vendor --check`) | A Maven reactor entry is intact and wired, but a declaration may still build the base release (an executable classifier or type copy, a version a property, profile or unpinned local root may move), so `vex` does not attest it. The entry stays `verified`; the detail names the purl and the declarations (`:`). | diff --git a/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs index f22f81f0f..5efaa9a81 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs @@ -54,6 +54,7 @@ mod prebuilt_common; #[path = "vex_e2e_common/mod.rs"] mod vex_e2e_common; +use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use maven_build_common::*; @@ -683,6 +684,205 @@ mod mediation { std::fs::write(proj.join(".socket/blobs").join(git_sha256(&after)), after).unwrap(); } + /// A second patch, for the newer victim. + const NEWER_UUID: &str = "8192a3b4-c5d6-4e7f-9081-92a3b4c5d6e7"; + + /// The manifest record `get` saves for a patch of the victim at + /// `version`, with its after-hash blob. + fn stage_all(proj: &Path, patches: &[(&str, &str)]) { + let mut records = serde_json::Map::new(); + std::fs::create_dir_all(proj.join(".socket/blobs")).unwrap(); + for (version, uuid) in patches { + let (before, after) = ( + fixture::pristine_member(fixture::VICTIM, version), + fixture::patched_member_of(version), + ); + records.insert( + format!("pkg:maven/{}/{}@{version}", fixture::GROUP, fixture::VICTIM), + serde_json::json!({ + "uuid": uuid, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { fixture::MEMBER: { + "beforeHash": git_sha256(&before), + "afterHash": git_sha256(&after), + } }, + "vulnerabilities": { "GHSA-mediation-maven-vendored": { + "cves": ["CVE-2026-7204"], "summary": "s", "severity": "high", + "description": "d" + } }, + "description": "maven mediation capstone", + "license": "MIT", + "tier": "free", + }), + ); + std::fs::write(proj.join(".socket/blobs").join(git_sha256(&after)), after).unwrap(); + } + std::fs::write( + proj.join(".socket/manifest.json"), + serde_json::to_string_pretty(&serde_json::json!({ "patches": records })).unwrap(), + ) + .unwrap(); + } + + /// The table's V3: in a reactor each module keeps the version it + /// selects. A patch of the base version is pinned in the modules that + /// select it (one through other artifacts, one by its own + /// declaration) and never in the parent they share with a module that + /// resolves a newer version, which Maven resolves exactly as before. A + /// patch of that newer version is then pinned in its module beside the + /// first, and the revert restores every pom. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_vendored_reactor_pins_each_module_at_the_version_it_selects() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().canonicalize().unwrap(); + let m2 = root.join("m2"); + let settings = root.join("settings.xml"); + write_settings(&settings, &[]); + let server = Server::start(); + fixture::publish(&server); + let proj = root.join("reactor"); + fixture::write_reactor(&proj, &server); + let poms = ["pom.xml", "a/pom.xml", "b/pom.xml", "c/pom.xml"]; + let read_poms = |proj: &Path| -> Vec> { + poms.iter() + .map(|rel| std::fs::read(proj.join(rel)).unwrap()) + .collect() + }; + let pristine = read_poms(&proj); + let vendor = |args: &[&str]| { + let mut all = vec!["vendor"]; + all.extend_from_slice(args); + all.extend_from_slice(&["--json", "--cwd", proj.to_str().unwrap()]); + socket(&proj, &m2, &all) + }; + let Some(before) = + fixture::resolve_reactor(SUITE, &mvn, &proj, &m2, &settings, "target/before") + else { + return; + }; + for (module, selects) in fixture::REACTOR_MODULES { + assert!( + before[module].contains_key(&fixture::victim_jar_name(selects)), + "{module} selects {selects}: {:?}", + before[module].keys() + ); + } + let base_sv = suffixed(); + let newer_sv = format!("{}-socket.{}", fixture::NEWER, &NEWER_UUID[..8]); + let resolved = |out_rel: &str| { + fixture::resolve_reactor(SUITE, &mvn, &proj, &m2, &settings, out_rel) + .expect("the local repository is warm") + }; + // What each module must resolve once `patched` versions are + // vendored: the same artifacts, the patched ones in their patched + // build, everything else byte for byte. + let assert_follows = |after: &BTreeMap>>, + patched: &[(&str, &str)]| { + for (module, selects) in fixture::REACTOR_MODULES { + let (was, now) = (&before[module], &after[module]); + assert_eq!( + fixture::unsuffixed(now.keys()), + was.keys().cloned().collect(), + "{module} resolves the artifacts it resolved before" + ); + let pristine_name = fixture::victim_jar_name(selects); + match patched.iter().find(|(version, _)| *version == selects) { + Some((version, sv)) => { + let jar = now.get(&fixture::victim_jar_name(sv)).unwrap_or_else(|| { + panic!("{module} resolves the patched {version}: {:?}", now.keys()) + }); + assert_eq!( + jar_member(jar, fixture::MEMBER), + Some(fixture::patched_member_of(version)), + "{module}: the patched jar" + ); + } + None => assert_eq!( + now.get(&pristine_name), + was.get(&pristine_name), + "{module} keeps the pristine {selects}" + ), + } + for (name, bytes) in was { + if *name != pristine_name { + assert_eq!(now.get(name), Some(bytes), "{module}: {name} is untouched"); + } + } + } + }; + + // The patch of the base version: pinned in `a` and `c`, never in + // the parent, and `b` is left exactly as it was. + stage_all(&proj, &[(fixture::BASE, UUID)]); + let (code, env, stderr) = vendor(&["--offline"]); + assert_eq!(code, Some(0), "vendor: {env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + let after = read_poms(&proj); + let text = |bytes: &[u8]| String::from_utf8_lossy(bytes).into_owned(); + assert!( + !text(&after[0]).contains("-socket."), + "the parent takes no pin:\n{}", + text(&after[0]) + ); + assert!( + text(&after[1]).contains(&format!("{base_sv}")), + "{}", + text(&after[1]) + ); + assert_eq!(after[2], pristine[2], "b/pom.xml is untouched"); + assert!( + text(&after[3]).contains(&format!("{base_sv}")), + "{}", + text(&after[3]) + ); + assert_follows(&resolved("target/after-base"), &[(fixture::BASE, &base_sv)]); + + // The patch of the version `b` selects joins it. + stage_all( + &proj, + &[(fixture::BASE, UUID), (fixture::NEWER, NEWER_UUID)], + ); + let (code, env, stderr) = vendor(&["--offline"]); + assert_eq!(code, Some(0), "second vendor: {env}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + let both = read_poms(&proj); + assert!(!text(&both[0]).contains("-socket."), "{}", text(&both[0])); + assert_eq!(both[1], after[1], "a/pom.xml keeps its pin"); + assert!( + text(&both[2]).contains(&format!("{newer_sv}")), + "{}", + text(&both[2]) + ); + assert!(!text(&both[2]).contains(&base_sv)); + assert_eq!(both[3], after[3], "c/pom.xml keeps its pin"); + assert_follows( + &resolved("target/after-both"), + &[(fixture::BASE, &base_sv), (fixture::NEWER, &newer_sv)], + ); + + // In sync, checked, and reverted byte for byte. + let wired = fixture::snapshot(&proj); + let (code, env, stderr) = vendor(&["--offline"]); + assert_eq!(code, Some(0), "re-vendor: {env}\n{stderr}"); + assert_eq!( + fixture::snapshot(&proj), + wired, + "a third run is a no-op: {env}" + ); + let (code, env, stderr) = vendor(&["--check"]); + assert_eq!(code, Some(0), "vendor --check: {env}\n{stderr}"); + let (code, env, stderr) = vendor(&["--revert"]); + assert_eq!(code, Some(0), "revert: {env}\n{stderr}"); + assert_eq!(read_poms(&proj), pristine, "the revert restores every pom"); + assert!(!proj.join(".socket/vendor/maven2").exists(), "{env}"); + assert!(!proj.join(".mvn").exists(), "{env}"); + } + fn skip_of<'e>(env: &'e serde_json::Value) -> Option<&'e serde_json::Value> { env["events"] .as_array() diff --git a/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs index 097e67ef5..ba542775c 100644 --- a/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs +++ b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs @@ -165,7 +165,12 @@ pub fn pristine_member(artifact: &str, version: &str) -> Vec { /// What the patch makes of the base victim's [`MEMBER`]. pub fn patched_member() -> Vec { - let mut out = pristine_member(VICTIM, BASE); + patched_member_of(BASE) +} + +/// What a patch of the victim at `version` makes of its [`MEMBER`]. +pub fn patched_member_of(version: &str) -> Vec { + let mut out = pristine_member(VICTIM, version); out.extend_from_slice(format!("{MARKER}\n").as_bytes()); out } @@ -258,6 +263,85 @@ pub fn project_pom(shape: Shape, server: &Server) -> String { ) } +/// The modules of [`write_reactor`], and the victim version each selects. +pub const REACTOR_MODULES: [(&str, &str); 3] = [("a", BASE), ("b", NEWER), ("c", BASE)]; + +/// Write a reactor into `dir` (the table's V3): a parent pom that three +/// modules inherit, `a` reaching the base version two levels down, `b` a +/// newer version through another artifact, `c` declaring the base version +/// itself. +pub fn write_reactor(dir: &Path, server: &Server) { + let modules: String = REACTOR_MODULES + .iter() + .map(|(name, _)| format!(" {name}\n")) + .collect(); + std::fs::create_dir_all(dir).unwrap(); + std::fs::write( + dir.join("pom.xml"), + format!( + "\n\ + \n \ + 4.0.0\n com.example\n \ + parent\n 1.0.0\n \ + pom\n \n{modules} \n \ + \n \n fixture\n \ + {}{REPO_ROUTE}\n \n \n\n", + server.uri() + ), + ) + .unwrap(); + for (name, deps) in [ + ("a", dependency("lib-deep", "1.0", "")), + ("b", dependency("lib-new", "1.0", "")), + ("c", dependency(VICTIM, BASE, "")), + ] { + std::fs::create_dir_all(dir.join(name)).unwrap(); + std::fs::write( + dir.join(name).join("pom.xml"), + format!( + "\n\ + \n \ + 4.0.0\n \n \ + com.example\n parent\n \ + 1.0.0\n \n {name}\n \ + \n{deps} \n\n" + ), + ) + .unwrap(); + } +} + +/// The jars Maven resolves for each module of the reactor at `proj` +/// (see [`resolve`]), by module name. +pub fn resolve_reactor( + suite: &str, + mvn: &Mvn, + proj: &Path, + m2: &Path, + settings: &Path, + out_rel: &str, +) -> Option>>> { + for (module, _) in REACTOR_MODULES { + let _ = std::fs::remove_dir_all(proj.join(module).join(out_rel)); + } + let out = with_central_fallback(suite, "reactor resolution", settings, |s, extra| { + copy_dependencies(mvn, proj, m2, s, out_rel, extra) + }); + if !ok(&out) { + crate::maven_build_common::skip( + suite, + &format!("resolving {} failed:\n{}", proj.display(), dump(&out)), + ); + return None; + } + Some( + REACTOR_MODULES + .iter() + .map(|(module, _)| (module.to_string(), copied(&proj.join(module), out_rel))) + .collect(), + ) +} + /// Write the project of `shape` into `dir`. pub fn write_project(dir: &Path, shape: Shape, server: &Server) { std::fs::create_dir_all(dir).unwrap(); diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs index cbc1a992a..71a000f00 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs @@ -208,17 +208,21 @@ pub fn plan_with_external( plan_with_selection(read, list, patch, config_enabled, external, None) } -/// [`plan_with_external`] that pins a local root only where Maven selects -/// the patch's base version already. A `` pin makes -/// every occurrence of the artifact that version, in the root and in every -/// module that inherits it, so it is written only when each of those -/// modules resolves the artifact at the base version (or not at all) by -/// `selection`. A module that resolves another version leaves the root -/// unpinned (`version_not_selected`); one whose answer is not certain -/// leaves the root as it is, pin or no pin (`selection_undetermined`). A +/// [`plan_with_external`] that puts the pin where Maven selects the +/// patch's base version already. A `` pin makes +/// every occurrence of the artifact that version, in its pom and in every +/// module that inherits it, so it goes in the highest pom whose modules +/// all resolve the artifact at the base version (or not at all) by +/// `selection`: a local root when the whole reactor under it agrees, else +/// the poms below it that do, down to a single module's own. A module +/// that resolves another version is thus never reached by a pin, and +/// patches for two versions of one artifact are each pinned in the +/// modules that select them. A module whose answer is not certain gets no +/// new pin and keeps the one it has (`selection_undetermined`). A /// declaration that names the base version is rewritten either way: that /// replaces the version where it stands, and moves nothing. `None` plans -/// without the check (callers that only probe a shape). +/// without the check and pins every local root (callers that only probe a +/// shape). pub fn plan_with_selection( read: ReadFn<'_>, list: ListFn<'_>, @@ -308,56 +312,39 @@ pub fn plan_with_selection( } } - // Roots whose pin stays as it is: nothing says what their modules - // select. + // Where the pin goes, and the poms whose pin stays as it is because + // nothing says what their modules select. + let mut pins: BTreeSet = BTreeSet::new(); let mut held: BTreeSet = BTreeSet::new(); - if let Some(selection) = selection { - for root in reactor.wired_roots() { - if unpinned.contains(&root) || managed_roots.contains(&root) { - continue; - } - let (mut selected, mut other, mut undetermined) = (false, None, None); - for rel in reactor - .reactor - .iter() - .filter(|rel| reactor.local_root(rel) == root) - { - match selection.verdict(rel, g, a, v) { - Verdict::Selected => selected = true, - Verdict::Other(version) => { - other.get_or_insert((rel.clone(), version)); - } - Verdict::Absent => {} - Verdict::Undetermined(why) => { - undetermined.get_or_insert((rel.clone(), why)); - } - } + let mut undetermined: BTreeMap = BTreeMap::new(); + for root in reactor.wired_roots() { + let open = !unpinned.contains(&root) && !managed_roots.contains(&root); + match selection { + None if open => { + pins.insert(root); } - if let Some((rel, version)) = other { - warnings.push(degraded( - "version_not_selected", - format!( - "{rel} resolves {g}:{a} at {version}, not {v}; {root} is not pinned, \ - since a pin there would change the version {rel} resolves" - ), - )); - unpinned.insert(root); - } else if let Some((rel, why)) = undetermined { - warnings.push(degraded( - "selection_undetermined", - format!( - "which version of {g}:{a} {rel} resolves cannot be told ({why}); the \ - pin of {root} is left as it is" - ), - )); - held.insert(root); - } else if !selected { - // No module under this root resolves the artifact: nothing - // would read a pin there. - unpinned.insert(root); + None => {} + Some(selection) => { + let mut placing = Placing { + selection, + patch, + pins: &mut pins, + held: &mut held, + undetermined: &mut undetermined, + }; + reactor.place(&root, open, &mut placing, 0); } } } + for (module, why) in undetermined { + warnings.push(degraded( + "selection_undetermined", + format!( + "which version of {g}:{a} {module} resolves cannot be told ({why}); no pin \ + is written for it, and one already there is left as it is" + ), + )); + } let banning = reactor .scope @@ -373,27 +360,31 @@ pub fn plan_with_selection( )); } let mut records: Vec = Vec::new(); - for root in reactor.wired_roots() { - let doc = &reactor.poms[&root].doc; - let file_edits = edits.entry(root.clone()).or_default(); - let pinned = !unpinned.contains(&root) && !managed_roots.contains(&root); + for rel in &reactor.scope { + let doc = &reactor.poms[rel].doc; + let file_edits = edits.entry(rel.clone()).or_default(); + let pinned = pins.contains(rel); match pin_of(doc, patch) { - _ if held.contains(&root) => {} + _ if held.contains(rel) => {} Some(pin) if !pinned => file_edits.push(Edit::plain(pin.start, pin.end, "")), Some(pin) if pin.uuid == patch.uuid => {} Some(pin) => { - records.push(adopt(&root, POM_FRAGMENT_KIND, "pin_section")); + records.push(adopt(rel, POM_FRAGMENT_KIND, "pin_section")); file_edits.push(pin_update(doc, &pin, patch)); } None if pinned => { let (edit, section) = pin_edit(doc, patch, &sv); if !section { - records.push(adopt(&root, POM_FRAGMENT_KIND, "pin_section")); + records.push(adopt(rel, POM_FRAGMENT_KIND, "pin_section")); } file_edits.push(edit); } None => {} } + } + for root in reactor.wired_roots() { + let doc = &reactor.poms[&root].doc; + let file_edits = edits.entry(root.clone()).or_default(); if banning.is_none() { if has_fallback_repository(doc) { records.push(adopt(&root, POM_FRAGMENT_KIND, "repository")); @@ -652,12 +643,11 @@ pub fn references_checked( /// The degraded reasons that leave a declaration or a root alone; the /// repository and config notes (and a mixed root's Gradle warnings) say /// nothing about why a reactor is unwired. -const UNWIRING: [&str; 9] = [ +const UNWIRING: [&str; 8] = [ "property_unresolved", "conflicting_literal_version", "conflicting_managed_version", "management_unresolved", - "version_not_selected", "selection_undetermined", "range", "coordinates_overridden", @@ -1282,6 +1272,84 @@ pub fn external_poms_needed( need } +/// What [`Reactor::place`] decides for one patch. +struct Placing<'p> { + selection: &'p MavenSelection, + patch: &'p JvmPatch<'p>, + /// The poms that get the pin. + pins: &'p mut BTreeSet, + /// The poms whose pin stays as it is. + held: &'p mut BTreeSet, + /// The modules whose selection cannot be told, and why. + undetermined: &'p mut BTreeMap, +} + +/// Deepest chain of local parents a pin is placed down. +const MAX_PLACING_DEPTH: usize = 64; + +impl Reactor { + /// Place the patch's pin at or below `rel`: in `rel` itself when every + /// reactor module that inherits it (or is it) resolves the artifact at + /// the base version or not at all, and one of them does resolve it; + /// else in the poms below it for which that holds. A pom some module + /// of which cannot be told is held, and gets no new pin. `open` is + /// false for a pom that takes no pin of its own (a local root a + /// declaration ruled out, or one that manages the artifact itself). + fn place(&self, rel: &str, open: bool, placing: &mut Placing<'_>, depth: usize) { + let (g, a, v) = ( + placing.patch.group_id, + placing.patch.artifact_id, + placing.patch.version, + ); + let (mut selected, mut other, mut unknown) = (false, false, false); + for module in &self.reactor { + if !self.chain(module).any(|p| p == rel) { + continue; + } + match placing.selection.verdict(module, g, a, v) { + Verdict::Selected => selected = true, + Verdict::Other(_) => other = true, + Verdict::Absent => {} + Verdict::Undetermined(why) => { + unknown = true; + placing.undetermined.entry(module.clone()).or_insert(why); + } + } + } + if unknown { + placing.held.insert(rel.to_string()); + } + if !unknown && !other { + // The user's own management on the chain already decides the + // version here: a base one was rewritten in place. + if selected && open && !self.manages(rel, g, a) { + placing.pins.insert(rel.to_string()); + } + return; + } + if depth >= MAX_PLACING_DEPTH { + return; + } + for child in &self.scope { + if self.local_parent.get(child).map(String::as_str) == Some(rel) { + self.place(child, true, placing, depth + 1); + } + } + } + + /// Whether `rel` or a local parent of it manages `g:a`'s main jar in + /// its own top-level `` (a pin vendoring wrote + /// is not such an entry). + fn manages(&self, rel: &str, g: &str, a: &str) -> bool { + self.chain(rel).any(|p| { + let doc = &self.poms[p].doc; + self.keyed_declarations(p, g, a) + .iter() + .any(|(dep, _)| doc.is_top_level_managed(*dep) && doc.is_main_jar(*dep)) + }) + } +} + /// One pom outside the checkout, parsed. struct ExternalPom { gav: Gav, @@ -2440,13 +2508,19 @@ impl Reactor { format!("{at}: {ga} version {declared} is left as is, probably unpatched"), )); } else { - warnings.push(degraded( - "conflicting_literal_version", - format!( - "{at}: {ga} is declared at {declared}, not {}; {root} is not pinned", - patch.version - ), - )); + // Another patch's wiring of the same artifact (a module + // that selects another version, patched too) is no + // conflict to report: this patch is pinned where its own + // version is selected. + if crate::formats::maven::split_socket_version(&resolved).is_none() { + warnings.push(degraded( + "conflicting_literal_version", + format!( + "{at}: {ga} is declared at {declared}, not {}; {root} is not pinned", + patch.version + ), + )); + } unpinned.insert(root); } } @@ -5117,37 +5191,119 @@ mod tests { } } - /// The table's V3 at the root: a pin there would move the module that - /// resolves another version, so none is written. + /// The table's V3: a pin in the shared parent would move the module + /// that resolves another version, so it goes in the module that + /// selects the base version, and nowhere else. #[test] - fn a_root_is_not_pinned_when_a_module_selects_another_version() { + fn a_pin_goes_in_the_module_when_a_sibling_selects_another_version() { let files = two_modules(); let selection = selecting(Some(Ok("1.10.0")), Some(Ok("1.11.0"))); let plan = run_selecting(&files, &selection); let after = applied(&files, &plan); - for rel in ["pom.xml", "a/pom.xml", "b/pom.xml"] { - assert!(!text(&after, rel).contains(SV), "{rel}"); - } - assert!(reasons(&plan).contains(&"version_not_selected".to_string())); - let warning = plan - .warnings - .iter() - .find(|w| w.detail.starts_with("reason: version_not_selected: ")) - .unwrap(); - assert_eq!( - warning.detail, - "reason: version_not_selected: b/pom.xml resolves \ - org.apache.commons:commons-text at 1.11.0, not 1.10.0; pom.xml is not pinned, \ - since a pin there would change the version b/pom.xml resolves" - ); - let refusal = left_unwired(&files, &plan).expect("nothing wired"); - assert_eq!(refusal_reason(&refusal), "nothing_wired"); assert!( - refusal.detail.contains("version_not_selected"), + text(&after, "a/pom.xml").contains(&format!("{SV}")), "{}", - refusal.detail + text(&after, "a/pom.xml") + ); + assert!(text(&after, "a/pom.xml").contains(PIN_TAG)); + assert!(!text(&after, "pom.xml").contains(SV)); + assert_eq!(after["b/pom.xml"], files["b/pom.xml"]); + assert!(!reasons(&plan).contains(&"selection_undetermined".to_string())); + assert!(left_unwired(&files, &plan).is_none()); + assert!(run_selecting(&after, &selection).writes.is_empty()); + + // The revert takes the module's pin out again, byte for byte. + let read = |rel: &str| after.get(rel).cloned(); + let undo = unplan(&read, &lister(&after), &patch().coords(), &plan.records); + let a = undo.changes.iter().find(|(r, _)| r == "a/pom.xml").unwrap(); + assert_eq!(a.1.as_deref(), Some(files["a/pom.xml"].as_slice())); + } + + /// The pin goes in the highest pom whose modules all agree: a parent + /// two modules share, under a root that a third module rules out. + #[test] + fn a_pin_goes_in_the_highest_pom_whose_modules_all_select_the_base() { + let under = |parent: &str, name: &str, extra: &str| { + format!( + "\n 4.0.0\n \n \ + t\n {parent}\n \ + 1\n \n {name}\n{extra}\ + \n" + ) + }; + let files = fs(&[ + ( + "pom.xml", + &PARENT_OF_TWO.replace("a", "mid"), + ), + ( + "mid/pom.xml", + &under( + "root", + "mid", + " pom\n \n m1\n \ + m2\n \n", + ), + ), + ("mid/m1/pom.xml", &under("mid", "m1", "")), + ("mid/m2/pom.xml", &under("mid", "m2", "")), + ("b/pom.xml", &inheriting("b")), + ]); + let ga = |pom: &'static str, version: &'static str| (pom, GA.0, GA.1, Ok(version)); + let selection = MavenSelection::answering( + &[ + "pom.xml", + "mid/pom.xml", + "mid/m1/pom.xml", + "mid/m2/pom.xml", + "b/pom.xml", + ], + &[ga("mid/m1/pom.xml", "1.10.0"), ga("b/pom.xml", "1.11.0")], ); - assert!(!unwired_by_selection_alone(&plan)); + let plan = run_selecting(&files, &selection); + let after = applied(&files, &plan); + assert!(text(&after, "mid/pom.xml").contains(&format!("{SV}"))); + for rel in ["pom.xml", "mid/m1/pom.xml", "mid/m2/pom.xml", "b/pom.xml"] { + assert!(!text(&after, rel).contains(SV), "{rel}"); + } + assert!(run_selecting(&after, &selection).writes.is_empty()); + } + + /// Patches for two versions of one artifact are each pinned in the + /// module that selects them, and neither plan undoes the other. + #[test] + fn patches_for_two_versions_are_each_pinned_where_they_are_selected() { + const OTHER_UUID: &str = "2e4d2ae3-6f70-4b8c-9dae-1f203b4c5d6e"; + const OTHER_SV: &str = "1.11.0-socket.2e4d2ae3"; + let other = JvmPatch { + version: "1.11.0", + uuid: OTHER_UUID, + upstream_pom: b"\n\n \ + org.apache.commons\n commons-text\n \ + 1.11.0\n\n", + ..patch() + }; + let selection = selecting(Some(Ok("1.10.0")), Some(Ok("1.11.0"))); + let plan_of = |files: &Fs, patch: &JvmPatch<'_>| { + let read = |p: &str| files.get(p).cloned(); + plan_with_selection(&read, &lister(files), patch, true, None, Some(&selection)) + .expect("plan") + }; + let files = two_modules(); + let first = applied(&files, &plan_of(&files, &patch())); + let both = applied(&first, &plan_of(&first, &other)); + assert!(text(&both, "a/pom.xml").contains(&format!("{SV}"))); + assert!(!text(&both, "a/pom.xml").contains(OTHER_SV)); + assert!(text(&both, "b/pom.xml").contains(&format!("{OTHER_SV}"))); + assert!(!text(&both, "b/pom.xml").contains(SV)); + assert!(!text(&both, "pom.xml").contains("-socket.")); + for patch in [patch(), other] { + assert!( + plan_of(&both, &patch).writes.is_empty(), + "{}", + patch.version + ); + } } /// No module resolves the artifact: a pin would be read by nothing. @@ -5155,8 +5311,10 @@ mod tests { fn a_root_no_module_resolves_the_artifact_under_is_not_pinned() { let files = two_modules(); let plan = run_selecting(&files, &selecting(None, None)); - assert!(!text(&applied(&files, &plan), "pom.xml").contains(SV)); - assert!(!reasons(&plan).contains(&"version_not_selected".to_string())); + let after = applied(&files, &plan); + for rel in ["pom.xml", "a/pom.xml", "b/pom.xml"] { + assert!(!text(&after, rel).contains(SV), "{rel}"); + } } /// What Maven selects cannot be told: no pin is written on a guess, @@ -5185,19 +5343,22 @@ mod tests { } /// A pin written before the selection was read (or before the build - /// moved on) goes once a module is known to resolve another version. + /// moved on) leaves the pom of a module it moves, for the pom of the + /// module that selects the base version. #[test] - fn a_pin_that_moves_a_module_is_removed() { + fn a_pin_that_moves_a_module_goes_to_the_module_it_belongs_in() { let files = two_modules(); let (_, pinned) = vendor(&files); assert!(text(&pinned, "pom.xml").contains(SV)); - let plan = run_selecting(&pinned, &selecting(Some(Ok("1.10.0")), Some(Ok("1.11.0")))); - let after = applied(&pinned, &plan); + let selection = selecting(Some(Ok("1.10.0")), Some(Ok("1.11.0"))); + let after = applied(&pinned, &run_selecting(&pinned, &selection)); assert!( !text(&after, "pom.xml").contains(SV), "{}", text(&after, "pom.xml") ); + assert!(text(&after, "a/pom.xml").contains(&format!("{SV}"))); + assert_eq!(after["b/pom.xml"], files["b/pom.xml"]); } /// A declaration that names the base version is rewritten whatever diff --git a/docs/design/maven-vendoring.md b/docs/design/maven-vendoring.md index 40ed9027e..f00377f1e 100644 --- a/docs/design/maven-vendoring.md +++ b/docs/design/maven-vendoring.md @@ -72,7 +72,9 @@ The backend writes: jar, suffixed POM, SHA-1 sidecars, and an ownership marker. - `.socket/vendor/maven2/.gitattributes`: disables line-ending conversion of committed repository bytes. -- A shared file repository and dependency-management pins in each local root. +- A shared file repository in each local root, and dependency-management pins + where Maven selects the patched version (the local root, or the modules + that select it when their siblings do not; see below). - Rewrites of conflicting base-version literals and resolved local properties, including profiles and local parent POMs outside the module list. - Two lines in `.mvn/maven.config`: offline file protocol access and the local @@ -142,23 +144,27 @@ project once and vendor again). A re-run after a BOM bump drops the pin the same way. `vendor --check` reads that metadata from the local repository only and accepts either decision when some of it is missing. -A pin makes every occurrence of the artifact one version, in the root and in -every module that inherits it, so a local root is pinned only when Maven -selects the patch's base version in each of those modules already (or the -module does not resolve the artifact). The selection is read from the -reactor's poms and the poms the Maven local repository holds: nearest -declaration first, the first declared on a tie, the module's own management -over every transitive version, ``, `optional`, scopes and version -ranges as Maven 3's resolver applies them. A module that resolves another -version leaves its root unpinned (`version_not_selected`); when no module of -the build selects the base version the patch is skipped before anything is -downloaded (`vendor_maven_version_not_selected`, exit 0, naming the version -Maven selects). When the selection cannot be read (a pom the local repository -lacks, a profile that may change the graph, a Maven 4 build), no root is -pinned and an existing pin is left alone (`selection_undetermined`); a -declaration that names the base version is rewritten either way, since that -replaces a version where it stands. `vendor --check` accepts the pins either -answer writes. +A pin makes every occurrence of the artifact one version, in its pom and in +every module that inherits it, so it is written only where Maven selects the +patch's base version already. The selection is read from the reactor's poms +and the poms the Maven local repository holds: nearest declaration first, the +first declared on a tie, the module's own management over every transitive +version, ``, `optional`, scopes and version ranges as Maven 3's +resolver applies them. The pin goes in the highest pom whose modules all +select the base version or do not resolve the artifact: the local root when +the whole reactor under it agrees, else the poms below it that do, down to one +module's own `pom.xml`. A module that resolves another version is never +reached by a pin, and a patch for that other version is pinned in that module +beside the first. A pom that manages the artifact itself takes no pin. When no +module of the build selects the base version the patch is skipped before +anything is downloaded (`vendor_maven_version_not_selected`, exit 0, naming +the version Maven selects). When a module's selection cannot be read (a pom +the local repository lacks, a profile that may change the graph, a Maven 4 +build), it gets no new pin and an existing one is left alone +(`selection_undetermined`); a declaration that names the base version is +rewritten either way, since that replaces a version where it stands. +`vendor --check` accepts the pins either answer writes. The fallback +repository stays in each local root, whichever pom holds the pin. Maven 3.9.2+ can read the repository tail without copying jars into `~/.m2` and without routing through mirrors. Older Maven versions use the fallback file From 82d923985f4bd2d5a1ab0be8640424403387960f Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 17:01:37 -0500 Subject: [PATCH 05/18] Keep vendored Maven pins where they were committed, on every machine Review fixes for the Maven selection work. Determinism. Where the pins go is decided when a patch is first wired, and the committed poms are the record. A later plan over poms that already wire the patch keeps every pin and adds none, whatever the local repository of that machine can tell, so one checkout plans the same everywhere and a re-run is a no-op. `vendor --check` no longer judges where a pin belongs: it takes every pin, and every absence of one, as committed. Before, a project vendored where nothing could be told (the declaration rewritten, no pin) drifted in `--check` and was rewritten by a re-scan on a machine with a full local repository. - A held pom still moves an older patch's pin to the new suffix: the tree the old suffix names is replaced by the same run. - A plan left unwired because one module's answer holds the root back is the vendor_maven_selection_undetermined skip, whatever the other modules select. It used to be the nothing_wired refusal. - A pin for a version the build no longer selects is taken out of the poms when the patch is skipped as not selected, and the skip says so. It used to stay and keep forcing that version. - A range is resolved only on the version lists cached for the repositories the module's poms declare (and central and local). A list cached for any other repository id leaves it undetermined. - The undetermined line names the remedy that fits its cause: resolving the project only when something is missing from the local repository. - Property lookup goes through the shared lookup_property, so a bare ${version} reads a property of that name before the project's own. - One artifact check for Coursier and Maven directories; the agent scan filters pom-only versions through the crawler, off the async runtime. - The selection is read off the async runtime, kept between the stages and patches of one run while every file it read is unchanged, and not read at all for a hosted reactor root, which is refused whole. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 34 ++- .../src/commands/scan/hosted.rs | 27 +- .../socket-patch-cli/src/commands/scan/mod.rs | 10 +- .../tests/e2e_vendor_maven_build.rs | 189 +++++++++++++ .../tests/maven_mediation_common/mod.rs | 35 ++- .../src/crawlers/maven_crawler.rs | 63 +++-- .../src/crawlers/maven_scope.rs | 5 + .../src/crawlers/maven_selection.rs | 263 ++++++++++++++---- .../src/crawlers/maven_selection/tests.rs | 125 ++++++++- crates/socket-patch-core/src/hosted/engine.rs | 5 +- .../src/patch/redirect/mod.rs | 20 +- .../socket-patch-core/src/vendor/jvm/apply.rs | 32 +-- .../src/vendor/jvm/maven_reactor.rs | 219 ++++++++++++++- .../src/vendor/jvm/sbt_gate.rs | 33 +-- .../src/vendor/maven_repo.rs | 133 +++++++-- .../socket-patch-core/src/vendor/refusals.rs | 6 +- docs/design/maven-vendoring.md | 13 +- docs/ecosystems.md | 7 +- 18 files changed, 1040 insertions(+), 179 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 172e105bd..579a8f8c6 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1996,8 +1996,8 @@ command's integration tests check its output. | `vendor_unsupported_ecosystem` | `skipped` | vendor: no vendor backend for this purl's ecosystem (jsr). | | `already_vendored` | `skipped` | vendor: artifact + wiring already in sync for this patch uuid. | | `vendor_gem_version_not_locked` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (gem): no section of the project's `Gemfile.lock` resolves the gem at this version (typically a gem Ruby ships in the gem home, or another project's copy in a shared gem home, which the crawl of that gem home returns). Decided before any download: the patch is not fetched, the Gemfile and lock stay byte-identical, and nothing is written. Human: `[skip] (vendor_gem_version_not_locked): …` in the download phase of `scan` / `get` (both identifier paths) and in their dry run, `Skipping : …` in `vendor`. The vendored twin of `redirect_gem_version_not_locked`. | -| `vendor_maven_version_not_selected` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): no module of the build resolves the artifact at the patch's base version; the reason names the versions Maven selects instead (a nearer declaration, the project's own declaration or management, an ``, a version range), or says that no module resolves the artifact. Decided before any download: the patch is not fetched and no file is written. Human: `[skip] (vendor_maven_version_not_selected): …` in the download phase of `scan` / `get` and in their dry run, `Skipping : …` in `vendor`. The vendored twin of `redirect_maven_version_not_selected`. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). | -| `vendor_maven_selection_undetermined` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): what the build selects for the artifact cannot be read (the reason says why: typically a pom the local repository does not hold, because the project was never resolved) and no declaration names the patch's base version, so nothing is pinned on a guess and no file is written. The reason carries the remedy: resolve the project once (`mvn -q dependency:resolve`) and re-run, or declare the artifact at the base version. The vendored twin of `redirect_maven_selection_undetermined`. | +| `vendor_maven_version_not_selected` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): no module of the build resolves the artifact at the patch's base version; the reason names the versions Maven selects instead (a nearer declaration, the project's own declaration or management, an ``, a version range), or says that no module resolves the artifact. Decided before any download: the patch is not fetched and no file is written, except that a pin an earlier run wrote for that version is taken out of the poms (the reason says so), since it would keep forcing a version the build no longer selects. Human: `[skip] (vendor_maven_version_not_selected): …` in the download phase of `scan` / `get` and in their dry run, `Skipping : …` in `vendor`. The vendored twin of `redirect_maven_version_not_selected`. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). | +| `vendor_maven_selection_undetermined` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): what the build selects for the artifact cannot be read (the reason says why: typically a pom the local repository does not hold, because the project was never resolved) and no declaration names the patch's base version, so nothing is pinned on a guess and no file is written. The reason carries the remedy that fits its cause (resolve the project once and re-run when a pom is missing from the local repository; otherwise declare the artifact at the base version). The vendored twin of `redirect_maven_selection_undetermined`. | | `vendor_prebuilt_pending` / `vendor_prebuilt_unavailable` | `skipped` | vendor / scan / get `--mode vendored` (every ecosystem, #954, #1235): the package is already vendored at another patch uuid, and the patch service has no prebuilt artifact for the selected (superseding) uuid — still building (`pending_build`) / not served (`build_failed`, `not_found`, `withdrawn`, no usable artifact). Nothing is touched: the older patch's artifact, wiring and ledger entry stay in force, the detail names both uuids (`kept the vendored patch : prebuilt is still building for patch `, where `` is the backend's artifact kind: `artifact` for the npm family, `.gem`, `crate`, `module zip`, `dist zip`, `wheel`, `.jar`, `.nupkg`, …), and the run does not fail (exit 0), the way hosted mode keeps its pin and lists the upgrade in `redirect.skipped[]`. A re-run picks the new patch up once the service serves it. A package with no vendored patch to keep still fails (`failed`, error `prebuilt is still building` / `prebuilt unavailable: `; outside the npm family under `vendor_prebuilt_required`), as does a request/transport failure. | | `unsafe_coordinates` | `failed` | vendor: purl/uuid would escape `.socket/vendor/` (tampered manifest/state); refused before any write. | | `revert_failed` | `failed` | vendor --revert: a recorded entry could not be reverted. | @@ -2723,8 +2723,10 @@ module's own and inherited ``, then each artifact's `compile` / `runtime`, non-optional dependencies, less what an `` removes; a declared version, else the managed one (parent chain, then imported BOMs), the module's management overriding every transitive version; a version range as -the highest version in it that the cached `maven-metadata-*.xml` lists; and -mediation: the nearest declaration wins, the first declared on a tie, and what +the highest version in it that the cached `maven-metadata-.xml` files list +for the repositories the module's poms declare (and Maven's own `central` and +`local`; a list cached for any other repository id, such as another project's +or a settings mirror's, leaves the range undetermined); and mediation: the nearest declaration wins, the first declared on a tie, and what a losing version depends on leaves the graph. A `-socket.` version an earlier run wrote reads as its base version, and a pin vendoring wrote is not read as the project's management. @@ -2750,8 +2752,28 @@ inherits it resolves the artifact at the base version or not at all. A module that resolves another version leaves the root unpinned (`vendor_jvm_degraded`, `reason: version_not_selected`, naming the module and its version); a patch that then reaches no pom is refused as `nothing_wired` with that reason. -`vendor --check` accepts the pins a run with the local repository's current -answer writes and the pins a run with no such answer writes. + +Where the pins go is decided when a patch is first wired, and the committed +poms are the record of it. A later run over poms that already wire the patch (a +pin of its version, or a declaration at its `-socket.` version) keeps +every pin where it is and adds none, whatever the local repository of that +machine holds: the same checkout plans the same on every machine, and a re-run +is a no-op. `vendor --check` does not judge where a pin belongs at all; it +takes every pin, and every absence of one, as committed. Two things still +change a wired pom. A pin of a superseded patch of the same version moves to +the new suffix where it stands. And a pin that is certain to move a module to +another version than Maven selects for it is taken out: when no module selects +the pinned version any more (a dependency was added or upgraded since), the run +removes the pin from the poms, reports the `vendor_maven_version_not_selected` +skip saying so, and leaves the ledger entry and tree for `vendor --revert` or +`scan --mode vendored --prune`. + +The undetermined line names the remedy that fits its cause: resolving the +project (`mvn -q dependency:resolve`) when a pom or version list is missing +from the local repository; otherwise (a profile that changes the graph, Maven +4, a cycle, a relocation, a range a pin would freeze, an undefined property) +a declaration of the artifact at the base version in the module that should +take the patch. The not-selected line reads `Maven selects : in this build, not , so the patch for has nothing to patch here` (or `no module diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index d695b5a2e..3d90bf108 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -1529,19 +1529,22 @@ async fn run_redirect_selected_untracked( let cargo_outer = || CargoCrawler::crates_io_source_for(&common.cwd); // What Maven selects in each module, from the poms its local repository // holds: a pin is written only where that is the patch's base version. - // Read once: the rewrite may run several times. - let maven_selection_once = std::sync::OnceLock::new(); - let maven_selection = || { - Some( - maven_selection_once - .get_or_init(|| { - socket_patch_core::crawlers::maven_selection::MavenSelection::for_project( - &common.cwd, - ) - }) - .clone(), - ) + // Read once per run, off the runtime (the walk reads a pom per artifact + // of the build), and only for a pom the rewriter will edit. + let maven_selection_read = if candidates.iter().any(|c| c.dep.ecosystem == "maven") + && read.files.contains_key("pom.xml") + && !socket_patch_core::patch::redirect::maven_reactor_root(&read.files) + { + let cwd = common.cwd.clone(); + tokio::task::spawn_blocking(move || { + socket_patch_core::crawlers::maven_selection::MavenSelection::for_project(&cwd) + }) + .await + .ok() + } else { + None }; + let maven_selection = || maven_selection_read.clone(); // The scan runs in the install's environment: a pnpm setting there // (`pnpm_config_trust_lockfile`) overrides the project's files. let pnpm_env = |var: &str| std::env::var(var).ok(); diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index fd073246b..a024c6b8c 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2461,14 +2461,8 @@ async fn scan_project( // and it must not end the run as a targeted patch that matched no // installed package. if apply { - filtered_crawled.retain(|package| { - Ecosystem::from_purl(&package.purl) != Some(Ecosystem::Maven) - || !socket_patch_core::crawlers::maven_crawler::pom_only_version_dir( - &package.path, - &package.name, - &package.version, - ) - }); + filtered_crawled = + socket_patch_core::crawlers::MavenCrawler::with_an_artifact(filtered_crawled).await; } // Gradle discovery notes (m2 gating, the user home) ride the run-level diff --git a/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs index f22f81f0f..5e320104c 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs @@ -683,6 +683,195 @@ mod mediation { std::fs::write(proj.join(".socket/blobs").join(git_sha256(&after)), after).unwrap(); } + /// The committed wiring is the record of where a patch is pinned: it + /// checks clean and a re-run leaves it alone on any machine, whatever + /// that machine's local repository holds. A project whose parent pom + /// comes from a repository is vendored on a machine that never + /// resolved it (what Maven selects cannot be told there, so the + /// declaration is rewritten and no pin is written). On a machine that + /// did resolve it, `vendor --check` passes, a second `vendor` changes + /// no byte, and Maven builds the patched jar. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_vendored_wiring_checks_clean_and_stays_put_on_any_machine() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().canonicalize().unwrap(); + let (warm, cold) = (root.join("m2-warm"), root.join("m2-cold")); + let settings = root.join("settings.xml"); + write_settings(&settings, &[]); + let server = Server::start(); + fixture::publish(&server); + let proj = root.join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write(proj.join("pom.xml"), fixture::parented_pom(&server)).unwrap(); + let Some(before) = fixture::resolve(SUITE, &mvn, &proj, &warm, &settings, "target/before") + else { + return; + }; + assert!(before.contains_key(&fixture::victim_jar_name(fixture::BASE))); + // The other machine holds the installed victim and nothing else of + // this build: not the parent pom its selection hangs on. + let installed = fixture::victim_dir(&cold, fixture::BASE); + std::fs::create_dir_all(&installed).unwrap(); + for entry in std::fs::read_dir(fixture::victim_dir(&warm, fixture::BASE)).unwrap() { + let entry = entry.unwrap(); + std::fs::copy(entry.path(), installed.join(entry.file_name())).unwrap(); + } + let vendor = |m2: &Path, args: &[&str]| { + let mut all = vec!["vendor"]; + all.extend_from_slice(args); + all.extend_from_slice(&["--json", "--cwd", proj.to_str().unwrap()]); + socket(&proj, m2, &all) + }; + + stage(&proj); + let (code, env, stderr) = vendor(&cold, &["--offline"]); + assert_eq!(code, Some(0), "vendor on the cold machine: {env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + let sv = suffixed(); + let pom = std::fs::read_to_string(proj.join("pom.xml")).unwrap(); + assert!(pom.contains(&format!("{sv}")), "{pom}"); + assert!( + !pom.contains("`); a property a parent outside the checkout defines is read from what Maven selects for the modules that read the declaration; - the `` goes in each local root a wired pom inherits from, and the Trusted Checksums files stay at the project root. Hosted mode keeps no ledger, so each edit says what it replaced by its own text, and `unwire_hosted` reads it back. The planner unwires every pom it would change before returning and leaves a pom alone when that does not give the text it had, so no edit is written that could not be taken back byte for byte (a pin in an empty `` is the case found; reported as `redirect_maven_edit_not_reversible`). The engine reads every pom the planner reads by asking it until it asks for nothing new, and confirms a planned dep from the planner's own report: a pin in a module pom, a property or a recorded declaration is no substring of the root pom. The placement code is shared with vendored mode (`place_pins`, moved out of `plan_with_selection` unchanged), `Reactor::under` can leave modules out, and `rewrite_declarations` can be told what a version the checkout does not define reads. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/hosted.rs | 3 +- crates/socket-patch-core/src/hosted/engine.rs | 126 ++- .../src/patch/redirect/mod.rs | 944 ++++++++++++++++-- .../src/vendor/jvm/maven_reactor.rs | 269 +++-- .../src/vendor/jvm/maven_reactor/hosted.rs | 695 +++++++++++++ .../vendor/jvm/maven_reactor/hosted/tests.rs | 561 +++++++++++ 6 files changed, 2364 insertions(+), 234 deletions(-) create mode 100644 crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs create mode 100644 crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 3d90bf108..ed5a88bac 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -1530,10 +1530,9 @@ async fn run_redirect_selected_untracked( // What Maven selects in each module, from the poms its local repository // holds: a pin is written only where that is the patch's base version. // Read once per run, off the runtime (the walk reads a pom per artifact - // of the build), and only for a pom the rewriter will edit. + // of the build), for a single pom and for every module of a reactor. let maven_selection_read = if candidates.iter().any(|c| c.dep.ecosystem == "maven") && read.files.contains_key("pom.xml") - && !socket_patch_core::patch::redirect::maven_reactor_root(&read.files) { let cwd = common.cwd.clone(); tokio::task::spawn_blocking(move || { diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index c441b941a..6ff50fe24 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -750,6 +750,53 @@ async fn read_advisory( } } +/// How many rounds [`read_maven_reactor`] reads: a reactor nested deeper +/// than this is read as far as that, and its planner then refuses it for +/// the module it cannot find. +const MAX_REACTOR_READ_ROUNDS: usize = 64; + +/// Read every pom the Maven reactor planner reads for the root `pom.xml`: +/// the modules it lists (theirs in turn), and each local parent on a +/// module's chain. The planner is asked what it reads until it asks for +/// nothing new, so the files are exactly the ones it will plan over. A pom +/// is a rewrite target and read as one; a module's `.mvn` files, which the +/// planner only asks about, are advisory. +async fn read_maven_reactor( + view: &ProjectView<'_>, + unreadable: &BTreeSet, + out: &mut CandidateFiles, +) { + let mut asked: BTreeSet = BTreeSet::new(); + for _ in 0..MAX_REACTOR_READ_ROUNDS { + let wanted: std::cell::RefCell> = Default::default(); + { + let read = |rel: &str| match out.files.get(rel) { + Some(text) => Some(text.clone().into_bytes()), + None => { + if !asked.contains(rel) { + wanted.borrow_mut().insert(rel.to_string()); + } + None + } + }; + let list = |dir: &str| crate::patch::redirect::gradle::key_list(&out.files, dir); + crate::vendor::jvm::maven_reactor::readable_for_hosted(&read, &list); + } + let wanted = wanted.into_inner(); + if wanted.is_empty() { + break; + } + for rel in wanted { + if rel.ends_with(".xml") && !rel.contains(".mvn/") { + out.read(view, unreadable, &rel).await; + } else if let Some(text) = read_advisory(view, unreadable, &rel).await { + out.files.insert(rel.clone(), text); + } + asked.insert(rel); + } + } +} + /// An in-memory project's Go files as the hosted engine reads them /// ([`read_advisory`]: a link or an entry without content is unreadable, /// but still exists). @@ -1063,6 +1110,10 @@ pub async fn read_candidate_files( out.files.insert(rel, text.unwrap_or_default()); } } + // Every pom of the reactor (and a local parent outside the + // module list): the rewriter pins a patch in the module poms + // that select it, so each is a rewrite target. + read_maven_reactor(view, unreadable, &mut out).await; } } @@ -2711,11 +2762,9 @@ async fn rewrite_once( } else { CratesIoSource::Registry }; - // Asked only for a pom the rewriter will edit: it refuses a reactor - // root whole, whatever Maven selects there. + // Asked only when there is a pom to pin: a single one, or a reactor's. let maven_selection = (rewrite_overrides.iter().any(|o| o.ecosystem == "maven") - && files.contains_key("pom.xml") - && !crate::patch::redirect::maven_reactor_root(&files)) + && files.contains_key("pom.xml")) .then(|| (options.maven_selection)()) .flatten(); let (files, mut rewrite) = if options.blocking { @@ -3772,6 +3821,11 @@ fn confirm( if !gradle || !files.contains_key("pom.xml") { return ProbeStep::Decided(gradle); } + if rewrite.maven_reactor_uuids.contains(uuid) { + return ProbeStep::Decided( + rewrite.confirmed_maven_reactor_uuids.contains(uuid), + ); + } let needles = candidate_presence_needles(&c.dep); return ProbeStep::Decided( final_texts @@ -3780,6 +3834,12 @@ fn confirm( .any(|(_, text)| needles.iter().any(|n| text.contains(n.as_str()))), ); } + // A dep the Maven reactor planner decided: its pin may sit in a + // module pom, a property or a comment-recorded declaration, so + // the planner's own report confirms it. + if rewrite.maven_reactor_uuids.contains(uuid) { + return ProbeStep::Decided(rewrite.confirmed_maven_reactor_uuids.contains(uuid)); + } ProbeStep::Needles(candidate_presence_needles(&c.dep)) }) .collect(); @@ -6136,21 +6196,24 @@ snapshots: /// #1809: a Maven 4 root whose subprojects Maven discovers (model /// 4.1.0, `pom` packaging, no list) is a reactor once a direct /// subdirectory holds a `pom.xml`. The engine reads that pom beside - /// the root, on disk and in memory, so the pom rewriter refuses the - /// root instead of pinning only it while the module keeps its version. + /// the root, on disk and in memory, so the pom rewriter plans both: a + /// subproject that declares the version itself is not left behind. #[tokio::test] - async fn a_maven_4_implicit_reactor_root_is_refused() { + async fn a_maven_4_implicit_reactor_is_read_and_planned_whole() { let root = "\n 4.1.0\n x\n y\n 1\n pom\n \n \n com.socketfixture\n victim\n 1.10.0\n \n \n\n"; let child = "\n 4.1.0\n \n a\n\n"; - let refused = |read: &CandidateFiles, done: &Rewritten| { + let planned = |read: &CandidateFiles, done: &Rewritten| { assert!( read.files.contains_key("a/pom.xml"), "{:?}", read.files.keys() ); - assert!(!done.rewrite.files.contains_key("pom.xml")); - assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); - assert!(done + assert!( + done.rewrite.files["pom.xml"].contains("1.10.0-socket.4d5e6f70") + ); + assert!(done.rewrite.files["pom.xml"].contains("socket-patch-")); + assert_eq!(done.confirmed.len(), 1, "{:?}", done.rewrite.warnings); + assert!(!done .rewrite .warnings .iter() @@ -6161,7 +6224,21 @@ snapshots: p.insert_text("pom.xml", root); p.insert_text("a/pom.xml", child); let (read, done) = gradle_rewrite(&p).await; - refused(&read, &done); + planned(&read, &done); + assert!(!done.rewrite.files.contains_key("a/pom.xml")); + + // A subproject that declares the version itself is rewritten too. + let declaring = child.replace( + "", + "\n \n \n com.socketfixture\n victim\n 1.10.0\n \n ", + ); + let mut p = MemoryProject::new(); + p.insert_text("pom.xml", root); + p.insert_text("a/pom.xml", declaring.as_str()); + let (read, done) = gradle_rewrite(&p).await; + planned(&read, &done); + assert!(done.rewrite.files["a/pom.xml"].contains("1.10.0-socket.4d5e6f70")); + assert!(!done.rewrite.files["a/pom.xml"].contains("")); let tmp = tempfile::tempdir().unwrap(); std::fs::write(tmp.path().join("pom.xml"), root).unwrap(); @@ -6170,22 +6247,25 @@ snapshots: // A directory without a pom is no subproject. std::fs::create_dir(tmp.path().join("src")).unwrap(); let (read, done) = gradle_rewrite_in(&ProjectView::Disk(tmp.path())).await; - refused(&read, &done); + planned(&read, &done); assert!(!read.files.contains_key("src/pom.xml")); - // A suffixed version an earlier release pinned into the root, or one - // a module names, confirms nothing: the refused root pins nothing. + // A reactor one of whose poms cannot be read is refused whole, and + // a suffixed version an earlier run left in it then confirms + // nothing: the refused root pins nothing. let stale = root.replace("1.10.0", "1.10.0-socket.4d5e6f70"); - let named = child.replace( - "", - "\n 1.10.0-socket.4d5e6f70", - ); - for (r, c) in [(stale.as_str(), child), (root, named.as_str())] { + for r in [root, stale.as_str()] { let mut p = MemoryProject::new(); p.insert_text("pom.xml", r); - p.insert_text("a/pom.xml", c); - let (read, done) = gradle_rewrite(&p).await; - refused(&read, &done); + p.insert_text("a/pom.xml", ""); + let (_, done) = gradle_rewrite(&p).await; + assert!(done.rewrite.files.is_empty(), "{:?}", done.rewrite.files); + assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); + assert!(done + .rewrite + .warnings + .iter() + .any(|w| w.code == "redirect_maven_multimodule_unsupported")); } // Without a subproject the root is a single pom, pinned as before. diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index d5824db49..a082010ff 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -406,6 +406,22 @@ pub struct RewriteResult { serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") )] pub refused_gradle_uuids: std::collections::BTreeSet, + /// Maven patch uuids the reactor planner decided (a reactor root, or a + /// single pom's `${property}` version): their pins may sit in module + /// poms, a property or a comment-recorded declaration, so the pom + /// rewriter's own report confirms them, never a substring. + #[cfg_attr( + test, + serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") + )] + pub maven_reactor_uuids: std::collections::BTreeSet, + /// Those of [`Self::maven_reactor_uuids`] some pom wires once the + /// rewrite is written (by this run, or already). + #[cfg_attr( + test, + serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") + )] + pub confirmed_maven_reactor_uuids: std::collections::BTreeSet, /// Patch uuids pinned in `socket-patch.sbt` and verified against the /// build's resolution evidence (kept or added by this run). On a pure /// sbt root ([`sbt::owns_maven_root`]) maven confirmation keys off this @@ -852,6 +868,8 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { gradle_uuids, confirmed_gradle_uuids, refused_gradle_uuids, + maven_reactor_uuids, + confirmed_maven_reactor_uuids, confirmed_sbt_uuids, refused_sbt_uuids, } = delta; @@ -896,6 +914,10 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { result.gradle_uuids.extend(gradle_uuids); result.confirmed_gradle_uuids.extend(confirmed_gradle_uuids); result.refused_gradle_uuids.extend(refused_gradle_uuids); + result.maven_reactor_uuids.extend(maven_reactor_uuids); + result + .confirmed_maven_reactor_uuids + .extend(confirmed_maven_reactor_uuids); result.bundled_skipped_uuids.extend(bundled_skipped_uuids); for (uuid, keys) in alias_skipped_entries { result @@ -8939,30 +8961,15 @@ fn rewrite_maven_pom( return; } let mut pom = files.get("pom.xml").cloned(); - // A reactor root: this rewriter reads only the root pom, and a module's - // own literal `` beats any pin written here, so that module - // would keep the unpatched upstream jar while the dep counts as - // redirected and VEX attests it (#261). Refuse the whole root, untouched; - // vendored mode's reactor planner rewrites each module's declaration. - // Maven 4 subprojects found by discovery count too (#1809): the engine - // reads each direct subdirectory's `pom.xml` beside such a root. - if pom.is_some() && maven_reactor_root(files) { - let gas: Vec = maven - .iter() - .map(|dep| match &dep.namespace { - Some(ns) => format!("{ns}:{}", dep.name), - None => dep.name.clone(), - }) - .collect(); - result.warnings.push(RewriteWarning { - code: "redirect_maven_multimodule_unsupported".into(), - detail: format!( - "pom.xml heads a multi-module reactor (/, or Maven 4 subproject discovery); hosted mode reads only the root pom, so a module's own of {} would stay unpatched. pom.xml and .mvn/ were left as they are and the dep is not counted as redirected; use `scan --mode vendored`, which pins each module's declaration", - gas.join(", ") - ), - }); - return; - } + // A reactor root (`` / ``, or Maven 4 subproject + // discovery, #1809) is planned over all of its poms by the reactor + // planner ([`plan_maven_reactor`]): a module's own `` beats any + // pin in the root pom (#261), so the pins go where each module selects + // the patched version. A single pom is rewritten below, and hands a + // `${property}` version to the same planner. + let reactor_root = pom.is_some() && maven_reactor_root(files); + // The module poms the reactor planner changed, as they read now. + let mut module_poms: BTreeMap = BTreeMap::new(); let mut pom_changed = false; // The hosted generations whose `socket-patch-` repository the pom // declared before this run: only a suffixed literal one of these minted @@ -9088,6 +9095,56 @@ fn rewrite_maven_pom( continue; } }; + if reactor_root { + let _ = idx; + let planned = plan_maven_reactor( + files, + pom_text, + &mut module_poms, + ReactorDep { + dep, + group_id: &group_id, + artifact_id: &artifact_id, + suffixed: suffixed_version.as_deref(), + repo_id: &repo_id, + index_url: &ov.index_url, + refusal: "redirect_maven_multimodule_unsupported", + }, + selection, + &user_properties, + result, + ); + pom_changed |= files.get("pom.xml") != Some(&*pom_text); + index = pom + .as_deref() + .map(|pom| maven_index::PomIndex::build(pom, &user_properties)); + let (Some(run), Some(suffixed)) = (planned, suffixed_version.as_deref()) else { + continue; + }; + if checksum_hashes.is_some() && run.wired { + pinned_jar_paths.push(crate::vendor::jvm::layout::artifact_path( + &group_id, + &artifact_id, + suffixed, + None, + "jar", + )); + } + checksum_drops.extend(run.superseded_paths); + if run.landed { + pin_maven_checksums( + files, + (&group_id, &artifact_id, suffixed), + checksum_hashes.as_ref(), + bad_checksum_hashes, + &mut mvn_config, + &mut mvn_config_changed, + &mut checksum_entries, + result, + ); + } + continue; + } // A `` pin makes every occurrence of the GA // one version, so it is safe only where Maven selects the patch's // base version already. A build that selects another version (or @@ -9413,20 +9470,61 @@ fn rewrite_maven_pom( continue; } - // A `${property}` version on any match: refuse this dep entirely. - // Editing the literal would break the property reference, and a depMgmt - // pin could strand sibling artifacts sharing the property. - if let Some(prop) = matches + // A `${property}` version on any match: the reactor planner wires + // it (this pom is a reactor of one). It rewrites the property's own + // value when nothing else reads that property, so no sibling + // artifact is stranded; else it replaces the one declaration and + // records the text it replaced beside it. + if matches .iter() - .find(|m| m.version_text.as_deref().is_some_and(|v| v.contains("${"))) + .any(|m| m.version_text.as_deref().is_some_and(|v| v.contains("${"))) { - result.warnings.push(RewriteWarning { - code: "redirect_maven_dep_unpinned".into(), - detail: format!( - "{group_id}:{artifact_id} is a property placeholder ({}); refusing to pin the suffixed version (a property edit could strand sibling artifacts)", - prop.version_text.as_deref().unwrap_or_default() - ), - }); + let planned = plan_maven_reactor( + files, + pom_text, + &mut module_poms, + ReactorDep { + dep, + group_id: &group_id, + artifact_id: &artifact_id, + suffixed: Some(&suffixed_version), + repo_id: &repo_id, + index_url: &ov.index_url, + refusal: "redirect_maven_dep_unpinned", + }, + selection, + &user_properties, + result, + ); + pom_changed |= files.get("pom.xml") != Some(&*pom_text); + index = pom + .as_deref() + .map(|pom| maven_index::PomIndex::build(pom, &user_properties)); + let Some(run) = planned else { + continue; + }; + if checksum_hashes.is_some() && run.wired { + pinned_jar_paths.push(crate::vendor::jvm::layout::artifact_path( + &group_id, + &artifact_id, + &suffixed_version, + None, + "jar", + )); + } + checksum_drops.extend(run.superseded_paths); + if run.landed { + pin_maven_checksums( + files, + (&group_id, &artifact_id, &suffixed_version), + checksum_hashes.as_ref(), + bad_checksum_hashes, + &mut mvn_config, + &mut mvn_config_changed, + &mut checksum_entries, + result, + ); + } continue; } @@ -9630,66 +9728,16 @@ fn rewrite_maven_pom( }); } - // Trusted Checksums: only when BOTH the jar sha256 and the served pom - // sha256 are known. Two entries per dep — the jar and the pom — under - // the SUFFIXED version's local-repo path. - if bad_checksum_hashes { - result.warnings.push(RewriteWarning { - code: "redirect_maven_trusted_checksums_invalid_hash".into(), - detail: format!( - "{group_id}:{artifact_id}: the grant's sha256 is not 64 hex digits; \ - no Trusted Checksums pin written to {MVN_CHECKSUMS} (the -socket \ - version suffix still pins the patched artifact)" - ), - }); - } - if let Some((jar, pom_hash)) = &checksum_hashes { - let (merged, conflicts) = - merge_mvn_config(&mvn_config, &format!("{group_id}:{artifact_id}")); - for conflict in conflicts { - result.warnings.push(RewriteWarning { - code: "redirect_maven_trusted_checksums_conflict".into(), - detail: conflict, - }); - } - if merged != mvn_config { - let action = if files.contains_key(MVN_CONFIG) { - "rewritten" - } else { - "added" - }; - mvn_config = merged; - mvn_config_changed = true; - result.edits.push(FileEdit { - path: MVN_CONFIG.into(), - kind: "redirect_maven_config".into(), - action: action.into(), - key: Some("trustedChecksums".into()), - original: None, - new: None, - }); - } - checksum_entries.push(( - crate::vendor::jvm::layout::artifact_path( - &group_id, - &artifact_id, - &suffixed_version, - None, - "jar", - ), - jar.clone(), - )); - checksum_entries.push(( - crate::vendor::jvm::layout::artifact_path( - &group_id, - &artifact_id, - &suffixed_version, - None, - "pom", - ), - pom_hash.clone(), - )); - } + pin_maven_checksums( + files, + (&group_id, &artifact_id, &suffixed_version), + checksum_hashes.as_ref(), + bad_checksum_hashes, + &mut mvn_config, + &mut mvn_config_changed, + &mut checksum_entries, + result, + ); } if pom_changed { @@ -9697,6 +9745,7 @@ fn rewrite_maven_pom( result.files.insert("pom.xml".into(), p); } } + result.files.extend(module_poms); if mvn_config_changed { result.files.insert(MVN_CONFIG.into(), mvn_config); } @@ -9754,6 +9803,417 @@ fn rewrite_maven_pom( } } +/// The Trusted Checksums pin of one dep whose version pin landed this run: +/// only when BOTH the jar sha256 and the served pom sha256 are known. Two +/// entries per dep — the jar and the pom — under the SUFFIXED version's +/// local-repo path. +#[allow(clippy::too_many_arguments)] +fn pin_maven_checksums( + files: &BTreeMap, + (group_id, artifact_id, suffixed_version): (&str, &str, &str), + checksum_hashes: Option<&(String, String)>, + bad_checksum_hashes: bool, + mvn_config: &mut String, + mvn_config_changed: &mut bool, + checksum_entries: &mut Vec<(String, String)>, + result: &mut RewriteResult, +) { + if bad_checksum_hashes { + result.warnings.push(RewriteWarning { + code: "redirect_maven_trusted_checksums_invalid_hash".into(), + detail: format!( + "{group_id}:{artifact_id}: the grant's sha256 is not 64 hex digits; \ + no Trusted Checksums pin written to {MVN_CHECKSUMS} (the -socket \ + version suffix still pins the patched artifact)" + ), + }); + } + let Some((jar, pom_hash)) = checksum_hashes else { + return; + }; + let (merged, conflicts) = merge_mvn_config(mvn_config, &format!("{group_id}:{artifact_id}")); + for conflict in conflicts { + result.warnings.push(RewriteWarning { + code: "redirect_maven_trusted_checksums_conflict".into(), + detail: conflict, + }); + } + if merged != *mvn_config { + let action = if files.contains_key(MVN_CONFIG) { + "rewritten" + } else { + "added" + }; + *mvn_config = merged; + *mvn_config_changed = true; + result.edits.push(FileEdit { + path: MVN_CONFIG.into(), + kind: "redirect_maven_config".into(), + action: action.into(), + key: Some("trustedChecksums".into()), + original: None, + new: None, + }); + } + for (ext, hash) in [("jar", jar), ("pom", pom_hash)] { + checksum_entries.push(( + crate::vendor::jvm::layout::artifact_path( + group_id, + artifact_id, + suffixed_version, + None, + ext, + ), + hash.clone(), + )); + } +} + +/// One dep handed to the reactor planner. +struct ReactorDep<'a> { + dep: &'a DepOverride, + group_id: &'a str, + artifact_id: &'a str, + /// The grant's suffixed version (`None`: a same-GAV grant). + suffixed: Option<&'a str>, + repo_id: &'a str, + index_url: &'a str, + /// The code a dep the planner cannot take is reported under: the one + /// the pom rewriter gave that shape before the planner read it. + refusal: &'static str, +} + +/// What [`plan_maven_reactor`] did for one dep. +struct ReactorRun { + /// A version, property or pin was written this run. + landed: bool, + /// Some pom wires the patch once the run is written. + wired: bool, + /// Trusted-checksum paths of the earlier patches of this version whose + /// pins moved to this one. + superseded_paths: Vec, +} + +/// The hosted warning a reactor planner note is reported under. +fn reactor_note_code(reason: &str) -> &'static str { + match reason { + "classifier_declared" => "redirect_maven_classifier_unsupported", + "coordinates_overridden" => "redirect_maven_profile_coordinates_unpatched", + "conflicting_literal_version" | "range" => "redirect_maven_dep_version_mismatch", + "selection_undetermined" => "redirect_maven_selection_undetermined", + "pin_would_move_module" => "redirect_maven_pin_would_move_module", + "edit_not_reversible" => "redirect_maven_edit_not_reversible", + _ => "redirect_maven_dep_unpinned", + } +} + +/// Wire one dep through the reactor planner +/// ([`crate::vendor::jvm::maven_reactor::plan_hosted`]): over every pom of +/// a reactor root, or over a single pom whose declaration reads a +/// `${property}`. The poms it changes land in `pom_text` (the root) and +/// `module_poms`; the `` goes in each local root a wired pom +/// inherits from. `None` when nothing wires the patch (the warning says +/// why); the `.mvn` files are the caller's. +fn plan_maven_reactor( + files: &BTreeMap, + pom_text: &mut String, + module_poms: &mut BTreeMap, + of: ReactorDep<'_>, + selection: Option<&MavenSelection>, + user_properties: &BTreeMap, + result: &mut RewriteResult, +) -> Option { + use crate::vendor::jvm::maven_reactor::{plan_hosted, HostedEditKind}; + let (dep, g, a) = (of.dep, of.group_id, of.artifact_id); + let ga = format!("{g}:{a}"); + let coords = crate::vendor::jvm::Coords { + group_id: g, + artifact_id: a, + version: &dep.version, + uuid: &dep.patch_uuid, + }; + let refuse = |result: &mut RewriteResult, why: String| { + result.warnings.push(RewriteWarning { + code: of.refusal.into(), + detail: format!( + "{ga}: {why}; the poms and .mvn/ were left as they are and the dep is not \ + counted as redirected (`scan --mode vendored` commits the patched artifact \ + instead)" + ), + }); + }; + result.maven_reactor_uuids.insert(dep.patch_uuid.clone()); + // The planner writes the suffix the patch uuid gives; a grant that + // serves another one (or none: a same-GAV grant) is not planned. + let suffixed = coords.suffixed_version(); + if of.suffixed != Some(suffixed.as_str()) || dep.patch_uuid.len() != 36 { + refuse( + result, + match of.suffixed { + Some(served) => { + format!("the grant serves {served}, not the {suffixed} its patch uuid names") + } + None => "the grant serves the patched artifact under its original version, \ + which a pin in one pom cannot keep apart from the upstream one in \ + another" + .to_string(), + }, + ); + return None; + } + let before: BTreeMap = module_poms.clone(); + let plan = { + let read = |rel: &str| { + let text = match rel { + "pom.xml" => Some(&*pom_text), + _ => module_poms.get(rel).or_else(|| files.get(rel)), + }; + text.map(|text| text.as_bytes().to_vec()) + }; + let list = |dir: &str| gradle::key_list(files, dir); + plan_hosted(&read, &list, &coords, selection) + }; + let plan = match plan { + Ok(plan) => plan, + Err(refusal) => { + refuse( + result, + refusal + .detail + .strip_prefix("reason: ") + .unwrap_or(&refusal.detail) + .to_string(), + ); + return None; + } + }; + if let Some(others) = &plan.not_selected { + result.warnings.push(RewriteWarning { + code: "redirect_maven_version_not_selected".into(), + detail: format!( + "{}; the poms were left as they are", + crate::crawlers::maven_selection::not_selected_detail(g, a, &dep.version, others) + ), + }); + return None; + } + for (reason, detail) in &plan.notes { + result.warnings.push(RewriteWarning { + code: reactor_note_code(reason).into(), + detail: detail.clone(), + }); + } + // Earlier patches of this version whose wiring this run moves on. + let generations = |texts: &dyn Fn(&str) -> Option, rels: &[String]| { + let mut found: std::collections::BTreeSet = std::collections::BTreeSet::new(); + let prefix = format!("{}-socket.", dep.version); + for rel in rels { + let Some(text) = texts(rel) else { continue }; + let masked = crate::formats::xml::blank_non_markup(&text).unwrap_or(text); + for (at, _) in masked.match_indices(&prefix) { + let hex8 = masked.get(at + prefix.len()..at + prefix.len() + 8); + if let Some(hex8) = hex8.filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit())) { + found.insert(format!("{prefix}{hex8}")); + } + } + } + found + }; + let changed: Vec = plan.poms.keys().cloned().collect(); + let old_text = |rel: &str| match rel { + "pom.xml" => Some(pom_text.clone()), + _ => before.get(rel).or_else(|| files.get(rel)).cloned(), + }; + let had = generations(&old_text, &changed); + for (rel, text) in &plan.poms { + match rel.as_str() { + "pom.xml" => *pom_text = text.clone(), + _ => { + module_poms.insert(rel.clone(), text.clone()); + } + } + } + for edit in &plan.edits { + let (kind, action, key, new) = match edit.kind { + HostedEditKind::Version => ( + "redirect_maven_dep_version", + "rewritten", + ga.clone(), + Some(Value::String(suffixed.clone())), + ), + HostedEditKind::Property => ( + "redirect_maven_property", + "rewritten", + edit.property.clone().unwrap_or_default(), + Some(Value::String(suffixed.clone())), + ), + HostedEditKind::Pin => ( + "redirect_maven_dep_management", + "added", + ga.clone(), + Some(json!({ "groupId": g, "artifactId": a, "version": suffixed })), + ), + HostedEditKind::PinMoved => ( + "redirect_maven_dep_management", + "rewritten", + ga.clone(), + Some(json!({ "groupId": g, "artifactId": a, "version": suffixed })), + ), + HostedEditKind::PinRemoved => { + ("redirect_maven_dep_management", "removed", ga.clone(), None) + } + }; + result.edits.push(FileEdit { + path: edit.rel.clone(), + kind: kind.into(), + action: action.into(), + key: Some(key), + original: edit.original.clone().map(Value::String), + new, + }); + match edit.kind { + HostedEditKind::Pin => result.warnings.push(RewriteWarning { + code: "redirect_maven_dep_management_added".into(), + detail: format!( + "{ga}: added a pin for the suffixed version \ + {suffixed} to {}, where every module selects {} already", + edit.rel, dep.version + ), + }), + HostedEditKind::PinRemoved => result.warnings.push(RewriteWarning { + code: "redirect_maven_pin_would_move_module".into(), + detail: format!( + "{ga}: the pin of {} in {} was removed: a module it reaches now resolves \ + another version, which the pin would hold back", + dep.version, edit.rel + ), + }), + _ => {} + } + } + let landed = plan + .edits + .iter() + .any(|edit| edit.kind != HostedEditKind::PinRemoved); + let superseded: Vec = { + let new_text = |rel: &str| match rel { + "pom.xml" => Some(pom_text.clone()), + _ => module_poms.get(rel).or_else(|| files.get(rel)).cloned(), + }; + had.difference(&generations(&new_text, &changed)) + .filter(|old| **old != suffixed) + .cloned() + .collect() + }; + if !plan.wired { + if plan.notes.is_empty() && plan.edits.is_empty() { + refuse( + result, + format!("no pom of the build could take the pin of {}", dep.version), + ); + } + return None; + } + result + .confirmed_maven_reactor_uuids + .insert(dep.patch_uuid.clone()); + if !plan.nested_mvn.is_empty() && landed { + result.warnings.push(RewriteWarning { + code: "redirect_maven_trusted_checksums_unenforced".into(), + detail: format!( + "{} has a .mvn directory of its own: a Maven started there reads that one, \ + not the project root's, so the Trusted Checksums pin in {MVN_CHECKSUMS} is \ + not enforced for such a build (the -socket version suffix still pins the \ + patched artifact)", + plan.nested_mvn.join(", ") + ), + }); + } + // The repository, where every wired pom inherits it; an earlier + // patch's goes once nothing names its suffix any more. + for root in &plan.roots { + let current = match root.as_str() { + "pom.xml" => Some(&*pom_text), + _ => module_poms.get(root).or_else(|| files.get(root)), + }; + let Some(mut text) = current.cloned() else { + continue; + }; + let Ok(mut index) = maven_index::PomIndex::build(&text, user_properties) else { + continue; + }; + let mut edit = |action: &str, key: &str, new: Option, kind: &str| { + result.edits.push(FileEdit { + path: root.clone(), + kind: kind.into(), + action: action.into(), + key: Some(key.to_string()), + original: None, + new, + }); + }; + let named = json!({ "id": of.repo_id, "url": of.index_url }); + if !index.has_repository(of.repo_id) { + index.insert_repository(&mut text, of.repo_id, of.index_url); + edit( + "added", + of.repo_id, + Some(named), + "redirect_maven_repository", + ); + } else if index.refresh_repository_url(&mut text, of.repo_id, of.index_url) { + edit( + "rewritten", + of.repo_id, + Some(named), + "redirect_maven_repository", + ); + } + for old in &superseded { + let hex8 = crate::formats::maven::split_socket_version(old) + .map(|(_, h)| h) + .unwrap_or_default(); + if text.contains(&format!("-socket.{hex8}")) { + continue; + } + for old_uuid in generation::named_generations(&text) { + if old_uuid == dep.patch_uuid || !old_uuid.starts_with(hex8) { + continue; + } + let old_id = generation::hosted_pin_name(&old_uuid); + if index.remove_repository(&mut text, &old_id) { + edit( + "removed", + &old_id, + None, + "redirect_maven_superseded_repository_removed", + ); + } + } + } + match root.as_str() { + "pom.xml" => *pom_text = text, + _ => { + if files.get(root) != Some(&text) || module_poms.contains_key(root) { + module_poms.insert(root.clone(), text); + } + } + } + } + let superseded_paths = superseded + .iter() + .flat_map(|old| { + ["jar", "pom"] + .map(|ext| crate::vendor::jvm::layout::artifact_path(g, a, old, None, ext)) + }) + .collect(); + Some(ReactorRun { + landed, + wired: true, + superseded_paths, + }) +} + static MAVEN_REPOSITORY_RE: LazyLock = LazyLock::new(|| { Regex::new(r"(?s).*?").expect("static repository regex is valid") }); @@ -10719,6 +11179,19 @@ mod tests { } } + const MAVEN_UUID: &str = "aaaaaaaa-1111-4222-8333-444444444444"; + + /// [`maven_override`] as the patch service grants it: the suffix is the + /// first eight hex digits of the patch uuid, which is what ties a pin + /// to its repository and what the reactor planner writes. + fn granted_maven_override() -> DepOverride { + let mut dep = maven_override(); + dep.patch_uuid = MAVEN_UUID.into(); + dep.registry_override.as_mut().unwrap().index_url = + format!("https://patch.socket.dev/patch-registry/maven/tok/{MAVEN_UUID}/maven2"); + dep + } + /// A legacy override — no suffixed version, no sha256 (same-GAV serving). fn legacy_maven_override() -> DepOverride { let mut dep = maven_override(); @@ -11126,11 +11599,13 @@ mod tests { /// #1809: a Maven 4 (model 4.1.0) `pom`-packaged root that lists no /// subprojects builds every direct subdirectory holding a `pom.xml`, so - /// it is a reactor like a declared one and refused untouched. Without - /// such a subdirectory, under a 4.0.0 model, or with discovery turned - /// off in `.mvn/maven.config`, it is a single pom and still rewritten. + /// it is a reactor like a declared one: each pom's own declaration of + /// the version is rewritten, and the repository goes in the root they + /// inherit. Without such a subdirectory, under a 4.0.0 model, or with + /// discovery turned off in `.mvn/maven.config`, it is a single pom and + /// rewritten alone. #[test] - fn maven_4_implicit_subprojects_root_is_refused() { + fn maven_4_implicit_subprojects_are_rewritten_with_their_root() { let dep = "\n \n org.slf4j\n slf4j-api\n 1.7.36\n \n \n"; let root = |model: &str| { format!( @@ -11141,23 +11616,35 @@ mod tests { let tree = |model: &str, extra: &[(&str, &str)]| { let mut files = BTreeMap::from([("pom.xml".to_string(), root(model))]); files.extend(extra.iter().map(|(k, v)| (k.to_string(), v.to_string()))); - rewrite_registry_redirect(&files, &[maven_override()]) + rewrite_registry_redirect(&files, &[granted_maven_override()]) }; let r = tree("4.1.0", &[("child/pom.xml", child)]); + for rel in ["pom.xml", "child/pom.xml"] { + let text = r.files.get(rel).map(String::as_str).unwrap_or_default(); + assert!( + text.contains(&format!("{MAVEN_SUFFIXED}")), + "{rel} declares the version itself: {text} {:?}", + r.warnings + ); + } assert!( - r.files.is_empty() && r.edits.is_empty(), - "an implicit reactor root must not be edited: files={:?} edits={:?}", - r.files.keys(), - r.edits + r.files["pom.xml"].contains("socket-patch-") + && !r.files["child/pom.xml"].contains(""), + "one repository, in the root the subproject inherits" + ); + assert!( + !warning_codes(&r).contains(&"redirect_maven_multimodule_unsupported"), + "{:?}", + r.warnings ); + // Nothing of it is planned when a subproject's pom cannot be read. + let r = tree("4.1.0", &[("child/pom.xml", "")]); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.files); assert_eq!( warning_codes(&r), vec!["redirect_maven_multimodule_unsupported"] ); - assert!(r.warnings[0] - .detail - .contains("Maven 4 subproject discovery")); let off = "-Dmaven.project.discoverSubprojects=false\n"; for (case, r) in [ @@ -11182,6 +11669,247 @@ mod tests { } } + /// Hosted-redirects slf4j-api over `files`, each module selecting what + /// `picks` says for it (a module left out does not resolve it). + fn rewrite_poms_selecting( + files: &BTreeMap, + picks: &[(&str, Result<&str, &str>)], + ) -> RewriteResult { + let modules: Vec<&str> = files + .keys() + .map(String::as_str) + .filter(|rel| rel.ends_with("pom.xml")) + .collect(); + let picks: Vec<_> = picks + .iter() + .map(|(pom, pick)| (*pom, "org.slf4j", "slf4j-api", *pick)) + .collect(); + let selection = MavenSelection::answering(&modules, &picks); + rewrite_registry_redirect_with_host( + files, + &[granted_maven_override()], + &BTreeMap::new(), + None, + false, + &std::collections::BTreeSet::new(), + &yarnrc::OuterYarnMirror::default(), + &CratesIoSource::Registry, + Some(&selection), + ) + } + + fn poms(files: &[(&str, &str)]) -> BTreeMap { + files + .iter() + .map(|(rel, text)| (rel.to_string(), text.to_string())) + .collect() + } + + const REACTOR_ROOT: &str = "\n 4.0.0\n \ + com.example\n root\n \ + 1.0.0\n pom\n \n \ + a\n b\n \n\n"; + + /// The module `name` of [`REACTOR_ROOT`], depending on logback (which + /// brings slf4j-api in) and on `more`. + fn reactor_module(name: &str, more: &str) -> String { + format!( + "\n 4.0.0\n \n \ + com.example\n root\n \ + 1.0.0\n \n {name}\n \ + \n \n ch.qos.logback\n \ + logback-classic\n 1.4.14\n \ + \n{more} \n\n" + ) + } + + /// A reactor is pinned module by module: the pin goes in the pom of + /// the module that selects the patch's version, the module that + /// resolves another one is not touched, and the repository and the + /// Trusted Checksums go where the whole reactor reads them. + #[test] + fn maven_reactor_is_pinned_in_the_modules_that_select_the_version() { + let files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let picks = [("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))]; + let r = rewrite_poms_selecting(&files, &picks); + assert_eq!( + r.files.keys().collect::>(), + [MVN_CHECKSUMS, MVN_CONFIG, "a/pom.xml", "pom.xml"], + "b/pom.xml is not written: {:?}", + r.warnings + ); + let pin = format!( + "\n \ + \n org.slf4j\n \ + slf4j-api\n {MAVEN_SUFFIXED}\n \ + " + ); + assert!( + r.files["a/pom.xml"].contains(&pin), + "{}", + r.files["a/pom.xml"] + ); + assert!(!r.files["a/pom.xml"].contains("")); + let root = &r.files["pom.xml"]; + assert!( + root.contains(&format!("socket-patch-{MAVEN_UUID}")) + && !root.contains(MAVEN_SUFFIXED), + "the root takes the repository and no pin: {root}" + ); + assert_eq!( + r.edits + .iter() + .map(|e| (e.path.as_str(), e.kind.as_str(), e.action.as_str())) + .collect::>(), + [ + ("a/pom.xml", "redirect_maven_dep_management", "added"), + ("pom.xml", "redirect_maven_repository", "added"), + (MVN_CONFIG, "redirect_maven_config", "added"), + (MVN_CHECKSUMS, "redirect_maven_trusted_checksums", "added"), + ] + ); + assert_eq!(warning_codes(&r), ["redirect_maven_dep_management_added"]); + assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); + + // A second run over what the first wrote changes nothing, and + // still counts the patch as pinned. + let mut after = files.clone(); + after.extend(r.files.clone()); + let again = rewrite_poms_selecting(&after, &picks); + assert!( + again.files.is_empty() && again.edits.is_empty(), + "{:?} {:?}", + again.files.keys(), + again.edits + ); + assert!(again.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); + + // No module selects the version: nothing is written, and the line + // says what the build selects instead. + let r = rewrite_poms_selecting( + &files, + &[("a/pom.xml", Ok("2.0.9")), ("b/pom.xml", Ok("2.0.9"))], + ); + assert!(r.files.is_empty() && r.edits.is_empty()); + assert_eq!(warning_codes(&r), ["redirect_maven_version_not_selected"]); + assert!(r.warnings[0].detail.contains("2.0.9"), "{:?}", r.warnings); + assert!(r.confirmed_maven_reactor_uuids.is_empty()); + } + + /// A reactor none of whose poms can be told is left as it is, but for + /// a declaration that names the version: that one is rewritten where + /// it stands, which moves nothing. + #[test] + fn maven_reactor_without_a_selection_rewrites_declarations_only() { + let declaring = " \n org.slf4j\n \ + slf4j-api\n 1.7.36\n \ + \n"; + let files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", declaring)), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let r = rewrite_registry_redirect(&files, &[granted_maven_override()]); + assert_eq!( + r.files["a/pom.xml"], + files["a/pom.xml"].replace("1.7.36<", &format!("{MAVEN_SUFFIXED}<")) + ); + assert!(!r.files.contains_key("b/pom.xml")); + assert_eq!( + warning_codes(&r), + ["redirect_maven_selection_undetermined"], + "b may resolve it too, and is not pinned on a guess" + ); + assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); + } + + fn property_pom(properties: &str, more: &str) -> String { + format!( + "\n 4.0.0\n com.example\n \ + app\n 1.0.0\n \n \ + {properties}\n \n \n \n \ + org.slf4j\n slf4j-api\n \ + ${{slf4j.version}}\n \n{more} \ + \n\n" + ) + } + + /// A `${property}` version is wired, no longer refused: the property + /// itself when only this artifact reads it, else the one declaration, + /// with the text it replaced recorded right after it so a rollback + /// can put it back. + #[test] + fn maven_property_version_is_wired_without_stranding_a_sibling() { + let picks = [("pom.xml", Ok("1.7.36"))]; + + let own = poms(&[( + "pom.xml", + &property_pom("1.7.36", ""), + )]); + let r = rewrite_poms_selecting(&own, &picks); + assert!( + r.files["pom.xml"] + .contains(&format!("{MAVEN_SUFFIXED}")) + && r.files["pom.xml"].contains("${slf4j.version}"), + "{}", + r.files["pom.xml"] + ); + assert_eq!(r.edits[0].kind, "redirect_maven_property"); + assert_eq!(r.edits[0].key.as_deref(), Some("slf4j.version")); + assert!(warning_codes(&r).is_empty(), "{:?}", r.warnings); + assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); + + let sibling = " \n org.slf4j\n \ + slf4j-simple\n \ + ${slf4j.version}\n \n"; + let shared = poms(&[( + "pom.xml", + &property_pom("1.7.36", sibling), + )]); + let r = rewrite_poms_selecting(&shared, &picks); + let pom = &r.files["pom.xml"]; + assert!( + pom.contains(&format!( + "slf4j-api\n {MAVEN_SUFFIXED}\ + " + )), + "{pom}" + ); + assert!( + pom.contains("1.7.36") + && pom.contains( + "slf4j-simple\n \ + ${slf4j.version}" + ), + "the property and its other reader are as they were: {pom}" + ); + assert_eq!(r.edits[0].kind, "redirect_maven_dep_version"); + assert_eq!( + r.edits[0].original, + Some(Value::String("${slf4j.version}".into())) + ); + let mut after = shared.clone(); + after.extend(r.files.clone()); + let again = rewrite_poms_selecting(&after, &picks); + assert!( + again.files.is_empty() && again.edits.is_empty(), + "{:?}", + again.edits + ); + + // A property no pom of the checkout defines, in a build whose + // selection is not known: left as it is, with the reason. + let undefined = poms(&[("pom.xml", &property_pom("1", ""))]); + let r = rewrite_registry_redirect(&undefined, &[granted_maven_override()]); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.files); + assert!(warning_codes(&r).contains(&"redirect_maven_dep_unpinned")); + assert!(r.confirmed_maven_reactor_uuids.is_empty()); + } + /// A direct declaration whose groupId / artifactId is a property of /// the pom's own `` is the GA (#683): its literal is /// rewritten, not shadowed by an added `` pin diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs index 5fe77de47..b809e1ee8 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs @@ -27,6 +27,12 @@ use super::{ TREE_GITATTRIBUTES, }; +mod hosted; +pub use hosted::{ + hosted_sites, plan_hosted, readable_for_hosted, unwire_hosted, HostedEdit, HostedEditKind, + HostedPlan, HostedSite, ORIGINAL_TAG, +}; + /// The committed maven2 tree. use super::layout::MAVEN2_TREE as TREE_ROOT; pub const MAVEN_CONFIG: &str = ".mvn/maven.config"; @@ -267,6 +273,7 @@ pub fn plan_with_selection( &mut unpinned, &mut managed_roots, &mut BTreeSet::new(), + &|_, _| None, ); } @@ -316,91 +323,13 @@ pub fn plan_with_selection( } // What the modules at and below each pom select, read once. - let under = selection.map(|selection| reactor.under(selection, patch)); + let under = selection.map(|selection| reactor.under(selection, patch, &|_| false)); if let Some(under) = &under { - // A module that declares another version itself resolves that - // version: its declaration is no conflict to report, and the pins - // go where the base version is selected. - warnings.retain(|w| { - !under.iter().any(|(rel, u)| { - u.own == Some(Own::Other) - && w.detail.contains(" is declared at ") - && w.detail - .starts_with(&format!("reason: conflicting_literal_version: {rel}:")) - }) - }); + forget_other_versions(&mut warnings, under); } // Where the pin goes, and the poms whose pin stays as it is. - let mut pins: BTreeSet = BTreeSet::new(); - let mut held: BTreeSet = BTreeSet::new(); let closed = |rel: &String| unpinned.contains(rel) || managed_roots.contains(rel); - // Where the pins go is decided when a patch is first wired, and the - // committed poms are the record of it: what this machine's local - // repository happens to hold must not move them, or the same checkout - // would plan differently from one machine to the next. A patch the - // poms already wire therefore keeps every pin it has and gets no new - // one, with or without a selection. The one exception is a pin that - // is certain to move a module to another version than Maven selects - // for it, which no run should have left: the pins are then placed - // afresh. - let moves = under.as_ref().is_some_and(|under| { - reactor.scope.iter().any(|rel| { - pin_of(&reactor.poms[rel].doc, patch).is_some() - && under.get(rel).is_some_and(|u| u.other.is_some()) - }) - }); - if reactor.wired_before(patch) && !moves { - // (A local root a declaration ruled out stays ruled out.) - held.extend(reactor.scope.iter().filter(|rel| !closed(rel)).cloned()); - } else { - let mut stranded: Vec = Vec::new(); - for root in reactor.wired_roots() { - let open = !closed(&root); - match &under { - None if open => { - pins.insert(root); - } - None => {} - Some(under) => { - let mut placing = Placing { - under, - patch, - pins: &mut pins, - held: &mut held, - stranded: &mut stranded, - }; - reactor.place(&root, open, &mut placing, 0); - } - } - } - warnings.extend( - stranded - .into_iter() - .map(|detail| degraded("pin_would_move_module", detail)), - ); - // One line for every module that cannot be told, however many. - let unknown: Vec<(&String, &String)> = under - .iter() - .flatten() - .filter_map(|(rel, u)| match &u.own { - Some(Own::Unknown(why)) => Some((rel, why)), - _ => None, - }) - .collect(); - if let Some((module, why)) = unknown.first() { - let more = match unknown.len() - 1 { - 0 => String::new(), - n => format!(", and {n} more"), - }; - warnings.push(degraded( - "selection_undetermined", - format!( - "which version of {g}:{a} {module} resolves cannot be told ({why}){more}; \ - no pin is written where that is so, and one already there is left as it is" - ), - )); - } - } + let (pins, held) = place_pins(&reactor, patch, under.as_ref(), &closed, &mut warnings); let banning = reactor .scope @@ -540,6 +469,104 @@ pub fn plan_with_selection( }) } +/// A module that declares another version itself resolves that version: +/// its declaration is no conflict to report, and the pins go where the +/// base version is selected. +fn forget_other_versions(warnings: &mut Vec, under: &BTreeMap) { + warnings.retain(|w| { + !under.iter().any(|(rel, u)| { + u.own == Some(Own::Other) + && w.detail.contains(" is declared at ") + && w.detail + .starts_with(&format!("reason: conflicting_literal_version: {rel}:")) + }) + }); +} + +/// Where `patch`'s pins go, and the poms whose pin stays as it is (held), +/// by what the modules at and below each pom select (`under`; `None`: not +/// asked). `closed` holds the local roots that take no pin of their own (a +/// declaration ruled them out, or they manage the artifact themselves). +/// +/// Where the pins go is decided when a patch is first wired, and the +/// committed poms are the record of it: what this machine's local +/// repository happens to hold must not move them, or the same checkout +/// would plan differently from one machine to the next. A patch the poms +/// already wire therefore keeps every pin it has and gets no new one, with +/// or without a selection. The one exception is a pin that is certain to +/// move a module to another version than Maven selects for it, which no +/// run should have left: the pins are then placed afresh. +fn place_pins( + reactor: &Reactor, + patch: &JvmPatch<'_>, + under: Option<&BTreeMap>, + closed: &dyn Fn(&String) -> bool, + warnings: &mut Vec, +) -> (BTreeSet, BTreeSet) { + let (g, a) = (patch.group_id, patch.artifact_id); + let mut pins: BTreeSet = BTreeSet::new(); + let mut held: BTreeSet = BTreeSet::new(); + let moves = under.is_some_and(|under| { + reactor.scope.iter().any(|rel| { + pin_of(&reactor.poms[rel].doc, patch).is_some() + && under.get(rel).is_some_and(|u| u.other.is_some()) + }) + }); + if reactor.wired_before(patch) && !moves { + // (A local root a declaration ruled out stays ruled out.) + held.extend(reactor.scope.iter().filter(|rel| !closed(rel)).cloned()); + return (pins, held); + } + let mut stranded: Vec = Vec::new(); + for root in reactor.wired_roots() { + let open = !closed(&root); + match under { + None if open => { + pins.insert(root); + } + None => {} + Some(under) => { + let mut placing = Placing { + under, + patch, + pins: &mut pins, + held: &mut held, + stranded: &mut stranded, + }; + reactor.place(&root, open, &mut placing, 0); + } + } + } + warnings.extend( + stranded + .into_iter() + .map(|detail| degraded("pin_would_move_module", detail)), + ); + // One line for every module that cannot be told, however many. + let unknown: Vec<(&String, &String)> = under + .into_iter() + .flatten() + .filter_map(|(rel, u)| match &u.own { + Some(Own::Unknown(why)) => Some((rel, why)), + _ => None, + }) + .collect(); + if let Some((module, why)) = unknown.first() { + let more = match unknown.len() - 1 { + 0 => String::new(), + n => format!(", and {n} more"), + }; + warnings.push(degraded( + "selection_undetermined", + format!( + "which version of {g}:{a} {module} resolves cannot be told ({why}){more}; \ + no pin is written where that is so, and one already there is left as it is" + ), + )); + } + (pins, held) +} + fn op_of_value(op: &Value) -> &str { op.get("op").and_then(Value::as_str).unwrap_or_default() } @@ -856,18 +883,7 @@ pub fn unattestable_checked( {ga}:{sv}" ))); } - let patch = JvmPatch { - group_id: c.group_id, - artifact_id: c.artifact_id, - version: c.version, - uuid: c.uuid, - jar: &[], - upstream_pom: &[], - upstream_parents: None, - upstream_module: None, - extra_artifacts: &[], - patched_members: &[], - }; + let patch = coords_patch(c); let mut edits = BTreeMap::new(); let mut uncertain = BTreeSet::new(); for rel in &reactor.scope { @@ -880,6 +896,7 @@ pub fn unattestable_checked( &mut BTreeSet::new(), &mut BTreeSet::new(), &mut uncertain, + &|_, _| None, ); } let mut at: Vec = edits.into_keys().collect(); @@ -895,6 +912,23 @@ pub fn unattestable_checked( })) } +/// `c` as a patch with no bytes: for planning that reads only what a +/// patch is of, never what it holds. +fn coords_patch<'a>(c: &Coords<'a>) -> JvmPatch<'a> { + JvmPatch { + group_id: c.group_id, + artifact_id: c.artifact_id, + version: c.version, + uuid: c.uuid, + jar: &[], + upstream_pom: &[], + upstream_parents: None, + upstream_module: None, + extra_artifacts: &[], + patched_members: &[], + } +} + /// `` comment, in the poms +//! [`place_pins`] picks (where every module at or below selects the base +//! version already, or does not resolve the artifact); +//! - a declaration whose version is one `${property}` the reactor's own +//! poms define, with nothing else reading that property, has the +//! property's value rewritten instead: the declaration keeps its text; +//! - any other `${...}` version is replaced by the literal suffixed +//! version, and the text it replaced is recorded in a comment right +//! after the element ([`ORIGINAL_TAG`]). +//! +//! [`unwire_hosted`] is the inverse, and [`plan_hosted`] makes no edit it +//! does not undo exactly: each pom it would change is unwired again before +//! the plan is returned, and left alone when that is not the text it had. +//! The `` and the `.mvn` files are the hosted rewriter's. + +use std::collections::{BTreeMap, BTreeSet}; +use std::ops::Range; + +use super::{ + apply_edits, coords_patch, forget_other_versions, is_base_like, line_span, pin_edit, pin_of, + pin_update, place_pins, safe_coordinates, Doc, Edit, Pin, Reactor, Role, +}; +use crate::crawlers::maven_selection::{MavenSelection, Standing, Verdict}; +use crate::formats::maven::split_socket_version; +use crate::vendor::jvm::{Coords, JvmRefusal, ListFn, ReadFn}; + +/// The start of the comment that records what a declaration's `` +/// read before hosted mode replaced it with a literal suffixed version: +/// `1.2-socket.0a1b2c3d`. +pub const ORIGINAL_TAG: &str = ""; + +/// What one edit of [`plan_hosted`] is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HostedEditKind { + /// A declaration's `` now reads the suffixed version. + Version, + /// A property's value now is the suffixed version. + Property, + /// A `` pin was added. + Pin, + /// The pin of an earlier patch of this version moved to this patch. + PinMoved, + /// A pin that would move a module to another version was taken out. + PinRemoved, +} + +/// One edit of [`plan_hosted`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HostedEdit { + /// The pom edited. + pub rel: String, + pub kind: HostedEditKind, + /// The text replaced: a version, a property's value (`None` for a pin, + /// and for a version an earlier patch had suffixed). + pub original: Option, + /// The property a [`HostedEditKind::Property`] edit rewrote. + pub property: Option, +} + +/// What hosted mode does to a reactor's poms for one patch. +#[derive(Debug, Default)] +pub struct HostedPlan { + /// The poms that change, with their new text. + pub poms: BTreeMap, + pub edits: Vec, + /// Why a declaration or a pom was left as it is: the vendored + /// planner's reason word, and the line. + pub notes: Vec<(String, String)>, + /// Whether a pom wires the patch once the plan is written (or did + /// before). + pub wired: bool, + /// The local roots under which a pom names the suffixed version: where + /// the `` goes, for every pom below to inherit. + pub roots: Vec, + /// The module directories with a `.mvn` of their own. + pub nested_mvn: Vec, + /// No module selects the base version, and every answer is certain: + /// the versions selected instead. Nothing is planned then. + pub not_selected: Option>, +} + +/// Plan the hosted wiring of the patch `c` in the reactor rooted at +/// `pom.xml` (a single pom is a reactor of one). `selection` is what Maven +/// selects in each module; `None` reads as "cannot be told", which rewrites +/// the declarations that name the base version and pins nothing. +pub fn plan_hosted( + read: ReadFn<'_>, + list: ListFn<'_>, + c: &Coords<'_>, + selection: Option<&MavenSelection>, +) -> Result { + let (g, a, base) = (c.group_id, c.artifact_id, c.version); + if !safe_coordinates(g, a, base) { + return Err(JvmRefusal { + code: "unsafe_coordinates", + detail: format!("unsafe maven coordinates `{g}:{a}:{base}`"), + }); + } + let patch = coords_patch(c); + let sv = c.suffixed_version(); + let reactor = Reactor::discover_for(read, list, true)?; + let unread; + let selection = match selection { + Some(selection) => selection, + None => { + unread = MavenSelection::unavailable("what Maven selects was not read"); + &unread + } + }; + let mut plan = HostedPlan { + nested_mvn: reactor.nested_mvn.clone(), + ..HostedPlan::default() + }; + if let Standing::NotSelected(others) = selection.standing(g, a, base) { + if !reactor.wired_before(&patch) { + plan.not_selected = Some(others); + return Ok(plan); + } + } + + // The declarations that name the base version. + let mut edits: BTreeMap> = BTreeMap::new(); + let mut warnings = Vec::new(); + let mut unpinned = BTreeSet::new(); + let mut managed_roots = BTreeSet::new(); + let told = |rel: &str, dep: usize| { + reactor + .readers_select(rel, dep, selection, c) + .then(|| base.to_string()) + }; + for rel in &reactor.scope { + reactor.rewrite_declarations( + rel, + &patch, + &sv, + &mut edits, + &mut warnings, + &mut unpinned, + &mut managed_roots, + &mut BTreeSet::new(), + &told, + ); + } + forget_other_versions(&mut warnings, &reactor.under(selection, &patch, &|_| false)); + let mut made: Vec = Vec::new(); + let edits = reactor.settle_properties(edits, c, &mut made, &mut plan.notes); + let mut texts: BTreeMap = edits + .into_iter() + .filter(|(_, edits)| !edits.is_empty()) + .map(|(rel, edits)| { + let text = apply_edits(&reactor.poms[&rel].doc.text, edits); + (rel, text) + }) + .collect(); + + // The pins: where a module selects the base version and no declaration + // wires it yet. + let rewritten = Reactor::discover_for(&reading(&texts, read), list, true)?; + let under = rewritten.under(selection, &patch, &|module| { + rewritten.wired_without_pin(module, c) + }); + let closed = |rel: &String| unpinned.contains(rel) || managed_roots.contains(rel); + let (pins, held) = place_pins(&reactor, &patch, Some(&under), &closed, &mut warnings); + for rel in &rewritten.scope { + let doc = &rewritten.poms[rel].doc; + let (pinned, held) = (pins.contains(rel), held.contains(rel)); + let (text, kind) = match pin_of(doc, &patch) { + Some(pin) if !pinned && !held => { + let gav = pin.gav.clone(); + let Some(text) = cut_pins(&doc.text, &|pin| pin.gav == gav) else { + continue; + }; + (text, HostedEditKind::PinRemoved) + } + Some(pin) if pin.uuid == c.uuid => continue, + Some(pin) => ( + apply_edits(&doc.text, vec![pin_update(doc, &pin, &patch)]), + HostedEditKind::PinMoved, + ), + None if pinned && !held => ( + apply_edits(&doc.text, vec![pin_edit(doc, &patch, &sv).0]), + HostedEditKind::Pin, + ), + None => continue, + }; + texts.insert(rel.clone(), text); + made.push(HostedEdit { + rel: rel.clone(), + kind, + original: None, + property: None, + }); + } + + // No edit that could not be taken back exactly. + for (rel, text) in std::mem::take(&mut texts) { + let before = &reactor.poms[&rel].doc.text; + let undone = unwire_hosted(&text, c, true, true); + if undone.is_ok() && undone == unwire_hosted(before, c, true, true) { + texts.insert(rel, text); + continue; + } + made.retain(|edit| edit.rel != rel); + plan.notes.push(( + "edit_not_reversible".to_string(), + format!( + "{rel}: the pin of {g}:{a}:{base} could not be removed again without a trace \ + (an empty or one-line , or a version that cannot be \ + recorded); {rel} was left as it is" + ), + )); + } + + let wired = Reactor::discover_for(&reading(&texts, read), list, true)?; + plan.wired = wired.wires(c); + for rel in &wired.scope { + let root = wired.local_root(rel); + if wired.poms[rel].doc.masked.contains(&sv) && !plan.roots.contains(&root) { + plan.roots.push(root); + } + } + plan.notes + .extend(warnings.into_iter().filter_map(|warning| { + let (reason, detail) = warning.detail.strip_prefix("reason: ")?.split_once(": ")?; + Some((reason.to_string(), detail.to_string())) + })); + plan.poms = texts + .into_iter() + .filter(|(rel, text)| *text != reactor.poms[rel].doc.text) + .collect(); + plan.edits = made + .into_iter() + .filter(|edit| plan.poms.contains_key(&edit.rel)) + .collect(); + Ok(plan) +} + +/// `texts` over `read`: the project as it reads once `texts` are written. +fn reading<'a>( + texts: &'a BTreeMap, + read: ReadFn<'a>, +) -> impl Fn(&str) -> Option> + 'a { + move |rel| match texts.get(rel) { + Some(text) => Some(text.clone().into_bytes()), + None => read(rel), + } +} + +/// `text` when it is one `${name}` reference and nothing else: the name. +fn sole_reference(text: &str) -> Option<&str> { + let name = text.trim().strip_prefix("${")?.strip_suffix('}')?; + (!name.is_empty() && !name.contains(['$', '{', '}'])).then_some(name) +} + +/// Whether `text` can be recorded in an XML comment and read back as it +/// is: no `--`, no markup, on one line. +fn recordable(text: &str) -> bool { + !text.is_empty() + && text.trim() == text + && !text.contains("--") + && !text.ends_with('-') + && !text.contains(['<', '>', '\n', '\r']) +} + +impl Reactor { + /// Whether `module` builds `c`'s suffixed version with no pin: from a + /// declaration it makes or inherits, or from the project's own + /// management nearest on its chain. A pin changes nothing for such a + /// module, so it has no say in where the pins go; one that a pin alone + /// wires still has, or a pin that came to move it would never be seen. + fn wired_without_pin(&self, module: &str, c: &Coords<'_>) -> bool { + let sv = c.suffixed_version(); + let resolve = |v: &str| self.interpolate(module, v); + let names = |doc: &Doc, dep: usize| { + doc.is_main_jar(dep) + && doc.pin_at(dep).is_none() + && doc.coordinate(dep, "groupId", &resolve).as_deref() == Some(c.group_id) + && doc.coordinate(dep, "artifactId", &resolve).as_deref() == Some(c.artifact_id) + }; + let reads = |doc: &Doc, dep: usize| doc.coordinate(dep, "version", &resolve); + let declared = self.chain(module).any(|p| { + let doc = &self.poms[p].doc; + doc.declarations().into_iter().any(|dep| { + doc.section_of(dep) == "dependencies" + && names(doc, dep) + && reads(doc, dep).as_deref() == Some(sv.as_str()) + }) + }); + declared + || self + .chain(module) + .find_map(|p| { + let doc = &self.poms[p].doc; + doc.declarations() + .into_iter() + .find(|&dep| doc.is_top_level_managed(dep) && names(doc, dep)) + .map(|dep| reads(doc, dep)) + }) + .flatten() + .as_deref() + == Some(sv.as_str()) + } + + /// Whether every reactor module that reads the declaration `dep` of + /// `rel` (the module itself, and each module inheriting its pom) + /// selects the base version of `c`: the declaration then reads it in + /// each, whatever defines its `${...}` version outside the checkout. + /// Only a declaration Maven always reads as the module's own direct + /// dependency is told this way: a managed entry, or one in a profile, + /// decides nothing on its own. + fn readers_select( + &self, + rel: &str, + dep: usize, + selection: &MavenSelection, + c: &Coords<'_>, + ) -> bool { + if self.poms[rel].doc.section_of(dep) != "dependencies" { + return false; + } + let mut readers = std::iter::once(rel) + .chain(self.inheritors(rel)) + .filter(|reader| self.reactor.iter().any(|module| module == reader)) + .peekable(); + readers.peek().is_some() + && readers.all(|reader| { + selection.verdict(reader, c.group_id, c.artifact_id, c.version) == Verdict::Selected + }) + } + + /// The one top-level `` entry of the scope that defines + /// `name`, when rewriting its value reaches the declarations that read + /// it and nothing else can redefine it: its pom, the span of its value + /// and the value (the base version, or an earlier patch's suffixed + /// one). `None` when a profile, the command line or the project model + /// defines the name too, or two poms do. + fn property_site(&self, name: &str, base: &str) -> Option<(String, Range)> { + if self.cli_props.contains_key(name) { + return None; + } + let mut site = None; + for rel in &self.scope { + let pom = &self.poms[rel]; + let in_profile = pom + .profile_props + .iter() + .any(|(_, props)| props.contains_key(name)); + if in_profile || self.model_ref(rel, name).is_some() { + return None; + } + let doc = &pom.doc; + let Some(properties) = doc.child(doc.project, "properties") else { + continue; + }; + let mut defined = doc.nodes[properties] + .children + .iter() + .copied() + .filter(|&n| doc.nodes[n].name == name); + let Some(node) = defined.next() else { + continue; + }; + let span = doc.value_span(node); + let literal = doc.text[span.clone()] == doc.text_of(node); + if defined.next().is_some() + || site.is_some() + || !literal + || !is_base_like(&doc.text[span.clone()], base) + { + return None; + } + site = Some((rel.clone(), span)); + } + site + } + + /// Decide how each `${...}` version among the planned version `edits` + /// is wired (the module docs): the property's own value where every + /// reference to it is one of these declarations, else the literal + /// suffixed version with the replaced text recorded beside it. The + /// edits to write, with what was done in `made` and what was not in + /// `notes`. + fn settle_properties( + &self, + mut edits: BTreeMap>, + c: &Coords<'_>, + made: &mut Vec, + notes: &mut Vec<(String, String)>, + ) -> BTreeMap> { + let sv = c.suffixed_version(); + let ga = format!("{}:{}", c.group_id, c.artifact_id); + // The versions that are one property reference, by its name. + let mut by_name: BTreeMap> = BTreeMap::new(); + for (rel, file_edits) in &edits { + let text = &self.poms[rel].doc.text; + for edit in file_edits { + if let Some(name) = sole_reference(&text[edit.start..edit.end]) { + *by_name + .entry(name.to_string()) + .or_default() + .entry(rel.clone()) + .or_default() += 1; + } + } + } + // A property only these declarations read is rewritten itself. + let mut rewritten: BTreeSet = BTreeSet::new(); + for (name, uses) in &by_name { + let reference = format!("${{{name}}}"); + let only_these = self.scope.iter().all(|rel| { + self.poms[rel].doc.text.matches(&reference).count() + == uses.get(rel).copied().unwrap_or(0) + }); + let Some((rel, span)) = self.property_site(name, c.version).filter(|_| only_these) + else { + continue; + }; + let was = self.poms[&rel].doc.text[span.clone()].to_string(); + edits + .entry(rel.clone()) + .or_default() + .push(Edit::plain(span.start, span.end, &sv)); + made.push(HostedEdit { + rel, + kind: HostedEditKind::Property, + original: (was == c.version).then_some(was), + property: Some(name.clone()), + }); + rewritten.insert(name.clone()); + } + for (rel, file_edits) in edits.iter_mut() { + let doc = &self.poms[rel].doc; + let mut kept = Vec::new(); + for edit in std::mem::take(file_edits) { + let Role::Version { original, .. } = &edit.role else { + kept.push(edit); + continue; + }; + let was = &doc.text[edit.start..edit.end]; + if sole_reference(was).is_some_and(|name| rewritten.contains(name)) { + continue; + } + let at = format!("{rel}:{}", doc.line_of(edit.start)); + if !was.contains("${") { + made.push(HostedEdit { + rel: rel.clone(), + kind: HostedEditKind::Version, + original: original.clone(), + property: None, + }); + kept.push(edit); + continue; + } + // The literal, with the text it replaces recorded right + // after the element. + let rest = &doc.masked[edit.end..]; + let close = rest.len() - rest.trim_start().len(); + let after = edit.end + close + "".len(); + let recorded = doc.text[after.min(doc.text.len())..].starts_with(ORIGINAL_TAG); + if original.is_none() + || !recordable(was) + || !rest[close..].starts_with("") + || recorded + { + notes.push(( + "property_unresolved".to_string(), + format!( + "{at}: {ga} version {was} cannot be replaced and recorded; left as \ + is, probably unpatched" + ), + )); + continue; + } + made.push(HostedEdit { + rel: rel.clone(), + kind: HostedEditKind::Version, + original: Some(was.to_string()), + property: None, + }); + kept.push(Edit::plain( + after, + after, + &format!("{ORIGINAL_TAG}{was}{COMMENT_CLOSE}"), + )); + kept.push(edit); + } + *file_edits = kept; + } + edits + } +} + +/// `text` without the pins `mine` accepts, each cut by its lines, and +/// without the `` section once those pins were all +/// it held; `None` when there is no such pin or `text` is not a pom. +fn cut_pins(text: &str, mine: &dyn Fn(&Pin) -> bool) -> Option { + let doc = Doc::parse(text.to_string()).ok()?; + let mut pins: Vec = doc + .declarations() + .into_iter() + .filter_map(|dep| doc.pin_at(dep)) + .filter(|pin| mine(pin)) + .collect(); + if pins.is_empty() { + return None; + } + pins.sort_by_key(|pin| std::cmp::Reverse(pin.start)); + let mut out = text.to_string(); + for pin in pins { + out.replace_range(pin.start..pin.end, ""); + } + Some(without_empty_management(&out).unwrap_or(out)) +} + +/// `text` without its top-level `` when that holds +/// one `` and no entry, comment or text at all: the section +/// a pin created, once the pin is cut. +fn without_empty_management(text: &str) -> Option { + let doc = Doc::parse(text.to_string()).ok()?; + let dm = doc.child(doc.project, "dependencyManagement")?; + let [deps] = doc.nodes[dm].children[..] else { + return None; + }; + let (dm, deps) = (&doc.nodes[dm], &doc.nodes[deps]); + let blank = |range: Range| text[range].trim().is_empty(); + if deps.name != "dependencies" + || deps.inner_start == deps.end + || !deps.children.is_empty() + || !blank(deps.inner_start..deps.inner_end) + || !blank(dm.inner_start..deps.start) + || !blank(deps.end..dm.inner_end) + { + return None; + } + let (start, end) = line_span(text, dm.start, dm.end); + Some(format!("{}{}", &text[..start], &text[end..])) +} + +/// `text` (one pom) without the hosted wiring of the patch `c` that +/// [`plan_hosted`] writes: its pin, a `${...}` version put back from the +/// comment that records it, and a property holding the suffixed version +/// back at the base version. `literals` also puts every other declaration +/// of the artifact at the suffixed version back at the base version: the +/// caller leaves them out for a pom an earlier release may have pinned, +/// whose own entry is told from a rewritten one by other means. +/// `any_patch` takes out the wiring of every patch of `c`'s version, not +/// `c`'s alone. The `` is not touched. +pub fn unwire_hosted( + text: &str, + c: &Coords<'_>, + any_patch: bool, + literals: bool, +) -> Result { + let gav = format!("{}:{}:{}", c.group_id, c.artifact_id, c.version); + let sv = c.suffixed_version(); + let ours = |version: &str| match any_patch { + true => version != c.version && is_base_like(version, c.version), + false => version == sv, + }; + let with_pins = cut_pins(text, &|pin| { + pin.gav == gav && (any_patch || pin.uuid == c.uuid) + }); + let text = with_pins.as_deref().unwrap_or(text); + let doc = Doc::parse(text.to_string())?; + let mut edits = Vec::new(); + for dep in doc.declarations() { + let Some(version) = doc.child(dep, "version") else { + continue; + }; + let named = |name: &str, want: &str| { + doc.child_text(dep, name) + .is_some_and(|text| text == want || text.contains("${")) + }; + if !ours(&doc.text_of(version)) + || !named("groupId", c.group_id) + || !named("artifactId", c.artifact_id) + { + continue; + } + let span = doc.value_span(version); + let after = doc.nodes[version].end; + let recorded = text[after..].strip_prefix(ORIGINAL_TAG).and_then(|rest| { + let len = rest.find(COMMENT_CLOSE)?; + Some(( + &rest[..len], + after + ORIGINAL_TAG.len() + len + COMMENT_CLOSE.len(), + )) + }); + match recorded { + Some((was, end)) => { + edits.push(Edit::plain(span.start, span.end, was)); + edits.push(Edit::plain(after, end, "")); + } + None if literals => edits.push(Edit::plain(span.start, span.end, c.version)), + None => {} + } + } + let models = + std::iter::once(doc.project).chain((0..doc.nodes.len()).filter(|&n| doc.is_profile(n))); + for model in models { + let Some(properties) = doc.child(model, "properties") else { + continue; + }; + for &property in &doc.nodes[properties].children { + let span = doc.value_span(property); + if ours(&doc.text[span.clone()]) { + edits.push(Edit::plain(span.start, span.end, c.version)); + } + } + } + Ok(apply_edits(text, edits)) +} + +/// Read the reactor as [`plan_hosted`] reads it; `false` when it cannot be +/// read from what `read` returned. For a caller that learns from `read` +/// which files the planner takes. +pub fn readable_for_hosted(read: ReadFn<'_>, list: ListFn<'_>) -> bool { + Reactor::discover_for(read, list, true).is_ok() +} + +/// One artifact some pom of a reactor builds at a Socket suffixed version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HostedSite { + pub group: String, + pub artifact: String, + /// `-socket.`. + pub suffixed: String, + /// The patch uuid a pin's comment names, when a pin carries it. + pub uuid: Option, + /// Every pom that names the suffixed version outside comments: a + /// declaration, a pin, or a property a declaration reads. + pub rels: BTreeSet, +} + +/// The artifacts the reactor's poms build at a Socket suffixed version, +/// read as Maven reads them (a `${...}` through the properties of the +/// declaring pom's chain), with the poms that name each. Declarations +/// inside `` are not read: Maven reads those only while their +/// profile is active. +pub fn hosted_sites(read: ReadFn<'_>, list: ListFn<'_>) -> Result, JvmRefusal> { + let reactor = Reactor::discover_for(read, list, true)?; + let mut sites: BTreeMap<(String, String, String), Option> = BTreeMap::new(); + for rel in &reactor.scope { + let doc = &reactor.poms[rel].doc; + let resolve = |v: &str| reactor.interpolate(rel, v); + for dep in doc.declarations() { + if doc.section_of(dep).starts_with("profile:") || !doc.is_main_jar(dep) { + continue; + } + let (Some(group), Some(artifact), Some(version)) = ( + doc.coordinate(dep, "groupId", &resolve), + doc.coordinate(dep, "artifactId", &resolve), + doc.coordinate(dep, "version", &resolve), + ) else { + continue; + }; + if split_socket_version(&version).is_none() { + continue; + } + let uuid = doc.pin_at(dep).map(|pin| pin.uuid); + let tagged = sites.entry((group, artifact, version)).or_default(); + if tagged.is_none() { + *tagged = uuid; + } + } + } + Ok(sites + .into_iter() + .map(|((group, artifact, suffixed), uuid)| HostedSite { + rels: reactor + .scope + .iter() + .filter(|rel| reactor.poms[*rel].doc.masked.contains(&suffixed)) + .cloned() + .collect(), + group, + artifact, + suffixed, + uuid, + }) + .collect()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs new file mode 100644 index 000000000..cc4329633 --- /dev/null +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs @@ -0,0 +1,561 @@ +use super::*; + +const G: &str = "org.x"; +const A: &str = "victim"; +const BASE: &str = "1.10.0"; +const UUID: &str = "4d5e6f70-8192-4a3b-9c4d-5e6f708192a3"; +const SV: &str = "1.10.0-socket.4d5e6f70"; +const TAG: &str = ""; + +type Fs = BTreeMap; + +fn coords() -> Coords<'static> { + Coords { + group_id: G, + artifact_id: A, + version: BASE, + uuid: UUID, + } +} + +fn fs(files: &[(&str, &str)]) -> Fs { + files + .iter() + .map(|(rel, text)| (rel.to_string(), text.to_string())) + .collect() +} + +fn dep(artifact: &str, version: Option<&str>) -> String { + let version = version.map_or(String::new(), |v| format!("\n {v}")); + format!( + " \n {G}\n \ + {artifact}{version}\n \n" + ) +} + +/// The reactor root `t:root:1` over the modules `a` and `b`, with `body`. +fn root(body: &str) -> String { + format!( + "\n 4.0.0\n t\n \ + root\n 1\n \ + pom\n \n a\n \ + b\n \n{body}\n" + ) +} + +/// The module `name` of [`root`], declaring `deps`. +fn module(name: &str, deps: &str) -> String { + format!( + "\n 4.0.0\n \n \ + t\n root\n \ + 1\n \n {name}\n \ + \n{deps} \n\n" + ) +} + +/// A pom on its own (no modules, no parent in the checkout), with `body`. +fn single(body: &str) -> String { + format!( + "\n 4.0.0\n t\n \ + app\n 1\n{body}\n" + ) +} + +fn deps(list: &str) -> String { + format!(" \n{list} \n") +} + +fn properties(list: &[(&str, &str)]) -> String { + let entries: String = list + .iter() + .map(|(name, value)| format!(" <{name}>{value}\n")) + .collect(); + format!(" \n{entries} \n") +} + +/// What each module of `files` selects for the victim: its base version, +/// another one, or why it cannot be told; a module left out does not +/// resolve it. +fn selecting(files: &Fs, picks: &[(&str, Result<&str, &str>)]) -> MavenSelection { + let modules: Vec<&str> = files + .keys() + .map(String::as_str) + .filter(|rel| rel.ends_with("pom.xml")) + .collect(); + let picks: Vec<_> = picks + .iter() + .map(|(pom, pick)| (*pom, G, A, *pick)) + .collect(); + MavenSelection::answering(&modules, &picks) +} + +fn planned(files: &Fs, selection: Option<&MavenSelection>) -> HostedPlan { + let read = |rel: &str| files.get(rel).map(|text| text.clone().into_bytes()); + let list = |dir: &str| { + let bytes: BTreeMap> = files + .iter() + .map(|(rel, text)| (rel.clone(), text.clone().into_bytes())) + .collect(); + crate::vendor::jvm::testing::list_of(&bytes, dir) + }; + plan_hosted(&read, &list, &coords(), selection).expect("a plan") +} + +fn written(files: &Fs, plan: &HostedPlan) -> Fs { + let mut out = files.clone(); + out.extend(plan.poms.clone()); + out +} + +/// Every pom of `after` unwired again, which must be `before`. +fn assert_unwires_to(after: &Fs, before: &Fs) { + for (rel, text) in after { + assert_eq!( + unwire_hosted(text, &coords(), false, true).as_deref(), + Ok(before[rel].as_str()), + "{rel}" + ); + } +} + +fn kinds(plan: &HostedPlan) -> Vec<(&str, HostedEditKind)> { + plan.edits + .iter() + .map(|edit| (edit.rel.as_str(), edit.kind)) + .collect() +} + +fn reasons(plan: &HostedPlan) -> Vec<&str> { + plan.notes + .iter() + .map(|(reason, _)| reason.as_str()) + .collect() +} + +/// Two modules reach the victim through other libraries: `a` resolves the +/// patch's version, `b` a newer one. The pin goes in `a` alone, so `b` +/// keeps what it resolves, and the repository goes in the root both +/// inherit. +#[test] +fn a_pin_goes_in_the_module_that_selects_the_version_and_no_other() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let selection = selecting( + &files, + &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok("1.11.0"))], + ); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("a/pom.xml", HostedEditKind::Pin)]); + assert!(plan.wired); + assert_eq!(plan.roots, ["pom.xml"]); + let a = &plan.poms["a/pom.xml"]; + assert!( + a.contains(&format!( + " \n \n {TAG}\n \n \ + {G}\n {A}\n \ + {SV}\n \n \n \ + \n " + )), + "{a}" + ); + let after = written(&files, &plan); + assert_unwires_to(&after, &files); + // A second run changes nothing, whatever it is told. + for told in [Some(&selection), None] { + let again = planned(&after, told); + assert!( + again.poms.is_empty() && again.edits.is_empty(), + "{:?}", + again.edits + ); + assert!(again.wired); + } +} + +/// Every module selects the version: one pin in the pom they all inherit. +#[test] +fn modules_that_all_select_the_version_are_pinned_in_their_parent() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let selection = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Pin)]); + assert_unwires_to(&written(&files, &plan), &files); +} + +/// A declaration that names the version is rewritten where it stands, and +/// a module it wires needs no pin: nothing but that one version changes. +#[test] +fn a_declaration_of_the_version_is_rewritten_and_needs_no_pin() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep(A, Some(BASE)))), + ("b/pom.xml", &module("b", &dep(A, Some("1.11.0")))), + ]); + let selection = selecting( + &files, + &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok("1.11.0"))], + ); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("a/pom.xml", HostedEditKind::Version)]); + assert_eq!(plan.edits[0].original.as_deref(), Some(BASE)); + assert_eq!( + plan.poms["a/pom.xml"], + files["a/pom.xml"].replace(BASE, SV), + "only the version text changes" + ); + assert!(reasons(&plan).is_empty(), "{:?}", plan.notes); + assert_unwires_to(&written(&files, &plan), &files); + // The declaration is rewritten whatever Maven selects elsewhere, since + // that replaces a version where it stands. + let unread = planned(&files, None); + assert_eq!(kinds(&unread), [("a/pom.xml", HostedEditKind::Version)]); +} + +/// A property only the patched artifact's declarations read is rewritten +/// itself: the declarations keep their `${...}` text. +#[test] +fn a_property_only_the_artifact_reads_is_rewritten_itself() { + let files = fs(&[ + ("pom.xml", &root(&properties(&[("victim.version", BASE)]))), + ( + "a/pom.xml", + &module("a", &dep(A, Some("${victim.version}"))), + ), + ( + "b/pom.xml", + &module("b", &dep(A, Some("${victim.version}"))), + ), + ]); + let selection = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Property)]); + assert_eq!(plan.edits[0].property.as_deref(), Some("victim.version")); + assert_eq!(plan.edits[0].original.as_deref(), Some(BASE)); + assert_eq!( + plan.poms["pom.xml"], + files["pom.xml"].replace( + "1.10.0", + &format!("{SV}") + ) + ); + assert!(plan.wired); + let after = written(&files, &plan); + assert_unwires_to(&after, &files); + let again = planned(&after, Some(&selection)); + assert!(again.poms.is_empty() && again.wired, "{:?}", again.edits); +} + +/// A property a sibling artifact reads too is left alone: the one +/// declaration takes the literal, and the text it replaced is recorded +/// right after it. +#[test] +fn a_property_a_sibling_reads_is_left_alone() { + let shared = format!( + "{}{}", + dep(A, Some("${lib.version}")), + dep("sibling", Some("${lib.version}")) + ); + let files = fs(&[( + "pom.xml", + &single(&format!( + "{}{}", + properties(&[("lib.version", BASE)]), + deps(&shared) + )), + )]); + let selection = selecting(&files, &[("pom.xml", Ok(BASE))]); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Version)]); + assert_eq!(plan.edits[0].original.as_deref(), Some("${lib.version}")); + let pom = &plan.poms["pom.xml"]; + assert_eq!( + *pom, + files["pom.xml"].replacen( + "${lib.version}", + &format!("{SV}"), + 1 + ) + ); + assert!( + pom.contains("1.10.0") + && pom.contains( + "sibling\n ${lib.version}" + ), + "the property and the sibling are untouched: {pom}" + ); + let after = written(&files, &plan); + assert_unwires_to(&after, &files); + let again = planned(&after, Some(&selection)); + assert!(again.poms.is_empty() && again.wired, "{:?}", again.edits); +} + +/// A property no pom of the checkout defines (a parent resolved from a +/// repository does): what it reads is what Maven selects for the module +/// that declares it. Certain, the declaration takes the literal with its +/// text recorded; not certain, it is left as it is. +#[test] +fn a_property_of_a_parent_outside_the_checkout_follows_the_selection() { + let parent = + " \n corp\n parent\n \ + 7\n \n \n"; + let files = fs(&[( + "pom.xml", + &single(&format!( + "{parent}{}", + deps(&dep(A, Some("${corp.victim.version}"))) + )), + )]); + let plan = planned(&files, Some(&selecting(&files, &[("pom.xml", Ok(BASE))]))); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Version)]); + assert!( + plan.poms["pom.xml"].contains(&format!( + "{SV}" + )), + "{}", + plan.poms["pom.xml"] + ); + assert_unwires_to(&written(&files, &plan), &files); + + for doubt in [ + Some(selecting( + &files, + &[("pom.xml", Err("a pom is not cached"))], + )), + Some(selecting(&files, &[("pom.xml", Ok("1.11.0"))])), + None, + ] { + let plan = planned(&files, doubt.as_ref()); + assert!(plan.poms.is_empty() && !plan.wired, "{:?}", plan.edits); + if plan.not_selected.is_none() { + assert!( + reasons(&plan).contains(&"property_unresolved"), + "{:?}", + plan.notes + ); + } + } +} + +/// A version-less declaration a parent outside the checkout manages (the +/// usual Spring Boot shape): no declaration is touched, the pin goes in +/// the project's own management. +#[test] +fn a_version_managed_outside_the_checkout_is_pinned_not_rewritten() { + let files = fs(&[("pom.xml", &single(&deps(&dep(A, None))))]); + let plan = planned(&files, Some(&selecting(&files, &[("pom.xml", Ok(BASE))]))); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Pin)]); + assert!(plan.wired); + assert_unwires_to(&written(&files, &plan), &files); +} + +/// No module of the build selects the version: nothing is planned, and +/// the plan says what is selected instead. +#[test] +fn a_version_no_module_selects_is_not_planned() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let selection = selecting( + &files, + &[("a/pom.xml", Ok("1.11.0")), ("b/pom.xml", Ok("1.9"))], + ); + let plan = planned(&files, Some(&selection)); + assert_eq!( + plan.not_selected, + Some(vec!["1.9".to_string(), "1.11.0".to_string()]) + ); + assert!(plan.poms.is_empty() && plan.edits.is_empty() && !plan.wired); +} + +/// A module whose selection cannot be told gets no pin (a pin there would +/// be a guess), and the one beside it that is certain still gets its own. +#[test] +fn an_undetermined_module_is_not_pinned_and_its_sibling_is() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let selection = selecting( + &files, + &[ + ("a/pom.xml", Ok(BASE)), + ("b/pom.xml", Err("lib-y:1.0 is not cached")), + ], + ); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("a/pom.xml", HostedEditKind::Pin)]); + assert_eq!(reasons(&plan), ["selection_undetermined"]); + + // Told nothing at all, nothing is pinned. + let unread = planned(&files, None); + assert!( + unread.poms.is_empty() && !unread.wired, + "{:?}", + unread.edits + ); + assert_eq!(reasons(&unread), ["selection_undetermined"]); +} + +/// A pin that now reaches a module resolving another version is taken out +/// again (it would hold that module back), leaving the pom as it was +/// before the pin. +#[test] +fn a_pin_that_would_move_a_module_is_taken_out() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let both = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let pinned = written(&files, &planned(&files, Some(&both))); + assert!(pinned["pom.xml"].contains(TAG)); + + let moved = selecting( + &pinned, + &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok("1.11.0"))], + ); + let plan = planned(&pinned, Some(&moved)); + assert_eq!( + kinds(&plan), + [ + ("pom.xml", HostedEditKind::PinRemoved), + ("a/pom.xml", HostedEditKind::Pin) + ] + ); + assert_eq!(plan.poms["pom.xml"], files["pom.xml"]); + assert_unwires_to(&written(&pinned, &plan), &files); +} + +/// A pin of an earlier patch of the same version moves to this patch +/// where it stands. +#[test] +fn a_pin_of_an_earlier_patch_moves_to_this_one() { + let files = fs(&[("pom.xml", &single(&deps(&dep(A, None))))]); + let selection = selecting(&files, &[("pom.xml", Ok(BASE))]); + let pinned = written(&files, &planned(&files, Some(&selection))); + let earlier = fs(&[( + "pom.xml", + &pinned["pom.xml"] + .replace(UUID, "0a1b2c3d-8192-4a3b-9c4d-5e6f708192a3") + .replace(SV, "1.10.0-socket.0a1b2c3d"), + )]); + let plan = planned(&earlier, Some(&selection)); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::PinMoved)]); + assert_eq!(plan.poms["pom.xml"], pinned["pom.xml"]); +} + +/// An edit that could not be taken back exactly is not made: a pin in a +/// `` that holds nothing would leave the section +/// changed (or gone) once removed. +#[test] +fn a_pin_that_could_not_be_removed_without_a_trace_is_not_written() { + for management in [ + " \n", + " \n", + " \n \n \n \ + \n", + ] { + let files = fs(&[( + "pom.xml", + &single(&format!("{management}{}", deps(&dep(A, None)))), + )]); + let plan = planned(&files, Some(&selecting(&files, &[("pom.xml", Ok(BASE))]))); + assert!( + plan.poms.is_empty() && !plan.wired, + "{management}: {:?}", + plan.poms + ); + assert_eq!(reasons(&plan), ["edit_not_reversible"], "{management}"); + } +} + +/// Unwiring takes out one patch's wiring and leaves another's, and leaves +/// a plain suffixed declaration to the caller when asked to. +#[test] +fn unwiring_takes_out_only_what_it_is_asked_for() { + let files = fs(&[( + "pom.xml", + &single(&format!( + "{}{}", + properties(&[("lib.version", BASE)]), + deps(&format!( + "{}{}", + dep(A, Some("${lib.version}")), + dep("sibling", Some("${lib.version}")) + )) + )), + )]); + let selection = selecting(&files, &[("pom.xml", Ok(BASE))]); + let after = written(&files, &planned(&files, Some(&selection))); + let other = Coords { + uuid: "0a1b2c3d-8192-4a3b-9c4d-5e6f708192a3", + ..coords() + }; + assert_eq!( + unwire_hosted(&after["pom.xml"], &other, false, true).as_deref(), + Ok(after["pom.xml"].as_str()) + ); + assert_eq!( + unwire_hosted(&after["pom.xml"], &other, true, true).as_deref(), + Ok(files["pom.xml"].as_str()) + ); + + let literal = single(&deps(&dep(A, Some(SV)))); + assert_eq!( + unwire_hosted(&literal, &coords(), false, false).as_deref(), + Ok(literal.as_str()) + ); + assert_eq!( + unwire_hosted(&literal, &coords(), false, true), + Ok(literal.replace(SV, BASE)) + ); +} + +/// What the poms build at a suffixed version is found wherever it is +/// wired: a declaration, a property a declaration of another pom reads, +/// or a pin, which names its patch. +#[test] +fn the_wiring_of_a_reactor_is_found_in_every_pom_that_carries_it() { + let files = fs(&[ + ("pom.xml", &root(&properties(&[("victim.version", BASE)]))), + ( + "a/pom.xml", + &module("a", &dep(A, Some("${victim.version}"))), + ), + ("b/pom.xml", &module("b", &dep(A, Some(BASE)))), + ]); + let selection = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let after = written(&files, &planned(&files, Some(&selection))); + let sites = |files: &Fs| { + let read = |rel: &str| files.get(rel).map(|text| text.clone().into_bytes()); + hosted_sites(&read, &|_| Vec::new()).unwrap() + }; + let site = |uuid: Option<&str>, rels: &[&str]| HostedSite { + group: G.to_string(), + artifact: A.to_string(), + suffixed: SV.to_string(), + uuid: uuid.map(str::to_string), + rels: rels.iter().map(|rel| rel.to_string()).collect(), + }; + assert_eq!( + sites(&after), + [site(None, &["b/pom.xml", "pom.xml"])], + "the property in the root, the declaration in b: {after:#?}" + ); + assert!(sites(&files).is_empty()); + + let pinned = fs(&[("pom.xml", &single(&deps(&dep(A, None))))]); + let selection = selecting(&pinned, &[("pom.xml", Ok(BASE))]); + let pinned = written(&pinned, &planned(&pinned, Some(&selection))); + assert_eq!(sites(&pinned), [site(Some(UUID), &["pom.xml"])]); +} From 9b79a5dd61555615528d04a5f3fb93a36635d03e Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 04:55:38 -0500 Subject: [PATCH 10/18] Find and restore hosted Maven pins in every pom of a reactor Discovery read only the root pom.xml, and restore only undid a pin there: a pin in a module pom was invisible to `list`, `vex`, `rollback` and `remove`, and a reactor root's pin was withheld from `vex` whatever the modules did. Discovery now reads a reactor whole (the poms the reactor planner reads, asked until it asks for nothing new): a pin's comment names its patch, any other suffixed version is tied to a `socket-patch-` repository by its 8-hex suffix as before, and a `${property}` version is read through the properties of the declaring pom's chain. Every pom that carries part of the wiring (the pin, a rewritten declaration, the property, the repository) is a file of the ref. The patch is attested by the rule vendored mode uses: no declaration may still build the base version, and every module that resolves it, or may, is reached by a pin or a declaration of the patch. What Maven selects is read from the local Maven repository, on disk only. A reactor whose poms cannot all be read falls back to its root pom, whose pin stays a ref and is not attested, as before. Restore undoes a pin in every pom discovery found it in, or in none: the planner's edits through `unwire_hosted` (the tagged pin, the recorded `${...}` version, the property), the `` in whichever pom declares it, and the `.mvn` files at the project root. A suffixed declaration in a reactor, or in a pom that carries one of the planner's marks, is a rewritten one and gets its base version back; only a single pom with no mark is read as an earlier release wrote it, where an added `` entry is told from a rewritten one by its shape. A project's own management entry that happens to have that shape is therefore no longer removed in a reactor. Co-Authored-By: Claude Fable 5.2 --- .../src/patch/redirect/upstream/maven.rs | 620 +++++++++++++----- .../src/vendor/jvm/maven_reactor.rs | 28 +- .../src/vendor/jvm/maven_reactor/hosted.rs | 18 +- .../src/vex/discover/maven.rs | 530 ++++++++++++++- 4 files changed, 998 insertions(+), 198 deletions(-) diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs index c7011a609..6afdcd8e5 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs @@ -7,6 +7,15 @@ //! trusted-checksums resolver lines to `.mvn/maven.config` and the //! suffixed jar/pom lines to `.mvn/checksums/checksums.sha256`. //! +//! In a reactor, and for a `${property}` version, the pins are the reactor +//! planner's (`maven_reactor::plan_hosted`), spread over the poms that +//! take them: a pin tagged with its patch uuid, a declaration with the +//! text it replaced recorded beside it, a property holding the suffixed +//! version. Each says what it replaced, and +//! [`unwire_hosted`](crate::vendor::jvm::maven_reactor::unwire_hosted) +//! puts it back, in every pom discovery found the pin in. What follows is +//! the single pom an earlier release pinned, which carries no such mark. +//! //! Everything but the `.mvn` provenance is derivable from the pom itself: //! the base version is the suffix's prefix, and the added blocks have the //! writer's exact shape. An added `` entry is told @@ -25,7 +34,7 @@ use std::collections::BTreeMap; use regex::Regex; -use super::{by_uuid, read_or_refuse, refuse_all_in, Ctx, FormatResult, HostedPin, View}; +use super::{by_uuid, read_or_refuse, Ctx, FormatResult, HostedPin, View}; use crate::formats::maven::trusted_checksums; use crate::patch::redirect::{ generation, maven_repositories_with_id, maven_tag_inner_range, maven_tag_text_in, @@ -138,51 +147,99 @@ fn dm_sections(pom: &str) -> Vec<(usize, usize)> { /// Remove the `socket-patch-` repository of `pom`: the element and /// the line break before it (the rewriter's own insertion), when it sits /// on lines of its own. -fn remove_repository(pom: &str, uuid: &str, ctx: &Ctx<'_>) -> Result { +fn remove_repository(rel: &str, pom: &str, uuid: &str, ctx: &Ctx<'_>) -> Result { let id = generation::hosted_pin_name(uuid); let (start, end) = match maven_repositories_with_id(pom, &id)[..] { [one] => one, - [] => return Err(format!("pom.xml has no with id {id}")), + [] => return Err(format!("{rel} has no with id {id}")), _ => { return Err(format!( - "pom.xml has several elements with id {id}" + "{rel} has several elements with id {id}" )) } }; let url = maven_tag_text_in(pom, "url", start, end).unwrap_or_default(); if ctx.hosted_uuid(&url).as_deref() != Some(uuid) { return Err(format!( - "the pom.xml repository {id} does not point at the Socket patch server" + "the {rel} repository {id} does not point at the Socket patch server" )); } remove_maven_repository(pom, &id) - .ok_or_else(|| format!("the pom.xml repository {id} is not on lines of its own")) + .ok_or_else(|| format!("the {rel} repository {id} is not on lines of its own")) +} + +/// What [`restore_pin`] took out of one pom. +struct Restored { + text: String, + /// The pin's `` was declared here. + repository: bool, + /// A pin, a declaration or a property of the patch was here. + wiring: bool, +} + +/// One pin and where it is restored. +struct PinIn<'a> { + group: &'a str, + artifact: &'a str, + base: &'a str, + uuid: &'a str, + /// The project root heads a reactor: its poms are the reactor + /// planner's to read, none an earlier release pinned. + reactor: bool, } -/// Restore one pin in `pom`, or say why not. +/// Restore one pin in the pom `rel` (`pom`), or say why not. fn restore_pin( + rel: &str, pom: &str, user_properties: &BTreeMap, - group: &str, - artifact: &str, - base: &str, - uuid: &str, + pin: &PinIn<'_>, ctx: &Ctx<'_>, -) -> Result { +) -> Result { + let PinIn { + group, + artifact, + base, + uuid, + reactor, + } = *pin; let suffixed = format!("{base}-socket.{}", &uuid[..8]); - let mut text = remove_repository(pom, uuid, ctx)?; + let coords = crate::vendor::jvm::Coords { + group_id: group, + artifact_id: artifact, + version: base, + uuid, + }; + let name = generation::hosted_pin_name(uuid); + let repository = !maven_repositories_with_id(pom, &name).is_empty(); + let mut text = match repository { + true => remove_repository(rel, pom, uuid, ctx)?, + false => pom.to_string(), + }; + // What the reactor planner wrote. A pom that carries none of its marks + // outside a reactor is one an earlier release may have pinned: there an + // added `` entry is told from a rewritten one + // below, by its shape; anywhere else every suffixed declaration is a + // rewritten one. + let unwire = |text: &str, literals: bool| { + crate::vendor::jvm::maven_reactor::unwire_hosted(text, &coords, false, literals) + .map_err(|why| format!("{rel} is not readable as a pom ({why})")) + }; + let marked = unwire(&text, false)?; + let legacy = !reactor && marked == text; + let unwired = match legacy { + true => marked, + false => unwire(&text, true)?, + }; + let mut wiring = unwired != text; + text = unwired; let scoped = crate::formats::maven::PomScope::with_user_properties(&text, user_properties) .and_then(|s| s.dependencies()); let matches = dep_matches(&text, scoped.as_deref().ok(), group, artifact); - if !matches + wiring |= matches .iter() - .any(|m| m.version_text.as_deref() == Some(suffixed.as_str())) - { - return Err(format!( - "pom.xml declares no {group}:{artifact} {suffixed}" - )); - } + .any(|m| m.version_text.as_deref() == Some(suffixed.as_str())); // The GA's suffixed literals where Maven reads them for the main jar: // not commented out, outside `` / `` / ``, // no classifier — the same scope the rewriter decides "transitive" by. @@ -253,30 +310,18 @@ fn restore_pin( let live = crate::formats::xml::blank_non_markup(&text).unwrap_or_else(|_| text.clone()); if live.contains(&suffixed) { return Err(format!( - "pom.xml still names {suffixed} outside a version (a property or \ - plugin configuration socket-patch did not write)" + "{rel} still names {suffixed} outside a version (a plugin \ + configuration or other text socket-patch did not write)" )); } - let name = generation::hosted_pin_name(uuid); if live.contains(&name) { - return Err(format!("pom.xml still names {name}")); + return Err(format!("{rel} still names {name}")); } - Ok(text) -} - -/// The `` directories a pom lists (plain relative paths only). -fn modules(pom: &str) -> Vec { - let re = Regex::new(r"\s*([^<]*?)\s*").expect("static module regex is valid"); - re.captures_iter(pom) - .map(|c| c[1].trim_end_matches('/').to_string()) - .filter(|m| { - !m.is_empty() - && !m.starts_with('/') - && !m.contains('\\') - && m.split('/') - .all(|seg| !seg.is_empty() && seg != "." && seg != "..") - }) - .collect() + Ok(Restored { + text, + repository, + wiring, + }) } pub(crate) async fn restore( @@ -285,116 +330,144 @@ pub(crate) async fn restore( files: &[String], ctx: &Ctx<'_>, ) -> FormatResult { + use crate::vendor::jvm::maven_reactor::{declares_modules, may_discover_subprojects}; let mut result = FormatResult::default(); let pins = by_uuid(pins); + // The poms as they are, and as they read once the pins so far are out. + let mut originals: BTreeMap = BTreeMap::new(); for rel in files { - let Some(original) = read_or_refuse(view, rel, &pins, &mut result).await else { + if let Some(text) = read_or_refuse(view, rel, &pins, &mut result).await { + originals.insert(rel.clone(), text); + } + } + let mut texts = originals.clone(); + // `.mvn/maven.config`'s `-D` user properties, which Maven reads over + // the pom's own when it interpolates a coordinate. + let config = view.read(MVN_CONFIG).await.ok().flatten(); + let user_properties = config + .as_deref() + .map(crate::formats::maven::maven_config_properties) + .unwrap_or_default(); + let reactor = view + .read("pom.xml") + .await + .ok() + .flatten() + .is_some_and(|root| { + declares_modules(&root) || may_discover_subprojects(&root, config.as_deref()) + }); + // Checksum-file path prefixes of the restored pins. + let mut checksum_dirs: Vec = Vec::new(); + let mut restored: Vec<&str> = Vec::new(); + for pin in pins.values() { + // A file that could not be read refused the pin above. + if pin.files.iter().any(|rel| !originals.contains_key(rel)) { + continue; + } + let Some((name, base)) = pin.name_version() else { + result.refuse(&pin.uuid, format!("{} is not a Maven purl", pin.purl)); continue; }; - let dir = rel - .rsplit_once('/') - .map(|(d, _)| format!("{d}/")) - .unwrap_or_default(); - let module_poms: Vec = modules(&original) - .into_iter() - .map(|m| { - if m.ends_with(".xml") { - format!("{dir}{m}") - } else { - format!("{dir}{m}/pom.xml") - } - }) - .collect(); - let mut text = original.clone(); - // `.mvn/maven.config`'s `-D` user properties, which Maven reads over - // the pom's own when it interpolates a coordinate. - let user_properties = match view.read(&format!("{dir}{MVN_CONFIG}")).await { - Ok(Some(config)) => crate::formats::maven::maven_config_properties(&config), - _ => BTreeMap::new(), + let Some((group, artifact)) = name.split_once('/') else { + result.refuse(&pin.uuid, format!("{} names no groupId", pin.purl)); + continue; }; - // Checksum-file path prefixes of the restored pins. - let mut checksum_dirs: Vec = Vec::new(); - let mut restored: Vec<&str> = Vec::new(); - for pin in pins.values().filter(|p| p.files.contains(rel)) { - let Some((name, base)) = pin.name_version() else { - result.refuse(&pin.uuid, format!("{} is not a Maven purl", pin.purl)); - continue; - }; - let Some((group, artifact)) = name.split_once('/') else { - result.refuse(&pin.uuid, format!("{} names no groupId", pin.purl)); - continue; - }; - if pin.uuid.len() < 8 { - result.refuse(&pin.uuid, format!("{} is not a patch uuid", pin.uuid)); - continue; - } - let suffixed = format!("{base}-socket.{}", &pin.uuid[..8]); - let mut in_module = None; - for module in &module_poms { - if let Ok(Some(child)) = view.read(module).await { - if child.contains(&suffixed) - || child.contains(&generation::hosted_pin_name(&pin.uuid)) - { - in_module = Some(module.clone()); - break; + if pin.uuid.len() < 8 { + result.refuse(&pin.uuid, format!("{} is not a patch uuid", pin.uuid)); + continue; + } + let suffixed = format!("{base}-socket.{}", &pin.uuid[..8]); + let of = PinIn { + group, + artifact, + base: &base, + uuid: &pin.uuid, + reactor, + }; + // Every pom the pin is wired in, or none: a pin refused in one of + // its poms is restored in none of them. + let mut staged: BTreeMap<&String, String> = BTreeMap::new(); + let (mut repository, mut wiring) = (false, false); + let mut refusal = None; + for rel in &pin.files { + let next = restore_pin(rel, &texts[rel], &user_properties, &of, ctx).and_then(|done| { + let mut text = done.text; + // The from-scratch wrappers, once emptied (repositories + // come last). + for empty in [EMPTY_REPOSITORIES, EMPTY_DEP_MANAGEMENT] { + if text.contains(empty) && !originals[rel].contains(empty) { + text = text.replacen(empty, "", 1); } } - } - if let Some(module) = in_module { - result.refuse( - &pin.uuid, - format!( - "the module pom {module} also pins {group}:{artifact} {suffixed}, and \ - socket-patch restores only the root {rel}" - ), - ); - continue; - } - match restore_pin( - &text, - &user_properties, - group, - artifact, - &base, - &pin.uuid, - ctx, - ) { - Ok(next) => { - text = next; - checksum_dirs.push(format!( - "{}/", - crate::vendor::jvm::layout::version_dir(group, artifact, &suffixed) - )); - restored.push(&pin.uuid); + crate::formats::maven::parse_pom(&text).map_err(|why| { + format!("restoring {rel} would not leave a readable pom: {why}") + })?; + repository |= done.repository; + wiring |= done.wiring; + Ok(text) + }); + match next { + Ok(text) => { + staged.insert(rel, text); + } + Err(why) => { + refusal = Some(why); + break; } - Err(why) => result.refuse(&pin.uuid, why), } } - // The from-scratch wrappers, once emptied (repositories come last). - for empty in [EMPTY_REPOSITORIES, EMPTY_DEP_MANAGEMENT] { - if text.contains(empty) && !original.contains(empty) { - text = text.replacen(empty, "", 1); + let poms = pin.files.join(", "); + let refusal = refusal.or_else(|| { + if !repository { + let id = generation::hosted_pin_name(&pin.uuid); + Some(format!("{poms} has no with id {id}")) + } else if !wiring { + Some(format!( + "{poms} declares no {group}:{artifact} {suffixed}" + )) + } else { + None } - } - if restored.is_empty() { + }); + if let Some(why) = refusal { + result.refuse(&pin.uuid, why); continue; } - if let Err(why) = crate::formats::maven::parse_pom(&text) { - refuse_all_in( - &pins, - rel, - &mut result, - format!("restoring {rel} would not leave a readable pom: {why}"), - ); - continue; + for (rel, text) in staged { + texts.insert(rel.clone(), text); + } + checksum_dirs.push(format!( + "{}/", + crate::vendor::jvm::layout::version_dir(group, artifact, &suffixed) + )); + restored.push(&pin.uuid); + } + if restored.is_empty() { + return result; + } + for (rel, text) in texts { + if originals[&rel] != text { + view.write(&rel, text); } - view.write(rel, text); + } + // The Trusted Checksums files, where the rewriter keeps them: at the + // project root (and beside a pom an earlier release pinned on its own). + let mut dirs: std::collections::BTreeSet = originals + .keys() + .map(|rel| { + rel.rsplit_once('/') + .map(|(d, _)| format!("{d}/")) + .unwrap_or_default() + }) + .collect(); + dirs.insert(String::new()); + for dir in dirs { restore_mvn(view, &dir, &checksum_dirs, &mut result).await; - result - .handled - .extend(restored.into_iter().map(str::to_string)); } result + .handled + .extend(restored.into_iter().map(str::to_string)); + result } /// Drop the restored pins' trusted-checksum lines, and the `.mvn` files @@ -468,39 +541,52 @@ mod tests { std::fs::read_to_string(p).unwrap() } - /// Restore the slf4j pin (offline: Maven needs no network) over - /// `files`; the outcome, and the tree after. - async fn run(files: &[(&str, String)]) -> (RestoreOutcome, BTreeMap) { - let tmp = tempfile::tempdir().unwrap(); + fn write_tree(root: &std::path::Path, files: &[(&str, String)]) { for (rel, text) in files { - let p = tmp.path().join(rel); + let p = root.join(rel); std::fs::create_dir_all(p.parent().unwrap()).unwrap(); std::fs::write(p, text).unwrap(); } - let pins = [HostedPin { - purl: "pkg:maven/org.slf4j/slf4j-api@1.7.36".into(), - uuid: UUID.into(), - files: vec!["pom.xml".into()], - }]; - let opts = RestoreOptions { - offline: true, - ..RestoreOptions::default() - }; - let outcome = restore_upstream(tmp.path(), &pins, &opts).await; + } + + fn read_tree(root: &std::path::Path) -> BTreeMap { let mut after = BTreeMap::new(); - for entry in walkdir::WalkDir::new(tmp.path()) + for entry in walkdir::WalkDir::new(root) .into_iter() .filter_map(Result::ok) { if entry.file_type().is_file() { - let rel = entry.path().strip_prefix(tmp.path()).unwrap(); + let rel = entry.path().strip_prefix(root).unwrap(); after.insert( rel.to_string_lossy().replace('\\', "/"), std::fs::read_to_string(entry.path()).unwrap(), ); } } - (outcome, after) + after + } + + /// Restore the slf4j pin (offline: Maven needs no network) over + /// `files`, wired in every pom among them; the outcome, and the tree + /// after. + async fn run(files: &[(&str, String)]) -> (RestoreOutcome, BTreeMap) { + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), files); + let pins = [HostedPin { + purl: "pkg:maven/org.slf4j/slf4j-api@1.7.36".into(), + uuid: UUID.into(), + files: files + .iter() + .map(|(rel, _)| rel.to_string()) + .filter(|rel| rel.ends_with("pom.xml")) + .collect(), + }]; + let opts = RestoreOptions { + offline: true, + ..RestoreOptions::default() + }; + let outcome = restore_upstream(tmp.path(), &pins, &opts).await; + (outcome, read_tree(tmp.path())) } fn refusal(outcome: &RestoreOutcome) -> String { @@ -728,21 +814,21 @@ mod tests { " pom\n \n core\n ", ); let module_pom = format!("{SUFFIXED}\n"); - let with_property = hosted.replace( + let with_plugin = hosted.replace( " jar", &format!( - " jar\n \n {SUFFIXED}\n " + " jar\n \n app-{SUFFIXED}\n " ), ); let no_repo = fixture("basic", "input", "pom.xml").replace("1.7.36", SUFFIXED); let inline_repo = hosted.replace("\n ", ""); let cases: Vec<(Vec<(&str, String)>, &str)> = vec![ ( - vec![("pom.xml", with_module), ("core/pom.xml", module_pom)], - "module pom core/pom.xml also pins", + vec![("core/pom.xml", module_pom), ("pom.xml", with_module)], + "core/pom.xml still names", ), ( - vec![("pom.xml", with_property)], + vec![("pom.xml", with_plugin)], "outside a version", ), (vec![("pom.xml", no_repo)], "no with id"), @@ -759,13 +845,235 @@ mod tests { let (outcome, after) = run(&files).await; let why = refusal(&outcome); assert!(why.contains(needle), "{needle}: {why}"); - assert!(why.contains("git checkout -- pom.xml"), "{why}"); + assert!( + why.contains("git checkout -- ") && why.contains("pom.xml"), + "{why}" + ); for (rel, text) in &files { assert_eq!(after.get(*rel), Some(text), "{needle}: {rel}"); } } } + /// What hosted mode writes for slf4j-api over `files` (each module + /// selecting what `picks` says), discovered again from the tree and + /// restored: the tree after, which must be `files`. + async fn round_trip( + files: &[(&str, String)], + picks: &[(&str, Result<&str, &str>)], + ) -> BTreeMap { + use crate::crawlers::maven_selection::MavenSelection; + use crate::patch::redirect::{ + DepOverride, Integrity, RegistryOverride, RegistryOverrideIdentifiers, + }; + let before: BTreeMap = files + .iter() + .map(|(rel, text)| (rel.to_string(), text.clone())) + .collect(); + let modules: Vec<&str> = files.iter().map(|(rel, _)| *rel).collect(); + let picks: Vec<_> = picks + .iter() + .map(|(pom, pick)| (*pom, "org.slf4j", "slf4j-api", *pick)) + .collect(); + let dep = DepOverride { + ecosystem: "maven".into(), + name: "slf4j-api".into(), + namespace: Some("org.slf4j".into()), + version: "1.7.36".into(), + token: "tok".into(), + patch_uuid: UUID.into(), + artifact_url: format!( + "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/tok/{UUID}/slf4j-api-1.7.36.jar" + ), + registry_override: Some(RegistryOverride { + kind: "maven2".into(), + index_url: format!("https://patch.socket.dev/patch-registry/maven/tok/{UUID}/maven2"), + identifiers: RegistryOverrideIdentifiers { + name: "org.slf4j/slf4j-api".into(), + version: "1.7.36".into(), + maven_group_id: Some("org.slf4j".into()), + maven_artifact_id: Some("slf4j-api".into()), + maven_suffixed_version: Some(SUFFIXED.into()), + maven_pom_sha256: Some("d".repeat(64)), + ..Default::default() + }, + }), + integrity: Integrity { + sha256: Some("c".repeat(64)), + ..Default::default() + }, + }; + let written = crate::patch::redirect::rewrite_registry_redirect_with_host( + &before, + &[dep], + &BTreeMap::new(), + None, + false, + &std::collections::BTreeSet::new(), + &Default::default(), + &crate::formats::cargo::source_replacement::CratesIoSource::Registry, + Some(&MavenSelection::answering(&modules, &picks)), + ); + assert!( + written.files.values().any(|text| text.contains(SUFFIXED)), + "nothing was pinned: {:?}", + written.warnings + ); + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), files); + let hosted: Vec<(&str, String)> = written + .files + .iter() + .map(|(rel, text)| (rel.as_str(), text.clone())) + .collect(); + write_tree(tmp.path(), &hosted); + + let view = crate::vendor::lock_inventory::ProjectView::Disk(tmp.path()); + let pins = HostedPin::discover(view, &[]).await; + assert_eq!(pins.len(), 1, "{pins:?}"); + assert_eq!( + (pins[0].purl.as_str(), pins[0].uuid.as_str()), + ("pkg:maven/org.slf4j/slf4j-api@1.7.36", UUID) + ); + // Every pom hosted mode wrote is one the pin is found in. + for rel in written.files.keys().filter(|rel| rel.ends_with("pom.xml")) { + assert!(pins[0].files.contains(rel), "{rel}: {:?}", pins[0].files); + } + let opts = RestoreOptions { + offline: true, + ..RestoreOptions::default() + }; + let outcome = restore_upstream(tmp.path(), &pins, &opts).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + let after = read_tree(tmp.path()); + assert_eq!(after, before, "every file is back, and none is left over"); + after + } + + const REACTOR_ROOT: &str = "\n 4.0.0\n \ + com.example\n root\n \ + 1.0.0\n pom\n \n \ + a\n b\n \n\n"; + + fn reactor_module(name: &str, dependencies: &str) -> String { + format!( + "\n 4.0.0\n \n \ + com.example\n root\n \ + 1.0.0\n \n {name}\n \ + \n{dependencies} \n\n" + ) + } + + fn dependency(group: &str, artifact: &str, version: Option<&str>) -> String { + let version = version.map_or(String::new(), |v| format!("\n {v}")); + format!( + " \n {group}\n \ + {artifact}{version}\n \n" + ) + } + + /// A reactor's wiring is spread over its poms (a pin in the module + /// that selects the version, a declaration rewritten where it stands, + /// the repository in the root, the checksums at the root): restoring + /// the patch puts every file back byte for byte and leaves none behind. + #[tokio::test] + async fn reactor_wiring_round_trips() { + let logback = dependency("ch.qos.logback", "logback-classic", Some("1.4.14")); + // A pin in one module's pom; its sibling resolves another version. + round_trip( + &[ + ("pom.xml", REACTOR_ROOT.to_string()), + ("a/pom.xml", reactor_module("a", &logback)), + ("b/pom.xml", reactor_module("b", &logback)), + ], + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ) + .await; + // One pin in the root both inherit, beside a declaration. + round_trip( + &[ + ("pom.xml", REACTOR_ROOT.to_string()), + ( + "a/pom.xml", + reactor_module("a", &dependency("org.slf4j", "slf4j-api", Some("1.7.36"))), + ), + ("b/pom.xml", reactor_module("b", &logback)), + ], + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("1.7.36"))], + ) + .await; + // The root manages the version in the shape an added entry has: + // it is the project's own, and stays. + let managing = REACTOR_ROOT.replace( + "", + &format!( + " \n \n {} \n \ + \n", + dependency("org.slf4j", "slf4j-api", Some("1.7.36")).replace("\n ", "\n ") + ), + ); + round_trip( + &[ + ("pom.xml", managing), + ( + "a/pom.xml", + reactor_module("a", &dependency("org.slf4j", "slf4j-api", None)), + ), + ("b/pom.xml", reactor_module("b", &logback)), + ], + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("1.7.36"))], + ) + .await; + } + + /// A `${property}` version is put back as it was written: the + /// property's own value, or the declaration's recorded text. + #[tokio::test] + async fn property_wiring_round_trips() { + let pom = |properties: &str, more: &str| { + format!( + "\n 4.0.0\n \ + com.example\n app\n \ + 1.0.0\n \n {properties}\n \n \ + \n{}{more} \n\n", + dependency("org.slf4j", "slf4j-api", Some("${slf4j.version}")) + ) + }; + let picks = [("pom.xml", Ok("1.7.36"))]; + // Only the patched artifact reads the property. + round_trip( + &[("pom.xml", pom("1.7.36", ""))], + &picks, + ) + .await; + // A sibling reads it too. + round_trip( + &[( + "pom.xml", + pom( + "1.7.36", + &dependency("org.slf4j", "slf4j-simple", Some("${slf4j.version}")), + ), + )], + &picks, + ) + .await; + // No pom of the checkout defines it (a parent from a repository). + round_trip( + &[( + "pom.xml", + pom("1", "").replace( + " com.example", + " \n corp\n parent\n \ + 7\n \n \n \ + com.example", + ), + )], + &picks, + ) + .await; + } + #[tokio::test] async fn crlf_pom_round_trips() { let input = fixture("basic", "input", "pom.xml").replace('\n', "\r\n"); diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs index b809e1ee8..cea85e8b4 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs @@ -29,8 +29,8 @@ use super::{ mod hosted; pub use hosted::{ - hosted_sites, plan_hosted, readable_for_hosted, unwire_hosted, HostedEdit, HostedEditKind, - HostedPlan, HostedSite, ORIGINAL_TAG, + hosted_sites, hosted_unattestable, plan_hosted, readable_for_hosted, unwire_hosted, HostedEdit, + HostedEditKind, HostedPlan, HostedSite, ORIGINAL_TAG, }; /// The committed maven2 tree. @@ -874,14 +874,18 @@ pub fn unattestable_checked( list: ListFn<'_>, c: &Coords<'_>, ) -> Result, JvmRefusal> { + Ok(unattestable_in(&Reactor::discover(read, list)?, c)) +} + +/// [`unattestable_checked`] over a reactor already read. +fn unattestable_in(reactor: &Reactor, c: &Coords<'_>) -> Option { let sv = c.suffixed_version(); let ga = format!("{}:{}", c.group_id, c.artifact_id); - let reactor = Reactor::discover(read, list)?; if !reactor.wires(c) { - return Ok(Some(format!( + return Some(format!( "no dependency or dependencyManagement declaration Maven always reads names \ {ga}:{sv}" - ))); + )); } let patch = coords_patch(c); let mut edits = BTreeMap::new(); @@ -901,7 +905,7 @@ pub fn unattestable_checked( } let mut at: Vec = edits.into_keys().collect(); at.extend(uncertain); - Ok((!at.is_empty()).then(|| { + (!at.is_empty()).then(|| { format!( "{} may still build {ga}:{} rather than {sv}: a base version declared since \ vendoring, a version a property, profile or unpinned root may move, or an \ @@ -909,7 +913,7 @@ pub fn unattestable_checked( at.join(", "), c.version ) - })) + }) } /// `c` as a patch with no bytes: for planning that reads only what a @@ -1614,7 +1618,11 @@ pub fn unwired_modules( c: &Coords<'_>, selection: &MavenSelection, ) -> Result, JvmRefusal> { - let reactor = Reactor::discover(read, list)?; + Ok(unwired_in(&Reactor::discover(read, list)?, c, selection)) +} + +/// [`unwired_modules`] over a reactor already read. +fn unwired_in(reactor: &Reactor, c: &Coords<'_>, selection: &MavenSelection) -> Option { let (g, a, v) = (c.group_id, c.artifact_id, c.version); let open: Vec = reactor .reactor @@ -1628,7 +1636,7 @@ pub fn unwired_modules( Verdict::Other(_) | Verdict::Absent => None, }) .collect(); - Ok(open.first().map(|first| { + open.first().map(|first| { let more = match open.len() - 1 { 0 => String::new(), n => format!(", and {n} more"), @@ -1637,7 +1645,7 @@ pub fn unwired_modules( "the patch of {g}:{a}:{v} is not wired in every module that resolves it: \ {first}{more}" ) - })) + }) } /// One pom outside the checkout, parsed. diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs index 872b52530..46285701a 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs @@ -27,7 +27,8 @@ use std::ops::Range; use super::{ apply_edits, coords_patch, forget_other_versions, is_base_like, line_span, pin_edit, pin_of, - pin_update, place_pins, safe_coordinates, Doc, Edit, Pin, Reactor, Role, + pin_update, place_pins, safe_coordinates, unattestable_in, unwired_in, Doc, Edit, Pin, Reactor, + Role, }; use crate::crawlers::maven_selection::{MavenSelection, Standing, Verdict}; use crate::formats::maven::split_socket_version; @@ -628,6 +629,21 @@ pub fn readable_for_hosted(read: ReadFn<'_>, list: ListFn<'_>) -> bool { Reactor::discover_for(read, list, true).is_ok() } +/// Why `vex` must not attest the hosted patch `c` although the reactor's +/// poms wire it, as vendored mode weighs its own wiring: a declaration +/// that may still build the base version ([`unattestable_in`]), or a +/// module that resolves it (or may, by `selection`) and no pin or +/// declaration reaches ([`unwired_in`]). `None` when nothing does. +pub fn hosted_unattestable( + read: ReadFn<'_>, + list: ListFn<'_>, + c: &Coords<'_>, + selection: &MavenSelection, +) -> Result, JvmRefusal> { + let reactor = Reactor::discover_for(read, list, true)?; + Ok(unattestable_in(&reactor, c).or_else(|| unwired_in(&reactor, c, selection))) +} + /// One artifact some pom of a reactor builds at a Socket suffixed version. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HostedSite { diff --git a/crates/socket-patch-core/src/vex/discover/maven.rs b/crates/socket-patch-core/src/vex/discover/maven.rs index eb09ef71d..4ba8e6c91 100644 --- a/crates/socket-patch-core/src/vex/discover/maven.rs +++ b/crates/socket-patch-core/src/vex/discover/maven.rs @@ -1,4 +1,5 @@ -//! Maven — the root `pom.xml`, plus `.mvn/maven.config` + +//! Maven — the root `pom.xml` (and, when it heads a reactor, every pom of +//! the reactor), plus `.mvn/maven.config` + //! `.mvn/checksums/checksums.sha256` for the hosted integrity pin. //! //! Maven has no lockfile: both Socket wirings live in `pom.xml`, and in both @@ -41,10 +42,14 @@ //! literal version wins over ``, so a managed Socket //! pin shadowed by a direct plain version (or a GA declared with several //! different effective versions) is diagnosed, not a ref. -//! A hosted pin in a reactor root (`` / ``) stays -//! a ref (rollback / remove find it) but marked unattested: a module's -//! own literal `` overrides it, and only the root pom is read here -//! (the rewriter refuses such roots, #261). A `${property}` version is +//! A reactor (`` / ``, or Maven 4 subproject +//! discovery) is read whole ([`extract_hosted_reactor`]): its pins sit in +//! the poms of the modules that select the patched version, and the patch +//! is attested only when every module that resolves the base version is +//! reached by one. A reactor whose poms cannot all be read falls back to +//! its root pom: a pin there stays a ref (rollback / remove find it) but +//! marked unattested, since a module's own literal `` overrides +//! it (#261). A `${property}` version is //! interpolated through every property it names (at most 16 deep; a cycle //! or an undefined name never resolves to a pin) twice: as the pom spells //! it (the root ``, what the rewriter writes and rolls back) @@ -134,9 +139,10 @@ //! (plugin classpaths) are not project resolution and are skipped silently; //! `` are only read when activated, so a Socket repository or pin //! there is diagnosed, never a ref (a profile that bypasses a live pin -//! withholds its attestation, [`bypasses`]). Submodule poms are not read, -//! and parent poms only for what they declare of a managed pin's GA -//! ([`Ancestors`]): a Socket repository or pin in one is not wiring here. +//! withholds its attestation, [`bypasses`]). Outside a reactor, submodule +//! poms are not read, and parent poms only for what they declare of a +//! managed pin's GA ([`Ancestors`]): a Socket repository or pin in one is +//! not wiring here. //! Gradle builds are discovered by //! `gradle.rs` (the hosted index) and the vendored JVM backend's own //! probes. @@ -213,16 +219,28 @@ pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { && !crate::vendor::jvm::maven_reactor::implicit_subprojects_in(&ctx.view) .await .is_empty()); - extract_hosted( - ctx, - (&raw, &pom), - &gas, - &hosted, - reactor, - config.as_deref(), - out, - ) - .await; + // A reactor is read whole; one whose poms cannot all be read falls + // back to its root pom, whose pin then stays a ref and is not attested. + let unread_reactor = match reactor { + true => { + extract_hosted_reactor(ctx, &raw, config.as_deref(), &user_properties, &hosted, out) + .await + .err() + } + false => None, + }; + if !reactor || unread_reactor.is_some() { + extract_hosted( + ctx, + (&raw, &pom), + &gas, + &hosted, + unread_reactor.as_deref(), + config.as_deref(), + out, + ) + .await; + } if !vendored.is_empty() { extract_vendored(ctx, &pom.deps, &vendored, out).await; } @@ -235,7 +253,7 @@ async fn extract_hosted( (raw, pom): (&str, &Pom), gas: &BTreeSet<(String, String)>, hosted: &BTreeMap, - reactor: bool, + unread_reactor: Option<&str>, config: Option<&str>, out: &mut Discovery, ) { @@ -374,19 +392,20 @@ async fn extract_hosted( .await; match candidates.as_slice() { [uuid] => { - // A reactor root's pin stays a ref (rollback, remove and - // list must still find it) but is never attested: a - // module's own , unread here, overrides it (#261). - if reactor { + // The pin of a reactor root whose modules cannot be read + // stays a ref (rollback, remove and list must still find + // it) but is never attested: a module's own , + // unread here, overrides it (#261). + if let Some(why) = unread_reactor { out.unattested( &purl, uuid, POM, format!( "{POM} heads a multi-module reactor (/, or \ - Maven 4 subproject discovery), and a module's own \ - of {ga} overrides this root pin; hosted mode reads only \ - the root pom (re-patch the reactor with `scan --mode vendored`)" + Maven 4 subproject discovery) whose poms cannot all be read \ + ({why}), and a module's own of {ga} overrides this root \ + pin" ), UnattestedKind::MavenReactorRoot, ); @@ -509,6 +528,320 @@ async fn extract_hosted( } } +// ── hosted, in a reactor ───────────────────────────────────────────────── + +/// How many rounds [`reactor_texts`] reads (see the hosted engine's +/// `read_maven_reactor`, which reads the same poms the same way). +const MAX_REACTOR_READ_ROUNDS: usize = 64; + +/// Every pom the reactor planner reads for the root pom `root`, by +/// root-relative path (the root and `.mvn/maven.config` included): it is +/// asked what it reads until it asks for nothing new. +async fn reactor_texts( + ctx: &DiscoverCtx<'_>, + root: &str, + config: Option<&str>, + out: &mut Discovery, +) -> BTreeMap { + use crate::vendor::jvm::maven_reactor::{ + implicit_subprojects_in, may_discover_subprojects, readable_for_hosted, + }; + let mut texts = BTreeMap::from([(POM.to_string(), root.to_string())]); + if let Some(config) = config { + texts.insert(MVN_CONFIG.to_string(), config.to_string()); + } + if may_discover_subprojects(root, config) { + for dir in implicit_subprojects_in(&ctx.view).await { + let rel = format!("{dir}/{POM}"); + if let Some(text) = ctx.read_text(&rel, out).await { + texts.insert(rel, text); + } + } + } + let mut asked: BTreeSet = BTreeSet::new(); + for _ in 0..MAX_REACTOR_READ_ROUNDS { + let wanted: std::cell::RefCell> = Default::default(); + { + let read = |rel: &str| match texts.get(rel) { + Some(text) => Some(text.clone().into_bytes()), + None => { + // A pom only: what else the planner asks about (a + // module's `.mvn`, a module path that is a directory) + // does not change what the poms wire. + if rel.ends_with(".xml") && !asked.contains(rel) { + wanted.borrow_mut().insert(rel.to_string()); + } + None + } + }; + let list = |dir: &str| crate::patch::redirect::gradle::key_list(&texts, dir); + readable_for_hosted(&read, &list); + } + let wanted = wanted.into_inner(); + if wanted.is_empty() { + break; + } + for rel in wanted { + if let Some(text) = ctx.read_text(&rel, out).await { + texts.insert(rel.clone(), text); + } + asked.insert(rel); + } + } + texts +} + +/// The hosted pins of a reactor (`patch::redirect::plan_maven_reactor`): +/// read from every pom the reactor planner reads, since a pin sits in the +/// pom of the modules that select the patched version, a declaration is +/// rewritten where it stands, and a `${property}` version may be wired +/// through the property in another pom. The `` (in the local +/// root a wired pom inherits from) names the patch uuid; a pin's comment +/// names it too, and any other suffixed version is tied to it by its +/// 8-hex suffix, as in a single pom. +/// +/// Every pom that carries part of the wiring is a ref's file (rollback and +/// remove undo each). The patch is attested only when every module that +/// resolves the base version, or may, is reached by a pin or a declaration +/// of the patch, and no declaration may still build the base version +/// ([`hosted_unattestable`](crate::vendor::jvm::maven_reactor::hosted_unattestable), +/// the rule vendored mode attests by). What Maven selects is read from the +/// local Maven repository, on disk only: in memory, a module the wiring +/// does not reach withholds the attestation. +async fn extract_hosted_reactor( + ctx: &DiscoverCtx<'_>, + root: &str, + config: Option<&str>, + user_properties: &BTreeMap, + root_hosted: &BTreeMap, + out: &mut Discovery, +) -> Result<(), String> { + use crate::crawlers::maven_selection::MavenSelection; + use crate::vendor::jvm::maven_reactor::{hosted_sites, hosted_unattestable}; + let texts = reactor_texts(ctx, root, config, out).await; + let read = |rel: &str| texts.get(rel).map(|text| text.clone().into_bytes()); + let list = |dir: &str| crate::patch::redirect::gradle::key_list(&texts, dir); + + // uuid -> its repository's url, and the poms that declare it. + let mut hosted: BTreeMap)> = root_hosted + .iter() + .map(|(uuid, url)| { + ( + uuid.clone(), + (url.clone(), BTreeSet::from([POM.to_string()])), + ) + }) + .collect(); + for (rel, text) in texts.iter().filter(|(rel, _)| rel.ends_with(".xml")) { + if rel == POM { + continue; + } + let Ok(pom) = parse_pom_with(text, user_properties) else { + continue; + }; + for repo in pom.repos.iter().filter(|repo| !repo.in_profile) { + let named = socket_patch_name_uuid(&repo.id, false); + let Some(uuid) = ctx + .hosted_uuid(&repo.url) + .filter(|uuid| named.as_deref() == Some(uuid.as_str())) + else { + continue; + }; + hosted + .entry(uuid) + .or_insert_with(|| (repo.url.clone(), BTreeSet::new())) + .1 + .insert(rel.clone()); + } + } + + let sites = hosted_sites(&read, &list).map_err(|refusal| { + refusal + .detail + .strip_prefix("reason: ") + .unwrap_or(&refusal.detail) + .to_string() + })?; + // uuid -> the (purl, g, a, suffixed version, poms) pins that tie to it. + type Tie = (String, String, String, String, BTreeSet); + let mut ties: BTreeMap> = BTreeMap::new(); + for site in sites { + let ga = format!("{}:{}", site.group, site.artifact); + let (base, hex8) = + split_socket_version(&site.suffixed).expect("a site is at a suffixed version"); + let file = site.rels.iter().next().map_or(POM, String::as_str); + let candidates: Vec<&String> = match &site.uuid { + Some(uuid) => hosted.keys().filter(|hosted| *hosted == uuid).collect(), + None => hosted + .keys() + .filter(|uuid| uuid.starts_with(hex8)) + .collect(), + }; + let Some(purl) = maven_purl(&site.group, &site.artifact, base).filter(|_| { + is_maven_coordinate(&site.group) + && is_maven_coordinate(&site.artifact) + && is_maven_version_text(&site.suffixed) + }) else { + out.diag( + DIAG_REF_INVALID, + file, + format!( + "{file}: {ga} {} is not a usable Maven coordinate", + site.suffixed + ), + ); + continue; + }; + match candidates.as_slice() { + [uuid] => ties.entry((*uuid).clone()).or_default().push(( + purl, + site.group, + site.artifact, + site.suffixed, + site.rels, + )), + // A vendored pin (its comment names a patch no hosted + // repository serves), or one whose committed tree serves it: + // attributed through the vendor ledger. + [] if site.uuid.is_some() + || ctx + .exists(&format!( + "{}/{}", + layout::MAVEN2_TREE, + layout::artifact_path( + &site.group, + &site.artifact, + &site.suffixed, + None, + "jar" + ) + )) + .await => {} + [] => out.diag( + DIAG_REF_UNATTRIBUTABLE, + file, + format!( + "{file}: {ga} {} carries a Socket patch suffix but no \ + socket-patch- repository's uuid starts with {hex8}", + site.suffixed + ), + ), + several => out.diag( + DIAG_REF_UNATTRIBUTABLE, + file, + format!( + "{file}: {ga} {} matches several Socket patch \ + repositories ({}); the 8-hex suffix cannot tell which one serves it", + site.suffixed, + several + .iter() + .map(|uuid| uuid.as_str()) + .collect::>() + .join(", ") + ), + ), + } + } + + let mut checksums: Option> = None; + let mut selection: Option = None; + for (uuid, (url, declared_in)) in &hosted { + let file = declared_in.iter().next().map_or(POM, String::as_str); + let Some(pins) = ties.get(uuid) else { + out.diag( + DIAG_REF_UNATTRIBUTABLE, + file, + format!( + "{file}: repository socket-patch-{uuid} is tied to no dependency (no \ + of the reactor carries the -socket.{} suffix; a same-GAV \ + repository cannot be attributed to an artifact)", + &uuid[..8] + ), + ); + continue; + }; + let [(purl, group, artifact, pinned, wired_in)] = &pins[..] else { + let purls: Vec<&str> = pins.iter().map(|(purl, ..)| purl.as_str()).collect(); + out.diag( + DIAG_REF_UNATTRIBUTABLE, + file, + format!( + "{file}: repository socket-patch-{uuid} is pinned by several packages \ + ({}); a Socket patch repository serves exactly one artifact", + purls.join(", ") + ), + ); + continue; + }; + if checksums.is_none() { + checksums = Some(trusted_checksums(ctx, config, out).await); + } + let jar = layout::artifact_path(group, artifact, pinned, None, "jar"); + let integrity = checksums + .as_ref() + .and_then(|c| c.get(&jar)) + .map(|hex| LockIntegrity::Sha256Hex(hex.clone())); + for rel in wired_in.iter().chain(declared_in).collect::>() { + out.push(PatchedRef::hosted( + purl.clone(), + uuid.clone(), + rel, + Some(url), + integrity.clone(), + false, + )); + } + // What each module selects, read once and only for a reactor that + // carries a hosted pin. + if selection.is_none() { + selection = Some(match ctx.view.disk_root() { + Some(root) => { + let root = root.to_path_buf(); + tokio::task::spawn_blocking(move || MavenSelection::for_project(&root)) + .await + .unwrap_or_else(|_| { + MavenSelection::unavailable("what Maven selects could not be read") + }) + } + None => MavenSelection::unavailable( + "the project is not on disk, so what Maven selects in each module is \ + not read", + ), + }); + } + let base = split_socket_version(pinned).map_or("", |(base, _)| base); + let coords = crate::vendor::jvm::Coords { + group_id: group, + artifact_id: artifact, + version: base, + uuid, + }; + let why = match hosted_unattestable( + &read, + &list, + &coords, + selection.as_ref().expect("read above"), + ) { + Ok(why) => why, + Err(refusal) => Some(refusal.detail), + }; + if let Some(why) = why { + out.unattested( + purl, + uuid, + wired_in.iter().next().map_or(file, String::as_str), + format!( + "{POM} heads a multi-module reactor, and {why}; the build may resolve the \ + upstream jar there (re-run `scan`, or patch the reactor with `scan --mode \ + vendored`)" + ), + UnattestedKind::MavenReactorRoot, + ); + } + } + Ok(()) +} + /// Whether the root pom itself declares `group:artifact`'s main jar among /// the `` Maven always reads, with a version or without. Its /// own declaration replaces any it would inherit, so a managed pin that @@ -1972,13 +2305,135 @@ mod tests { assert!(out.unattested.is_empty(), "{:?}", out.unattested); } + /// The reactor root `com.example:app:1.0.0` over the modules `a` and + /// `b`, carrying the hosted repository of `UUID_A`. + fn reactor_root(more: &str) -> String { + pom(&format!( + "pom\n\na\nb\n\ + \n{more}\n{}\n", + hosted_repo_a() + )) + } + + /// A module of [`reactor_root`] with `body`. + fn reactor_module(name: &str, body: &str) -> String { + format!( + "\n4.0.0\n\n\ + com.example\napp\n\ + 1.0.0\n\n{name}\n{body}\n" + ) + } + + fn sources(out: &Discovery) -> Vec { + let mut files: Vec = out + .refs + .iter() + .map(|r| r.source_file.to_string_lossy().replace('\\', "/")) + .collect(); + files.sort(); + files + } + + /// A reactor's pins are found where the reactor planner writes them: + /// a tagged pin in the pom of the module that selects the version, the + /// repository in the root. Each pom that carries part of the wiring is + /// a file of the ref, so rollback and remove undo every one. The patch + /// is attested while every module that resolves the version is reached. + #[tokio::test] + async fn hosted_pin_in_a_reactor_module_is_found_and_attested() { + let pin = format!( + "\n\n\n{}\n\n", + dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))) + ); + let p = Project::new(); + p.write("pom.xml", reactor_root("")); + p.write("a/pom.xml", reactor_module("a", &pin)); + p.write("b/pom.xml", reactor_module("b", "")); + let out = run(&p).await; + assert_eq!(sources(&out), ["a/pom.xml", "pom.xml"]); + assert!( + out.refs + .iter() + .all(|r| (r.purl.as_str(), r.uuid.as_str(), r.mode) + == (FX_PURL, UUID_A, WiringMode::Hosted)), + "{:?}", + out.refs + ); + assert!(out.unattested.is_empty(), "{:?}", out.unattested); + + // A module that declares the base version itself is not reached by + // the pin in its sibling: the patch is found, and not attested. + p.write( + "b/pom.xml", + reactor_module( + "b", + &format!( + "\n{}\n", + dep("org.slf4j", "slf4j-api", Some("1.7.36")) + ), + ), + ); + let out = run(&p).await; + assert_eq!(sources(&out), ["a/pom.xml", "pom.xml"]); + assert_eq!(out.unattested.len(), 1, "{:?}", out.unattested); + let u = &out.unattested[0]; + assert_eq!(u.kind, UnattestedKind::MavenReactorRoot); + assert!(u.detail.contains("b/pom.xml"), "{}", u.detail); + } + + /// A `${property}` version wired through the property is a pin of the + /// pom that defines it, read by the declarations of other poms; one + /// replaced by a recorded literal is a pin of its own pom. + #[tokio::test] + async fn hosted_property_pins_of_a_reactor_are_found() { + let declaring = |version: &str| { + reactor_module( + "a", + &format!( + "\n{}\n", + dep("org.slf4j", "slf4j-api", Some(version)) + ), + ) + }; + let p = Project::new(); + p.write( + "pom.xml", + reactor_root(&format!( + "\n{}\n\n", + suffixed(UUID_A) + )), + ); + p.write("a/pom.xml", declaring("${slf4j.version}")); + p.write("b/pom.xml", reactor_module("b", "")); + let out = run(&p).await; + assert_eq!(sources(&out), ["pom.xml"]); + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert!(out.unattested.is_empty(), "{:?}", out.unattested); + + let p = Project::new(); + p.write("pom.xml", reactor_root("")); + p.write( + "a/pom.xml", + declaring(&suffixed(UUID_A)).replace( + "", + "", + ), + ); + p.write("b/pom.xml", reactor_module("b", "")); + let out = run(&p).await; + assert_eq!(sources(&out), ["a/pom.xml", "pom.xml"]); + assert!(out.unattested.is_empty(), "{:?}", out.unattested); + } + /// #1809: a Maven 4 (model 4.1.0) `pom`-packaged root listing no /// subprojects builds every direct subdirectory holding a `pom.xml`, - /// so its hosted pin is a reactor root's: kept as a ref, never - /// attested. A 4.0.0 model, no such subdirectory, or discovery turned - /// off in `.mvn/maven.config` leaves it a single pom, attested. + /// so its hosted pin is a reactor's: attested while the root's pin + /// reaches every subproject, and not once one declares the base + /// version itself. A 4.0.0 model, no such subdirectory, or discovery + /// turned off in `.mvn/maven.config` leaves it a single pom, attested. #[tokio::test] - async fn hosted_pin_in_a_maven_4_implicit_reactor_root_is_not_attested() { + async fn hosted_pin_in_a_maven_4_implicit_reactor_is_weighed_per_subproject() { let body = format!( "pom\n\n\n{}\n\n\n{}\n", dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))), @@ -1988,12 +2443,25 @@ mod tests { .replace("POM/4.0.0", "POM/4.1.0") .replace("4.0.0", "4.1.0"); let child = "\n4.1.0\n\nchild\n\n"; + let declaring = child.replace( + "", + &format!( + "\n\n{}", + dep("org.slf4j", "slf4j-api", Some("1.7.36")) + ), + ); let off = "-Dmaven.project.discoverSubprojects=false\n"; for (case, root, files, attested) in [ ( - "implicit reactor", + "implicit reactor the pin reaches", &model_4_1, &[("child/pom.xml", child)][..], + true, + ), + ( + "implicit reactor with its own version", + &model_4_1, + &[("child/pom.xml", declaring.as_str())][..], false, ), ("no subproject", &model_4_1, &[][..], true), From 6ee38a8be914e39b75b198b2d0d1ae3899c1de52 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 05:02:51 -0500 Subject: [PATCH 11/18] Test hosted Maven reactors and property versions against real Maven Two capstones on the hosted suite's harness and fake registry, each checking the invariant (the artifacts Maven resolves after the scan are the ones it resolved before, the patched one in its patched build), that a second scan writes nothing, and that `rollback` restores every file byte for byte and leaves none behind: - a reactor (the V3 shape): the module that reaches the base version through another artifact is pinned in its own pom, the module that declares it has the declaration rewritten, the module that resolves a newer version is untouched and resolves what it resolved before; a Maven started in a module directory resolves the patched jar too; `vex` attests the patch, and withholds it naming the module once a module declares the base version itself; - a `${property}` version: a property only the patched artifact reads, a property a sibling artifact reads too, and a property a parent pom from the repository defines. The fixture repository gains a sibling artifact at the victim's version and a parent pom that defines a version property. Docs: the CLI contract and the ecosystem guide describe hosted reactors and property versions (where the pins, the repository and the Trusted Checksums go, how a `${...}` version is wired and restored, what `vex` attests, what happens to a pin an earlier release wrote), with the new warning codes `redirect_maven_pin_would_move_module` and `redirect_maven_edit_not_reversible`, the edit kind `redirect_maven_property`, and the narrowed meaning of `redirect_maven_multimodule_unsupported` and `vex_maven_reactor_root`. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 100 ++++- .../src/commands/vex_sources.rs | 5 +- .../tests/e2e_redirect_maven_build.rs | 384 ++++++++++++++++++ .../tests/maven_mediation_common/mod.rs | 96 ++++- docs/design/lock-model-divergences.md | 2 +- docs/ecosystems.md | 51 ++- 6 files changed, 620 insertions(+), 18 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 23a19cd43..e55fc7f3d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -402,7 +402,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Grant gate (additive).** A reference grant is the patch API's answer, and its fields are written into files the project commits. Each granted reference is therefore checked once, before anything is planned for it (no takeover, no artifact fetch, no rewriter sees one that fails): the patch uuid is a canonical lowercase uuid; the artifact URL and a registry override's index URL are `https` URLs of plain URL characters (no whitespace or control character, no quote, backslash, `$`, `{`, `}`, `<`, `>`, `&`, `#`, `;`, `|` or `^`; cargo's `sparse+` prefix is kept); `sha1` is 40 hex digits, `sha256` 64, `sha512` exactly one `sha512-` token, the Go hashes `h1:` hashes, the yarn berry checksum `/`, the cargo and gem checksums 64 hex digits; the package's name and version, and every identifier of a registry override, are in their ecosystem's coordinate grammar (letters, digits and that ecosystem's punctuation; Maven coordinates as the JVM backends accept them). A Maven grant's sha256 digests may also be spelled `sha256-…` / `sha256:…`: the pom, Gradle and sbt planners read those, and a digest that is still not 64 hex digits writes no checksum pin (`redirect_maven_trusted_checksums_invalid_hash`). An absent or empty optional field is not checked. A grant that fails is refused for that package only: a `skipped` event whose `errorCode` is `redirect_grant_malformed` and whose `reason` names the field (never its value), the same code and detail in `warnings[]`, nothing written for it, the rest of the run and the exit code unchanged. A plain-`http` artifact or index URL is refused the same way with `redirect_grant_insecure_url` (every later install would send the grant token in clear text), unless its origin is the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin (scheme, host and port) or a loopback address (`localhost`, `127.0.0.0/8`, `::1`). The in-memory engine applies the same gate; it has no configured origin. -The rewriter reads a fixed set of candidate files from the project root: the npm-family locks (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `shrinkwrap.yaml`, `yarn.lock`, plus `.yarnrc.yml` for the berry cache-config gate, `bun.lock` / `bun.lockb`, and `vlt-lock.json` with `vlt.json` and `node_modules/.vlt-lock.json` read only), `requirements.txt` / `uv.lock` / `Pipfile.lock` (pipfile-spec 6; see the Pipenv section below) / `poetry.lock` (every Poetry lock generation from 1.0 on — the 0.12 `[metadata.hashes]` layout is refused because that installer ignores URL sources; a Poetry < 1.4 writer additionally gets `redirect_poetry_stale_install_risk`, see `docs/testing/poetry-compatibility.md`) / `pdm.lock` (PDM lock formats `2` and `4.3`–`4.5.1`; the identity-losing `3.1` / `4.0`–`4.2` formats and unknown future formats are refused with `redirect_pdm_refused`, and a lock-format-`2` writer additionally gets `redirect_pdm_legacy_sync_required`, see `docs/testing/pdm-compatibility.md`; when `uv.lock` or `poetry.lock` sits beside it they drive and `pdm.lock` is left alone), `Cargo.toml` / `Cargo.lock` / `.cargo/config.toml` (plus the legacy extensionless `.cargo/config` — cargo reads that spelling in preference when both exist, so the managed `[registries.…]` block is written into whichever one is present; the hosted redirect is a `sparse+` registry, which cargo loads only from **1.68**, so `rust-toolchain.toml` / `rust-toolchain` are read too (never edited) and a project whose declared floor — the lowest `rust-version` of the root and the member manifests read here (a `rust-version.workspace = true` inheritor reads `[workspace.package]`), else the channel rustup picks from the root (the legacy `rust-toolchain` over `rust-toolchain.toml`; a dated `nightly-`/`beta-YYYY-MM-DD` maps to its release train) — is below 1.68 is refused `redirect_cargo_old_cargo` per crate (nothing written, an earlier run's pins left in place with the `rollback` that drops them named; `--mode vendored` builds on cargo 1.41+), while an undeclared or rolling-channel floor still redirects (toolchain files in ancestor directories are not read); **cargo also reads every workspace-member manifest** — the `[workspace] members` globs minus `exclude` — and every in-root path-dependency manifest, recursively, reached without crossing a symbolic link and never under `.socket/`, and pins the crate in each one that declares it, so those `/Cargo.toml` files can appear in `rewrittenFiles`. A crate is redirected only when every declaration pins and every other `Cargo.lock` package depending on it is a planned member: one a registry or git crate — or a path package outside the root or behind a link — also depends on is refused `redirect_cargo_transitive_dependents` (a pin reaches only the declarations it sits on), a crate no manifest declares keeps `redirect_cargo_toml_dep_not_found` with a transitive-only detail naming `--mode vendored`, a crate every declaration of which requires another version (no requirement accepts the patched version) is refused `redirect_cargo_toml_dep_unrewritable`, and so is a requirement that also matches another locked version of the crate — each a transactional skip, never recorded or attested. With NO `Cargo.lock` there is no resolved graph to ask, so the dependents question is answered from the manifests instead: a crate declared beside any other dependency — anything but a path dependency on a manifest this run also pins, or a `workspace = true` inheritor of a table it scans — or beside a workspace member this run did not read (a `members` glob, or a member outside the project or behind a symbolic link, which member discovery drops) is refused `redirect_cargo_lockless_dependents`, whose detail names the remedies (commit a lockfile, or `--mode vendored`); a project whose only dependency is the patched crate has nothing that could pull it in and still redirects. All-CRLF manifests, locks and configs are rewritten with CRLF kept (mixed endings keep refusing where the grammar does not match), and `remove` / rollback match the recorded fragments across a later CRLF↔LF checkout conversion), `composer.lock`, `nuget.config` / `packages.lock.json` (plus, v5.0 #353/#514, every lock a project under the root restores into: a member project's `packages.lock.json`, a per-project `packages..lock.json`, a literal `NuGetLockFilePath` — each pinned with the root config; a `NuGetLockFilePath` it cannot evaluate warns `redirect_nuget_lock_path_unresolved` and a project tree it cannot list warns `redirect_nuget_lock_unreadable`, both skipping the nuget redirect with nothing written), `Gemfile` / `Gemfile.lock`, `pom.xml` (+ `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` for maven Trusted Checksums merge, and, for a Gradle build, every settings, build, `buildSrc`, included-build, applied and plugin-source script, version catalog and lock file the script graph reaches, plus `gradle/verification-metadata.xml`, `gradle/wrapper/gradle-wrapper.properties` and the owned `.socket/gradle/` files), and the sbt build files (`socket-patch.sbt`, `socket-patch-vendor.sbt`, `build.sbt`, `project/build.properties`, `.sbtopts`, `.jvmopts`; `build.sbt.lock` and the Mill / scala-cli build files `build.mill`, `build.mill.yaml`, `build.sc`, `.mill-version`, `project.scala` for their presence only) — read, never edited; `socket-patch.sbt` is the only sbt file hosted mode writes (see **Hosted sbt** below). **npm-family flavor coverage**: package-lock / npm-shrinkwrap (a package the project patches itself with npm ≥ 12.1's native `npm patch` — a root `patchedDependencies` key, or the lock entry's `patched` record — is left on its registry entry in every npm lock, `redirect_npm_patched_dependency_skipped`), pnpm (root OR any nested `*/pnpm-lock.yaml`), yarn classic (a yarn 2+ install migrates a v1 `yarn.lock` and drops its pins, so a run whose v1 lock carries a hosted pin warns `redirect_yarn_classic_berry_migration_risk` — the hosted twin of the vendored `yarn_classic_berry_migration_risk` — unless the root `package.json`, read as advisory input, declares `"packageManager": "yarn@1…"`), **yarn berry** (the pin yarn writes for a root `resolutions` entry: the root `package.json` — edited only beside a berry `yarn.lock` — gains one `"@npm:": ""` selector per locked range (`redirect_yarn_berry_resolution` edits), and only that `yarn.lock` entry is re-keyed `"@"` with the same `resolution:` + `yarnBerry10c0` checksum (`redirect_yarn_berry_entry`), moved to yarn's key order; never an `npm:` locator, whose fetcher sends npm registry auth to the patch host, nor a tarball locator under an `npm:` key, which hardened mode rejects (YN0078). An older release's `npm:::__archiveUrl=` pin is still recognized and is re-pinned on the next run; rollback rebuilds the key from the selectors and drops them. Refused, nothing written: a user-authored `resolutions` entry for the package `redirect_yarn_berry_resolutions_conflict`, no root manifest `redirect_yarn_berry_manifest_missing`, a builtin `patch:` entry wrapping the same descriptor `redirect_yarn_berry_shared_descriptor`, an artifact URL yarn cannot fetch as a tarball `redirect_yarn_berry_artifact_url_unsupported`; cacheKey `10c0` and `.yarnrc.yml compressionLevel 0` gated by `redirect_yarn_berry_cache_unsupported`), and **bun** (text `bun.lock` lockfileVersion 0, 1 or 2 — 0 is the `--save-text-lockfile` opt-in lock of Bun 1.1.39–1.1.45, 1 the 1.2–1.3 default, 2 the 1.4+ default; all three emit one `packages` grammar, so the registry 4-tuple → URL 3-tuple rewrite is version-independent and the lock's own version line is kept. Any other or missing version, or a `packages` section outside bun's single-line grammar, is refused `redirect_bun_lock_unsupported` — the detail is the shared version gate's text (a newer version: update socket-patch, re-locking would reproduce it; no integer: re-lock with Bun ≥ 1.2), identical to the vendored refusal. A version-0 lock holding `workspace:` packages is refused `redirect_bun_workspace_unsupported` (its 2-tuple workspace grammar cannot keep the hosted tuple through a frozen install); the remedy is to delete `bun.lock` and re-run `bun install` with Bun ≥ 1.2, which writes lockfileVersion 1 (accepted). A plain in-place `bun install` bumps the version only when a workspace depends on another workspace (e.g. root → member — the shape the matrix measured); otherwise Bun 1.2.0 keeps version 0 and Bun 1.2.23+ fail to resolve, so the in-place bump is not the documented remedy. Bun lock version, grammar and workspace compatibility are checked before a vendored takeover, including during dry-run: these refusals preserve the existing lock, artifact and vendor ledger. Version-1 and version-2 workspace locks are rewritten, nested versions included. A granted dep with no rewritable entry warns `redirect_bun_entry_not_found` (or `redirect_bun_non_registry_entry_skipped` when the only same-version entry is a user URL / `file:` tarball, #497), a grant without a sha512 `redirect_bun_missing_sha512`; a CRLF lock keeps `\r\n` on the rewritten line, and a hosted URL left by an earlier grant of the same `name@version` is re-pinned in place. **Digest-less re-saves (Bun 1.1.39–1.3.9)**: every text-lock Bun below 1.3.10 re-saves a URL tuple WITHOUT its `sha512` whenever the lock is re-saved for another reason (`bun add`, `bun install` after a package.json or workspace change), leaving the 2-tuple `["name@", {meta}]` — the spec Bun installs from is intact. The CLI treats that spelling as its own wiring: a repeat hosted run counts the dep as redirected (no `redirect_bun_entry_not_found`) and HEALS the line back to the 3-tuple with the current `sha512`, recording the heal as a further `redirect_bun_lock_package` edit whose `original` is the 2-tuple (a stale URL is re-pinned from either spelling); `rollback`, scoped `rollback ` / `remove ` and the vendored takeover accept the digest-less spelling of a recorded `new` line (same key, spec and meta, only the trailing `"sha512-…"` missing) and restore the recorded original over it, so the chain always unwinds to the pristine registry line. Anything else — another uuid/token, another version, a re-laid meta object — is still drift. **Native `bun.lockb`**: when no text `bun.lock` exists, binary format versions 1, 2 and 3 are read and rewritten directly. Socket Patch does not invoke Bun or convert the project to a text lockfile. Exact matching package records are rewritten to hosted tarballs with the granted integrity, preserving dependency resolution IDs, workspace/dependency topology and unrelated package metadata; binary pointers and the package metadata hash are updated. Per-package `redirect_bun_lockb_package` snapshots support scoped rollback, repeat runs, superseding grants and hosted ↔ vendored takeover. A regular binary lock is discoverable even with no Bun runtime or `node_modules`; a dry run previews the same binary edits without writing them. A malformed, unreadable, unsupported or unverified binary structure is `redirect_bun_lockb_invalid` (exit 0, `redirected: 0`), and it refuses the npm rewrite before any takeover or sibling npm-family lock mutation. A symlinked binary write target is `redirect_symlinked_file_unsupported` (exit 1, including dry-run). `bun.lock` wins when both spellings exist. Binary-only projects do not receive `redirect_npm_no_lockfile`. Measured boundaries and the real-Bun matrix: `docs/testing/bun-compatibility.md`), and **vlt** (`vlt-lock.json` without `lockfileVersion`, `0` or `1`; see the vlt hosted-mode contract below). **Rush monorepos**: when `rush.json` is present the rewriter also reads `common/config/rush/pnpm-lock.yaml` and each `common/config/subspaces//pnpm-lock.yaml` (sorted for determinism) under their repo-relative keys and repoints them in place; editing them emits `redirect_rush_repo_state_stale` when the `repo-state.json` beside a rewritten lock exists (`common/config/rush/repo-state.json` for the common lock, `common/config/subspaces//repo-state.json` for a subspace lock; the `pnpmShrinkwrapHash` desync is refreshed by `rush update`, which the redirect survives), and `redirect_pnpm_trust_lockfile` carries the Rush pnpm >=11 install remedy (see the trust paragraph above). **maven** is fail-closed via version suffixing: a `mavenSuffixedVersion` + `mavenPomSha256` override pins the Socket-only `-socket.` by rewriting the literal `` (`redirect_maven_dep_version`) or adding a `` entry (`redirect_maven_dep_management_added`), plus optional Trusted Checksums (`redirect_maven_trusted_checksums`, conflicts as `redirect_maven_trusted_checksums_conflict`; when `.mvn/wrapper/maven-wrapper.properties` pins a Maven older than 3.9.4, which ignores those files, the additive warning `redirect_maven_trusted_checksums_unenforced`; a grant sha256 that is not 64 hex digits writes no checksum line, `redirect_maven_trusted_checksums_invalid_hash`); a `${property}` version is refused (`redirect_maven_dep_unpinned`), a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`; each such subdirectory's `pom.xml` is read for this, never edited) is refused whole with `redirect_maven_multimodule_unsupported`: `pom.xml` and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the pom pins it too), since a module's own literal `` would shadow a root pin (use `--mode vendored`; `vex` omits a hosted pin in a reactor root as `vex_maven_reactor_root`), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped, with nothing written, when a variant other than `sources` / `javadoc`, live or inside ``, may resolve any version but the suffixed pin — the patched release, another one, a `${property}` a profile moves, or no version in the pom once its classifier-keyed `` (a profile's too) is consulted — since `vex` would never attest that pin: `vex_maven_classifier_unpatched`), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`): when any version it may resolve — its own, or what its own profile's or any combination of profiles' `` make of it, read as `vex` reads it — is not the suffixed pin, the dep is refused with nothing written, since it overrides the pin whenever that profile is active and `vex` would never attest it (a profile `` entry only when management governs the pin, i.e. no live direct declaration carries a version); a versionless one takes the pin, and the dep is also skipped when a profile holds its only declaration, a `${property}` groupId / artifactId resolved from the pom's own `` before matching (one the pom does not define, which may be the patched GA and whose own version would then win, refuses the dep with nothing written: `redirect_maven_coordinate_unresolved`), and a `${property}` groupId / artifactId some profile's `` (or several profiles' together) redefine so that the declaration a pin would go into names another package, or another declaration names the GA's main jar at another version (or one of its executable classifier copies, a `test-jar` included), refuses the dep with nothing written too (`redirect_maven_profile_coordinates_unpatched`): `vex` would never attest that pin (`vex_maven_profile_unpatched`), and a pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). A pin is written only where Maven selects the patch's base version already (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`): see [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). **gradle** (v5.0) is automated wiring, no longer a pasted snippet: the owned settings script `.socket/gradle/socket-patch.hosted.settings.gradle` with its index `.socket/gradle/hosted-index.tsv`, one apply line per build's settings file, every lock entry of the GA moved to the suffixed version, and the suffixed component in an existing `gradle/verification-metadata.xml`. A refused dep writes nothing and keeps `redirect_gradle_manual_snippet` as its fallback; same-GAV grants are refused (`redirect_gradle_same_gav_unsupported`). Rules, refusals and codes: [Gradle builds](#gradle-builds-v50). +The rewriter reads a fixed set of candidate files from the project root: the npm-family locks (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `shrinkwrap.yaml`, `yarn.lock`, plus `.yarnrc.yml` for the berry cache-config gate, `bun.lock` / `bun.lockb`, and `vlt-lock.json` with `vlt.json` and `node_modules/.vlt-lock.json` read only), `requirements.txt` / `uv.lock` / `Pipfile.lock` (pipfile-spec 6; see the Pipenv section below) / `poetry.lock` (every Poetry lock generation from 1.0 on — the 0.12 `[metadata.hashes]` layout is refused because that installer ignores URL sources; a Poetry < 1.4 writer additionally gets `redirect_poetry_stale_install_risk`, see `docs/testing/poetry-compatibility.md`) / `pdm.lock` (PDM lock formats `2` and `4.3`–`4.5.1`; the identity-losing `3.1` / `4.0`–`4.2` formats and unknown future formats are refused with `redirect_pdm_refused`, and a lock-format-`2` writer additionally gets `redirect_pdm_legacy_sync_required`, see `docs/testing/pdm-compatibility.md`; when `uv.lock` or `poetry.lock` sits beside it they drive and `pdm.lock` is left alone), `Cargo.toml` / `Cargo.lock` / `.cargo/config.toml` (plus the legacy extensionless `.cargo/config` — cargo reads that spelling in preference when both exist, so the managed `[registries.…]` block is written into whichever one is present; the hosted redirect is a `sparse+` registry, which cargo loads only from **1.68**, so `rust-toolchain.toml` / `rust-toolchain` are read too (never edited) and a project whose declared floor — the lowest `rust-version` of the root and the member manifests read here (a `rust-version.workspace = true` inheritor reads `[workspace.package]`), else the channel rustup picks from the root (the legacy `rust-toolchain` over `rust-toolchain.toml`; a dated `nightly-`/`beta-YYYY-MM-DD` maps to its release train) — is below 1.68 is refused `redirect_cargo_old_cargo` per crate (nothing written, an earlier run's pins left in place with the `rollback` that drops them named; `--mode vendored` builds on cargo 1.41+), while an undeclared or rolling-channel floor still redirects (toolchain files in ancestor directories are not read); **cargo also reads every workspace-member manifest** — the `[workspace] members` globs minus `exclude` — and every in-root path-dependency manifest, recursively, reached without crossing a symbolic link and never under `.socket/`, and pins the crate in each one that declares it, so those `/Cargo.toml` files can appear in `rewrittenFiles`. A crate is redirected only when every declaration pins and every other `Cargo.lock` package depending on it is a planned member: one a registry or git crate — or a path package outside the root or behind a link — also depends on is refused `redirect_cargo_transitive_dependents` (a pin reaches only the declarations it sits on), a crate no manifest declares keeps `redirect_cargo_toml_dep_not_found` with a transitive-only detail naming `--mode vendored`, a crate every declaration of which requires another version (no requirement accepts the patched version) is refused `redirect_cargo_toml_dep_unrewritable`, and so is a requirement that also matches another locked version of the crate — each a transactional skip, never recorded or attested. With NO `Cargo.lock` there is no resolved graph to ask, so the dependents question is answered from the manifests instead: a crate declared beside any other dependency — anything but a path dependency on a manifest this run also pins, or a `workspace = true` inheritor of a table it scans — or beside a workspace member this run did not read (a `members` glob, or a member outside the project or behind a symbolic link, which member discovery drops) is refused `redirect_cargo_lockless_dependents`, whose detail names the remedies (commit a lockfile, or `--mode vendored`); a project whose only dependency is the patched crate has nothing that could pull it in and still redirects. All-CRLF manifests, locks and configs are rewritten with CRLF kept (mixed endings keep refusing where the grammar does not match), and `remove` / rollback match the recorded fragments across a later CRLF↔LF checkout conversion), `composer.lock`, `nuget.config` / `packages.lock.json` (plus, v5.0 #353/#514, every lock a project under the root restores into: a member project's `packages.lock.json`, a per-project `packages..lock.json`, a literal `NuGetLockFilePath` — each pinned with the root config; a `NuGetLockFilePath` it cannot evaluate warns `redirect_nuget_lock_path_unresolved` and a project tree it cannot list warns `redirect_nuget_lock_unreadable`, both skipping the nuget redirect with nothing written), `Gemfile` / `Gemfile.lock`, `pom.xml` (+ `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` for maven Trusted Checksums merge, and, for a Gradle build, every settings, build, `buildSrc`, included-build, applied and plugin-source script, version catalog and lock file the script graph reaches, plus `gradle/verification-metadata.xml`, `gradle/wrapper/gradle-wrapper.properties` and the owned `.socket/gradle/` files), and the sbt build files (`socket-patch.sbt`, `socket-patch-vendor.sbt`, `build.sbt`, `project/build.properties`, `.sbtopts`, `.jvmopts`; `build.sbt.lock` and the Mill / scala-cli build files `build.mill`, `build.mill.yaml`, `build.sc`, `.mill-version`, `project.scala` for their presence only) — read, never edited; `socket-patch.sbt` is the only sbt file hosted mode writes (see **Hosted sbt** below). **npm-family flavor coverage**: package-lock / npm-shrinkwrap (a package the project patches itself with npm ≥ 12.1's native `npm patch` — a root `patchedDependencies` key, or the lock entry's `patched` record — is left on its registry entry in every npm lock, `redirect_npm_patched_dependency_skipped`), pnpm (root OR any nested `*/pnpm-lock.yaml`), yarn classic (a yarn 2+ install migrates a v1 `yarn.lock` and drops its pins, so a run whose v1 lock carries a hosted pin warns `redirect_yarn_classic_berry_migration_risk` — the hosted twin of the vendored `yarn_classic_berry_migration_risk` — unless the root `package.json`, read as advisory input, declares `"packageManager": "yarn@1…"`), **yarn berry** (the pin yarn writes for a root `resolutions` entry: the root `package.json` — edited only beside a berry `yarn.lock` — gains one `"@npm:": ""` selector per locked range (`redirect_yarn_berry_resolution` edits), and only that `yarn.lock` entry is re-keyed `"@"` with the same `resolution:` + `yarnBerry10c0` checksum (`redirect_yarn_berry_entry`), moved to yarn's key order; never an `npm:` locator, whose fetcher sends npm registry auth to the patch host, nor a tarball locator under an `npm:` key, which hardened mode rejects (YN0078). An older release's `npm:::__archiveUrl=` pin is still recognized and is re-pinned on the next run; rollback rebuilds the key from the selectors and drops them. Refused, nothing written: a user-authored `resolutions` entry for the package `redirect_yarn_berry_resolutions_conflict`, no root manifest `redirect_yarn_berry_manifest_missing`, a builtin `patch:` entry wrapping the same descriptor `redirect_yarn_berry_shared_descriptor`, an artifact URL yarn cannot fetch as a tarball `redirect_yarn_berry_artifact_url_unsupported`; cacheKey `10c0` and `.yarnrc.yml compressionLevel 0` gated by `redirect_yarn_berry_cache_unsupported`), and **bun** (text `bun.lock` lockfileVersion 0, 1 or 2 — 0 is the `--save-text-lockfile` opt-in lock of Bun 1.1.39–1.1.45, 1 the 1.2–1.3 default, 2 the 1.4+ default; all three emit one `packages` grammar, so the registry 4-tuple → URL 3-tuple rewrite is version-independent and the lock's own version line is kept. Any other or missing version, or a `packages` section outside bun's single-line grammar, is refused `redirect_bun_lock_unsupported` — the detail is the shared version gate's text (a newer version: update socket-patch, re-locking would reproduce it; no integer: re-lock with Bun ≥ 1.2), identical to the vendored refusal. A version-0 lock holding `workspace:` packages is refused `redirect_bun_workspace_unsupported` (its 2-tuple workspace grammar cannot keep the hosted tuple through a frozen install); the remedy is to delete `bun.lock` and re-run `bun install` with Bun ≥ 1.2, which writes lockfileVersion 1 (accepted). A plain in-place `bun install` bumps the version only when a workspace depends on another workspace (e.g. root → member — the shape the matrix measured); otherwise Bun 1.2.0 keeps version 0 and Bun 1.2.23+ fail to resolve, so the in-place bump is not the documented remedy. Bun lock version, grammar and workspace compatibility are checked before a vendored takeover, including during dry-run: these refusals preserve the existing lock, artifact and vendor ledger. Version-1 and version-2 workspace locks are rewritten, nested versions included. A granted dep with no rewritable entry warns `redirect_bun_entry_not_found` (or `redirect_bun_non_registry_entry_skipped` when the only same-version entry is a user URL / `file:` tarball, #497), a grant without a sha512 `redirect_bun_missing_sha512`; a CRLF lock keeps `\r\n` on the rewritten line, and a hosted URL left by an earlier grant of the same `name@version` is re-pinned in place. **Digest-less re-saves (Bun 1.1.39–1.3.9)**: every text-lock Bun below 1.3.10 re-saves a URL tuple WITHOUT its `sha512` whenever the lock is re-saved for another reason (`bun add`, `bun install` after a package.json or workspace change), leaving the 2-tuple `["name@", {meta}]` — the spec Bun installs from is intact. The CLI treats that spelling as its own wiring: a repeat hosted run counts the dep as redirected (no `redirect_bun_entry_not_found`) and HEALS the line back to the 3-tuple with the current `sha512`, recording the heal as a further `redirect_bun_lock_package` edit whose `original` is the 2-tuple (a stale URL is re-pinned from either spelling); `rollback`, scoped `rollback ` / `remove ` and the vendored takeover accept the digest-less spelling of a recorded `new` line (same key, spec and meta, only the trailing `"sha512-…"` missing) and restore the recorded original over it, so the chain always unwinds to the pristine registry line. Anything else — another uuid/token, another version, a re-laid meta object — is still drift. **Native `bun.lockb`**: when no text `bun.lock` exists, binary format versions 1, 2 and 3 are read and rewritten directly. Socket Patch does not invoke Bun or convert the project to a text lockfile. Exact matching package records are rewritten to hosted tarballs with the granted integrity, preserving dependency resolution IDs, workspace/dependency topology and unrelated package metadata; binary pointers and the package metadata hash are updated. Per-package `redirect_bun_lockb_package` snapshots support scoped rollback, repeat runs, superseding grants and hosted ↔ vendored takeover. A regular binary lock is discoverable even with no Bun runtime or `node_modules`; a dry run previews the same binary edits without writing them. A malformed, unreadable, unsupported or unverified binary structure is `redirect_bun_lockb_invalid` (exit 0, `redirected: 0`), and it refuses the npm rewrite before any takeover or sibling npm-family lock mutation. A symlinked binary write target is `redirect_symlinked_file_unsupported` (exit 1, including dry-run). `bun.lock` wins when both spellings exist. Binary-only projects do not receive `redirect_npm_no_lockfile`. Measured boundaries and the real-Bun matrix: `docs/testing/bun-compatibility.md`), and **vlt** (`vlt-lock.json` without `lockfileVersion`, `0` or `1`; see the vlt hosted-mode contract below). **Rush monorepos**: when `rush.json` is present the rewriter also reads `common/config/rush/pnpm-lock.yaml` and each `common/config/subspaces//pnpm-lock.yaml` (sorted for determinism) under their repo-relative keys and repoints them in place; editing them emits `redirect_rush_repo_state_stale` when the `repo-state.json` beside a rewritten lock exists (`common/config/rush/repo-state.json` for the common lock, `common/config/subspaces//repo-state.json` for a subspace lock; the `pnpmShrinkwrapHash` desync is refreshed by `rush update`, which the redirect survives), and `redirect_pnpm_trust_lockfile` carries the Rush pnpm >=11 install remedy (see the trust paragraph above). **maven** is fail-closed via version suffixing: a `mavenSuffixedVersion` + `mavenPomSha256` override pins the Socket-only `-socket.` by rewriting the literal `` (`redirect_maven_dep_version`) or adding a `` entry (`redirect_maven_dep_management_added`), plus optional Trusted Checksums (`redirect_maven_trusted_checksums`, conflicts as `redirect_maven_trusted_checksums_conflict`; when `.mvn/wrapper/maven-wrapper.properties` pins a Maven older than 3.9.4, which ignores those files, the additive warning `redirect_maven_trusted_checksums_unenforced`; a grant sha256 that is not 64 hex digits writes no checksum line, `redirect_maven_trusted_checksums_invalid_hash`); a `${property}` version is wired through the property's own value (`redirect_maven_property`) or a literal that records the text it replaced (`redirect_maven_dep_version` with the `${...}` text as `original`), and stays `redirect_maven_dep_unpinned` only when what it reads cannot be told, a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`) is planned over every pom of the reactor, each module `pom.xml` that takes an edit appearing in `rewrittenFiles` (see [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions)); a reactor one of whose poms cannot be read, and a same-GAV grant in a reactor, are refused whole with `redirect_maven_multimodule_unsupported`: the poms and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the poms pin it too), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped, with nothing written, when a variant other than `sources` / `javadoc`, live or inside ``, may resolve any version but the suffixed pin — the patched release, another one, a `${property}` a profile moves, or no version in the pom once its classifier-keyed `` (a profile's too) is consulted — since `vex` would never attest that pin: `vex_maven_classifier_unpatched`), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`): when any version it may resolve — its own, or what its own profile's or any combination of profiles' `` make of it, read as `vex` reads it — is not the suffixed pin, the dep is refused with nothing written, since it overrides the pin whenever that profile is active and `vex` would never attest it (a profile `` entry only when management governs the pin, i.e. no live direct declaration carries a version); a versionless one takes the pin, and the dep is also skipped when a profile holds its only declaration, a `${property}` groupId / artifactId resolved from the pom's own `` before matching (one the pom does not define, which may be the patched GA and whose own version would then win, refuses the dep with nothing written: `redirect_maven_coordinate_unresolved`), and a `${property}` groupId / artifactId some profile's `` (or several profiles' together) redefine so that the declaration a pin would go into names another package, or another declaration names the GA's main jar at another version (or one of its executable classifier copies, a `test-jar` included), refuses the dep with nothing written too (`redirect_maven_profile_coordinates_unpatched`): `vex` would never attest that pin (`vex_maven_profile_unpatched`), and a pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). A pin is written only where Maven selects the patch's base version already (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`): see [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). **gradle** (v5.0) is automated wiring, no longer a pasted snippet: the owned settings script `.socket/gradle/socket-patch.hosted.settings.gradle` with its index `.socket/gradle/hosted-index.tsv`, one apply line per build's settings file, every lock entry of the GA moved to the suffixed version, and the suffixed component in an existing `gradle/verification-metadata.xml`. A refused dep writes nothing and keeps `redirect_gradle_manual_snippet` as its fallback; same-GAV grants are refused (`redirect_gradle_same_gav_unsupported`). Rules, refusals and codes: [Gradle builds](#gradle-builds-v50). **Hosted sbt (v5.0, additive)**: an sbt build root (`project/build.properties` naming an `sbt.version`, 0.13.18 or later) is wired through ONE generated root file, `socket-patch.sbt` — no user file is edited. It pins every granted Maven patch build-wide (a `ThisBuild` `dependencyOverrides +=` of the Socket-only `-socket.` version plus a `file:` resolver over `.socket/sbt-hosted/maven2/`, moved ahead of the default repositories on sbt 0.13 / 1.x so an unreachable one never blocks it offline), downloads the pinned pom and jar there on the first sbt load (sha256-checked, gitignored by the file itself), and installs a load-time verifier that fails `update` when any project resolves another version or a pinned artifact whose bytes are not pinned. Edits: `redirect_sbt_pin` (added), `redirect_sbt_pin_updated` (an existing row replaced: same GA and base under a new uuid, or the same uuid with new served values; `original` names the previous uuid and version), `redirect_sbt_pin_rechecked` (an existing row re-verified after the build's dependencies changed: its dependency digest is recorded anew, `original`/`new` are `{deps}`). The load-time verifier also fails `update` when a project declares a pinned GA at a version newer than the pin's base (the build-wide override would otherwise force it back down). A new pin is gated on sbt's own resolution records under `target/` (never the machine-wide cache): run-level stops wire nothing, warn once and exit 0 — `redirect_sbt_no_resolution_evidence` (none; run `sbt update` first; always the in-memory engine's answer), `redirect_sbt_resolution_incomplete` (a declared project left no evidence, or the project definitions cannot be read statically), `redirect_sbt_resolution_stale` (a build source is newer than some project's evidence: each project is dated by its own newest record, so a partial `sbt /update` does not vouch for the others). Per-patch refusals (never confirmed): `redirect_sbt_missing_override` (no `maven2` override or no suffixed version), `redirect_sbt_integrity_missing` (jar or pom sha256 missing), `redirect_sbt_unsafe_value` (a value unsafe in a Scala literal, or an index URL not naming the uuid), `redirect_sbt_version_conflict` (some project resolves another version, or a build source declares the GA newer than the patch's base), `redirect_sbt_override_conflict` (two patches for one GA in a run, or another base already pinned), `redirect_sbt_vendored_conflict` (the GA is pinned by `socket-patch-vendor.sbt`, or that file cannot be parsed — then every Maven patch), `redirect_sbt_owned_file_modified` / `redirect_sbt_owned_file_foreign` (`socket-patch.sbt` edited, or not socket-patch's — every Maven patch), `redirect_sbt_owned_file_unreadable` (a whole-run refusal: `socket-patch.sbt` is on disk but cannot be read as UTF-8 text, so writing it would replace it; nothing is written), `redirect_sbt_unsupported_version`, `redirect_sbt_build_root_unknown` (sbt files but no versioned build root — every Maven patch), `redirect_sbt_overrides_assignment` / `redirect_sbt_resolvers_assignment` (a build source reassigns `dependencyOverrides` / `resolvers` with `:=`, `~=`, `--=` or `<<=`), `redirect_sbt_onload_assignment` (a build source reassigns `onLoad`, in any scope, with `:=`, `~=`, `--=` or `<<=` without keeping its previous value — a `:=` reading `(Global / onLoad).value`, or a `~=` that composes with `andThen` / `compose`, keeps it — which drops the generated file's load-time verifier and resolver order), `redirect_sbt_dependency_lock_present` (a `build.sbt.lock`), `redirect_sbt_scala_runtime_unsupported` (`org.scala-lang`), `redirect_sbt_classifier_unsupported`; a GA no library configuration resolves is skipped silently (`redirect_sbt_meta_build_only` when only the meta-build resolves it). Advisories: `redirect_sbt_version_untested` (sbt 2.1+, still wired), `redirect_sbt_override_build_repos` (`sbt.override.build.repos=true`), `redirect_maven_pom_ignored_sbt_build` (a `pom.xml` beside the sbt build, which sbt never reads; the Maven rewriter still edits it for the Maven build). A re-run keeps an existing row and re-checks it. When the build's dependency digest changed since the pin, evidence resolved after the change (fresh, newer than the generated file) re-verifies it and the row's digest is refreshed (`redirect_sbt_pin_rechecked`); the uuid is NOT confirmed on `redirect_sbt_pin_declared_newer` (a build source now declares the GA newer than the pin's base; the row stays, sbt's load-time verifier fails the build, and the remedy is `socket-patch rollback` or declaring the base again), `redirect_sbt_pin_unverifiable` (the digest changed and the evidence predates the change, or the digest cannot be computed: run `sbt update`, then re-run socket-patch), `redirect_sbt_override_shadowed` (the evidence still resolves the base version) or `redirect_sbt_resolved_elsewhere` (the pinned version resolves from outside the pin repository from a file whose sha256 is not the pinned jar's; a copy holding the pinned bytes, such as the Ivy cache a second checkout reads, is fine — at most 64 pinned artifact files of up to 256 MiB are hashed, anything else counts as elsewhere), and also when a build source now reassigns `dependencyOverrides` / `resolvers` / `onLoad` or a `build.sbt.lock` appeared (the same `redirect_sbt_overrides_assignment` / `redirect_sbt_resolvers_assignment` / `redirect_sbt_onload_assignment` / `redirect_sbt_dependency_lock_present` codes; the row stays and sbt's load-time verifier fails the build). For a pure sbt root (no `pom.xml` / Gradle script beside it), maven confirmation is decided only by the sbt rewriter's report; on a mixed root a uuid the sbt rewriter refused is still confirmed by the Maven rewriter's own `pom.xml` pin (the generated sbt files never prove a pin by substring). **Mill and scala-cli** are guidance only: per Maven patch `redirect_mill_manual_snippet` / `redirect_scala_cli_manual_snippet` carry a paste-able snippet (repository + forced suffixed version), nothing is written or confirmed, and a pure Mill / scala-cli root gets no `redirect_maven_no_pom`; there, a Maven patch the server sent without a `maven2` registry override gets `redirect_maven_missing_override` instead of a snippet (with a `pom.xml` beside the Mill / scala-cli files the pom rewriter reports it). `rollback` / `remove` restore `socket-patch.sbt` offline (the rows removed, the file deleted with its last pin; the gitignored downloads are left). Manifest-less VEX reads every strictly parsed pin as a hosted reference but grants it the lockfile basis only when the local evidence shows every recorded version of the GA is the pinned one and every recorded artifact hashes to a pinned sha256 (else `sbt_resolution_unverified`, and the suffixed copy sbt downloaded into `.socket/sbt-hosted` is its only basis). Where the build provably does not use the pinned bytes, that copy proves nothing and the patch is omitted (`vex_sbt_pin_bypassed`): a build source reassigns `dependencyOverrides` (`:=`, `~=`, `--=`; replacing the generated override) or reassigns `onLoad` without keeping its previous value (dropping the installer that holds the load-time verifier and resolver order), whether or not any evidence exists, or a resolution record dated after the generated files and every build source shows the GA's base version (the override shadowed), or the pinned version from outside the pin repository with bytes that are not pinned (judged exactly as the hosted rewriter re-checks a pin, `redirect_sbt_override_shadowed` / `redirect_sbt_resolved_elsewhere`). A record older than the wiring (a project or cross build not re-resolved since) proves nothing, and current records that verify the pin always keep it. A `resolvers` reassignment or `sbt.override.build.repos=true` alone is no bypass: the override still forces the Socket-only version and the load-time verifier checks its bytes, so the build runs the pinned bytes or fails (which is why an `onLoad` reassignment dropping that verifier is one). Stale or partial evidence, project definitions that cannot be read statically and a `build.sbt.lock` only withhold the lockfile basis. A file under a generated name without socket-patch's header is read as the root build definition sbt loads it as. @@ -707,7 +707,7 @@ Recognition rules that hold for every ecosystem: * **Patch hosts.** A hosted reference counts only on `https://patch.socket.dev` or the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin, with no userinfo. The URL must be one every client reads alike: a backslash, whitespace or a control character anywhere in it (after the lock format's own `\/` unescape and the trim of surrounding whitespace) makes it no reference, because URL parsers disagree about the host of a URL such as `https://patch.socket.dev\@evil.example/…`. Its path must be one the patch server serves a patch under: `patch//…`, `patch-registry//…` (`` one of `npm`, `pypi`, `cargo`, `golang`, `gem`, `composer`, `maven`, `nuget`) or `gopatch/…`, first in the path on Socket's own server and under any path prefix on a `--patch-server-url` deployment, with no percent-encoded `/` or `\` (`%2f`, `%5c`) anywhere in it. The uuid is the LAST canonical-uuid segment below that level, because grant tokens may themselves be uuid-shaped. A URL on a patch host that fails these rules is not a hosted pin (`vex` does not attest it; `list`, `rollback`, `remove` and `scan` do not manage it, and a hosted `scan` does not write one), but a uuid in its path still counts as *mentioned* for the liveness gates below, so no ledger record is revived from it. The Go module prefix is fixed. `socket-patch-` registry / repository / source names count only through a pin. For a URL on any other host, see **Patch hosts** above. * **Pins, not definitions.** A registry, index or source *definition* alone (cargo `[registries]`, nuget ``, pom ``, uv index tables, `.npmrc`) never makes a reference, because it survives a reverted pin. Sections the package manager ignores are not read: npm's v2 `dependencies` mirror, a `.cargo/config.toml` shadowed by `.cargo/config`. A Socket pin inside a maven `` is diagnosed, never a reference. * **Contested locks.** When one lock wires a package to a patch and another lock resolves the same `name@version` from a non-Socket source, the build's bytes depend on which package manager runs. The reference is then dropped with a `patched_ref_unattributable` diagnostic naming both files. This applies across npm / pnpm / yarn / bun and across uv / pylock / poetry / pdm / Pipfile.lock / requirements. A PEP 723 script lock is a lock like the others: `uv run` installs its script's dependencies from it, so a script lock that resolves the release from the index contests a project lock's reference and the reverse (both writers rewire script locks, so a re-run clears it). A Python lock also contests itself: another entry of the **same** `uv.lock`, script lock, `pylock*.toml`, `poetry.lock`, `pdm.lock` or `Pipfile.lock` that resolves the wired release from a non-Socket source (a uv marker fork, a Poetry multiple-constraint dependency, a PEP 751 marker split, a PDM extras variant, the other `Pipfile.lock` category) is installed wherever its markers, extras or category select it, so the reference is withheld until `scan` / `vendor` rewires every entry. Requirements and `pyproject.toml` / `hatch.toml` declarations are not lock entries, and a Socket reference there is withheld (`patched_ref_unattributable`, naming the other requirement) while another requirement of the same package can install the same release where the reference does not apply: beside a reference that carries an environment marker, any requirement of the set that is not an exact pin of another release; beside a reference in an extra, a dependency group or a Hatch environment, any requirement of the package in `[project].dependencies` (which `pip install .` reads), or an exact pin of the release in any table not installed together with the reference. A reference and a compatible requirement that pip resolves together (one requirement set, or `[project].dependencies` with the project's extras) resolve to the reference, so an unmarked reference is not contested there. The root `requirements.txt` and its in-root `-r` includes count as one lock here: pip reads them as one requirement set, where a direct reference wins over a compatible `==` pin of the same version in another file of the set (#1086). A PyPI version matches under PEP 440 equality, so a requirements line pinned in any spelling that can only install the wired release (`==1.2.3.0`, `==v1.2.3`, `===1.2.3`) contests it like `==1.2.3` does; a range or wildcard (`~=1.2.3`, `==1.2.*`) does not (#1602). A **bundled** npm copy (`inBundle: true`, or v1 `bundled: true`, beneath a dependency that bundles it; the root project's own bundles install from the lock, #1618) of the same `name@version` contests the reference too, in the same lock, in the other npm lock of a shrinkwrap/package-lock pair, or in any other lock. npm unpacks it from the parent package's tarball, so no rewire reaches it and it stays unpatched. Bun and vlt unpack bundled copies the same way (#469, #471). pnpm unpacks bundled copies too, but its lock cannot tie one to a reference (see **Unattested references** below). For Bun, that is a `bun.lock` entry whose meta is `{ "bundled": true }`, or a `bun.lockb` record that a dependency edge with the `bundled` behavior bit reaches, including one Bun shares with a regular install. Such an entry is never a reference, and it contests the reference the same way. For vlt, the lock records no node for a bundled copy, so the copy is found in the installed store: a real package directory inside a store package's own `node_modules`. yarn classic's `yarn.lock` records nothing about bundled copies either (#758), so for a lock with a Socket wiring they are found in the installed `node_modules`: each package a parent's `bundleDependencies` / `bundledDependencies` names inside the parent's own `node_modules`, the dependencies of those beside them, and everything nested under them. Such a copy contests the reference in `yarn.lock` (the diagnostic names the parent's lock entry and the copy's directory); a lock-only `vex` with no `node_modules` can't see it. Hosted and vendored scans skip these copies with `redirect_bun_bundled_instance_skipped` / `redirect_vlt_bundled_instance_skipped` / `vendor_bundled_instance_skipped`, and a yarn classic hosted scan names one with `redirect_copy_unpatched`. When a bundled copy is the only instance, vendoring refuses with `vendor_lock_entry_not_rewritable`. A reference withheld only because such an unreachable copy installs beside it (a bundled npm / Bun / vlt copy, an npm copy beneath a `hasShrinkwrap` package (#753) or one npm installs from a git / url / `file:` spec, or a yarn classic git or `file:` directory block of the same `name@version`) is still the rewriter's own wiring of exactly one package version: it is never attested, but `rollback`, `remove`, `list` and the hosted → vendored takeover treat it as an ordinary hosted pin and restore its upstream registry entry (#828), rather than refusing it with `hosted_wiring_contested`. Another entry of the **same** npm, Bun or yarn lock that resolves the wired `name@version` from a non-Socket source (for example a workspace member added after the rewire, then `npm install` / `bun install` / `yarn install`; for yarn berry, a registry locator such as `left-pad@npm:1.3.0` beside the hosted `…::__archiveUrl=` one) contests the reference too (#588). The package manager installs both entries, and that copy stays unpatched. Re-running `scan` / `vendor` rewires every copy. -* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Thirteen cases besides Gradle's (`vex_gradle_lock_above_base`) and NuGet's (`vex_nuget_lock_other_version`, see the table above); one of them, a vendored pin in a lock the package manager is told not to read (`vex_lock_not_read`), has its own bullet below; another, **hosted sbt pins a build bypasses** (`vex_sbt_pin_bypassed`), is under **Hosted sbt** above: **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactor roots** (`vex_maven_reactor_root`): a hosted pin in a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers (see the hosted Maven rewriter), is omitted, because a module's own literal `` overrides a root pin and module poms are not read (#261); hosted scan refuses such roots (`redirect_maven_multimodule_unsupported`), so this only covers pins an older release wrote. **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA (or one whose `` implies a classifier or carries code, such as `test-jar`) is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build), live or inside ``, resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier (a profile's overriding the live one), or no version in the root pom — the pin is omitted. A pre-v5 single-pom vendored repository holds only the main jar, so any such copy omits its reference. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep, writing nothing, when an executable copy may resolve anything but the suffixed pin (so it never writes a pin this rule withholds). **Maven profile declarations** (`vex_maven_profile_unpatched`): a `` declaration of a pinned GA's main jar in the root `pom.xml` at any version other than the pin (the base release, another release, a `${property}` the pom does not resolve) overrides the pin whenever that profile is active, so the reference is omitted. A profile `` entry always counts; a profile `` entry counts only when management governs the pin (no direct `` outside ``), since a direct literal version beats management. A declaration without a `` takes the live pin, and a `pom` (or `java-source` / `javadoc`) typed one carries no code; neither withholds the statement. Activation is not evaluated: every profile counts, as in vendored mode, which rewrites profile declarations too; hosted scan leaves them as written and writes no pin they bypass (`redirect_maven_profile_dependency_unpatched`). A pin spelled through a property counts the same way: a `${property}` `` is interpolated through every property it names, the project's own `${project.version}` included (itself often spelled through `${revision}`), at most 16 levels deep (a cycle or an undefined name never resolves to a pin), and when any profile's `` — or any combination of profiles' together, each nested reference read with that combination active, as the vendored planner weighs them too — redefine one of those properties so that it resolves anything other than the pin (or nothing), the reference is omitted too; a `.mvn/maven.config` user property wins over every profile's. A profile declaration reads its own profile's `` first. When more than 8 profiles may change such a version, or a profile's `` cannot be parsed, the reference is omitted (fail closed); the rest of the pom is still read. One pom's `${property}` texts are also given a fixed amount of interpolation in all (about four million property lookups, which a pom reaches only with thousands of different texts that each take hundreds of lookups under many profile combinations); a `${property}` read after that counts as unresolved, the same fail-closed way. The statement names the profiles that move the pin and the version they move it to. Coordinates count the same way: when a profile's `` (or several profiles' together, or the profile holding the declaration) redefine a property a `${property}` `` / `` names, so that the declaration carrying the pin names another package (the pin then no longer applies to the patched GA) or another declaration names the patched GA (its main jar, or an executable classifier copy) at a version other than the pin, or as a classifier copy with no version of its own, the reference is omitted; a profile value the pom cannot resolve may name any package, a user property wins over every profile's, and the same 8-profile and unreadable-profile limits fail closed. Each such reading is weighed like a declaration of its own: a retargeted classifier copy (a `test-jar` is the `tests` copy; an explicit `` names the copy whatever the type) by the classifier rule (`vex_maven_classifier_unpatched`, so a pre-v5 vendored repository, which serves only the main jar, is bypassed even at the vendored version), any other non-`jar` type not at all, and a reading that moves the coordinates and the version onto the pin together does not withhold the statement. Hosted scan refuses such a dep (`redirect_maven_profile_coordinates_unpatched`), and vendored mode leaves the declaration as written and does not pin its root (`coordinates_overridden`), except a retargeted classifier copy, which it reports as `classifier_declared` with the root still pinned. The same holds for a pre-v5 single-pom vendored repository, which serves only the original version. **Maven parent poms** (`vex_maven_parent_declares`): a pin that only the root pom's `` carries, for a package the root pom does not declare in its own `` (what hosted scan adds for a dependency with no literal ``), governs the declaration the build inherits. Maven merges a parent pom's `` into the child, and management fills in only a dependency that declares no version (Maven 3.9.16: with the parent declaring the package at a literal version the build resolves the upstream jar and never asks for the patched version). The parent chain is followed through the checkout (``, default `../pom.xml`, when the pom there is the parent the reference names). When a parent pom, one above it, or a profile of either declares the package with a version, the reference is omitted, naming that pom; declare the package in the root pom with no `` (its own declaration replaces the inherited one and the pin governs it) or drop the version from the parent's declaration. The nearest parent declaring it with no version, or a chain read to a pom with no `` that never declares it, leaves the pin attested. A parent that cannot be read (`` or no pom at the relative path, so Maven resolves it from a repository; a pom outside the git checkout; one that does not parse) may declare it either way, so the reference then attests only from the installed copy of the patched version (`-socket.` in the local repository, hash-verified) and is `package_not_found` until a build has resolved it. A pin on the root pom's own declaration, or one governing a declaration the root pom makes with no version, is not weighed against any parent. **Maven user properties** (`vex_maven_config_override`): Maven resolves a `${property}` `` from `.mvn/maven.config`'s `-D` user properties before the pom's `` (`${project.*}` / `${pom.*}` always come from the model). A pin the pom spells through a property that `.mvn/maven.config` redefines resolves that other version, so the reference is omitted. A Socket version that only a `-D` user property supplies is not `pom.xml` wiring (hosted scan never writes one, and `rollback` / `remove` never edit `.mvn/maven.config`): it is no reference at all, only a diagnostic. **pnpm branch locks** (`vex_pnpm_git_branch_lockfile`): with `gitBranchLockfile` on, pnpm installs a git branch from its own `pnpm-lock..yaml` (the **pnpm per-branch locks** state above), which no wiring reaches. `vex` does not decide whether the setting is on: the presence of any branch lock (at the root, or in a workspace member that installs from its own lock under `sharedWorkspaceLockfile: false`, read from the project's files and never from the environment) omits every reference of the root pnpm lock (`pnpm-lock.yaml`, or `shrinkwrap.yaml` without it) and of each member's own lock, hosted and vendored alike, whatever `gitBranchLockfile` or pnpm's `lockfile` setting says (#556; deterministic and fail-closed). This is checked only when a root or member pnpm lock wires a patch. Hosted mode refuses every pnpm pin when the setting is on and vendored mode refuses the project, so this also covers wiring written before the branch lock appeared. The run warning names the branch lock in the marked lock's own directory. Rush locks are not affected. **Self-patched npm and Bun packages** (`vex_npm_patched_dependency`): a reference in `package-lock.json` / `npm-shrinkwrap.json` / `bun.lock` / `bun.lockb` to a package the project patches itself is omitted, by the hosted rewriters' own per-dependency rule (`redirect_npm_patched_dependency_skipped`, #711; `redirect_bun_patched_dependency_skipped`, #367): a root `package.json` `patchedDependencies` key for its `name@version`, its bare name, or `name@` of any tarball (npm and Bun alike); for npm also a non-null `patched` record on any present npm lock's entry for that `name@version`; for `bun.lock` also the keys it mirrors (the run warning then names `bun.lock` as the key's source). npm applies the user's diff on top of whatever tarball the lock names and Bun applies it only to the resolution it is keyed on, so both modes leave such a package unwired; this covers pins an earlier release wrote, and an npm one fails `npm ci` with `EPATCHFAILED` until `socket-patch rollback ` restores the registry entry (the remedy says so). A key naming the pinned tarball itself (a patch made on top of the pin) is no conflict for the hosted rewriters, which keep the pin, but the reference is omitted all the same: the user's diff runs over the Socket bytes, never the Socket patch alone; a reference with neither a hosted url nor a vendored tarball is matched by its `name@version` and counts every tarball key. Only a reference that survives the lock contests carries this reason. **Packages patched with pnpm, Yarn or patch-package** (`vex_npm_patched_dependency` too): a reference of any npm-family lock (pnpm, Rush, yarn classic and berry, vlt, npm, Bun; hosted or vendored) to a `name@version` the project patches itself is omitted, read from the project, its declared workspace members and (on disk) the ancestor workspace settings up to the git repository root, by the consent gate's own walk: pnpm's `patchedDependencies` (`package.json`'s `pnpm.patchedDependencies`, `pnpm-workspace.yaml`'s `patchedDependencies`, and the `patchedDependencies` map or a `(patch_hash=…)` key suffix in the reference's own pnpm lock or the root one), a yarn berry `patch:` descriptor outside Yarn's builtin compatibility patches (`package.json`'s dependency maps and `resolutions`, or a `patch:` locator `yarn.lock` resolves, including one wrapping the hosted tarball), or a patch-package file (`patches/+.patch`, or under a `--patch-dir` a `package.json` script names; it counts for every version of ``, since patch-package applies it to whichever version is installed). A key's version may be exact, a range or absent (every version), and metadata that cannot be read (an unparseable `package.json`, a `--patch-dir` the script computes) omits every npm reference. This is the `user_patch_conflict` consent gate's evidence (see [Existing project patches](#existing-project-patches)) minus native npm / Bun and the other ecosystems, and the evidence the in-memory hosted engine withholds a package by. The package manager (or the postinstall) applies the user's diff on top of whatever tarball the lock names, so the install never runs the Socket patch alone: the reference is omitted even when an `--allow-patch-conflicts` run wired it, for as long as the patch is declared. Yarn classic and vlt have no patch mechanism of their own (vlt's `vlt.json` `modifiers` rewrite specs, not contents), so patch-package is what is read for them. npm's and Bun's own top-level `patchedDependencies` are judged by the rule above, not here. **Go workspaces** (`go_workspace_override`): a hosted or vendored Go `replace` that the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects, by the same check hosted and vendored modes run before writing one (`redirect_golang_workspace_conflict`, `vendor_go_workspace_conflict`), is omitted under the reason `vex`'s own go.mod gate reports. So is a replace in the root `go.work` while go builds another one. **Unpinned Cargo declarations** (`vex_cargo_unpinned_declaration`): cargo resolves each source on its own, so when one declaration of a crate pins it to `socket-patch-` but another — the root `Cargo.toml`'s or a workspace member's, read as hosted scan reads them — is not pinned, with a version requirement that may select the locked patched version, that declaration builds a separate, unpatched copy, possibly of the very version the pin covers. Not pinned means crates.io or another registry that no Socket `[patch.]` registry entry redirects, a `registry-index`, a path or git — the last three even beside `registry = "socket-patch-"`, which they override (hosted scan's own pinned check). The `Cargo.lock` reference is omitted, naming the unpinned declaration's manifest. Hosted scan pins every declaration, so this is a partial revert or a hand edit; the warning says whether re-running `scan` pins it again (a crates.io declaration whose requirement matches no other locked version of the crate) or cannot (`redirect_cargo_toml_dep_unrewritable`: roll the patch back or change the declaration). A declaration whose requirement excludes the patched version (cargo resolves it to another version), and a `[workspace.dependencies]` entry no manifest inherits, do not withhold the statement. When the lock already holds a same-version copy from another source, the reference is withheld as an unpatched lock copy instead. A declaration pinned to ANOTHER Socket patch, which the lock does not resolve the crate from, adds that patch's `Cargo.toml` reference, so the package is gated as `wiring_conflict`. **Vendored Cargo copies a `[patch]` does not reach** (`vex_cargo_patch_bypassed`): a `[patch.]` entry replaces the crate only in declarations from ``, and `vendor` writes `[patch.crates-io]`. So a vendored reference is omitted when a live declaration of the crate (the root `Cargo.toml`'s or a workspace member's) names another registry, a `registry-index` or a git repository, with a version requirement that may select the patched version, unless a `[patch]` table for its source points at the same copy (`[patch.]` for a registry dependency, `[patch.""]` for a `registry-index` one, `[patch.""]` for a git one; URLs compare as cargo canonicalizes them: the host's case, a lock's `registry+` prefix, one trailing `/` and a `.git` suffix ignored, a GitHub URL case-insensitive, a `sparse+` index another source than the git one, and the crates.io git index is crates.io); cargo builds that declaration's own, unpatched copy. Workspace members are read for this whenever the root manifest or the project cargo config wires a Socket copy through `[patch]`, whatever the lock says. It is also omitted when `Cargo.lock` locks the crate at exactly the patched version from any source (a registry, crates.io included, or git) beside the vendored copy; the warning names that lock entry. A path declaration (the user's own fork) does not withhold the statement. Only `[patch]` entries cargo honors count: a manifest entry the project config or a crates.io URL table replaces covers nothing. The warning ends with the remedy for its evidence: for a declaration, re-running `vendor` does not help (declare the crate from crates.io there, point a `[patch]` table for its source at the copy, or roll the patch back); for a stale lock entry a `[patch]` table at the copy redirects (crates.io under `[patch.crates-io]`, or a git repository under its own table), re-lock (`cargo update -p `, or re-run `vendor` for crates.io); for another lock entry, `cargo tree -i @` names the dependency that declares it. +* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Thirteen cases besides Gradle's (`vex_gradle_lock_above_base`) and NuGet's (`vex_nuget_lock_other_version`, see the table above); one of them, a vendored pin in a lock the package manager is told not to read (`vex_lock_not_read`), has its own bullet below; another, **hosted sbt pins a build bypasses** (`vex_sbt_pin_bypassed`), is under **Hosted sbt** above: **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactors** (`vex_maven_reactor_root`): a hosted patch in a reactor (a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers) is omitted while a module that resolves the patched version, or may, is reached by no pin and no declaration of the patch, or a declaration may still build the unpatched version: a module's own literal `` overrides a pin above it (#261). The note names the module. A reactor one of whose poms cannot be read is omitted the same way, whatever its root pins. See [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA (or one whose `` implies a classifier or carries code, such as `test-jar`) is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build), live or inside ``, resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier (a profile's overriding the live one), or no version in the root pom — the pin is omitted. A pre-v5 single-pom vendored repository holds only the main jar, so any such copy omits its reference. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep, writing nothing, when an executable copy may resolve anything but the suffixed pin (so it never writes a pin this rule withholds). **Maven profile declarations** (`vex_maven_profile_unpatched`): a `` declaration of a pinned GA's main jar in the root `pom.xml` at any version other than the pin (the base release, another release, a `${property}` the pom does not resolve) overrides the pin whenever that profile is active, so the reference is omitted. A profile `` entry always counts; a profile `` entry counts only when management governs the pin (no direct `` outside ``), since a direct literal version beats management. A declaration without a `` takes the live pin, and a `pom` (or `java-source` / `javadoc`) typed one carries no code; neither withholds the statement. Activation is not evaluated: every profile counts, as in vendored mode, which rewrites profile declarations too; hosted scan leaves them as written and writes no pin they bypass (`redirect_maven_profile_dependency_unpatched`). A pin spelled through a property counts the same way: a `${property}` `` is interpolated through every property it names, the project's own `${project.version}` included (itself often spelled through `${revision}`), at most 16 levels deep (a cycle or an undefined name never resolves to a pin), and when any profile's `` — or any combination of profiles' together, each nested reference read with that combination active, as the vendored planner weighs them too — redefine one of those properties so that it resolves anything other than the pin (or nothing), the reference is omitted too; a `.mvn/maven.config` user property wins over every profile's. A profile declaration reads its own profile's `` first. When more than 8 profiles may change such a version, or a profile's `` cannot be parsed, the reference is omitted (fail closed); the rest of the pom is still read. One pom's `${property}` texts are also given a fixed amount of interpolation in all (about four million property lookups, which a pom reaches only with thousands of different texts that each take hundreds of lookups under many profile combinations); a `${property}` read after that counts as unresolved, the same fail-closed way. The statement names the profiles that move the pin and the version they move it to. Coordinates count the same way: when a profile's `` (or several profiles' together, or the profile holding the declaration) redefine a property a `${property}` `` / `` names, so that the declaration carrying the pin names another package (the pin then no longer applies to the patched GA) or another declaration names the patched GA (its main jar, or an executable classifier copy) at a version other than the pin, or as a classifier copy with no version of its own, the reference is omitted; a profile value the pom cannot resolve may name any package, a user property wins over every profile's, and the same 8-profile and unreadable-profile limits fail closed. Each such reading is weighed like a declaration of its own: a retargeted classifier copy (a `test-jar` is the `tests` copy; an explicit `` names the copy whatever the type) by the classifier rule (`vex_maven_classifier_unpatched`, so a pre-v5 vendored repository, which serves only the main jar, is bypassed even at the vendored version), any other non-`jar` type not at all, and a reading that moves the coordinates and the version onto the pin together does not withhold the statement. Hosted scan refuses such a dep (`redirect_maven_profile_coordinates_unpatched`), and vendored mode leaves the declaration as written and does not pin its root (`coordinates_overridden`), except a retargeted classifier copy, which it reports as `classifier_declared` with the root still pinned. The same holds for a pre-v5 single-pom vendored repository, which serves only the original version. **Maven parent poms** (`vex_maven_parent_declares`): a pin that only the root pom's `` carries, for a package the root pom does not declare in its own `` (what hosted scan adds for a dependency with no literal ``), governs the declaration the build inherits. Maven merges a parent pom's `` into the child, and management fills in only a dependency that declares no version (Maven 3.9.16: with the parent declaring the package at a literal version the build resolves the upstream jar and never asks for the patched version). The parent chain is followed through the checkout (``, default `../pom.xml`, when the pom there is the parent the reference names). When a parent pom, one above it, or a profile of either declares the package with a version, the reference is omitted, naming that pom; declare the package in the root pom with no `` (its own declaration replaces the inherited one and the pin governs it) or drop the version from the parent's declaration. The nearest parent declaring it with no version, or a chain read to a pom with no `` that never declares it, leaves the pin attested. A parent that cannot be read (`` or no pom at the relative path, so Maven resolves it from a repository; a pom outside the git checkout; one that does not parse) may declare it either way, so the reference then attests only from the installed copy of the patched version (`-socket.` in the local repository, hash-verified) and is `package_not_found` until a build has resolved it. A pin on the root pom's own declaration, or one governing a declaration the root pom makes with no version, is not weighed against any parent. **Maven user properties** (`vex_maven_config_override`): Maven resolves a `${property}` `` from `.mvn/maven.config`'s `-D` user properties before the pom's `` (`${project.*}` / `${pom.*}` always come from the model). A pin the pom spells through a property that `.mvn/maven.config` redefines resolves that other version, so the reference is omitted. A Socket version that only a `-D` user property supplies is not `pom.xml` wiring (hosted scan never writes one, and `rollback` / `remove` never edit `.mvn/maven.config`): it is no reference at all, only a diagnostic. **pnpm branch locks** (`vex_pnpm_git_branch_lockfile`): with `gitBranchLockfile` on, pnpm installs a git branch from its own `pnpm-lock..yaml` (the **pnpm per-branch locks** state above), which no wiring reaches. `vex` does not decide whether the setting is on: the presence of any branch lock (at the root, or in a workspace member that installs from its own lock under `sharedWorkspaceLockfile: false`, read from the project's files and never from the environment) omits every reference of the root pnpm lock (`pnpm-lock.yaml`, or `shrinkwrap.yaml` without it) and of each member's own lock, hosted and vendored alike, whatever `gitBranchLockfile` or pnpm's `lockfile` setting says (#556; deterministic and fail-closed). This is checked only when a root or member pnpm lock wires a patch. Hosted mode refuses every pnpm pin when the setting is on and vendored mode refuses the project, so this also covers wiring written before the branch lock appeared. The run warning names the branch lock in the marked lock's own directory. Rush locks are not affected. **Self-patched npm and Bun packages** (`vex_npm_patched_dependency`): a reference in `package-lock.json` / `npm-shrinkwrap.json` / `bun.lock` / `bun.lockb` to a package the project patches itself is omitted, by the hosted rewriters' own per-dependency rule (`redirect_npm_patched_dependency_skipped`, #711; `redirect_bun_patched_dependency_skipped`, #367): a root `package.json` `patchedDependencies` key for its `name@version`, its bare name, or `name@` of any tarball (npm and Bun alike); for npm also a non-null `patched` record on any present npm lock's entry for that `name@version`; for `bun.lock` also the keys it mirrors (the run warning then names `bun.lock` as the key's source). npm applies the user's diff on top of whatever tarball the lock names and Bun applies it only to the resolution it is keyed on, so both modes leave such a package unwired; this covers pins an earlier release wrote, and an npm one fails `npm ci` with `EPATCHFAILED` until `socket-patch rollback ` restores the registry entry (the remedy says so). A key naming the pinned tarball itself (a patch made on top of the pin) is no conflict for the hosted rewriters, which keep the pin, but the reference is omitted all the same: the user's diff runs over the Socket bytes, never the Socket patch alone; a reference with neither a hosted url nor a vendored tarball is matched by its `name@version` and counts every tarball key. Only a reference that survives the lock contests carries this reason. **Packages patched with pnpm, Yarn or patch-package** (`vex_npm_patched_dependency` too): a reference of any npm-family lock (pnpm, Rush, yarn classic and berry, vlt, npm, Bun; hosted or vendored) to a `name@version` the project patches itself is omitted, read from the project, its declared workspace members and (on disk) the ancestor workspace settings up to the git repository root, by the consent gate's own walk: pnpm's `patchedDependencies` (`package.json`'s `pnpm.patchedDependencies`, `pnpm-workspace.yaml`'s `patchedDependencies`, and the `patchedDependencies` map or a `(patch_hash=…)` key suffix in the reference's own pnpm lock or the root one), a yarn berry `patch:` descriptor outside Yarn's builtin compatibility patches (`package.json`'s dependency maps and `resolutions`, or a `patch:` locator `yarn.lock` resolves, including one wrapping the hosted tarball), or a patch-package file (`patches/+.patch`, or under a `--patch-dir` a `package.json` script names; it counts for every version of ``, since patch-package applies it to whichever version is installed). A key's version may be exact, a range or absent (every version), and metadata that cannot be read (an unparseable `package.json`, a `--patch-dir` the script computes) omits every npm reference. This is the `user_patch_conflict` consent gate's evidence (see [Existing project patches](#existing-project-patches)) minus native npm / Bun and the other ecosystems, and the evidence the in-memory hosted engine withholds a package by. The package manager (or the postinstall) applies the user's diff on top of whatever tarball the lock names, so the install never runs the Socket patch alone: the reference is omitted even when an `--allow-patch-conflicts` run wired it, for as long as the patch is declared. Yarn classic and vlt have no patch mechanism of their own (vlt's `vlt.json` `modifiers` rewrite specs, not contents), so patch-package is what is read for them. npm's and Bun's own top-level `patchedDependencies` are judged by the rule above, not here. **Go workspaces** (`go_workspace_override`): a hosted or vendored Go `replace` that the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects, by the same check hosted and vendored modes run before writing one (`redirect_golang_workspace_conflict`, `vendor_go_workspace_conflict`), is omitted under the reason `vex`'s own go.mod gate reports. So is a replace in the root `go.work` while go builds another one. **Unpinned Cargo declarations** (`vex_cargo_unpinned_declaration`): cargo resolves each source on its own, so when one declaration of a crate pins it to `socket-patch-` but another — the root `Cargo.toml`'s or a workspace member's, read as hosted scan reads them — is not pinned, with a version requirement that may select the locked patched version, that declaration builds a separate, unpatched copy, possibly of the very version the pin covers. Not pinned means crates.io or another registry that no Socket `[patch.]` registry entry redirects, a `registry-index`, a path or git — the last three even beside `registry = "socket-patch-"`, which they override (hosted scan's own pinned check). The `Cargo.lock` reference is omitted, naming the unpinned declaration's manifest. Hosted scan pins every declaration, so this is a partial revert or a hand edit; the warning says whether re-running `scan` pins it again (a crates.io declaration whose requirement matches no other locked version of the crate) or cannot (`redirect_cargo_toml_dep_unrewritable`: roll the patch back or change the declaration). A declaration whose requirement excludes the patched version (cargo resolves it to another version), and a `[workspace.dependencies]` entry no manifest inherits, do not withhold the statement. When the lock already holds a same-version copy from another source, the reference is withheld as an unpatched lock copy instead. A declaration pinned to ANOTHER Socket patch, which the lock does not resolve the crate from, adds that patch's `Cargo.toml` reference, so the package is gated as `wiring_conflict`. **Vendored Cargo copies a `[patch]` does not reach** (`vex_cargo_patch_bypassed`): a `[patch.]` entry replaces the crate only in declarations from ``, and `vendor` writes `[patch.crates-io]`. So a vendored reference is omitted when a live declaration of the crate (the root `Cargo.toml`'s or a workspace member's) names another registry, a `registry-index` or a git repository, with a version requirement that may select the patched version, unless a `[patch]` table for its source points at the same copy (`[patch.]` for a registry dependency, `[patch.""]` for a `registry-index` one, `[patch.""]` for a git one; URLs compare as cargo canonicalizes them: the host's case, a lock's `registry+` prefix, one trailing `/` and a `.git` suffix ignored, a GitHub URL case-insensitive, a `sparse+` index another source than the git one, and the crates.io git index is crates.io); cargo builds that declaration's own, unpatched copy. Workspace members are read for this whenever the root manifest or the project cargo config wires a Socket copy through `[patch]`, whatever the lock says. It is also omitted when `Cargo.lock` locks the crate at exactly the patched version from any source (a registry, crates.io included, or git) beside the vendored copy; the warning names that lock entry. A path declaration (the user's own fork) does not withhold the statement. Only `[patch]` entries cargo honors count: a manifest entry the project config or a crates.io URL table replaces covers nothing. The warning ends with the remedy for its evidence: for a declaration, re-running `vendor` does not help (declare the crate from crates.io there, point a `[patch]` table for its source at the copy, or roll the patch back); for a stale lock entry a `[patch]` table at the copy redirects (crates.io under `[patch.crates-io]`, or a git repository under its own table), re-lock (`cargo update -p `, or re-run `vendor` for crates.io); for another lock entry, `cargo tree -i @` names the dependency that declares it. * **Shrinkwrap without a twin (#899).** npm >= 12 never reads `npm-shrinkwrap.json`: on a project whose only npm lock is the shrinkwrap it resolves the tree from the registry and writes a fresh `package-lock.json`, so a Socket reference there reaches npm <= 11 only. The reference is still discovered, so `list`, `rollback` and `remove` manage it, but `vex` omits the patch (`vex_npm_shrinkwrap_only`, as a run warning and as the `failed[].reason`). A `package-lock.json` beside it (wired the same way) makes it attestable again. Hosted and vendored runs still rewire the shrinkwrap and warn `redirect_npm_shrinkwrap_only` / `vendor_npm_shrinkwrap_only`. * **Locks the package manager is told not to read.** A reference in a lock the project's own configuration turns off proves nothing about what installs. Read from the project's own rc file only (no user or global config, no environment): npm's `package-lock` or its alias `shrinkwrap` set to `false` / `null` in `.npmrc` (`npm install` then ignores `package-lock.json` and `npm-shrinkwrap.json` and resolves from the registry; only `npm ci` still installs from the lock; a `${VAR}` value counts as off); yarn 1's `--install.no-lockfile`, `--*.no-lockfile` or `--no-lockfile` in `.yarnrc` with any value but `false` (yarn neither reads nor writes `yarn.lock`, `--frozen-lockfile` included); a yarn berry `lockfileFilename` in `.yarnrc.yml` naming another file (yarn 2 and 3 read that file, yarn 4 rejects the setting and installs nothing); and pnpm's `lockfile` setting (**pnpm with its lockfile off** above). A hosted reference of such a lock keeps no lockfile basis: `vex` attests it only from an installed tree whose every copy verifies, and discovery warns `patched_ref_unattributable` naming the setting. A vendored reference stays a reference but is omitted (`vex_lock_not_read`, as a run warning and as the `failed[].reason`), because its basis is the committed artifact and nothing installs it through a lock nothing reads; the pnpm exception is an override that routes the package to the artifact. * **Lockless pins.** With no lock to name a version, a `Cargo.toml` pin (every declaration on `socket-patch-`, that registry defined on the patch host for the same uuid) or an exclusive nuget exact-id mapping is never a reference on its own, so v5.0 does not attest it (nor does `list` show it, or `rollback` / `remove` restore it — restore those files from version control). Only a pre-v5 redirect-ledger record naming a version the pin admits keeps it live. For Cargo, declarations are read as for a locked pin (**Unpinned Cargo declarations**): one that is no pin admits nothing, and its requirement (any version, without one) is excluded from the pin; a `[workspace.dependencies]` template no manifest inherits is no declaration at all. The same holds for a gem wired only in the `Gemfile` (the pre-bundler-2.6 mixed state, lock not converged). @@ -2103,7 +2103,10 @@ command's integration tests check its output. | `upstream_gem_install_would_refresh` | `warnings[]` (note) | the same on `--dry-run`: what a wet unwind would replace. | | `redirect_gem_version_not_locked` | `warnings[]` (warning) | scan `--mode hosted` (gem): the crawled gem version is installed on the machine but no `GEM` section of the project's lock resolves it (another project's copy in the shared gem home). The gem is skipped and the Gemfile and lock stay byte-identical. | | `redirect_maven_version_not_selected` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the build does not resolve the artifact at the patch's base version; the detail names the version Maven selects instead, or says that the build does not resolve the artifact. `pom.xml` and `.mvn/` stay byte-identical and the dep is not counted as redirected. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). | -| `redirect_maven_selection_undetermined` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): what the build selects for the artifact cannot be read and `pom.xml` declares no version of it to replace, so no `` pin is written on a guess. `pom.xml` and `.mvn/` stay byte-identical; the detail carries the reason and the remedy (resolve the project once and re-run, or declare the artifact at the base version). | +| `redirect_maven_selection_undetermined` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): what the build selects for the artifact cannot be read and `pom.xml` declares no version of it to replace, so no `` pin is written on a guess. `pom.xml` and `.mvn/` stay byte-identical; the detail carries the reason and the remedy (resolve the project once and re-run, or declare the artifact at the base version). In a reactor it names the first module whose selection cannot be read and counts the rest: those modules get no new pin, while the modules that are certain are still pinned and a declaration that names the base version is still rewritten, so the dep may be counted as redirected beside this warning. | +| `redirect_maven_multimodule_unsupported` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the root `pom.xml` heads a reactor that cannot be planned: a module pom is missing or not readable as a pom, a `` path is a property or leaves the project, or the grant serves the patched artifact under its original version (a same-GAV grant). The detail carries the reason. The poms and `.mvn/` stay byte-identical and the dep is not counted as redirected. A reactor that can be read is patched module by module: see [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). | +| `redirect_maven_pin_would_move_module` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven reactor): a parent pom resolves the base version itself above a module that resolves another version, so the parent takes no pin (Maven's management always reaches the children); the modules below it that select the base version are pinned. Also reported when a pin an earlier run wrote is taken out because a module it reaches now resolves another version, which the pin would hold back (the `redirect_maven_dep_management` edit has `action: "removed"`). Exit 0. | +| `redirect_maven_edit_not_reversible` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): a pom would take an edit that `rollback` could not undo byte for byte from the pom alone (a pin in a `` that holds no entry, which would be left changed or removed). That pom is left as it is; the modules it would have wired stay unpatched, and `vex` withholds the statement while one of them resolves the base version. Exit 0. | | `redirect_gem_no_checksums_section` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock has no `CHECKSUMS` section (Bundler < 2.6 does not write one), so it cannot record the sha256 of the patched gems. They are redirected all the same (manifest and lock converged, frozen installs accept the pair) and pinned by source alone. Reported once per run, naming the gems; relock with Bundler ≥ 2.6 (`bundle lock --add-checksums`) and re-run to pin the checksums too. | | `redirect_gem_merged_lock_layout` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock was written by Bundler < 2.2 (`BUNDLED WITH`), which lists every gem source in ONE `GEM` section, so this run added the patch registry to that section's `remote:` lines. The pair installs with that Bundler, frozen / deployment mode included. Newer Bundlers deprecate such a section and from 2.5 on refuse the pair under frozen / deployment mode: if a newer Bundler installs the project, run `bundle lock` with it, commit the lock and re-run the hosted scan. Raised only by a run that wrote the lock. | | `redirect_gem_unrecognized_declaration` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the gem's declaration cannot take a `source:` option in place (the detail gives the reason). The gem is skipped and the manifest and lock stay byte-identical for it; write the declaration as one `gem "", …` call with literal arguments on a line of its own, or use `--mode vendored` / `--mode agent`. | @@ -2773,6 +2776,95 @@ not reach that resolves the base version, or whose selection cannot be told on the machine that runs `vex`, withholds the attestation, with the module named. `vendor --check` does not ask this. +### Hosted Maven reactors and property versions + +Hosted mode patches a multi-module reactor, and a declaration whose +`` is a `${property}`, with pom edits only. It plans both with the +reactor planner vendored mode uses, over every pom of the reactor (the modules +the root lists, theirs in turn, and each parent pom a module inherits from +inside the checkout; a single pom is a reactor of one), with the same +selection and the same placement: + +- A declaration that names the base version is rewritten where it stands, in + whichever pom holds it (`redirect_maven_dep_version`, `path` the pom). +- The `` pin goes in the highest pom whose modules all + resolve the artifact at the base version or not at all, down to one module's + own `pom.xml` (`redirect_maven_dep_management`, `redirect_maven_dep_management_added` + naming the pom). A module that resolves another version is never reached. A + module a declaration already wires has no say and needs no pin. The pin is + the entry vendored mode writes, with its comment: + `` on the line before the + ``. A single pom that hosted mode pins without the planner (no + `${property}` version) keeps the uncommented entry earlier releases wrote. +- The `` (`socket-patch-`) goes in the local root each wired + pom inherits from: the reactor root, or a module's own pom when its parent + is not in the checkout. It is absolute, so it resolves the same from the + root, from a module directory, and with `-f`. +- The Trusted Checksums files stay in the project root's `.mvn/`. Maven finds + that directory by walking up from the pom it is started on, so a build + started in a module directory or with `-f` reads it too. A module with a + `.mvn` of its own is reported (`redirect_maven_trusted_checksums_unenforced`): + a Maven started there reads that directory, not the root's, so the checksum + pin is not enforced for that build. The version suffix still is. + +A `${property}` version is wired in the least invasive way that `rollback` +can undo exactly from the pom: + +1. **The property's own value.** When the reactor's poms define the property + once, at top level, as the base version, and every `${name}` in every pom + of the reactor is the whole `` of a declaration of the patched + artifact, the value takes the patched version and the declarations keep + their text (`redirect_maven_property`, `key` the property name). No other + artifact reads it, so none is moved. Not taken when a profile, + `.mvn/maven.config` or the project model defines the name too. +2. **No declaration at all.** A version-less declaration that a parent pom or + a BOM manages through a property is not edited: the `` + pin overrides that management. +3. **The one declaration, with its text recorded.** Otherwise the declaration + takes the literal patched version, and a comment directly after the element + records the text it replaced: + `1.2-socket.0a1b2c3d` + (`redirect_maven_dep_version`, `original` the `${...}` text). The property + and every sibling that reads it are untouched. From then on that one + declaration no longer follows the property. A property no pom of the + checkout defines (a parent resolved from a repository does) is read from + what Maven selects: the declaration is rewritten only when every module + that reads it is certain to select the base version, and is otherwise left + as it is (`redirect_maven_dep_unpinned`). + +No ledger records these edits. Each says what it replaced by its own text: the +base version is the suffix's prefix, a pin is its commented entry (and the +section that held nothing else), a recorded declaration carries its comment. +The planner undoes every pom it would change before it writes anything, and +leaves a pom alone when that does not give back the text it had +(`redirect_maven_edit_not_reversible`). `rollback` and `remove` undo the wiring +in every pom `list` finds it in, or in none: each pom returns to its bytes +before the scan, the `` goes from whichever pom declares it, and +the `.mvn/` lines and files hosted mode wrote are removed. + +Where the pins go is decided when a patch is first wired, as in vendored mode: +a later scan keeps every pin where it is and adds none, so a second scan +changes nothing. The exceptions are the same: a pin of an earlier patch of the +same version moves to the new suffix where it stands (its repository and +checksum lines are replaced), and a pin that now reaches a module resolving +another version is taken out and written where it belongs +(`redirect_maven_pin_would_move_module`). + +`vex` attests a hosted patch in a reactor by the vendored rule above: every +module that resolves the base version, or may, is reached by a pin or a +declaration of the patch, and no declaration may still build the base version. +Otherwise the statement is withheld and the module named +(`vex_maven_reactor_root`). What each module selects is read from the Maven +local repository of the machine that runs `vex`. + +A hosted pin an earlier release wrote in a single pom carries no comment. It +is still found, rolled back and removed as before. When that pom has since +come to head a reactor, the pin is kept as it is (no new pin is added, since +the patch is already wired), `vex` weighs it module by module like any other, +and `rollback` restores its version; an entry that release added to +`` is then left at the base version instead of removed, +since in a reactor it cannot be told from the project's own. + Where the pins go is decided when a patch is first wired, and the committed poms are the record of it. A later run over poms that already wire the patch (a pin of its version, or a declaration at its `-socket.` version) keeps @@ -3192,7 +3284,7 @@ match it, withholds the statement: | `vex_gradle_lock_above_base` | run warning and `failed[].reason` | A hosted pin is wired, but a lock file records a release above its base, which that build resolves instead of the patch; no statement until it is re-locked or the patch is rolled back. | | `vex_pnpm_bundled_copy` | run warning and `failed[].reason` | An npm pin is wired, but its pnpm lock names a package whose `bundledDependencies` may ship an unpatched copy of it (the lock does not record that copy's version); no statement while that package bundles it. `vendor --check` and `scan` still treat the wiring as live. | | `vex_deno_lock_copy` | run warning and `failed[].reason` | An npm pin is wired, but `deno.lock` locks the same `name@version`, which `deno install` installs without the wiring; no statement while it does. `vendor --check` and `scan` still treat the wiring as live. | -| `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven pin sits in a root `pom.xml` that declares `` / `` (a profile's included), where a module's own literal `` overrides it; only the root pom is read, so no statement (#261). `list`, `rollback` and `remove` still find the pin. | +| `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven patch is wired in a reactor (`` / ``, a profile's included, or Maven 4 subproject discovery) one of whose modules may build the unpatched version: it resolves the patched version, or its selection cannot be told on the machine that runs `vex`, and no pin or declaration of the patch reaches it; or a declaration may still build the base version; or a pom of the reactor cannot be read. No statement; the note names the module (#261). `list`, `rollback` and `remove` still find the wiring. | | `go_workspace_override` | run warning and `failed[].reason` | A hosted or vendored Go `replace` is wired, but the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects it, or go builds another `go.work` than the root's that holds it; no statement while it does. `list`, `rollback` and `remove` still find the replace. | | `vex_maven_classifier_unpatched` | run warning and `failed[].reason` | A hosted (or pre-v5 vendored) Maven pin's GA also has an executable `` copy (not `sources` / `javadoc`; live or inside ``) at a version other than the pin, which the classifier-less pin does not retarget and the grant does not serve; no statement while it does. `list`, `rollback` and `remove` still find the pin. | | `vex_maven_profile_unpatched` | run warning and `failed[].reason` | A Maven pin's GA main jar is also declared inside `` in the root `pom.xml` at a version other than the pin (a profile `` entry only where management governs the pin), or a profile's `` redefine a property the pin's `${property}` version names so it resolves another version, or a property a `${property}` groupId / artifactId names so the pin names another package or another declaration becomes the pinned GA off the pin, which overrides the pin whenever that profile is active; no statement while it does. `list`, `rollback` and `remove` still find the pin. | diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index 79e73c88a..c1bc04da1 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -326,8 +326,9 @@ fn unattested_note(kind: UnattestedKind) -> (&'static str, &'static str) { ), UnattestedKind::MavenReactorRoot => ( NOTE_MAVEN_REACTOR_ROOT, - "not attested while the root declares modules (roll it back and re-patch the \ - reactor with `scan --mode vendored`)", + "not attested while a module of the reactor may build the unpatched version \ + (re-run `scan` once that module resolves it, or patch the reactor with `scan \ + --mode vendored`)", ), UnattestedKind::MavenClassifierUnpatched => ( NOTE_MAVEN_CLASSIFIER_UNPATCHED, diff --git a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs index 525112fae..f1567d895 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs @@ -525,6 +525,8 @@ fn maven_scan_hosted_fresh_checkout_install_and_manifestless_vex() { // ── a pin follows the version Maven selects ───────────────────────────── mod mediation { + use std::collections::BTreeMap; + use super::maven_mediation_common::{self as fixture, Shape}; use super::*; @@ -731,4 +733,386 @@ mod mediation { // and no pom of this project names it: a range selects another. unselected(Shape::Ranged).expect("the local repository is warm"); } + /// What a hosted mediation test runs against: the fixture repository, + /// the patch API and the Socket repository of [`PATCH`] on one server, + /// a cold local repository, and Maven settings without and with the + /// Socket repository mirrored to that server. + struct Bench { + _tmp: tempfile::TempDir, + root: PathBuf, + m2: PathBuf, + plain: PathBuf, + mirrored: PathBuf, + server: Server, + patched_jar: Vec, + suffixed: String, + view: serde_json::Value, + } + + impl Bench { + fn new() -> Bench { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().canonicalize().unwrap(); + let plain = root.join("settings-plain.xml"); + write_settings(&plain, &[]); + let server = Server::start(); + fixture::publish(&server); + let patched_jar = fixture::patched_victim_jar(); + let suffixed = PATCH.suffixed(); + let served_pom = fixture::served_victim_pom(&suffixed).into_bytes(); + let view = patch_view( + UUID, + &fixture::purl(), + &[( + &fixture::victim_jar_name(fixture::BASE), + &git_sha256(&patched_jar), + )], + &[(PATCH.ghsa, &[PATCH.cve])], + ); + hosted_maven_common::mount_api(&server, &PATCH, &patched_jar, &served_pom, &view); + fixture::answer_lookups_only_for(&server, ORG, &fixture::purl()["pkg:maven/".len()..]); + server.serve_repo(&PATCH, &patched_jar, &served_pom, None); + let mirrored = root.join("settings-socket.xml"); + let mirror_url = format!("{}{}", server.uri(), PATCH.repo_path()); + write_settings(&mirrored, &[(&format!("socket-patch-{UUID}"), &mirror_url)]); + Bench { + m2: root.join("m2"), + _tmp: tmp, + root, + plain, + mirrored, + server, + patched_jar, + suffixed, + view, + } + } + + fn scan(&self, proj: &Path) -> (Option, serde_json::Value, String) { + socket( + proj, + &self.m2, + &[ + "scan", + "--mode", + "hosted", + "--json", + "--yes", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + &self.server.uri(), + "--org", + ORG, + "--api-token", + "fake", + ], + ) + } + + /// Roll the project back (Maven's restore needs no network), and + /// check that it is the hosted pin of the victim that went. + fn rollback(&self, proj: &Path) { + let (code, env, stderr) = socket( + proj, + &self.m2, + &[ + "rollback", + "--json", + "--offline", + "--cwd", + proj.to_str().unwrap(), + ], + ); + assert_eq!(code, Some(0), "rollback: {env}\n{stderr}"); + assert_eq!( + rollback_json::hosted_reverted(&env), + serde_json::json!([fixture::purl()]), + "rollback restores the hosted pin: {env}" + ); + } + + /// A second scan finds the wiring of the first and writes nothing. + fn assert_rescan_is_a_no_op(&self, proj: &Path) { + let pinned = fixture::snapshot(proj); + let (code, env, stderr) = self.scan(proj); + assert_eq!(code, Some(0), "rescan: {env}\n{stderr}"); + assert_eq!( + fixture::snapshot(proj), + pinned, + "a rescan is a no-op: {env}" + ); + } + + /// The invariant: `after` holds the artifacts of `before`, the + /// base victim in its patched build and every other jar as it was. + fn assert_only_the_victim_is_patched( + &self, + what: &str, + before: &BTreeMap>, + after: &BTreeMap>, + ) { + assert_eq!( + fixture::unsuffixed(after.keys()), + before.keys().cloned().collect(), + "{what}: the same artifacts, the victim in its patched build" + ); + assert_eq!( + after.get(&fixture::victim_jar_name(&self.suffixed)), + Some(&self.patched_jar), + "{what}: Maven resolves the patched jar: {:?}", + after.keys() + ); + for (name, bytes) in before { + if *name != fixture::victim_jar_name(fixture::BASE) { + assert_eq!(after.get(name), Some(bytes), "{what}: {name} is untouched"); + } + } + } + } + + /// A `${property}` version is patched in hosted mode, with pom edits + /// only, and no artifact that shares the property is moved: + /// + /// - a property only the patched artifact reads is rewritten itself; + /// - a property a sibling artifact reads too stays as it is, and the + /// one declaration takes the patched version, the text it replaced + /// recorded beside it; + /// - so does a declaration whose property a parent pom resolved from a + /// repository defines. + /// + /// In each, Maven resolves what it resolved before but for the patched + /// build of the victim, a second scan writes nothing, and a rollback + /// restores every file byte for byte and leaves none behind. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_patches_a_property_version_and_rolls_back_clean() { + use fixture::Property; + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let bench = Bench::new(); + let suffixed = &bench.suffixed; + for property in [Property::Own, Property::Shared, Property::OfParent] { + let what = property.name(); + let proj = bench.root.join(what); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("pom.xml"), + fixture::property_pom(property, &bench.server), + ) + .unwrap(); + let Some(before) = + fixture::resolve(SUITE, &mvn, &proj, &bench.m2, &bench.plain, "target/before") + else { + return; + }; + assert!( + before.contains_key(&fixture::victim_jar_name(fixture::BASE)), + "{what}: {:?}", + before.keys() + ); + let pristine = fixture::snapshot(&proj); + + let (code, env, stderr) = bench.scan(&proj); + assert_eq!(code, Some(0), "{what}: {env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{what}: {env}"); + let wired = std::fs::read_to_string(proj.join("pom.xml")).unwrap(); + let reference = property.reference(); + match property { + Property::Own => assert!( + wired.contains(&format!("{suffixed}")) + && wired.contains(&format!("{reference}")), + "the property takes the patched version, the declaration keeps its \ + text:\n{wired}" + ), + Property::Shared | Property::OfParent => assert!( + wired.contains(&format!( + "{suffixed}" + )), + "{what}: the declaration takes the patched version, and says what it \ + replaced:\n{wired}" + ), + } + if property == Property::Shared { + assert!( + wired.contains(&format!( + "{}", + fixture::BASE + )) && wired.contains(&fixture::dependency(fixture::SIBLING, &reference, "")), + "the property and the sibling that reads it are as they were:\n{wired}" + ); + } + assert!( + wired.contains(&format!("socket-patch-{UUID}")), + "{what}:\n{wired}" + ); + + let after = + fixture::resolve_warm(&mvn, &proj, &bench.m2, &bench.mirrored, "target/after", &[]); + bench.assert_only_the_victim_is_patched(what, &before, &after); + bench.assert_rescan_is_a_no_op(&proj); + + bench.rollback(&proj); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "{what}: rollback restores every file byte for byte and leaves none behind" + ); + } + } + + /// A multi-module reactor is patched in hosted mode module by module + /// (the table's V3): the module that reaches the base version through + /// another artifact gets the pin in its own pom, the module that + /// declares it has that declaration rewritten, and the module that + /// resolves a newer version is not touched and resolves what it + /// resolved before. The repository and the Trusted Checksums sit at + /// the root every module inherits, so a Maven started in a module + /// directory resolves the patched jar too. `vex` attests the patch + /// while every module that resolves the base version is wired, and + /// withholds it, naming the module, once one is not. A rollback + /// restores every pom byte for byte and removes what the scan created. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_patches_a_reactor_module_by_module_and_rolls_back_clean() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let bench = Bench::new(); + let suffixed = &bench.suffixed; + let proj = bench.root.join("reactor"); + fixture::write_reactor(&proj, &bench.server); + let Some(before) = + fixture::resolve_reactor(SUITE, &mvn, &proj, &bench.m2, &bench.plain, "target/before") + else { + return; + }; + let pristine = fixture::snapshot(&proj); + let was = |rel: &str| String::from_utf8(pristine[rel].clone()).unwrap(); + let now = |rel: &str| std::fs::read_to_string(proj.join(rel)).unwrap(); + + let (code, env, stderr) = bench.scan(&proj); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + assert!( + warning(&env, "redirect_maven_multimodule_unsupported").is_none(), + "{env}" + ); + let a = now("a/pom.xml"); + assert!( + a.contains(&format!( + "", + fixture::GROUP, + fixture::VICTIM, + fixture::BASE + )) && a.contains(&format!("{suffixed}")), + "a reaches the base version through another artifact, and is pinned:\n{a}" + ); + assert_eq!( + now("c/pom.xml"), + was("c/pom.xml").replace( + &format!("{}", fixture::BASE), + &format!("{suffixed}") + ), + "c declares the base version, and only that version text changes" + ); + assert_eq!( + now("b/pom.xml"), + was("b/pom.xml"), + "b resolves another version and is not touched" + ); + let root = now("pom.xml"); + assert!( + root.contains(&format!("socket-patch-{UUID}")) && !root.contains(suffixed), + "the root takes the repository every module inherits, and no pin:\n{root}" + ); + assert!(proj.join(".mvn/checksums/checksums.sha256").is_file()); + for module in ["a", "b", "c"] { + assert!( + !proj.join(module).join(".mvn").exists(), + "{module}: the Trusted Checksums are the root's" + ); + } + + let after = fixture::resolve_reactor( + SUITE, + &mvn, + &proj, + &bench.m2, + &bench.mirrored, + "target/after", + ) + .expect("the local repository is warm"); + for (module, selects, ..) in fixture::REACTOR_MODULES { + if selects == fixture::BASE { + bench.assert_only_the_victim_is_patched(module, &before[module], &after[module]); + } else { + assert_eq!( + after[module], before[module], + "{module} resolves what it resolved before" + ); + } + } + // Started in a module directory, Maven reads the parent pom for the + // repository and the root's `.mvn` for the checksums. + let from_module = fixture::resolve_warm( + &mvn, + &proj.join("a"), + &bench.m2, + &bench.mirrored, + "target/from-module", + &[], + ); + bench.assert_only_the_victim_is_patched( + "a, from its directory", + &before["a"], + &from_module, + ); + bench.assert_rescan_is_a_no_op(&proj); + + // VEX: attested while every module that resolves the base version + // is wired. + let api = PatchApi::start(vec![(UUID.to_string(), bench.view.clone())]); + let run = VexRun { + proxy_url: Some(api.uri()), + ..vex_run(&bench.m2) + }; + let out = run_vex(&binary(), &proj, &run); + assert_eq!(out.code, Some(0), "{out}"); + assert_attested( + out.doc(), + &fixture::purl(), + UUID, + Marker::Redirected, + &[(PATCH.ghsa, &[PATCH.cve])], + ); + // A module that comes to declare the base version itself builds the + // unpatched jar, whatever its siblings are wired to. + let wired_b = now("b/pom.xml"); + std::fs::write( + proj.join("b/pom.xml"), + fixture::module_pom("b", fixture::VICTIM, fixture::BASE), + ) + .unwrap(); + let out = run_vex(&binary(), &proj, &run); + assert_omitted( + &out, + &fixture::purl(), + "vex_maven_reactor_root", + "a module that builds the unpatched version", + ); + assert!( + out.envelope.to_string().contains("b/pom.xml"), + "the note names the module: {out}" + ); + std::fs::write(proj.join("b/pom.xml"), wired_b).unwrap(); + + bench.rollback(&proj); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "rollback restores every pom byte for byte and removes what the scan created" + ); + } } diff --git a/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs index 8a49bed79..553c55324 100644 --- a/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs +++ b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs @@ -14,6 +14,9 @@ //! `lib-range:1.0` → `victim:[1.10.5,1.11.0]`. //! * the artifact-level `maven-metadata.xml` of `victim`, which resolves //! the range. +//! * `sibling:1.10.0`, which shares the victim's base version (and so can +//! share a version property with it), and the parent poms `lib-parent` +//! and `lib-parent-props`, the latter defining [`PARENT_PROPERTY`]. //! //! One [`Shape`] per row of the bug: which version Maven selects for the //! victim, with the base version somewhere else in the graph (deeper, @@ -214,10 +217,11 @@ fn serve(server: &Server, rel: &str, bytes: &[u8]) { /// Serve the fixture repository from `server`. pub fn publish(server: &Server) { - let artifacts: [(&str, &str, &[(&str, &str)]); 8] = [ + let artifacts: [(&str, &str, &[(&str, &str)]); 9] = [ (VICTIM, OLDER, &[]), (VICTIM, BASE, &[]), (VICTIM, NEWER, &[]), + (SIBLING, BASE, &[]), ("lib-base", "1.0", &[(VICTIM, BASE)]), ("lib-new", "1.0", &[(VICTIM, NEWER)]), ("lib-old", "1.0", &[(VICTIM, OLDER)]), @@ -248,6 +252,20 @@ pub fn publish(server: &Server) { ) .as_bytes(), ); + // A parent pom that defines the version property its children read. + serve( + server, + &format!("{GROUP_PATH}/{PARENT_WITH_PROPERTY}/1.0/{PARENT_WITH_PROPERTY}-1.0.pom"), + fixture_pom(PARENT_WITH_PROPERTY, "1.0", &[]) + .replace( + "1.0\n", + &format!( + "1.0\n pom\n \n \ + <{PARENT_PROPERTY}>{BASE}\n \n" + ), + ) + .as_bytes(), + ); let versions: String = [OLDER, BASE, NEWER] .iter() .map(|v| format!(" {v}\n")) @@ -369,6 +387,82 @@ pub fn resolve_reactor( /// A parent pom the fixture repository serves. pub const PARENT: &str = "lib-parent"; +/// A parent pom the fixture repository serves that defines +/// [`PARENT_PROPERTY`] as the victim's base version. +pub const PARENT_WITH_PROPERTY: &str = "lib-parent-props"; +pub const PARENT_PROPERTY: &str = "corp.victim.version"; +/// An artifact published at the victim's base version. +pub const SIBLING: &str = "sibling"; + +/// How a project names the victim's version through a property. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Property { + /// The project defines it, and only the victim's declaration reads it. + Own, + /// The project defines it, and [`SIBLING`] reads it too. + Shared, + /// A parent pom resolved from the repository defines it. + OfParent, +} + +impl Property { + pub fn name(self) -> &'static str { + match self { + Property::Own => "property-own", + Property::Shared => "property-shared", + Property::OfParent => "property-of-parent", + } + } + + /// The property the victim's `` reads. + pub fn reference(self) -> String { + match self { + Property::Own => "${victim.version}".to_string(), + Property::Shared => "${fixture.version}".to_string(), + Property::OfParent => format!("${{{PARENT_PROPERTY}}}"), + } + } +} + +/// The `pom.xml` of a project that declares the base victim through +/// `property`. +pub fn property_pom(property: Property, server: &Server) -> String { + let reference = property.reference(); + let pom = project_pom(Shape::Selected, server); + let own = |name: &str| { + format!( + " jar\n \n <{name}>{BASE}\n \ + \n" + ) + }; + let (head, dependencies) = match property { + Property::Own => ( + pom.replace(" jar\n", &own("victim.version")), + dependency(VICTIM, &reference, ""), + ), + Property::Shared => ( + pom.replace(" jar\n", &own("fixture.version")), + [ + dependency(VICTIM, &reference, ""), + dependency(SIBLING, &reference, ""), + ] + .concat(), + ), + Property::OfParent => ( + pom.replace( + " com.example\n", + &format!( + " \n {GROUP}\n \ + {PARENT_WITH_PROPERTY}\n \ + 1.0\n \n \n \ + com.example\n" + ), + ), + dependency(VICTIM, &reference, ""), + ), + }; + head.replace(&dependency("lib-deep", "1.0", ""), &dependencies) +} /// The `pom.xml` of a project that inherits [`PARENT`] from the repository /// and declares the base victim itself. diff --git a/docs/design/lock-model-divergences.md b/docs/design/lock-model-divergences.md index e79113a10..d645efb33 100644 --- a/docs/design/lock-model-divergences.md +++ b/docs/design/lock-model-divergences.md @@ -29,7 +29,7 @@ follow from the install-tree decision. N11 was decided on 2026-11-05. | # | Question | Hosted today | Decision | |---|---|---|---| | J1 | Does a base-version Maven dependency declared in a `` block block attestation? | Warns, still pins the top level and counts the package as redirected (`patch/redirect/mod.rs` ~8744) | Vendored's rule: any profile declaration at the base version makes the ref unattested (fixed now in discovery), and the merged planner rewrites profile declarations in both modes. | -| J3 | Which Maven poms count? | Refuses a reactor root (~8572) | The reactor reader becomes the shared core, so hosted gains reactor support. | +| J3 | Which Maven poms count? | Reads every pom of a reactor through the vendored reactor planner (`maven_reactor::plan_hosted`); a reactor it cannot read is refused | The reactor reader becomes the shared core, so hosted gains reactor support. | | J12 | scala-cli | Guidance only (`patch/redirect/scala_guidance.rs`) | Back-port: hosted wires scala-cli through the merged planner (a same-GAV Socket repository instead of a suffixed version). | | P3 | Is a shadowed `pdm.lock` rewritten? | Only when it governs (`pdm_drives`, ~564) | Rewrite it like every other tree, per the install-tree decision. | | P4 | Are `-r` includes of `requirements.txt` rewritten? | Root file only (`patch/redirect/requirements.rs` ~208) | Follow includes, per the install-tree decision. An include outside the repository root stays bounded in workspace runs: never read or rewritten (owner, 2026-11-05; #2025 (draft)). | diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 5363a8fe7..6b99584a3 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -855,9 +855,9 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: so a resolver that can't reach the Socket repo, or is handed different bytes, has nowhere to fall through to: the build **hard-fails** instead of silently resolving the unpatched upstream artifact. The ``'s `checksumPolicy=fail` still verifies - the transport-level `.jar.sha1` sidecar on top. A `${property}` version is refused - (`redirect_maven_dep_unpinned`) — a literal edit would break the property reference and - a depMgmt pin could strand sibling artifacts sharing the property. A literal version + the transport-level `.jar.sha1` sidecar on top. A `${property}` version is patched + without stranding an artifact that shares the property (see **Property versions** + below). A literal version that matches neither the base nor the suffixed value is skipped (`redirect_maven_dep_version_mismatch`). A `-socket.` literal left by an earlier hosted patch for the same release (the pom declares that patch's @@ -912,13 +912,44 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: to patch and is left out of an agent scan. Maven 4 builds, profiles that declare dependencies or management, relocations and dependency cycles are not modelled: the artifacts they touch count as not readable. -* **Multi-module reactors are vendored-only (hosted Maven).** Hosted mode reads only - the root `pom.xml`, and a module's own literal `` always beats a root - `` pin, so a root pin would leave that module on the unpatched - upstream jar. A root that declares `` or `` (directly or in a - profile) is therefore refused with `redirect_maven_multimodule_unsupported` (`pom.xml` and - `.mvn/` are left untouched and the dep is not counted as redirected); use `scan --mode vendored`, whose reactor planner rewrites each module's - declaration. `vex` likewise does not attest a hosted pin found in a reactor root. +* **Multi-module reactors (hosted Maven).** A root that declares `` or + `` (directly or in a profile, or a Maven 4 root whose subprojects Maven + discovers) is patched module by module, with pom edits only, by the planner vendored + mode uses. A declaration that names the patched version is rewritten where it stands, + in whichever pom holds it. The `` pin goes in the highest pom + whose modules all resolve the artifact at that version or not at all: the root when + the whole reactor agrees, else the modules that do, down to one module's own + `pom.xml`. A module that resolves another version is never reached and resolves what + it resolved before. Such a pin carries the comment vendored pins carry + (``), which is how a later run tells it from the + project's own management. The `` goes in the local root every wired pom + inherits (a module whose parent is not in the checkout gets its own), and the Trusted + Checksums stay in the project root's `.mvn/`, which Maven also reads when it is + started in a module directory or with `-f`; a module with a `.mvn` of its own is + reported (`redirect_maven_trusted_checksums_unenforced`), since a Maven started there + reads that one. A reactor one of whose poms cannot be read is left untouched + (`redirect_maven_multimodule_unsupported`, with the reason). `vex` attests the patch + only when every module that resolves the patched version, or may, is reached by a pin + or a declaration; otherwise it withholds the statement and names the module + (`vex_maven_reactor_root`). `rollback` and `remove` undo the wiring in every pom and + restore each byte for byte. +* **Property versions (hosted Maven).** A declaration whose `` is a + `${property}` is patched in one of two ways, and neither moves another artifact. When + the reactor's own poms define the property once and nothing but declarations of the + patched artifact reads it, the property's value takes the patched version and the + declarations keep their text. Otherwise (a sibling artifact reads it too, a profile or + `.mvn/maven.config` may redefine it, or a parent pom outside the checkout defines it) + the one declaration takes the literal patched version, and the text it replaced is + recorded in a comment right after it: + `1.2-socket.0a1b2c3d`. + Rollback reads that comment back, so the declaration returns to its `${...}` text + exactly. Such a declaration no longer follows the property: bump the property and the + patched artifact stays where it is until the next `scan`. A property no pom of the + checkout defines is read from what Maven selects for the modules that read the + declaration; when that cannot be told (the parent pom is not in the local Maven + repository yet) the declaration is left as it is (`redirect_maven_dep_unpinned`). + A version-less declaration a parent or BOM manages needs no edit of its own: the + `` pin overrides the management. * **A parent pom can override a managed pin (hosted Maven).** For a dependency with no literal `` in the root pom (a transitive one, or one whose version a parent manages), hosted mode pins it in the root pom's `` From 8d4fbb8bd45f83ba12a49f4a611e48dbf935f0a5 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 05:11:18 -0500 Subject: [PATCH 12/18] Let a later hosted scan pin the Maven modules an earlier one could not tell A hosted scan over a cold local Maven repository rewrites the declarations that name the base version and pins nothing where what Maven selects cannot be told, saying so with the remedy: resolve the project once and scan again. That second scan then found the patch already wired and, by the rule vendored mode keeps (pins are placed when a patch is first wired), added nothing, so the reactor stayed half patched whatever was done. A patch the poms already wire still keeps every pin where it is. A module that no pin or declaration reaches and that is now certain to select the base version is pinned all the same, by the usual placement over the unreached modules only. A scan told nothing new still writes nothing. The pieces of `place_pins` this needs are split out (`keeps_placement`, `undetermined_note`); vendored planning is unchanged. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 16 +++-- .../src/vendor/jvm/maven_reactor.rs | 64 +++++++++++-------- .../src/vendor/jvm/maven_reactor/hosted.rs | 39 +++++++++-- .../vendor/jvm/maven_reactor/hosted/tests.rs | 43 +++++++++++++ 4 files changed, 125 insertions(+), 37 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index e55fc7f3d..e7d70e404 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2842,13 +2842,15 @@ in every pom `list` finds it in, or in none: each pom returns to its bytes before the scan, the `` goes from whichever pom declares it, and the `.mvn/` lines and files hosted mode wrote are removed. -Where the pins go is decided when a patch is first wired, as in vendored mode: -a later scan keeps every pin where it is and adds none, so a second scan -changes nothing. The exceptions are the same: a pin of an earlier patch of the -same version moves to the new suffix where it stands (its repository and -checksum lines are replaced), and a pin that now reaches a module resolving -another version is taken out and written where it belongs -(`redirect_maven_pin_would_move_module`). +A later scan keeps every pin where an earlier one wrote it, so a second scan +changes nothing. It adds a pin only for a module that nothing reaches yet and +that is now certain to select the base version: a first scan over a cold Maven +local repository wires what it can tell (`redirect_maven_selection_undetermined` +names the rest), and the next one, once the project was resolved there, +completes it. A pin of an earlier patch of the same version moves to the new +suffix where it stands (its repository and checksum lines are replaced), and a +pin that now reaches a module resolving another version is taken out and +written where it belongs (`redirect_maven_pin_would_move_module`). `vex` attests a hosted patch in a reactor by the vendored rule above: every module that resolves the base version, or may, is reached by a pin or a diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs index cea85e8b4..0f7dc7b5e 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs @@ -503,16 +503,9 @@ fn place_pins( closed: &dyn Fn(&String) -> bool, warnings: &mut Vec, ) -> (BTreeSet, BTreeSet) { - let (g, a) = (patch.group_id, patch.artifact_id); let mut pins: BTreeSet = BTreeSet::new(); let mut held: BTreeSet = BTreeSet::new(); - let moves = under.is_some_and(|under| { - reactor.scope.iter().any(|rel| { - pin_of(&reactor.poms[rel].doc, patch).is_some() - && under.get(rel).is_some_and(|u| u.other.is_some()) - }) - }); - if reactor.wired_before(patch) && !moves { + if keeps_placement(reactor, patch, under) { // (A local root a declaration ruled out stays ruled out.) held.extend(reactor.scope.iter().filter(|rel| !closed(rel)).cloned()); return (pins, held); @@ -542,29 +535,50 @@ fn place_pins( .into_iter() .map(|detail| degraded("pin_would_move_module", detail)), ); - // One line for every module that cannot be told, however many. + warnings.extend(under.and_then(|under| undetermined_note(patch, under))); + (pins, held) +} + +/// Whether the pins of `patch` stay where the poms have them: the poms +/// already wire the patch, and no pin is certain (by `under`) to move a +/// module to another version than Maven selects for it. +fn keeps_placement( + reactor: &Reactor, + patch: &JvmPatch<'_>, + under: Option<&BTreeMap>, +) -> bool { + let moves = under.is_some_and(|under| { + reactor.scope.iter().any(|rel| { + pin_of(&reactor.poms[rel].doc, patch).is_some() + && under.get(rel).is_some_and(|u| u.other.is_some()) + }) + }); + reactor.wired_before(patch) && !moves +} + +/// One line for every module of `under` whose selection cannot be told, +/// however many: the first, and how many more. +fn undetermined_note(patch: &JvmPatch<'_>, under: &BTreeMap) -> Option { + let (g, a) = (patch.group_id, patch.artifact_id); let unknown: Vec<(&String, &String)> = under - .into_iter() - .flatten() + .iter() .filter_map(|(rel, u)| match &u.own { Some(Own::Unknown(why)) => Some((rel, why)), _ => None, }) .collect(); - if let Some((module, why)) = unknown.first() { - let more = match unknown.len() - 1 { - 0 => String::new(), - n => format!(", and {n} more"), - }; - warnings.push(degraded( - "selection_undetermined", - format!( - "which version of {g}:{a} {module} resolves cannot be told ({why}){more}; \ - no pin is written where that is so, and one already there is left as it is" - ), - )); - } - (pins, held) + let (module, why) = unknown.first()?; + let more = match unknown.len() - 1 { + 0 => String::new(), + n => format!(", and {n} more"), + }; + Some(degraded( + "selection_undetermined", + format!( + "which version of {g}:{a} {module} resolves cannot be told ({why}){more}; \ + no pin is written where that is so, and one already there is left as it is" + ), + )) } fn op_of_value(op: &Value) -> &str { diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs index 46285701a..2cacd05c1 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs @@ -9,7 +9,9 @@ //! - a `` pin is the entry vendored mode writes, with //! its `` comment, in the poms //! [`place_pins`] picks (where every module at or below selects the base -//! version already, or does not resolve the artifact); +//! version already, or does not resolve the artifact). A later scan +//! keeps every pin where it is, and adds one only for a module nothing +//! reaches yet that is certain to select the base version; //! - a declaration whose version is one `${property}` the reactor's own //! poms define, with nothing else reading that property, has the //! property's value rewritten instead: the declaration keeps its text; @@ -26,9 +28,9 @@ use std::collections::{BTreeMap, BTreeSet}; use std::ops::Range; use super::{ - apply_edits, coords_patch, forget_other_versions, is_base_like, line_span, pin_edit, pin_of, - pin_update, place_pins, safe_coordinates, unattestable_in, unwired_in, Doc, Edit, Pin, Reactor, - Role, + apply_edits, coords_patch, degraded, forget_other_versions, is_base_like, keeps_placement, + line_span, pin_edit, pin_of, pin_update, place_pins, safe_coordinates, unattestable_in, + undetermined_note, unwired_in, Doc, Edit, Pin, Placing, Reactor, Role, }; use crate::crawlers::maven_selection::{MavenSelection, Standing, Verdict}; use crate::formats::maven::split_socket_version; @@ -171,7 +173,34 @@ pub fn plan_hosted( rewritten.wired_without_pin(module, c) }); let closed = |rel: &String| unpinned.contains(rel) || managed_roots.contains(rel); - let (pins, held) = place_pins(&reactor, &patch, Some(&under), &closed, &mut warnings); + let (mut pins, mut held) = place_pins(&reactor, &patch, Some(&under), &closed, &mut warnings); + // A patch the poms already wire keeps its pins where they are, and a + // module nothing reaches yet that is certain to select the base version + // is pinned all the same: a scan over a cold local repository wires + // what it can tell, and the next one, once the project was resolved, + // completes it. Nothing a pom already holds is moved by this. + if keeps_placement(&reactor, &patch, Some(&under)) { + let unreached = rewritten.under(selection, &patch, &|module| rewritten.covers(module, c)); + let (mut more, mut ignored, mut stranded) = (BTreeSet::new(), BTreeSet::new(), Vec::new()); + for root in reactor.wired_roots() { + let mut placing = Placing { + under: &unreached, + patch: &patch, + pins: &mut more, + held: &mut ignored, + stranded: &mut stranded, + }; + reactor.place(&root, !closed(&root), &mut placing, 0); + } + held.retain(|rel| !more.contains(rel)); + pins.extend(more); + warnings.extend( + stranded + .into_iter() + .map(|detail| degraded("pin_would_move_module", detail)), + ); + warnings.extend(undetermined_note(&patch, &unreached)); + } for rel in &rewritten.scope { let doc = &rewritten.poms[rel].doc; let (pinned, held) = (pins.contains(rel), held.contains(rel)); diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs index cc4329633..29d6f1e7c 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs @@ -406,6 +406,49 @@ fn an_undetermined_module_is_not_pinned_and_its_sibling_is() { assert_eq!(reasons(&unread), ["selection_undetermined"]); } +/// A scan over a cold local repository wires what it can tell; the next +/// one, once Maven has resolved the project, pins the module the first +/// could not, and moves nothing the first wrote. Told nothing new, it +/// writes nothing. +#[test] +fn a_later_scan_completes_what_an_earlier_one_could_not_tell() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep(A, Some(BASE)))), + ]); + let cold = selecting( + &files, + &[ + ("a/pom.xml", Err("lib-x:1.0 is not cached")), + ("b/pom.xml", Ok(BASE)), + ], + ); + let first = planned(&files, Some(&cold)); + assert_eq!(kinds(&first), [("b/pom.xml", HostedEditKind::Version)]); + assert_eq!(reasons(&first), ["selection_undetermined"]); + let after = written(&files, &first); + let again = planned( + &after, + Some(&selecting( + &after, + &[("a/pom.xml", Err("still")), ("b/pom.xml", Ok(BASE))], + )), + ); + assert!(again.poms.is_empty(), "{:?}", again.edits); + assert_eq!(reasons(&again), ["selection_undetermined"]); + + let warm = selecting(&after, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let second = planned(&after, Some(&warm)); + // (In the root: both modules select the version now.) + assert_eq!(kinds(&second), [("pom.xml", HostedEditKind::Pin)]); + assert!(reasons(&second).is_empty(), "{:?}", second.notes); + let done = written(&after, &second); + assert_unwires_to(&done, &files); + let third = planned(&done, Some(&warm)); + assert!(third.poms.is_empty() && third.wired, "{:?}", third.edits); +} + /// A pin that now reaches a module resolving another version is taken out /// again (it would hold that module back), leaving the pom as it was /// before the pin. From c377458681dd630e8865b08754c6c6e62b205f74 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 05:19:32 -0500 Subject: [PATCH 13/18] Never fail a hosted run on a Maven module pom that cannot be read Module poms were read as rewrite targets, so one that is a link out of the repository, not UTF-8, or (in memory) linked or without content refused the whole hosted run with exit 1, as an unreadable root pom does. Before module poms were read at all, such a reactor was left alone with exit 0. They are now read as advisory input, and a module pom that is a symbolic link is not read at all (the rewrite would replace the link with a copy). The planner then finds the reactor incomplete and leaves it as it is, `redirect_maven_multimodule_unsupported` with the reason, exit 0. The guard on linked or unreadable rewrite targets is unchanged and has nothing to refuse. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/hosted/engine.rs | 75 +++++++++++++++++-- 1 file changed, 68 insertions(+), 7 deletions(-) diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 6ff50fe24..43b649c73 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -758,9 +758,13 @@ const MAX_REACTOR_READ_ROUNDS: usize = 64; /// Read every pom the Maven reactor planner reads for the root `pom.xml`: /// the modules it lists (theirs in turn), and each local parent on a /// module's chain. The planner is asked what it reads until it asks for -/// nothing new, so the files are exactly the ones it will plan over. A pom -/// is a rewrite target and read as one; a module's `.mvn` files, which the -/// planner only asks about, are advisory. +/// nothing new, so the files are exactly the ones it will plan over. +/// +/// A module pom that cannot be read as text, or that is a symbolic link +/// (the rewrite would replace the link with a copy), is left out: the +/// planner then finds the reactor incomplete and refuses it with nothing +/// written, which is what a reactor got before module poms were read at +/// all. It never fails the run, as an unreadable root candidate does. async fn read_maven_reactor( view: &ProjectView<'_>, unreadable: &BTreeSet, @@ -787,10 +791,10 @@ async fn read_maven_reactor( break; } for rel in wanted { - if rel.ends_with(".xml") && !rel.contains(".mvn/") { - out.read(view, unreadable, &rel).await; - } else if let Some(text) = read_advisory(view, unreadable, &rel).await { - out.files.insert(rel.clone(), text); + if !view.is_symlink(&rel) { + if let Some(text) = read_advisory(view, unreadable, &rel).await { + out.files.insert(rel.clone(), text); + } } asked.insert(rel); } @@ -6276,6 +6280,63 @@ snapshots: assert_eq!(done.confirmed.len(), 1); } + /// A module pom that is a symbolic link, or that is there without + /// readable content, is no reason to fail the run: the reactor is left + /// as it is, with the reason, as every reactor was before module poms + /// were read. The guard that refuses a linked or unreadable rewrite + /// target has nothing to refuse. + #[tokio::test] + async fn a_reactor_with_an_unreadable_module_pom_is_left_alone_not_failed() { + let root = "\n 4.0.0\n x\n y\n 1\n pom\n \n a\n \n \n \n com.socketfixture\n victim\n 1.10.0\n \n \n\n"; + let left_alone = |view: &ProjectView<'_>, read: &CandidateFiles, done: &Rewritten| { + assert!( + read.symlinked_reads.is_empty() + && read.unreadable_reads.is_empty() + && read.undecodable_reads.is_empty(), + "{read:?}" + ); + assert!(done.rewrite.files.is_empty(), "{:?}", done.rewrite.files); + assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); + assert!(done + .rewrite + .warnings + .iter() + .any(|w| w.code == "redirect_maven_multimodule_unsupported")); + assert!(guard(view, done, &[gradle_candidate()]).is_none()); + }; + for entry in [MemoryEntry::Symlink, MemoryEntry::Present] { + let mut p = MemoryProject::new(); + p.insert_text("pom.xml", root); + p.insert("a/pom.xml", entry); + let view = ProjectView::Memory(&p); + let (read, done) = gradle_rewrite_in(&view).await; + left_alone(&view, &read, &done); + } + + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join("pom.xml"), root).unwrap(); + std::fs::create_dir(tmp.path().join("a")).unwrap(); + // Not UTF-8. + std::fs::write(tmp.path().join("a/pom.xml"), [0xff, 0xfe, 0x00]).unwrap(); + let view = ProjectView::Disk(tmp.path()); + let (read, done) = gradle_rewrite_in(&view).await; + left_alone(&view, &read, &done); + // A link, to a pom that would otherwise be planned. + #[cfg(unix)] + { + std::fs::remove_file(tmp.path().join("a/pom.xml")).unwrap(); + std::fs::write( + tmp.path().join("real.xml"), + "\n 4.0.0\n \n x\n y\n 1\n \n a\n\n", + ) + .unwrap(); + std::os::unix::fs::symlink(tmp.path().join("real.xml"), tmp.path().join("a/pom.xml")) + .unwrap(); + let (read, done) = gradle_rewrite_in(&view).await; + left_alone(&view, &read, &done); + } + } + /// An sbt build beside a Gradle build: the Gradle planner pinning a /// uuid the sbt rewriter refused (here: no resolution evidence) does /// not confirm it — the sbt build still loads the upstream artifact. From d8793844bcbaf00391e9f3c33c5930d721dc36ca Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 05:22:46 -0500 Subject: [PATCH 14/18] Read an earlier release's Maven pin by its shape only in a single pom Restore told a reactor from a single pom by the root's model alone, so a Maven 4 root that could discover subprojects but has none was read as a reactor: an entry an earlier release added to its `` was put back at the base version instead of removed. It now asks what discovery asks (the root lists modules, or Maven 4 finds a subproject under it), so such a root is restored as the single pom it is. A test pins both readings: the added entry goes from a single pom, and in a reactor a managed entry at the suffixed version keeps its place at the base version, since there it cannot be told from the project's own. Co-Authored-By: Claude Fable 5.2 --- .../src/patch/redirect/upstream/maven.rs | 75 ++++++++++++++++--- 1 file changed, 66 insertions(+), 9 deletions(-) diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs index 6afdcd8e5..6dcfab58c 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs @@ -330,7 +330,9 @@ pub(crate) async fn restore( files: &[String], ctx: &Ctx<'_>, ) -> FormatResult { - use crate::vendor::jvm::maven_reactor::{declares_modules, may_discover_subprojects}; + use crate::vendor::jvm::maven_reactor::{ + declares_modules, implicit_subprojects_in, may_discover_subprojects, + }; let mut result = FormatResult::default(); let pins = by_uuid(pins); // The poms as they are, and as they read once the pins so far are out. @@ -348,14 +350,17 @@ pub(crate) async fn restore( .as_deref() .map(crate::formats::maven::maven_config_properties) .unwrap_or_default(); - let reactor = view - .read("pom.xml") - .await - .ok() - .flatten() - .is_some_and(|root| { - declares_modules(&root) || may_discover_subprojects(&root, config.as_deref()) - }); + // A reactor as discovery reads one: the root lists modules, or Maven 4 + // finds a subproject under it. + let root_pom = view.read("pom.xml").await.ok().flatten(); + let reactor = match &root_pom { + Some(root) if declares_modules(root) => true, + Some(root) if may_discover_subprojects(root, config.as_deref()) => { + let disk = crate::vendor::lock_inventory::ProjectView::Disk(view.root); + !implicit_subprojects_in(&disk).await.is_empty() + } + _ => false, + }; // Checksum-file path prefixes of the restored pins. let mut checksum_dirs: Vec = Vec::new(); let mut restored: Vec<&str> = Vec::new(); @@ -1113,6 +1118,58 @@ mod tests { assert_eq!(after["pom.xml"], input); } + /// An earlier release's pin is read by its shape only in a single pom. + /// A Maven 4 root that could discover subprojects but has none is one: + /// the entry that release added goes, as before. With a subproject + /// beside it the root heads a reactor, where a managed entry at the + /// suffixed version is a rewritten one of the project's and keeps its + /// place at the base version. + #[tokio::test] + async fn an_earlier_pin_is_told_by_its_shape_only_in_a_single_pom() { + let maven_4 = |pom: String| { + pom.replace("POM/4.0.0", "POM/4.1.0") + .replace("4.0.0", "4.1.0") + .replace("jar", "pom") + }; + let input = maven_4(fixture("transitive-depmgmt", "input", "pom.xml")); + let hosted = maven_4(fixture("transitive-depmgmt", "expected", "pom.xml")); + assert!(hosted.contains("") && !input.contains("Management")); + + let (outcome, after) = run(&[("pom.xml", hosted.clone())]).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + assert_eq!(after["pom.xml"], input, "the added entry goes"); + + let child = "\n 4.1.0\n \n child\n\n"; + let tmp = tempfile::tempdir().unwrap(); + write_tree( + tmp.path(), + &[ + ("pom.xml", hosted.clone()), + ("child/pom.xml", child.to_string()), + ], + ); + let pins = [HostedPin { + purl: "pkg:maven/org.slf4j/slf4j-api@1.7.36".into(), + uuid: UUID.into(), + files: vec!["pom.xml".into()], + }]; + let opts = RestoreOptions { + offline: true, + ..RestoreOptions::default() + }; + let outcome = restore_upstream(tmp.path(), &pins, &opts).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + let after = read_tree(tmp.path()); + assert!( + after["pom.xml"].contains("1.7.36\n \n \n ") + && !after["pom.xml"].contains(SUFFIXED) + && !after["pom.xml"].contains("socket-patch-"), + "the managed entry stays, at the base version: {}", + after["pom.xml"] + ); + assert_eq!(after["child/pom.xml"], child); + } + #[tokio::test] async fn existing_mvn_lines_are_kept_and_warned() { let config = format!( From 36c418fa75dfcdbf5a4899dee7b266184980337d Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 06:13:10 -0500 Subject: [PATCH 15/18] Write a hosted Maven plan whole or not at all, over a reactor read once Review of the hosted reactor work found six ways a scan or a rollback could leave a pom naming a `-socket.` version with nothing to serve it, or wiring no rollback would find, and two ways a large reactor was not read. They share one invariant, now enforced in one place. The invariant: once a plan is written, no pom names the suffixed version unless the repository that serves it is declared in that pom's local root and a declaration Maven always reads resolves to it (so discovery finds the patch, and every pom that carries part of it); a rollback returns every pom the plan first wired to its bytes; when no pom names the suffixed version any more its repository and checksum lines go too, and an earlier patch's go only once no pom of the reactor names it. `HostedReactor::plan` plans declarations, properties, pins and the `` together, checks the result against that (running the rollback's own restore over each pom it would write), and returns the whole plan or a refusal that leaves every pom as it was: - a declaration only a `` holds was rewritten with no repository and no way for a rollback to find it: now refused whole; - a root the repository could not be added to was skipped while the modules below kept their pins: now refused whole; - an earlier patch's repository and checksum lines were dropped by looking at the poms the plan changed, while an unchanged pom still named that patch: now every pom of the reactor is asked; - a scan that took out the last pin left its repository and checksum lines, which no rollback could clear: they go with the pin; - the warning for a module with a `.mvn` of its own was given only by the scan that wrote the pin: now by every scan. Reading. The engine learned the reactor one module per round, parsing every pom again each round, and stopped after 64 rounds, so a reactor of more than 64 modules was refused. `read_reactor` walks the files itself: each pom is fetched and parsed once, and a missing file stops nothing. The engine, discovery and restore read through it, with one rule for what is read (a module pom that is a symbolic link is not), so what one plans over the others find. The rewriter reads the reactor once per run and plans every patch over it; discovery reads it once for all pins. Discovery reads a single pom together with the parent poms it inherits from inside the checkout, where a property rewrite and the repository may sit. A reactor one of whose poms cannot be read is read for the pins of the others (found, never attested), where it fell back to the root pom alone. Restore reads the reactor itself and restores a pin in every pom that carries part of it, whatever discovery listed, or in none: a pin found through the root alone no longer leaves a module naming a version whose repository the rollback just removed. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/hosted/engine.rs | 134 +-- .../src/patch/redirect/mod.rs | 802 +++++++++------ .../src/patch/redirect/upstream/maven.rs | 675 ++++++++++--- .../src/patch/redirect/upstream/mod.rs | 2 +- .../src/vendor/jvm/maven_reactor.rs | 122 ++- .../src/vendor/jvm/maven_reactor/hosted.rs | 910 ++++++++++++------ .../vendor/jvm/maven_reactor/hosted/tests.rs | 459 ++++++++- .../src/vendor/jvm/maven_reactor/reader.rs | 319 ++++++ .../src/vex/discover/maven.rs | 254 ++--- .../socket-patch-core/src/vex/discover/mod.rs | 14 + 10 files changed, 2753 insertions(+), 938 deletions(-) create mode 100644 crates/socket-patch-core/src/vendor/jvm/maven_reactor/reader.rs diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 43b649c73..3c15dcf89 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -750,54 +750,34 @@ async fn read_advisory( } } -/// How many rounds [`read_maven_reactor`] reads: a reactor nested deeper -/// than this is read as far as that, and its planner then refuses it for -/// the module it cannot find. -const MAX_REACTOR_READ_ROUNDS: usize = 64; - -/// Read every pom the Maven reactor planner reads for the root `pom.xml`: -/// the modules it lists (theirs in turn), and each local parent on a -/// module's chain. The planner is asked what it reads until it asks for -/// nothing new, so the files are exactly the ones it will plan over. +/// Read every file the Maven reactor planner reads for the root `pom.xml` +/// ([`read_reactor`](crate::vendor::jvm::maven_reactor::read_reactor), the +/// reader discovery and restore share, so each finds what the others +/// wrote): every pom is fetched and parsed once, however many modules. /// -/// A module pom that cannot be read as text, or that is a symbolic link -/// (the rewrite would replace the link with a copy), is left out: the -/// planner then finds the reactor incomplete and refuses it with nothing -/// written, which is what a reactor got before module poms were read at -/// all. It never fails the run, as an unreadable root candidate does. +/// They are advisory input: a module pom that cannot be read as text, or +/// that is a symbolic link, is left out, and the planner then finds the +/// reactor incomplete and refuses it with nothing written. That is what a +/// reactor got before module poms were read at all; it never fails the +/// run, as an unreadable root candidate does. async fn read_maven_reactor( view: &ProjectView<'_>, unreadable: &BTreeSet, out: &mut CandidateFiles, ) { - let mut asked: BTreeSet = BTreeSet::new(); - for _ in 0..MAX_REACTOR_READ_ROUNDS { - let wanted: std::cell::RefCell> = Default::default(); - { - let read = |rel: &str| match out.files.get(rel) { - Some(text) => Some(text.clone().into_bytes()), - None => { - if !asked.contains(rel) { - wanted.borrow_mut().insert(rel.to_string()); - } - None - } - }; - let list = |dir: &str| crate::patch::redirect::gradle::key_list(&out.files, dir); - crate::vendor::jvm::maven_reactor::readable_for_hosted(&read, &list); - } - let wanted = wanted.into_inner(); - if wanted.is_empty() { - break; - } - for rel in wanted { - if !view.is_symlink(&rel) { - if let Some(text) = read_advisory(view, unreadable, &rel).await { - out.files.insert(rel.clone(), text); - } - } - asked.insert(rel); - } + let Some(root) = out.files.get("pom.xml") else { + return; + }; + let config = out.files.get(crate::patch::redirect::MVN_CONFIG); + let read = crate::vendor::jvm::maven_reactor::read_reactor( + view, + root, + config.map(String::as_str), + |rel| async move { read_advisory(view, unreadable, &rel).await }, + ) + .await; + for (rel, text) in read { + out.files.entry(rel).or_insert(text); } } @@ -1096,29 +1076,12 @@ pub async fn read_candidate_files( read_go_workspace(view, unreadable, &mut out).await; } - // A Maven 4 root that discovers its subprojects (#1809): each direct - // subdirectory holding a `pom.xml` is a module, which the pom rewriter - // must see to refuse the root as a reactor (it pins only the root pom). - // Advisory: keyed `/pom.xml`, never rewritten, and one that cannot - // be read still counts as present. + // Every pom of a Maven reactor (the modules the root lists, theirs in + // turn, each parent pom one inherits from inside the checkout, and the + // subprojects Maven 4 discovers, #1809): the rewriter pins a patch in + // the poms of the modules that select it. if candidates.iter().any(|c| c.dep.ecosystem == "maven") { - if let Some(pom) = out.files.get("pom.xml") { - let config = out.files.get(crate::patch::redirect::MVN_CONFIG); - if crate::vendor::jvm::maven_reactor::may_discover_subprojects( - pom, - config.map(String::as_str), - ) { - for dir in crate::vendor::jvm::maven_reactor::implicit_subprojects_in(view).await { - let rel = format!("{dir}/pom.xml"); - let text = read_advisory(view, unreadable, &rel).await; - out.files.insert(rel, text.unwrap_or_default()); - } - } - // Every pom of the reactor (and a local parent outside the - // module list): the rewriter pins a patch in the module poms - // that select it, so each is a rewrite target. - read_maven_reactor(view, unreadable, &mut out).await; - } + read_maven_reactor(view, unreadable, &mut out).await; } // NuGet merges the user config and every parent directory's config @@ -6280,6 +6243,49 @@ snapshots: assert_eq!(done.confirmed.len(), 1); } + /// A reactor of hundreds of modules is read and planned whole: every + /// module pom is a candidate file, and each one that declares the + /// version is rewritten. (The reader learned one module per round, and + /// stopped after 64.) + #[tokio::test] + async fn a_reactor_of_hundreds_of_modules_is_read_and_planned_whole() { + let declaring = " \n \n com.socketfixture\n victim\n 1.10.0\n \n \n"; + let names: Vec = (0..200).map(|n| format!("module-{n}")).collect(); + let listed: String = names + .iter() + .map(|name| format!(" {name}\n")) + .collect(); + let mut p = MemoryProject::new(); + p.insert_text( + "pom.xml", + format!( + "\n 4.0.0\n x\n y\n 1\n pom\n \n{listed} \n\n" + ) + .as_str(), + ); + for name in &names { + p.insert_text( + format!("{name}/pom.xml"), + format!( + "\n 4.0.0\n \n x\n y\n 1\n \n {name}\n{declaring}\n" + ) + .as_str(), + ); + } + let (read, done) = gradle_rewrite(&p).await; + for name in &names { + let rel = format!("{name}/pom.xml"); + assert!(read.files.contains_key(&rel), "{rel} was not read"); + assert!( + done.rewrite.files[&rel].contains("1.10.0-socket.4d5e6f70"), + "{rel} was not rewritten: {:?}", + done.rewrite.warnings + ); + } + assert!(done.rewrite.files["pom.xml"].contains("socket-patch-")); + assert_eq!(done.confirmed.len(), 1, "{:?}", done.rewrite.warnings); + } + /// A module pom that is a symbolic link, or that is there without /// readable content, is no reason to fail the run: the reactor is left /// as it is, with the reason, as every reactor was before module poms diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index a082010ff..d2c3f8562 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -8968,8 +8968,7 @@ fn rewrite_maven_pom( // the patched version. A single pom is rewritten below, and hands a // `${property}` version to the same planner. let reactor_root = pom.is_some() && maven_reactor_root(files); - // The module poms the reactor planner changed, as they read now. - let mut module_poms: BTreeMap = BTreeMap::new(); + let mut planner = MavenReactorRewrite::default(); let mut pom_changed = false; // The hosted generations whose `socket-patch-` repository the pom // declared before this run: only a suffixed literal one of these minted @@ -9096,11 +9095,12 @@ fn rewrite_maven_pom( } }; if reactor_root { + // (Every dep of a reactor is the planner's: the root's index + // is read once, to tell a pom that is not one.) let _ = idx; - let planned = plan_maven_reactor( + let planned = planner.plan( files, pom_text, - &mut module_poms, ReactorDep { dep, group_id: &group_id, @@ -9108,6 +9108,8 @@ fn rewrite_maven_pom( suffixed: suffixed_version.as_deref(), repo_id: &repo_id, index_url: &ov.index_url, + checksums: checksum_hashes.is_some(), + reactor_root, refusal: "redirect_maven_multimodule_unsupported", }, selection, @@ -9115,9 +9117,6 @@ fn rewrite_maven_pom( result, ); pom_changed |= files.get("pom.xml") != Some(&*pom_text); - index = pom - .as_deref() - .map(|pom| maven_index::PomIndex::build(pom, &user_properties)); let (Some(run), Some(suffixed)) = (planned, suffixed_version.as_deref()) else { continue; }; @@ -9130,7 +9129,7 @@ fn rewrite_maven_pom( "jar", )); } - checksum_drops.extend(run.superseded_paths); + checksum_drops.extend(run.drops); if run.landed { pin_maven_checksums( files, @@ -9479,10 +9478,9 @@ fn rewrite_maven_pom( .iter() .any(|m| m.version_text.as_deref().is_some_and(|v| v.contains("${"))) { - let planned = plan_maven_reactor( + let planned = planner.plan( files, pom_text, - &mut module_poms, ReactorDep { dep, group_id: &group_id, @@ -9490,6 +9488,8 @@ fn rewrite_maven_pom( suffixed: Some(&suffixed_version), repo_id: &repo_id, index_url: &ov.index_url, + checksums: checksum_hashes.is_some(), + reactor_root, refusal: "redirect_maven_dep_unpinned", }, selection, @@ -9512,7 +9512,7 @@ fn rewrite_maven_pom( "jar", )); } - checksum_drops.extend(run.superseded_paths); + checksum_drops.extend(run.drops); if run.landed { pin_maven_checksums( files, @@ -9745,7 +9745,7 @@ fn rewrite_maven_pom( result.files.insert("pom.xml".into(), p); } } - result.files.extend(module_poms); + result.files.extend(planner.module_poms); if mvn_config_changed { result.files.insert(MVN_CONFIG.into(), mvn_config); } @@ -9878,23 +9878,29 @@ struct ReactorDep<'a> { suffixed: Option<&'a str>, repo_id: &'a str, index_url: &'a str, + /// The grant carries the hashes of a Trusted Checksums pin. + checksums: bool, + /// The root pom heads a reactor (else the planner reads a single pom). + reactor_root: bool, /// The code a dep the planner cannot take is reported under: the one /// the pom rewriter gave that shape before the planner read it. refusal: &'static str, } -/// What [`plan_maven_reactor`] did for one dep. +/// What the reactor planner did for one dep. struct ReactorRun { /// A version, property or pin was written this run. landed: bool, - /// Some pom wires the patch once the run is written. + /// The poms wire the patch once the run is written. wired: bool, - /// Trusted-checksum paths of the earlier patches of this version whose - /// pins moved to this one. - superseded_paths: Vec, + /// Trusted-checksum paths nothing names any more: an earlier patch of + /// this version whose pins moved to this one, or this patch's own once + /// its last pin was taken out. + drops: Vec, } -/// The hosted warning a reactor planner note is reported under. +/// The hosted warning a reactor planner note, or the reason a plan was +/// refused for, is reported under. fn reactor_note_code(reason: &str) -> &'static str { match reason { "classifier_declared" => "redirect_maven_classifier_unsupported", @@ -9903,53 +9909,130 @@ fn reactor_note_code(reason: &str) -> &'static str { "selection_undetermined" => "redirect_maven_selection_undetermined", "pin_would_move_module" => "redirect_maven_pin_would_move_module", "edit_not_reversible" => "redirect_maven_edit_not_reversible", + "nothing_wired" => "redirect_maven_profile_dependency_unpatched", + "repository_unwritable" => "redirect_maven_pom_unreadable", _ => "redirect_maven_dep_unpinned", } } -/// Wire one dep through the reactor planner -/// ([`crate::vendor::jvm::maven_reactor::plan_hosted`]): over every pom of -/// a reactor root, or over a single pom whose declaration reads a -/// `${property}`. The poms it changes land in `pom_text` (the root) and -/// `module_poms`; the `` goes in each local root a wired pom -/// inherits from. `None` when nothing wires the patch (the warning says -/// why); the `.mvn` files are the caller's. -fn plan_maven_reactor( - files: &BTreeMap, - pom_text: &mut String, - module_poms: &mut BTreeMap, - of: ReactorDep<'_>, - selection: Option<&MavenSelection>, +/// The hosted rewriter's `` edits and its restore, as the +/// reactor planner calls them +/// ([`HostedRepository`](crate::vendor::jvm::maven_reactor::HostedRepository)): +/// the same insertion a single pom gets, and the restore `rollback` runs +/// ([`upstream::maven::restore_pom`]), so the planner holds every pom it +/// plans to what a rollback will make of it. `reactor_root` is whether +/// the project heads a reactor, which the restore reads a pom by. +pub(crate) fn with_hosted_repository( + coords: &crate::vendor::jvm::Coords<'_>, + index_url: &str, user_properties: &BTreeMap, - result: &mut RewriteResult, -) -> Option { - use crate::vendor::jvm::maven_reactor::{plan_hosted, HostedEditKind}; - let (dep, g, a) = (of.dep, of.group_id, of.artifact_id); - let ga = format!("{g}:{a}"); - let coords = crate::vendor::jvm::Coords { - group_id: g, - artifact_id: a, - version: &dep.version, - uuid: &dep.patch_uuid, + reactor_root: bool, + run: impl FnOnce(&crate::vendor::jvm::maven_reactor::HostedRepository<'_>) -> R, +) -> R { + use crate::vendor::jvm::maven_reactor::{HostedRepository, RepositoryEdit}; + let repo_id = generation::hosted_pin_name(coords.uuid); + let ensure = |pom: &str| -> Result, String> { + let mut text = pom.to_string(); + let mut index = maven_index::PomIndex::build(&text, user_properties)?; + if !index.has_repository(&repo_id) { + index.insert_repository(&mut text, &repo_id, index_url); + Ok(Some(RepositoryEdit::Added(text))) + } else if index.refresh_repository_url(&mut text, &repo_id, index_url) { + Ok(Some(RepositoryEdit::Refreshed(text))) + } else { + Ok(None) + } }; - let refuse = |result: &mut RewriteResult, why: String| { - result.warnings.push(RewriteWarning { - code: of.refusal.into(), - detail: format!( - "{ga}: {why}; the poms and .mvn/ were left as they are and the dep is not \ - counted as redirected (`scan --mode vendored` commits the patched artifact \ - instead)" - ), - }); + let remove = |pom: &str, uuid: &str| { + upstream::maven::without_repository(pom, &generation::hosted_pin_name(uuid)) }; - result.maven_reactor_uuids.insert(dep.patch_uuid.clone()); - // The planner writes the suffix the patch uuid gives; a grant that - // serves another one (or none: a same-GAV grant) is not planned. - let suffixed = coords.suffixed_version(); - if of.suffixed != Some(suffixed.as_str()) || dep.patch_uuid.len() != 36 { - refuse( - result, - match of.suffixed { + let declared = |pom: &str| -> Vec { + generation::named_generations(pom) + .into_iter() + .filter(|uuid| { + !maven_repositories_with_id(pom, &generation::hosted_pin_name(uuid)).is_empty() + }) + .collect() + }; + let restored = |rel: &str, pom: &str| { + let pin = upstream::maven::PinIn { + group: coords.group_id, + artifact: coords.artifact_id, + base: coords.version, + uuid: coords.uuid, + reactor: reactor_root, + }; + // The repository this run declares is the patch's, whichever host + // the grant names. + let hosted_uuid = |url: &str| (url == index_url).then(|| coords.uuid.to_string()); + upstream::maven::restore_pom(rel, pom, user_properties, &pin, &hosted_uuid) + .map(|done| done.text) + }; + run(&HostedRepository { + ensure: &ensure, + remove: &remove, + declared: &declared, + restored: &restored, + }) +} + +/// The reactor planner's side of one hosted Maven rewrite: the reactor, +/// read once and planned over for every dep of the run, and the module +/// poms the plans changed. +#[derive(Default)] +struct MavenReactorRewrite { + /// The reactor as the plans so far left it (`None`: not read yet). + reactor: Option>, + /// The poms other than the root that a plan changed, as they read now. + module_poms: BTreeMap, + /// The nested-`.mvn` warning was given. + warned_nested_mvn: bool, +} + +impl MavenReactorRewrite { + /// Wire one dep through the reactor planner + /// ([`HostedReactor::plan`](crate::vendor::jvm::maven_reactor::HostedReactor::plan)): + /// over every pom of a reactor root, or over a single pom whose + /// declaration reads a `${property}`. A plan is written whole (the + /// root into `pom_text`, the rest into [`Self::module_poms`]) or not + /// at all: pins, rewritten declarations and properties, and the + /// `` in each local root a wired pom inherits from. `None` + /// when nothing was planned (the warning says why); the `.mvn` files + /// are the caller's. + fn plan( + &mut self, + files: &BTreeMap, + pom_text: &mut String, + of: ReactorDep<'_>, + selection: Option<&MavenSelection>, + user_properties: &BTreeMap, + result: &mut RewriteResult, + ) -> Option { + use crate::vendor::jvm::maven_reactor::{HostedEditKind, HostedReactor}; + let (dep, g, a) = (of.dep, of.group_id, of.artifact_id); + let ga = format!("{g}:{a}"); + let coords = crate::vendor::jvm::Coords { + group_id: g, + artifact_id: a, + version: &dep.version, + uuid: &dep.patch_uuid, + }; + let refuse = |result: &mut RewriteResult, code: &str, why: &str| { + result.warnings.push(RewriteWarning { + code: code.into(), + detail: format!( + "{ga}: {why}; the poms and .mvn/ were left as they are and the dep is not \ + counted as redirected (`scan --mode vendored` commits the patched \ + artifact instead)" + ), + }); + }; + result.maven_reactor_uuids.insert(dep.patch_uuid.clone()); + // The planner writes the suffix the patch uuid gives; a grant that + // serves another one (or none: a same-GAV grant) is not planned. + let suffixed = coords.suffixed_version(); + if of.suffixed != Some(suffixed.as_str()) || dep.patch_uuid.len() != 36 { + let why = match of.suffixed { Some(served) => { format!("the grant serves {served}, not the {suffixed} its patch uuid names") } @@ -9957,261 +10040,224 @@ fn plan_maven_reactor( which a pin in one pom cannot keep apart from the upstream one in \ another" .to_string(), - }, - ); - return None; - } - let before: BTreeMap = module_poms.clone(); - let plan = { - let read = |rel: &str| { - let text = match rel { - "pom.xml" => Some(&*pom_text), - _ => module_poms.get(rel).or_else(|| files.get(rel)), }; - text.map(|text| text.as_bytes().to_vec()) - }; - let list = |dir: &str| gradle::key_list(files, dir); - plan_hosted(&read, &list, &coords, selection) - }; - let plan = match plan { - Ok(plan) => plan, - Err(refusal) => { - refuse( - result, + refuse(result, of.refusal, &why); + return None; + } + // The reactor: read once, then kept in step with every plan. + if self.reactor.is_none() { + let read = |rel: &str| { + let text = match rel { + "pom.xml" => Some(&*pom_text), + _ => files.get(rel), + }; + text.map(|text| text.as_bytes().to_vec()) + }; + let list = |dir: &str| gradle::key_list(files, dir); + self.reactor = Some(HostedReactor::read(&read, &list).map_err(|refusal| { refusal .detail .strip_prefix("reason: ") .unwrap_or(&refusal.detail) - .to_string(), - ); - return None; + .to_string() + })); } - }; - if let Some(others) = &plan.not_selected { - result.warnings.push(RewriteWarning { - code: "redirect_maven_version_not_selected".into(), - detail: format!( - "{}; the poms were left as they are", - crate::crawlers::maven_selection::not_selected_detail(g, a, &dep.version, others) - ), - }); - return None; - } - for (reason, detail) in &plan.notes { - result.warnings.push(RewriteWarning { - code: reactor_note_code(reason).into(), - detail: detail.clone(), - }); - } - // Earlier patches of this version whose wiring this run moves on. - let generations = |texts: &dyn Fn(&str) -> Option, rels: &[String]| { - let mut found: std::collections::BTreeSet = std::collections::BTreeSet::new(); - let prefix = format!("{}-socket.", dep.version); - for rel in rels { - let Some(text) = texts(rel) else { continue }; - let masked = crate::formats::xml::blank_non_markup(&text).unwrap_or(text); - for (at, _) in masked.match_indices(&prefix) { - let hex8 = masked.get(at + prefix.len()..at + prefix.len() + 8); - if let Some(hex8) = hex8.filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit())) { - found.insert(format!("{prefix}{hex8}")); - } + let reactor = match self.reactor.as_mut().expect("read above") { + Ok(reactor) => reactor, + Err(why) => { + refuse(result, of.refusal, why); + return None; } - } - found - }; - let changed: Vec = plan.poms.keys().cloned().collect(); - let old_text = |rel: &str| match rel { - "pom.xml" => Some(pom_text.clone()), - _ => before.get(rel).or_else(|| files.get(rel)).cloned(), - }; - let had = generations(&old_text, &changed); - for (rel, text) in &plan.poms { - match rel.as_str() { - "pom.xml" => *pom_text = text.clone(), - _ => { - module_poms.insert(rel.clone(), text.clone()); + }; + // The single-pom rewriter may have edited the root since. + if reactor.text("pom.xml") != Some(pom_text.as_str()) { + if let Err(refusal) = reactor.set_text("pom.xml", pom_text) { + refuse(result, of.refusal, &refusal.detail); + return None; } } - } - for edit in &plan.edits { - let (kind, action, key, new) = match edit.kind { - HostedEditKind::Version => ( - "redirect_maven_dep_version", - "rewritten", - ga.clone(), - Some(Value::String(suffixed.clone())), - ), - HostedEditKind::Property => ( - "redirect_maven_property", - "rewritten", - edit.property.clone().unwrap_or_default(), - Some(Value::String(suffixed.clone())), - ), - HostedEditKind::Pin => ( - "redirect_maven_dep_management", - "added", - ga.clone(), - Some(json!({ "groupId": g, "artifactId": a, "version": suffixed })), - ), - HostedEditKind::PinMoved => ( - "redirect_maven_dep_management", - "rewritten", - ga.clone(), - Some(json!({ "groupId": g, "artifactId": a, "version": suffixed })), - ), - HostedEditKind::PinRemoved => { - ("redirect_maven_dep_management", "removed", ga.clone(), None) - } - }; - result.edits.push(FileEdit { - path: edit.rel.clone(), - kind: kind.into(), - action: action.into(), - key: Some(key), - original: edit.original.clone().map(Value::String), - new, - }); - match edit.kind { - HostedEditKind::Pin => result.warnings.push(RewriteWarning { - code: "redirect_maven_dep_management_added".into(), - detail: format!( - "{ga}: added a pin for the suffixed version \ - {suffixed} to {}, where every module selects {} already", - edit.rel, dep.version - ), - }), - HostedEditKind::PinRemoved => result.warnings.push(RewriteWarning { - code: "redirect_maven_pin_would_move_module".into(), + let plan = with_hosted_repository( + &coords, + of.index_url, + user_properties, + of.reactor_root, + |repository| reactor.plan(&coords, selection, repository), + ); + for (reason, detail) in &plan.notes { + result.warnings.push(RewriteWarning { + code: reactor_note_code(reason).into(), + detail: detail.clone(), + }); + } + if let Some((reason, why)) = &plan.refused { + let code = match reason.as_str() { + "unsafe_coordinates" => of.refusal, + reason => reactor_note_code(reason), + }; + refuse(result, code, why); + return None; + } + if let Some(others) = &plan.not_selected { + result.warnings.push(RewriteWarning { + code: "redirect_maven_version_not_selected".into(), detail: format!( - "{ga}: the pin of {} in {} was removed: a module it reaches now resolves \ - another version, which the pin would hold back", - dep.version, edit.rel + "{}; the poms were left as they are", + crate::crawlers::maven_selection::not_selected_detail( + g, + a, + &dep.version, + others + ) ), - }), - _ => {} + }); + return None; } - } - let landed = plan - .edits - .iter() - .any(|edit| edit.kind != HostedEditKind::PinRemoved); - let superseded: Vec = { - let new_text = |rel: &str| match rel { - "pom.xml" => Some(pom_text.clone()), - _ => module_poms.get(rel).or_else(|| files.get(rel)).cloned(), - }; - had.difference(&generations(&new_text, &changed)) - .filter(|old| **old != suffixed) - .cloned() - .collect() - }; - if !plan.wired { - if plan.notes.is_empty() && plan.edits.is_empty() { - refuse( - result, - format!("no pom of the build could take the pin of {}", dep.version), - ); + // The plan, whole. + for (rel, text) in &plan.poms { + match rel.as_str() { + "pom.xml" => *pom_text = text.clone(), + _ => { + self.module_poms.insert(rel.clone(), text.clone()); + } + } } - return None; - } - result - .confirmed_maven_reactor_uuids - .insert(dep.patch_uuid.clone()); - if !plan.nested_mvn.is_empty() && landed { - result.warnings.push(RewriteWarning { - code: "redirect_maven_trusted_checksums_unenforced".into(), - detail: format!( - "{} has a .mvn directory of its own: a Maven started there reads that one, \ - not the project root's, so the Trusted Checksums pin in {MVN_CHECKSUMS} is \ - not enforced for such a build (the -socket version suffix still pins the \ - patched artifact)", - plan.nested_mvn.join(", ") - ), - }); - } - // The repository, where every wired pom inherits it; an earlier - // patch's goes once nothing names its suffix any more. - for root in &plan.roots { - let current = match root.as_str() { - "pom.xml" => Some(&*pom_text), - _ => module_poms.get(root).or_else(|| files.get(root)), - }; - let Some(mut text) = current.cloned() else { - continue; - }; - let Ok(mut index) = maven_index::PomIndex::build(&text, user_properties) else { - continue; - }; - let mut edit = |action: &str, key: &str, new: Option, kind: &str| { + for edit in &plan.edits { + let pinned = || Some(json!({ "groupId": g, "artifactId": a, "version": suffixed })); + let served = || Some(json!({ "id": of.repo_id, "url": of.index_url })); + let version = || Some(Value::String(suffixed.clone())); + let (kind, action, key, new) = match edit.kind { + HostedEditKind::Version => ( + "redirect_maven_dep_version", + "rewritten", + ga.clone(), + version(), + ), + HostedEditKind::Property => ( + "redirect_maven_property", + "rewritten", + edit.property.clone().unwrap_or_default(), + version(), + ), + HostedEditKind::Pin => ( + "redirect_maven_dep_management", + "added", + ga.clone(), + pinned(), + ), + HostedEditKind::PinMoved => ( + "redirect_maven_dep_management", + "rewritten", + ga.clone(), + pinned(), + ), + HostedEditKind::PinRemoved => { + ("redirect_maven_dep_management", "removed", ga.clone(), None) + } + HostedEditKind::Repository => ( + "redirect_maven_repository", + "added", + of.repo_id.to_string(), + served(), + ), + HostedEditKind::RepositoryUrl => ( + "redirect_maven_repository", + "rewritten", + of.repo_id.to_string(), + served(), + ), + HostedEditKind::RepositoryRemoved => match edit.repository.as_deref() { + Some(uuid) if uuid != dep.patch_uuid => ( + "redirect_maven_superseded_repository_removed", + "removed", + generation::hosted_pin_name(uuid), + None, + ), + _ => ( + "redirect_maven_repository", + "removed", + of.repo_id.to_string(), + None, + ), + }, + }; result.edits.push(FileEdit { - path: root.clone(), + path: edit.rel.clone(), kind: kind.into(), action: action.into(), - key: Some(key.to_string()), - original: None, + key: Some(key), + original: edit.original.clone().map(Value::String), new, }); - }; - let named = json!({ "id": of.repo_id, "url": of.index_url }); - if !index.has_repository(of.repo_id) { - index.insert_repository(&mut text, of.repo_id, of.index_url); - edit( - "added", - of.repo_id, - Some(named), - "redirect_maven_repository", - ); - } else if index.refresh_repository_url(&mut text, of.repo_id, of.index_url) { - edit( - "rewritten", - of.repo_id, - Some(named), - "redirect_maven_repository", - ); - } - for old in &superseded { - let hex8 = crate::formats::maven::split_socket_version(old) - .map(|(_, h)| h) - .unwrap_or_default(); - if text.contains(&format!("-socket.{hex8}")) { - continue; - } - for old_uuid in generation::named_generations(&text) { - if old_uuid == dep.patch_uuid || !old_uuid.starts_with(hex8) { - continue; - } - let old_id = generation::hosted_pin_name(&old_uuid); - if index.remove_repository(&mut text, &old_id) { - edit( - "removed", - &old_id, - None, - "redirect_maven_superseded_repository_removed", - ); - } + match edit.kind { + HostedEditKind::Pin => result.warnings.push(RewriteWarning { + code: "redirect_maven_dep_management_added".into(), + detail: format!( + "{ga}: added a pin for the suffixed version \ + {suffixed} to {}, where every module selects {} already", + edit.rel, dep.version + ), + }), + HostedEditKind::PinRemoved => result.warnings.push(RewriteWarning { + code: "redirect_maven_pin_would_move_module".into(), + detail: format!( + "{ga}: the pin of {} in {} was removed: a module it reaches now \ + resolves another version, which the pin would hold back", + dep.version, edit.rel + ), + }), + _ => {} } } - match root.as_str() { - "pom.xml" => *pom_text = text, - _ => { - if files.get(root) != Some(&text) || module_poms.contains_key(root) { - module_poms.insert(root.clone(), text); - } + let landed = plan.edits.iter().any(|edit| { + matches!( + edit.kind, + HostedEditKind::Version + | HostedEditKind::Property + | HostedEditKind::Pin + | HostedEditKind::PinMoved + ) + }); + let gone = plan + .superseded + .iter() + .chain(plan.unnamed.then_some(&suffixed)); + let drops = gone + .flat_map(|version| { + ["jar", "pom"] + .map(|ext| crate::vendor::jvm::layout::artifact_path(g, a, version, None, ext)) + }) + .collect(); + if plan.wired { + result + .confirmed_maven_reactor_uuids + .insert(dep.patch_uuid.clone()); + // Judged on the poms as they stand, so a re-scan says it too. + if of.checksums && !plan.nested_mvn.is_empty() && !self.warned_nested_mvn { + self.warned_nested_mvn = true; + result.warnings.push(RewriteWarning { + code: "redirect_maven_trusted_checksums_unenforced".into(), + detail: format!( + "{} has a .mvn directory of its own: a Maven started there reads that \ + one, not the project root's, so the Trusted Checksums pin in \ + {MVN_CHECKSUMS} is not enforced for such a build (the -socket version \ + suffix still pins the patched artifact)", + plan.nested_mvn.join(", ") + ), + }); } + } else if plan.notes.is_empty() && plan.edits.is_empty() { + refuse( + result, + of.refusal, + &format!("no pom of the build could take the pin of {}", dep.version), + ); } - } - let superseded_paths = superseded - .iter() - .flat_map(|old| { - ["jar", "pom"] - .map(|ext| crate::vendor::jvm::layout::artifact_path(g, a, old, None, ext)) + Some(ReactorRun { + landed, + wired: plan.wired, + drops, }) - .collect(); - Some(ReactorRun { - landed, - wired: true, - superseded_paths, - }) + } } static MAVEN_REPOSITORY_RE: LazyLock = LazyLock::new(|| { @@ -11827,6 +11873,182 @@ mod tests { assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); } + /// A reactor whose only declaration of the version sits in a module's + /// ``: rewriting it alone would name a version with no + /// repository to serve it, which a build with that profile could not + /// resolve and a rollback could not find. Nothing is written. + #[test] + fn maven_reactor_profile_only_declaration_writes_nothing() { + let profiled = "\n 4.0.0\n \n \ + com.example\n root\n \ + 1.0.0\n \n a\n \n \ + \n extra\n \n \n \ + org.slf4j\n slf4j-api\n \ + 1.7.36\n \n \n \ + \n \n\n"; + let files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", profiled), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let r = rewrite_registry_redirect(&files, &[granted_maven_override()]); + assert!( + r.files.is_empty() && r.edits.is_empty(), + "{:?} {:?}", + r.files.keys(), + r.edits + ); + assert!( + warning_codes(&r).contains(&"redirect_maven_profile_dependency_unpatched"), + "{:?}", + r.warnings + ); + assert!(r.confirmed_maven_reactor_uuids.is_empty()); + } + + /// The whole plan or nothing: a root whose `` cannot + /// take the repository in a form a rollback puts back exactly gets no + /// repository, so the module below gets no pin either. + #[test] + fn maven_reactor_that_cannot_take_the_repository_writes_nothing() { + let files = poms(&[ + ( + "pom.xml", + &REACTOR_ROOT.replace("", " \n"), + ), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let r = rewrite_poms_selecting( + &files, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + assert!( + r.files.is_empty() && r.edits.is_empty(), + "{:?} {:?}", + r.files.keys(), + r.edits + ); + assert_eq!(warning_codes(&r), ["redirect_maven_edit_not_reversible"]); + assert!(r.confirmed_maven_reactor_uuids.is_empty()); + } + + /// When the last pin of a patch is taken out (the module it reached + /// now resolves another version), its repository and its checksum + /// lines go with it: nothing is left that only a rollback could clear, + /// and no rollback would find. + #[test] + fn maven_reactor_last_pin_removed_takes_the_repository_and_checksums() { + let files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let first = rewrite_poms_selecting( + &files, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + let mut wired = files.clone(); + wired.extend(first.files.clone()); + assert!(wired[MVN_CHECKSUMS].contains(MAVEN_SUFFIXED)); + + let r = rewrite_poms_selecting( + &wired, + &[("a/pom.xml", Ok("2.0.9")), ("b/pom.xml", Ok("2.0.9"))], + ); + assert_eq!(r.files["a/pom.xml"], files["a/pom.xml"]); + assert_eq!(r.files["pom.xml"], files["pom.xml"], "the repository went"); + assert!( + !r.files[MVN_CHECKSUMS].contains(MAVEN_SUFFIXED), + "the checksum lines went: {}", + r.files[MVN_CHECKSUMS] + ); + assert!( + warning_codes(&r).contains(&"redirect_maven_pin_would_move_module"), + "{:?}", + r.warnings + ); + assert!(r.confirmed_maven_reactor_uuids.is_empty()); + let removed: Vec<_> = r + .edits + .iter() + .filter(|e| e.action == "removed") + .map(|e| (e.path.as_str(), e.kind.as_str())) + .collect(); + assert_eq!( + removed, + [ + ("a/pom.xml", "redirect_maven_dep_management"), + ("pom.xml", "redirect_maven_repository") + ] + ); + } + + /// A module with a `.mvn` of its own is reported on every scan, not + /// only the one that writes the pin: the condition is judged on the + /// files as they stand. + #[test] + fn maven_reactor_nested_mvn_is_reported_on_every_scan() { + let mut files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + files.insert("a/.mvn/maven.config".to_string(), "-T1\n".to_string()); + let picks = [("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))]; + let first = rewrite_poms_selecting(&files, &picks); + let nested = |r: &RewriteResult| { + r.warnings + .iter() + .filter(|w| w.code == "redirect_maven_trusted_checksums_unenforced") + .filter(|w| w.detail.starts_with("a has a .mvn directory of its own")) + .count() + }; + assert_eq!(nested(&first), 1, "{:?}", first.warnings); + let mut wired = files.clone(); + wired.extend(first.files.clone()); + let again = rewrite_poms_selecting(&wired, &picks); + assert!(again.files.is_empty(), "{:?}", again.files.keys()); + assert_eq!(nested(&again), 1, "{:?}", again.warnings); + } + + /// A single pom that inherits from a parent pom inside the checkout + /// (no ``): a property the parent defines is rewritten there, + /// and the repository goes in the parent the pom inherits it from. + /// Both are written, or neither. + #[test] + fn maven_single_pom_wires_through_its_parent_in_the_checkout() { + let parent = "\n 4.0.0\n \ + com.example\n parent\n \ + 1.0.0\n pom\n \n \ + 1.7.36\n \n\n"; + let child = property_pom("1", "").replace( + " com.example", + " \n com.example\n \ + parent\n 1.0.0\n \ + parent/pom.xml\n \n \ + com.example", + ); + let files = poms(&[("pom.xml", &child), ("parent/pom.xml", parent)]); + let r = rewrite_poms_selecting(&files, &[("pom.xml", Ok("1.7.36"))]); + assert_eq!( + r.files + .keys() + .filter(|rel| rel.ends_with("pom.xml")) + .collect::>(), + ["parent/pom.xml"], + "{:?}", + r.warnings + ); + let wired = &r.files["parent/pom.xml"]; + assert!( + wired.contains(&format!("{MAVEN_SUFFIXED}")) + && wired.contains(&format!("socket-patch-{MAVEN_UUID}")), + "{wired}" + ); + assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); + } + fn property_pom(properties: &str, more: &str) -> String { format!( "\n 4.0.0\n com.example\n \ diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs index 6dcfab58c..030973fdc 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs @@ -147,7 +147,12 @@ fn dm_sections(pom: &str) -> Vec<(usize, usize)> { /// Remove the `socket-patch-` repository of `pom`: the element and /// the line break before it (the rewriter's own insertion), when it sits /// on lines of its own. -fn remove_repository(rel: &str, pom: &str, uuid: &str, ctx: &Ctx<'_>) -> Result { +fn remove_repository( + rel: &str, + pom: &str, + uuid: &str, + hosted_uuid: &dyn Fn(&str) -> Option, +) -> Result { let id = generation::hosted_pin_name(uuid); let (start, end) = match maven_repositories_with_id(pom, &id)[..] { [one] => one, @@ -159,7 +164,7 @@ fn remove_repository(rel: &str, pom: &str, uuid: &str, ctx: &Ctx<'_>) -> Result< } }; let url = maven_tag_text_in(pom, "url", start, end).unwrap_or_default(); - if ctx.hosted_uuid(&url).as_deref() != Some(uuid) { + if hosted_uuid(&url).as_deref() != Some(uuid) { return Err(format!( "the {rel} repository {id} does not point at the Socket patch server" )); @@ -168,24 +173,63 @@ fn remove_repository(rel: &str, pom: &str, uuid: &str, ctx: &Ctx<'_>) -> Result< .ok_or_else(|| format!("the {rel} repository {id} is not on lines of its own")) } -/// What [`restore_pin`] took out of one pom. -struct Restored { - text: String, +/// `pom` without the `` whose id is `id`, and without the +/// `` section the rewriter authored for it once that holds +/// nothing else; `None` unless exactly one such repository sits on lines +/// of its own. What the rewriter itself runs when it takes a repository +/// out (the last pin of a patch went, or a newer patch superseded it), so +/// a scan leaves what a rollback would. +pub(crate) fn without_repository(pom: &str, id: &str) -> Option { + let mut text = remove_maven_repository(pom, id)?; + if text.contains(EMPTY_REPOSITORIES) && !pom.contains(EMPTY_REPOSITORIES) { + text = text.replacen(EMPTY_REPOSITORIES, "", 1); + } + Some(text) +} + +/// What [`restore_pom`] took out of one pom. +pub(crate) struct Restored { + pub(crate) text: String, /// The pin's `` was declared here. - repository: bool, + pub(crate) repository: bool, /// A pin, a declaration or a property of the patch was here. - wiring: bool, + pub(crate) wiring: bool, } /// One pin and where it is restored. -struct PinIn<'a> { - group: &'a str, - artifact: &'a str, - base: &'a str, - uuid: &'a str, +pub(crate) struct PinIn<'a> { + pub(crate) group: &'a str, + pub(crate) artifact: &'a str, + pub(crate) base: &'a str, + pub(crate) uuid: &'a str, /// The project root heads a reactor: its poms are the reactor /// planner's to read, none an earlier release pinned. - reactor: bool, + pub(crate) reactor: bool, +} + +/// The pom `rel` (`pom`) as restoring `pin` leaves it, or why it cannot +/// be restored: the pin taken out ([`restore_pin`]), the wrappers the +/// rewriter authored from scratch gone once emptied, and what is left +/// still a readable pom. `hosted_uuid` says which patch a repository URL +/// serves. It reads nothing but `pom`, so the rewriter runs it over the +/// text it plans to write: an edit this would not take back is not made. +pub(crate) fn restore_pom( + rel: &str, + pom: &str, + user_properties: &BTreeMap, + pin: &PinIn<'_>, + hosted_uuid: &dyn Fn(&str) -> Option, +) -> Result { + let mut done = restore_pin(rel, pom, user_properties, pin, hosted_uuid)?; + // The from-scratch wrappers, once emptied (repositories come last). + for empty in [EMPTY_REPOSITORIES, EMPTY_DEP_MANAGEMENT] { + if done.text.contains(empty) && !pom.contains(empty) { + done.text = done.text.replacen(empty, "", 1); + } + } + crate::formats::maven::parse_pom(&done.text) + .map_err(|why| format!("restoring {rel} would not leave a readable pom: {why}"))?; + Ok(done) } /// Restore one pin in the pom `rel` (`pom`), or say why not. @@ -194,7 +238,7 @@ fn restore_pin( pom: &str, user_properties: &BTreeMap, pin: &PinIn<'_>, - ctx: &Ctx<'_>, + hosted_uuid: &dyn Fn(&str) -> Option, ) -> Result { let PinIn { group, @@ -213,7 +257,7 @@ fn restore_pin( let name = generation::hosted_pin_name(uuid); let repository = !maven_repositories_with_id(pom, &name).is_empty(); let mut text = match repository { - true => remove_repository(rel, pom, uuid, ctx)?, + true => remove_repository(rel, pom, uuid, hosted_uuid)?, false => pom.to_string(), }; // What the reactor planner wrote. A pom that carries none of its marks @@ -330,19 +374,10 @@ pub(crate) async fn restore( files: &[String], ctx: &Ctx<'_>, ) -> FormatResult { - use crate::vendor::jvm::maven_reactor::{ - declares_modules, implicit_subprojects_in, may_discover_subprojects, - }; + use crate::vendor::jvm::maven_reactor::{heads_reactor_in, read_reactor}; + use crate::vendor::lock_inventory::ProjectView; let mut result = FormatResult::default(); let pins = by_uuid(pins); - // The poms as they are, and as they read once the pins so far are out. - let mut originals: BTreeMap = BTreeMap::new(); - for rel in files { - if let Some(text) = read_or_refuse(view, rel, &pins, &mut result).await { - originals.insert(rel.clone(), text); - } - } - let mut texts = originals.clone(); // `.mvn/maven.config`'s `-D` user properties, which Maven reads over // the pom's own when it interpolates a coordinate. let config = view.read(MVN_CONFIG).await.ok().flatten(); @@ -350,17 +385,32 @@ pub(crate) async fn restore( .as_deref() .map(crate::formats::maven::maven_config_properties) .unwrap_or_default(); - // A reactor as discovery reads one: the root lists modules, or Maven 4 - // finds a subproject under it. + // The reactor, read as the rewriter and discovery read it. A pin is + // restored in every pom of it that carries part of the pin, whether or + // not discovery listed that pom: a reactor discovery could not read + // whole (a module pom since deleted or broken) is found by its root + // alone, and restoring only the root would leave a module naming a + // version nothing serves any more. + let disk = ProjectView::Disk(view.root); let root_pom = view.read("pom.xml").await.ok().flatten(); - let reactor = match &root_pom { - Some(root) if declares_modules(root) => true, - Some(root) if may_discover_subprojects(root, config.as_deref()) => { - let disk = crate::vendor::lock_inventory::ProjectView::Disk(view.root); - !implicit_subprojects_in(&disk).await.is_empty() - } - _ => false, + let (reactor, reactor_poms) = match &root_pom { + Some(root) => ( + heads_reactor_in(&disk, root, config.as_deref()).await, + read_reactor(&disk, root, config.as_deref(), |rel| async move { + disk.read_text(&rel).await.ok() + }) + .await, + ), + None => (false, BTreeMap::new()), }; + // The poms as they are, and as they read once the pins so far are out. + let mut originals: BTreeMap = BTreeMap::new(); + for rel in files { + if let Some(text) = read_or_refuse(view, rel, &pins, &mut result).await { + originals.insert(rel.clone(), text); + } + } + let mut texts = originals.clone(); // Checksum-file path prefixes of the restored pins. let mut checksum_dirs: Vec = Vec::new(); let mut restored: Vec<&str> = Vec::new(); @@ -382,6 +432,20 @@ pub(crate) async fn restore( continue; } let suffixed = format!("{base}-socket.{}", &pin.uuid[..8]); + let repository_id = generation::hosted_pin_name(&pin.uuid); + let tag = format!( + "{}{}:", + crate::vendor::jvm::maven_reactor::PIN_TAG, + pin.uuid + ); + let mut poms: Vec = pin.files.clone(); + for (rel, text) in &reactor_poms { + let carries = + text.contains(&suffixed) || text.contains(&repository_id) || text.contains(&tag); + if carries && !rel.contains(".mvn/") && !poms.contains(rel) { + poms.push(rel.clone()); + } + } let of = PinIn { group, artifact, @@ -391,29 +455,30 @@ pub(crate) async fn restore( }; // Every pom the pin is wired in, or none: a pin refused in one of // its poms is restored in none of them. - let mut staged: BTreeMap<&String, String> = BTreeMap::new(); + let mut staged: BTreeMap = BTreeMap::new(); let (mut repository, mut wiring) = (false, false); let mut refusal = None; - for rel in &pin.files { - let next = restore_pin(rel, &texts[rel], &user_properties, &of, ctx).and_then(|done| { - let mut text = done.text; - // The from-scratch wrappers, once emptied (repositories - // come last). - for empty in [EMPTY_REPOSITORIES, EMPTY_DEP_MANAGEMENT] { - if text.contains(empty) && !originals[rel].contains(empty) { - text = text.replacen(empty, "", 1); + for rel in &poms { + let current = match texts.get(rel) { + Some(text) => text.clone(), + None => match view.read(rel).await { + Ok(Some(text)) => { + originals.insert(rel.clone(), text.clone()); + text } - } - crate::formats::maven::parse_pom(&text).map_err(|why| { - format!("restoring {rel} would not leave a readable pom: {why}") - })?; - repository |= done.repository; - wiring |= done.wiring; - Ok(text) - }); - match next { - Ok(text) => { - staged.insert(rel, text); + Ok(None) => continue, + Err(why) => { + refusal = Some(why); + break; + } + }, + }; + let hosted_uuid = |url: &str| ctx.hosted_uuid(url); + match restore_pom(rel, ¤t, &user_properties, &of, &hosted_uuid) { + Ok(done) => { + repository |= done.repository; + wiring |= done.wiring; + staged.insert(rel.clone(), done.text); } Err(why) => { refusal = Some(why); @@ -421,14 +486,15 @@ pub(crate) async fn restore( } } } - let poms = pin.files.join(", "); + let named = poms.join(", "); let refusal = refusal.or_else(|| { if !repository { - let id = generation::hosted_pin_name(&pin.uuid); - Some(format!("{poms} has no with id {id}")) + Some(format!( + "{named} has no with id {repository_id}" + )) } else if !wiring { Some(format!( - "{poms} declares no {group}:{artifact} {suffixed}" + "{named} declares no {group}:{artifact} {suffixed}" )) } else { None @@ -438,9 +504,7 @@ pub(crate) async fn restore( result.refuse(&pin.uuid, why); continue; } - for (rel, text) in staged { - texts.insert(rel.clone(), text); - } + texts.extend(staged); checksum_dirs.push(format!( "{}/", crate::vendor::jvm::layout::version_dir(group, artifact, &suffixed) @@ -450,14 +514,14 @@ pub(crate) async fn restore( if restored.is_empty() { return result; } - for (rel, text) in texts { - if originals[&rel] != text { - view.write(&rel, text); + for (rel, text) in &texts { + if originals.get(rel) != Some(text) { + view.write(rel, text.clone()); } } // The Trusted Checksums files, where the rewriter keeps them: at the // project root (and beside a pom an earlier release pinned on its own). - let mut dirs: std::collections::BTreeSet = originals + let mut dirs: std::collections::BTreeSet = texts .keys() .map(|rel| { rel.rsplit_once('/') @@ -533,6 +597,8 @@ async fn restore_mvn( #[cfg(test)] mod tests { use super::super::{restore_upstream, HostedPin, PinStatus, RestoreOptions, RestoreOutcome}; + use super::{generation, MVN_CHECKSUMS, MVN_CONFIG}; + use crate::patch::redirect::RewriteResult; use std::collections::BTreeMap; const UUID: &str = "77777777-7777-7777-7777-777777777777"; @@ -860,22 +926,27 @@ mod tests { } } - /// What hosted mode writes for slf4j-api over `files` (each module - /// selecting what `picks` says), discovered again from the tree and - /// restored: the tree after, which must be `files`. - async fn round_trip( - files: &[(&str, String)], - picks: &[(&str, Result<&str, &str>)], - ) -> BTreeMap { + /// A second patch of the same version, which supersedes [`UUID`]'s. + const NEWER: &str = "88888888-8888-4888-8888-888888888888"; + + /// What each module selects for slf4j-api (a module left out does not + /// resolve it). + type Picks<'a> = &'a [(&'a str, Result<&'a str, &'a str>)]; + + /// One hosted scan of the tree at `root` for the slf4j-api patch + /// `uuid`, each module selecting what `picks` says: the rewrite, with + /// its files written. + fn scan(root: &std::path::Path, uuid: &str, picks: Picks<'_>) -> RewriteResult { use crate::crawlers::maven_selection::MavenSelection; use crate::patch::redirect::{ DepOverride, Integrity, RegistryOverride, RegistryOverrideIdentifiers, }; - let before: BTreeMap = files - .iter() - .map(|(rel, text)| (rel.to_string(), text.clone())) + let tree = read_tree(root); + let modules: Vec<&str> = tree + .keys() + .map(String::as_str) + .filter(|rel| rel.ends_with("pom.xml")) .collect(); - let modules: Vec<&str> = files.iter().map(|(rel, _)| *rel).collect(); let picks: Vec<_> = picks .iter() .map(|(pom, pick)| (*pom, "org.slf4j", "slf4j-api", *pick)) @@ -886,19 +957,19 @@ mod tests { namespace: Some("org.slf4j".into()), version: "1.7.36".into(), token: "tok".into(), - patch_uuid: UUID.into(), + patch_uuid: uuid.into(), artifact_url: format!( - "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/tok/{UUID}/slf4j-api-1.7.36.jar" + "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/tok/{uuid}/slf4j-api-1.7.36.jar" ), registry_override: Some(RegistryOverride { kind: "maven2".into(), - index_url: format!("https://patch.socket.dev/patch-registry/maven/tok/{UUID}/maven2"), + index_url: format!("https://patch.socket.dev/patch-registry/maven/tok/{uuid}/maven2"), identifiers: RegistryOverrideIdentifiers { name: "org.slf4j/slf4j-api".into(), version: "1.7.36".into(), maven_group_id: Some("org.slf4j".into()), maven_artifact_id: Some("slf4j-api".into()), - maven_suffixed_version: Some(SUFFIXED.into()), + maven_suffixed_version: Some(format!("1.7.36-socket.{}", &uuid[..8])), maven_pom_sha256: Some("d".repeat(64)), ..Default::default() }, @@ -909,7 +980,7 @@ mod tests { }, }; let written = crate::patch::redirect::rewrite_registry_redirect_with_host( - &before, + &tree, &[dep], &BTreeMap::new(), None, @@ -919,40 +990,177 @@ mod tests { &crate::formats::cargo::source_replacement::CratesIoSource::Registry, Some(&MavenSelection::answering(&modules, &picks)), ); - assert!( - written.files.values().any(|text| text.contains(SUFFIXED)), - "nothing was pinned: {:?}", - written.warnings - ); - let tmp = tempfile::tempdir().unwrap(); - write_tree(tmp.path(), files); - let hosted: Vec<(&str, String)> = written + let files: Vec<(&str, String)> = written .files .iter() .map(|(rel, text)| (rel.as_str(), text.clone())) .collect(); - write_tree(tmp.path(), &hosted); + write_tree(root, &files); + written + } - let view = crate::vendor::lock_inventory::ProjectView::Disk(tmp.path()); - let pins = HostedPin::discover(view, &[]).await; - assert_eq!(pins.len(), 1, "{pins:?}"); - assert_eq!( - (pins[0].purl.as_str(), pins[0].uuid.as_str()), - ("pkg:maven/org.slf4j/slf4j-api@1.7.36", UUID) - ); - // Every pom hosted mode wrote is one the pin is found in. - for rel in written.files.keys().filter(|rel| rel.ends_with("pom.xml")) { - assert!(pins[0].files.contains(rel), "{rel}: {:?}", pins[0].files); + /// The hosted pins discovery reads from the tree at `root`. + async fn discovered(root: &std::path::Path) -> Vec { + HostedPin::discover(crate::vendor::lock_inventory::ProjectView::Disk(root), &[]).await + } + + /// THE INVARIANT, on the tree at `root` as a build and a rollback + /// would find it. No pom names a `-socket.` version, and no pom + /// declares a `socket-patch-` repository, but as part of a pin + /// discovery finds in that very pom (so a rollback undoes it); every + /// pin has the checksum lines of its jar and pom; and no checksum line + /// is left for a suffix no pin has. The pins found. + async fn assert_invariant(case: &str, root: &std::path::Path) -> Vec { + let tree = read_tree(root); + let pins = discovered(root).await; + let found = |hex8: &str, rel: &str| { + pins.iter() + .any(|pin| pin.uuid.starts_with(hex8) && pin.files.iter().any(|f| f == rel)) + }; + for (rel, text) in &tree { + if !rel.ends_with(".xml") || rel.contains(".mvn/") { + continue; + } + let live = crate::formats::xml::blank_non_markup(text).unwrap(); + for (at, _) in live.match_indices("-socket.") { + let hex8 = &live[at + 8..at + 16]; + assert!( + found(hex8, rel), + "{case}: {rel} names -socket.{hex8}, which no pin found there covers: \ + {pins:?}\n{text}" + ); + } + for uuid in generation::named_generations(text) { + assert!( + found(&uuid[..8], rel), + "{case}: {rel} declares the repository of {uuid}, which no pin found \ + there uses: {pins:?}\n{text}" + ); + } + } + let sums = tree.get(MVN_CHECKSUMS).cloned().unwrap_or_default(); + for line in sums.lines().filter(|line| line.contains("-socket.")) { + assert!( + pins.iter() + .any(|pin| line.contains(&format!("-socket.{}/", &pin.uuid[..8]))), + "{case}: a checksum line is left for a suffix no pin has: {line}" + ); + } + for pin in &pins { + let suffix = format!("-socket.{}/", &pin.uuid[..8]); + assert_eq!( + sums.lines().filter(|line| line.contains(&suffix)).count(), + 2, + "{case}: the jar and pom checksum lines of {}: {sums}", + pin.uuid + ); + } + pins + } + + /// Roll every hosted pin of the tree at `root` back. + async fn roll_back(case: &str, root: &std::path::Path) { + let pins = discovered(root).await; + if pins.is_empty() { + return; } let opts = RestoreOptions { offline: true, ..RestoreOptions::default() }; - let outcome = restore_upstream(tmp.path(), &pins, &opts).await; - assert_eq!(outcome.pins[0].status, PinStatus::Restored); + let outcome = restore_upstream(root, &pins, &opts).await; + for pin in &outcome.pins { + assert_eq!(pin.status, PinStatus::Restored, "{case}: {}", pin.purl); + } + } + + /// One fixture through the life of a hosted patch, the invariant + /// checked after every step ([`assert_invariant`]): + /// + /// - scanned, scanned again (which writes nothing), rolled back: the + /// tree is `files` again, byte for byte, with no file left over; + /// - scanned, then scanned for a newer patch of the same version + /// (which takes the place of the first everywhere), then with every + /// module resolving another version (which takes out the pins), then + /// rolled back: every pom is as in `files`, and nothing of either + /// patch is left. + /// + /// `wired` is whether the scan is expected to pin the patch at all. + async fn lifecycle(case: &str, files: &[(&str, String)], picks: Picks<'_>, wired: bool) { + let before: BTreeMap = files + .iter() + .map(|(rel, text)| (rel.to_string(), text.clone())) + .collect(); + let suffixed_in = + |tree: &BTreeMap| tree.values().any(|text| text.contains("-socket.")); + + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), files); + let first = scan(tmp.path(), UUID, picks); + assert_eq!( + suffixed_in(&first.files), + wired, + "{case}: {:?}", + first.warnings + ); + let pins = assert_invariant(case, tmp.path()).await; + assert_eq!(pins.len(), usize::from(wired), "{case}: {pins:?}"); + for pin in &pins { + assert_eq!( + (pin.purl.as_str(), pin.uuid.as_str()), + ("pkg:maven/org.slf4j/slf4j-api@1.7.36", UUID) + ); + } + let again = scan(tmp.path(), UUID, picks); + assert!( + again.files.is_empty() && again.edits.is_empty(), + "{case}: a second scan writes nothing: {:?} {:?}", + again.files.keys(), + again.edits + ); + roll_back(case, tmp.path()).await; + assert_eq!( + read_tree(tmp.path()), + before, + "{case}: a rollback puts every file back and leaves none" + ); + + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), files); + scan(tmp.path(), UUID, picks); + scan(tmp.path(), NEWER, picks); + let pins = assert_invariant(&format!("{case}, superseded"), tmp.path()).await; + assert!( + pins.iter().all(|pin| pin.uuid == NEWER) && pins.len() == usize::from(wired), + "{case}: the newer patch takes the place of the first: {pins:?}" + ); + assert!( + !read_tree(tmp.path()) + .values() + .any(|text| text.contains(&UUID[..8])), + "{case}: nothing of the first patch is left: {:#?}", + read_tree(tmp.path()) + ); + let again = scan(tmp.path(), NEWER, picks); + assert!(again.files.is_empty(), "{case}: {:?}", again.files.keys()); + let elsewhere: Vec<(&str, Result<&str, &str>)> = + picks.iter().map(|(pom, _)| (*pom, Ok("2.0.9"))).collect(); + scan(tmp.path(), NEWER, &elsewhere); + assert_invariant(&format!("{case}, moved on"), tmp.path()).await; + roll_back(case, tmp.path()).await; let after = read_tree(tmp.path()); - assert_eq!(after, before, "every file is back, and none is left over"); - after + assert!(!suffixed_in(&after), "{case}: {after:#?}"); + for (rel, text) in &before { + assert_eq!(after.get(rel), Some(text), "{case}: {rel}"); + } + // (A scan that took out the last pin itself cannot delete the + // `.mvn` files it once wrote: they stay, with no line of a patch.) + for rel in after.keys().filter(|rel| !before.contains_key(*rel)) { + assert!( + [MVN_CONFIG, MVN_CHECKSUMS].contains(&rel.as_str()), + "{case}: {rel} is left over" + ); + } } const REACTOR_ROOT: &str = "\n 4.0.0\n \ @@ -977,34 +1185,50 @@ mod tests { ) } + /// A single pom declaring slf4j-api at `${slf4j.version}`, with + /// `properties` and `more` dependencies. + fn property_pom(properties: &str, more: &str) -> String { + format!( + "\n 4.0.0\n \ + com.example\n app\n \ + 1.0.0\n \n {properties}\n \n \ + \n{}{more} \n\n", + dependency("org.slf4j", "slf4j-api", Some("${slf4j.version}")) + ) + } + /// A reactor's wiring is spread over its poms (a pin in the module /// that selects the version, a declaration rewritten where it stands, - /// the repository in the root, the checksums at the root): restoring - /// the patch puts every file back byte for byte and leaves none behind. + /// the repository in the root, the checksums at the root). Through + /// scan, re-scan, a superseding patch, pins taken out and rollback, + /// no pom is ever left naming a version without the repository and + /// checksum lines that serve it and a pin a rollback finds; and a + /// rollback puts every file back byte for byte. #[tokio::test] - async fn reactor_wiring_round_trips() { + async fn reactor_wiring_keeps_the_invariant_through_its_life() { let logback = dependency("ch.qos.logback", "logback-classic", Some("1.4.14")); - // A pin in one module's pom; its sibling resolves another version. - round_trip( + let declaring = dependency("org.slf4j", "slf4j-api", Some("1.7.36")); + let both = [("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("1.7.36"))]; + lifecycle( + "a pin in one module, its sibling on another version", &[ ("pom.xml", REACTOR_ROOT.to_string()), ("a/pom.xml", reactor_module("a", &logback)), ("b/pom.xml", reactor_module("b", &logback)), ], &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + true, ) .await; - // One pin in the root both inherit, beside a declaration. - round_trip( + lifecycle( + "a pin in the root both inherit, beside a declaration", &[ ("pom.xml", REACTOR_ROOT.to_string()), - ( - "a/pom.xml", - reactor_module("a", &dependency("org.slf4j", "slf4j-api", Some("1.7.36"))), - ), + ("a/pom.xml", reactor_module("a", &declaring)), ("b/pom.xml", reactor_module("b", &logback)), ], - &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("1.7.36"))], + &both, + true, ) .await; // The root manages the version in the shape an added entry has: @@ -1014,10 +1238,11 @@ mod tests { &format!( " \n \n {} \n \ \n", - dependency("org.slf4j", "slf4j-api", Some("1.7.36")).replace("\n ", "\n ") + declaring.replace("\n ", "\n ") ), ); - round_trip( + lifecycle( + "the root's own management", &[ ("pom.xml", managing), ( @@ -1026,48 +1251,91 @@ mod tests { ), ("b/pom.xml", reactor_module("b", &logback)), ], - &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("1.7.36"))], + &both, + true, + ) + .await; + lifecycle( + "a property of the root the modules read", + &[ + ( + "pom.xml", + REACTOR_ROOT.replace( + " pom\n", + " pom\n \n \ + 1.7.36\n \n", + ), + ), + ( + "a/pom.xml", + reactor_module( + "a", + &dependency("org.slf4j", "slf4j-api", Some("${slf4j.version}")), + ), + ), + ("b/pom.xml", reactor_module("b", &logback)), + ], + &both, + true, + ) + .await; + // The only declaration is one Maven reads while a profile is + // active: nothing is written at any step. + let profiled = reactor_module("a", "").replace( + "", + &format!( + " \n \n extra\n \n\ + {declaring} \n \n \n" + ), + ); + lifecycle( + "a declaration only a profile holds", + &[ + ("pom.xml", REACTOR_ROOT.to_string()), + ("a/pom.xml", profiled), + ("b/pom.xml", reactor_module("b", "")), + ], + &[], + false, ) .await; } - /// A `${property}` version is put back as it was written: the - /// property's own value, or the declaration's recorded text. + /// The same for a single pom: a `${property}` version put back as it + /// was written (the property's own value, or the declaration's + /// recorded text), wiring that sits in a parent pom of the checkout, + /// and the pins an earlier release's rewriter still writes. #[tokio::test] - async fn property_wiring_round_trips() { - let pom = |properties: &str, more: &str| { - format!( - "\n 4.0.0\n \ - com.example\n app\n \ - 1.0.0\n \n {properties}\n \n \ - \n{}{more} \n\n", - dependency("org.slf4j", "slf4j-api", Some("${slf4j.version}")) - ) - }; + async fn single_pom_wiring_keeps_the_invariant_through_its_life() { let picks = [("pom.xml", Ok("1.7.36"))]; - // Only the patched artifact reads the property. - round_trip( - &[("pom.xml", pom("1.7.36", ""))], + lifecycle( + "a property only the artifact reads", + &[( + "pom.xml", + property_pom("1.7.36", ""), + )], &picks, + true, ) .await; - // A sibling reads it too. - round_trip( + lifecycle( + "a property a sibling reads too", &[( "pom.xml", - pom( + property_pom( "1.7.36", &dependency("org.slf4j", "slf4j-simple", Some("${slf4j.version}")), ), )], &picks, + true, ) .await; - // No pom of the checkout defines it (a parent from a repository). - round_trip( + lifecycle( + "a property a parent from a repository defines", &[( "pom.xml", - pom("1", "").replace( + property_pom("1", "").replace( " com.example", " \n corp\n parent\n \ 7\n \n \n \ @@ -1075,6 +1343,49 @@ mod tests { ), )], &picks, + true, + ) + .await; + // The wiring lands in a parent pom the project lists no module + // for: discovery and rollback must read that pom too. + lifecycle( + "a property a parent pom of the checkout defines", + &[ + ( + "pom.xml", + property_pom("1", "").replace( + " com.example", + " \n com.example\n \ + parent\n 1.0.0\n \ + parent/pom.xml\n \n \ + com.example", + ), + ), + ( + "parent/pom.xml", + "\n 4.0.0\n \ + com.example\n parent\n \ + 1.0.0\n pom\n \n \ + 1.7.36\n \n\n" + .to_string(), + ), + ], + &picks, + true, + ) + .await; + lifecycle( + "a literal declaration", + &[("pom.xml", fixture("basic", "input", "pom.xml"))], + &picks, + true, + ) + .await; + lifecycle( + "no declaration: an added management entry", + &[("pom.xml", fixture("transitive-depmgmt", "input", "pom.xml"))], + &picks, + true, ) .await; } @@ -1118,6 +1429,88 @@ mod tests { assert_eq!(after["pom.xml"], input); } + /// A reactor one of whose module poms has gone missing is still read + /// for the pins of the others: the pin in a module's pom is found with + /// the repository in the root, and a rollback takes out both. + #[tokio::test] + async fn a_reactor_with_a_missing_module_is_still_rolled_back_whole() { + let logback = dependency("ch.qos.logback", "logback-classic", Some("1.4.14")); + let files = [ + ("pom.xml", REACTOR_ROOT.to_string()), + ("a/pom.xml", reactor_module("a", &logback)), + ("b/pom.xml", reactor_module("b", &logback)), + ]; + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), &files); + scan( + tmp.path(), + UUID, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + std::fs::remove_file(tmp.path().join("b/pom.xml")).unwrap(); + let pins = discovered(tmp.path()).await; + assert_eq!(pins.len(), 1, "{pins:?}"); + assert_eq!(pins[0].files, ["a/pom.xml", "pom.xml"]); + roll_back("a missing module", tmp.path()).await; + let after = read_tree(tmp.path()); + assert_eq!(after["a/pom.xml"], files[1].1); + assert_eq!(after["pom.xml"], files[0].1); + assert!(!after.contains_key(MVN_CHECKSUMS), "{:?}", after.keys()); + } + + /// A pin is restored in every pom of the reactor that carries part of + /// it, whatever discovery listed, or in none: restoring the root alone + /// would take the repository from under a module that still names the + /// suffixed version. + #[tokio::test] + async fn a_pin_is_restored_in_every_pom_that_carries_it_or_in_none() { + let logback = dependency("ch.qos.logback", "logback-classic", Some("1.4.14")); + let files = [ + ("pom.xml", REACTOR_ROOT.to_string()), + ("a/pom.xml", reactor_module("a", &logback)), + ("b/pom.xml", reactor_module("b", &logback)), + ]; + let root_only = [HostedPin { + purl: "pkg:maven/org.slf4j/slf4j-api@1.7.36".into(), + uuid: UUID.into(), + files: vec!["pom.xml".into()], + }]; + let opts = RestoreOptions { + offline: true, + ..RestoreOptions::default() + }; + let wire = || { + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), &files); + scan( + tmp.path(), + UUID, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + tmp + }; + + // The module's pin goes with the root's repository. + let tmp = wire(); + let outcome = restore_upstream(tmp.path(), &root_only, &opts).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + let after = read_tree(tmp.path()); + for (rel, text) in &files { + assert_eq!(after.get(*rel), Some(text), "{rel}"); + } + + // A module that still names the pin and can no longer be read as + // a pom: nothing is restored, the root keeps its repository. + let tmp = wire(); + let broken = read_tree(tmp.path())["a/pom.xml"].replace("", ""); + std::fs::write(tmp.path().join("a/pom.xml"), &broken).unwrap(); + let wired = read_tree(tmp.path()); + let outcome = restore_upstream(tmp.path(), &root_only, &opts).await; + let why = refusal(&outcome); + assert!(why.contains("a/pom.xml"), "{why}"); + assert_eq!(read_tree(tmp.path()), wired, "nothing changed"); + } + /// An earlier release's pin is read by its shape only in a single pom. /// A Maven 4 root that could discover subprojects but has none is one: /// the entry that release added goes, as before. With a subproject diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs index 2567e3220..a3399d011 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -36,7 +36,7 @@ mod composer; mod gem; mod golang; mod gradle; -mod maven; +pub(crate) mod maven; pub(crate) mod npm; mod nuget; mod pypi; diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs index 0f7dc7b5e..9ae2b0116 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs @@ -28,10 +28,12 @@ use super::{ }; mod hosted; +mod reader; pub use hosted::{ - hosted_sites, hosted_unattestable, plan_hosted, readable_for_hosted, unwire_hosted, HostedEdit, - HostedEditKind, HostedPlan, HostedSite, ORIGINAL_TAG, + unwire_hosted, HostedEdit, HostedEditKind, HostedPlan, HostedReactor, HostedRepository, + HostedSite, RepositoryEdit, ORIGINAL_TAG, }; +pub use reader::read_reactor; /// The committed maven2 tree. use super::layout::MAVEN2_TREE as TREE_ROOT; @@ -113,18 +115,46 @@ pub fn may_discover_subprojects(pom: &str, maven_config: Option<&str>) -> bool { pub async fn implicit_subprojects_in( view: &crate::vendor::lock_inventory::ProjectView<'_>, ) -> Vec { + subprojects_in(view, "").await +} + +/// [`implicit_subprojects_in`] under the directory `dir` (`""`: the +/// root), as names relative to it. +async fn subprojects_in( + view: &crate::vendor::lock_inventory::ProjectView<'_>, + dir: &str, +) -> Vec { + let under = |name: &str| match dir { + "" => name.to_string(), + _ => format!("{dir}/{name}"), + }; let mut out = Vec::new(); - for entry in view.list_dir("").await.unwrap_or_default() { - if entry.name == GIT_DIR || !(entry.is_dir || view.is_symlink(&entry.name)) { + for entry in view.list_dir(dir).await.unwrap_or_default() { + let path = under(&entry.name); + if entry.name == GIT_DIR || !(entry.is_dir || view.is_symlink(&path)) { continue; } - if view.is_file(&format!("{}/{}", entry.name, layout::POM_FILE)) { + if view.is_file(&format!("{path}/{}", layout::POM_FILE)) { out.push(entry.name); } } out } +/// Whether the root pom `pom` of the project `view` reads heads a reactor +/// ([`is_reactor_root`], for a caller that holds the pom and reads the +/// project through a view): the one question the hosted rewriter's +/// discovery and its restore both ask. +pub async fn heads_reactor_in( + view: &crate::vendor::lock_inventory::ProjectView<'_>, + pom: &str, + maven_config: Option<&str>, +) -> bool { + declares_modules(pom) + || (may_discover_subprojects(pom, maven_config) + && !implicit_subprojects_in(view).await.is_empty()) +} + /// A checkout's git directory: never a subproject, whatever it holds (the /// planner's reader refuses every path through it). const GIT_DIR: &str = ".git"; @@ -329,7 +359,15 @@ pub fn plan_with_selection( } // Where the pin goes, and the poms whose pin stays as it is. let closed = |rel: &String| unpinned.contains(rel) || managed_roots.contains(rel); - let (pins, held) = place_pins(&reactor, patch, under.as_ref(), &closed, &mut warnings); + let kept = keeps_placement(&reactor, patch, under.as_ref()); + let (pins, held) = place_pins( + &reactor, + patch, + under.as_ref(), + &closed, + kept, + &mut warnings, + ); let banning = reactor .scope @@ -495,17 +533,20 @@ fn forget_other_versions(warnings: &mut Vec, under: &BTreeMap, under: Option<&BTreeMap>, closed: &dyn Fn(&String) -> bool, + kept: bool, warnings: &mut Vec, ) -> (BTreeSet, BTreeSet) { let mut pins: BTreeSet = BTreeSet::new(); let mut held: BTreeSet = BTreeSet::new(); - if keeps_placement(reactor, patch, under) { + if kept { // (A local root a declaration ruled out stays ruled out.) held.extend(reactor.scope.iter().filter(|rel| !closed(rel)).cloned()); return (pins, held); @@ -547,13 +588,22 @@ fn keeps_placement( patch: &JvmPatch<'_>, under: Option<&BTreeMap>, ) -> bool { - let moves = under.is_some_and(|under| { + reactor.wired_before(patch) && !pin_moves(reactor, patch, under) +} + +/// Whether a pin of `patch` is certain (by `under`) to move a module to +/// another version than Maven selects for it. +fn pin_moves( + reactor: &Reactor, + patch: &JvmPatch<'_>, + under: Option<&BTreeMap>, +) -> bool { + under.is_some_and(|under| { reactor.scope.iter().any(|rel| { pin_of(&reactor.poms[rel].doc, patch).is_some() && under.get(rel).is_some_and(|u| u.other.is_some()) }) - }); - reactor.wired_before(patch) && !moves + }) } /// One line for every module of `under` whose selection cannot be told, @@ -2221,6 +2271,30 @@ impl Reactor { list: ListFn<'_>, hosted: bool, ) -> Result { + Self::discover_with(read, list, hosted, None) + } + + /// [`Self::discover_for`]. With `unread`, a module or a parent pom + /// that cannot be found or parsed is left out and named there instead + /// of refusing the reactor: for finding the wiring a reactor carries, + /// never for planning over it. + fn discover_with( + read: ReadFn<'_>, + list: ListFn<'_>, + hosted: bool, + mut unread: Option<&mut Vec>, + ) -> Result { + // Leave out what cannot be read, when the caller allows it. + let mut skip = |refusal: JvmRefusal| -> Result<(), JvmRefusal> { + match unread.as_mut() { + Some(unread) => { + let why = refusal.detail.strip_prefix("reason: "); + unread.push(why.unwrap_or(&refusal.detail).to_string()); + Ok(()) + } + None => Err(refusal), + } + }; let root = read("pom.xml") .ok_or_else(|| shape_refusal("no_build_file", "no pom.xml at the project root"))?; let cli_props = read(MAVEN_CONFIG) @@ -2240,14 +2314,27 @@ impl Reactor { modules.extend(implicit_subprojects(list, &poms[&rel].dir)); } for module in modules { - let (module_rel, bytes) = resolve_module(read, &poms[&rel].dir, &rel, &module)?; + let (module_rel, bytes) = match resolve_module(read, &poms[&rel].dir, &rel, &module) + { + Ok(found) => found, + Err(refusal) => { + skip(refusal)?; + continue; + } + }; if poms.contains_key(&module_rel) { if !reactor.contains(&module_rel) { reactor.push(module_rel); } continue; } - let pom = Pom::parse(&module_rel, bytes)?; + let pom = match Pom::parse(&module_rel, bytes) { + Ok(pom) => pom, + Err(refusal) => { + skip(refusal)?; + continue; + } + }; let nested = NESTED_MVN_FILES.iter().find(|f| { !pom.dir.is_empty() && read(&format!("{}/.mvn/{f}", pom.dir)).is_some() }); @@ -2272,8 +2359,13 @@ impl Reactor { for rel in &reactor { let mut cur = rel.clone(); while !local_parent.contains_key(&cur) { - let Some(parent_rel) = local_parent_of(read, &mut poms, &cur)? else { - break; + let parent_rel = match local_parent_of(read, &mut poms, &cur) { + Ok(Some(parent_rel)) => parent_rel, + Ok(None) => break, + Err(refusal) => { + skip(refusal)?; + break; + } }; local_parent.insert(cur.clone(), parent_rel.clone()); if !scope.contains(&parent_rel) { diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs index 2cacd05c1..7d1030fb8 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted.rs @@ -17,20 +17,40 @@ //! property's value rewritten instead: the declaration keeps its text; //! - any other `${...}` version is replaced by the literal suffixed //! version, and the text it replaced is recorded in a comment right -//! after the element ([`ORIGINAL_TAG`]). +//! after the element ([`ORIGINAL_TAG`]); +//! - the `` that serves the suffixed version is declared in +//! the local root of every pom that names it, through the hosted +//! rewriter's own edits ([`HostedRepository`]). //! -//! [`unwire_hosted`] is the inverse, and [`plan_hosted`] makes no edit it -//! does not undo exactly: each pom it would change is unwired again before -//! the plan is returned, and left alone when that is not the text it had. -//! The `` and the `.mvn` files are the hosted rewriter's. +//! # The invariant +//! +//! A plan is whole or it is nothing ([`HostedReactor::plan`]). Once it is +//! written: +//! +//! - no pom names the suffixed version unless the repository that serves +//! it is declared in that pom's local root, and a declaration Maven +//! always reads resolves to it, so discovery ([`HostedReactor::sites`]) +//! finds the patch and every pom that carries part of it; +//! - a rollback returns every pom the plan first wired to the bytes it had +//! ([`HostedRepository::restored`], the restore itself, run over the +//! planned text before anything is written); +//! - when the plan leaves no pom naming the suffixed version (a pin that +//! came to move a module was taken out), the repository goes with it, +//! and the caller drops its checksum lines ([`HostedPlan::unnamed`]); an +//! earlier patch's repository and checksum lines go only once no pom of +//! the reactor names that patch's suffix any more +//! ([`HostedPlan::superseded`]). +//! +//! A plan that cannot keep these is refused ([`HostedPlan::refused`]) and +//! the reactor stays as it was read. use std::collections::{BTreeMap, BTreeSet}; use std::ops::Range; use super::{ - apply_edits, coords_patch, degraded, forget_other_versions, is_base_like, keeps_placement, - line_span, pin_edit, pin_of, pin_update, place_pins, safe_coordinates, unattestable_in, - undetermined_note, unwired_in, Doc, Edit, Pin, Placing, Reactor, Role, + apply_edits, coords_patch, degraded, forget_other_versions, is_base_like, line_span, pin_edit, + pin_moves, pin_of, pin_update, place_pins, safe_coordinates, unattestable_in, + undetermined_note, unwired_in, Doc, Edit, Pin, Placing, Pom, Reactor, Role, }; use crate::crawlers::maven_selection::{MavenSelection, Standing, Verdict}; use crate::formats::maven::split_socket_version; @@ -42,7 +62,7 @@ use crate::vendor::jvm::{Coords, JvmRefusal, ListFn, ReadFn}; pub const ORIGINAL_TAG: &str = ""; -/// What one edit of [`plan_hosted`] is. +/// What one edit of a [`HostedPlan`] is. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HostedEditKind { /// A declaration's `` now reads the suffixed version. @@ -55,234 +75,654 @@ pub enum HostedEditKind { PinMoved, /// A pin that would move a module to another version was taken out. PinRemoved, + /// The patch's `` was declared. + Repository, + /// The patch's `` took its current URL. + RepositoryUrl, + /// A `` nothing names any more was taken out: the patch's + /// own, or an earlier patch's. + RepositoryRemoved, } -/// One edit of [`plan_hosted`]. +/// One edit of a [`HostedPlan`]. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HostedEdit { /// The pom edited. pub rel: String, pub kind: HostedEditKind, - /// The text replaced: a version, a property's value (`None` for a pin, - /// and for a version an earlier patch had suffixed). + /// The text replaced: a version, a property's value (`None` for a pin + /// or a repository, and for a version an earlier patch had suffixed). pub original: Option, /// The property a [`HostedEditKind::Property`] edit rewrote. pub property: Option, + /// The patch uuid whose repository a repository edit concerns. + pub repository: Option, +} + +impl HostedEdit { + fn of(rel: &str, kind: HostedEditKind) -> HostedEdit { + HostedEdit { + rel: rel.to_string(), + kind, + original: None, + property: None, + repository: None, + } + } +} + +/// A pom with the patch's repository declared. +pub enum RepositoryEdit { + /// The repository was added. + Added(String), + /// It was there, pointing elsewhere (a rotated grant). + Refreshed(String), +} + +/// The hosted rewriter's own edits of a pom's ``, and its +/// restore: the planner decides where the repository goes, and holds +/// every pom it plans to what a rollback makes of it. +pub struct HostedRepository<'a> { + /// `pom` with the patch's repository declared; `Ok(None)` when it is + /// there as it should be, `Err` when it cannot be declared in it. + pub ensure: &'a dyn Fn(&str) -> Result, String>, + /// `pom` without the hosted repository of the patch `uuid`; `None` + /// when it declares none that can be taken out. + pub remove: &'a dyn Fn(&str, &str) -> Option, + /// The patch uuids whose hosted repository `pom` declares. + pub declared: &'a dyn Fn(&str) -> Vec, + /// The pom at the first path, holding the second as its text, as a + /// rollback of the patch leaves it. + pub restored: &'a dyn Fn(&str, &str) -> Result, } /// What hosted mode does to a reactor's poms for one patch. #[derive(Debug, Default)] pub struct HostedPlan { - /// The poms that change, with their new text. + /// The poms that change, with their new text: all of them are written, + /// or (a refused plan holds none) nothing is. pub poms: BTreeMap, pub edits: Vec, /// Why a declaration or a pom was left as it is: the vendored /// planner's reason word, and the line. pub notes: Vec<(String, String)>, - /// Whether a pom wires the patch once the plan is written (or did - /// before). + /// Whether the poms wire the patch once the plan is written (or did + /// before): a declaration Maven always reads resolves to the suffixed + /// version, and its repository is declared. pub wired: bool, - /// The local roots under which a pom names the suffixed version: where - /// the `` goes, for every pom below to inherit. - pub roots: Vec, + /// The patch's suffixed version was named before the plan and no pom + /// names it after: its repository was taken out, and its checksum + /// lines are the caller's to drop. + pub unnamed: bool, + /// The suffixed versions of earlier patches of this version that no + /// pom of the reactor names any more: their checksum lines go. + pub superseded: Vec, /// The module directories with a `.mvn` of their own. pub nested_mvn: Vec, /// No module selects the base version, and every answer is certain: /// the versions selected instead. Nothing is planned then. pub not_selected: Option>, + /// Why nothing was planned: the plan could not be written whole + /// without breaking the invariant (the module docs). + pub refused: Option<(String, String)>, } -/// Plan the hosted wiring of the patch `c` in the reactor rooted at -/// `pom.xml` (a single pom is a reactor of one). `selection` is what Maven -/// selects in each module; `None` reads as "cannot be told", which rewrites -/// the declarations that name the base version and pins nothing. -pub fn plan_hosted( - read: ReadFn<'_>, - list: ListFn<'_>, - c: &Coords<'_>, - selection: Option<&MavenSelection>, -) -> Result { - let (g, a, base) = (c.group_id, c.artifact_id, c.version); - if !safe_coordinates(g, a, base) { - return Err(JvmRefusal { - code: "unsafe_coordinates", - detail: format!("unsafe maven coordinates `{g}:{a}:{base}`"), - }); +/// One artifact some pom of a reactor builds at a Socket suffixed version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HostedSite { + pub group: String, + pub artifact: String, + /// `-socket.`. + pub suffixed: String, + /// The patch uuid a pin's comment names, when a pin carries it. + pub uuid: Option, + /// Every pom that names the suffixed version outside comments: a + /// declaration, a pin, or a property a declaration reads. + pub rels: BTreeSet, +} + +/// A reactor read once for hosted mode (a single pom is a reactor of +/// one, with the parent poms it inherits from inside the checkout): the +/// rewriter plans every patch of a run over it, and discovery reads every +/// pin from it, each pom parsed once. A plan rewrites it in place, so the +/// next patch is planned over what the last one wrote. +pub struct HostedReactor { + reactor: Reactor, +} + +/// Why a plan is refused: the reason word, and the line. +type Refused = (String, String); + +fn refused(reason: &str, detail: impl Into) -> Refused { + (reason.to_string(), detail.into()) +} + +impl HostedReactor { + /// Read the reactor rooted at `pom.xml`. Unlike vendored mode, a + /// module with a `.mvn` of its own is no refusal. + pub fn read(read: ReadFn<'_>, list: ListFn<'_>) -> Result { + Reactor::discover_for(read, list, true).map(|reactor| HostedReactor { reactor }) } - let patch = coords_patch(c); - let sv = c.suffixed_version(); - let reactor = Reactor::discover_for(read, list, true)?; - let unread; - let selection = match selection { - Some(selection) => selection, - None => { - unread = MavenSelection::unavailable("what Maven selects was not read"); - &unread - } - }; - let mut plan = HostedPlan { - nested_mvn: reactor.nested_mvn.clone(), - ..HostedPlan::default() - }; - if let Standing::NotSelected(others) = selection.standing(g, a, base) { - if !reactor.wired_before(&patch) { - plan.not_selected = Some(others); - return Ok(plan); + + /// [`Self::read`] for finding the wiring a reactor carries, never for + /// planning over it: a module or a parent pom that cannot be found or + /// parsed is left out, and named in the second value. A reactor + /// discovery could not read whole still shows the pins of the poms it + /// could, so they can be listed and rolled back. + pub fn read_what_is_there( + read: ReadFn<'_>, + list: ListFn<'_>, + ) -> Result<(HostedReactor, Vec), JvmRefusal> { + let mut unread = Vec::new(); + let reactor = Reactor::discover_with(read, list, true, Some(&mut unread))?; + Ok((HostedReactor { reactor }, unread)) + } + + /// Every pom read: the reactor's modules, and each parent pom one + /// inherits from inside the checkout. + pub fn scope(&self) -> &[String] { + &self.reactor.scope + } + + /// The reactor's modules, the root first. + pub fn modules(&self) -> &[String] { + &self.reactor.reactor + } + + /// The text of the pom at `rel` as it reads now. + pub fn text(&self, rel: &str) -> Option<&str> { + self.reactor.poms.get(rel).map(|pom| pom.doc.text.as_str()) + } + + /// Take `text` for the pom at `rel` (a pom of the scope): what another + /// rewriter made of it since it was read. + pub fn set_text(&mut self, rel: &str, text: &str) -> Result<(), JvmRefusal> { + let pom = Pom::parse(rel, text.as_bytes().to_vec())?; + self.reactor.poms.insert(rel.to_string(), pom); + Ok(()) + } + + /// The artifacts the poms build at a Socket suffixed version, read as + /// Maven reads them (a `${...}` through the properties of the + /// declaring pom's chain), with the poms that name each. Declarations + /// inside `` are not read: Maven reads those only while + /// their profile is active. + pub fn sites(&self) -> Vec { + let reactor = &self.reactor; + let mut sites: BTreeMap<(String, String, String), Option> = BTreeMap::new(); + for rel in &reactor.scope { + let doc = &reactor.poms[rel].doc; + let resolve = |v: &str| reactor.interpolate(rel, v); + for dep in doc.declarations() { + if doc.section_of(dep).starts_with("profile:") || !doc.is_main_jar(dep) { + continue; + } + let (Some(group), Some(artifact), Some(version)) = ( + doc.coordinate(dep, "groupId", &resolve), + doc.coordinate(dep, "artifactId", &resolve), + doc.coordinate(dep, "version", &resolve), + ) else { + continue; + }; + if split_socket_version(&version).is_none() { + continue; + } + let uuid = doc.pin_at(dep).map(|pin| pin.uuid); + let tagged = sites.entry((group, artifact, version)).or_default(); + if tagged.is_none() { + *tagged = uuid; + } + } } + sites + .into_iter() + .map(|((group, artifact, suffixed), uuid)| HostedSite { + rels: self.naming(&suffixed).into_iter().collect(), + group, + artifact, + suffixed, + uuid, + }) + .collect() + } + + /// Why `vex` must not attest the hosted patch `c` although the poms + /// wire it, as vendored mode weighs its own wiring: a declaration that + /// may still build the base version ([`unattestable_in`]), or a module + /// that resolves it (or may, by `selection`) and no pin or declaration + /// reaches ([`unwired_in`]). `None` when nothing does. + pub fn unattestable(&self, c: &Coords<'_>, selection: &MavenSelection) -> Option { + unattestable_in(&self.reactor, c).or_else(|| unwired_in(&self.reactor, c, selection)) } - // The declarations that name the base version. - let mut edits: BTreeMap> = BTreeMap::new(); - let mut warnings = Vec::new(); - let mut unpinned = BTreeSet::new(); - let mut managed_roots = BTreeSet::new(); - let told = |rel: &str, dep: usize| { + /// The poms that name `version` outside comments. + fn naming(&self, version: &str) -> Vec { + let reactor = &self.reactor; reactor - .readers_select(rel, dep, selection, c) - .then(|| base.to_string()) - }; - for rel in &reactor.scope { - reactor.rewrite_declarations( - rel, - &patch, - &sv, - &mut edits, - &mut warnings, - &mut unpinned, - &mut managed_roots, - &mut BTreeSet::new(), - &told, - ); + .scope + .iter() + .filter(|rel| reactor.poms[*rel].doc.masked.contains(version)) + .cloned() + .collect() } - forget_other_versions(&mut warnings, &reactor.under(selection, &patch, &|_| false)); - let mut made: Vec = Vec::new(); - let edits = reactor.settle_properties(edits, c, &mut made, &mut plan.notes); - let mut texts: BTreeMap = edits - .into_iter() - .filter(|(_, edits)| !edits.is_empty()) - .map(|(rel, edits)| { - let text = apply_edits(&reactor.poms[&rel].doc.text, edits); - (rel, text) - }) - .collect(); - // The pins: where a module selects the base version and no declaration - // wires it yet. - let rewritten = Reactor::discover_for(&reading(&texts, read), list, true)?; - let under = rewritten.under(selection, &patch, &|module| { - rewritten.wired_without_pin(module, c) - }); - let closed = |rel: &String| unpinned.contains(rel) || managed_roots.contains(rel); - let (mut pins, mut held) = place_pins(&reactor, &patch, Some(&under), &closed, &mut warnings); - // A patch the poms already wire keeps its pins where they are, and a - // module nothing reaches yet that is certain to select the base version - // is pinned all the same: a scan over a cold local repository wires - // what it can tell, and the next one, once the project was resolved, - // completes it. Nothing a pom already holds is moved by this. - if keeps_placement(&reactor, &patch, Some(&under)) { - let unreached = rewritten.under(selection, &patch, &|module| rewritten.covers(module, c)); - let (mut more, mut ignored, mut stranded) = (BTreeSet::new(), BTreeSet::new(), Vec::new()); - for root in reactor.wired_roots() { - let mut placing = Placing { - under: &unreached, - patch: &patch, - pins: &mut more, - held: &mut ignored, - stranded: &mut stranded, + /// Every `-socket.` the poms name outside comments. + fn generations(&self, base: &str) -> BTreeSet { + let prefix = format!("{base}-socket."); + let mut found = BTreeSet::new(); + for rel in &self.reactor.scope { + let masked = &self.reactor.poms[rel].doc.masked; + for (at, _) in masked.match_indices(&prefix) { + let hex8 = masked.get(at + prefix.len()..at + prefix.len() + 8); + if let Some(hex8) = hex8.filter(|h| { + h.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) { + found.insert(format!("{prefix}{hex8}")); + } + } + } + found + } + + /// Take `text` for `rel`, keeping what it held when the plan began. + fn replace( + &mut self, + rel: &str, + text: String, + before: &mut BTreeMap, + ) -> Result<(), Refused> { + let pom = Pom::parse(rel, text.into_bytes()).map_err(|refusal| { + refused( + "edit_not_reversible", + format!("{rel} would no longer read as a pom ({})", refusal.detail), + ) + })?; + if let Some(was) = self.reactor.poms.insert(rel.to_string(), pom) { + before.entry(rel.to_string()).or_insert(was.doc.text); + } + Ok(()) + } + + /// Plan the hosted wiring of the patch `c`, whole or not at all (the + /// module docs), and take it: the reactor then reads as the plan + /// leaves it. `selection` is what Maven selects in each module; `None` + /// reads as "cannot be told", which rewrites the declarations that + /// name the base version and pins nothing. A refused plan + /// ([`HostedPlan::refused`]) leaves the reactor as it was. + pub fn plan( + &mut self, + c: &Coords<'_>, + selection: Option<&MavenSelection>, + repository: &HostedRepository<'_>, + ) -> HostedPlan { + let mut plan = HostedPlan { + nested_mvn: self.reactor.nested_mvn.clone(), + ..HostedPlan::default() + }; + let mut before: BTreeMap = BTreeMap::new(); + if let Err(why) = self.plan_into(c, selection, repository, &mut plan, &mut before) { + for (rel, text) in &before { + // It was read from this text. + let _ = self.set_text(rel, text); + } + return HostedPlan { + refused: Some(why), + notes: plan.notes, + nested_mvn: plan.nested_mvn, + ..HostedPlan::default() }; - reactor.place(&root, !closed(&root), &mut placing, 0); } - held.retain(|rel| !more.contains(rel)); - pins.extend(more); - warnings.extend( - stranded - .into_iter() - .map(|detail| degraded("pin_would_move_module", detail)), - ); - warnings.extend(undetermined_note(&patch, &unreached)); + plan.poms = before + .iter() + .filter_map(|(rel, was)| { + let now = &self.reactor.poms[rel].doc.text; + (now != was).then(|| (rel.clone(), now.clone())) + }) + .collect(); + plan.edits.retain(|edit| plan.poms.contains_key(&edit.rel)); + plan } - for rel in &rewritten.scope { - let doc = &rewritten.poms[rel].doc; - let (pinned, held) = (pins.contains(rel), held.contains(rel)); - let (text, kind) = match pin_of(doc, &patch) { - Some(pin) if !pinned && !held => { - let gav = pin.gav.clone(); - let Some(text) = cut_pins(&doc.text, &|pin| pin.gav == gav) else { - continue; + + fn plan_into( + &mut self, + c: &Coords<'_>, + selection: Option<&MavenSelection>, + repository: &HostedRepository<'_>, + plan: &mut HostedPlan, + before: &mut BTreeMap, + ) -> Result<(), Refused> { + let (g, a, base) = (c.group_id, c.artifact_id, c.version); + if !safe_coordinates(g, a, base) { + return Err(refused( + "unsafe_coordinates", + format!("unsafe maven coordinates `{g}:{a}:{base}`"), + )); + } + let patch = coords_patch(c); + let sv = c.suffixed_version(); + let unread; + let selection = match selection { + Some(selection) => selection, + None => { + unread = MavenSelection::unavailable("what Maven selects was not read"); + &unread + } + }; + // What the poms held before this plan rewrote anything. + let was_wired = self.reactor.wired_before(&patch); + let named_before = self.generations(base); + if let Standing::NotSelected(others) = selection.standing(g, a, base) { + if !was_wired { + plan.not_selected = Some(others); + return Ok(()); + } + } + + // The declarations that name the base version. + let mut warnings = Vec::new(); + let mut unpinned = BTreeSet::new(); + let mut managed_roots = BTreeSet::new(); + let rewritten: Vec<(String, String)> = { + let reactor = &self.reactor; + let mut edits: BTreeMap> = BTreeMap::new(); + let told = |rel: &str, dep: usize| { + reactor + .readers_select(rel, dep, selection, c) + .then(|| base.to_string()) + }; + for rel in &reactor.scope { + reactor.rewrite_declarations( + rel, + &patch, + &sv, + &mut edits, + &mut warnings, + &mut unpinned, + &mut managed_roots, + &mut BTreeSet::new(), + &told, + ); + } + forget_other_versions(&mut warnings, &reactor.under(selection, &patch, &|_| false)); + reactor + .settle_properties(edits, c, &mut plan.edits, &mut plan.notes) + .into_iter() + .filter(|(_, edits)| !edits.is_empty()) + .map(|(rel, edits)| { + let text = apply_edits(&reactor.poms[&rel].doc.text, edits); + (rel, text) + }) + .collect() + }; + for (rel, text) in rewritten { + self.replace(&rel, text, before)?; + } + + // The pins: where a module selects the base version and no + // declaration wires it yet. + let pinned: Vec<(String, String, HostedEditKind)> = { + let reactor = &self.reactor; + let under = reactor.under(selection, &patch, &|module| { + reactor.wired_without_pin(module, c) + }); + let closed = |rel: &String| unpinned.contains(rel) || managed_roots.contains(rel); + let kept = was_wired && !pin_moves(reactor, &patch, Some(&under)); + let (mut pins, mut held) = + place_pins(reactor, &patch, Some(&under), &closed, kept, &mut warnings); + // A patch the poms already wire keeps its pins where they are, + // and a module nothing reaches yet that is certain to select + // the base version is pinned all the same: a scan over a cold + // local repository wires what it can tell, and the next one, + // once the project was resolved, completes it. Nothing a pom + // already holds is moved by this. + if kept { + let unreached = + reactor.under(selection, &patch, &|module| reactor.covers(module, c)); + let (mut more, mut ignored, mut stranded) = + (BTreeSet::new(), BTreeSet::new(), Vec::new()); + for root in reactor.wired_roots() { + let mut placing = Placing { + under: &unreached, + patch: &patch, + pins: &mut more, + held: &mut ignored, + stranded: &mut stranded, + }; + reactor.place(&root, !closed(&root), &mut placing, 0); + } + held.retain(|rel| !more.contains(rel)); + pins.extend(more); + warnings.extend( + stranded + .into_iter() + .map(|detail| degraded("pin_would_move_module", detail)), + ); + warnings.extend(undetermined_note(&patch, &unreached)); + } + let mut pinned = Vec::new(); + for rel in &reactor.scope { + let doc = &reactor.poms[rel].doc; + let (wanted, held) = (pins.contains(rel), held.contains(rel)); + let (text, kind) = match pin_of(doc, &patch) { + Some(pin) if !wanted && !held => { + let gav = pin.gav.clone(); + let Some(text) = cut_pins(&doc.text, &|pin| pin.gav == gav) else { + continue; + }; + (text, HostedEditKind::PinRemoved) + } + Some(pin) if pin.uuid == c.uuid => continue, + Some(pin) => ( + apply_edits(&doc.text, vec![pin_update(doc, &pin, &patch)]), + HostedEditKind::PinMoved, + ), + None if wanted && !held => ( + apply_edits(&doc.text, vec![pin_edit(doc, &patch, &sv).0]), + HostedEditKind::Pin, + ), + None => continue, }; - (text, HostedEditKind::PinRemoved) + pinned.push((rel.clone(), text, kind)); } - Some(pin) if pin.uuid == c.uuid => continue, - Some(pin) => ( - apply_edits(&doc.text, vec![pin_update(doc, &pin, &patch)]), - HostedEditKind::PinMoved, - ), - None if pinned && !held => ( - apply_edits(&doc.text, vec![pin_edit(doc, &patch, &sv).0]), - HostedEditKind::Pin, - ), - None => continue, + pinned }; - texts.insert(rel.clone(), text); - made.push(HostedEdit { - rel: rel.clone(), - kind, - original: None, - property: None, - }); - } + for (rel, text, kind) in pinned { + self.replace(&rel, text, before)?; + plan.edits.push(HostedEdit::of(&rel, kind)); + } - // No edit that could not be taken back exactly. - for (rel, text) in std::mem::take(&mut texts) { - let before = &reactor.poms[&rel].doc.text; - let undone = unwire_hosted(&text, c, true, true); - if undone.is_ok() && undone == unwire_hosted(before, c, true, true) { - texts.insert(rel, text); - continue; + // No edit of a pom that the pom alone could not take back: such a + // pom is left as it was (its modules stay unpatched, and are named). + for (rel, was) in before.clone() { + let now = &self.reactor.poms[&rel].doc.text; + let undone = unwire_hosted(now, c, true, true); + if undone.is_ok() && undone == unwire_hosted(&was, c, true, true) { + continue; + } + // It was read from this text. + let _ = self.set_text(&rel, &was); + plan.edits.retain(|edit| edit.rel != rel); + plan.notes.push(( + "edit_not_reversible".to_string(), + format!( + "{rel}: the pin of {g}:{a}:{base} could not be removed again without a \ + trace (an empty or one-line , or a version that \ + cannot be recorded); {rel} was left as it is" + ), + )); } - made.retain(|edit| edit.rel != rel); - plan.notes.push(( - "edit_not_reversible".to_string(), - format!( - "{rel}: the pin of {g}:{a}:{base} could not be removed again without a trace \ - (an empty or one-line , or a version that cannot be \ - recorded); {rel} was left as it is" - ), - )); - } - let wired = Reactor::discover_for(&reading(&texts, read), list, true)?; - plan.wired = wired.wires(c); - for rel in &wired.scope { - let root = wired.local_root(rel); - if wired.poms[rel].doc.masked.contains(&sv) && !plan.roots.contains(&root) { - plan.roots.push(root); + // The repository follows the wiring: declared in the local root of + // every pom that names the suffixed version, and gone once none + // does. + let named = self.naming(&sv); + let mut removed: BTreeSet = BTreeSet::new(); + if named.is_empty() { + if named_before.contains(&sv) { + plan.unnamed = true; + removed.insert(c.uuid.to_string()); + } + } else { + let mut roots: Vec = Vec::new(); + for rel in &named { + let root = self.reactor.local_root(rel); + if !roots.contains(&root) { + roots.push(root); + } + } + for root in roots { + let text = self.reactor.poms[&root].doc.text.clone(); + let (text, kind) = match (repository.ensure)(&text) { + Ok(None) => continue, + Ok(Some(RepositoryEdit::Added(text))) => (text, HostedEditKind::Repository), + Ok(Some(RepositoryEdit::Refreshed(text))) => { + (text, HostedEditKind::RepositoryUrl) + } + Err(why) => { + return Err(refused( + "repository_unwritable", + format!( + "{root} cannot take the that serves {g}:{a}:{sv} \ + ({why}), and the poms below it would name a version nothing \ + serves" + ), + )) + } + }; + self.replace(&root, text, before)?; + plan.edits.push(HostedEdit { + repository: Some(c.uuid.to_string()), + ..HostedEdit::of(&root, kind) + }); + } + } + // An earlier patch of this version is gone once no pom of the + // reactor names its suffix: any pom, changed by this plan or not. + let named_after = self.generations(base); + plan.superseded = named_before + .difference(&named_after) + .filter(|old| **old != sv) + .cloned() + .collect(); + let suffix_named = |this: &HostedReactor, hex8: &str| { + let suffix = format!("-socket.{hex8}"); + this.reactor + .scope + .iter() + .any(|rel| this.reactor.poms[rel].doc.masked.contains(&suffix)) + }; + let mut gone: Vec<&str> = plan + .superseded + .iter() + .filter_map(|old| split_socket_version(old).map(|(_, hex8)| hex8)) + .filter(|hex8| !suffix_named(self, hex8)) + .collect(); + gone.dedup(); + for rel in self.reactor.scope.clone() { + let mut text = self.reactor.poms[&rel].doc.text.clone(); + let mut taken = Vec::new(); + for uuid in (repository.declared)(&text) { + let superseded = uuid != c.uuid && gone.iter().any(|hex8| uuid.starts_with(hex8)); + if !superseded && !removed.contains(&uuid) { + continue; + } + match (repository.remove)(&text, &uuid) { + Some(next) => { + text = next; + taken.push(uuid); + } + None if uuid == c.uuid => { + return Err(refused( + "repository_unwritable", + format!( + "{rel} declares the of {g}:{a}:{sv}, which no pom \ + names any more, in a form that cannot be taken out" + ), + )) + } + None => {} + } + } + if taken.is_empty() { + continue; + } + self.replace(&rel, text, before)?; + for uuid in taken { + removed.insert(uuid.clone()); + plan.edits.push(HostedEdit { + repository: Some(uuid), + ..HostedEdit::of(&rel, HostedEditKind::RepositoryRemoved) + }); + } } - } - plan.notes - .extend(warnings.into_iter().filter_map(|warning| { - let (reason, detail) = warning.detail.strip_prefix("reason: ")?.split_once(": ")?; - Some((reason.to_string(), detail.to_string())) - })); - plan.poms = texts - .into_iter() - .filter(|(rel, text)| *text != reactor.poms[rel].doc.text) - .collect(); - plan.edits = made - .into_iter() - .filter(|edit| plan.poms.contains_key(&edit.rel)) - .collect(); - Ok(plan) -} -/// `texts` over `read`: the project as it reads once `texts` are written. -fn reading<'a>( - texts: &'a BTreeMap, - read: ReadFn<'a>, -) -> impl Fn(&str) -> Option> + 'a { - move |rel| match texts.get(rel) { - Some(text) => Some(text.clone().into_bytes()), - None => read(rel), + // The plan as a whole: what names the patch is served and found, + // and what it first wired a rollback takes back exactly. + let wired = !named.is_empty() && self.reactor.wires(c); + if !named.is_empty() { + let found = self + .sites() + .into_iter() + .any(|site| site.group == g && site.artifact == a && site.suffixed == sv); + if !wired || !found { + return Err(refused( + "nothing_wired", + format!( + "{} would name {g}:{a}:{sv} only where Maven does not always read it \ + (inside ), so no build is certain to resolve it and a \ + rollback could not find it", + named.join(", ") + ), + )); + } + for rel in &named { + let root = self.reactor.local_root(rel); + let declared = (repository.declared)(&self.reactor.poms[&root].doc.text); + if !declared.iter().any(|uuid| uuid == c.uuid) { + return Err(refused( + "repository_unwritable", + format!( + "{rel} would name {g}:{a}:{sv} with no for it in {root}" + ), + )); + } + } + } + for (rel, was) in before.iter() { + let now = &self.reactor.poms[rel].doc.text; + if now == was { + continue; + } + let back = (repository.restored)(rel, now).map_err(|why| { + refused( + "edit_not_reversible", + format!("{rel} could not be rolled back once written ({why})"), + ) + })?; + // A pom this plan is the first to wire returns to its bytes. + let fresh = unwire_hosted(was, c, true, true).as_deref() == Ok(was.as_str()) + && !(repository.declared)(was) + .iter() + .any(|uuid| uuid == c.uuid || removed.contains(uuid)); + if fresh && back != *was { + return Err(refused( + "edit_not_reversible", + format!( + "a rollback would not return {rel} to the bytes it has now (a \ + or section in a shape that \ + cannot be told from the one written)" + ), + )); + } + } + plan.wired = wired; + plan.notes + .extend(warnings.into_iter().filter_map(|warning| { + let (reason, detail) = warning.detail.strip_prefix("reason: ")?.split_once(": ")?; + Some((reason.to_string(), detail.to_string())) + })); + Ok(()) } } @@ -465,6 +905,7 @@ impl Reactor { kind: HostedEditKind::Property, original: (was == c.version).then_some(was), property: Some(name.clone()), + repository: None, }); rewritten.insert(name.clone()); } @@ -487,6 +928,7 @@ impl Reactor { kind: HostedEditKind::Version, original: original.clone(), property: None, + repository: None, }); kept.push(edit); continue; @@ -516,6 +958,7 @@ impl Reactor { kind: HostedEditKind::Version, original: Some(was.to_string()), property: None, + repository: None, }); kept.push(Edit::plain( after, @@ -651,90 +1094,5 @@ pub fn unwire_hosted( Ok(apply_edits(text, edits)) } -/// Read the reactor as [`plan_hosted`] reads it; `false` when it cannot be -/// read from what `read` returned. For a caller that learns from `read` -/// which files the planner takes. -pub fn readable_for_hosted(read: ReadFn<'_>, list: ListFn<'_>) -> bool { - Reactor::discover_for(read, list, true).is_ok() -} - -/// Why `vex` must not attest the hosted patch `c` although the reactor's -/// poms wire it, as vendored mode weighs its own wiring: a declaration -/// that may still build the base version ([`unattestable_in`]), or a -/// module that resolves it (or may, by `selection`) and no pin or -/// declaration reaches ([`unwired_in`]). `None` when nothing does. -pub fn hosted_unattestable( - read: ReadFn<'_>, - list: ListFn<'_>, - c: &Coords<'_>, - selection: &MavenSelection, -) -> Result, JvmRefusal> { - let reactor = Reactor::discover_for(read, list, true)?; - Ok(unattestable_in(&reactor, c).or_else(|| unwired_in(&reactor, c, selection))) -} - -/// One artifact some pom of a reactor builds at a Socket suffixed version. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct HostedSite { - pub group: String, - pub artifact: String, - /// `-socket.`. - pub suffixed: String, - /// The patch uuid a pin's comment names, when a pin carries it. - pub uuid: Option, - /// Every pom that names the suffixed version outside comments: a - /// declaration, a pin, or a property a declaration reads. - pub rels: BTreeSet, -} - -/// The artifacts the reactor's poms build at a Socket suffixed version, -/// read as Maven reads them (a `${...}` through the properties of the -/// declaring pom's chain), with the poms that name each. Declarations -/// inside `` are not read: Maven reads those only while their -/// profile is active. -pub fn hosted_sites(read: ReadFn<'_>, list: ListFn<'_>) -> Result, JvmRefusal> { - let reactor = Reactor::discover_for(read, list, true)?; - let mut sites: BTreeMap<(String, String, String), Option> = BTreeMap::new(); - for rel in &reactor.scope { - let doc = &reactor.poms[rel].doc; - let resolve = |v: &str| reactor.interpolate(rel, v); - for dep in doc.declarations() { - if doc.section_of(dep).starts_with("profile:") || !doc.is_main_jar(dep) { - continue; - } - let (Some(group), Some(artifact), Some(version)) = ( - doc.coordinate(dep, "groupId", &resolve), - doc.coordinate(dep, "artifactId", &resolve), - doc.coordinate(dep, "version", &resolve), - ) else { - continue; - }; - if split_socket_version(&version).is_none() { - continue; - } - let uuid = doc.pin_at(dep).map(|pin| pin.uuid); - let tagged = sites.entry((group, artifact, version)).or_default(); - if tagged.is_none() { - *tagged = uuid; - } - } - } - Ok(sites - .into_iter() - .map(|((group, artifact, suffixed), uuid)| HostedSite { - rels: reactor - .scope - .iter() - .filter(|rel| reactor.poms[*rel].doc.masked.contains(&suffixed)) - .cloned() - .collect(), - group, - artifact, - suffixed, - uuid, - }) - .collect()) -} - #[cfg(test)] mod tests; diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs index 29d6f1e7c..63a0dde72 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs @@ -89,7 +89,11 @@ fn selecting(files: &Fs, picks: &[(&str, Result<&str, &str>)]) -> MavenSelection MavenSelection::answering(&modules, &picks) } -fn planned(files: &Fs, selection: Option<&MavenSelection>) -> HostedPlan { +/// Where the grant serves the patch from. +const INDEX_URL: &str = + "https://patch.socket.dev/patch-registry/maven/tok/4d5e6f70-8192-4a3b-9c4d-5e6f708192a3/maven2"; + +fn reactor(files: &Fs) -> HostedReactor { let read = |rel: &str| files.get(rel).map(|text| text.clone().into_bytes()); let list = |dir: &str| { let bytes: BTreeMap> = files @@ -98,7 +102,29 @@ fn planned(files: &Fs, selection: Option<&MavenSelection>) -> HostedPlan { .collect(); crate::vendor::jvm::testing::list_of(&bytes, dir) }; - plan_hosted(&read, &list, &coords(), selection).expect("a plan") + HostedReactor::read(&read, &list).expect("a reactor") +} + +/// Whether `files` head a reactor, which is how a rollback reads them. +fn heads_reactor(files: &Fs) -> bool { + files.keys().filter(|rel| rel.ends_with("pom.xml")).count() > 1 +} + +/// The plan for `c` over `files`, with the hosted rewriter's own +/// repository edits and restore. +fn planned_for(files: &Fs, c: &Coords<'_>, selection: Option<&MavenSelection>) -> HostedPlan { + let index_url = INDEX_URL.replace(UUID, c.uuid); + crate::patch::redirect::with_hosted_repository( + c, + &index_url, + &BTreeMap::new(), + heads_reactor(files), + |repository| reactor(files).plan(c, selection, repository), + ) +} + +fn planned(files: &Fs, selection: Option<&MavenSelection>) -> HostedPlan { + planned_for(files, &coords(), selection) } fn written(files: &Fs, plan: &HostedPlan) -> Fs { @@ -107,20 +133,103 @@ fn written(files: &Fs, plan: &HostedPlan) -> Fs { out } -/// Every pom of `after` unwired again, which must be `before`. +/// `files` as a rollback of the patch `c` leaves them: every pom through +/// the restore `rollback` runs. +fn rolled_back_for(files: &Fs, c: &Coords<'_>) -> Fs { + let index_url = INDEX_URL.replace(UUID, c.uuid); + let pin = crate::patch::redirect::upstream::maven::PinIn { + group: c.group_id, + artifact: c.artifact_id, + base: c.version, + uuid: c.uuid, + reactor: heads_reactor(files), + }; + let hosted_uuid = |url: &str| (url == index_url).then(|| c.uuid.to_string()); + files + .iter() + .map(|(rel, text)| { + let done = crate::patch::redirect::upstream::maven::restore_pom( + rel, + text, + &BTreeMap::new(), + &pin, + &hosted_uuid, + ) + .unwrap_or_else(|why| panic!("{rel}: {why}")); + (rel.clone(), done.text) + }) + .collect() +} + +/// Every pom of `after` rolled back, which must be `before`. fn assert_unwires_to(after: &Fs, before: &Fs) { - for (rel, text) in after { - assert_eq!( - unwire_hosted(text, &coords(), false, true).as_deref(), - Ok(before[rel].as_str()), - "{rel}" - ); + assert_eq!(&rolled_back_for(after, &coords()), before); +} + +/// THE INVARIANT, on poms as written: a pom names a `-socket.` +/// version only when a declaration Maven always reads resolves to it (so +/// discovery finds it, in every pom that names it) and its local root +/// declares the repository that serves it; and no pom declares a hosted +/// repository whose suffix no pom names. +fn assert_invariant(files: &Fs) { + let reactor = reactor(files); + let sites = reactor.sites(); + let repositories = |text: &str| -> Vec { + crate::patch::redirect::generation::named_generations(text) + .into_iter() + .collect() + }; + for (rel, text) in files { + let (masked, _) = super::super::mask(text); + for (at, _) in masked.match_indices("-socket.") { + let hex8 = &masked[at + 8..at + 16]; + let site = sites + .iter() + .find(|site| site.suffixed.ends_with(hex8) && site.rels.contains(rel)) + .unwrap_or_else(|| panic!("{rel} names -socket.{hex8}, which discovery cannot find: {sites:?}\n{text}")); + // The root of the chain: the last pom a child inherits from. + let served = files.iter().any(|(_, other)| { + repositories(other) + .iter() + .any(|uuid| uuid.starts_with(hex8)) + }); + assert!( + served, + "{rel} names {} with no repository for it", + site.suffixed + ); + } + for uuid in repositories(text) { + assert!( + sites.iter().any(|site| site.suffixed.ends_with(&uuid[..8])), + "{rel} declares the repository of {uuid}, which no pom names: {text}" + ); + } } } +fn is_repository(kind: HostedEditKind) -> bool { + matches!( + kind, + HostedEditKind::Repository + | HostedEditKind::RepositoryUrl + | HostedEditKind::RepositoryRemoved + ) +} + +/// The pom edits of `plan`, the repository's apart ([`repositories`]). fn kinds(plan: &HostedPlan) -> Vec<(&str, HostedEditKind)> { plan.edits .iter() + .filter(|edit| !is_repository(edit.kind)) + .map(|edit| (edit.rel.as_str(), edit.kind)) + .collect() +} + +fn repositories(plan: &HostedPlan) -> Vec<(&str, HostedEditKind)> { + plan.edits + .iter() + .filter(|edit| is_repository(edit.kind)) .map(|edit| (edit.rel.as_str(), edit.kind)) .collect() } @@ -150,7 +259,10 @@ fn a_pin_goes_in_the_module_that_selects_the_version_and_no_other() { let plan = planned(&files, Some(&selection)); assert_eq!(kinds(&plan), [("a/pom.xml", HostedEditKind::Pin)]); assert!(plan.wired); - assert_eq!(plan.roots, ["pom.xml"]); + assert_eq!( + repositories(&plan), + [("pom.xml", HostedEditKind::Repository)] + ); let a = &plan.poms["a/pom.xml"]; assert!( a.contains(&format!( @@ -210,6 +322,10 @@ fn a_declaration_of_the_version_is_rewritten_and_needs_no_pin() { files["a/pom.xml"].replace(BASE, SV), "only the version text changes" ); + assert_eq!( + repositories(&plan), + [("pom.xml", HostedEditKind::Repository)] + ); assert!(reasons(&plan).is_empty(), "{:?}", plan.notes); assert_unwires_to(&written(&files, &plan), &files); // The declaration is rewritten whatever Maven selects elsewhere, since @@ -238,12 +354,10 @@ fn a_property_only_the_artifact_reads_is_rewritten_itself() { assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Property)]); assert_eq!(plan.edits[0].property.as_deref(), Some("victim.version")); assert_eq!(plan.edits[0].original.as_deref(), Some(BASE)); - assert_eq!( - plan.poms["pom.xml"], - files["pom.xml"].replace( - "1.10.0", - &format!("{SV}") - ) + assert!( + plan.poms["pom.xml"].contains(&format!("{SV}")) + && !plan.poms.contains_key("a/pom.xml"), + "the property takes the version, the declarations keep their text" ); assert!(plan.wired); let after = written(&files, &plan); @@ -275,13 +389,19 @@ fn a_property_a_sibling_reads_is_left_alone() { assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Version)]); assert_eq!(plan.edits[0].original.as_deref(), Some("${lib.version}")); let pom = &plan.poms["pom.xml"]; - assert_eq!( - *pom, - files["pom.xml"].replacen( - "${lib.version}", - &format!("{SV}"), - 1 - ) + assert!( + pom.starts_with( + files["pom.xml"] + .replacen( + "${lib.version}", + &format!( + "{SV}" + ), + 1 + ) + .trim_end_matches("\n") + ), + "{pom}" ); assert!( pom.contains("1.10.0") @@ -475,8 +595,28 @@ fn a_pin_that_would_move_a_module_is_taken_out() { ("a/pom.xml", HostedEditKind::Pin) ] ); - assert_eq!(plan.poms["pom.xml"], files["pom.xml"]); - assert_unwires_to(&written(&pinned, &plan), &files); + assert!( + !plan.poms["pom.xml"].contains(SV) && plan.poms["pom.xml"].contains(""), + "the pin goes from the root, the repository a still needs stays" + ); + let after = written(&pinned, &plan); + assert_invariant(&after); + assert_unwires_to(&after, &files); + + // No module selects the version any more: the last pin goes, and the + // repository with it, so nothing of the patch is left to roll back. + let none = selecting( + &after, + &[("a/pom.xml", Ok("1.11.0")), ("b/pom.xml", Ok("1.11.0"))], + ); + let plan = planned(&after, Some(&none)); + assert_eq!(kinds(&plan), [("a/pom.xml", HostedEditKind::PinRemoved)]); + assert_eq!( + repositories(&plan), + [("pom.xml", HostedEditKind::RepositoryRemoved)] + ); + assert!(plan.unnamed && !plan.wired); + assert_eq!(written(&after, &plan), files, "as before the first scan"); } /// A pin of an earlier patch of the same version moves to this patch @@ -494,6 +634,14 @@ fn a_pin_of_an_earlier_patch_moves_to_this_one() { )]); let plan = planned(&earlier, Some(&selection)); assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::PinMoved)]); + assert_eq!( + repositories(&plan), + [ + ("pom.xml", HostedEditKind::Repository), + ("pom.xml", HostedEditKind::RepositoryRemoved) + ] + ); + assert_eq!(plan.superseded, ["1.10.0-socket.0a1b2c3d"]); assert_eq!(plan.poms["pom.xml"], pinned["pom.xml"]); } @@ -548,9 +696,12 @@ fn unwiring_takes_out_only_what_it_is_asked_for() { unwire_hosted(&after["pom.xml"], &other, false, true).as_deref(), Ok(after["pom.xml"].as_str()) ); - assert_eq!( - unwire_hosted(&after["pom.xml"], &other, true, true).as_deref(), - Ok(files["pom.xml"].as_str()) + let unwired = unwire_hosted(&after["pom.xml"], &other, true, true).unwrap(); + assert!( + !unwired.contains(SV) + && !unwired.contains(ORIGINAL_TAG) + && unwired.matches("${lib.version}").count() == 2, + "{unwired}" ); let literal = single(&deps(&dep(A, Some(SV)))); @@ -579,10 +730,7 @@ fn the_wiring_of_a_reactor_is_found_in_every_pom_that_carries_it() { ]); let selection = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); let after = written(&files, &planned(&files, Some(&selection))); - let sites = |files: &Fs| { - let read = |rel: &str| files.get(rel).map(|text| text.clone().into_bytes()); - hosted_sites(&read, &|_| Vec::new()).unwrap() - }; + let sites = |files: &Fs| reactor(files).sites(); let site = |uuid: Option<&str>, rels: &[&str]| HostedSite { group: G.to_string(), artifact: A.to_string(), @@ -602,3 +750,250 @@ fn the_wiring_of_a_reactor_is_found_in_every_pom_that_carries_it() { let pinned = written(&pinned, &planned(&pinned, Some(&selection))); assert_eq!(sites(&pinned), [site(Some(UUID), &["pom.xml"])]); } + +/// A declaration Maven reads only while a profile is active wires +/// nothing on its own: rewriting it would name a version no build is +/// certain to resolve and no discovery reads, with no repository to serve +/// it. The plan is refused whole, and the reactor is as it was read. +#[test] +fn a_declaration_only_a_profile_holds_is_not_rewritten_alone() { + let profiled = format!( + "\n 4.0.0\n \n t\n \ + root\n 1\n \n \ + a\n \n \n extra\n \ + \n {} \n \n \n\n", + dep(A, Some(BASE)) + ); + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &profiled), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + for selection in [None, Some(selecting(&files, &[("b/pom.xml", Err("cold"))]))] { + let mut reactor = reactor(&files); + let plan = crate::patch::redirect::with_hosted_repository( + &coords(), + INDEX_URL, + &BTreeMap::new(), + true, + |repository| reactor.plan(&coords(), selection.as_ref(), repository), + ); + assert_eq!( + plan.refused.as_ref().map(|(reason, _)| reason.as_str()), + Some("nothing_wired"), + "{:?}", + plan.notes + ); + assert!(plan.poms.is_empty() && plan.edits.is_empty() && !plan.wired); + for (rel, text) in &files { + assert_eq!( + reactor.text(rel), + Some(text.as_str()), + "{rel} is as it was read" + ); + } + } + // Beside a declaration Maven always reads, the profile's one is + // rewritten with it: the repository then serves both. + let both = fs(&[ + ("pom.xml", &root("")), + ( + "a/pom.xml", + &profiled.replace( + " ", + &format!("{} ", deps(&dep(A, Some(BASE)))), + ), + ), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let plan = planned(&both, None); + assert!(plan.wired && plan.refused.is_none(), "{:?}", plan.refused); + assert_eq!(plan.poms["a/pom.xml"].matches(SV).count(), 2); + let after = written(&both, &plan); + assert_invariant(&after); + assert_unwires_to(&after, &both); +} + +/// A plan is written whole or not at all. When the pom that must declare +/// the repository cannot take it, nothing is written: not the pin in the +/// module below, which would name a version nothing serves. +#[test] +fn a_plan_whose_repository_cannot_be_declared_writes_nothing() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep(A, Some(BASE)))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let selection = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let mut reactor = reactor(&files); + let plan = crate::patch::redirect::with_hosted_repository( + &coords(), + INDEX_URL, + &BTreeMap::new(), + true, + |real| { + let unreadable = HostedRepository { + ensure: &|_| Err("not readable as a pom".to_string()), + remove: real.remove, + declared: real.declared, + restored: real.restored, + }; + reactor.plan(&coords(), Some(&selection), &unreadable) + }, + ); + assert_eq!( + plan.refused.as_ref().map(|(reason, _)| reason.as_str()), + Some("repository_unwritable") + ); + assert!(plan.poms.is_empty() && plan.edits.is_empty() && !plan.wired); + for (rel, text) in &files { + assert_eq!( + reactor.text(rel), + Some(text.as_str()), + "{rel} is as it was read" + ); + } + + // A `` in a shape a rollback could not put back (a + // self-closed one is expanded to take the repository) refuses the + // plan the same way. + let self_closed = fs(&[ + ("pom.xml", &root(" \n")), + ("a/pom.xml", &module("a", &dep(A, Some(BASE)))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let plan = planned(&self_closed, Some(&selection)); + assert_eq!( + plan.refused.as_ref().map(|(reason, _)| reason.as_str()), + Some("edit_not_reversible"), + "{:?}", + plan.poms + ); + assert!(plan.poms.is_empty()); +} + +/// An earlier patch's repository goes only once no pom of the reactor +/// names that patch's suffix: a pom this plan did not change counts. Here +/// module b still reads the earlier suffix through a property a profile +/// may redefine, which this plan leaves alone, while the pin moves on. +#[test] +fn an_earlier_patch_keeps_its_repository_while_any_pom_names_it() { + const EARLIER: &str = "0a1b2c3d-8192-4a3b-9c4d-5e6f708192a3"; + const EARLIER_SV: &str = "1.10.0-socket.0a1b2c3d"; + let earlier = Coords { + uuid: EARLIER, + ..coords() + }; + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ( + "b/pom.xml", + &module("b", &dep(A, Some("${victim.version}"))).replace( + " ", + &format!( + "{} ", + properties(&[("victim.version", BASE)]) + ), + ), + ), + ]); + let selection = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let first = planned_for(&files, &earlier, Some(&selection)); + assert!(first.wired, "{:?}", first.refused); + let mut wired = written(&files, &first); + assert!(wired["b/pom.xml"].contains(&format!("{EARLIER_SV}<"))); + assert!( + wired["pom.xml"].contains(EARLIER_SV), + "a is pinned, through the root: {:?}", + first.edits + ); + // b's property comes to be redefined by a profile: no later plan may + // rewrite it, since the profile's build must keep its own version. + let b = wired["b/pom.xml"].replace( + "", + " \n \n old\n \n \ + 1.9\n \n \n \ + \n", + ); + wired.insert("b/pom.xml".to_string(), b); + + // (b's declaration now rules the root out, so the pin is written + // afresh below it; what matters here is what becomes of the earlier + // patch's repository.) + let plan = planned(&wired, Some(&selection)); + assert!(plan.wired, "{:?}", plan.refused); + assert_eq!( + repositories(&plan), + [("pom.xml", HostedEditKind::Repository)] + ); + assert!( + plan.superseded.is_empty(), + "b still names it: {:?}", + plan.superseded + ); + let after = written(&wired, &plan); + assert!( + after["pom.xml"].contains(&format!("socket-patch-{EARLIER}")) + && after["pom.xml"].contains(&format!("socket-patch-{UUID}")), + "both repositories serve a pom: {}", + after["pom.xml"] + ); + assert!( + after["b/pom.xml"].contains(&format!("{EARLIER_SV}<")) + && after["a/pom.xml"].contains(SV), + "b keeps the version it reads, a moves on: {after:#?}" + ); + assert_invariant(&after); + + // Once b moves on too, the earlier repository goes with its last use. + let mut moved = after.clone(); + let b = moved["b/pom.xml"].replace(EARLIER_SV, SV); + moved.insert("b/pom.xml".to_string(), b); + moved.insert("pom.xml".to_string(), wired["pom.xml"].clone()); + let plan = planned(&moved, Some(&selection)); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::PinMoved)]); + assert_eq!(plan.superseded, [EARLIER_SV]); + let after = written(&moved, &plan); + assert!(!after["pom.xml"].contains(EARLIER), "{}", after["pom.xml"]); + assert_invariant(&after); +} + +/// One reactor is read once and planned over for every patch of a run: +/// the second patch is planned over what the first wrote. +#[test] +fn every_patch_of_a_run_is_planned_over_one_reactor() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep(A, Some(BASE)))), + ("b/pom.xml", &module("b", &dep("other", Some("2.0")))), + ]); + let other = Coords { + group_id: G, + artifact_id: "other", + version: "2.0", + uuid: "0a1b2c3d-8192-4a3b-9c4d-5e6f708192a3", + }; + let mut reactor = reactor(&files); + let mut all = files.clone(); + for c in [coords(), other] { + let index_url = INDEX_URL.replace(UUID, c.uuid); + let plan = crate::patch::redirect::with_hosted_repository( + &c, + &index_url, + &BTreeMap::new(), + true, + |repository| reactor.plan(&c, None, repository), + ); + assert!(plan.wired, "{:?}", plan.refused); + all.extend(plan.poms); + } + for (rel, text) in &all { + assert_eq!(reactor.text(rel), Some(text.as_str()), "{rel}"); + } + assert!( + all["pom.xml"].matches("").count() == 2 + && all["b/pom.xml"].contains("2.0-socket.0a1b2c3d") + ); + assert_invariant(&all); +} diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/reader.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/reader.rs new file mode 100644 index 000000000..8d1d0c6c8 --- /dev/null +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/reader.rs @@ -0,0 +1,319 @@ +//! Reads the files of a reactor for a caller that reads a project its own +//! way (a disk, a snapshot of it, an in-memory project). +//! +//! The reactor planner reads through a synchronous function, and stops at +//! the first module pom it cannot find. A caller that learns from it which +//! files to fetch therefore learns one module at a time. [`read_reactor`] +//! walks the same files by itself instead: every pom is parsed once, each +//! pom's modules, parent and (for Maven 4) discovered subprojects are asked +//! for together, and a file that is not there stops nothing. The hosted +//! rewriter, its discovery and its restore all read a reactor through it, +//! so what one of them plans over is what the others find. + +use std::collections::{BTreeMap, BTreeSet}; +use std::future::Future; + +use super::{ + cli_properties, discovery_on, module_refs, normalize, pom_candidates, subprojects_in, Pom, + MAVEN_CONFIG, NESTED_MVN_FILES, +}; +use crate::vendor::jvm::layout::POM_FILE; +use crate::vendor::lock_inventory::ProjectView; + +/// How many files one reactor is read for: far more than any reactor +/// holds, so only a walk gone wrong stops here (the planner then refuses +/// the reactor for the module it cannot find). +const MAX_FILES: usize = 200_000; + +/// One thing the walk asks its caller for. +enum Wanted { + /// The text of a file. + File(String), + /// The subprojects Maven 4 discovers under a directory. + Subprojects(String), +} + +/// The walk: what was read so far, and what to read next. +struct Walk { + texts: BTreeMap, + /// Every path asked for, answered or not. + asked: BTreeSet, + /// The paths that are poms when they are there. + poms: BTreeSet, + /// `/pom.xml` → ``: a `` or `` may name + /// the pom file itself, which is tried once its directory reading has + /// no `pom.xml`. + named_file: BTreeMap, + wanted: Vec, + /// Maven 4 subproject discovery is on (`.mvn/maven.config` may turn it + /// off). + discovery: bool, + listed: BTreeSet, +} + +impl Walk { + fn new(root_pom: &str, maven_config: Option<&str>) -> Walk { + let mut walk = Walk { + texts: BTreeMap::new(), + asked: BTreeSet::from([POM_FILE.to_string(), MAVEN_CONFIG.to_string()]), + poms: BTreeSet::from([POM_FILE.to_string()]), + named_file: BTreeMap::new(), + wanted: Vec::new(), + discovery: discovery_on(&maven_config.map(cli_properties).unwrap_or_default()), + listed: BTreeSet::new(), + }; + if let Some(config) = maven_config { + walk.texts + .insert(MAVEN_CONFIG.to_string(), config.to_string()); + } + walk.supply(POM_FILE.to_string(), Some(root_pom.to_string())); + walk + } + + fn want(&mut self, rel: String) { + if self.asked.len() < MAX_FILES && self.asked.insert(rel.clone()) { + self.wanted.push(Wanted::File(rel)); + } + } + + /// Ask for the pom the normalized `path` names: `/pom.xml`, else + /// the file `path` itself. + fn want_pom(&mut self, path: String) { + let mut candidates = pom_candidates(path).into_iter(); + let Some(first) = candidates.next() else { + return; + }; + if let Some(file) = candidates.next() { + self.named_file.insert(first.clone(), file); + } + self.poms.insert(first.clone()); + self.want(first); + } + + /// The answer for `rel`: its text, or `None` when it is not there (or + /// cannot be read). + fn supply(&mut self, rel: String, text: Option) { + let Some(text) = text else { + if let Some(file) = self.named_file.remove(&rel) { + self.poms.insert(file.clone()); + self.want(file); + } + return; + }; + if self.poms.contains(&rel) { + self.follow(&rel, &text); + } + self.texts.insert(rel, text); + } + + /// Ask for what the pom at `rel` leads the planner to: its modules, + /// its parent in the checkout, the subprojects Maven 4 discovers under + /// it, and whether its directory has a `.mvn` of its own. A pom that + /// does not parse leads nowhere; the planner says so. + fn follow(&mut self, rel: &str, text: &str) { + let Ok(pom) = Pom::parse(rel, text.as_bytes().to_vec()) else { + return; + }; + for module in module_refs(&pom.doc) { + if module.is_empty() || module.contains("${") { + continue; + } + if let Some(path) = normalize(&pom.dir, &module) { + self.want_pom(path); + } + } + if self.discovery && pom.discovers_subprojects && self.listed.insert(pom.dir.clone()) { + self.wanted.push(Wanted::Subprojects(pom.dir.clone())); + } + if !pom.dir.is_empty() { + for file in NESTED_MVN_FILES { + self.want(format!("{}/.mvn/{file}", pom.dir)); + } + } + let relative = match &pom.parent { + None => None, + Some(parent) => match parent.relative_path.as_deref() { + Some("") => None, + Some(path) => Some(path), + None => Some("../pom.xml"), + }, + }; + if let Some(path) = relative.and_then(|path| normalize(&pom.dir, path)) { + self.want_pom(path); + } + } +} + +/// Every file the reactor planner reads for the project whose root pom is +/// `root_pom` (with `.mvn/maven.config` as `maven_config`), by +/// root-relative path: the root pom and the config themselves, the pom of +/// each module (theirs in turn), each parent pom a module inherits from +/// inside the checkout, the subprojects Maven 4 discovers, and the `.mvn` +/// files of a module directory (the planner asks whether they are there). +/// +/// `read` fetches one file as text, `None` when it is missing or not +/// readable; a path the walk asks for may be a directory. A file that is a +/// symbolic link is never read: hosted mode would replace the link with a +/// copy when it rewrote it, and the planner must not plan over a pom it +/// may not write. Its module then reads as missing, and the planner +/// refuses the reactor with nothing written. A subproject Maven 4 +/// discovers whose pom cannot be read is kept, empty, so the reactor is +/// refused the same way and not planned without it. +pub async fn read_reactor( + view: &ProjectView<'_>, + root_pom: &str, + maven_config: Option<&str>, + mut read: F, +) -> BTreeMap +where + F: FnMut(String) -> Fut, + Fut: Future>, +{ + let mut walk = Walk::new(root_pom, maven_config); + while let Some(wanted) = walk.wanted.pop() { + match wanted { + Wanted::File(rel) => { + let text = match view.is_symlink(&rel) { + true => None, + false => read(rel.clone()).await, + }; + walk.supply(rel, text); + } + Wanted::Subprojects(dir) => { + for name in subprojects_in(view, &dir).await { + let rel = match dir.as_str() { + "" => format!("{name}/{POM_FILE}"), + dir => format!("{dir}/{name}/{POM_FILE}"), + }; + if !walk.asked.insert(rel.clone()) { + continue; + } + let text = match view.is_symlink(&rel) { + true => None, + false => read(rel.clone()).await, + }; + walk.poms.insert(rel.clone()); + walk.supply(rel, Some(text.unwrap_or_default())); + } + } + } + } + walk.texts +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::vendor::lock_inventory::{MemoryEntry, MemoryProject}; + + fn pom(artifact: &str, body: &str) -> String { + format!( + "\n 4.0.0\n t\n \ + {artifact}\n 1\n{body}\n" + ) + } + + fn modules(names: &[String]) -> String { + let list: String = names + .iter() + .map(|name| format!(" {name}\n")) + .collect(); + format!(" pom\n \n{list} \n") + } + + /// Read the reactor of `project`, with every path `read` was asked. + async fn read(project: &MemoryProject) -> (BTreeMap, Vec) { + let view = ProjectView::Memory(project); + let root = match project.get("pom.xml") { + Some(MemoryEntry::Text(text)) => text.to_string(), + _ => panic!("no root pom"), + }; + let asked = std::cell::RefCell::new(Vec::new()); + let texts = read_reactor(&view, &root, None, |rel| { + asked.borrow_mut().push(rel.clone()); + let text = match project.get(&rel) { + Some(MemoryEntry::Text(text)) => Some(text.to_string()), + _ => None, + }; + async move { text } + }) + .await; + (texts, asked.into_inner()) + } + + /// A reactor of hundreds of modules, groups of them under their own + /// aggregator, is read whole, each file asked for once: the number of + /// modules bounds nothing, and no pom is fetched or parsed twice. + #[tokio::test] + async fn a_large_reactor_is_read_whole_and_each_file_once() { + let mut project = MemoryProject::new(); + let groups: Vec = (0..20).map(|g| format!("group-{g}")).collect(); + project.insert_text("pom.xml", pom("root", &modules(&groups)).as_str()); + let mut poms = vec!["pom.xml".to_string()]; + for group in &groups { + let members: Vec = (0..10).map(|m| format!("module-{m}")).collect(); + project.insert_text( + format!("{group}/pom.xml"), + pom(group, &modules(&members)).as_str(), + ); + poms.push(format!("{group}/pom.xml")); + for member in &members { + project.insert_text( + format!("{group}/{member}/pom.xml"), + pom(&format!("{group}-{member}"), "").as_str(), + ); + poms.push(format!("{group}/{member}/pom.xml")); + } + } + let (texts, asked) = read(&project).await; + assert_eq!(poms.len(), 221); + for rel in &poms { + assert!(texts.contains_key(rel), "{rel} was not read"); + } + let mut once = asked.clone(); + once.sort(); + once.dedup(); + assert_eq!(asked.len(), once.len(), "a path was asked for twice"); + // What the planner then reads from these files is the whole reactor. + let read = |rel: &str| texts.get(rel).map(|text| text.clone().into_bytes()); + let list = |dir: &str| crate::patch::redirect::gradle::key_list(&texts, dir); + let reactor = super::super::HostedReactor::read(&read, &list).expect("a reactor"); + assert_eq!(reactor.modules().len(), 221); + } + + /// A file that is not there stops nothing: its siblings are read all + /// the same. A module named by its pom file is read; a module pom that + /// is a symbolic link is not; a parent pom outside the module list is. + #[tokio::test] + async fn a_missing_or_linked_module_stops_nothing() { + let mut project = MemoryProject::new(); + let names: Vec = ["gone", "linked", "named/custom.xml", "kept"] + .map(str::to_string) + .into(); + project.insert_text("pom.xml", pom("root", &modules(&names)).as_str()); + project.insert("linked/pom.xml", MemoryEntry::Symlink); + project.insert_text("named/custom.xml", pom("named", "").as_str()); + project.insert_text( + "kept/pom.xml", + pom( + "kept", + " \n t\n base\n \ + 1\n ../base/pom.xml\n \ + \n", + ) + .as_str(), + ); + project.insert_text("base/pom.xml", pom("base", "").as_str()); + let (texts, _) = read(&project).await; + let read: Vec<&str> = texts.keys().map(String::as_str).collect(); + assert_eq!( + read, + [ + "base/pom.xml", + "kept/pom.xml", + "named/custom.xml", + "pom.xml" + ] + ); + } +} diff --git a/crates/socket-patch-core/src/vex/discover/maven.rs b/crates/socket-patch-core/src/vex/discover/maven.rs index 4ba8e6c91..ba1737c37 100644 --- a/crates/socket-patch-core/src/vex/discover/maven.rs +++ b/crates/socket-patch-core/src/vex/discover/maven.rs @@ -214,32 +214,56 @@ pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { } let gas = live_gas(&pom.deps); - let reactor = crate::vendor::jvm::maven_reactor::declares_modules(&raw) - || (crate::vendor::jvm::maven_reactor::may_discover_subprojects(&raw, config.as_deref()) - && !crate::vendor::jvm::maven_reactor::implicit_subprojects_in(&ctx.view) - .await - .is_empty()); - // A reactor is read whole; one whose poms cannot all be read falls - // back to its root pom, whose pin then stays a ref and is not attested. - let unread_reactor = match reactor { - true => { - extract_hosted_reactor(ctx, &raw, config.as_deref(), &user_properties, &hosted, out) - .await - .err() - } - false => None, + // The project as the hosted rewriter reads it: every pom of a reactor, + // and each parent pom one inherits from inside the checkout. Hosted + // wiring may sit in any of them, so whenever there is more than the + // root pom they are read together. A pom of the reactor that cannot + // be read is left out: the pins of the others are still refs, and + // none is attested. Only a root pom the reactor reader cannot parse + // falls back to the single-pom reading below. + use crate::vendor::jvm::maven_reactor::{heads_reactor_in, read_reactor, HostedReactor}; + let texts = read_reactor(&ctx.view, &raw, config.as_deref(), |rel| async move { + ctx.read_text_quiet(&rel).await + }) + .await; + let heads_reactor = heads_reactor_in(&ctx.view, &raw, config.as_deref()).await; + let reactor = { + let read = |rel: &str| texts.get(rel).map(|text| text.clone().into_bytes()); + let list = |dir: &str| crate::patch::redirect::gradle::key_list(&texts, dir); + HostedReactor::read_what_is_there(&read, &list) }; - if !reactor || unread_reactor.is_some() { - extract_hosted( - ctx, - (&raw, &pom), - &gas, - &hosted, - unread_reactor.as_deref(), - config.as_deref(), - out, - ) - .await; + match reactor { + Ok((reactor, unread)) if heads_reactor || reactor.scope().len() > 1 => { + extract_hosted_reactor( + ctx, + (&reactor, &unread), + &texts, + config.as_deref(), + &user_properties, + &hosted, + out, + ) + .await; + } + reactor => { + let unread = reactor.err().filter(|_| heads_reactor).map(|refusal| { + refusal + .detail + .strip_prefix("reason: ") + .unwrap_or(&refusal.detail) + .to_string() + }); + extract_hosted( + ctx, + (&raw, &pom), + &gas, + &hosted, + unread.as_deref(), + config.as_deref(), + out, + ) + .await; + } } if !vendored.is_empty() { extract_vendored(ctx, &pom.deps, &vendored, out).await; @@ -530,72 +554,12 @@ async fn extract_hosted( // ── hosted, in a reactor ───────────────────────────────────────────────── -/// How many rounds [`reactor_texts`] reads (see the hosted engine's -/// `read_maven_reactor`, which reads the same poms the same way). -const MAX_REACTOR_READ_ROUNDS: usize = 64; - -/// Every pom the reactor planner reads for the root pom `root`, by -/// root-relative path (the root and `.mvn/maven.config` included): it is -/// asked what it reads until it asks for nothing new. -async fn reactor_texts( - ctx: &DiscoverCtx<'_>, - root: &str, - config: Option<&str>, - out: &mut Discovery, -) -> BTreeMap { - use crate::vendor::jvm::maven_reactor::{ - implicit_subprojects_in, may_discover_subprojects, readable_for_hosted, - }; - let mut texts = BTreeMap::from([(POM.to_string(), root.to_string())]); - if let Some(config) = config { - texts.insert(MVN_CONFIG.to_string(), config.to_string()); - } - if may_discover_subprojects(root, config) { - for dir in implicit_subprojects_in(&ctx.view).await { - let rel = format!("{dir}/{POM}"); - if let Some(text) = ctx.read_text(&rel, out).await { - texts.insert(rel, text); - } - } - } - let mut asked: BTreeSet = BTreeSet::new(); - for _ in 0..MAX_REACTOR_READ_ROUNDS { - let wanted: std::cell::RefCell> = Default::default(); - { - let read = |rel: &str| match texts.get(rel) { - Some(text) => Some(text.clone().into_bytes()), - None => { - // A pom only: what else the planner asks about (a - // module's `.mvn`, a module path that is a directory) - // does not change what the poms wire. - if rel.ends_with(".xml") && !asked.contains(rel) { - wanted.borrow_mut().insert(rel.to_string()); - } - None - } - }; - let list = |dir: &str| crate::patch::redirect::gradle::key_list(&texts, dir); - readable_for_hosted(&read, &list); - } - let wanted = wanted.into_inner(); - if wanted.is_empty() { - break; - } - for rel in wanted { - if let Some(text) = ctx.read_text(&rel, out).await { - texts.insert(rel.clone(), text); - } - asked.insert(rel); - } - } - texts -} - -/// The hosted pins of a reactor (`patch::redirect::plan_maven_reactor`): -/// read from every pom the reactor planner reads, since a pin sits in the -/// pom of the modules that select the patched version, a declaration is -/// rewritten where it stands, and a `${property}` version may be wired -/// through the property in another pom. The `` (in the local +/// The hosted pins of a reactor, or of a single pom that inherits from a +/// parent pom inside the checkout (the reactor planner's wiring, +/// `HostedReactor::plan`): read from every pom the planner reads, since a +/// pin sits in the pom of the modules that select the patched version, a +/// declaration is rewritten where it stands, and a `${property}` version +/// may be wired through the property in another pom. The `` (in the local /// root a wired pom inherits from) names the patch uuid; a pin's comment /// names it too, and any other suffixed version is tied to it by its /// 8-hex suffix, as in a single pom. @@ -604,23 +568,20 @@ async fn reactor_texts( /// remove undo each). The patch is attested only when every module that /// resolves the base version, or may, is reached by a pin or a declaration /// of the patch, and no declaration may still build the base version -/// ([`hosted_unattestable`](crate::vendor::jvm::maven_reactor::hosted_unattestable), +/// ([`HostedReactor::unattestable`](crate::vendor::jvm::maven_reactor::HostedReactor::unattestable), /// the rule vendored mode attests by). What Maven selects is read from the /// local Maven repository, on disk only: in memory, a module the wiring /// does not reach withholds the attestation. async fn extract_hosted_reactor( ctx: &DiscoverCtx<'_>, - root: &str, + (reactor, unread): (&crate::vendor::jvm::maven_reactor::HostedReactor, &[String]), + texts: &BTreeMap, config: Option<&str>, user_properties: &BTreeMap, root_hosted: &BTreeMap, out: &mut Discovery, -) -> Result<(), String> { +) { use crate::crawlers::maven_selection::MavenSelection; - use crate::vendor::jvm::maven_reactor::{hosted_sites, hosted_unattestable}; - let texts = reactor_texts(ctx, root, config, out).await; - let read = |rel: &str| texts.get(rel).map(|text| text.clone().into_bytes()); - let list = |dir: &str| crate::patch::redirect::gradle::key_list(&texts, dir); // uuid -> its repository's url, and the poms that declare it. let mut hosted: BTreeMap)> = root_hosted @@ -632,11 +593,11 @@ async fn extract_hosted_reactor( ) }) .collect(); - for (rel, text) in texts.iter().filter(|(rel, _)| rel.ends_with(".xml")) { - if rel == POM { - continue; - } - let Ok(pom) = parse_pom_with(text, user_properties) else { + for rel in reactor.scope().iter().filter(|rel| *rel != POM) { + let Some(Ok(pom)) = texts + .get(rel) + .map(|text| parse_pom_with(text, user_properties)) + else { continue; }; for repo in pom.repos.iter().filter(|repo| !repo.in_profile) { @@ -655,13 +616,7 @@ async fn extract_hosted_reactor( } } - let sites = hosted_sites(&read, &list).map_err(|refusal| { - refusal - .detail - .strip_prefix("reason: ") - .unwrap_or(&refusal.detail) - .to_string() - })?; + let sites = reactor.sites(); // uuid -> the (purl, g, a, suffixed version, poms) pins that tie to it. type Tie = (String, String, String, String, BTreeSet); let mut ties: BTreeMap> = BTreeMap::new(); @@ -816,14 +771,14 @@ async fn extract_hosted_reactor( version: base, uuid, }; - let why = match hosted_unattestable( - &read, - &list, - &coords, - selection.as_ref().expect("read above"), - ) { - Ok(why) => why, - Err(refusal) => Some(refusal.detail), + // A pom that could not be read may declare the base version + // itself, whatever the others are wired to. + let why = match unread.first() { + Some(first) => Some(format!( + "a pom of it cannot be read ({first}), so whether that module builds \ + {group}:{artifact} unpatched is not known" + )), + None => reactor.unattestable(&coords, selection.as_ref().expect("read above")), }; if let Some(why) = why { out.unattested( @@ -839,7 +794,6 @@ async fn extract_hosted_reactor( ); } } - Ok(()) } /// Whether the root pom itself declares `group:artifact`'s main jar among @@ -2426,6 +2380,68 @@ mod tests { assert!(out.unattested.is_empty(), "{:?}", out.unattested); } + /// A single pom that inherits from a parent pom inside the checkout + /// (no ``) may be wired through that parent: the property + /// the declaration reads, and the repository, sit in the parent's pom. + /// Both poms are read, and the parent is a file of the ref, so + /// rollback and remove undo it there. + #[tokio::test] + async fn hosted_wiring_in_a_parent_pom_of_the_checkout_is_found() { + let p = Project::new(); + p.write( + "pom.xml", + format!( + "\n4.0.0\n\n\ + com.example\nparent\n\ + 1.0.0\nparent/pom.xml\n\ + \napp\n\n{}\n\ + \n", + dep("org.slf4j", "slf4j-api", Some("${slf4j.version}")) + ), + ); + p.write( + "parent/pom.xml", + format!( + "\n4.0.0\ncom.example\n\ + parent\n1.0.0\n\ + pom\n\n{}\n\ + \n\n{}\n\n", + suffixed(UUID_A), + hosted_repo_a() + ), + ); + let out = run(&p).await; + assert_eq!(sources(&out), ["parent/pom.xml"]); + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert!(out.unattested.is_empty(), "{:?}", out.unattested); + } + + /// A reactor one of whose poms cannot be read is still read for the + /// pins of the others, which stay refs (rollback, remove and list find + /// them) and are not attested: the unread module may declare the base + /// version itself. + #[tokio::test] + async fn hosted_pins_of_a_reactor_with_an_unread_module_are_found_not_attested() { + let pin = format!( + "\n\n\n{}\n\n", + dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))) + ); + let p = Project::new(); + p.write("pom.xml", reactor_root("")); + p.write("a/pom.xml", reactor_module("a", &pin)); + // (b is listed and missing.) + let out = run(&p).await; + assert_eq!(sources(&out), ["a/pom.xml", "pom.xml"]); + assert_eq!(out.unattested.len(), 1, "{:?}", out.unattested); + assert_eq!(out.unattested[0].kind, UnattestedKind::MavenReactorRoot); + assert!( + out.unattested[0].detail.contains("b"), + "{}", + out.unattested[0].detail + ); + } + /// #1809: a Maven 4 (model 4.1.0) `pom`-packaged root listing no /// subprojects builds every direct subdirectory holding a `pom.xml`, /// so its hosted pin is a reactor's: attested while the root's pin diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index 03d16c5cd..4887481e8 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -2303,6 +2303,20 @@ impl<'a> DiscoverCtx<'a> { self.ignored.contains(&rel) } + /// [`Self::read_text`] for a path that may be no file at all (one the + /// Maven reactor reader asks about: a module named by its directory, a + /// module's `.mvn` file): missing or unreadable, it is `None` with no + /// diagnostic. What is read is recognized and logged all the same. + pub(crate) async fn read_text_quiet(&self, rel: &str) -> Option { + if self.is_ignored(rel) { + return None; + } + let text = self.view.read_text(rel).await.ok()?; + self.log_read(rel, true); + self.recognize_text(rel, &text); + Some(text) + } + /// Guarded UTF-8 read of root-relative `rel`: `None` when missing /// (silent) or unreadable ([`DIAG_LOCKFILE_UNREADABLE`] recorded). The /// content is swept for the Socket identities it mentions BEFORE any From 56ae4eecc90ed8d041be4ed8faaf6e214c29bc8a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 06:16:31 -0500 Subject: [PATCH 16/18] Test the hosted Maven invariant against real Maven, and document it Three more capstones on the hosted suite: - a reactor whose only declaration of the version sits in a module's profile: the scan exits 0, says why, writes nothing, and the build with that profile resolves what it did; - a single pom whose version is a property a parent pom of the checkout defines: the property and the repository are written in the parent, Maven resolves the patched jar, and a rollback restores both poms byte for byte; - a newer patch superseding an earlier one while a module still reads the earlier version through a property a profile may redefine: the earlier patch keeps its repository and checksum lines, and Maven resolves each module from the repository of the patch its pom names. The CLI contract and the ecosystem guide state the rule a hosted plan is held to (written whole or not at all), what refuses a plan and under which code, what a later scan removes with the last pin, how rollback and remove read a reactor, and how a single pom is read with a parent pom of the checkout. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 61 +++- .../tests/e2e_redirect_maven_build.rs | 342 ++++++++++++++++++ .../tests/maven_mediation_common/mod.rs | 39 +- docs/ecosystems.md | 19 +- 4 files changed, 431 insertions(+), 30 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index e7d70e404..75e7b9ebd 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2106,7 +2106,7 @@ command's integration tests check its output. | `redirect_maven_selection_undetermined` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): what the build selects for the artifact cannot be read and `pom.xml` declares no version of it to replace, so no `` pin is written on a guess. `pom.xml` and `.mvn/` stay byte-identical; the detail carries the reason and the remedy (resolve the project once and re-run, or declare the artifact at the base version). In a reactor it names the first module whose selection cannot be read and counts the rest: those modules get no new pin, while the modules that are certain are still pinned and a declaration that names the base version is still rewritten, so the dep may be counted as redirected beside this warning. | | `redirect_maven_multimodule_unsupported` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the root `pom.xml` heads a reactor that cannot be planned: a module pom is missing or not readable as a pom, a `` path is a property or leaves the project, or the grant serves the patched artifact under its original version (a same-GAV grant). The detail carries the reason. The poms and `.mvn/` stay byte-identical and the dep is not counted as redirected. A reactor that can be read is patched module by module: see [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). | | `redirect_maven_pin_would_move_module` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven reactor): a parent pom resolves the base version itself above a module that resolves another version, so the parent takes no pin (Maven's management always reaches the children); the modules below it that select the base version are pinned. Also reported when a pin an earlier run wrote is taken out because a module it reaches now resolves another version, which the pin would hold back (the `redirect_maven_dep_management` edit has `action: "removed"`). Exit 0. | -| `redirect_maven_edit_not_reversible` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): a pom would take an edit that `rollback` could not undo byte for byte from the pom alone (a pin in a `` that holds no entry, which would be left changed or removed). That pom is left as it is; the modules it would have wired stay unpatched, and `vex` withholds the statement while one of them resolves the base version. Exit 0. | +| `redirect_maven_edit_not_reversible` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): a pom would take an edit that `rollback` could not undo byte for byte from the pom alone. A pin in a `` that holds no entry (which would be left changed or removed) leaves that one pom as it is: the modules it would have wired stay unpatched, and `vex` withholds the statement while one of them resolves the base version. Any other case (a `` section that would not come back as it was) refuses the whole plan for the patch: nothing is written and the dep is not counted as redirected. Exit 0. See [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). | | `redirect_gem_no_checksums_section` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock has no `CHECKSUMS` section (Bundler < 2.6 does not write one), so it cannot record the sha256 of the patched gems. They are redirected all the same (manifest and lock converged, frozen installs accept the pair) and pinned by source alone. Reported once per run, naming the gems; relock with Bundler ≥ 2.6 (`bundle lock --add-checksums`) and re-run to pin the checksums too. | | `redirect_gem_merged_lock_layout` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock was written by Bundler < 2.2 (`BUNDLED WITH`), which lists every gem source in ONE `GEM` section, so this run added the patch registry to that section's `remote:` lines. The pair installs with that Bundler, frozen / deployment mode included. Newer Bundlers deprecate such a section and from 2.5 on refuse the pair under frozen / deployment mode: if a newer Bundler installs the project, run `bundle lock` with it, commit the lock and re-run the hosted scan. Raised only by a run that wrote the lock. | | `redirect_gem_unrecognized_declaration` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the gem's declaration cannot take a `source:` option in place (the detail gives the reason). The gem is skipped and the manifest and lock stay byte-identical for it; write the declaration as one `gem "", …` call with literal arguments on a line of its own, or use `--mode vendored` / `--mode agent`. | @@ -2835,12 +2835,55 @@ can undo exactly from the pom: No ledger records these edits. Each says what it replaced by its own text: the base version is the suffix's prefix, a pin is its commented entry (and the section that held nothing else), a recorded declaration carries its comment. -The planner undoes every pom it would change before it writes anything, and -leaves a pom alone when that does not give back the text it had -(`redirect_maven_edit_not_reversible`). `rollback` and `remove` undo the wiring -in every pom `list` finds it in, or in none: each pom returns to its bytes -before the scan, the `` goes from whichever pom declares it, and -the `.mvn/` lines and files hosted mode wrote are removed. + +**A plan is written whole or not at all.** For each patch the planner plans the +declarations, the property, the pins and the `` together, then +holds the result to one rule before any file is written: + +- no pom names the patched version unless the `` that serves it is + declared in that pom's local root, and a declaration Maven always reads + resolves to it, so `list`, `vex`, `rollback` and `remove` find the patch and + every pom that carries part of it; +- `rollback`, run over the text about to be written, returns every pom the plan + is the first to wire to the bytes it has now. + +A plan that cannot keep the rule writes nothing, and the warning says why: + +- the only declaration of the version sits inside `` + (`redirect_maven_profile_dependency_unpatched`): Maven reads it only while + that profile is active, so nothing would be certain to resolve the patched + version and no rollback would find the edit. Beside a declaration Maven + always reads, a profile's one is rewritten with it; +- the pom that must declare the repository cannot take it + (`redirect_maven_pom_unreadable`); +- a pom could not be put back exactly, for instance a self-closed + `` that would be expanded + (`redirect_maven_edit_not_reversible`). A pin in a `` + that holds no entry is the one case handled pom by pom: that pom is left as + it is under the same code, and the rest of the plan stands. + +The same rule holds for what a later scan takes away. When the last pin of a +patch goes (`redirect_maven_pin_would_move_module`: the module it reached now +resolves another version) and no pom names the patched version any more, its +`` is removed (`redirect_maven_repository`, `action: "removed"`) +and its lines leave `.mvn/checksums/checksums.sha256`. An earlier patch's +repository and checksum lines go only once no pom of the reactor names that +patch's version, whether or not the scan changed that pom. + +`rollback` and `remove` read the reactor themselves and undo a patch in every +pom that carries part of it, whatever `list` showed, or in none: each pom +returns to its bytes before the scan, the `` goes from whichever +pom declares it, and the `.mvn/` lines and files hosted mode wrote are removed. +A pom that still names the patched version and can no longer be read as a pom +refuses the patch, with nothing changed. + +A reactor is read once per run, each pom fetched and parsed once, however many +modules it has. A module pom that is a symbolic link, or that cannot be read as +text, counts as missing: the reactor is then refused +(`redirect_maven_multimodule_unsupported`), never the run. A single pom that +inherits from a parent pom inside the checkout is read with that parent: a +property the parent defines is rewritten there, and the repository goes in the +parent the pom inherits it from. A later scan keeps every pin where an earlier one wrote it, so a second scan changes nothing. It adds a pin only for a module that nothing reaches yet and @@ -2857,7 +2900,9 @@ module that resolves the base version, or may, is reached by a pin or a declaration of the patch, and no declaration may still build the base version. Otherwise the statement is withheld and the module named (`vex_maven_reactor_root`). What each module selects is read from the Maven -local repository of the machine that runs `vex`. +local repository of the machine that runs `vex`. A reactor one of whose poms +cannot be read is read for the pins of the others: they are listed and can be +rolled back, and none is attested. A hosted pin an earlier release wrote in a single pom carries no comment. It is still found, rolled back and removed as before. When that pom has since diff --git a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs index f1567d895..68ab5b11a 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs @@ -1115,4 +1115,346 @@ mod mediation { "rollback restores every pom byte for byte and removes what the scan created" ); } + + /// A declaration Maven reads only while a profile is active is not + /// rewritten on its own: the scan would leave a version with no + /// repository to serve it, which a build with that profile could not + /// resolve and no rollback could find. The scan exits 0, says why, and + /// writes nothing; the build with the profile resolves what it did. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_leaves_a_declaration_only_a_profile_holds() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let bench = Bench::new(); + let proj = bench.root.join("profile-only"); + std::fs::create_dir_all(proj.join("a")).unwrap(); + std::fs::create_dir_all(proj.join("b")).unwrap(); + std::fs::write( + proj.join("pom.xml"), + fixture::reactor_root_pom(&["a", "b"], &bench.server), + ) + .unwrap(); + let profiled = fixture::module_pom("a", "lib-old", "1.0").replace( + "", + &format!( + " \n \n with-victim\n \ + \n{} \n \n \n", + fixture::dependency(fixture::VICTIM, fixture::BASE, "") + ), + ); + std::fs::write(proj.join("a/pom.xml"), profiled).unwrap(); + std::fs::write( + proj.join("b/pom.xml"), + fixture::module_pom("b", "lib-new", "1.0"), + ) + .unwrap(); + // Warm the local repository (the dependency plugin, and the base + // version the profile brings in). + if fixture::resolve( + SUITE, + &mvn, + &proj.join("b"), + &bench.m2, + &bench.plain, + "target/warm", + ) + .is_none() + { + return; + } + let with_profile = |out: &str| { + fixture::resolve_warm( + &mvn, + &proj.join("a"), + &bench.m2, + &bench.plain, + out, + &["-Pwith-victim"], + ) + }; + let before = with_profile("target/before"); + assert!( + before.contains_key(&fixture::victim_jar_name(fixture::BASE)), + "{:?}", + before.keys() + ); + let pristine = fixture::snapshot(&proj); + + let (code, env, stderr) = bench.scan(&proj); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "the scan writes nothing: {env}" + ); + assert!( + warning(&env, "redirect_maven_profile_dependency_unpatched").is_some(), + "the scan says why: {env}" + ); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + assert_eq!( + with_profile("target/after"), + before, + "the profile's build resolves what it did" + ); + } + + /// A single pom that inherits from a parent pom inside the checkout + /// (no ``), its version a property that parent defines: the + /// property and the repository are written in the parent's pom, where + /// `rollback` finds them. Maven resolves the patched jar, and the + /// rollback restores both poms byte for byte. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_patches_through_a_parent_pom_of_the_checkout() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let bench = Bench::new(); + let suffixed = &bench.suffixed; + let proj = bench.root.join("local-parent"); + std::fs::create_dir_all(proj.join("parent")).unwrap(); + let property = format!( + " \n {}\n \n", + fixture::BASE + ); + let child = fixture::property_pom(fixture::Property::Own, &bench.server) + .replace(&property, "") + .replace( + " com.example\n", + " \n com.example\n \ + base\n 1.0.0\n \ + parent/pom.xml\n \n \ + com.example\n", + ); + assert!(!child.contains(""), "{child}"); + std::fs::write(proj.join("pom.xml"), &child).unwrap(); + std::fs::write( + proj.join("parent/pom.xml"), + format!( + "\n\ + \n \ + 4.0.0\n com.example\n \ + base\n 1.0.0\n \ + pom\n{property}\n" + ), + ) + .unwrap(); + let Some(before) = + fixture::resolve(SUITE, &mvn, &proj, &bench.m2, &bench.plain, "target/before") + else { + return; + }; + let pristine = fixture::snapshot(&proj); + + let (code, env, stderr) = bench.scan(&proj); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + let parent = std::fs::read_to_string(proj.join("parent/pom.xml")).unwrap(); + assert!( + parent.contains(&format!("{suffixed}")) + && parent.contains(&format!("socket-patch-{UUID}")), + "the parent takes the property and the repository:\n{parent}" + ); + assert_eq!( + std::fs::read_to_string(proj.join("pom.xml")).unwrap(), + child, + "the pom that declares it keeps its text" + ); + let after = + fixture::resolve_warm(&mvn, &proj, &bench.m2, &bench.mirrored, "target/after", &[]); + bench.assert_only_the_victim_is_patched("a local parent", &before, &after); + bench.assert_rescan_is_a_no_op(&proj); + + bench.rollback(&proj); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "rollback restores both poms byte for byte and leaves no file behind" + ); + } + + /// A newer patch of the same version takes the place of an earlier + /// one only where the poms let it. A module that still reads the + /// earlier patch's version (through a property a profile may redefine, + /// which no scan rewrites) keeps resolving it: the earlier patch's + /// repository and checksum lines stay for as long as any pom of the + /// reactor names it, so Maven resolves both modules. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_keeps_an_earlier_patch_served_while_a_module_names_it() { + const NEWER_UUID: &str = "8192a3b4-c5d6-4e7f-8a9b-0c1d2e3f4a5b"; + const NEWER: Hosted = Hosted { + org: ORG, + uuid: NEWER_UUID, + hex8: "8192a3b4", + token: "44444444-5555-4666-8777-888888888888", + ghsa: "GHSA-mediation-maven-newer", + cve: "CVE-2026-7204", + group: fixture::GROUP, + artifact: fixture::VICTIM, + version: fixture::BASE, + title: "maven mediation capstone, superseding", + }; + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let bench = Bench::new(); + let earlier = &bench.suffixed; + let proj = bench.root.join("superseded"); + std::fs::create_dir_all(proj.join("a")).unwrap(); + std::fs::create_dir_all(proj.join("b")).unwrap(); + std::fs::write( + proj.join("pom.xml"), + fixture::reactor_root_pom(&["a", "b"], &bench.server), + ) + .unwrap(); + std::fs::write( + proj.join("a/pom.xml"), + fixture::module_pom("a", "lib-deep", "1.0"), + ) + .unwrap(); + let b = fixture::module_pom("b", fixture::VICTIM, "${victim.version}").replace( + " \n", + &format!( + " \n {}\n \n \ + \n", + fixture::BASE + ), + ); + std::fs::write(proj.join("b/pom.xml"), b).unwrap(); + let resolve_module = |module: &str, settings: &Path, out: &str| { + fixture::resolve_warm(&mvn, &proj.join(module), &bench.m2, settings, out, &[]) + }; + if fixture::resolve( + SUITE, + &mvn, + &proj.join("a"), + &bench.m2, + &bench.plain, + "target/before", + ) + .is_none() + { + return; + } + resolve_module("b", &bench.plain, "target/before"); + + // The earlier patch: both modules resolve its build. + let (code, env, stderr) = bench.scan(&proj); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + let read = |rel: &str| std::fs::read_to_string(proj.join(rel)).unwrap(); + assert!( + read("b/pom.xml").contains(&format!("{earlier}")), + "{}", + read("b/pom.xml") + ); + for module in ["a", "b"] { + let jars = resolve_module(module, &bench.mirrored, "target/earlier"); + assert!( + jars.contains_key(&fixture::victim_jar_name(earlier)), + "{module}: {:?}", + jars.keys() + ); + } + // b's property comes to be redefined by a profile: from here on no + // scan may rewrite it, since that profile's build keeps its own. + let profiled = read("b/pom.xml").replace( + "", + &format!( + " \n \n older\n \n \ + {}\n \n \n \ + \n", + fixture::OLDER + ), + ); + std::fs::write(proj.join("b/pom.xml"), &profiled).unwrap(); + + // The newer patch, from its own server. + let server = Server::start(); + let patched_jar = fixture::patched_victim_jar(); + let newer = NEWER.suffixed(); + let served_pom = fixture::served_victim_pom(&newer).into_bytes(); + let view = patch_view( + NEWER_UUID, + &fixture::purl(), + &[( + &fixture::victim_jar_name(fixture::BASE), + &git_sha256(&patched_jar), + )], + &[(NEWER.ghsa, &[NEWER.cve])], + ); + hosted_maven_common::mount_api(&server, &NEWER, &patched_jar, &served_pom, &view); + fixture::answer_lookups_only_for(&server, ORG, &fixture::purl()["pkg:maven/".len()..]); + server.serve_repo(&NEWER, &patched_jar, &served_pom, None); + let (code, env, stderr) = socket( + &proj, + &bench.m2, + &[ + "scan", + "--mode", + "hosted", + "--json", + "--yes", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + &server.uri(), + "--org", + ORG, + "--api-token", + "fake", + ], + ); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(read("b/pom.xml"), profiled, "b is left as it is: {env}"); + assert!( + read("a/pom.xml").contains(&newer) || read("pom.xml").contains(&newer), + "a moves to the newer patch: {env}" + ); + let root = read("pom.xml"); + assert!( + root.contains(&format!("socket-patch-{UUID}")) + && root.contains(&format!("socket-patch-{NEWER_UUID}")), + "both patches are still served: {root}" + ); + let sums = read(".mvn/checksums/checksums.sha256"); + assert!( + sums.contains(earlier.as_str()) && sums.contains(&newer), + "both patches keep their checksum lines:\n{sums}" + ); + + // Maven resolves both modules, each from the repository of the + // patch its pom names; the earlier one is fetched afresh. + let _ = std::fs::remove_dir_all(fixture::victim_dir(&bench.m2, earlier)); + let both = bench.root.join("settings-both.xml"); + write_settings( + &both, + &[ + ( + &format!("socket-patch-{UUID}"), + &format!("{}{}", bench.server.uri(), PATCH.repo_path()), + ), + ( + &format!("socket-patch-{NEWER_UUID}"), + &format!("{}{}", server.uri(), NEWER.repo_path()), + ), + ], + ); + let a = resolve_module("a", &both, "target/newer"); + assert!( + a.contains_key(&fixture::victim_jar_name(&newer)), + "a builds the newer patch: {:?}", + a.keys() + ); + let b = resolve_module("b", &both, "target/newer"); + assert!( + b.contains_key(&fixture::victim_jar_name(earlier)), + "b still builds the earlier patch, from its repository: {:?}", + b.keys() + ); + } } diff --git a/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs index 553c55324..e235c13d1 100644 --- a/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs +++ b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs @@ -320,30 +320,33 @@ pub fn module_pom(name: &str, artifact: &str, version: &str) -> String { ) } +/// The root pom `com.example:parent:1.0.0` of a reactor over `modules`, +/// which every [`module_pom`] inherits: it names the fixture repository. +pub fn reactor_root_pom(modules: &[&str], server: &Server) -> String { + let modules: String = modules + .iter() + .map(|name| format!(" {name}\n")) + .collect(); + format!( + "\n\ + \n \ + 4.0.0\n com.example\n \ + parent\n 1.0.0\n \ + pom\n \n{modules} \n \ + \n \n fixture\n \ + {}{REPO_ROUTE}\n \n \n\n", + server.uri() + ) +} + /// Write a reactor into `dir` (the table's V3): a parent pom that three /// modules inherit, `a` reaching the base version two levels down, `b` a /// newer version through another artifact, `c` declaring the base version /// itself. pub fn write_reactor(dir: &Path, server: &Server) { - let modules: String = REACTOR_MODULES - .iter() - .map(|(name, ..)| format!(" {name}\n")) - .collect(); + let names: Vec<&str> = REACTOR_MODULES.iter().map(|(name, ..)| *name).collect(); std::fs::create_dir_all(dir).unwrap(); - std::fs::write( - dir.join("pom.xml"), - format!( - "\n\ - \n \ - 4.0.0\n com.example\n \ - parent\n 1.0.0\n \ - pom\n \n{modules} \n \ - \n \n fixture\n \ - {}{REPO_ROUTE}\n \n \n\n", - server.uri() - ), - ) - .unwrap(); + std::fs::write(dir.join("pom.xml"), reactor_root_pom(&names, server)).unwrap(); for (name, _, artifact, version) in REACTOR_MODULES { std::fs::create_dir_all(dir.join(name)).unwrap(); std::fs::write( diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 6b99584a3..c965cdba4 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -928,11 +928,19 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: started in a module directory or with `-f`; a module with a `.mvn` of its own is reported (`redirect_maven_trusted_checksums_unenforced`), since a Maven started there reads that one. A reactor one of whose poms cannot be read is left untouched - (`redirect_maven_multimodule_unsupported`, with the reason). `vex` attests the patch + (`redirect_maven_multimodule_unsupported`, with the reason). The plan for a patch is + written whole or not at all: a pom is never left naming a patched version without the + repository that serves it, its checksum lines, and wiring a rollback can find. So a + declaration only a `` holds is not rewritten on its own + (`redirect_maven_profile_dependency_unpatched`), and neither is anything when the pom + that must take the repository cannot (`redirect_maven_pom_unreadable`), or when a + rollback could not put a pom back exactly (`redirect_maven_edit_not_reversible`). When + a later scan takes out the last pin of a patch (the module it reached moved to another + version), the repository and the checksum lines go with it. `vex` attests the patch only when every module that resolves the patched version, or may, is reached by a pin or a declaration; otherwise it withholds the statement and names the module - (`vex_maven_reactor_root`). `rollback` and `remove` undo the wiring in every pom and - restore each byte for byte. + (`vex_maven_reactor_root`). `rollback` and `remove` undo the wiring in every pom that + carries part of it, or in none, and restore each byte for byte. * **Property versions (hosted Maven).** A declaration whose `` is a `${property}` is patched in one of two ways, and neither moves another artifact. When the reactor's own poms define the property once and nothing but declarations of the @@ -949,7 +957,10 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: declaration; when that cannot be told (the parent pom is not in the local Maven repository yet) the declaration is left as it is (`redirect_maven_dep_unpinned`). A version-less declaration a parent or BOM manages needs no edit of its own: the - `` pin overrides the management. + `` pin overrides the management. A single pom that inherits + from a parent pom inside the checkout is read together with it: a property that parent + defines is rewritten there, and the repository goes in the parent the pom inherits it + from; `list`, `vex`, `rollback` and `remove` read both poms. * **A parent pom can override a managed pin (hosted Maven).** For a dependency with no literal `` in the root pom (a transitive one, or one whose version a parent manages), hosted mode pins it in the root pom's `` From 7e1f39cd44e835d3b633e8266f34e05b84310808 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 06:47:02 -0500 Subject: [PATCH 17/18] test(maven): pin the hosted property and reactor rewrites in the golden fixtures The shared `redirect/maven/pom` golden still expected a `${property}` version to be left alone (`property-version-warn`: no file, no edit), which the hosted rewriter no longer does, so `redirect_golden_fixtures_match` failed in CI. Only `--lib` and the CLI suites had been run before the push; this time every core test target was. Each expectation below was written from the behaviour the change intends, then compared with what the rewriter does; none was regenerated unread. - `property-version-warn` becomes `property-version`: a property that is defined once and read only by the patched artifact takes the suffixed version as its value, the pom gets the repository, and nothing warns. - `property-shared-sibling` (new): a second artifact reads the property, so the property stays and the declaration takes the literal with the `` comment that rollback reads. - `property-external-parent-warn` (new): no pom of the checkout defines the property and nothing says what Maven selects, so nothing is written (`redirect_maven_dep_unpinned`, `redirect_maven_selection_undetermined`). - `profile-property-warn` (new): only a profile declares the artifact, so the plan is refused whole (`redirect_maven_profile_dependency_unpatched`). - `reactor-module-literal`, `reactor-root-property` (new): a reactor with no selection to read; the declaration or the root's property is rewritten, the repository goes in the root, no pin is placed, and the run says so (`redirect_maven_selection_undetermined`). - `parent-in-checkout` (new): a single pom whose parent is in the checkout and holds the property; both edits land in the parent pom. The five that write files also run through `maven_goldens_round_trip` (discovery, then restore, byte for byte), and every side of every case has its entry in the discovery golden, whose only other change is the renamed key. The other nineteen `maven/pom` cases pass unchanged. depscan reads the same fixtures (`golden.test.ts`); the PR description lists the seven for its `TS_LAGGING`. Co-Authored-By: Claude Fable 5.2 --- .../src/vex/discover/maven.rs | 2 +- .../parent-in-checkout/expected-edits.json | 31 +++ .../expected-warnings.json} | 0 .../expected/.mvn/checksums/checksums.sha256 | 2 + .../expected/.mvn/maven.config | 6 + .../expected/build-parent/pom.xml | 26 +++ .../input/build-parent/pom.xml | 13 ++ .../pom/parent-in-checkout/input/pom.xml | 21 ++ .../overrides.json | 0 .../profile-property-warn/expected-edits.json | 1 + .../expected-warnings.json | 3 + .../pom/profile-property-warn/input/pom.xml | 25 ++ .../pom/profile-property-warn/overrides.json | 28 +++ .../expected-edits.json | 1 + .../expected-warnings.json | 4 + .../input/pom.xml | 22 ++ .../overrides.json | 28 +++ .../expected-edits.json | 31 +++ .../expected-warnings.json | 1 + .../expected/.mvn/checksums/checksums.sha256 | 2 + .../expected/.mvn/maven.config | 6 + .../property-shared-sibling/expected/pom.xml | 38 +++ .../pom/property-shared-sibling/input/pom.xml | 25 ++ .../property-shared-sibling/overrides.json | 28 +++ .../pom/property-version/expected-edits.json | 31 +++ .../property-version/expected-warnings.json | 1 + .../expected/.mvn/checksums/checksums.sha256 | 2 + .../expected/.mvn/maven.config | 6 + .../pom/property-version/expected/pom.xml | 33 +++ .../input/pom.xml | 0 .../maven/pom/property-version/overrides.json | 28 +++ .../expected-edits.json | 31 +++ .../expected-warnings.json | 3 + .../expected/.mvn/checksums/checksums.sha256 | 2 + .../expected/.mvn/maven.config | 6 + .../expected/app/pom.xml | 19 ++ .../reactor-module-literal/expected/pom.xml | 27 +++ .../reactor-module-literal/input/app/pom.xml | 19 ++ .../reactor-module-literal/input/lib/pom.xml | 12 + .../pom/reactor-module-literal/input/pom.xml | 14 ++ .../pom/reactor-module-literal/overrides.json | 28 +++ .../reactor-root-property/expected-edits.json | 31 +++ .../expected-warnings.json | 3 + .../expected/.mvn/checksums/checksums.sha256 | 2 + .../expected/.mvn/maven.config | 6 + .../reactor-root-property/expected/pom.xml | 29 +++ .../reactor-root-property/input/app/pom.xml | 19 ++ .../pom/reactor-root-property/input/pom.xml | 16 ++ .../pom/reactor-root-property/overrides.json | 28 +++ .../vex-discover-golden/redirect-maven.json | 219 +++++++++++++++++- 50 files changed, 957 insertions(+), 2 deletions(-) create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-edits.json rename crates/socket-patch-core/tests/fixtures/redirect/maven/pom/{property-version-warn/expected-edits.json => parent-in-checkout/expected-warnings.json} (100%) create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/checksums/checksums.sha256 create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/maven.config create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/build-parent/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/build-parent/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/pom.xml rename crates/socket-patch-core/tests/fixtures/redirect/maven/pom/{property-version-warn => parent-in-checkout}/overrides.json (100%) create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-edits.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-warnings.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/input/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/overrides.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-edits.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-warnings.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/input/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/overrides.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-edits.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-warnings.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/checksums/checksums.sha256 create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/maven.config create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/input/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/overrides.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-edits.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-warnings.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/checksums/checksums.sha256 create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/maven.config create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/pom.xml rename crates/socket-patch-core/tests/fixtures/redirect/maven/pom/{property-version-warn => property-version}/input/pom.xml (100%) create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/overrides.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-edits.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-warnings.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/checksums/checksums.sha256 create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/maven.config create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/app/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/app/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/lib/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/overrides.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-edits.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-warnings.json create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/checksums/checksums.sha256 create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/maven.config create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/app/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/pom.xml create mode 100644 crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/overrides.json diff --git a/crates/socket-patch-core/src/vex/discover/maven.rs b/crates/socket-patch-core/src/vex/discover/maven.rs index ba1737c37..9bc2a9c48 100644 --- a/crates/socket-patch-core/src/vex/discover/maven.rs +++ b/crates/socket-patch-core/src/vex/discover/maven.rs @@ -2107,7 +2107,7 @@ mod tests { async fn unwired_rewriter_inputs_yield_nothing() { for case in [ "basic", - "property-version-warn", + "property-version", "version-mismatch-skip", "transitive-depmgmt", ] { diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-edits.json new file mode 100644 index 000000000..81f6e0173 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "build-parent/pom.xml", + "kind": "redirect_maven_property", + "action": "rewritten", + "key": "slf4j.version", + "original": "1.7.36", + "new": "1.7.36-socket.77777777" + }, + { + "path": "build-parent/pom.xml", + "kind": "redirect_maven_repository", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": { + "id": "socket-patch-77777777-7777-7777-7777-777777777777", + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2" + } + }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "trustedChecksums" + }, + { + "path": ".mvn/checksums/checksums.sha256", + "kind": "redirect_maven_trusted_checksums", + "action": "added" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-warnings.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/expected-edits.json rename to crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-warnings.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 000000000..71c583f77 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/checksums/checksums.sha256 @@ -0,0 +1,2 @@ +cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar +dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.pom diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/maven.config new file mode 100644 index 000000000..d3b91570d --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/build-parent/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/build-parent/pom.xml new file mode 100644 index 000000000..0b02b2f63 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/build-parent/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + dev.socket.test + build-parent + 1.0.0 + pom + + 1.7.36-socket.77777777 + + + + socket-patch-77777777-7777-7777-7777-777777777777 + https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2 + + true + fail + + + false + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/build-parent/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/build-parent/pom.xml new file mode 100644 index 000000000..582515471 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/build-parent/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + dev.socket.test + build-parent + 1.0.0 + pom + + 1.7.36 + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/pom.xml new file mode 100644 index 000000000..e54544a89 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + + dev.socket.test + build-parent + 1.0.0 + build-parent/pom.xml + + consumer + jar + + + org.slf4j + slf4j-api + ${slf4j.version} + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/overrides.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/overrides.json rename to crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/overrides.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-edits.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-edits.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-warnings.json new file mode 100644 index 000000000..3b7af7dfa --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-warnings.json @@ -0,0 +1,3 @@ +[ + "redirect_maven_profile_dependency_unpatched" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/input/pom.xml new file mode 100644 index 000000000..94d303f0e --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/input/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + 1.7.36 + + + + slf4j-direct + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/overrides.json new file mode 100644 index 000000000..53deb25b8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-edits.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-edits.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-warnings.json new file mode 100644 index 000000000..d99973767 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-warnings.json @@ -0,0 +1,4 @@ +[ + "redirect_maven_dep_unpinned", + "redirect_maven_selection_undetermined" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/input/pom.xml new file mode 100644 index 000000000..47b1f18f5 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/input/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + dev.socket.test + company-parent + 7 + + + consumer + 1.0.0 + jar + + + org.slf4j + slf4j-api + ${slf4j.version} + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/overrides.json new file mode 100644 index 000000000..53deb25b8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-edits.json new file mode 100644 index 000000000..1233a9a57 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "pom.xml", + "kind": "redirect_maven_dep_version", + "action": "rewritten", + "key": "org.slf4j:slf4j-api", + "original": "${slf4j.version}", + "new": "1.7.36-socket.77777777" + }, + { + "path": "pom.xml", + "kind": "redirect_maven_repository", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": { + "id": "socket-patch-77777777-7777-7777-7777-777777777777", + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2" + } + }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "trustedChecksums" + }, + { + "path": ".mvn/checksums/checksums.sha256", + "kind": "redirect_maven_trusted_checksums", + "action": "added" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-warnings.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-warnings.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 000000000..71c583f77 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/checksums/checksums.sha256 @@ -0,0 +1,2 @@ +cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar +dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.pom diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/maven.config new file mode 100644 index 000000000..d3b91570d --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/pom.xml new file mode 100644 index 000000000..fa05615f7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + 1.7.36 + + + + org.slf4j + slf4j-api + 1.7.36-socket.77777777 + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + + + socket-patch-77777777-7777-7777-7777-777777777777 + https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2 + + true + fail + + + false + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/input/pom.xml new file mode 100644 index 000000000..1efaf2e40 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/input/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + 1.7.36 + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/overrides.json new file mode 100644 index 000000000..53deb25b8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-edits.json new file mode 100644 index 000000000..6e5939b9a --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "pom.xml", + "kind": "redirect_maven_property", + "action": "rewritten", + "key": "slf4j.version", + "original": "1.7.36", + "new": "1.7.36-socket.77777777" + }, + { + "path": "pom.xml", + "kind": "redirect_maven_repository", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": { + "id": "socket-patch-77777777-7777-7777-7777-777777777777", + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2" + } + }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "trustedChecksums" + }, + { + "path": ".mvn/checksums/checksums.sha256", + "kind": "redirect_maven_trusted_checksums", + "action": "added" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-warnings.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-warnings.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 000000000..71c583f77 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/checksums/checksums.sha256 @@ -0,0 +1,2 @@ +cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar +dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.pom diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/maven.config new file mode 100644 index 000000000..d3b91570d --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/pom.xml new file mode 100644 index 000000000..a5a6942dc --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + 1.7.36-socket.77777777 + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + + socket-patch-77777777-7777-7777-7777-777777777777 + https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2 + + true + fail + + + false + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/input/pom.xml similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/input/pom.xml rename to crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/input/pom.xml diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/overrides.json new file mode 100644 index 000000000..53deb25b8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-edits.json new file mode 100644 index 000000000..791f6cc83 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "app/pom.xml", + "kind": "redirect_maven_dep_version", + "action": "rewritten", + "key": "org.slf4j:slf4j-api", + "original": "1.7.36", + "new": "1.7.36-socket.77777777" + }, + { + "path": "pom.xml", + "kind": "redirect_maven_repository", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": { + "id": "socket-patch-77777777-7777-7777-7777-777777777777", + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2" + } + }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "trustedChecksums" + }, + { + "path": ".mvn/checksums/checksums.sha256", + "kind": "redirect_maven_trusted_checksums", + "action": "added" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-warnings.json new file mode 100644 index 000000000..44c9e80ea --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-warnings.json @@ -0,0 +1,3 @@ +[ + "redirect_maven_selection_undetermined" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 000000000..71c583f77 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/checksums/checksums.sha256 @@ -0,0 +1,2 @@ +cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar +dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.pom diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/maven.config new file mode 100644 index 000000000..d3b91570d --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/app/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/app/pom.xml new file mode 100644 index 000000000..38ddc0f43 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/app/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + dev.socket.test + reactor + 1.0.0 + + app + + + org.slf4j + slf4j-api + 1.7.36-socket.77777777 + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/pom.xml new file mode 100644 index 000000000..15a36eec4 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + dev.socket.test + reactor + 1.0.0 + pom + + app + lib + + + + socket-patch-77777777-7777-7777-7777-777777777777 + https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2 + + true + fail + + + false + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/app/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/app/pom.xml new file mode 100644 index 000000000..6384d6c60 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/app/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + dev.socket.test + reactor + 1.0.0 + + app + + + org.slf4j + slf4j-api + 1.7.36 + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/lib/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/lib/pom.xml new file mode 100644 index 000000000..9ea023c12 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/lib/pom.xml @@ -0,0 +1,12 @@ + + + 4.0.0 + + dev.socket.test + reactor + 1.0.0 + + lib + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/pom.xml new file mode 100644 index 000000000..da6f2b6e2 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + dev.socket.test + reactor + 1.0.0 + pom + + app + lib + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/overrides.json new file mode 100644 index 000000000..53deb25b8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-edits.json new file mode 100644 index 000000000..6e5939b9a --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "pom.xml", + "kind": "redirect_maven_property", + "action": "rewritten", + "key": "slf4j.version", + "original": "1.7.36", + "new": "1.7.36-socket.77777777" + }, + { + "path": "pom.xml", + "kind": "redirect_maven_repository", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": { + "id": "socket-patch-77777777-7777-7777-7777-777777777777", + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2" + } + }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "trustedChecksums" + }, + { + "path": ".mvn/checksums/checksums.sha256", + "kind": "redirect_maven_trusted_checksums", + "action": "added" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-warnings.json new file mode 100644 index 000000000..44c9e80ea --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-warnings.json @@ -0,0 +1,3 @@ +[ + "redirect_maven_selection_undetermined" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 000000000..71c583f77 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/checksums/checksums.sha256 @@ -0,0 +1,2 @@ +cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar +dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.pom diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/maven.config new file mode 100644 index 000000000..d3b91570d --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/pom.xml new file mode 100644 index 000000000..69d1ba93a --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + dev.socket.test + reactor + 1.0.0 + pom + + 1.7.36-socket.77777777 + + + app + + + + socket-patch-77777777-7777-7777-7777-777777777777 + https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2 + + true + fail + + + false + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/app/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/app/pom.xml new file mode 100644 index 000000000..d707c3acb --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/app/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + dev.socket.test + reactor + 1.0.0 + + app + + + org.slf4j + slf4j-api + ${slf4j.version} + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/pom.xml new file mode 100644 index 000000000..c21ad0961 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + dev.socket.test + reactor + 1.0.0 + pom + + 1.7.36 + + + app + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/overrides.json new file mode 100644 index 000000000..53deb25b8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-maven.json b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-maven.json index 9d433d65e..07374b37a 100644 --- a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-maven.json +++ b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-maven.json @@ -437,6 +437,22 @@ "elsewhere": [], "live_claims": [] }, + "redirect/maven/pom/parent-in-checkout/expected": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/parent-in-checkout/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, "redirect/maven/pom/plugin-dependency/expected": { "refs": [ { @@ -535,6 +551,14 @@ "elsewhere": [], "live_claims": [] }, + "redirect/maven/pom/profile-property-warn/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, "redirect/maven/pom/profile-repositories/expected": { "refs": [ { @@ -580,7 +604,200 @@ "elsewhere": [], "live_claims": [] }, - "redirect/maven/pom/property-version-warn/input": { + "redirect/maven/pom/property-external-parent-warn/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/property-shared-sibling/expected": { + "refs": [ + { + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "source_file": "pom.xml", + "artifact_rel": null, + "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "integrity_required": false, + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "lockfile_basis_ok": true + } + ], + "diagnostics": [], + "recognized": [ + { + "uuid": "11111111-1111-1111-1111-111111111111", + "mode": "hosted", + "file": "pom.xml" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "pom.xml" + } + ], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [ + { + "mode": "hosted", + "uuid": "77777777-7777-7777-7777-777777777777", + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36" + } + ] + }, + "redirect/maven/pom/property-shared-sibling/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/property-version/expected": { + "refs": [ + { + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "source_file": "pom.xml", + "artifact_rel": null, + "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "integrity_required": false, + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "lockfile_basis_ok": true + } + ], + "diagnostics": [], + "recognized": [ + { + "uuid": "11111111-1111-1111-1111-111111111111", + "mode": "hosted", + "file": "pom.xml" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "pom.xml" + } + ], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [ + { + "mode": "hosted", + "uuid": "77777777-7777-7777-7777-777777777777", + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36" + } + ] + }, + "redirect/maven/pom/property-version/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/reactor-module-literal/expected": { + "refs": [ + { + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "source_file": "app/pom.xml", + "artifact_rel": null, + "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "integrity_required": false, + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "lockfile_basis_ok": true + }, + { + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "source_file": "pom.xml", + "artifact_rel": null, + "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "integrity_required": false, + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "lockfile_basis_ok": true + } + ], + "diagnostics": [], + "recognized": [ + { + "uuid": "11111111-1111-1111-1111-111111111111", + "mode": "hosted", + "file": "pom.xml" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "app/pom.xml" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "pom.xml" + } + ], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [ + { + "mode": "hosted", + "uuid": "77777777-7777-7777-7777-777777777777", + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36" + } + ], + "unattested": [ + { + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", + "uuid": "77777777-7777-7777-7777-777777777777", + "file": "app/pom.xml", + "detail": "pom.xml heads a multi-module reactor, and a pom of it cannot be read (module_path_unresolvable: pom.xml: lib has no pom), so whether that module builds org.slf4j:slf4j-api unpatched is not known; the build may resolve the upstream jar there (re-run `scan`, or patch the reactor with `scan --mode vendored`)", + "kind": "MavenReactorRoot" + } + ] + }, + "redirect/maven/pom/reactor-module-literal/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/reactor-root-property/expected": { + "refs": [], + "diagnostics": [ + { + "code": "patched_ref_unattributable", + "file": "pom.xml", + "detail": "pom.xml: repository socket-patch-77777777-7777-7777-7777-777777777777 is tied to no dependency (no of the reactor carries the -socket.77777777 suffix; a same-GAV repository cannot be attributed to an artifact)" + } + ], + "recognized": [ + { + "uuid": "11111111-1111-1111-1111-111111111111", + "mode": "hosted", + "file": "pom.xml" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "pom.xml" + } + ], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/reactor-root-property/input": { "refs": [], "diagnostics": [], "recognized": [], From dc3ccc28c9a93129e6567b0050c458ae9851f7df Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 17:26:07 -0500 Subject: [PATCH 18/18] Never take a reactor pom that is not UTF-8 text for a missing one The hosted engine, discovery and the restore each read a reactor's module and parent poms through a reader that dropped every read error, so a pom that exists but is not UTF-8 text looked like a module with no pom: - the scan reported the reactor as short of a pom it has (`redirect_maven_multimodule_unsupported`) instead of refusing the run for a file whose content it does not know; - discovery left the pom out without a word, and a pin was attested or withheld for the wrong reason; - a rollback restored the poms it could read and left the undecodable one naming a version whose repository was gone. Each now tells "there, but not UTF-8" from "not there": - the engine records such poms and its guard refuses the run for the first, by name, with `candidate_file_unreadable`, as it does for an undecodable root pom. They are judged by what read them, not by their file name: a module's pom may be called anything. A linked or unopenable module pom still only leaves the reactor alone; - discovery reports the file as unreadable and treats it as a pom of the reactor it could not read: the pins of the other poms stay refs and none is attested, for that reason; - the restore refuses every pin of the reactor, names the file, and writes nothing: a pin is restored in every pom that carries part of it or in none, and with a pom unread "every" cannot be kept. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 11 +- .../src/commands/scan/hosted/takeover.rs | 8 +- crates/socket-patch-core/src/hosted/engine.rs | 136 +++++++++++++++--- .../src/hosted/memory/mod.rs | 1 + .../src/patch/redirect/upstream/maven.rs | 111 +++++++++++++- .../src/vex/discover/maven.rs | 71 ++++++++- .../socket-patch-core/src/vex/discover/mod.rs | 27 ++-- docs/ecosystems.md | 6 +- 8 files changed, 338 insertions(+), 33 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index fec652ab4..310aae96f 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -3067,9 +3067,14 @@ A pom that still names the patched version and can no longer be read as a pom refuses the patch, with nothing changed. A reactor is read once per run, each pom fetched and parsed once, however many -modules it has. A module pom that is a symbolic link, or that cannot be read as -text, counts as missing: the reactor is then refused -(`redirect_maven_multimodule_unsupported`), never the run. A single pom that +modules it has. A module pom that is a symbolic link, or that cannot be opened, +counts as missing: the reactor is then refused +(`redirect_maven_multimodule_unsupported`), never the run. A pom of the reactor +that is there but is not UTF-8 text is not missing: its content is unknown, so +the scan refuses the run for it by name (`candidate_file_unreadable`, as for an +undecodable root `pom.xml`), `vex` and `list` report it as unreadable and attest +no pin of that reactor, and `rollback` / `remove` refuse every pin of it with +nothing changed, since that pom may hold part of one. A single pom that inherits from a parent pom inside the checkout is read with that parent: a property the parent defines is rewritten there, and the repository goes in the parent the pom inherits it from. diff --git a/crates/socket-patch-cli/src/commands/scan/hosted/takeover.rs b/crates/socket-patch-cli/src/commands/scan/hosted/takeover.rs index c1e2e7f84..785126a27 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted/takeover.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted/takeover.rs @@ -188,7 +188,13 @@ impl Takeover { if let Some(refusal) = socket_patch_core::hosted::engine::undecodable_guard( &read.undecodable_reads, candidates, - ) { + ) + .or_else(|| { + socket_patch_core::hosted::engine::undecodable_maven_guard( + &read.undecodable_maven_poms, + candidates, + ) + }) { return Err(refusal); } } diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 67b6fa383..04dcf360c 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -619,6 +619,12 @@ pub struct CandidateFiles { /// are left out of `files`; a project whose candidates could rewrite /// one is refused rather than read as if the file were absent. pub undecodable_reads: Vec, + /// Poms of the Maven reactor (a module's, or a parent's inside the + /// checkout, whatever the file is called) that exist but are not UTF-8 + /// text. A Maven candidate could rewrite any of them, so the run is + /// refused like for [`Self::undecodable_reads`], never planned as if + /// the pom were missing. + pub undecodable_maven_poms: Vec, /// Gradle build files the script graph reached that exist but cannot be /// read as text (any view): the hosted Gradle planner refuses the build /// instead of taking them for absent (and creating a settings file over @@ -735,18 +741,37 @@ async fn read_advisory( unreadable: &BTreeSet, rel: &str, ) -> Option { + read_pom_text(view, unreadable, rel).await.ok().flatten() +} + +/// The file `rel` is there, but is not UTF-8 text. +struct Undecodable; + +/// [`read_advisory`] that tells a file which is there but is not UTF-8 +/// text (`Err`) from one that is missing, linked or not readable at all +/// (`Ok(None)`): the first is a file whose content this run does not know, +/// and must never be taken for an absent one. +async fn read_pom_text( + view: &ProjectView<'_>, + unreadable: &BTreeSet, + rel: &str, +) -> Result, Undecodable> { match view { - ProjectView::Disk(_) | ProjectView::Snapshot(_) => view.read_text(rel).await.ok(), + ProjectView::Disk(_) | ProjectView::Snapshot(_) => match view.read_text(rel).await { + Ok(text) => Ok(Some(text)), + Err(e) if e.kind() == std::io::ErrorKind::InvalidData => Err(Undecodable), + Err(_) => Ok(None), + }, ProjectView::Memory(project) if !project.is_symlink(rel) && !unreadable.contains(rel) => { match project.get(rel) { - Some(MemoryEntry::Text(text)) => Some(text.to_string()), - Some(MemoryEntry::Binary(bytes)) => { - std::str::from_utf8(bytes).ok().map(str::to_string) - } - _ => None, + Some(MemoryEntry::Text(text)) => Ok(Some(text.to_string())), + Some(MemoryEntry::Binary(bytes)) => std::str::from_utf8(bytes) + .map(|text| Some(text.to_string())) + .map_err(|_| Undecodable), + _ => Ok(None), } } - ProjectView::Memory(_) => None, + ProjectView::Memory(_) => Ok(None), } } @@ -755,11 +780,14 @@ async fn read_advisory( /// reader discovery and restore share, so each finds what the others /// wrote): every pom is fetched and parsed once, however many modules. /// -/// They are advisory input: a module pom that cannot be read as text, or -/// that is a symbolic link, is left out, and the planner then finds the -/// reactor incomplete and refuses it with nothing written. That is what a -/// reactor got before module poms were read at all; it never fails the -/// run, as an unreadable root candidate does. +/// They are advisory input: a module pom that is a symbolic link, or that +/// cannot be opened, is left out, and the planner then finds the reactor +/// incomplete and refuses it with nothing written. That is what a reactor +/// got before module poms were read at all; it never fails the run, as an +/// unreadable root candidate does. A pom that is there but is not UTF-8 +/// text is another matter: its content is unknown, not absent, so it is +/// recorded ([`CandidateFiles::undecodable_maven_poms`]) and the guard +/// refuses the run for it, as for an undecodable root pom. async fn read_maven_reactor( view: &ProjectView<'_>, unreadable: &BTreeSet, @@ -769,16 +797,40 @@ async fn read_maven_reactor( return; }; let config = out.files.get(crate::patch::redirect::MVN_CONFIG); + // A pom that is there but is not UTF-8 text is not a missing module: + // its content is unknown, so it is recorded like any other undecodable + // candidate and the run is refused for it (`candidate_file_unreadable`), + // instead of the reactor being reported as short of a pom it has. + let undecodable = std::sync::Mutex::new(Vec::new()); let read = crate::vendor::jvm::maven_reactor::read_reactor( view, root, config.map(String::as_str), - |rel| async move { read_advisory(view, unreadable, &rel).await }, + |rel| { + let undecodable = &undecodable; + async move { + match read_pom_text(view, unreadable, &rel).await { + Ok(text) => text, + Err(Undecodable) => { + undecodable + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(rel); + None + } + } + } + }, ) .await; for (rel, text) in read { out.files.entry(rel).or_insert(text); } + let mut undecodable = undecodable + .into_inner() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + undecodable.sort(); + out.undecodable_maven_poms = undecodable; } /// An in-memory project's Go files as the hosted engine reads them @@ -2054,6 +2106,8 @@ pub struct Rewritten { pub symlinked_reads: Vec, pub unreadable_reads: Vec, pub undecodable_reads: Vec, + /// [`CandidateFiles::undecodable_maven_poms`]. + pub undecodable_maven_poms: Vec, /// The rewriters' override slice (the candidates' deps). pub overrides: Vec, pub rewrite: RewriteResult, @@ -2681,6 +2735,7 @@ async fn rewrite_once( symlinked_reads, unreadable_reads, undecodable_reads, + undecodable_maven_poms, gradle_unreadable, gem_refusal, pnpm_refusal, @@ -2950,6 +3005,7 @@ async fn rewrite_once( symlinked_reads, unreadable_reads, undecodable_reads, + undecodable_maven_poms, overrides, rewrite, rewritten, @@ -3938,6 +3994,17 @@ pub fn undecodable_guard(undecodable: &[String], candidates: &[Candidate]) -> Op .map(|rel| undecodable_refusal(rel)) } +/// The non-UTF-8 rule for the poms of a Maven reactor +/// ([`CandidateFiles::undecodable_maven_poms`]): with a Maven candidate, +/// the first of them refuses the run, as an undecodable root `pom.xml` +/// does. A module's pom may be a file of any name, so these are judged by +/// what read them, not by their name. +pub fn undecodable_maven_guard(poms: &[String], candidates: &[Candidate]) -> Option { + poms.first() + .filter(|_| candidates.iter().any(|c| c.dep.ecosystem == "maven")) + .map(|rel| undecodable_refusal(rel)) +} + /// SYMLINK GUARD — fail-closed, whole rewrite, before any write (hosted /// rewrites are transactional). The writer stages next to /// the path and renames over it, which REPLACES a symbolic link with a @@ -3972,6 +4039,9 @@ pub fn guard( if let Some(refusal) = undecodable_guard(&done.undecodable_reads, candidates) { return Some(refusal); } + if let Some(refusal) = undecodable_maven_guard(&done.undecodable_maven_poms, candidates) { + return Some(refusal); + } let candidate_ecosystems: BTreeSet<&str> = candidates .iter() .map(|c| c.dep.ecosystem.as_str()) @@ -6382,7 +6452,8 @@ snapshots: /// readable content, is no reason to fail the run: the reactor is left /// as it is, with the reason, as every reactor was before module poms /// were read. The guard that refuses a linked or unreadable rewrite - /// target has nothing to refuse. + /// target has nothing to refuse. A module pom that is there but is not + /// UTF-8 text is refused by name instead: it must never look absent. #[tokio::test] async fn a_reactor_with_an_unreadable_module_pom_is_left_alone_not_failed() { let root = "\n 4.0.0\n x\n y\n 1\n pom\n \n a\n \n \n \n com.socketfixture\n victim\n 1.10.0\n \n \n\n"; @@ -6411,14 +6482,47 @@ snapshots: left_alone(&view, &read, &done); } + // A pom that is there but is not UTF-8 text is not a missing one: + // its content is unknown, so the run is refused for it by name, + // as for an undecodable root pom, with nothing written. On disk and + // in memory alike. + let undecodable = |view: &ProjectView<'_>, read: &CandidateFiles, done: &Rewritten| { + assert_eq!(read.undecodable_maven_poms, ["a/pom.xml"]); + assert!(done.rewrite.files.is_empty(), "{:?}", done.rewrite.files); + assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); + let refusal = guard(view, done, &[gradle_candidate()]).expect("refused"); + assert_eq!(refusal.code, UNREADABLE_REFUSAL); + assert!(refusal.message.contains("a/pom.xml"), "{}", refusal.message); + }; + let mut p = MemoryProject::new(); + p.insert_text("pom.xml", root); + p.insert( + "a/pom.xml", + MemoryEntry::Binary(vec![0xff, 0xfe, 0x00].into()), + ); + let view = ProjectView::Memory(&p); + let (read, done) = gradle_rewrite_in(&view).await; + undecodable(&view, &read, &done); + let tmp = tempfile::tempdir().unwrap(); std::fs::write(tmp.path().join("pom.xml"), root).unwrap(); std::fs::create_dir(tmp.path().join("a")).unwrap(); - // Not UTF-8. std::fs::write(tmp.path().join("a/pom.xml"), [0xff, 0xfe, 0x00]).unwrap(); let view = ProjectView::Disk(tmp.path()); let (read, done) = gradle_rewrite_in(&view).await; - left_alone(&view, &read, &done); + undecodable(&view, &read, &done); + // A module pom of another name is one too. + std::fs::write( + tmp.path().join("pom.xml"), + root.replace("a", "a/build.xml"), + ) + .unwrap(); + std::fs::rename(tmp.path().join("a/pom.xml"), tmp.path().join("a/build.xml")).unwrap(); + let (read, done) = gradle_rewrite_in(&view).await; + assert_eq!(read.undecodable_maven_poms, ["a/build.xml"]); + assert!(guard(&view, &done, &[gradle_candidate()]).is_some()); + std::fs::rename(tmp.path().join("a/build.xml"), tmp.path().join("a/pom.xml")).unwrap(); + std::fs::write(tmp.path().join("pom.xml"), root).unwrap(); // A link, to a pom that would otherwise be planned. #[cfg(unix)] { diff --git a/crates/socket-patch-core/src/hosted/memory/mod.rs b/crates/socket-patch-core/src/hosted/memory/mod.rs index 8d3cd30ef..e0a78a8dd 100644 --- a/crates/socket-patch-core/src/hosted/memory/mod.rs +++ b/crates/socket-patch-core/src/hosted/memory/mod.rs @@ -1610,6 +1610,7 @@ mod tests { symlinked_reads: Vec::new(), unreadable_reads: Vec::new(), undecodable_reads: Vec::new(), + undecodable_maven_poms: Vec::new(), overrides: Vec::new(), rewrite, rewritten: files.iter().map(|(rel, _)| (*rel).to_string()).collect(), diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs index 030973fdc..ded2ff951 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs @@ -393,16 +393,53 @@ pub(crate) async fn restore( // version nothing serves any more. let disk = ProjectView::Disk(view.root); let root_pom = view.read("pom.xml").await.ok().flatten(); + // A pom that is there but is not UTF-8 text is not a missing module: + // it may hold part of a pin, and nothing can tell. + let undecodable = std::sync::Mutex::new(Vec::new()); let (reactor, reactor_poms) = match &root_pom { Some(root) => ( heads_reactor_in(&disk, root, config.as_deref()).await, - read_reactor(&disk, root, config.as_deref(), |rel| async move { - disk.read_text(&rel).await.ok() + read_reactor(&disk, root, config.as_deref(), |rel| { + let undecodable = &undecodable; + async move { + match disk.read_text(&rel).await { + Ok(text) => Some(text), + Err(e) => { + if e.kind() == std::io::ErrorKind::InvalidData { + undecodable + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(rel); + } + None + } + } + } }) .await, ), None => (false, BTreeMap::new()), }; + // A pin is restored in every pom that carries part of it, or in none. + // With a pom of the reactor unread, "every" cannot be kept: restoring + // the others would leave that one naming a version whose repository is + // gone. Every pin is refused, and nothing is written. + let mut undecodable = undecodable + .into_inner() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + undecodable.sort(); + if let Some(rel) = undecodable.first() { + for pin in pins.values() { + result.refuse( + &pin.uuid, + format!( + "{rel} is there but is not UTF-8 text, so whether it holds part of the \ + pin cannot be told; re-save it as UTF-8 and re-run" + ), + ); + } + return result; + } // The poms as they are, and as they read once the pins so far are out. let mut originals: BTreeMap = BTreeMap::new(); for rel in files { @@ -1458,6 +1495,76 @@ mod tests { assert!(!after.contains_key(MVN_CHECKSUMS), "{:?}", after.keys()); } + /// A module pom that is there but is not UTF-8 text is not a missing + /// one. Its content is unknown, and here it holds one of the pins: + /// restoring the poms that can be read would take the repository from + /// under it. Discovery still finds the pin in those; the rollback + /// refuses it, names the file, and changes nothing. + #[tokio::test] + async fn a_reactor_with_an_undecodable_module_is_not_rolled_back_in_part() { + let logback = dependency("ch.qos.logback", "logback-classic", Some("1.4.14")); + let root = REACTOR_ROOT.replace( + "b", + "b\n c", + ); + assert_ne!(root, REACTOR_ROOT); + let files = [ + ("pom.xml", root), + ("a/pom.xml", reactor_module("a", &logback)), + ("b/pom.xml", reactor_module("b", &logback)), + ("c/pom.xml", reactor_module("c", &logback)), + ]; + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), &files); + // `a` and `c` select the base version and take a pin each; `b` + // resolves another, so the root takes none. + scan( + tmp.path(), + UUID, + &[ + ("a/pom.xml", Ok("1.7.36")), + ("b/pom.xml", Ok("2.0.9")), + ("c/pom.xml", Ok("1.7.36")), + ], + ); + // The pom of `c`, pin and all, re-saved in another encoding (a + // Latin-1 "é" in a comment). + let pinned = std::fs::read(tmp.path().join("c/pom.xml")).unwrap(); + assert!(String::from_utf8_lossy(&pinned).contains("-socket.")); + let mut latin1 = b"\n".to_vec(); + latin1.extend_from_slice(&pinned); + std::fs::write(tmp.path().join("c/pom.xml"), &latin1).unwrap(); + let bytes = |root: &std::path::Path| -> BTreeMap> { + walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_file()) + .map(|entry| { + let rel = entry.path().strip_prefix(root).unwrap(); + ( + rel.to_string_lossy().replace('\\', "/"), + std::fs::read(entry.path()).unwrap(), + ) + }) + .collect() + }; + let before = bytes(tmp.path()); + + let pins = discovered(tmp.path()).await; + assert_eq!(pins.len(), 1, "{pins:?}"); + let opts = RestoreOptions { + offline: true, + ..RestoreOptions::default() + }; + let outcome = restore_upstream(tmp.path(), &pins, &opts).await; + let why = refusal(&outcome); + assert!( + why.contains("c/pom.xml") && why.contains("not UTF-8"), + "{why}" + ); + assert_eq!(bytes(tmp.path()), before, "nothing was written"); + } + /// A pin is restored in every pom of the reactor that carries part of /// it, whatever discovery listed, or in none: restoring the root alone /// would take the repository from under a module that still names the diff --git a/crates/socket-patch-core/src/vex/discover/maven.rs b/crates/socket-patch-core/src/vex/discover/maven.rs index 9bc2a9c48..c7043e582 100644 --- a/crates/socket-patch-core/src/vex/discover/maven.rs +++ b/crates/socket-patch-core/src/vex/discover/maven.rs @@ -222,10 +222,41 @@ pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { // none is attested. Only a root pom the reactor reader cannot parse // falls back to the single-pom reading below. use crate::vendor::jvm::maven_reactor::{heads_reactor_in, read_reactor, HostedReactor}; - let texts = read_reactor(&ctx.view, &raw, config.as_deref(), |rel| async move { - ctx.read_text_quiet(&rel).await + // A pom that is there but is not UTF-8 text is reported as unreadable + // (as the root pom is), and stands as a pom of the reactor that could + // not be read: it may hold a pin, or declare the base version. + let undecodable = std::sync::Mutex::new(Vec::new()); + let texts = read_reactor(&ctx.view, &raw, config.as_deref(), |rel| { + let undecodable = &undecodable; + async move { + match ctx.read_text_quiet(&rel).await { + Ok(text) => text, + Err(why) => { + undecodable + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push((rel, why)); + None + } + } + } }) .await; + let mut undecodable = undecodable + .into_inner() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + undecodable.sort(); + for (rel, why) in &undecodable { + out.diag( + super::DIAG_LOCKFILE_UNREADABLE, + rel, + format!("cannot read {rel}: {why}"), + ); + } + let undecodable: Vec = undecodable + .into_iter() + .map(|(rel, _)| format!("{rel} is there but is not UTF-8 text")) + .collect(); let heads_reactor = heads_reactor_in(&ctx.view, &raw, config.as_deref()).await; let reactor = { let read = |rel: &str| texts.get(rel).map(|text| text.clone().into_bytes()); @@ -234,6 +265,9 @@ pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { }; match reactor { Ok((reactor, unread)) if heads_reactor || reactor.scope().len() > 1 => { + // (The undecodable pom first: the reader below only knows that + // it found no pom there.) + let unread: Vec = undecodable.iter().cloned().chain(unread).collect(); extract_hosted_reactor( ctx, (&reactor, &unread), @@ -253,6 +287,7 @@ pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { .unwrap_or(&refusal.detail) .to_string() }); + let unread = undecodable.first().cloned().or(unread); extract_hosted( ctx, (&raw, &pom), @@ -2442,6 +2477,38 @@ mod tests { ); } + /// A module pom that is there but is not UTF-8 text is not a missing + /// module: discovery says it cannot read the file, by name, and the + /// pins of the other poms are refs that are not attested, for that + /// reason and not for a pom the reactor "does not have". + #[tokio::test] + async fn an_undecodable_module_pom_is_reported_unreadable_not_missing() { + let pin = format!( + "\n\n\n{}\n\n", + dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))) + ); + let p = Project::new(); + p.write("pom.xml", reactor_root("")); + p.write("a/pom.xml", reactor_module("a", &pin)); + p.write("b/pom.xml", b"\xff\xfe"); + let out = run(&p).await; + assert_eq!(sources(&out), ["a/pom.xml", "pom.xml"]); + assert_eq!(diag_codes(&out), vec![DIAG_LOCKFILE_UNREADABLE]); + assert!( + out.diagnostics[0].detail.contains("b/pom.xml"), + "{:?}", + out.diagnostics + ); + assert_eq!(out.unattested.len(), 1, "{:?}", out.unattested); + let detail = &out.unattested[0].detail; + assert!( + detail.contains("b/pom.xml is there but is not UTF-8 text"), + "{detail}" + ); + assert!(!detail.contains("has no pom"), "{detail}"); + } + /// #1809: a Maven 4 (model 4.1.0) `pom`-packaged root listing no /// subprojects builds every direct subdirectory holding a `pom.xml`, /// so its hosted pin is a reactor's: attested while the root's pin diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index 4887481e8..09cfe6b4c 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -2305,16 +2305,27 @@ impl<'a> DiscoverCtx<'a> { /// [`Self::read_text`] for a path that may be no file at all (one the /// Maven reactor reader asks about: a module named by its directory, a - /// module's `.mvn` file): missing or unreadable, it is `None` with no - /// diagnostic. What is read is recognized and logged all the same. - pub(crate) async fn read_text_quiet(&self, rel: &str) -> Option { + /// module's `.mvn` file): missing, or not a file that can be opened, it + /// is `Ok(None)` with no diagnostic. What is read is recognized and + /// logged all the same. A file that is there but is not UTF-8 text is + /// `Err`, with the reader's message: its content is unknown, which the + /// caller must say rather than take the file for absent. + pub(crate) async fn read_text_quiet(&self, rel: &str) -> Result, String> { if self.is_ignored(rel) { - return None; + return Ok(None); + } + match self.view.read_text(rel).await { + Ok(text) => { + self.log_read(rel, true); + self.recognize_text(rel, &text); + Ok(Some(text)) + } + Err(e) if e.kind() == std::io::ErrorKind::InvalidData => { + self.log_read(rel, false); + Err(e.to_string()) + } + Err(_) => Ok(None), } - let text = self.view.read_text(rel).await.ok()?; - self.log_read(rel, true); - self.recognize_text(rel, &text); - Some(text) } /// Guarded UTF-8 read of root-relative `rel`: `None` when missing diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 99d450364..7269ef883 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -968,7 +968,11 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: started in a module directory or with `-f`; a module with a `.mvn` of its own is reported (`redirect_maven_trusted_checksums_unenforced`), since a Maven started there reads that one. A reactor one of whose poms cannot be read is left untouched - (`redirect_maven_multimodule_unsupported`, with the reason). The plan for a patch is + (`redirect_maven_multimodule_unsupported`, with the reason). A pom that is there but is + not UTF-8 text (re-saved as Latin-1 or UTF-16, say) is never taken for a missing one: + the scan refuses the run and names it (`candidate_file_unreadable`), `vex` reports it + as unreadable and attests no pin of that reactor, and `rollback` / `remove` change + nothing until it is UTF-8 again, since it may hold part of a pin. The plan for a patch is written whole or not at all: a pom is never left naming a patched version without the repository that serves it, its checksum lines, and wiring a rollback can find. So a declaration only a `` holds is not rewritten on its own