diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 0603d75f4e..4566a008e8 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 to 3 — 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, 3 what Bun 1.4+ writes when `package.json` has a nested override or a yarn-style path resolution (only the lock's head differs: its `overrides` object nests); all four 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 to 3 — 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, 3 what Bun 1.4+ writes when `package.json` has a nested override or a yarn-style path resolution (only the lock's head differs: its `overrides` object nests); all four 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. @@ -2162,6 +2162,9 @@ 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, 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_maven_pin_would_move_module` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven reactor): the only poms that resolve the artifact at the patch's base version are parent poms above a module that resolves another version. A `` pin in the parent is inherited by that module and would move it, and Maven has no management that reaches a parent and not its children, so nothing is pinned and no file is written; the reason names the parent, the module and its version. When a sibling module does select the base version it is pinned and the same sentence is the `vendor_jvm_degraded` reason `pin_would_move_module`. | | `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. | @@ -2267,6 +2270,8 @@ command's integration tests check its output. | `upstream_gem_install_refreshed` | `warnings[]` (note); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem): an installed copy or cache-dir archive the unwind replaced with the sha256-verified upstream gem. A wet vendored gem unwind (#2083, #2093): an installed copy only. A human run prints a progress line instead. | | `upstream_gem_install_would_refresh` | `warnings[]` (note) | the same on `--dry-run`: what a wet unwind would replace. | | `redirect_gem_version_not_locked` | `warnings[]` (warning) | scan `--mode hosted` (gem): the crawled gem version is installed on the machine but no `GEM` section of the project's lock resolves it (another project's copy in the shared gem home). The gem is skipped and the Gemfile and lock stay byte-identical. | +| `redirect_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`. | @@ -2872,6 +2877,116 @@ 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` 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. + +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. + +A file the local repository lacks (the pom of an artifact the module resolves, +a parent pom, an imported BOM, the version list of a range) weighs more than +the other causes. A version range may be in what was not read, and a range +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 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 +`-socket.` copy (a build pinned to the copy fetches no other) reads +the copy's. An artifact published without any pom stays a missing file. Any +other cause leaves a declaration nearer the module than it is certain. + +| 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; 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 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, even while a sibling's selection cannot be told. A +pom that manages the artifact itself takes no pin (its own entry is rewritten +when it names the base version), and neither does a local root a conflicting +declaration rules out; the modules below either are still pinned where they +select the base version. A parent pom that resolves the base version itself, +above a module that resolves another, cannot be pinned without moving that +module: it takes no pin (`pin_would_move_module`, naming both), and when it is +the only pom that selects the base version the patch is the +`vendor_maven_pin_would_move_module` skip. A plan made without a selection +(`repair`, a probe) keeps the committed pins in whichever pom they are. + +`vex` attests a vendored Maven patch only when every module that resolves the +base version is wired: reached by a pin on its parent chain, the project's own +management at the patched version, or a declaration at it. A module a pin does +not reach that resolves the base version, or whose selection cannot be told on +the machine that runs `vex`, withholds the attestation, with the module named. +`vendor --check` does not ask this. + +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, and the pins are +placed afresh for the build as it is: 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 +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 @@ -3216,7 +3331,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), `selection_undetermined` (Maven reactor: what one or more modules resolve cannot be read, so no pin is written where that is so and one already there is left as it is; one event however many modules, naming the first and counting the rest), `pin_would_move_module` (Maven reactor: a parent pom resolves the base version itself above a module that resolves another version, so the parent takes no pin. 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 2cd93365c6..b60266f5ca 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -1553,6 +1553,32 @@ 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 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(); + 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 + }; + 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(); @@ -1570,6 +1596,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 9d01684e18..8f33bdb0f9 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2493,6 +2493,17 @@ 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 = + socket_patch_core::crawlers::MavenCrawler::with_an_artifact(filtered_crawled).await; + } + // 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 a2f6b2b0b1..525112faed 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 21e67d5b92..6c27c2ea70 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs @@ -43,13 +43,18 @@ //! `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"] mod vex_e2e_common; +use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use maven_build_common::*; @@ -632,3 +637,618 @@ 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. + fn stage(proj: &Path) { + stage_all(proj, &[(fixture::BASE, UUID)]); + } + + /// 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( + fixture::purl_of(version), + 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}"); + } + + /// A pin in a shared parent must go once a module below it resolves + /// another version, even while a sibling's selection cannot be told, + /// and the revert must restore every pom byte for byte. A reactor + /// whose modules all select the base version is vendored (one pin, in + /// the parent). Then `b` moves to a newer version and `a` gains a + /// dependency this machine never resolved. The next run takes the pin + /// out of the parent (it would hold `b` back), keeps the module that + /// still certainly selects the base version patched, and Maven builds + /// `b` on the version it selects. `vendor --revert` then leaves each + /// pom exactly as the user has it: no empty management block where + /// the pin was. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_vendored_parent_pin_goes_when_a_module_moves_on_and_reverts_clean() { + 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_to_string(proj.join(rel)).unwrap()) + .collect() + }; + // Every module on the base version: `b` through lib-deep, like `a`. + let b_on_newer = std::fs::read_to_string(proj.join("b/pom.xml")).unwrap(); + std::fs::write( + proj.join("b/pom.xml"), + fixture::module_pom("b", "lib-deep", "1.0"), + ) + .unwrap(); + if fixture::resolve_reactor(SUITE, &mvn, &proj, &m2, &settings, "target/before").is_none() { + return; + } + 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) + }; + stage(&proj); + let (code, env, stderr) = vendor(&["--offline"]); + assert_eq!(code, Some(0), "vendor: {env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + let sv = suffixed(); + let pinned = read_poms(&proj); + assert!( + pinned[0].contains(&format!("{sv}")), + "every module selects the base version, so the parent is pinned:\n{}", + pinned[0] + ); + + // The build moves on. + std::fs::write(proj.join("b/pom.xml"), &b_on_newer).unwrap(); + let a_with_unread = pinned[1].replace( + "\n \n", + &format!( + "\n \n{}", + fixture::dependency("lib-range", "1.0", "") + ), + ); + assert_ne!(a_with_unread, pinned[1]); + std::fs::write(proj.join("a/pom.xml"), &a_with_unread).unwrap(); + let users = read_poms(&proj); + // Maven has built `b` since (and nothing else): what `b` selects + // can be told, what `a` selects cannot. The pin still forces the + // old version on `b`. + let goal = format!("{DEPENDENCY_PLUGIN}:copy-dependencies"); + let out = mvn.run( + &proj, + &m2, + &settings, + &[&goal, "-DoutputDirectory=target/forced", "-pl", "b"], + ); + assert!(ok(&out), "{}", dump(&out)); + assert!( + proj.join("b/target/forced") + .join(fixture::victim_jar_name(&sv)) + .is_file(), + "the parent's pin holds b on the old version" + ); + std::fs::remove_dir_all(proj.join("b/target")).unwrap(); + + let (code, env, stderr) = vendor(&["--offline"]); + assert_eq!(code, Some(0), "vendor after the change: {env}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + let after = read_poms(&proj); + assert!( + !after[0].contains(&sv), + "the parent's pin would hold b back, so it goes:\n{}", + after[0] + ); + assert_eq!( + after[1], users[1], + "a cannot be told: no pin is written for it" + ); + assert_eq!(after[2], users[2], "b is untouched"); + assert!( + after[3].contains(&format!("{sv}")), + "c still selects the base version:\n{}", + after[3] + ); + let built = fixture::resolve_reactor(SUITE, &mvn, &proj, &m2, &settings, "target/after") + .expect("the local repository is warm"); + assert!( + built["b"].contains_key(&fixture::victim_jar_name(fixture::NEWER)) + && !built["b"].keys().any(|name| name.contains("-socket.")), + "b builds on the version Maven selects for it: {:?}", + built["b"].keys() + ); + assert_eq!( + built["c"] + .get(&fixture::victim_jar_name(&sv)) + .and_then(|jar| jar_member(jar, fixture::MEMBER)), + Some(fixture::patched_member()) + ); + + let (code, env, stderr) = vendor(&["--revert"]); + assert_eq!(code, Some(0), "revert: {env}\n{stderr}"); + let reverted = read_poms(&proj); + let pristine_root = { + let fresh = root.join("fresh"); + fixture::write_reactor(&fresh, &server); + std::fs::read_to_string(fresh.join("pom.xml")).unwrap() + }; + assert_eq!( + reverted[0], pristine_root, + "the parent pom, byte for byte: {env}" + ); + assert_eq!( + reverted[1], + users[1].replace(&sv, fixture::BASE), + "a/pom.xml" + ); + assert_eq!(reverted[2], users[2], "b/pom.xml"); + assert_eq!( + reverted[3], + fixture::module_pom("c", fixture::VICTIM, fixture::BASE), + "c/pom.xml" + ); + assert!(!proj.join(".mvn").exists(), "{env}"); + } + + 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 0000000000..8a49bed794 --- /dev/null +++ b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs @@ -0,0 +1,549 @@ +//! 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 { + purl_of(BASE) +} + +/// The purl of the victim at `version`. +pub fn purl_of(version: &str) -> String { + format!("pkg:maven/{GROUP}/{VICTIM}@{version}") +} + +/// 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", ""), + } + } +} + +/// One `` on a fixture artifact, as the project poms write it. +pub 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 { + 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 +} + +/// 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)), + ); + } + // A parent pom a project inherits from the repository. + serve( + server, + &format!("{GROUP_PATH}/{PARENT}/1.0/{PARENT}-1.0.pom"), + fixture_pom(PARENT, "1.0", &[]) + .replace( + "1.0\n", + "1.0\n pom\n", + ) + .as_bytes(), + ); + 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() + ) +} + +/// The modules of [`write_reactor`]: its name, the victim version it +/// selects, and the one dependency it declares (artifact, version). +pub const REACTOR_MODULES: [(&str, &str, &str, &str); 3] = [ + ("a", BASE, "lib-deep", "1.0"), + ("b", NEWER, "lib-new", "1.0"), + ("c", BASE, VICTIM, BASE), +]; + +/// The `pom.xml` of a reactor module `name` that declares `artifact` at +/// `version`. +pub fn module_pom(name: &str, artifact: &str, version: &str) -> String { + format!( + "\n\ + \n \ + 4.0.0\n \n \ + com.example\n parent\n \ + 1.0.0\n \n {name}\n \ + \n{} \n\n", + dependency(artifact, version, "") + ) +} + +/// 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, _, artifact, version) in REACTOR_MODULES { + std::fs::create_dir_all(dir.join(name)).unwrap(); + std::fs::write( + dir.join(name).join("pom.xml"), + module_pom(name, artifact, version), + ) + .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(), + ) +} + +/// A parent pom the fixture repository serves. +pub const PARENT: &str = "lib-parent"; + +/// The `pom.xml` of a project that inherits [`PARENT`] from the repository +/// and declares the base victim itself. +pub fn parented_pom(server: &Server) -> String { + project_pom(Shape::Selected, server) + .replace( + " com.example\n", + &format!( + " \n {GROUP}\n \ + {PARENT}\n 1.0\n \ + \n \n com.example\n" + ), + ) + .replace( + &dependency("lib-deep", "1.0", ""), + &dependency(VICTIM, BASE, ""), + ) +} + +/// 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 235b6be511..a235fc5c03 100644 --- a/crates/socket-patch-core/src/crawlers/maven_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/maven_crawler.rs @@ -848,20 +848,47 @@ fn coursier_spelled(path: &Path) -> bool { /// for the versions it picks, and an evicted version's pom-only directory /// is no installed copy (Ivy's crawler likewise requires the jar). fn holds_artifact(dir: &Path) -> bool { + // What a cache keeps beside an artifact: poms and Gradle modules, + // their checksum and signature sidecars, the resolver's own + // bookkeeping (`_remote.repositories`, `resolver-status.properties`, + // `maven-metadata-*.xml`), and the marks of a failed or unfinished + // download. const NOT_ARTIFACTS: &[&str] = &[ - ".pom", ".module", ".sha1", ".md5", ".sha256", ".sha512", ".asc", ".json", + ".pom", + ".module", + ".sha1", + ".md5", + ".sha256", + ".sha512", + ".asc", + ".json", + ".lastUpdated", + ".part", + ".lock", + ".repositories", + ".properties", ]; 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()) }) }) } +/// 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 { + dir.join(format!("{artifact}-{version}.pom")).is_file() && !holds_artifact(dir) +} + /// 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 @@ -1129,6 +1156,26 @@ impl MavenCrawler { packages } + /// `packages` less the Maven ones whose version directory holds a pom + /// and no artifact ([`pom_only_version_dir`]), for a crawl whose + /// packages are patched where they lie (agent mode): there is no jar + /// to patch, and such a package must not end the run as a targeted + /// patch that matched no installed copy. Hosted and vendored mode keep + /// them: a pin needs the pom, not the jar. + pub async fn with_an_artifact(packages: Vec) -> Vec { + run_walk(move || { + packages + .into_iter() + .filter(|p| { + !(super::types::Ecosystem::from_purl(&p.purl) + == Some(super::types::Ecosystem::Maven) + && pom_only_version_dir(&p.path, &p.name, &p.version)) + }) + .collect() + }) + .await + } + /// Find specific packages by PURL inside a single Maven repository path. /// /// For each PURL, constructs the expected path: @@ -2504,6 +2551,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 4c0269cacf..570e39fc6a 100644 --- a/crates/socket-patch-core/src/crawlers/maven_scope.rs +++ b/crates/socket-patch-core/src/crawlers/maven_scope.rs @@ -25,13 +25,18 @@ //! 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::cell::RefCell; +use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; +use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::sync::Arc; -use crate::formats::maven::interpolate_strict; +use crate::formats::maven::{interpolate_strict, split_socket_version}; use crate::vendor::jvm::maven_reactor::{ implicit_subprojects, may_discover_subprojects, pom_model, PomDecl, PomModel, MAVEN_CONFIG, }; @@ -70,17 +75,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 +91,23 @@ 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, + /// Where [`Walk::read`] and [`Walk::list`] note what they returned, + /// for a caller that keeps its answer ([`Walk::noting`]). + reads: Option<&'w Reads>, /// Parsed poms by path (`None`: missing or unreadable). models: HashMap>>, scope: ProjectScope, @@ -120,15 +118,66 @@ 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, + reads: None, + 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(), + } + } + + /// A walk that notes in `reads` every file and directory it reads: + /// each pom looked up (found or not), `.mvn/maven.config`, each + /// directory listed for subprojects, and whatever its caller reads + /// through [`Walk::read`] and [`Walk::list`]. It is for reading the + /// reactor and its poms' chains; the scope's queue ([`Walk::run`]), + /// whose listing of an artifact's cached versions is not noted, is + /// not run on it. + pub(super) fn noting(cwd: &'w Path, repo: &'w Path, reads: &'w Reads) -> Walk<'w> { + Walk { + reads: Some(reads), + ..Walk::new(cwd, repo) + } + } + + /// The bytes of the regular file at `path` (`None`: missing or not + /// readable), as the run's own readers see it. + pub(super) fn read(&self, path: &Path) -> Option> { + match self.reads { + Some(reads) => reads.file(path), + None => read_file(path), + } + } + + /// The entries of the directory at `path` (`None`: it cannot be + /// listed): each name, and whether it is a directory (through a link). + pub(super) fn list(&self, path: &Path) -> Option> { + match self.reads { + Some(reads) => reads.dir(path), + None => list_dir(path), + } + } + + pub(super) fn model(&mut self, path: &Path, include_profiles: bool) -> Option> { if let Some(found) = self.models.get(path) { return found.clone(); } - let parsed = read_model(path, include_profiles, &self.work); + let parsed = parse_model(self.read(path), include_profiles, &self.work); self.models.insert(path.to_path_buf(), parsed.clone()); parsed } @@ -140,12 +189,10 @@ impl Walk<'_> { .filter_map(|gav| self.repo_pom(gav)) .filter(|path| !self.models.contains_key(path)) .collect(); - let work = std::rc::Rc::clone(&self.work); - let parsed = paths.into_iter().map(|path| { - let model = read_model(&path, false, &work); - (path, model) - }); - self.models.extend(parsed); + for path in paths { + let model = parse_model(self.read(&path), false, &self.work); + self.models.insert(path, model); + } } /// Whether `path` stays inside the checkout (lexically). @@ -156,12 +203,14 @@ 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| { + // 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)) { @@ -176,10 +225,33 @@ impl Walk<'_> { ) } + /// The `-socket.` copies of `gav` the local repository + /// holds, in name order. + pub(super) fn socket_copies(&self, gav: &Gav) -> Vec { + let (g, a, v) = gav; + let Some(dir) = self + .repo_pom(gav) + .and_then(|pom| Some(pom.parent()?.parent()?.to_path_buf())) + else { + return Vec::new(); + }; + let mut copies: Vec = self + .list(&dir) + .unwrap_or_default() + .into_iter() + .filter(|(_, is_dir)| *is_dir) + .filter_map(|(name, _)| name.into_string().ok()) + .filter(|name| split_socket_version(name).is_some_and(|(base, _)| base == v)) + .map(|name| (g.clone(), a.clone(), name)) + .collect(); + copies.sort(); + copies + } + /// `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 +310,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,8 +341,9 @@ impl Walk<'_> { local: true, }]; let mut seen: HashSet = HashSet::from([root]); - let config = crate::utils::fs::read_regular_to_bytes_sync(&self.cwd.join(MAVEN_CONFIG)) - .ok() + let mut chains = Vec::new(); + let config = self + .read(&self.cwd.join(MAVEN_CONFIG)) .map(|b| String::from_utf8_lossy(&b).into_owned()); while let Some(node) = pending.pop() { if seen.len() > MAX_REACTOR || self.work.spent() { @@ -255,45 +351,43 @@ impl Walk<'_> { } let dir = node.path.parent().unwrap_or(self.cwd).to_path_buf(); let mut modules = node.model.modules.clone(); - modules.extend(discovered_subprojects(&node.path, &dir, config.as_deref())); + modules.extend(self.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 @@ -410,6 +504,7 @@ impl Walk<'_> { { return; } + debug_assert!(self.reads.is_none(), "an unnoted read on a noting walk"); let dir = self.repo.join(g.replace('.', "/")).join(a); let Ok(entries) = std::fs::read_dir(&dir) else { return; @@ -492,46 +587,136 @@ impl Walk<'_> { } Some(()) } -} -/// The subprojects Maven 4 discovers under the pom at `path` (#1809): when -/// it lists none ([`may_discover_subprojects`]), the direct subdirectories -/// of `dir` holding a `pom.xml` ([`implicit_subprojects`]), as `` -/// names. -fn discovered_subprojects(path: &Path, dir: &Path, config: Option<&str>) -> Vec { - let Ok(bytes) = crate::utils::fs::read_regular_to_bytes_sync(path) else { - return Vec::new(); - }; - if !may_discover_subprojects(&String::from_utf8_lossy(&bytes), config) { - return Vec::new(); - } - // The planners' listing: bare names, directories (followed through a - // link) ending in `/`. - let list = |rel: &str| -> Vec { - let Ok(entries) = std::fs::read_dir(dir.join(rel)) else { + /// The subprojects Maven 4 discovers under the pom at `path` (#1809): + /// when it lists none ([`may_discover_subprojects`]), the direct + /// subdirectories of `dir` holding a `pom.xml` + /// ([`implicit_subprojects`]), as `` names. + fn discovered_subprojects(&self, path: &Path, dir: &Path, config: Option<&str>) -> Vec { + let Some(bytes) = self.read(path) else { return Vec::new(); }; - entries - .flatten() - .filter_map(|e| { - let name = e.file_name().to_str()?.to_string(); - Some(if e.path().is_dir() { - format!("{name}/") - } else { - name + if !may_discover_subprojects(&String::from_utf8_lossy(&bytes), config) { + return Vec::new(); + } + // The planners' listing: bare names, directories (followed through + // a link) ending in `/`. + let list = |rel: &str| -> Vec { + self.list(&dir.join(rel)) + .unwrap_or_default() + .into_iter() + .filter_map(|(name, is_dir)| { + let name = name.to_str()?.to_string(); + Some(if is_dir { format!("{name}/") } else { name }) }) - }) - .collect() - }; - let mut out = implicit_subprojects(&list, ""); - out.sort(); - out + .collect() + }; + let mut out = implicit_subprojects(&list, ""); + out.sort(); + out + } } -/// The pom at `path` parsed, when it is readable. Its size adds to the +/// Every read of the file system a [`Walk::noting`] walk made, each with +/// the SHA-256 of what it returned: all that an answer computed from the +/// walk depends on. The digest is taken from the very bytes (or entries) +/// the walk went on to use, through the readers [`Reads::hold`] repeats, +/// so an answer kept with its reads is exactly as old as they say: +/// +/// - it is content that is compared, never a length or a modification +/// time, which a file rewritten to the same length within one tick of +/// the file system's clock leaves as they were; +/// - a file is read as the run's own readers see it, a write the run has +/// captured and not committed yet included +/// ([`group_commit`](crate::utils::group_commit)); +/// - a file that was not there, and a directory's entries, are reads too: +/// a pom Maven caches later, or a subproject that appears, changes them. +#[derive(Default)] +pub(super) struct Reads(RefCell>); + +/// Which read of a path a [`Reads`] entry is. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Kind { + File, + Dir, +} + +/// The SHA-256 of what a read returned (`None`: nothing). +type Digest = Option<[u8; 32]>; + +impl Reads { + fn file(&self, path: &Path) -> Option> { + let bytes = read_file(path); + self.note(path, Kind::File, file_digest(bytes.as_deref())); + bytes + } + + fn dir(&self, path: &Path) -> Option> { + let entries = list_dir(path); + self.note(path, Kind::Dir, dir_digest(entries.as_deref())); + entries + } + + /// One entry per read and result: a path read twice with two results + /// (it changed under the walk) keeps both, and never holds again. + fn note(&self, path: &Path, kind: Kind, digest: Digest) { + self.0 + .borrow_mut() + .insert((path.to_path_buf(), kind, digest)); + } + + /// Whether every read returns now what it returned then. + pub(super) fn hold(&self) -> bool { + self.0.borrow().iter().all(|(path, kind, was)| { + *was == match kind { + Kind::File => file_digest(read_file(path).as_deref()), + Kind::Dir => dir_digest(list_dir(path).as_deref()), + } + }) + } +} + +fn read_file(path: &Path) -> Option> { + crate::utils::fs::read_regular_to_bytes_sync(path).ok() +} + +/// The entries of the directory at `path` by name, each with whether it is +/// a directory (through a link). +fn list_dir(path: &Path) -> Option> { + let mut entries: Vec<(OsString, bool)> = std::fs::read_dir(path) + .ok()? + .flatten() + .map(|entry| (entry.file_name(), entry.path().is_dir())) + .collect(); + entries.sort(); + Some(entries) +} + +fn file_digest(bytes: Option<&[u8]>) -> Digest { + use sha2::Digest as _; + bytes.map(|bytes| sha2::Sha256::digest(bytes).into()) +} + +fn dir_digest(entries: Option<&[(OsString, bool)]>) -> Digest { + use sha2::Digest as _; + let mut hash = sha2::Sha256::new(); + for (name, is_dir) in entries? { + let name = name.as_encoded_bytes(); + hash.update((name.len() as u64).to_le_bytes()); + hash.update(name); + hash.update([u8::from(*is_dir)]); + } + Some(hash.finalize().into()) +} + +/// The pom in `bytes` parsed, when there is one. Its size adds to the /// lookups the walk may make. -fn read_model(path: &Path, include_profiles: bool, work: &Work) -> Option> { - let bytes = crate::utils::fs::read_regular_to_bytes_sync(path).ok()?; +fn parse_model( + bytes: Option>, + include_profiles: bool, + work: &Work, +) -> Option> { + let bytes = bytes?; work.grant(bytes.len()); String::from_utf8(bytes) .ok() @@ -539,7 +724,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 +780,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 +794,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 +804,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() { @@ -647,6 +832,28 @@ 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 new file mode 100644 index 0000000000..5274823082 --- /dev/null +++ b/crates/socket-patch-core/src/crawlers/maven_selection.rs @@ -0,0 +1,1652 @@ +//! 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. +//! +//! A file the local repository does not hold (the pom of an artifact the +//! module resolves, a parent pom, an imported BOM, the version list of a +//! range) weighs more than the other causes. A version range may be in +//! what was not read, and a range binds at any depth, so a module with +//! such a file missing never answers "selects the base version", however +//! near the declaration that would win. It still answers "selects another +//! version": that writes no new pin (the patch is skipped, and a pin of +//! that version already there is taken out), so the worst a hidden range +//! can do to it is a patch not applied. Resolving the project fills the +//! files in. The other causes stay however often the project is resolved, +//! and leave a declaration nearer the module than they are certain. + +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, Reads, Walk}; +use crate::formats::maven::version::{MavenVersion, VersionRange}; +use crate::formats::maven::{ + interpolate_strict, lookup_property, maven_config_properties, split_socket_version, PomLayer, +}; +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)>, + /// Why part of what the module resolves was not read for want of a + /// file in the local repository. A version range may be in that part, + /// and a range binds at any depth, so the module is not known to + /// select the base version of any artifact. + uncached: Option, +} + +#[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 { + Self::for_project_in(project_root, None) + } + + /// [`Self::for_project`] over the local repository `repo` when one is + /// given. + pub fn for_project_in(project_root: &Path, repo: Option<&Path>) -> Self { + let repo = match repo { + Some(repo) => Some(repo.to_path_buf()), + None => super::maven_crawler::JvmEnv::from_process().m2_repo, + }; + match 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`. One run asks for it once per patch and command + /// stage, so the last answer is kept, and given again for as long as + /// every read of the file system it was made from returns what it + /// returned then: content is compared, never a length or a time. + pub fn of(project_root: &Path, repo: &Path) -> Self { + static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + Kept::or_read(&mut last, 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()) + }; + // Whatever else is in doubt, a file the local repository lacks is + // the reason given: resolving the project comes first. + let because = |why: String| module.uncached.clone().unwrap_or(why); + let Some(pick) = module.picks.get(&(group.to_string(), artifact.to_string())) else { + return match unread(usize::MAX) { + Some(why) => Verdict::Undetermined(because(why)), + None => Verdict::Absent, + }; + }; + if let Some(why) = pick.doubt.clone().or_else(|| unread(pick.depth)) { + return Verdict::Undetermined(because(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); + // A range in what the local repository lacks would overrule this + // version, and a pin of it would then move the build. + if let (true, Some(why)) = (selected, &module.uncached) { + return Verdict::Undetermined(why.clone()); + } + 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" + )), + } + } + + /// The first module whose selection of `group:artifact` cannot be + /// told, and why. + pub fn undetermined_in( + &self, + group: &str, + artifact: &str, + base: &str, + ) -> Option<(String, String)> { + if let Some(why) = &self.unavailable { + return Some(("pom.xml".to_string(), why.clone())); + } + self.modules.iter().find_map(|module| { + match self.verdict(&module.pom, group, artifact, base) { + Verdict::Undetermined(why) => Some((module.pom.clone(), why)), + _ => None, + } + }) + } + + /// [`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, + uncached: None, + }) + .collect(); + MavenSelection { + modules, + unavailable: None, + incomplete: None, + } + } +} + +/// The last selection [`MavenSelection::of`] read, with every read of the +/// file system it was made from. +struct Kept { + key: (PathBuf, PathBuf), + reads: Reads, + selection: MavenSelection, +} + +impl Kept { + /// The selection `last` holds, when it is of this project over this + /// repository and each of its reads returns the same bytes (or + /// directory entries) now: the project's poms and configuration, each + /// pom looked up in the repository (found or not), each version list. + /// Reading them again and comparing digests costs a fraction of + /// parsing them and walking the graph, and cannot take a rewritten + /// file for an unchanged one, as its length and modification time can. + /// Otherwise the selection is read anew and kept in its place, so what + /// a run writes itself (a pin, a rewritten declaration) is read too. + fn or_read(last: &mut Option, project_root: &Path, repo: &Path) -> MavenSelection { + let key = (project_root.to_path_buf(), repo.to_path_buf()); + if let Some(kept) = last.as_ref() { + if kept.key == key && kept.reads.hold() { + return kept.selection.clone(); + } + } + let reads = Reads::default(); + let selection = select(project_root, repo, &reads); + *last = Some(Kept { + key, + reads, + selection: selection.clone(), + }); + selection + } +} + +/// 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 ") + ) + } +} + +/// What every "not cached" cause names: resolving the project fills it. +const NOT_CACHED: &str = "the local Maven repository"; + +/// The one line that says the selection of an artifact could not be told, +/// with the remedy that can work for `why`. Resolving the project helps +/// only when a pom or version list is missing from the local repository; +/// anything else (a profile that may change the graph, Maven 4, a cycle, a +/// relocation, a range a pin would freeze, an undefined property) stays as +/// it is however often the project is resolved, and a declaration of the +/// artifact at the base version, which is patched where it stands, is the +/// way through. +pub fn undetermined_detail(group: &str, artifact: &str, base: &str, why: &str) -> String { + let declare = format!( + "declare {group}:{artifact} {base} in the pom of each module that should take the \ + patch (a declaration that names the version is patched where it stands)" + ); + let remedy = if why.contains(NOT_CACHED) { + format!("resolve the project once (`mvn -q dependency:resolve`) and re-run, or {declare}") + } else { + format!("resolving the project again will not change that: {declare}") + }; + format!( + "which version of {group}:{artifact} Maven selects cannot be told ({why}), so nothing \ + was pinned for {base}: {remedy}" + ) +} + +// ── 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, + /// The same when the cause is a pom the local repository does not + /// hold (a parent, an imported BOM). + uncached: 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, + /// Why a pom the local repository does not hold (a parent, an imported + /// BOM) may change these. + uncached: 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 range that cannot be resolved: a hard requirement at any depth, + /// so it leaves the artifact's selection undetermined however deep it is. + hard: bool, + /// The version cannot be read for want of a file in the local + /// repository (the version list of its range). + uncached: 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)>, + /// The same when the cause is a file the local repository does not + /// hold. + uncached: Option, +} + +/// 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, + hard: bool, + uncached: 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, + hard: edge.hard, + uncached: edge.uncached, + } + } +} + +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 for the module + /// being read. + listed: HashMap>, String>>, + /// The repositories the module being read resolves from, by id. + repositories: BTreeSet, +} + +/// The selection of the project at `cwd` over `repo`. Every file and +/// directory it is read from is read through the walk, which notes each +/// in `reads`: nothing here touches the file system any other way. +fn select(cwd: &Path, repo: &Path, reads: &Reads) -> MavenSelection { + let walk = Walk::noting(cwd, repo, reads); + let read = |rel: &str| { + walk.read(&cwd.join(rel)) + .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 user = read(MAVEN_CONFIG) + .map(|config| maven_config_properties(&config)) + .unwrap_or_default(); + let mut selector = Selector { + walk, + user, + 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(), + repositories: BTreeSet::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, in + /// Maven's order ([`lookup_property`]): a `project.*` reference, the + /// command line's properties, the `` up the chain, then a + /// deprecated bare model reference (`${version}`). 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 model = |name: &str| -> Option { + 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, + } + }; + let moved = std::cell::RefCell::new(None::); + let no_user = BTreeMap::new(); + let lookup = |name: &str| -> Option { + if !self.walk.work.spend() { + return None; + } + let layers = || { + chain.iter().map(|n| PomLayer { + own: &n.model.props, + profiles: Vec::new(), + }) + }; + let prefixed = name.starts_with("project.") || name.starts_with("pom."); + if !(prefixed && model(name).is_some()) + && chain.iter().any(|n| n.model.profiles.props.contains(name)) + { + moved.borrow_mut().get_or_insert(name.to_string()); + } + // The command line's properties win in the project's own poms; + // a dependency's pom reads them after its own. + if head.local { + lookup_property(name, &model, &self.user, layers()) + } else { + lookup_property(name, &model, &no_user, layers()) + .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. The + /// other way round too: a build pinned to such a copy fetches the + /// copy's pom and never the base version's. + fn pom_of(&mut self, gav: &Gav) -> Option { + if let Some(node) = self.reactor.get(gav) { + return Some(node.clone()); + } + if let Some(found) = self.repo_node(gav) { + return Some(found); + } + match split_socket_version(&gav.2) { + Some((base, _)) => { + let base = (gav.0.clone(), gav.1.clone(), base.to_string()); + self.pom_of(&base) + } + None => self + .walk + .socket_copies(gav) + .iter() + .find_map(|copy| self.repo_node(copy)), + } + } + + /// The local repository's pom of `gav`. + fn repo_node(&mut self, gav: &Gav) -> Option { + let path = self.walk.repo_pom(gav)?; + let model = self.walk.model(&path, false)?; + Some(Node { + model, + path, + local: false, + }) + } + + /// 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), + uncached: 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 { + let why = format!( + "the BOM {}:{}:{} is not in the local Maven repository", + gav.0, gav.1, gav.2 + ); + out.uncached.get_or_insert_with(|| why.clone()); + out.incomplete = Some(why); + 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(); + } + if out.uncached.is_none() { + out.uncached = imported.uncached.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, + uncached: management.uncached.clone(), + }; + 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) + )); + } + // 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, + 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.contains(&key) { + 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(); + } + 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)); + out + } + + /// The versions Maven lists for `ga` when it resolves a range in the + /// module being read: those of the `maven-metadata-.xml` files the + /// local repository caches for the repositories the module's poms + /// declare (and Maven's own `central` and `local`), and the reactor's + /// own. `Ok(None)` when none is cached; `Err` when a file is cached + /// for a repository the module does not declare (another project's, + /// or a mirror from the user settings, which are not read): Maven may + /// or may not consult it, so the list cannot be told. + fn listed_versions(&mut self, ga: &Ga) -> Result>, String> { + if let Some(found) = self.listed.get(ga) { + return found.clone(); + } + // 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) { + let dir = self.walk.repo.join(ga.0.replace('.', "/")).join(&ga.1); + for (entry, _) in self.walk.list(&dir).unwrap_or_default() { + let name = entry.to_string_lossy(); + let Some(id) = name + .strip_prefix("maven-metadata") + .and_then(|rest| rest.strip_suffix(".xml")) + else { + continue; + }; + let id = id.strip_prefix('-').unwrap_or(id); + if !self.repositories.contains(id) { + foreign.push(id.to_string()); + continue; + } + let Some(bytes) = self.walk.read(&dir.join(&entry)) else { + continue; + }; + versions + .get_or_insert_with(Vec::new) + .extend(metadata_versions(&String::from_utf8_lossy(&bytes))); + } + } + let listed = if foreign.is_empty() { + 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(); + } + Ok(versions) + } else { + foreign.sort(); + Err(format!( + "versions of {}:{} are cached for repositories this build does not declare ({})", + ga.0, + ga.1, + foreign.join(", ") + )) + }; + self.listed.insert(ga.clone(), listed.clone()); + listed + } + + /// 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, + hard: false, + uncached: false, + }; + // A range Maven obeys but this model cannot resolve. + let hard = |why: String| { + vec![Edge { + hard: true, + ..edge(0, Ver::Unknown(why), None) + }] + }; + // The same for want of a version list. Resolving the project + // fetches one, except for a module of the reactor: Maven lists + // that from the build itself. + let in_reactor = self + .reactor + .keys() + .any(|(g, a, _)| *g == key.group && *a == key.artifact); + let unlisted = |why: String| { + vec![Edge { + hard: true, + uncached: !in_reactor, + ..edge(0, Ver::Unknown(why), None) + }] + }; + 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 hard(why); + } + 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 listed = match self.listed_versions(&ga) { + Ok(Some(listed)) => listed, + Ok(None) => { + let why = format!( + "{}:{} is declared as the range {raw} and the local Maven repository lists \ + no versions of it", + ga.0, ga.1 + ); + return unlisted(why); + } + Err(why) => { + let why = format!("{why}, so the range {raw} cannot be resolved"); + return hard(why); + } + }; + 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 unlisted(why); + } + 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)), + uncached: deps.uncached.clone(), + }; + 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 { + let why = format!( + "the pom of {}:{}:{version} is not in the local Maven repository", + key.group, key.artifact + ); + return Expanded { + edges: Vec::new(), + unknown: Some((1, why.clone())), + uncached: Some(why), + }; + }; + // 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 + ), + )), + uncached: None, + }; + } + 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)), + uncached: deps.uncached.clone(), + }; + 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 { + // Maven's own repositories, then the ones the module's poms name. + self.repositories = ["central", "local"] + .into_iter() + .map(str::to_string) + .chain(chain.iter().flat_map(|n| n.model.repositories.clone())) + .collect(); + self.listed.clear(); + let root = self.management(chain, 0); + let direct = self.direct(chain, &root); + let mut module = Module { + pom, + picks: HashMap::new(), + unknown: direct.unknown.clone(), + uncached: direct.uncached.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; + // A range that cannot be resolved binds the selection at any depth. + let mut hard: Option = None; + for item in &items { + if let Ver::Unknown(why) = &item.version { + note(module, item.path.len() + 1, why); + if item.uncached && module.uncached.is_none() { + module.uncached = Some(why.clone()); + } + if item.hard && hard.is_none() { + hard = Some(why.clone()); + } + 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()); + } + } + if let Some(why) = &hard { + 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); + } + if module.uncached.is_none() { + module.uncached = below.uncached.clone(); + } + 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 0000000000..e2253a5d77 --- /dev/null +++ b/crates/socket-patch-core/src/crawlers/maven_selection/tests.rs @@ -0,0 +1,1352 @@ +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]) { + write( + repo, + &format!("org/x/{a}/maven-metadata-central.xml"), + &metadata(a, versions), + ); +} + +fn metadata(a: &str, versions: &[&str]) -> String { + let versions: String = versions + .iter() + .map(|v| format!("{v}")) + .collect(); + format!( + "{G}{a}\ + {versions}" + ) +} + +struct Fixture { + _dir: tempfile::TempDir, + cwd: PathBuf, + repo: PathBuf, + /// This fixture's own kept answer, which no other test's selection + /// replaces: every [`Fixture::select`] but the first is one a stale + /// answer would fail. + kept: std::cell::RefCell>, +} + +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, + kept: Default::default(), + } + } + + /// 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 { + Kept::or_read(&mut self.kept.borrow_mut(), &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")); +} + +/// A range is a hard requirement at any depth, so one the model cannot +/// resolve (here its only version list is a mirror's) leaves a nearer plain +/// version undetermined: Maven may select a version inside the range. +#[test] +fn an_unresolved_deeper_range_leaves_a_nearer_version_undetermined() { + 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", &[]); + write( + &f.repo, + &format!("org/x/{A}/maven-metadata-nexus.xml"), + &metadata(A, &["1.0", "2.5", "3.0"]), + ); + let why = f.verdict("1.0"); + assert!(undetermined(&why).contains("[2.0,3.0)"), "{why:?}"); + + // The same deeper declaration at a plain version loses to the nearer one. + 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.5")]) + .cache(A, "1.0", &[]) + .cache(A, "2.5", &[]); + assert_eq!(f.verdict("1.0"), Verdict::Selected); +} + +/// 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. Nearer than that the module still answers which other +/// version it selects, but never that it selects the base version: what +/// the missing pom depends on is not known, and a version range among it +/// would overrule a nearer version. +#[test] +fn a_missing_pom_leaves_no_base_version_selected() { + 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 names_the_pom = |verdict: Verdict| { + assert!( + undetermined(&verdict).contains("never-resolved"), + "names the missing pom: {verdict:?}" + ); + }; + names_the_pom(f.verdict("2.9.10")); + let selection = f.select(); + // Declared by the module itself, nearer than the missing pom. + names_the_pom(selection.verdict("pom.xml", G, "direct", "1.0")); + assert_eq!( + selection.verdict("pom.xml", G, "direct", "0.9"), + other("1.0") + ); + assert_eq!( + selection.standing(G, "direct", "0.9"), + Standing::NotSelected(vec!["1.0".to_string()]) + ); + names_the_pom(selection.verdict("pom.xml", G, "absent", "1.0")); + assert!(matches!( + selection.standing(G, A, "2.7.9.2"), + Standing::Undetermined(_) + )); +} + +/// The downgrade a missing pom could hide. The nearest declaration of the +/// artifact is 1.0, two levels down. `lib-r`, three levels down, is not in +/// the local repository; were it to require `[2.0,3.0)`, Maven would +/// select 2.5 and a pin of 1.0 would move the build. +#[test] +fn a_pom_missing_below_the_winner_leaves_it_undetermined() { + let graph = |f: &Fixture| { + 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(A, "1.0", &[]); + }; + let f = Fixture::new(); + graph(&f); + let why = f.verdict("1.0"); + assert!( + undetermined(&why).contains("lib-r"), + "names the missing pom: {why:?}" + ); + assert!( + undetermined_detail(G, A, "1.0", undetermined(&why)).contains("dependency:resolve"), + "resolving the project is the remedy" + ); + // A patch of another version still learns what the build selects. + assert_eq!(f.verdict("0.9"), other("1.0")); + + // With the pom there the answer is certain, whichever way it goes. + let f = Fixture::new(); + graph(&f); + f.cache("lib-r", "1.0", &[]); + assert_eq!(f.verdict("1.0"), Verdict::Selected); + + let f = Fixture::new(); + graph(&f); + f.cache("lib-r", "1.0", &[x(A, "[2.0,3.0)")]) + .cache(A, "2.5", &[]); + list(&f.repo, A, &["1.0", "2.5"]); + assert_eq!(f.verdict("1.0"), other("2.5")); + + // A version that loses mediation takes what it depends on out of the + // graph, so its missing pom casts no doubt. + let f = Fixture::new(); + f.app(&deps(&[x(A, "1.0"), x("lib-a", "1.0")])) + .cache("lib-a", "1.0", &[x(A, "2.5")]) + .cache(A, "1.0", &[]); + assert_eq!(f.verdict("1.0"), Verdict::Selected); +} + +/// Each other file a resolved project has in the local repository, missing +/// where it leaves unread only what is deeper than the victim's nearest +/// declaration: a parent pom, an imported BOM, the version list of a range. +#[test] +fn each_file_the_local_repository_lacks_holds_the_base_version_back() { + // `lib-t` is two levels down, as the victim is, with `body` in its + // pom: what it brings in is three levels down. + let graph = |f: &Fixture, body: &str| { + 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-t", "1.0")]) + .cache(A, "1.0", &[]) + .cache("leaf", "1.0", &[]); + cache(&f.repo, "lib-t", "1.0", body); + }; + let held_back_by = |f: &Fixture, what: &str| { + let why = f.verdict("1.0"); + assert!(undetermined(&why).contains(what), "{why:?}"); + assert!( + undetermined_detail(G, A, "1.0", undetermined(&why)).contains("dependency:resolve"), + "resolving the project is the remedy: {why:?}" + ); + assert_eq!(f.verdict("0.9"), other("1.0")); + }; + + // A parent pom. A second cause in the same pom, a coordinate through + // a property the parent would define, does not hide it. + let parent = format!( + "{G}t-parent\ + 1" + ); + let with_parent = format!("{parent}{}", deps(&[x("leaf_${series}", "1.0")])); + let f = Fixture::new(); + graph(&f, &with_parent); + held_back_by(&f, "t-parent"); + // Every answer of the module names the missing parent, the remedy + // that works, and not the undefined property it leaves behind. + let absent = f.select().verdict("pom.xml", G, "absent", "1.0"); + assert!(undetermined(&absent).contains("t-parent"), "{absent:?}"); + let f = Fixture::new(); + graph(&f, &with_parent); + cache( + &f.repo, + "t-parent", + "1", + "pom2", + ); + f.cache("leaf_2", "1.0", &[]); + assert_eq!(f.verdict("1.0"), Verdict::Selected); + + // An imported BOM. + let import = dep( + G, + "t-bom", + Some("1"), + "pomimport", + ); + let with_bom = format!("{}{}", managed(&[import]), deps(&[x("leaf", "1.0")])); + let f = Fixture::new(); + graph(&f, &with_bom); + held_back_by(&f, "t-bom"); + let f = Fixture::new(); + graph(&f, &with_bom); + cache(&f.repo, "t-bom", "1", "pom"); + assert_eq!(f.verdict("1.0"), Verdict::Selected); + + // The version list of a range on another artifact. + let with_range = deps(&[x("leaf", "[1.0,2.0)")]); + let f = Fixture::new(); + graph(&f, &with_range); + held_back_by(&f, "[1.0,2.0)"); + let f = Fixture::new(); + graph(&f, &with_range); + list(&f.repo, "leaf", &["1.0"]); + assert_eq!(f.verdict("1.0"), Verdict::Selected); + + // A cause resolving the project does not change keeps its reach: a + // relocation three levels down leaves the nearer version certain. + let f = Fixture::new(); + graph(&f, &deps(&[x("lib-u", "1.0")])); + cache( + &f.repo, + "lib-u", + "1.0", + "lib-u-ng\ + ", + ); + assert_eq!(f.verdict("1.0"), Verdict::Selected); +} + +/// A range on a module of the reactor that was never installed has no +/// version list in the local repository, and resolving the project +/// writes none: Maven lists the module from the build. That leaves the +/// module's own selection untold, as before, and holds nothing else back. +#[test] +fn a_range_on_a_module_of_the_reactor_is_no_gap_in_the_local_repository() { + let f = Fixture::new(); + write( + &f.cwd, + "pom.xml", + &pom( + "com.example", + "parent", + "1", + "pomab", + ), + ); + 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, "1.0"), dep("com.example", "b", Some("[1,2)"), "")], + ), + ); + write(&f.cwd, "b/pom.xml", &module("b", &[])); + f.cache(A, "1.0", &[]); + let selection = f.select(); + assert_eq!( + selection.verdict("a/pom.xml", G, A, "1.0"), + Verdict::Selected + ); + undetermined(&selection.verdict("a/pom.xml", "com.example", "b", "1")); +} + +/// A build pinned to a patched copy fetches the copy's pom and never the +/// base version's, so a fresh machine holds only the copy. The model reads +/// the project without its pins, at the base version, and takes what that +/// version depends on from the copy: an earlier patch does not hold the +/// next one back. +#[test] +fn a_base_version_only_its_patched_copy_is_cached_for_reads_the_copy() { + let f = Fixture::new(); + f.app(&format!( + "\n\ + \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. + 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("cannot be told (why)")); +} + +#[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:?}"), + } +} + +/// 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); +} + +/// Maven resolves a range against the repositories the build declares. +/// A version list cached for any other repository (another project's, or +/// a mirror from the user settings) may or may not count, so the range is +/// not resolved on it. +#[test] +fn a_version_list_of_a_repository_the_build_does_not_declare_resolves_no_range() { + let corp = |f: &Fixture| { + write( + &f.repo, + "org/x/victim/maven-metadata-corp.xml", + "2.9.9\ + ", + ); + }; + 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.9.10", &[]); + list(&f.repo, A, &["2.9.0", "2.9.10"]); + assert_eq!(f.verdict("2.7.9.2"), other("2.9.10")); + corp(&f); + let why = f.verdict("2.7.9.2"); + assert!(undetermined(&why).contains("(corp)"), "{why:?}"); + + // The build declares that repository: its list counts. + let f = Fixture::new(); + f.app(&format!( + "corphttps://corp.example/repo\ + {}", + deps(&[x("lib-r", "1.0")]) + )) + .cache("lib-r", "1.0", &[x(A, "[2.9.0,2.9.10]")]) + .cache(A, "2.9.9", &[]) + .cache(A, "2.9.10", &[]); + list(&f.repo, A, &["2.9.0", "2.9.10"]); + corp(&f); + assert_eq!(f.verdict("2.7.9.2"), other("2.9.10")); +} + +/// Resolving the project helps only when something is missing from the +/// local repository; for every other cause the line names the remedy that +/// can work, a declaration of the artifact at the base version. +#[test] +fn the_remedy_fits_the_cause() { + let resolve = "mvn -q dependency:resolve"; + let declare = "declare org.x:victim 2.7.9.2 in the pom"; + // A pom the local repository lacks. + let f = Fixture::new(); + f.app(&deps(&[x("never-resolved", "1.0")])); + let line = undetermined_detail(G, A, "2.7.9.2", undetermined(&f.verdict("2.7.9.2"))); + assert!(line.contains(resolve) && line.contains(declare), "{line}"); + // A range no cached list resolves. + let f = Fixture::new(); + f.app(&deps(&[x(A, "[2.0,3.0)")])); + let line = undetermined_detail(G, A, "2.7.9.2", undetermined(&f.verdict("2.7.9.2"))); + assert!(line.contains(resolve), "{line}"); + + // A profile that declares dependencies: no resolve changes that. + 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", &[]); + let line = undetermined_detail(G, A, "2.7.9.2", undetermined(&f.verdict("2.7.9.2"))); + assert!(!line.contains(resolve) && line.contains(declare), "{line}"); + for why in [ + "the project builds with Maven 4, whose dependency management is not modelled", + "org.x:victim is part of a dependency cycle", + "a profile redefines ${v}", + "pom.xml selects org.x:victim 2.7.9.2 as the highest version of a version range, which \ + a pin would freeze", + "versions of org.x:victim are cached for repositories this build does not declare (corp)", + "${nowhere} is not defined", + ] { + let line = undetermined_detail(G, A, "2.7.9.2", why); + assert!(!line.contains(resolve) && line.contains(declare), "{line}"); + } +} + +/// `${version}` is a property of that name before it is the project's own +/// version (Maven reads the bare model references last). +#[test] +fn a_bare_model_reference_reads_a_property_of_that_name_first() { + let f = Fixture::new(); + f.app(&format!( + "2.9.10{}", + deps(&[x(A, "${version}")]) + )) + .cache(A, "2.9.10", &[]) + .cache(A, "1", &[]); + assert_eq!(f.verdict("2.9.10"), Verdict::Selected); + + let f = Fixture::new(); + f.app(&deps(&[ + x(A, "${version}"), + x("lib-a", "${project.version}"), + ])) + .cache(A, "1", &[]) + .cache("lib-a", "1", &[]); + let selection = f.select(); + assert_eq!(selection.verdict("pom.xml", G, A, "1"), Verdict::Selected); + assert_eq!( + selection.verdict("pom.xml", G, "lib-a", "1"), + Verdict::Selected + ); +} + +/// One run asks for the selection once per patch: the answer is kept +/// while the project's files are as they were, and read again once one of +/// them changes. +#[test] +fn the_selection_is_read_again_when_a_project_file_changes() { + 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); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + f.app(&deps(&[x(A, "2.9.10"), x("pad", "1")])); + assert_eq!(f.verdict("2.7.9.2"), other("2.9.10")); +} + +/// Write `text` over the file at `path` and leave its length and its +/// modification time what they were. That is what a rewrite within one +/// tick of the file system's clock (a few milliseconds on Linux) looks +/// like, made to happen on any machine: the hardest rewrite to notice, +/// not a way to help one be noticed. +fn rewrite_within_the_tick(path: &Path, text: &str) { + let before = std::fs::metadata(path).unwrap(); + std::fs::write(path, text).unwrap(); + let file = std::fs::File::options().write(true).open(path).unwrap(); + file.set_modified(before.modified().unwrap()).unwrap(); + drop(file); + let after = std::fs::metadata(path).unwrap(); + assert_eq!( + (after.len(), after.modified().unwrap()), + (before.len(), before.modified().unwrap()), + "the file's metadata must not show the rewrite" + ); +} + +/// The kept answer is checked against what the files hold, never their +/// length or modification time: a file rewritten to the same length with +/// no delay (a version bumped by one digit) is a new project, the clock +/// having ticked in between or not. +#[test] +fn a_file_rewritten_to_the_same_length_is_read_again() { + // The project's own pom. + let f = Fixture::new(); + f.cache(A, "2.7.9.2", &[]).cache(A, "2.7.9.3", &[]); + f.app(&deps(&[x(A, "2.7.9.2")])); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + f.app(&deps(&[x(A, "2.7.9.3")])); + assert_eq!(f.verdict("2.7.9.2"), other("2.7.9.3")); + rewrite_within_the_tick( + &f.cwd.join("pom.xml"), + &pom("com.example", "app", "1", &deps(&[x(A, "2.7.9.2")])), + ); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + + // A pom of the local repository. + let f = Fixture::new(); + f.app(&deps(&[x("lib-a", "1.0")])) + .cache(A, "2.7.9.2", &[]) + .cache(A, "2.7.9.3", &[]); + f.cache("lib-a", "1.0", &[x(A, "2.7.9.2")]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + f.cache("lib-a", "1.0", &[x(A, "2.7.9.3")]); + assert_eq!(f.verdict("2.7.9.2"), other("2.7.9.3")); + rewrite_within_the_tick( + &f.repo.join("org/x/lib-a/1.0/lib-a-1.0.pom"), + &pom(G, "lib-a", "1.0", &deps(&[x(A, "2.7.9.2")])), + ); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + + // A cached version list. + let f = Fixture::new(); + f.app(&deps(&[x(A, "[2.9.0,2.9.9]")])) + .cache(A, "2.9.7", &[]) + .cache(A, "2.9.8", &[]); + list(&f.repo, A, &["2.9.7"]); + assert_eq!(f.verdict("2.9.6"), other("2.9.7")); + list(&f.repo, A, &["2.9.8"]); + assert_eq!(f.verdict("2.9.6"), other("2.9.8")); + rewrite_within_the_tick( + &f.repo.join("org/x/victim/maven-metadata-central.xml"), + &metadata(A, &["2.9.7"]), + ); + assert_eq!(f.verdict("2.9.6"), other("2.9.7")); +} + +/// What was not there when the selection was read is part of what it was +/// read from: a pom Maven has cached since, a version list, a subproject +/// Maven 4 finds by listing the directory of a pom that names none. +#[test] +fn a_file_that_appears_is_read() { + let f = Fixture::new(); + f.app(&deps(&[x("lib-a", "1.0")])).cache(A, "2.7.9.2", &[]); + undetermined(&f.verdict("2.7.9.2")); + f.cache("lib-a", "1.0", &[x(A, "2.7.9.2")]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + + let f = Fixture::new(); + f.app(&deps(&[x(A, "[2.9.0,2.9.9]")])) + .cache(A, "2.9.7", &[]); + undetermined(&f.verdict("2.9.6")); + list(&f.repo, A, &["2.9.7"]); + assert_eq!(f.verdict("2.9.6"), other("2.9.7")); + + let f = Fixture::new(); + f.app("poma") + .cache(A, "2.7.9.2", &[]); + write( + &f.cwd, + "a/pom.xml", + "4.1.0\ + com.examplea1\ + pom", + ); + let sub = |name: &str| { + write( + &f.cwd, + &format!("a/{name}/pom.xml"), + &pom("com.example", name, "1", &deps(&[x(A, "2.7.9.2")])), + ); + }; + sub("one"); + assert_eq!( + f.select().modules().collect::>(), + ["a/one/pom.xml", "a/pom.xml", "pom.xml"] + ); + sub("two"); + let selection = f.select(); + assert_eq!( + selection.modules().collect::>(), + ["a/one/pom.xml", "a/pom.xml", "a/two/pom.xml", "pom.xml"] + ); + assert_eq!( + selection.verdict("a/two/pom.xml", G, A, "2.7.9.2"), + Verdict::Selected + ); +} + +/// A vendored run holds its writes to the project in memory until it +/// commits them ([`GroupCommit`](crate::utils::group_commit::GroupCommit)), +/// and its readers answer from them. The selection reads a pom as they +/// do, and a kept answer is checked the same way: a pom the run has +/// written is the pom, on disk yet or not. +#[test] +fn a_write_the_run_has_not_committed_is_read() { + use crate::utils::group_commit::{capture_write, GroupCommit}; + let f = Fixture::new(); + f.app(&deps(&[x(A, "2.7.9.2")])) + .cache(A, "2.7.9.2", &[]) + .cache(A, "2.7.9.3", &[]); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); + + let run = GroupCommit::begin(&f.cwd); + let written = pom("com.example", "app", "1", &deps(&[x(A, "2.7.9.3")])); + assert!(capture_write( + &f.cwd.join("pom.xml"), + written.as_bytes(), + false + )); + assert_eq!(f.verdict("2.7.9.2"), other("2.7.9.3")); + // Dropped uncommitted: the pom is the one on disk again. + drop(run); + assert_eq!(f.verdict("2.7.9.2"), Verdict::Selected); +} + +/// A kept answer is as good as its record of what it was read from: the +/// selection reads the file system only through its walk, which notes +/// every read it makes. +#[test] +fn the_selection_reads_the_file_system_only_through_its_walk() { + let source = include_str!("../maven_selection.rs"); + for direct in ["std::fs", "utils::fs"] { + assert!( + !source.contains(direct), + "maven_selection.rs uses `{direct}`: read through `Walk::read` and `Walk::list`, \ + which note what they return" + ); + } +} diff --git a/crates/socket-patch-core/src/crawlers/mod.rs b/crates/socket-patch-core/src/crawlers/mod.rs index b657910e58..c2f944e20e 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 bb8b3cf95c..c78762c159 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 0000000000..bfb5544a2f --- /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 869cd57e26..f492c64aff 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,13 @@ async fn rewrite_once( } else { CratesIoSource::Registry }; + // Asked only for a pom the rewriter will edit: it refuses a reactor + // root whole, whatever Maven selects there. + let maven_selection = (rewrite_overrides.iter().any(|o| o.ecosystem == "maven") + && files.contains_key("pom.xml") + && !crate::patch::redirect::maven_reactor_root(&files)) + .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 +2732,7 @@ async fn rewrite_once( &gradle_unreadable, &yarn_outer, &cargo_outer, + maven_selection.as_ref(), ); (files, rewrite) }) @@ -2735,6 +2751,7 @@ async fn rewrite_once( &gradle_unreadable, &yarn_outer, &cargo_outer, + maven_selection.as_ref(), ); (files, rewrite) }; @@ -4165,6 +4182,10 @@ mod tests { ); } + fn no_maven_selection() -> Option { + None + } + fn no_cargo_outer() -> CratesIoSource { CratesIoSource::Registry } @@ -4581,6 +4602,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(), @@ -4644,6 +4666,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(), @@ -4937,6 +4960,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(), @@ -5625,6 +5649,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(), @@ -5732,6 +5757,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(), @@ -5942,6 +5968,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(), @@ -6338,6 +6365,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(), @@ -6546,6 +6574,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(), @@ -6593,6 +6622,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(), @@ -6783,6 +6813,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(), @@ -7186,6 +7217,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 54883bc5e2..345ad98b28 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 e012bc418b..16808d8244 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 face29f7c8..7561c41ae7 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) }), @@ -8978,9 +8986,20 @@ fn find_maven_dependency_matches( .collect() } +/// Whether the root `pom.xml` among `files` heads a multi-module reactor +/// (`` / ``, or Maven 4 subproject discovery), which +/// the pom rewriter refuses whole: nothing it would ask about the build, +/// such as what Maven selects, is needed then. +pub fn maven_reactor_root(files: &BTreeMap) -> bool { + let read = |rel: &str| files.get(rel).map(|t| t.as_bytes().to_vec()); + let list = |dir: &str| gradle::key_list(files, dir); + crate::vendor::jvm::maven_reactor::is_reactor_root(&read, &list) +} + fn rewrite_maven_pom( files: &BTreeMap, overrides: &[DepOverride], + selection: Option<&MavenSelection>, result: &mut RewriteResult, ) { let maven: Vec<&DepOverride> = overrides @@ -9003,11 +9022,7 @@ fn rewrite_maven_pom( // vendored mode's reactor planner rewrites each module's declaration. // Maven 4 subprojects found by discovery count too (#1809): the engine // reads each direct subdirectory's `pom.xml` beside such a root. - if pom.is_some() && { - let read = |rel: &str| files.get(rel).map(|t| t.as_bytes().to_vec()); - let list = |dir: &str| gradle::key_list(files, dir); - crate::vendor::jvm::maven_reactor::is_reactor_root(&read, &list) - } { + if pom.is_some() && maven_reactor_root(files) { let gas: Vec = maven .iter() .map(|dep| match &dep.namespace { @@ -9149,6 +9164,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 @@ -9534,6 +9576,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; @@ -11526,6 +11586,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 in the local Maven repository", + )); + 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 in the local Maven repository") + && 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. @@ -14422,6 +14579,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 6d81f17ccb..76e0b6cc75 100644 --- a/crates/socket-patch-core/src/vendor/jvm/apply.rs +++ b/crates/socket-patch-core/src/vendor/jvm/apply.rs @@ -1098,6 +1098,19 @@ fn entry_wiring_checked(root: &Path, entry: &VendorEntry, attest: bool) -> Resul if maven && wired == Ok(true) { wired = maven_reactor::attestable_checked(&read, &list, &c).map_err(|e| e.detail); } + // A pin can sit in one module's pom: the patch is attested only + // when every module that resolves the base version (or may, where + // that cannot be told) is wired. `vendor --check` does not ask + // this (`attest` is false there): it would make the check depend + // on what the machine's local repository holds. + if attest && maven && wired == Ok(true) { + let selection = crate::crawlers::maven_selection::MavenSelection::for_project(root); + wired = match maven_reactor::unwired_modules(&read, &list, &c, &selection) { + Ok(None) => Ok(true), + Ok(Some(why)) => Err(why), + Err(e) => Err(e.detail), + }; + } wired }; if let Some(e) = reader.read_error.borrow().as_ref() { @@ -1314,15 +1327,33 @@ pub fn check_entry_in( attempts.push((as_committed, None)); } } + // Where the pins are is not judged here. `vendor` places them when a + // patch is first wired, from what the local repository of that machine + // could tell it, and keeps them where they are afterwards: the + // committed poms are the record. Checking them against this machine's + // local repository would pass or fail the same checkout depending on + // what happens to be cached, so every pin (and every absence of one) + // is taken as it stands; a patch no pom wires at all still fails + // below. + let as_committed = matches!(shape, Shape::MavenReactor | Shape::Mixed).then(|| { + crate::crawlers::maven_selection::MavenSelection::unavailable( + "vendor --check does not judge where a pin belongs", + ) + }); + let attempts: Vec<_> = attempts + .iter() + .map(|(patch, external)| (patch, *external, as_committed.as_ref())) + .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 e3b78c8f61..5fe77de47b 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,35 @@ 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 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. A parent pom +/// that resolves the base version itself above a module that resolves +/// another takes no pin (`pin_would_move_module`). `None` plans without +/// the check: a patch no pom wires yet is pinned in every local root, and +/// one the poms already wire keeps the pins it has, in whichever pom they +/// are (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 +315,93 @@ pub fn plan_with_external( } } + // What the modules at and below each pom select, read once. + let under = selection.map(|selection| reactor.under(selection, patch)); + if let Some(under) = &under { + // A module that declares another version itself resolves that + // version: its declaration is no conflict to report, and the pins + // go where the base version is selected. + warnings.retain(|w| { + !under.iter().any(|(rel, u)| { + u.own == Some(Own::Other) + && w.detail.contains(" is declared at ") + && w.detail + .starts_with(&format!("reason: conflicting_literal_version: {rel}:")) + }) + }); + } + // Where the pin goes, and the poms whose pin stays as it is. + let mut pins: BTreeSet = BTreeSet::new(); + let mut held: BTreeSet = BTreeSet::new(); + let closed = |rel: &String| unpinned.contains(rel) || managed_roots.contains(rel); + // Where the pins go is decided when a patch is first wired, and the + // committed poms are the record of it: what this machine's local + // repository happens to hold must not move them, or the same checkout + // would plan differently from one machine to the next. A patch the + // poms already wire therefore keeps every pin it has and gets no new + // one, with or without a selection. The one exception is a pin that + // is certain to move a module to another version than Maven selects + // for it, which no run should have left: the pins are then placed + // afresh. + let moves = under.as_ref().is_some_and(|under| { + reactor.scope.iter().any(|rel| { + pin_of(&reactor.poms[rel].doc, patch).is_some() + && under.get(rel).is_some_and(|u| u.other.is_some()) + }) + }); + if reactor.wired_before(patch) && !moves { + // (A local root a declaration ruled out stays ruled out.) + held.extend(reactor.scope.iter().filter(|rel| !closed(rel)).cloned()); + } else { + let mut stranded: Vec = Vec::new(); + for root in reactor.wired_roots() { + let open = !closed(&root); + match &under { + None if open => { + pins.insert(root); + } + None => {} + Some(under) => { + let mut placing = Placing { + under, + patch, + pins: &mut pins, + held: &mut held, + stranded: &mut stranded, + }; + reactor.place(&root, open, &mut placing, 0); + } + } + } + warnings.extend( + stranded + .into_iter() + .map(|detail| degraded("pin_would_move_module", detail)), + ); + // One line for every module that cannot be told, however many. + let unknown: Vec<(&String, &String)> = under + .iter() + .flatten() + .filter_map(|(rel, u)| match &u.own { + Some(Own::Unknown(why)) => Some((rel, why)), + _ => None, + }) + .collect(); + if let Some((module, why)) = unknown.first() { + let more = match unknown.len() - 1 { + 0 => String::new(), + n => format!(", and {n} more"), + }; + warnings.push(degraded( + "selection_undetermined", + format!( + "which version of {g}:{a} {module} resolves cannot be told ({why}){more}; \ + no pin is written where that is so, and one already there is left as it is" + ), + )); + } + } + let banning = reactor .scope .iter() @@ -299,26 +416,40 @@ pub fn plan_with_external( )); } 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); + let held = held.contains(rel); match pin_of(doc, patch) { - Some(pin) if !pinned => file_edits.push(Edit::plain(pin.start, pin.end, "")), + Some(pin) if !pinned && !held => { + // The section the first run may have created for the pin + // stays this patch's to undo: its record is carried over, + // so the revert still takes the empty shell out. + records.push(adopt(rel, POM_FRAGMENT_KIND, "pin_section")); + file_edits.push(Edit::plain(pin.start, pin.end, "")); + } Some(pin) if pin.uuid == patch.uuid => {} + // A pin of an earlier patch of this version moves to the new + // suffix where it stands, held or not: the tree it names is + // about to be replaced. 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 => { + None if pinned && !held => { 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")); @@ -574,11 +705,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] = [ + "pin_would_move_module", + "property_unresolved", + "conflicting_literal_version", + "conflicting_managed_version", + "management_unresolved", + "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 +738,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 +757,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 +767,64 @@ pub fn refuse_unwired( }) } +/// The plan that takes every pin of `c`'s g:a:v (from any patch uuid) out +/// of the reactor's poms, for a build that is known not to select that +/// version any more: the pin would keep forcing it. `None` when no pom +/// holds one. Declarations are left as they are (one that names the +/// version is what selects it), and so are the tree and the ledger entry, +/// which `vendor --revert` and `scan --prune` drop. +pub fn unpin_plan(read: ReadFn<'_>, list: ListFn<'_>, c: &Coords<'_>) -> Option { + let reactor = Reactor::discover(read, list).ok()?; + let gav = format!("{}:{}:{}", c.group_id, c.artifact_id, c.version); + let writes: Vec = reactor + .scope + .iter() + .filter_map(|rel| { + let doc = &reactor.poms[rel].doc; + let pin = doc.pin_of_gav(&gav)?; + Some(FileWrite { + rel: rel.clone(), + bytes: apply_edits(&doc.text, vec![Edit::plain(pin.start, pin.end, "")]) + .into_bytes(), + tree: false, + }) + }) + .collect(); + (!writes.is_empty()).then(|| JvmPlan { + writes, + ..JvmPlan::default() + }) +} + +/// Whether the only thing that left `plan` without a pin is what Maven +/// selects: it could not be told (`selection_undetermined`), or the only +/// poms that select the base version are parents whose pin would move a +/// module below them (`pin_would_move_module`). 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| matches!(*r, "selection_undetermined" | "pin_would_move_module")) +} + +/// The `pin_would_move_module` reason of `plan`, when it has one: a parent +/// pom resolves the base version itself and cannot be pinned without +/// moving a module that inherits it. +pub fn pin_would_move(plan: &JvmPlan) -> Option<&str> { + plan.warnings + .iter() + .filter(|w| w.code == DEGRADED) + .find_map(|w| w.detail.strip_prefix("reason: pin_would_move_module: ")) +} + /// [`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 +1139,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 +1167,38 @@ 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, + /// The `` of each `` the project itself declares (no + /// profile's). + pub repositories: Vec, +} + +/// 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 +1207,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 +1232,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 +1311,15 @@ pub(crate) fn pom_model(text: &str, include_profiles: bool) -> Result, + /// Some module selects the base version. + selected: bool, + /// A module that is certain to resolve another version, and which. + other: Option<(String, String)>, + /// Some module's answer cannot be told. + unknown: bool, +} + +/// What [`Reactor::place`] decides for one patch. +struct Placing<'p> { + under: &'p BTreeMap, + 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, + /// Why a pom that resolves the base version itself takes no pin. + stranded: &'p mut Vec, +} + +/// Deepest chain of local parents a pin is placed down. +const MAX_PLACING_DEPTH: usize = 64; + +impl Reactor { + /// What the modules at and below each pom select for `patch`: every + /// module is asked once, and its answer marked on each pom of its + /// chain. + fn under(&self, selection: &MavenSelection, patch: &JvmPatch<'_>) -> BTreeMap { + let (g, a, v) = (patch.group_id, patch.artifact_id, patch.version); + let mut out: BTreeMap = BTreeMap::new(); + for module in &self.reactor { + let (own, version) = match selection.verdict(module, g, a, v) { + Verdict::Selected => (Own::Selected, None), + Verdict::Other(version) => (Own::Other, Some(version)), + Verdict::Undetermined(why) => (Own::Unknown(why), None), + Verdict::Absent => continue, + }; + for pom in self.chain(module) { + let under = out.entry(pom.to_string()).or_default(); + match (&own, &version) { + (Own::Selected, _) => under.selected = true, + (Own::Other, Some(version)) => { + under + .other + .get_or_insert_with(|| (module.clone(), version.clone())); + } + (Own::Other, None) => {} + (Own::Unknown(_), _) => under.unknown = true, + } + } + out.entry(module.clone()).or_default().own = Some(own); + } + out + } + + /// Place the patch's pin at or below `rel`: in `rel` itself when every + /// reactor module at or below 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. `open` is false for a local + /// root that takes no pin of its own (a declaration ruled it out, or + /// it manages the artifact itself): the poms below it are still + /// placed. A pom some module of which cannot be told, and none of + /// which is certain to resolve another version, is held: it gets no + /// new pin and keeps the one it has. A pom with a module that is + /// certain to resolve another version is never held, so a pin there + /// goes. + 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 under = placing.under.get(rel).cloned().unwrap_or_default(); + if under.other.is_none() && !under.unknown { + if !under.selected { + return; + } + if open { + // The user's own management on the chain already decides + // the version here: a base one was rewritten in place. + if !self.manages(rel, g, a) { + placing.pins.insert(rel.to_string()); + } + return; + } + } else if under.other.is_none() && open { + placing.held.insert(rel.to_string()); + } + // A parent pom that resolves the base version itself, above a + // module that resolves another: a pin here is inherited by that + // module and would move it, and Maven has no management that + // reaches a parent and not its children. + if let (Some(Own::Selected), Some((module, version))) = (&under.own, &under.other) { + placing.stranded.push(format!( + "{rel} resolves {g}:{a} at {v} itself, but a pin there is inherited by \ + {module}, which resolves {version}, and would move it; {rel} is not pinned \ + (the modules below it that select {v} are)" + )); + } + 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)) + }) + } + + /// Whether the patch `c` is wired for `module`: Maven reads its + /// suffixed version there from the nearest management on the module's + /// chain (a pin, or the project's own entry), or from a declaration + /// the module makes or inherits. + fn covers(&self, module: &str, c: &Coords<'_>) -> bool { + let sv = c.suffixed_version(); + if self + .managed_version(module, c.group_id, c.artifact_id) + .as_deref() + == Some(sv.as_str()) + { + return true; + } + self.chain(module).any(|p| { + let doc = &self.poms[p].doc; + self.keyed_declarations(p, c.group_id, c.artifact_id) + .iter() + .any(|(dep, _)| { + let section = doc.section_of(*dep); + !section.ends_with("dependencyManagement") + && !section.starts_with("profile:") + && doc.is_main_jar(*dep) + && doc + .child(*dep, "version") + .and_then(|version| self.interpolate(module, &doc.text_of(version))) + .as_deref() + == Some(sv.as_str()) + }) + }) + } +} + +/// Why `vex` must not attest the patch `c` although a pom wires it: a +/// module that resolves the base version (or may: its selection cannot be +/// told) is reached by no pin and no declaration of the patch, so it +/// builds the unpatched jar. A pin can sit in one module's pom while a +/// sibling was left out (undetermined when the patch was first wired, or +/// added since). `None` when every such module is wired. +pub fn unwired_modules( + read: ReadFn<'_>, + list: ListFn<'_>, + c: &Coords<'_>, + selection: &MavenSelection, +) -> Result, JvmRefusal> { + let reactor = Reactor::discover(read, list)?; + let (g, a, v) = (c.group_id, c.artifact_id, c.version); + let open: Vec = reactor + .reactor + .iter() + .filter(|module| !reactor.covers(module, c)) + .filter_map(|module| match selection.verdict(module, g, a, v) { + Verdict::Selected => Some(format!("{module} resolves it unpatched")), + Verdict::Undetermined(why) => { + Some(format!("{module} may resolve it unpatched ({why})")) + } + Verdict::Other(_) | Verdict::Absent => None, + }) + .collect(); + Ok(open.first().map(|first| { + let more = match open.len() - 1 { + 0 => String::new(), + n => format!(", and {n} more"), + }; + format!( + "the patch of {g}:{a}:{v} is not wired in every module that resolves it: \ + {first}{more}" + ) + })) +} + /// One pom outside the checkout, parsed. struct ExternalPom { gav: Gav, @@ -1758,6 +2249,22 @@ impl Reactor { roots } + /// Whether the poms already wire a patch of `patch`'s g:a:v, this one + /// or one it supersedes: a pin of that version, or a declaration at one + /// of its `-socket.` versions. + fn wired_before(&self, patch: &JvmPatch<'_>) -> bool { + self.scope.iter().any(|rel| { + let doc = &self.poms[rel].doc; + pin_of(doc, patch).is_some() + || self + .keyed_declarations(rel, patch.group_id, patch.artifact_id) + .iter() + .filter_map(|(dep, _)| doc.child(*dep, "version")) + .filter_map(|version| self.interpolate(rel, &doc.text_of(version))) + .any(|v| v != patch.version && is_base_like(&v, patch.version)) + }) + } + /// Whether a pom of the scope declares `c`'s main jar at its suffixed /// version where Maven always reads it (see [`wired_checked`]). fn wires(&self, c: &Coords<'_>) -> bool { @@ -2267,13 +2774,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); } } @@ -4877,6 +5390,681 @@ mod tests { .unwrap() } + // ── a root is pinned only where Maven selects the base version ── + + const GA: (&str, &str) = ("org.apache.commons", "commons-text"); + const PARENT_OF_TWO: &str = "\n 4.0.0\n \ + t\n root\n 1\n \ + pom\n \n a\n b\n \ + \n\n"; + + fn inheriting(name: &str) -> 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: 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_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); + assert!( + text(&after, "a/pom.xml").contains(&format!("{SV}")), + "{}", + 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")], + ); + 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. + #[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)); + 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, + /// 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) 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_goes_to_the_module_it_belongs_in() { + let files = two_modules(); + let (_, pinned) = vendor(&files); + assert!(text(&pinned, "pom.xml").contains(SV)); + 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` declares the base version itself; `b` reaches the artifact + /// through others. + fn declared_in_a() -> Fs { + let mut files = two_modules(); + files.insert( + "a/pom.xml".to_string(), + inheriting("a") + .replace( + "", + &format!( + " {}\n", + dep("1.10.0") + ), + ) + .into_bytes(), + ); + files + } + + /// Where the pins go is decided when a patch is first wired, and the + /// committed poms are the record: a later plan keeps them as they are + /// whatever the local repository of that machine can or cannot tell. + #[test] + fn a_wired_patch_keeps_its_pins_on_every_machine() { + let files = declared_in_a(); + let cold = selecting( + Some(Ok("1.10.0")), + Some(Err("the pom of x:y:1 is not in the local Maven repository")), + ); + let warm = selecting(Some(Ok("1.10.0")), Some(Ok("1.10.0"))); + let unread = MavenSelection::unavailable("nothing was read"); + // Wired where nothing could be told of `b`: the declaration, and + // no pin. A machine that can tell adds none. + let committed = applied(&files, &run_selecting(&files, &cold)); + assert!(text(&committed, "a/pom.xml").contains(&format!("{SV}"))); + assert!(!text(&committed, "pom.xml").contains(SV)); + // Wired where everything could be told: the pin too. A machine + // that cannot tell keeps it. + let pinned = applied(&files, &run_selecting(&files, &warm)); + assert!(text(&pinned, "pom.xml").contains(&format!("{SV}"))); + for state in [&committed, &pinned] { + for selection in [&cold, &warm, &unread] { + let again = run_selecting(state, selection); + assert!(again.writes.is_empty(), "{:?}", pom_rels(&again)); + } + } + } + + /// A held pom keeps its pin, but a pin of an earlier patch of the same + /// version still moves to the new suffix: the tree the old one names + /// is replaced by this run. + #[test] + fn a_held_pin_moves_to_the_suffix_of_a_superseding_patch() { + const NEXT_UUID: &str = "3f5e3bf4-7081-4c9d-8ebf-203142536475"; + const NEXT_SV: &str = "1.10.0-socket.3f5e3bf4"; + let files = declared_in_a(); + let pinned = applied( + &files, + &run_selecting(&files, &selecting(Some(Ok("1.10.0")), Some(Ok("1.10.0")))), + ); + assert!(text(&pinned, "pom.xml").contains(SV)); + let next = JvmPatch { + uuid: NEXT_UUID, + ..patch() + }; + let read = |p: &str| pinned.get(p).cloned(); + for selection in [ + selecting(Some(Err("unread")), Some(Ok("1.10.0"))), + MavenSelection::unavailable("nothing was read"), + ] { + let plan = + plan_with_selection(&read, &lister(&pinned), &next, true, None, Some(&selection)) + .expect("plan"); + let after = applied(&pinned, &plan); + for rel in ["pom.xml", "a/pom.xml"] { + assert!(text(&after, rel).contains(NEXT_SV), "{rel}"); + assert!(!text(&after, rel).contains(SV), "{rel}"); + } + } + } + + /// A plan that wires nothing because one module's answer holds a + /// shared pom back is the undetermined skip, whatever the other + /// modules select: here the parent resolves the base version itself, + /// and a pin in it would reach the module that cannot be told. + #[test] + fn a_plan_held_back_by_one_undetermined_module_is_a_skip() { + let files = two_modules(); + let selection = MavenSelection::answering( + &["pom.xml", "a/pom.xml", "b/pom.xml"], + &[ + ("pom.xml", GA.0, GA.1, Ok("1.10.0")), + ( + "b/pom.xml", + GA.0, + GA.1, + Err("a profile of b/pom.xml declares dependencies"), + ), + ], + ); + let plan = run_selecting(&files, &selection); + assert!(left_unwired(&files, &plan).is_some()); + let skip = super::super::sbt_gate::maven_undetermined( + Some(&selection), + &plan, + GA.0, + GA.1, + "1.10.0", + ); + let Some(crate::vendor::VendorOutcome::Refused { code, detail }) = skip else { + panic!("an undetermined skip"); + }; + assert_eq!(code, "vendor_maven_selection_undetermined"); + assert!( + detail.contains("b/pom.xml: a profile of b/pom.xml declares dependencies") + && !detail.contains("dependency:resolve"), + "{detail}" + ); + } + + /// A build that no longer selects a pinned version loses the pin, in + /// every pom that holds one, and nothing else. + #[test] + fn unpin_plan_takes_the_pins_of_a_version_out() { + let files = two_modules(); + let (_, pinned) = vendor(&files); + assert!(text(&pinned, "pom.xml").contains(PIN_TAG)); + let read = |p: &str| pinned.get(p).cloned(); + let plan = unpin_plan(&read, &lister(&pinned), &patch().coords()).expect("a pin"); + assert_eq!(pom_rels(&plan), ["pom.xml"]); + let after = applied(&pinned, &plan); + assert!(!text(&after, "pom.xml").contains(PIN_TAG)); + assert!(!text(&after, "pom.xml").contains(SV)); + assert!( + text(&after, "pom.xml").contains(REPO_ID), + "the repository stays" + ); + let read = |p: &str| after.get(p).cloned(); + assert!(unpin_plan(&read, &lister(&after), &patch().coords()).is_none()); + } + + /// A parent and the modules `names`, none of which declares the + /// artifact. + fn modules_under_root(names: &[&str]) -> Fs { + let listed: String = names + .iter() + .map(|name| format!(" {name}\n")) + .collect(); + let root = + PARENT_OF_TWO.replace(" a\n b\n", &listed); + let mut files = vec![("pom.xml".to_string(), root)]; + files.extend( + names + .iter() + .map(|name| (format!("{name}/pom.xml"), inheriting(name))), + ); + let files: Vec<(&str, &str)> = files + .iter() + .map(|(p, c)| (p.as_str(), c.as_str())) + .collect(); + fs(&files) + } + + /// The selection of a root and its modules: `picks` name the modules + /// that resolve the artifact. + fn answering(files: &Fs, picks: &[(&str, Result<&str, &str>)]) -> MavenSelection { + let modules: Vec<&str> = files + .keys() + .filter(|rel| rel.ends_with("pom.xml")) + .map(String::as_str) + .collect(); + let picks: Vec<_> = picks + .iter() + .map(|(pom, pick)| (*pom, GA.0, GA.1, *pick)) + .collect(); + MavenSelection::answering(&modules, &picks) + } + + /// A pin that moves a module goes even when another module under the + /// same pom cannot be told: holding it would keep the module that is + /// certain to resolve another version on the wrong one. + #[test] + fn a_pin_that_moves_a_module_is_not_held_for_an_undetermined_sibling() { + let files = modules_under_root(&["a", "b", "d"]); + let (_, pinned) = vendor(&files); + assert!(text(&pinned, "pom.xml").contains(SV)); + let selection = answering( + &pinned, + &[ + ("a/pom.xml", Ok("1.10.0")), + ("b/pom.xml", Ok("1.11.0")), + ( + "d/pom.xml", + Err("the pom of x:y:1 is not in the local Maven repository"), + ), + ], + ); + let plan = run_selecting(&pinned, &selection); + let after = applied(&pinned, &plan); + 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"]); + assert_eq!(after["d/pom.xml"], files["d/pom.xml"]); + // The section the first run created in the root stays this + // patch's to undo. + assert!(plan.records.iter().any(|w| w.file == "pom.xml" + && w.kind == POM_FRAGMENT_KIND + && w.key.as_deref() == Some("pin_section"))); + } + + /// A parent that resolves the base version itself above a module that + /// resolves another cannot take a pin: the module would inherit it. + /// The plan says so, pins the siblings that select the base version, + /// and is a skip of its own when nothing else wires the patch. + #[test] + fn a_parent_above_a_module_on_another_version_is_reported_not_pinned() { + let files = two_modules(); + let alone = answering( + &files, + &[("pom.xml", Ok("1.10.0")), ("b/pom.xml", Ok("1.11.0"))], + ); + let plan = run_selecting(&files, &alone); + let after = applied(&files, &plan); + for rel in ["pom.xml", "a/pom.xml", "b/pom.xml"] { + assert!(!text(&after, rel).contains(SV), "{rel}"); + } + let why = pin_would_move(&plan).expect("the reason"); + assert_eq!( + why, + "pom.xml resolves org.apache.commons:commons-text at 1.10.0 itself, but a pin \ + there is inherited by b/pom.xml, which resolves 1.11.0, and would move it; pom.xml \ + is not pinned (the modules below it that select 1.10.0 are)" + ); + assert!(left_unwired(&files, &plan).is_some()); + let skip = + super::super::sbt_gate::maven_undetermined(Some(&alone), &plan, GA.0, GA.1, "1.10.0"); + let Some(crate::vendor::VendorOutcome::Refused { code, detail }) = skip else { + panic!("a skip"); + }; + assert_eq!(code, "vendor_maven_pin_would_move_module"); + assert!( + detail.contains("b/pom.xml, which resolves 1.11.0"), + "{detail}" + ); + + // With a sibling that selects the base version, that one is pinned + // and the parent is still named. + let beside = answering( + &files, + &[ + ("pom.xml", Ok("1.10.0")), + ("a/pom.xml", Ok("1.10.0")), + ("b/pom.xml", Ok("1.11.0")), + ], + ); + let plan = run_selecting(&files, &beside); + let after = applied(&files, &plan); + assert!(text(&after, "a/pom.xml").contains(&format!("{SV}"))); + assert!(!text(&after, "pom.xml").contains(SV)); + assert!(pin_would_move(&plan).is_some()); + assert!(left_unwired(&files, &plan).is_none()); + } + + /// A sibling that declares another version itself resolves that + /// version: its declaration is no conflict to report once the + /// selection says so. + #[test] + fn a_sibling_declaring_another_version_is_no_conflict_under_a_selection() { + let mut files = two_modules(); + files.insert( + "b/pom.xml".to_string(), + inheriting("b") + .replace( + "", + &format!( + " {}\n", + dep("1.11.0") + ), + ) + .into_bytes(), + ); + let conflict = "conflicting_literal_version".to_string(); + assert!(reasons(&run(&files).expect("plan")).contains(&conflict)); + let selection = answering( + &files, + &[("a/pom.xml", Ok("1.10.0")), ("b/pom.xml", Ok("1.11.0"))], + ); + let plan = run_selecting(&files, &selection); + assert!(!reasons(&plan).contains(&conflict), "{:?}", reasons(&plan)); + let after = applied(&files, &plan); + assert!(text(&after, "a/pom.xml").contains(&format!("{SV}"))); + assert_eq!(after["b/pom.xml"], files["b/pom.xml"]); + } + + /// However many modules cannot be told, the plan says so once. + #[test] + fn undetermined_modules_are_reported_in_one_line() { + let files = modules_under_root(&["a", "b", "d"]); + let unread = Err("the pom of x:y:1 is not in the local Maven repository"); + let selection = answering( + &files, + &[ + ("a/pom.xml", unread), + ("b/pom.xml", unread), + ("d/pom.xml", unread), + ], + ); + let plan = run_selecting(&files, &selection); + let lines: Vec<&JvmWarning> = plan + .warnings + .iter() + .filter(|w| w.detail.starts_with("reason: selection_undetermined: ")) + .collect(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!( + lines[0] + .detail + .contains("a/pom.xml resolves cannot be told") + && lines[0].detail.contains(", and 2 more"), + "{}", + lines[0].detail + ); + } + + /// A root a declaration rules out takes no pin, with or without a + /// module that resolves another version beside it: the modules below + /// it that select the base version are pinned either way. + #[test] + fn a_closed_root_does_not_keep_its_modules_from_their_pins() { + let mut files = two_modules(); + // `b` manages another version it never uses. + files.insert( + "b/pom.xml".to_string(), + inheriting("b") + .replace( + "", + &format!( + " {}\ + \n", + dep("1.11.0") + ), + ) + .into_bytes(), + ); + let selection = answering(&files, &[("a/pom.xml", Ok("1.10.0"))]); + 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_eq!(after["b/pom.xml"], files["b/pom.xml"]); + assert!(left_unwired(&files, &plan).is_none()); + } + + /// A plan without a selection keeps the pins the poms hold, in + /// whichever pom they are: it must not pull a module's pin up into the + /// root, where it would move the sibling it was kept away from. + #[test] + fn a_plan_without_a_selection_keeps_module_pins_where_they_are() { + let files = two_modules(); + let selection = selecting(Some(Ok("1.10.0")), Some(Ok("1.11.0"))); + let pinned = applied(&files, &run_selecting(&files, &selection)); + assert!(text(&pinned, "a/pom.xml").contains(PIN_TAG)); + let again = run(&pinned).expect("plan"); + assert!(again.writes.is_empty(), "{:?}", pom_rels(&again)); + } + + /// `vex` attests a patch only when every module that resolves the base + /// version is wired: a pin in one module's pom says nothing of a + /// sibling that resolves it too, or may. + #[test] + fn a_module_left_without_the_patch_withholds_attestation() { + let files = two_modules(); + let pinned = applied( + &files, + &run_selecting(&files, &selecting(Some(Ok("1.10.0")), Some(Ok("1.11.0")))), + ); + let read = |p: &str| pinned.get(p).cloned(); + let unwired = |selection: &MavenSelection| { + unwired_modules(&read, &lister(&pinned), &patch().coords(), selection).unwrap() + }; + // `b` resolves another version: the pin in `a` is all there is to + // wire. + assert_eq!( + unwired(&selecting(Some(Ok("1.10.0")), Some(Ok("1.11.0")))), + None + ); + // `b` resolves the base version too (added or changed since). + let why = unwired(&selecting(Some(Ok("1.10.0")), Some(Ok("1.10.0")))).expect("withheld"); + assert!(why.contains("b/pom.xml resolves it unpatched"), "{why}"); + // What `b` resolves cannot be told. + let why = unwired(&selecting(Some(Ok("1.10.0")), Some(Err("unread")))).expect("withheld"); + assert!( + why.contains("b/pom.xml may resolve it unpatched (unread)"), + "{why}" + ); + // A pin in the root reaches every module, told or not. + let (_, rooted) = vendor(&files); + let read = |p: &str| rooted.get(p).cloned(); + let all = selecting(Some(Err("unread")), Some(Err("unread"))); + assert_eq!( + unwired_modules(&read, &lister(&rooted), &patch().coords(), &all).unwrap(), + None + ); + } + + /// 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 1581a8acdd..04263e3500 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 adb409f381..3e81608d87 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,27 @@ 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, + MAVEN_PIN_WOULD_MOVE, ]; +/// A Maven reactor in which the only poms that resolve the patch's base +/// version are parents of a module that resolves another version: a pin +/// in the parent is inherited by that module and would move it, so +/// nothing is pinned. +pub const MAVEN_PIN_WOULD_MOVE: &str = "vendor_maven_pin_would_move_module"; + +/// 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 +139,46 @@ 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 (`selection`, which an async caller reads off +/// the runtime; else read here): 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, + selection: Option, ) -> 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 = selection.unwrap_or_else(|| 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 +188,40 @@ 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 of +/// what Maven selects: `selection` could not tell what some module selects +/// (the pom that would take the pin is then held, whatever the other +/// modules select), or the only poms that select the base version are +/// parents whose pin would move a module below them. `None` 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; + } + if let Some((module, why)) = selection?.undetermined_in(g, a, base) { + return Some(refused( + MAVEN_UNDETERMINED, + undetermined_detail(g, a, base, &format!("{module}: {why}")), + )); + } + let why = super::maven_reactor::pin_would_move(plan)?; + Some(refused( + MAVEN_PIN_WOULD_MOVE, + format!("{why}; nothing was written for the patch of {base}"), + )) +} + /// 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 e01925a414..935e85d5b5 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,54 @@ 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 `candidates` (`(purl, uuid)`) 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. A +/// candidate an earlier run pinned is left to the backend, which takes the +/// pin out ([`unpin_unselected`]). Empty for any other build. +pub(super) fn maven_not_selected_refusals( + project_root: &Path, + candidates: &[(String, 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); + let reader = super::jvm::apply::ProjectReader::new(project_root); + candidates + .iter() + .filter_map(|(purl, uuid)| { + let (g, a, v) = parse_maven_purl(purl)?; + let Standing::NotSelected(others) = selection.standing(&g, &a, &v) else { + return None; + }; + let coords = super::jvm::Coords { + group_id: &g, + artifact_id: &a, + version: &v, + uuid, + }; + let pinned = super::jvm::maven_reactor::unpin_plan( + &|rel| reader.read(rel), + &|dir| reader.list(dir), + &coords, + ) + .is_some(); + (!pinned).then(|| { + ( + purl.clone(), + ( + super::jvm::sbt_gate::MAVEN_NOT_SELECTED, + not_selected_detail(&g, &a, &v, &others), + ), + ) + }) + }) + .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 +645,8 @@ 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) + let selection = maven_selection(shape, project_root, None).await; + super::jvm::sbt_gate::for_shape(shape, project_root, &g, &a, &v, selection) .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 +752,98 @@ async fn jvm_committed_patch( .then_some((committed, extras)) } +/// What Maven selects in each module of a Maven root, read off the async +/// runtime (the walk reads a pom per artifact of the build) over the local +/// repository `repo`, or the one this process resolves against. `None` for +/// any other shape. +async fn maven_selection( + shape: super::jvm::Shape, + project_root: &Path, + repo: Option<&Path>, +) -> Option { + use crate::crawlers::maven_selection::MavenSelection; + if !matches!( + shape, + super::jvm::Shape::MavenReactor | super::jvm::Shape::Mixed + ) { + return None; + } + let (root, repo) = (project_root.to_path_buf(), repo.map(Path::to_path_buf)); + tokio::task::spawn_blocking(move || MavenSelection::for_project_in(&root, repo.as_deref())) + .await + .ok() +} + +/// A patch the gate skipped because no module selects its base version +/// may still be pinned by an earlier run (the build has moved on since: a +/// dependency was added or upgraded). That pin keeps forcing the version +/// Maven no longer selects, so it is taken out of the poms here and the +/// skip says so; any other outcome is returned as it is. +async fn unpin_unselected( + outcome: VendorOutcome, + purl: &str, + project_root: &Path, + record: &PatchRecord, + dry_run: bool, +) -> VendorOutcome { + let VendorOutcome::Refused { code, detail } = outcome else { + return outcome; + }; + let keep = |detail: String| VendorOutcome::Refused { code, detail }; + if code != super::jvm::sbt_gate::MAVEN_NOT_SELECTED { + return keep(detail); + } + let Some((g, a, v)) = parse_maven_purl(purl) else { + return keep(detail); + }; + let coords = super::jvm::Coords { + group_id: &g, + artifact_id: &a, + version: &v, + uuid: &record.uuid, + }; + let reader = super::jvm::apply::ProjectReader::new(project_root); + let plan = super::jvm::maven_reactor::unpin_plan( + &|rel| reader.read(rel), + &|dir| reader.list(dir), + &coords, + ); + let Some(plan) = plan.filter(|_| reader.escaped().is_none()) else { + return keep(detail); + }; + let poms: Vec<&str> = plan.writes.iter().map(|w| w.rel.as_str()).collect(); + let poms = poms.join(", "); + if dry_run { + return keep(format!( + "{detail}; the pin an earlier run wrote in {poms} still forces {v} and would be removed" + )); + } + match super::jvm::apply::write_plan(project_root, &plan).await { + Ok(_) => keep(format!( + "{detail}; the pin an earlier run wrote in {poms} still forced {v} and was removed (`socket-patch vendor --revert` or `scan --mode vendored --prune` drops the vendored copy it pointed at)" + )), + Err(e) => keep(format!( + "{detail}; the pin an earlier run wrote in {poms} still forces {v} and could not be removed ({e}): run `socket-patch vendor --revert`" + )), + } +} + +/// 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 +863,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 +892,16 @@ 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 selection = maven_selection(shape, project_root, maven_repo).await; + let gate_pass = super::jvm::sbt_gate::for_shape( + shape, + project_root, + &group_id, + &artifact_id, + &version, + selection, + ) + .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,9 +939,19 @@ 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, + Err(outcome) => { + return unpin_unselected(outcome, purl, project_root, record, dry_run).await + } }; let state = Some(state); let gradle = matches!(shape, Shape::Gradle | Shape::Mixed); @@ -810,11 +971,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 +997,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 +1018,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 +1219,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 +1245,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 +2387,54 @@ 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(), UUID.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(), UUID.to_string())]).is_empty() + ); + } + #[tokio::test] #[serial_test::serial] async fn missing_reactor_module_is_refused_without_writes() { @@ -2236,6 +2466,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 +4191,29 @@ 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(); + // 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:?}"); @@ -4228,7 +4488,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 bec256a6cf..a51eb254a9 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<(String, String)> = candidates + .iter() + .filter(|(purl, _)| Ecosystem::from_purl(purl) == Some(Ecosystem::Maven)) + .map(|(purl, uuid)| (purl.to_string(), uuid.to_string())) + .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 b20c8b3915..2110266346 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,6 +144,45 @@ 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 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, and +neither does a root a conflicting declaration rules out; the poms below them +are still placed. A parent that resolves the base version itself above a +module that resolves another takes no pin either (`pin_would_move_module`): +Maven's management always reaches the children, so there is no pin that +patches the parent and leaves the child alone. `vex` attests the patch only +when every module that resolves the base version is reached by its wiring. 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 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 +pin. + +Where the pins go is decided when a patch is first wired, and the committed +poms are the record: a later run over poms that already wire the patch keeps +every pin where it is and adds none, whatever that machine's local repository +holds, so a checkout plans the same everywhere and a re-run is a no-op. +`vendor --check` does not judge where a pin belongs. A pin of a superseded +patch still moves to the new suffix in place, and a pin that is certain to +move a module is taken out: when the build no longer selects a pinned version +at all, the run removes the pin and says so in its +`vendor_maven_version_not_selected` skip. + 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 3b3b141df2..0c124e03d0 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -924,6 +924,34 @@ 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; 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 + dependency:resolve` and a re-scan when a pom is missing from the local repository, + else a declaration of the artifact at the patched version. Vendored pins are placed + when a patch is first wired and stay where they are on every machine afterwards; a + pin for a version the build no longer selects is removed on the next run. 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