From fd064219b7e69e58d38ef9ab68625e9ff8f0f6c5 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 15:51:20 -0500 Subject: [PATCH 01/10] 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/10] 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/10] 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/10] 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/10] 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("\n\ + {}{}", + x(A, "2.7.9.2-socket.8e82692a"), + deps(&[x("lib-a", "1.0"), x("lib-b", "1.0")]) + )) + .cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache("lib-b", "1.0", &[x("next", "1")]) + .cache(A, "2.7.9.2-socket.8e82692a", &[x("below", "1")]) + .cache("below", "1", &[]) + .cache("next", "1", &[]); + let selection = f.select(); + assert_eq!( + selection.verdict("pom.xml", G, A, "2.7.9.2"), + Verdict::Selected + ); + // Read through the copy's pom. + assert_eq!( + selection.verdict("pom.xml", G, "below", "1"), + Verdict::Selected + ); + // The artifact the next patch is for. + assert_eq!( + selection.verdict("pom.xml", G, "next", "1"), + Verdict::Selected + ); + + // A copy of another version is not this version's. + let f = Fixture::new(); + f.app(&deps(&[x("lib-a", "1.0"), x("lib-b", "1.0")])) + .cache("lib-a", "1.0", &[x(A, "2.7.9.2")]) + .cache("lib-b", "1.0", &[x("next", "1")]) + .cache(A, "2.7.9.1-socket.8e82692a", &[]) + .cache("next", "1", &[]); + assert!(undetermined(&f.select().verdict("pom.xml", G, "next", "1")).contains(A)); +} + #[test] fn a_version_the_poms_do_not_define_is_undetermined() { // The nearest declaration reads an undefined property. diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index 02fb6313e..935e85d5b 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -4204,6 +4204,16 @@ mod tests { ", ) .unwrap(); + // What commons-text depends on, as a resolved project holds it: + // with a pom missing, the build is not known to select 1.10.0. + let lang3 = root.join("m2/org/apache/commons/commons-lang3/3.12.0"); + std::fs::create_dir_all(&lang3).unwrap(); + std::fs::write( + lang3.join("commons-lang3-3.12.0.pom"), + "4.0.0org.apache.commons\ + commons-lang33.12.0", + ) + .unwrap(); let (result, entry, warnings) = unwrap_done(run_jvm(root, &blobs, &installed, &record, None).await); assert!(result.success, "{result:?}"); diff --git a/docs/design/maven-vendoring.md b/docs/design/maven-vendoring.md index 31b0cb4a7..211026634 100644 --- a/docs/design/maven-vendoring.md +++ b/docs/design/maven-vendoring.md @@ -165,8 +165,9 @@ when every module that resolves the base version is reached by its wiring. When 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 +the local repository lacks among what the module resolves, 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. The fallback repository stays in each local root, whichever pom holds the diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 5363a8fe7..f66a2f6e4 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -900,7 +900,9 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: 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 + the project was never resolved, so the local repository lacks its poms; one pom + missing among what a module resolves holds back every new pin in that module, since + it may hold a version range and a range binds at any depth), 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`): the line names the remedy, `mvn -q From e0442f584951e83f7075c114c4c0747d3fbc0ea9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:26:36 +0000 Subject: [PATCH 10/10] Fail closed when the Maven selection is unreadable; keep repo paths inside the repository - hosted scan: a failed selection task (panic or cancel) turned into `None`, which the pom rewriter reads as "no selection" and pins unchecked. Map it to `MavenSelection::unavailable`, so the rewriter treats it as undetermined like any other unreadable selection. - `repo_pom` and `listed_versions`: a coordinate with a leading or trailing `.` became a leading `/` (or a trailing one) after the `.` -> `/` mapping, and `PathBuf::join` with an absolute path drops the repository root, so a pom in the local repository could point the read-only walk at any directory. Reject leading/trailing `.` and `:` (a Windows drive) too. Test added. - CLI_CONTRACT: taking out an existing pin of a version Maven does not select is vendored-only; a hosted pin a scan wrote earlier carries no marker and is not re-checked. Assisted-by: Claude Code:claude-opus-5-5 --- crates/socket-patch-cli/CLI_CONTRACT.md | 3 +- .../src/commands/scan/hosted.rs | 18 +++++++---- .../src/crawlers/maven_scope.rs | 30 +++++++++++++++++-- .../src/crawlers/maven_selection.rs | 11 +++++-- 4 files changed, 51 insertions(+), 11 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index bbc6c8304..1a3dddd21 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2749,7 +2749,8 @@ binds at any depth, so a module with such a file missing is never reported to select the base version, however near the module the declaration that would win is. The other modules of the build keep their own answers. Such a module is still reported to select another version: that writes no new pin (the patch -is skipped, and a pin of that version already there is taken out). Resolving +is skipped, and in vendored mode a pin of that version already there is taken +out; a hosted pin a scan wrote earlier is not re-checked). Resolving the project fills the files in, and the reason given names the missing file. The pom of a version that loses mediation is not part of what the module resolves, and a base version whose pom is cached only for its diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 3d90bf108..9a3616ecf 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -1536,11 +1536,19 @@ async fn run_redirect_selected_untracked( && !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() + Some( + tokio::task::spawn_blocking(move || { + socket_patch_core::crawlers::maven_selection::MavenSelection::for_project(&cwd) + }) + .await + // A selection that could not be read answers "undetermined", never + // "no selection": `None` would let the rewriter pin unchecked. + .unwrap_or_else(|err| { + socket_patch_core::crawlers::maven_selection::MavenSelection::unavailable(format!( + "the Maven selection could not be read ({err})" + )) + }), + ) } else { None }; diff --git a/crates/socket-patch-core/src/crawlers/maven_scope.rs b/crates/socket-patch-core/src/crawlers/maven_scope.rs index 128aa8f76..570e39fc6 100644 --- a/crates/socket-patch-core/src/crawlers/maven_scope.rs +++ b/crates/socket-patch-core/src/crawlers/maven_scope.rs @@ -205,10 +205,12 @@ impl<'w> Walk<'w> { pub(super) fn repo_pom(&self, (g, a, v): &Gav) -> Option { let safe = |s: &str| { + // A leading or trailing `.` would turn into a `/` that roots the + // path outside the repository; `:` would name a Windows drive. !s.is_empty() - && s != "." - && s != ".." - && !s.contains(['/', '\\', '$', '{', '}']) + && !s.starts_with('.') + && !s.ends_with('.') + && !s.contains(['/', '\\', ':', '$', '{', '}']) && !s.contains("..") }; if !(safe(g) && safe(a) && safe(v)) { @@ -830,6 +832,28 @@ pub(super) fn normalize(path: &Path) -> Option { mod tests { use super::*; + #[test] + fn repo_pom_stays_inside_the_repository() { + let repo = Path::new("/repo"); + let walk = Walk::new(Path::new("/project"), repo); + let gav = |g: &str, a: &str, v: &str| (g.to_string(), a.to_string(), v.to_string()); + assert_eq!( + walk.repo_pom(&gav("org.example", "lib", "1.0")), + Some(repo.join("org/example/lib/1.0/lib-1.0.pom")) + ); + // A leading `.` becomes a leading `/`, which `join` takes as a new + // root; a trailing one or a `:` (a Windows drive) escapes as well. + for bad in [ + gav(".etc", "lib", "1.0"), + gav("org.", "lib", "1.0"), + gav("C:", "lib", "1.0"), + gav("org", ".", "1.0"), + gav("org", "lib", ".."), + ] { + assert_eq!(walk.repo_pom(&bad), None, "{bad:?}"); + } + } + fn write(root: &Path, rel: &str, body: &str) { let p = root.join(rel); std::fs::create_dir_all(p.parent().unwrap()).unwrap(); diff --git a/crates/socket-patch-core/src/crawlers/maven_selection.rs b/crates/socket-patch-core/src/crawlers/maven_selection.rs index 5f3266109..527482308 100644 --- a/crates/socket-patch-core/src/crawlers/maven_selection.rs +++ b/crates/socket-patch-core/src/crawlers/maven_selection.rs @@ -1058,8 +1058,15 @@ impl Selector<'_> { if let Some(found) = self.listed.get(ga) { return found.clone(); } - let safe = - |s: &str| !s.is_empty() && !s.contains(['/', '\\', '$', '{', '}']) && !s.contains(".."); + // A leading or trailing `.` would turn into a `/` that roots the + // path outside the repository; `:` would name a Windows drive. + let safe = |s: &str| { + !s.is_empty() + && !s.starts_with('.') + && !s.ends_with('.') + && !s.contains(['/', '\\', ':', '$', '{', '}']) + && !s.contains("..") + }; let mut versions: Option> = None; let mut foreign: Vec = Vec::new(); if safe(&ga.0) && safe(&ga.1) {