diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index c6a8dd16b..9d4c96d9d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -363,7 +363,7 @@ For a **9.0 root lock**, the CLI ensures `pnpm-workspace.yaml` carries `trustLoc **Attribution gate (v5.0).** A hosted run never leaves wiring that lockfile discovery calls contested: before the rewrite writes any lockfile, the same discovery `vex`, `list`, `rollback`, `remove` and `vendor` read runs over the project as the rewrite would leave it. A candidate whose pin discovery reads but cannot attribute to one package version (a requirements `-r` include resolving the same version from the registry beside a rewired `Pipfile.lock`, #567; a Maven pin in a ``, #260) is left out of the rewrite and reported as a `skipped` event with `errorCode` `redirect_unattributable` (nothing written for it; exit code unchanged). Unchanged: a pin in a file discovery does not read (a pre-2.6 bundler `Gemfile`, locked by the next `bundle install`) keeps the rewriter's verdict, and so does a deliberate partial redirect the run already reports (a bundled or `bun patch`-ed copy left on the registry, a yarn `npm:` alias entry left on the registry with `redirect_yarn_classic_alias_skipped` / `redirect_yarn_berry_alias_skipped` while the package's direct entry is pinned, a dep withheld from the vlt rewrite while a sibling lock takes it), and so does a vendored→hosted takeover: its vendored wiring is reverted in the run's staged overlay before the rewrite plans, and it is redirected when the rewriters pin it (otherwise it is retracted and stays vendored), in a `--dry-run` preview the same. A pin whose own pnpm or yarn lock also installs an unpatched copy of the same `name@version` (a pnpm `file:` directory or tarball dependency; a yarn `file:` / URL / berry `portal:` / `link:` dependency declared under another name) is written too, with a `redirect_copy_unpatched` warning naming that entry, and is not attested. A lockless NuGet / Cargo pin (an exclusive Socket source mapping without `packages.lock.json`, a Cargo registry pin without `Cargo.lock`) is still written, with a `redirect_pin_lockless` warning: no lockfile records its version, so `vex` cannot attest it and `rollback` / `remove` / `vendor` refuse it until the lockfile exists (whether such pins should be written at all is an open decision). The rollout's recorded view uses the same discovery: a uuid a file merely mentions (a stale `package.json` field, an inactive `pdm.lock`, a comment) is not a pin and does not count as already patched. -The rewriter reads a fixed set of candidate files from the project root: the npm-family locks (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `shrinkwrap.yaml`, `yarn.lock`, plus `.yarnrc.yml` for the berry cache-config gate, `bun.lock` / `bun.lockb`, and `vlt-lock.json` with `vlt.json` and `node_modules/.vlt-lock.json` read only), `requirements.txt` / `uv.lock` / `Pipfile.lock` (pipfile-spec 6; see the Pipenv section below) / `poetry.lock` (every Poetry lock generation from 1.0 on — the 0.12 `[metadata.hashes]` layout is refused because that installer ignores URL sources; a Poetry < 1.4 writer additionally gets `redirect_poetry_stale_install_risk`, see `docs/testing/poetry-compatibility.md`) / `pdm.lock` (PDM lock formats `2` and `4.3`–`4.5.1`; the identity-losing `3.1` / `4.0`–`4.2` formats and unknown future formats are refused with `redirect_pdm_refused`, and a lock-format-`2` writer additionally gets `redirect_pdm_legacy_sync_required`, see `docs/testing/pdm-compatibility.md`; when `uv.lock` or `poetry.lock` sits beside it they drive and `pdm.lock` is left alone), `Cargo.toml` / `Cargo.lock` / `.cargo/config.toml` (plus the legacy extensionless `.cargo/config` — cargo reads that spelling in preference when both exist, so the managed `[registries.…]` block is written into whichever one is present; the hosted redirect is a `sparse+` registry, which cargo loads only from **1.68**, so `rust-toolchain.toml` / `rust-toolchain` are read too (never edited) and a project whose declared floor — the lowest `rust-version` of the root and the member manifests read here (a `rust-version.workspace = true` inheritor reads `[workspace.package]`), else the channel rustup picks from the root (the legacy `rust-toolchain` over `rust-toolchain.toml`; a dated `nightly-`/`beta-YYYY-MM-DD` maps to its release train) — is below 1.68 is refused `redirect_cargo_old_cargo` per crate (nothing written, an earlier run's pins left in place with the `rollback` that drops them named; `--mode vendored` builds on cargo 1.41+), while an undeclared or rolling-channel floor still redirects (toolchain files in ancestor directories are not read); **cargo also reads every workspace-member manifest** — the `[workspace] members` globs minus `exclude` — and every in-root path-dependency manifest, recursively, reached without crossing a symbolic link and never under `.socket/`, and pins the crate in each one that declares it, so those `/Cargo.toml` files can appear in `rewrittenFiles`. A crate is redirected only when every declaration pins and every other `Cargo.lock` package depending on it is a planned member: one a registry or git crate — or a path package outside the root or behind a link — also depends on is refused `redirect_cargo_transitive_dependents` (a pin reaches only the declarations it sits on), a crate no manifest declares keeps `redirect_cargo_toml_dep_not_found` with a transitive-only detail naming `--mode vendored`, a crate every declaration of which requires another version (no requirement accepts the patched version) is refused `redirect_cargo_toml_dep_unrewritable`, and so is a requirement that also matches another locked version of the crate — each a transactional skip, never recorded or attested. With NO `Cargo.lock` there is no resolved graph to ask, so the dependents question is answered from the manifests instead: a crate declared beside any other dependency — anything but a path dependency on a manifest this run also pins, or a `workspace = true` inheritor of a table it scans — or beside a workspace member this run did not read (a `members` glob, or a member outside the project or behind a symbolic link, which member discovery drops) is refused `redirect_cargo_lockless_dependents`, whose detail names the remedies (commit a lockfile, or `--mode vendored`); a project whose only dependency is the patched crate has nothing that could pull it in and still redirects. All-CRLF manifests, locks and configs are rewritten with CRLF kept (mixed endings keep refusing where the grammar does not match), and `remove` / rollback match the recorded fragments across a later CRLF↔LF checkout conversion), `composer.lock`, `nuget.config` / `packages.lock.json` (plus, v5.0 #353/#514, every lock a project under the root restores into: a member project's `packages.lock.json`, a per-project `packages..lock.json`, a literal `NuGetLockFilePath` — each pinned with the root config; a `NuGetLockFilePath` it cannot evaluate warns `redirect_nuget_lock_path_unresolved` and a project tree it cannot list warns `redirect_nuget_lock_unreadable`, both skipping the nuget redirect with nothing written), `Gemfile` / `Gemfile.lock`, `pom.xml` (+ `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` for maven Trusted Checksums merge, and, for a Gradle build, every settings, build, `buildSrc`, included-build, applied and plugin-source script, version catalog and lock file the script graph reaches, plus `gradle/verification-metadata.xml`, `gradle/wrapper/gradle-wrapper.properties` and the owned `.socket/gradle/` files), and the sbt build files (`socket-patch.sbt`, `socket-patch-vendor.sbt`, `build.sbt`, `project/build.properties`, `.sbtopts`, `.jvmopts`; `build.sbt.lock` and the Mill / scala-cli build files `build.mill`, `build.mill.yaml`, `build.sc`, `.mill-version`, `project.scala` for their presence only) — read, never edited; `socket-patch.sbt` is the only sbt file hosted mode writes (see **Hosted sbt** below). **npm-family flavor coverage**: package-lock / npm-shrinkwrap (a package the project patches itself with npm ≥ 12.1's native `npm patch` — a root `patchedDependencies` key, or the lock entry's `patched` record — is left on its registry entry in every npm lock, `redirect_npm_patched_dependency_skipped`), pnpm (root OR any nested `*/pnpm-lock.yaml`), yarn classic (a yarn 2+ install migrates a v1 `yarn.lock` and drops its pins, so a run whose v1 lock carries a hosted pin warns `redirect_yarn_classic_berry_migration_risk` — the hosted twin of the vendored `yarn_classic_berry_migration_risk` — unless the root `package.json`, read as advisory input, declares `"packageManager": "yarn@1…"`), **yarn berry** (the pin yarn writes for a root `resolutions` entry: the root `package.json` — edited only beside a berry `yarn.lock` — gains one `"@npm:": ""` selector per locked range (`redirect_yarn_berry_resolution` edits), and only that `yarn.lock` entry is re-keyed `"@"` with the same `resolution:` + `yarnBerry10c0` checksum (`redirect_yarn_berry_entry`), moved to yarn's key order; never an `npm:` locator, whose fetcher sends npm registry auth to the patch host, nor a tarball locator under an `npm:` key, which hardened mode rejects (YN0078). An older release's `npm:::__archiveUrl=` pin is still recognized and is re-pinned on the next run; rollback rebuilds the key from the selectors and drops them. Refused, nothing written: a user-authored `resolutions` entry for the package `redirect_yarn_berry_resolutions_conflict`, no root manifest `redirect_yarn_berry_manifest_missing`, a builtin `patch:` entry wrapping the same descriptor `redirect_yarn_berry_shared_descriptor`, an artifact URL yarn cannot fetch as a tarball `redirect_yarn_berry_artifact_url_unsupported`; cacheKey `10c0` and `.yarnrc.yml compressionLevel 0` gated by `redirect_yarn_berry_cache_unsupported`), and **bun** (text `bun.lock` lockfileVersion 0, 1 or 2 — 0 is the `--save-text-lockfile` opt-in lock of Bun 1.1.39–1.1.45, 1 the 1.2–1.3 default, 2 the 1.4+ default; all three emit one `packages` grammar, so the registry 4-tuple → URL 3-tuple rewrite is version-independent and the lock's own version line is kept. Any other or missing version, or a `packages` section outside bun's single-line grammar, is refused `redirect_bun_lock_unsupported` — the detail is the shared version gate's text (a newer version: update socket-patch, re-locking would reproduce it; no integer: re-lock with Bun ≥ 1.2), identical to the vendored refusal. A version-0 lock holding `workspace:` packages is refused `redirect_bun_workspace_unsupported` (its 2-tuple workspace grammar cannot keep the hosted tuple through a frozen install); the remedy is to delete `bun.lock` and re-run `bun install` with Bun ≥ 1.2, which writes lockfileVersion 1 (accepted). A plain in-place `bun install` bumps the version only when a workspace depends on another workspace (e.g. root → member — the shape the matrix measured); otherwise Bun 1.2.0 keeps version 0 and Bun 1.2.23+ fail to resolve, so the in-place bump is not the documented remedy. Bun lock version, grammar and workspace compatibility are checked before a vendored takeover, including during dry-run: these refusals preserve the existing lock, artifact and vendor ledger. Version-1 and version-2 workspace locks are rewritten, nested versions included. A granted dep with no rewritable entry warns `redirect_bun_entry_not_found` (or `redirect_bun_non_registry_entry_skipped` when the only same-version entry is a user URL / `file:` tarball, #497), a grant without a sha512 `redirect_bun_missing_sha512`; a CRLF lock keeps `\r\n` on the rewritten line, and a hosted URL left by an earlier grant of the same `name@version` is re-pinned in place. **Digest-less re-saves (Bun 1.1.39–1.3.9)**: every text-lock Bun below 1.3.10 re-saves a URL tuple WITHOUT its `sha512` whenever the lock is re-saved for another reason (`bun add`, `bun install` after a package.json or workspace change), leaving the 2-tuple `["name@", {meta}]` — the spec Bun installs from is intact. The CLI treats that spelling as its own wiring: a repeat hosted run counts the dep as redirected (no `redirect_bun_entry_not_found`) and HEALS the line back to the 3-tuple with the current `sha512`, recording the heal as a further `redirect_bun_lock_package` edit whose `original` is the 2-tuple (a stale URL is re-pinned from either spelling); `rollback`, scoped `rollback ` / `remove ` and the vendored takeover accept the digest-less spelling of a recorded `new` line (same key, spec and meta, only the trailing `"sha512-…"` missing) and restore the recorded original over it, so the chain always unwinds to the pristine registry line. Anything else — another uuid/token, another version, a re-laid meta object — is still drift. **Native `bun.lockb`**: when no text `bun.lock` exists, binary format versions 1, 2 and 3 are read and rewritten directly. Socket Patch does not invoke Bun or convert the project to a text lockfile. Exact matching package records are rewritten to hosted tarballs with the granted integrity, preserving dependency resolution IDs, workspace/dependency topology and unrelated package metadata; binary pointers and the package metadata hash are updated. Per-package `redirect_bun_lockb_package` snapshots support scoped rollback, repeat runs, superseding grants and hosted ↔ vendored takeover. A regular binary lock is discoverable even with no Bun runtime or `node_modules`; a dry run previews the same binary edits without writing them. A malformed, unreadable, unsupported or unverified binary structure is `redirect_bun_lockb_invalid` (exit 0, `redirected: 0`), and it refuses the npm rewrite before any takeover or sibling npm-family lock mutation. A symlinked binary write target is `redirect_symlinked_file_unsupported` (exit 1, including dry-run). `bun.lock` wins when both spellings exist. Binary-only projects do not receive `redirect_npm_no_lockfile`. Measured boundaries and the real-Bun matrix: `docs/testing/bun-compatibility.md`), and **vlt** (`vlt-lock.json` without `lockfileVersion`, `0` or `1`; see the vlt hosted-mode contract below). **Rush monorepos**: when `rush.json` is present the rewriter also reads `common/config/rush/pnpm-lock.yaml` and each `common/config/subspaces//pnpm-lock.yaml` (sorted for determinism) under their repo-relative keys and repoints them in place; editing them emits `redirect_rush_repo_state_stale` when the `repo-state.json` beside a rewritten lock exists (`common/config/rush/repo-state.json` for the common lock, `common/config/subspaces//repo-state.json` for a subspace lock; the `pnpmShrinkwrapHash` desync is refreshed by `rush update`, which the redirect survives), and `redirect_pnpm_trust_lockfile` carries the Rush pnpm >=11 install remedy (see the trust paragraph above). **maven** is fail-closed via version suffixing: a `mavenSuffixedVersion` + `mavenPomSha256` override pins the Socket-only `-socket.` by rewriting the literal `` (`redirect_maven_dep_version`) or adding a `` entry (`redirect_maven_dep_management_added`), plus optional Trusted Checksums (`redirect_maven_trusted_checksums`, conflicts as `redirect_maven_trusted_checksums_conflict`; when `.mvn/wrapper/maven-wrapper.properties` pins a Maven older than 3.9.4, which ignores those files, the additive warning `redirect_maven_trusted_checksums_unenforced`; a grant sha256 that is not 64 hex digits writes no checksum line, `redirect_maven_trusted_checksums_invalid_hash`); a `${property}` version is refused (`redirect_maven_dep_unpinned`), a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`; each such subdirectory's `pom.xml` is read for this, never edited) is refused whole with `redirect_maven_multimodule_unsupported`: `pom.xml` and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the pom pins it too), since a module's own literal `` would shadow a root pin (use `--mode vendored`; `vex` omits a hosted pin in a reactor root as `vex_maven_reactor_root`), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped when a variant other than `sources` / `javadoc` names the patched release), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`; the dep is 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 pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). **gradle** (v5.0) is automated wiring, no longer a pasted snippet: the owned settings script `.socket/gradle/socket-patch.hosted.settings.gradle` with its index `.socket/gradle/hosted-index.tsv`, one apply line per build's settings file, every lock entry of the GA moved to the suffixed version, and the suffixed component in an existing `gradle/verification-metadata.xml`. A refused dep writes nothing and keeps `redirect_gradle_manual_snippet` as its fallback; same-GAV grants are refused (`redirect_gradle_same_gav_unsupported`). Rules, refusals and codes: [Gradle builds](#gradle-builds-v50). +The rewriter reads a fixed set of candidate files from the project root: the npm-family locks (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `shrinkwrap.yaml`, `yarn.lock`, plus `.yarnrc.yml` for the berry cache-config gate, `bun.lock` / `bun.lockb`, and `vlt-lock.json` with `vlt.json` and `node_modules/.vlt-lock.json` read only), `requirements.txt` / `uv.lock` / `Pipfile.lock` (pipfile-spec 6; see the Pipenv section below) / `poetry.lock` (every Poetry lock generation from 1.0 on — the 0.12 `[metadata.hashes]` layout is refused because that installer ignores URL sources; a Poetry < 1.4 writer additionally gets `redirect_poetry_stale_install_risk`, see `docs/testing/poetry-compatibility.md`) / `pdm.lock` (PDM lock formats `2` and `4.3`–`4.5.1`; the identity-losing `3.1` / `4.0`–`4.2` formats and unknown future formats are refused with `redirect_pdm_refused`, and a lock-format-`2` writer additionally gets `redirect_pdm_legacy_sync_required`, see `docs/testing/pdm-compatibility.md`; when `uv.lock` or `poetry.lock` sits beside it they drive and `pdm.lock` is left alone), `Cargo.toml` / `Cargo.lock` / `.cargo/config.toml` (plus the legacy extensionless `.cargo/config` — cargo reads that spelling in preference when both exist, so the managed `[registries.…]` block is written into whichever one is present; the hosted redirect is a `sparse+` registry, which cargo loads only from **1.68**, so `rust-toolchain.toml` / `rust-toolchain` are read too (never edited) and a project whose declared floor — the lowest `rust-version` of the root and the member manifests read here (a `rust-version.workspace = true` inheritor reads `[workspace.package]`), else the channel rustup picks from the root (the legacy `rust-toolchain` over `rust-toolchain.toml`; a dated `nightly-`/`beta-YYYY-MM-DD` maps to its release train) — is below 1.68 is refused `redirect_cargo_old_cargo` per crate (nothing written, an earlier run's pins left in place with the `rollback` that drops them named; `--mode vendored` builds on cargo 1.41+), while an undeclared or rolling-channel floor still redirects (toolchain files in ancestor directories are not read); **cargo also reads every workspace-member manifest** — the `[workspace] members` globs minus `exclude` — and every in-root path-dependency manifest, recursively, reached without crossing a symbolic link and never under `.socket/`, and pins the crate in each one that declares it, so those `/Cargo.toml` files can appear in `rewrittenFiles`. A crate is redirected only when every declaration pins and every other `Cargo.lock` package depending on it is a planned member: one a registry or git crate — or a path package outside the root or behind a link — also depends on is refused `redirect_cargo_transitive_dependents` (a pin reaches only the declarations it sits on), a crate no manifest declares keeps `redirect_cargo_toml_dep_not_found` with a transitive-only detail naming `--mode vendored`, a crate every declaration of which requires another version (no requirement accepts the patched version) is refused `redirect_cargo_toml_dep_unrewritable`, and so is a requirement that also matches another locked version of the crate — each a transactional skip, never recorded or attested. With NO `Cargo.lock` there is no resolved graph to ask, so the dependents question is answered from the manifests instead: a crate declared beside any other dependency — anything but a path dependency on a manifest this run also pins, or a `workspace = true` inheritor of a table it scans — or beside a workspace member this run did not read (a `members` glob, or a member outside the project or behind a symbolic link, which member discovery drops) is refused `redirect_cargo_lockless_dependents`, whose detail names the remedies (commit a lockfile, or `--mode vendored`); a project whose only dependency is the patched crate has nothing that could pull it in and still redirects. All-CRLF manifests, locks and configs are rewritten with CRLF kept (mixed endings keep refusing where the grammar does not match), and `remove` / rollback match the recorded fragments across a later CRLF↔LF checkout conversion), `composer.lock`, `nuget.config` / `packages.lock.json` (plus, v5.0 #353/#514, every lock a project under the root restores into: a member project's `packages.lock.json`, a per-project `packages..lock.json`, a literal `NuGetLockFilePath` — each pinned with the root config; a `NuGetLockFilePath` it cannot evaluate warns `redirect_nuget_lock_path_unresolved` and a project tree it cannot list warns `redirect_nuget_lock_unreadable`, both skipping the nuget redirect with nothing written), `Gemfile` / `Gemfile.lock`, `pom.xml` (+ `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` for maven Trusted Checksums merge, and, for a Gradle build, every settings, build, `buildSrc`, included-build, applied and plugin-source script, version catalog and lock file the script graph reaches, plus `gradle/verification-metadata.xml`, `gradle/wrapper/gradle-wrapper.properties` and the owned `.socket/gradle/` files), and the sbt build files (`socket-patch.sbt`, `socket-patch-vendor.sbt`, `build.sbt`, `project/build.properties`, `.sbtopts`, `.jvmopts`; `build.sbt.lock` and the Mill / scala-cli build files `build.mill`, `build.mill.yaml`, `build.sc`, `.mill-version`, `project.scala` for their presence only) — read, never edited; `socket-patch.sbt` is the only sbt file hosted mode writes (see **Hosted sbt** below). **npm-family flavor coverage**: package-lock / npm-shrinkwrap (a package the project patches itself with npm ≥ 12.1's native `npm patch` — a root `patchedDependencies` key, or the lock entry's `patched` record — is left on its registry entry in every npm lock, `redirect_npm_patched_dependency_skipped`), pnpm (root OR any nested `*/pnpm-lock.yaml`), yarn classic (a yarn 2+ install migrates a v1 `yarn.lock` and drops its pins, so a run whose v1 lock carries a hosted pin warns `redirect_yarn_classic_berry_migration_risk` — the hosted twin of the vendored `yarn_classic_berry_migration_risk` — unless the root `package.json`, read as advisory input, declares `"packageManager": "yarn@1…"`), **yarn berry** (the pin yarn writes for a root `resolutions` entry: the root `package.json` — edited only beside a berry `yarn.lock` — gains one `"@npm:": ""` selector per locked range (`redirect_yarn_berry_resolution` edits), and only that `yarn.lock` entry is re-keyed `"@"` with the same `resolution:` + `yarnBerry10c0` checksum (`redirect_yarn_berry_entry`), moved to yarn's key order; never an `npm:` locator, whose fetcher sends npm registry auth to the patch host, nor a tarball locator under an `npm:` key, which hardened mode rejects (YN0078). An older release's `npm:::__archiveUrl=` pin is still recognized and is re-pinned on the next run; rollback rebuilds the key from the selectors and drops them. Refused, nothing written: a user-authored `resolutions` entry for the package `redirect_yarn_berry_resolutions_conflict`, no root manifest `redirect_yarn_berry_manifest_missing`, a builtin `patch:` entry wrapping the same descriptor `redirect_yarn_berry_shared_descriptor`, an artifact URL yarn cannot fetch as a tarball `redirect_yarn_berry_artifact_url_unsupported`; cacheKey `10c0` and `.yarnrc.yml compressionLevel 0` gated by `redirect_yarn_berry_cache_unsupported`), and **bun** (text `bun.lock` lockfileVersion 0, 1 or 2 — 0 is the `--save-text-lockfile` opt-in lock of Bun 1.1.39–1.1.45, 1 the 1.2–1.3 default, 2 the 1.4+ default; all three emit one `packages` grammar, so the registry 4-tuple → URL 3-tuple rewrite is version-independent and the lock's own version line is kept. Any other or missing version, or a `packages` section outside bun's single-line grammar, is refused `redirect_bun_lock_unsupported` — the detail is the shared version gate's text (a newer version: update socket-patch, re-locking would reproduce it; no integer: re-lock with Bun ≥ 1.2), identical to the vendored refusal. A version-0 lock holding `workspace:` packages is refused `redirect_bun_workspace_unsupported` (its 2-tuple workspace grammar cannot keep the hosted tuple through a frozen install); the remedy is to delete `bun.lock` and re-run `bun install` with Bun ≥ 1.2, which writes lockfileVersion 1 (accepted). A plain in-place `bun install` bumps the version only when a workspace depends on another workspace (e.g. root → member — the shape the matrix measured); otherwise Bun 1.2.0 keeps version 0 and Bun 1.2.23+ fail to resolve, so the in-place bump is not the documented remedy. Bun lock version, grammar and workspace compatibility are checked before a vendored takeover, including during dry-run: these refusals preserve the existing lock, artifact and vendor ledger. Version-1 and version-2 workspace locks are rewritten, nested versions included. A granted dep with no rewritable entry warns `redirect_bun_entry_not_found` (or `redirect_bun_non_registry_entry_skipped` when the only same-version entry is a user URL / `file:` tarball, #497), a grant without a sha512 `redirect_bun_missing_sha512`; a CRLF lock keeps `\r\n` on the rewritten line, and a hosted URL left by an earlier grant of the same `name@version` is re-pinned in place. **Digest-less re-saves (Bun 1.1.39–1.3.9)**: every text-lock Bun below 1.3.10 re-saves a URL tuple WITHOUT its `sha512` whenever the lock is re-saved for another reason (`bun add`, `bun install` after a package.json or workspace change), leaving the 2-tuple `["name@", {meta}]` — the spec Bun installs from is intact. The CLI treats that spelling as its own wiring: a repeat hosted run counts the dep as redirected (no `redirect_bun_entry_not_found`) and HEALS the line back to the 3-tuple with the current `sha512`, recording the heal as a further `redirect_bun_lock_package` edit whose `original` is the 2-tuple (a stale URL is re-pinned from either spelling); `rollback`, scoped `rollback ` / `remove ` and the vendored takeover accept the digest-less spelling of a recorded `new` line (same key, spec and meta, only the trailing `"sha512-…"` missing) and restore the recorded original over it, so the chain always unwinds to the pristine registry line. Anything else — another uuid/token, another version, a re-laid meta object — is still drift. **Native `bun.lockb`**: when no text `bun.lock` exists, binary format versions 1, 2 and 3 are read and rewritten directly. Socket Patch does not invoke Bun or convert the project to a text lockfile. Exact matching package records are rewritten to hosted tarballs with the granted integrity, preserving dependency resolution IDs, workspace/dependency topology and unrelated package metadata; binary pointers and the package metadata hash are updated. Per-package `redirect_bun_lockb_package` snapshots support scoped rollback, repeat runs, superseding grants and hosted ↔ vendored takeover. A regular binary lock is discoverable even with no Bun runtime or `node_modules`; a dry run previews the same binary edits without writing them. A malformed, unreadable, unsupported or unverified binary structure is `redirect_bun_lockb_invalid` (exit 0, `redirected: 0`), and it refuses the npm rewrite before any takeover or sibling npm-family lock mutation. A symlinked binary write target is `redirect_symlinked_file_unsupported` (exit 1, including dry-run). `bun.lock` wins when both spellings exist. Binary-only projects do not receive `redirect_npm_no_lockfile`. Measured boundaries and the real-Bun matrix: `docs/testing/bun-compatibility.md`), and **vlt** (`vlt-lock.json` without `lockfileVersion`, `0` or `1`; see the vlt hosted-mode contract below). **Rush monorepos**: when `rush.json` is present the rewriter also reads `common/config/rush/pnpm-lock.yaml` and each `common/config/subspaces//pnpm-lock.yaml` (sorted for determinism) under their repo-relative keys and repoints them in place; editing them emits `redirect_rush_repo_state_stale` when the `repo-state.json` beside a rewritten lock exists (`common/config/rush/repo-state.json` for the common lock, `common/config/subspaces//repo-state.json` for a subspace lock; the `pnpmShrinkwrapHash` desync is refreshed by `rush update`, which the redirect survives), and `redirect_pnpm_trust_lockfile` carries the Rush pnpm >=11 install remedy (see the trust paragraph above). **maven** is fail-closed via version suffixing: a `mavenSuffixedVersion` + `mavenPomSha256` override pins the Socket-only `-socket.` by rewriting the literal `` (`redirect_maven_dep_version`) or adding a `` entry (`redirect_maven_dep_management_added`), plus optional Trusted Checksums (`redirect_maven_trusted_checksums`, conflicts as `redirect_maven_trusted_checksums_conflict`; when `.mvn/wrapper/maven-wrapper.properties` pins a Maven older than 3.9.4, which ignores those files, the additive warning `redirect_maven_trusted_checksums_unenforced`; a grant sha256 that is not 64 hex digits writes no checksum line, `redirect_maven_trusted_checksums_invalid_hash`); a `${property}` version is refused (`redirect_maven_dep_unpinned`), a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`; each such subdirectory's `pom.xml` is read for this, never edited) is refused whole with `redirect_maven_multimodule_unsupported`: `pom.xml` and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the pom pins it too), since a module's own literal `` would shadow a root pin (use `--mode vendored`; `vex` omits a hosted pin in a reactor root as `vex_maven_reactor_root`), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped, with nothing written, when a variant other than `sources` / `javadoc`, live or inside ``, may resolve any version but the suffixed pin — the patched release, another one, a `${property}` a profile moves, or no version in the pom once its classifier-keyed `` (a profile's too) is consulted — since `vex` would never attest that pin: `vex_maven_classifier_unpatched`), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`): when any version it may resolve — its own, or what its own profile's or any combination of profiles' `` make of it, read as `vex` reads it — is not the suffixed pin, the dep is refused with nothing written, since it overrides the pin whenever that profile is active and `vex` would never attest it (a profile `` entry only when management governs the pin, i.e. no live direct declaration carries a version); a versionless one takes the pin, and the dep is also skipped when a profile holds its only declaration, a `${property}` groupId / artifactId resolved from the pom's own `` before matching (one the pom does not define, which may be the patched GA and whose own version would then win, refuses the dep with nothing written: `redirect_maven_coordinate_unresolved`), and a `${property}` groupId / artifactId some profile's `` (or several profiles' together) redefine so that the declaration a pin would go into names another package, or another declaration names the GA's main jar at another version (or one of its executable classifier copies, a `test-jar` included), refuses the dep with nothing written too (`redirect_maven_profile_coordinates_unpatched`): `vex` would never attest that pin (`vex_maven_profile_unpatched`), and a pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). **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. @@ -581,7 +581,7 @@ Recognition rules that hold for every ecosystem: * **Patch hosts.** A hosted reference counts only on `https://patch.socket.dev` or the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin, with no userinfo. The uuid is the URL's LAST canonical-uuid path segment, because grant tokens may themselves be uuid-shaped. The Go module prefix is fixed. `socket-patch-` registry / repository / source names count only through a pin. For a URL on any other host, see **Patch hosts** above. * **Pins, not definitions.** A registry, index or source *definition* alone (cargo `[registries]`, nuget ``, pom ``, uv index tables, `.npmrc`) never makes a reference, because it survives a reverted pin. Sections the package manager ignores are not read: npm's v2 `dependencies` mirror, a `.cargo/config.toml` shadowed by `.cargo/config`. A Socket pin inside a maven `` is diagnosed, never a reference. * **Contested locks.** When one lock wires a package to a patch and another lock resolves the same `name@version` from a non-Socket source, the build's bytes depend on which package manager runs. The reference is then dropped with a `patched_ref_unattributable` diagnostic naming both files. This applies across npm / pnpm / yarn / bun and across uv / pylock / poetry / pdm / Pipfile.lock / requirements. PEP 723 script locks neither contest nor are contested. The root `requirements.txt` and its in-root `-r` includes count as one lock here: pip reads them as one requirement set, where a direct reference wins over a compatible `==` pin of the same version in another file of the set (#1086). A PyPI version matches under PEP 440 equality, so a requirements line pinned in any spelling that can only install the wired release (`==1.2.3.0`, `==v1.2.3`, `===1.2.3`) contests it like `==1.2.3` does; a range or wildcard (`~=1.2.3`, `==1.2.*`) does not (#1602). A **bundled** npm copy (`inBundle: true`, or v1 `bundled: true`, beneath a dependency that bundles it; the root project's own bundles install from the lock, #1618) of the same `name@version` contests the reference too, in the same lock, in the other npm lock of a shrinkwrap/package-lock pair, or in any other lock. npm unpacks it from the parent package's tarball, so no rewire reaches it and it stays unpatched. Bun and vlt unpack bundled copies the same way (#469, #471). pnpm unpacks bundled copies too, but its lock cannot tie one to a reference (see **Unattested references** below). For Bun, that is a `bun.lock` entry whose meta is `{ "bundled": true }`, or a `bun.lockb` record that a dependency edge with the `bundled` behavior bit reaches, including one Bun shares with a regular install. Such an entry is never a reference, and it contests the reference the same way. For vlt, the lock records no node for a bundled copy, so the copy is found in the installed store: a real package directory inside a store package's own `node_modules`. yarn classic's `yarn.lock` records nothing about bundled copies either (#758), so for a lock with a Socket wiring they are found in the installed `node_modules`: each package a parent's `bundleDependencies` / `bundledDependencies` names inside the parent's own `node_modules`, the dependencies of those beside them, and everything nested under them. Such a copy contests the reference in `yarn.lock` (the diagnostic names the parent's lock entry and the copy's directory); a lock-only `vex` with no `node_modules` can't see it. Hosted and vendored scans skip these copies with `redirect_bun_bundled_instance_skipped` / `redirect_vlt_bundled_instance_skipped` / `vendor_bundled_instance_skipped`, and a yarn classic hosted scan names one with `redirect_copy_unpatched`. When a bundled copy is the only instance, vendoring refuses with `vendor_lock_entry_not_rewritable`. A reference withheld only because such an unreachable copy installs beside it (a bundled npm / Bun / vlt copy, an npm copy beneath a `hasShrinkwrap` package (#753) or one npm installs from a git / url / `file:` spec, or a yarn classic git or `file:` directory block of the same `name@version`) is still the rewriter's own wiring of exactly one package version: it is never attested, but `rollback`, `remove`, `list` and the hosted → vendored takeover treat it as an ordinary hosted pin and restore its upstream registry entry (#828), rather than refusing it with `hosted_wiring_contested`. Another entry of the **same** npm, Bun or yarn lock that resolves the wired `name@version` from a non-Socket source (for example a workspace member added after the rewire, then `npm install` / `bun install` / `yarn install`; for yarn berry, a registry locator such as `left-pad@npm:1.3.0` beside the hosted `…::__archiveUrl=` one) contests the reference too (#588). The package manager installs both entries, and that copy stays unpatched. Re-running `scan` / `vendor` rewires every copy. -* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Ten cases besides Gradle's (`vex_gradle_lock_above_base`) and NuGet's (`vex_nuget_lock_other_version`, see the table above); one of them, **hosted sbt pins a build bypasses** (`vex_sbt_pin_bypassed`), is under **Hosted sbt** above: **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactor roots** (`vex_maven_reactor_root`): a hosted pin in a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers (see the hosted Maven rewriter), is omitted, because a module's own literal `` overrides a root pin and module poms are not read (#261); hosted scan refuses such roots (`redirect_maven_multimodule_unsupported`), so this only covers pins an older release wrote. **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a live, non-profile classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build) resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier, or no version in the root pom — the pin is omitted. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep when an executable copy names the patched release. **pnpm branch locks** (`vex_pnpm_git_branch_lockfile`): with `gitBranchLockfile` on, pnpm installs a git branch from its own `pnpm-lock..yaml` (the **pnpm per-branch locks** state above), which no wiring reaches. `vex` does not decide whether the setting is on: the presence of any branch lock (at the root, or in a workspace member that installs from its own lock under `sharedWorkspaceLockfile: false`, read from the project's files and never from the environment) omits every reference of the root pnpm lock (`pnpm-lock.yaml`, or `shrinkwrap.yaml` without it) and of each member's own lock, hosted and vendored alike, whatever `gitBranchLockfile` or pnpm's `lockfile` setting says (#556; deterministic and fail-closed). This is checked only when a root or member pnpm lock wires a patch. Hosted mode refuses every pnpm pin when the setting is on and vendored mode refuses the project, so this also covers wiring written before the branch lock appeared. The run warning names the branch lock in the marked lock's own directory. Rush locks are not affected. **Self-patched npm and Bun packages** (`vex_npm_patched_dependency`): a reference in `package-lock.json` / `npm-shrinkwrap.json` / `bun.lock` / `bun.lockb` to a package the project patches itself is omitted, by the hosted rewriters' own per-dependency rule (`redirect_npm_patched_dependency_skipped`, #711; `redirect_bun_patched_dependency_skipped`, #367): a root `package.json` `patchedDependencies` key for its `name@version`, its bare name, or `name@` of any tarball (npm and Bun alike); for npm also a non-null `patched` record on any present npm lock's entry for that `name@version`; for `bun.lock` also the keys it mirrors (the run warning then names `bun.lock` as the key's source). npm applies the user's diff on top of whatever tarball the lock names and Bun applies it only to the resolution it is keyed on, so both modes leave such a package unwired; this covers pins an earlier release wrote, and an npm one fails `npm ci` with `EPATCHFAILED` until `socket-patch rollback ` restores the registry entry (the remedy says so). A key naming the pinned tarball itself (a patch made on top of the pin) is no conflict for the hosted rewriters, which keep the pin, but the reference is omitted all the same: the user's diff runs over the Socket bytes, never the Socket patch alone; a reference with neither a hosted url nor a vendored tarball is matched by its `name@version` and counts every tarball key. Only a reference that survives the lock contests carries this reason. **Packages patched with pnpm, Yarn or patch-package** (`vex_npm_patched_dependency` too): a reference of any npm-family lock (pnpm, Rush, yarn classic and berry, vlt, npm, Bun; hosted or vendored) to a `name@version` the project patches itself is omitted, read from the project, its declared workspace members and (on disk) the ancestor workspace settings up to the git repository root, by the consent gate's own walk: pnpm's `patchedDependencies` (`package.json`'s `pnpm.patchedDependencies`, `pnpm-workspace.yaml`'s `patchedDependencies`, and the `patchedDependencies` map or a `(patch_hash=…)` key suffix in the reference's own pnpm lock or the root one), a yarn berry `patch:` descriptor outside Yarn's builtin compatibility patches (`package.json`'s dependency maps and `resolutions`, or a `patch:` locator `yarn.lock` resolves, including one wrapping the hosted tarball), or a patch-package file (`patches/+.patch`, or under a `--patch-dir` a `package.json` script names; it counts for every version of ``, since patch-package applies it to whichever version is installed). A key's version may be exact, a range or absent (every version), and metadata that cannot be read (an unparseable `package.json`, a `--patch-dir` the script computes) omits every npm reference. This is the `user_patch_conflict` consent gate's evidence (see [Existing project patches](#existing-project-patches)) minus native npm / Bun and the other ecosystems, and the evidence the in-memory hosted engine withholds a package by. The package manager (or the postinstall) applies the user's diff on top of whatever tarball the lock names, so the install never runs the Socket patch alone: the reference is omitted even when an `--allow-patch-conflicts` run wired it, for as long as the patch is declared. Yarn classic and vlt have no patch mechanism of their own (vlt's `vlt.json` `modifiers` rewrite specs, not contents), so patch-package is what is read for them. npm's and Bun's own top-level `patchedDependencies` are judged by the rule above, not here. **Go workspaces** (`go_workspace_override`): a hosted or vendored Go `replace` that the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects, by the same check hosted and vendored modes run before writing one (`redirect_golang_workspace_conflict`, `vendor_go_workspace_conflict`), is omitted under the reason `vex`'s own go.mod gate reports. So is a replace in the root `go.work` while go builds another one. **Unpinned Cargo declarations** (`vex_cargo_unpinned_declaration`): cargo resolves each source on its own, so when one declaration of a crate pins it to `socket-patch-` but another — the root `Cargo.toml`'s or a workspace member's, read as hosted scan reads them — is not pinned, with a version requirement that may select the locked patched version, that declaration builds a separate, unpatched copy, possibly of the very version the pin covers. Not pinned means crates.io or another registry that no Socket `[patch.]` registry entry redirects, a `registry-index`, a path or git — the last three even beside `registry = "socket-patch-"`, which they override (hosted scan's own pinned check). The `Cargo.lock` reference is omitted, naming the unpinned declaration's manifest. Hosted scan pins every declaration, so this is a partial revert or a hand edit; the warning says whether re-running `scan` pins it again (a crates.io declaration whose requirement matches no other locked version of the crate) or cannot (`redirect_cargo_toml_dep_unrewritable`: roll the patch back or change the declaration). A declaration whose requirement excludes the patched version (cargo resolves it to another version), and a `[workspace.dependencies]` entry no manifest inherits, do not withhold the statement. When the lock already holds a same-version copy from another source, the reference is withheld as an unpatched lock copy instead. A declaration pinned to ANOTHER Socket patch, which the lock does not resolve the crate from, adds that patch's `Cargo.toml` reference, so the package is gated as `wiring_conflict`. **Vendored Cargo copies a `[patch]` does not reach** (`vex_cargo_patch_bypassed`): a `[patch.]` entry replaces the crate only in declarations from ``, and `vendor` writes `[patch.crates-io]`. So a vendored reference is omitted when a live declaration of the crate (the root `Cargo.toml`'s or a workspace member's) names another registry, a `registry-index` or a git repository, with a version requirement that may select the patched version, unless a `[patch]` table for its source points at the same copy (`[patch.]` for a registry dependency, `[patch.""]` for a `registry-index` one, `[patch.""]` for a git one; URLs compare as cargo canonicalizes them: the host's case, a lock's `registry+` prefix, one trailing `/` and a `.git` suffix ignored, a GitHub URL case-insensitive, a `sparse+` index another source than the git one, and the crates.io git index is crates.io); cargo builds that declaration's own, unpatched copy. Workspace members are read for this whenever the root manifest or the project cargo config wires a Socket copy through `[patch]`, whatever the lock says. It is also omitted when `Cargo.lock` locks the crate at exactly the patched version from any source (a registry, crates.io included, or git) beside the vendored copy; the warning names that lock entry. A path declaration (the user's own fork) does not withhold the statement. Only `[patch]` entries cargo honors count: a manifest entry the project config or a crates.io URL table replaces covers nothing. The warning ends with the remedy for its evidence: for a declaration, re-running `vendor` does not help (declare the crate from crates.io there, point a `[patch]` table for its source at the copy, or roll the patch back); for a stale lock entry a `[patch]` table at the copy redirects (crates.io under `[patch.crates-io]`, or a git repository under its own table), re-lock (`cargo update -p `, or re-run `vendor` for crates.io); for another lock entry, `cargo tree -i @` names the dependency that declares it. +* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Twelve cases besides Gradle's (`vex_gradle_lock_above_base`) and NuGet's (`vex_nuget_lock_other_version`, see the table above); one of them, **hosted sbt pins a build bypasses** (`vex_sbt_pin_bypassed`), is under **Hosted sbt** above: **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactor roots** (`vex_maven_reactor_root`): a hosted pin in a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers (see the hosted Maven rewriter), is omitted, because a module's own literal `` overrides a root pin and module poms are not read (#261); hosted scan refuses such roots (`redirect_maven_multimodule_unsupported`), so this only covers pins an older release wrote. **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA (or one whose `` implies a classifier or carries code, such as `test-jar`) is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build), live or inside ``, resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier (a profile's overriding the live one), or no version in the root pom — the pin is omitted. A pre-v5 single-pom vendored repository holds only the main jar, so any such copy omits its reference. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep, writing nothing, when an executable copy may resolve anything but the suffixed pin (so it never writes a pin this rule withholds). **Maven profile declarations** (`vex_maven_profile_unpatched`): a `` declaration of a pinned GA's main jar in the root `pom.xml` at any version other than the pin (the base release, another release, a `${property}` the pom does not resolve) overrides the pin whenever that profile is active, so the reference is omitted. A profile `` entry always counts; a profile `` entry counts only when management governs the pin (no direct `` outside ``), since a direct literal version beats management. A declaration without a `` takes the live pin, and a `pom` (or `java-source` / `javadoc`) typed one carries no code; neither withholds the statement. Activation is not evaluated: every profile counts, as in vendored mode, which rewrites profile declarations too; hosted scan leaves them as written and writes no pin they bypass (`redirect_maven_profile_dependency_unpatched`). A pin spelled through a property counts the same way: a `${property}` `` is interpolated through every property it names, the project's own `${project.version}` included (itself often spelled through `${revision}`), at most 16 levels deep (a cycle or an undefined name never resolves to a pin), and when any profile's `` — or any combination of profiles' together, each nested reference read with that combination active, as the vendored planner weighs them too — redefine one of those properties so that it resolves anything other than the pin (or nothing), the reference is omitted too; a `.mvn/maven.config` user property wins over every profile's. A profile declaration reads its own profile's `` first. When more than 8 profiles may change such a version, or a profile's `` cannot be parsed, the reference is omitted (fail closed); the rest of the pom is still read. The statement names the profiles that move the pin and the version they move it to. Coordinates count the same way: when a profile's `` (or several profiles' together, or the profile holding the declaration) redefine a property a `${property}` `` / `` names, so that the declaration carrying the pin names another package (the pin then no longer applies to the patched GA) or another declaration names the patched GA (its main jar, or an executable classifier copy) at a version other than the pin, or as a classifier copy with no version of its own, the reference is omitted; a profile value the pom cannot resolve may name any package, a user property wins over every profile's, and the same 8-profile and unreadable-profile limits fail closed. Each such reading is weighed like a declaration of its own: a retargeted classifier copy (a `test-jar` is the `tests` copy; an explicit `` names the copy whatever the type) by the classifier rule (`vex_maven_classifier_unpatched`, so a pre-v5 vendored repository, which serves only the main jar, is bypassed even at the vendored version), any other non-`jar` type not at all, and a reading that moves the coordinates and the version onto the pin together does not withhold the statement. Hosted scan refuses such a dep (`redirect_maven_profile_coordinates_unpatched`), and vendored mode leaves the declaration as written and does not pin its root (`coordinates_overridden`), except a retargeted classifier copy, which it reports as `classifier_declared` with the root still pinned. The same holds for a pre-v5 single-pom vendored repository, which serves only the original version. **Maven user properties** (`vex_maven_config_override`): Maven resolves a `${property}` `` from `.mvn/maven.config`'s `-D` user properties before the pom's `` (`${project.*}` / `${pom.*}` always come from the model). A pin the pom spells through a property that `.mvn/maven.config` redefines resolves that other version, so the reference is omitted. A Socket version that only a `-D` user property supplies is not `pom.xml` wiring (hosted scan never writes one, and `rollback` / `remove` never edit `.mvn/maven.config`): it is no reference at all, only a diagnostic. **pnpm branch locks** (`vex_pnpm_git_branch_lockfile`): with `gitBranchLockfile` on, pnpm installs a git branch from its own `pnpm-lock..yaml` (the **pnpm per-branch locks** state above), which no wiring reaches. `vex` does not decide whether the setting is on: the presence of any branch lock (at the root, or in a workspace member that installs from its own lock under `sharedWorkspaceLockfile: false`, read from the project's files and never from the environment) omits every reference of the root pnpm lock (`pnpm-lock.yaml`, or `shrinkwrap.yaml` without it) and of each member's own lock, hosted and vendored alike, whatever `gitBranchLockfile` or pnpm's `lockfile` setting says (#556; deterministic and fail-closed). This is checked only when a root or member pnpm lock wires a patch. Hosted mode refuses every pnpm pin when the setting is on and vendored mode refuses the project, so this also covers wiring written before the branch lock appeared. The run warning names the branch lock in the marked lock's own directory. Rush locks are not affected. **Self-patched npm and Bun packages** (`vex_npm_patched_dependency`): a reference in `package-lock.json` / `npm-shrinkwrap.json` / `bun.lock` / `bun.lockb` to a package the project patches itself is omitted, by the hosted rewriters' own per-dependency rule (`redirect_npm_patched_dependency_skipped`, #711; `redirect_bun_patched_dependency_skipped`, #367): a root `package.json` `patchedDependencies` key for its `name@version`, its bare name, or `name@` of any tarball (npm and Bun alike); for npm also a non-null `patched` record on any present npm lock's entry for that `name@version`; for `bun.lock` also the keys it mirrors (the run warning then names `bun.lock` as the key's source). npm applies the user's diff on top of whatever tarball the lock names and Bun applies it only to the resolution it is keyed on, so both modes leave such a package unwired; this covers pins an earlier release wrote, and an npm one fails `npm ci` with `EPATCHFAILED` until `socket-patch rollback ` restores the registry entry (the remedy says so). A key naming the pinned tarball itself (a patch made on top of the pin) is no conflict for the hosted rewriters, which keep the pin, but the reference is omitted all the same: the user's diff runs over the Socket bytes, never the Socket patch alone; a reference with neither a hosted url nor a vendored tarball is matched by its `name@version` and counts every tarball key. Only a reference that survives the lock contests carries this reason. **Packages patched with pnpm, Yarn or patch-package** (`vex_npm_patched_dependency` too): a reference of any npm-family lock (pnpm, Rush, yarn classic and berry, vlt, npm, Bun; hosted or vendored) to a `name@version` the project patches itself is omitted, read from the project, its declared workspace members and (on disk) the ancestor workspace settings up to the git repository root, by the consent gate's own walk: pnpm's `patchedDependencies` (`package.json`'s `pnpm.patchedDependencies`, `pnpm-workspace.yaml`'s `patchedDependencies`, and the `patchedDependencies` map or a `(patch_hash=…)` key suffix in the reference's own pnpm lock or the root one), a yarn berry `patch:` descriptor outside Yarn's builtin compatibility patches (`package.json`'s dependency maps and `resolutions`, or a `patch:` locator `yarn.lock` resolves, including one wrapping the hosted tarball), or a patch-package file (`patches/+.patch`, or under a `--patch-dir` a `package.json` script names; it counts for every version of ``, since patch-package applies it to whichever version is installed). A key's version may be exact, a range or absent (every version), and metadata that cannot be read (an unparseable `package.json`, a `--patch-dir` the script computes) omits every npm reference. This is the `user_patch_conflict` consent gate's evidence (see [Existing project patches](#existing-project-patches)) minus native npm / Bun and the other ecosystems, and the evidence the in-memory hosted engine withholds a package by. The package manager (or the postinstall) applies the user's diff on top of whatever tarball the lock names, so the install never runs the Socket patch alone: the reference is omitted even when an `--allow-patch-conflicts` run wired it, for as long as the patch is declared. Yarn classic and vlt have no patch mechanism of their own (vlt's `vlt.json` `modifiers` rewrite specs, not contents), so patch-package is what is read for them. npm's and Bun's own top-level `patchedDependencies` are judged by the rule above, not here. **Go workspaces** (`go_workspace_override`): a hosted or vendored Go `replace` that the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects, by the same check hosted and vendored modes run before writing one (`redirect_golang_workspace_conflict`, `vendor_go_workspace_conflict`), is omitted under the reason `vex`'s own go.mod gate reports. So is a replace in the root `go.work` while go builds another one. **Unpinned Cargo declarations** (`vex_cargo_unpinned_declaration`): cargo resolves each source on its own, so when one declaration of a crate pins it to `socket-patch-` but another — the root `Cargo.toml`'s or a workspace member's, read as hosted scan reads them — is not pinned, with a version requirement that may select the locked patched version, that declaration builds a separate, unpatched copy, possibly of the very version the pin covers. Not pinned means crates.io or another registry that no Socket `[patch.]` registry entry redirects, a `registry-index`, a path or git — the last three even beside `registry = "socket-patch-"`, which they override (hosted scan's own pinned check). The `Cargo.lock` reference is omitted, naming the unpinned declaration's manifest. Hosted scan pins every declaration, so this is a partial revert or a hand edit; the warning says whether re-running `scan` pins it again (a crates.io declaration whose requirement matches no other locked version of the crate) or cannot (`redirect_cargo_toml_dep_unrewritable`: roll the patch back or change the declaration). A declaration whose requirement excludes the patched version (cargo resolves it to another version), and a `[workspace.dependencies]` entry no manifest inherits, do not withhold the statement. When the lock already holds a same-version copy from another source, the reference is withheld as an unpatched lock copy instead. A declaration pinned to ANOTHER Socket patch, which the lock does not resolve the crate from, adds that patch's `Cargo.toml` reference, so the package is gated as `wiring_conflict`. **Vendored Cargo copies a `[patch]` does not reach** (`vex_cargo_patch_bypassed`): a `[patch.]` entry replaces the crate only in declarations from ``, and `vendor` writes `[patch.crates-io]`. So a vendored reference is omitted when a live declaration of the crate (the root `Cargo.toml`'s or a workspace member's) names another registry, a `registry-index` or a git repository, with a version requirement that may select the patched version, unless a `[patch]` table for its source points at the same copy (`[patch.]` for a registry dependency, `[patch.""]` for a `registry-index` one, `[patch.""]` for a git one; URLs compare as cargo canonicalizes them: the host's case, a lock's `registry+` prefix, one trailing `/` and a `.git` suffix ignored, a GitHub URL case-insensitive, a `sparse+` index another source than the git one, and the crates.io git index is crates.io); cargo builds that declaration's own, unpatched copy. Workspace members are read for this whenever the root manifest or the project cargo config wires a Socket copy through `[patch]`, whatever the lock says. It is also omitted when `Cargo.lock` locks the crate at exactly the patched version from any source (a registry, crates.io included, or git) beside the vendored copy; the warning names that lock entry. A path declaration (the user's own fork) does not withhold the statement. Only `[patch]` entries cargo honors count: a manifest entry the project config or a crates.io URL table replaces covers nothing. The warning ends with the remedy for its evidence: for a declaration, re-running `vendor` does not help (declare the crate from crates.io there, point a `[patch]` table for its source at the copy, or roll the patch back); for a stale lock entry a `[patch]` table at the copy redirects (crates.io under `[patch.crates-io]`, or a git repository under its own table), re-lock (`cargo update -p `, or re-run `vendor` for crates.io); for another lock entry, `cargo tree -i @` names the dependency that declares it. * **Shrinkwrap without a twin (#899).** npm >= 12 never reads `npm-shrinkwrap.json`: on a project whose only npm lock is the shrinkwrap it resolves the tree from the registry and writes a fresh `package-lock.json`, so a Socket reference there reaches npm <= 11 only. The reference is still discovered, so `list`, `rollback` and `remove` manage it, but `vex` omits the patch (`vex_npm_shrinkwrap_only`, as a run warning and as the `failed[].reason`). A `package-lock.json` beside it (wired the same way) makes it attestable again. Hosted and vendored runs still rewire the shrinkwrap and warn `redirect_npm_shrinkwrap_only` / `vendor_npm_shrinkwrap_only`. * **Lockless pins.** With no lock to name a version, a `Cargo.toml` pin (every declaration on `socket-patch-`, that registry defined on the patch host for the same uuid) or an exclusive nuget exact-id mapping is never a reference on its own, so v5.0 does not attest it (nor does `list` show it, or `rollback` / `remove` restore it — restore those files from version control). Only a pre-v5 redirect-ledger record naming a version the pin admits keeps it live. For Cargo, declarations are read as for a locked pin (**Unpinned Cargo declarations**): one that is no pin admits nothing, and its requirement (any version, without one) is excluded from the pin; a `[workspace.dependencies]` template no manifest inherits is no declaration at all. The same holds for a gem wired only in the `Gemfile` (the pre-bundler-2.6 mixed state, lock not converged). @@ -2737,7 +2737,9 @@ match it, withholds the statement: | `vex_deno_lock_copy` | run warning and `failed[].reason` | An npm pin is wired, but `deno.lock` locks the same `name@version`, which `deno install` installs without the wiring; no statement while it does. `vendor --check` and `scan` still treat the wiring as live. | | `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven pin sits in a root `pom.xml` that declares `` / `` (a profile's included), where a module's own literal `` overrides it; only the root pom is read, so no statement (#261). `list`, `rollback` and `remove` still find the pin. | | `go_workspace_override` | run warning and `failed[].reason` | A hosted or vendored Go `replace` is wired, but the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects it, or go builds another `go.work` than the root's that holds it; no statement while it does. `list`, `rollback` and `remove` still find the replace. | -| `vex_maven_classifier_unpatched` | run warning and `failed[].reason` | A hosted Maven pin's GA also has a live executable `` copy (not `sources` / `javadoc`) at a version other than the pin, which the classifier-less pin does not retarget and the grant does not serve; no statement while it does. `list`, `rollback` and `remove` still find the pin. | +| `vex_maven_classifier_unpatched` | run warning and `failed[].reason` | A hosted (or pre-v5 vendored) Maven pin's GA also has an executable `` copy (not `sources` / `javadoc`; live or inside ``) at a version other than the pin, which the classifier-less pin does not retarget and the grant does not serve; no statement while it does. `list`, `rollback` and `remove` still find the pin. | +| `vex_maven_profile_unpatched` | run warning and `failed[].reason` | A Maven pin's GA main jar is also declared inside `` in the root `pom.xml` at a version other than the pin (a profile `` entry only where management governs the pin), or a profile's `` redefine a property the pin's `${property}` version names so it resolves another version, or a property a `${property}` groupId / artifactId names so the pin names another package or another declaration becomes the pinned GA off the pin, which overrides the pin whenever that profile is active; no statement while it does. `list`, `rollback` and `remove` still find the pin. | +| `vex_maven_config_override` | run warning and `failed[].reason` | A hosted (or pre-v5 vendored) Maven pin is spelled through a `${property}` that a `-D` user property in `.mvn/maven.config` redefines, so Maven resolves another version; no statement while it does. `list`, `rollback` and `remove` still find the pin. | | `vex_cargo_unpinned_declaration` | run warning and `failed[].reason` | A hosted Cargo pin is wired, but another declaration of the crate (the root's or a workspace member's) is not pinned (crates.io or another registry no Socket `[patch]` entry redirects, a `registry-index`, a path or git) and may select the patched version, so cargo builds a separate unpatched copy for it; no statement while it does. The warning says whether re-running `scan` can pin it. `list`, `rollback` and `remove` still find the pin. | | `vex_cargo_patch_bypassed` | run warning and `failed[].reason` | A vendored Cargo copy is wired, but a declaration of the crate from another registry or git accepts the patched version, or `Cargo.lock` locks that version from a registry or git, and the copy's `[patch]` entry does not redirect it; no statement while it does. `list`, `rollback` and `remove` still find the wiring. | | `vex_pnpm_git_branch_lockfile` | run warning and `failed[].reason` | An npm pin is wired in a pnpm lock, but a `pnpm-lock..yaml` exists, which pnpm installs the branch from instead when `gitBranchLockfile` is on (#556); the branch lock's presence withholds the statement whatever the setting says, until the branch locks are folded in and deleted. `list`, `rollback` and `remove` still find the pin, and `vendor --check` and `scan` still treat the wiring as live. | diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index 739df5cf0..c90cf9396 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -231,10 +231,15 @@ const NOTE_NPM_SHRINKWRAP_ONLY: &str = "vex_npm_shrinkwrap_only"; /// Omission tag and note: a hosted Maven pin sits in a reactor root, where a /// module's own `` may override it (`vex::Unattested`). const NOTE_MAVEN_REACTOR_ROOT: &str = "vex_maven_reactor_root"; -/// Omission tag and note: a hosted Maven pin's GA also has an executable -/// classifier copy at another version, which the pin does not reach +/// Omission tag and note for [`UnattestedKind::MavenClassifierUnpatched`] /// (`vex::Unattested`). const NOTE_MAVEN_CLASSIFIER_UNPATCHED: &str = "vex_maven_classifier_unpatched"; +/// Omission tag and note for [`UnattestedKind::MavenProfileUnpatched`] +/// (`vex::Unattested`). +const NOTE_MAVEN_PROFILE_UNPATCHED: &str = "vex_maven_profile_unpatched"; +/// Omission tag and note for [`UnattestedKind::MavenConfigOverride`] +/// (`vex::Unattested`). +const NOTE_MAVEN_CONFIG_OVERRIDE: &str = "vex_maven_config_override"; /// Omission tag and note: a hosted Cargo pin beside another declaration of /// the crate that names no Socket registry, which cargo resolves as a /// separate, unpatched package (`vex::Unattested`). @@ -311,6 +316,22 @@ fn unattested_note(kind: UnattestedKind) -> (&'static str, &'static str) { "not attested while that classifier copy resolves an unpatched version; the \ wiring itself is intact, so re-running `scan` does not change this", ), + UnattestedKind::MavenProfileUnpatched => ( + NOTE_MAVEN_PROFILE_UNPATCHED, + "not attested while a profile declares it at, or its move it to, \ + another version, or its redefine a groupId / artifactId property so \ + the pin names another package or another declaration names this one; the wiring \ + itself is intact, so re-running `scan` does not change this (drop that profile \ + or property or set it to the pin; `scan --mode vendored` rewrites a \ + literal profile , but neither mode wires a pin a profile's \ + can move, and hosted `scan` writes no pin a profile bypasses)", + ), + UnattestedKind::MavenConfigOverride => ( + NOTE_MAVEN_CONFIG_OVERRIDE, + "not attested while .mvn/maven.config redefines the property it is spelled \ + through; the wiring itself is intact, so re-running `scan` does not change this \ + (drop that -D from .mvn/maven.config, or write the pinned version literally)", + ), UnattestedKind::CargoUnpinnedDeclaration => ( NOTE_CARGO_UNPINNED_DECLARATION, "not attested while that declaration stands", diff --git a/crates/socket-patch-core/src/formats/maven/mod.rs b/crates/socket-patch-core/src/formats/maven/mod.rs index 3962679ce..7d13c9ef7 100644 --- a/crates/socket-patch-core/src/formats/maven/mod.rs +++ b/crates/socket-patch-core/src/formats/maven/mod.rs @@ -3,8 +3,16 @@ //! `-socket.` version split, and the Trusted Checksums files //! ([`trusted_checksums`]). Pure: text in, structure out. +mod properties; + use std::collections::BTreeMap; +pub(crate) use properties::{ + interpolate_keeping, interpolate_strict, lookup_property, profile_combinations, Definitions, + Interpolate, PomLayer, MAX_COMBINED_PROFILES, MAX_INTERPOLATION_DEPTH, +}; +use properties::{interpolate_lenient, read_properties}; + use super::xml::{blank_non_markup, child_text, elements, open_tags, Element}; pub(crate) mod trusted_checksums; @@ -40,13 +48,44 @@ pub(crate) struct PomRepo { pub(crate) in_profile: bool, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub(crate) struct PomDep { + /// `` / `` as [`ScopedDep::group`] reads them: + /// with no profile active, an undefined `${…}` kept as written. pub(crate) group: String, pub(crate) artifact: String, - /// Trimmed literal version, `${prop}` resolved from the root - /// `` when possible; `None` when the declaration has none. + /// The trimmed `` / `` text as written. + pub(crate) group_text: String, + pub(crate) artifact_text: String, + /// How the declaration reads under each combination of active profiles + /// whose `` move its coordinates off + /// [`Self::group`] / [`Self::artifact`] (for one inside a profile, its + /// own profile is always active), with the version it resolves there + /// ([`PomScope::coordinate_alternatives`]); a coordinate reference left + /// unresolved stays as written ([`may_name`] reads it as any text). + /// Empty when no profile can move its coordinates. + pub(crate) coordinate_alternatives: Vec, + /// Trimmed version, every `${prop}` interpolated + /// ([`interpolate_strict`]) from the project model (`project.*` / + /// `pom.*`), the `` of the profile holding the declaration + /// (if any), then the root ``: the version the pom itself + /// spells, which the hosted rewriter writes and rolls back. As written + /// when that fails (undefined, cyclic, too deep); `None` when the + /// declaration has none. pub(crate) version: Option, + /// [`Self::version`] as the build resolves it: the build's user + /// properties (`.mvn/maven.config`'s `-D`) come before the profile's + /// and the root `` at every level — Maven's own lookup + /// order (the model still comes first). + pub(crate) build_version: Option, + /// The trimmed `` text as written. + pub(crate) version_text: Option, + /// The other versions [`Self::build_version`] becomes when some + /// combination of profiles is active whose `` redefine a + /// property it names, directly, through another, or through the + /// project model ([`PomScope::resolve_in_build`]); the smallest + /// combination that moves it first. Empty when no profile can move it. + pub(crate) version_alternatives: Vec, /// The non-empty ``: a sibling artifact of the GA (sources, /// tests, a native build), managed and resolved apart from the main jar. pub(crate) classifier: Option, @@ -55,6 +94,79 @@ pub(crate) struct PomDep { /// Inside ``. pub(crate) managed: bool, pub(crate) in_profile: bool, + /// `None` for a declaration as the pom writes it ([`parse_pom`]); a + /// reader that expands one into its [`Self::coordinate_alternatives`] + /// sets the profiles that give each such reading. + pub(crate) retargeted_by: Option, +} + +/// A value some combination of active profiles gives a `${…}` text other +/// than its resolution with none active, and why. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Alternative { + /// The value, or the text as written when that combination leaves it + /// unresolved (undefined, cyclic, too deep) or it could not be worked + /// out. + pub(crate) value: String, + pub(crate) by: MovedBy, +} + +/// How a declaration reads under one combination of active profiles that +/// moves its `(groupId, artifactId)` off the no-profile reading, and why. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct CoordinateAlternative { + pub(crate) group: String, + pub(crate) artifact: String, + /// Its `` in the build under the same profiles + /// ([`interpolate_strict`], as written when that fails); `None` when + /// it has none. + pub(crate) version: Option, + pub(crate) by: MovedBy, +} + +/// What each text of a declaration reads under one combination of active +/// profiles, and which ([`PomScope::resolve_all_in_build`]). +type Reading = (Vec>, MovedBy); + +/// What gives an [`Alternative`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum MovedBy { + /// These profiles (their ``s) active together. + Profiles(Vec), + /// More profiles may change it than are combined + /// ([`MAX_COMBINED_PROFILES`]): not worked out, fail closed. + TooManyProfiles, + /// A `` `` this reader cannot parse: fail closed. + Unreadable(String), +} + +impl std::fmt::Display for MovedBy { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + MovedBy::Profiles(ids) => { + let s = if ids.len() == 1 { "" } else { "s" }; + write!(f, "profile{s} {}", ids.join(" + ")) + } + MovedBy::TooManyProfiles => write!( + f, + "some combination of the more than {MAX_COMBINED_PROFILES} profiles that redefine \ + what it names" + ), + MovedBy::Unreadable(e) => { + write!(f, "a section this reader cannot parse ({e})") + } + } + } +} + +/// One `` inside ``: the `` element that +/// holds it (when the scan finds one), that profile's ``, and its +/// `name -> trimmed value` pairs. +#[derive(Debug)] +struct ProfileProperties { + holder: Option, + id: String, + props: BTreeMap, } /// Where Maven reads a root pom's model from: its text with comments and @@ -63,7 +175,9 @@ pub(crate) struct PomDep { /// classpaths, `` / `` plugin /// and deploy repositories; `` apply only when activated. Shared /// by the VEX reader ([`parse_pom`]) and the hosted rewriter, so the -/// rewriter edits exactly the markup VEX later attests. +/// rewriter edits exactly the markup VEX later attests. Both the VEX +/// reader and the hosted rewriter's index weigh profile `` +/// ([`Self::read_profiles`]). #[derive(Debug)] pub(crate) struct PomScope { /// The pom with comments and CDATA blanked byte-for-byte. @@ -72,11 +186,21 @@ pub(crate) struct PomScope { profiles: Vec, /// The root `` (see [`properties`]). properties: BTreeMap, - /// [`Self::properties`] plus the `${project.*}` model references a - /// coordinate may name (see [`model_refs`]). - coordinate_refs: BTreeMap, + /// The build's user properties (`.mvn/maven.config`'s `-D`). + user: BTreeMap, + /// The project model references, raw (see [`model_refs`]). + model: BTreeMap, + /// Each `` inside ``, once [`Self::read_profiles`] + /// has read them: merged over the root's while that profile is active. + profile_properties: Vec, + /// Why [`Self::read_profiles`] could not read them (every `${…}` then + /// fails closed in [`Self::resolve_in_build`]). + profiles_unreadable: Option, } +/// No user properties: the view of a version as the pom spells it. +static NO_USER_PROPERTIES: BTreeMap = BTreeMap::new(); + impl PomScope { /// Fails (fail-closed) on a pom that is not well-formed where it /// matters: no ``, or an unterminated element or CDATA. @@ -87,9 +211,10 @@ impl PomScope { /// [`Self::new`], with the user properties the build passes Maven /// (`.mvn/maven.config`'s `-D`, see [`maven_config_properties`]): they - /// override a same-named pom property when a coordinate is - /// interpolated, as Maven's model interpolator reads them after the - /// model's own. + /// override a same-named pom property when a coordinate or a version is + /// interpolated, as Maven's model interpolator looks them up before the + /// pom's own. Profile `` are not read (see + /// [`Self::read_profiles`]). pub(crate) fn with_user_properties( raw: &str, user: &BTreeMap, @@ -107,26 +232,269 @@ impl PomScope { .concat(); let profiles = elements(&masked, "profiles")?; let properties = properties(&masked, &ignored, &profiles)?; - let mut coordinate_refs = properties.clone(); - coordinate_refs.extend(user.iter().map(|(k, v)| (k.clone(), v.clone()))); - // A `project.*` / `pom.*` reference names the model, whatever a - // same-named property says; the deprecated bare form yields to one. - for (name, value) in model_refs(&masked, &coordinate_refs.clone())? { - if name.starts_with("project.") || name.starts_with("pom.") { - coordinate_refs.insert(name, value); - } else { - coordinate_refs.entry(name).or_insert(value); - } - } + let model = model_refs(&masked)?; Ok(PomScope { masked, ignored, profiles, properties, - coordinate_refs, + user: user.clone(), + model, + profile_properties: Vec::new(), + profiles_unreadable: None, }) } + /// Read every `` inside ``, which only + /// [`Self::resolve_in_build`] weighs. One this reader cannot parse + /// does not fail the pom: it is recorded, and every `${…}` resolution + /// then fails closed ([`MovedBy::Unreadable`]). + pub(crate) fn read_profiles(&mut self) { + match profile_properties(&self.masked, &self.ignored, &self.profiles) { + Ok(found) => self.profile_properties = found, + Err(e) => self.profiles_unreadable = Some(e), + } + } + + /// The indices into [`Self::profile_properties`] of the profile that + /// holds `pos` (none outside one). + fn own_profile(&self, pos: usize) -> Vec { + (0..self.profile_properties.len()) + .filter(|&i| { + self.profile_properties[i] + .holder + .is_some_and(|p| pos >= p.start && pos < p.end) + }) + .collect() + } + + /// A model reference's raw text (an empty element binds nothing). + fn model_ref(&self, name: &str) -> Option { + self.model.get(name).filter(|v| !v.is_empty()).cloned() + } + + /// What `${name}` reads ([`lookup_property`]) with the profiles `active` + /// (indices, in pom order) active, with or without the build's user + /// properties. + fn lookup(&self, name: &str, active: &[usize], user: bool) -> Option { + let layer = PomLayer { + own: &self.properties, + profiles: active + .iter() + .map(|&i| &self.profile_properties[i].props) + .collect(), + }; + let user = if user { + &self.user + } else { + &NO_USER_PROPERTIES + }; + lookup_property(name, &|n| self.model_ref(n), user, [layer]) + } + + /// Where `${name}` may be defined in the build, for + /// [`profile_combinations`]: the model or a user property fixes it; + /// otherwise the root's, every profile's (each but `own`, which is + /// always active, may be the one read) and a bare model reference. + fn definitions(&self, name: &str, own: &[usize]) -> Definitions { + if let Some(fixed) = Definitions::fixed(name, &|n| self.model_ref(n), &self.user) { + return fixed; + } + let mut d = Definitions::default(); + d.texts.extend(self.properties.get(name).cloned()); + d.texts.extend(self.model_ref(name)); + for (i, p) in self.profile_properties.iter().enumerate() { + if let Some(v) = p.props.get(name) { + d.texts.push(v.clone()); + if !own.contains(&i) { + d.profiles.push(i); + } + } + } + d + } + + /// The `` text of the declaration at `pos`, resolved as + /// [`PomDep::version`], [`PomDep::build_version`] and + /// [`PomDep::version_alternatives`] describe. + fn resolve_version(&self, text: &str, pos: usize) -> (String, String, Vec) { + if !text.contains("${") { + return (text.to_string(), text.to_string(), Vec::new()); + } + let own = self.own_profile(pos); + let spelled = interpolate_strict(text, &|name| self.lookup(name, &own, false)) + .unwrap_or_else(|| text.to_string()); + let (build, alternatives) = self.build_versions(text, pos); + (spelled, build, alternatives) + } + + /// [`PomDep::build_version`] and [`PomDep::version_alternatives`] of + /// the `` text of the declaration at `pos`. + pub(crate) fn build_versions(&self, text: &str, pos: usize) -> (String, Vec) { + match self.resolve_in_build(text, pos) { + (Some(build), alternatives) => (build, alternatives), + // Unresolved here (a parent pom this reader never sees may + // define it): the build version stays as written, but a value + // some profiles give it is still one the build may resolve. + (None, alternatives) => ( + text.to_string(), + alternatives + .into_iter() + .filter(|a| a.value != text) + .collect(), + ), + } + } + + /// What the version `text` (written in the declaration at `pos`) + /// resolves to in the build with no profile active but the one holding + /// it ([`interpolate_strict`]), and each other value a combination of + /// active profiles gives it ([`profile_combinations`], the vendored + /// reactor's too), the smallest combination first; a combination that + /// cannot resolve it gives the text as written. Fails closed: when the + /// combinations cannot be enumerated or a profile's `` is + /// unreadable, the text as written is an alternative. + fn resolve_in_build(&self, text: &str, pos: usize) -> (Option, Vec) { + let (mut base, readings) = self.resolve_all_in_build(&[(text, interpolate_strict)], pos); + let mut alternatives: Vec = Vec::new(); + for (mut values, by) in readings { + let value = values.remove(0).unwrap_or_else(|| text.to_string()); + if alternatives.iter().all(|a| a.value != value) { + alternatives.push(Alternative { value, by }); + } + } + (base.remove(0), alternatives) + } + + /// [`Self::resolve_in_build`] for several texts of one declaration (its + /// groupId, artifactId and version), each through its own + /// interpolation and work budget but all under the same combination of + /// active profiles: what they read with none active but the one holding + /// the declaration, and each combination ([`profile_combinations`] of + /// them all) under which any reads otherwise, the smallest first, with + /// what they all read there. Fails closed: when the combinations cannot + /// be enumerated or a profile's `` is unreadable, every text + /// as written is one reading. + fn resolve_all_in_build( + &self, + texts: &[(&str, Interpolate)], + pos: usize, + ) -> (Vec>, Vec) { + let own = self.own_profile(pos); + let read = |active: &[usize]| -> Vec> { + texts + .iter() + .map(|(text, interpolate)| { + interpolate(text, &|name| self.lookup(name, active, true)) + }) + .collect() + }; + let base = read(&own); + if texts.iter().all(|(text, _)| !text.contains("${")) { + return (base, Vec::new()); + } + let as_written = |by: MovedBy| { + let values = texts.iter().map(|(text, _)| Some(text.to_string())); + vec![(values.collect(), by)] + }; + if let Some(e) = &self.profiles_unreadable { + return (base, as_written(MovedBy::Unreadable(e.clone()))); + } + let values: Vec<&str> = texts.iter().map(|(text, _)| *text).collect(); + let Some(combinations) = + profile_combinations(&values, &|name| self.definitions(name, &own)) + else { + return (base, as_written(MovedBy::TooManyProfiles)); + }; + let mut readings: Vec = Vec::new(); + for combination in combinations { + let mut active: Vec = own.iter().chain(&combination).copied().collect(); + active.sort_unstable(); + active.dedup(); + // What a text cannot resolve there is read as written. + let values: Vec> = read(&active) + .into_iter() + .zip(texts) + .map(|(v, (text, _))| v.or_else(|| Some(text.to_string()))) + .collect(); + if values != base && readings.iter().all(|(v, _)| *v != values) { + let ids = combination + .iter() + .map(|&i| self.profile_properties[i].id.clone()) + .collect(); + readings.push((values, MovedBy::Profiles(ids))); + } + } + (base, readings) + } + + /// [`PomDep::coordinate_alternatives`] of `dep`: its groupId and + /// artifactId (keeping an unresolved reference, + /// [`interpolate_keeping`]) and version ([`interpolate_strict`]) read + /// together ([`Self::resolve_all_in_build`]), every reading whose + /// coordinates differ from what it reads with no profile active but + /// the one holding it ([`ScopedDep::group`] / [`ScopedDep::artifact`]). + pub(crate) fn coordinate_alternatives(&self, dep: &ScopedDep) -> Vec { + let (Some(group_text), Some(artifact_text), Some(group), Some(artifact)) = ( + dep.group_text.as_deref(), + dep.artifact_text.as_deref(), + dep.group.as_deref(), + dep.artifact.as_deref(), + ) else { + return Vec::new(); + }; + if !group_text.contains("${") && !artifact_text.contains("${") { + return Vec::new(); + } + let mut texts: Vec<(&str, Interpolate)> = vec![ + (group_text, interpolate_keeping), + (artifact_text, interpolate_keeping), + ]; + if let Some(version) = dep.version_text.as_deref() { + texts.push((version, interpolate_strict)); + } + let (_, readings) = self.resolve_all_in_build(&texts, dep.element.start); + let mut out: Vec = Vec::new(); + for (values, by) in readings { + let mut values = values.into_iter(); + let (Some(Some(g)), Some(Some(a))) = (values.next(), values.next()) else { + continue; + }; + let version = values.next().flatten(); + if (g.as_str(), a.as_str()) == (group, artifact) { + continue; + } + let reading = CoordinateAlternative { + group: g, + artifact: a, + version, + by, + }; + if !out.iter().any(|o| { + (&o.group, &o.artifact, &o.version) + == (&reading.group, &reading.artifact, &reading.version) + }) { + out.push(reading); + } + } + out + } + + /// `text` (a coordinate of the declaration at `pos`) with every + /// `${name}` the build defines interpolated, reading the declaration's + /// own profile `` first when it sits in a profile (as its + /// version is: that profile is always active with it), an undefined + /// one kept as written ([`interpolate_lenient`]). What other profiles + /// make of it is [`Self::coordinate_alternatives`]' job, which every + /// coordinate check weighs. + fn interpolate_coordinate(&self, text: &str, pos: usize) -> String { + if !text.contains("${") { + return text.to_string(); + } + let own = self.own_profile(pos); + interpolate_lenient(text, &|name| self.lookup(name, &own, true)) + } + /// Inside a plugin / deploy section (never project resolution). pub(crate) fn is_ignored(&self, pos: usize) -> bool { inside(pos, &self.ignored) @@ -170,12 +538,17 @@ fn inside(pos: usize, set: &[Element]) -> bool { #[derive(Debug)] pub(crate) struct ScopedDep { pub(crate) element: Element, - /// `` / `` with every `${prop}` the root - /// `` or the project's own coordinates define - /// interpolated (see [`interpolate`]); an - /// undefined one stays as written, so [`may_name`] can tell it apart. + /// `` / `` with every `${prop}` the build defines + /// with no profile active but, for a `` declaration, its own + /// (user properties, the project model, the root ``) + /// interpolated ([`PomScope::interpolate_coordinate`]); an undefined + /// one stays as written, so [`may_name`] can tell it apart. What other + /// profiles make of them is [`PomScope::coordinate_alternatives`]' job. pub(crate) group: Option, pub(crate) artifact: Option, + /// The trimmed `` / `` text as written. + pub(crate) group_text: Option, + pub(crate) artifact_text: Option, /// Inner-text byte range of the literal ``, when present. pub(crate) version_inner: Option<(usize, usize)>, /// Trimmed `` text as written (no property resolution). @@ -194,12 +567,18 @@ impl PomScope { for dep in self.elements("dependency")? { let body = blank_elements(dep.inner(&self.masked), "exclusions")?; let version = elements(&body, "version")?.into_iter().next(); + let group_text = child_text(&body, "groupId")?; + let artifact_text = child_text(&body, "artifactId")?; out.push(ScopedDep { element: dep, - group: child_text(&body, "groupId")? - .map(|g| interpolate(&g, &self.coordinate_refs)), - artifact: child_text(&body, "artifactId")? - .map(|a| interpolate(&a, &self.coordinate_refs)), + group: group_text + .as_deref() + .map(|g| self.interpolate_coordinate(g, dep.start)), + artifact: artifact_text + .as_deref() + .map(|a| self.interpolate_coordinate(a, dep.start)), + group_text, + artifact_text, version_inner: version.map(|v| { ( dep.inner_start + v.inner_start, @@ -228,7 +607,8 @@ pub(crate) fn parse_pom(raw: &str) -> Result { /// [`parse_pom`] with the build's user properties (see /// [`PomScope::with_user_properties`]). pub(crate) fn parse_pom_with(raw: &str, user: &BTreeMap) -> Result { - let scope = PomScope::with_user_properties(raw, user)?; + let mut scope = PomScope::with_user_properties(raw, user)?; + scope.read_profiles(); let text = &scope.masked; let managed = elements(text, "dependencyManagement")?; let mut pom = Pom::default(); @@ -243,19 +623,34 @@ pub(crate) fn parse_pom_with(raw: &str, user: &BTreeMap) -> Resu } for dep in scope.dependencies()? { - let (Some(group), Some(artifact)) = (dep.group, dep.artifact) else { + let coordinate_alternatives = scope.coordinate_alternatives(&dep); + let (Some(group), Some(artifact), Some(group_text), Some(artifact_text)) = + (dep.group, dep.artifact, dep.group_text, dep.artifact_text) + else { continue; }; + let (version, build_version, version_alternatives) = match &dep.version_text { + Some(text) => { + let (spelled, build, alternatives) = scope.resolve_version(text, dep.element.start); + (Some(spelled), Some(build), alternatives) + } + None => (None, None, Vec::new()), + }; pom.deps.push(PomDep { group, artifact, - version: dep - .version_text - .map(|v| resolve_property(&v, &scope.properties)), + group_text, + artifact_text, + coordinate_alternatives, + version, + build_version, + version_text: dep.version_text, + version_alternatives, classifier: dep.classifier, type_text: dep.type_text, managed: inside(dep.element.start, &managed), in_profile: dep.in_profile, + retargeted_by: None, }); } Ok(pom) @@ -278,100 +673,79 @@ fn properties( { continue; } - let body = props.inner(text); - let mut from = 0; - while let Some(rel) = body[from..].find('<') { - let lt = from + rel; - let Some(gt) = body[lt..].find('>').map(|r| lt + r) else { - return Err("unterminated tag in ".to_string()); - }; - let name = &body[lt + 1..gt]; - if !is_property_name(name) { - from = gt + 1; - continue; - } - let close = format!(""); - let Some(end) = body[gt + 1..].find(&close).map(|r| gt + 1 + r) else { - return Err(format!("unterminated <{name}> in ")); - }; - map.entry(name.to_string()) - .or_insert_with(|| body[gt + 1..end].trim().to_string()); - from = end + close.len(); - } + read_properties(props.inner(text), &mut map)?; } Ok(map) } -/// `${name}` → the property's value (one level, no recursion); anything -/// else, or an undefined property, is returned unchanged. -fn resolve_property(version: &str, properties: &BTreeMap) -> String { - version - .strip_prefix("${") - .and_then(|rest| rest.strip_suffix('}')) - .filter(|name| is_property_name(name)) - .and_then(|name| properties.get(name)) - .cloned() - .unwrap_or_else(|| version.to_string()) -} - -/// Interpolation rounds before a still-unresolved reference is given up on -/// (a property defined through another, or a cycle). -const MAX_INTERPOLATION: usize = 8; - -/// Longest text interpolation builds. A real coordinate is far shorter; a -/// pom whose properties each name the previous one many times would -/// otherwise grow exponentially with every round ("billion laughs"). -const MAX_INTERPOLATED_LEN: usize = 1024; - -/// `text` with every `${name}` the root `` or project model -/// defines replaced by its value, as Maven interpolates a coordinate such as -/// `org.${vendor}` (a value naming another property is resolved too, up to -/// [`MAX_INTERPOLATION`] rounds); an undefined or malformed reference is -/// kept as written, and a round that would exceed [`MAX_INTERPOLATED_LEN`] -/// is not taken, leaving its references unresolved (which fails closed). -fn interpolate(text: &str, properties: &BTreeMap) -> String { - let mut text = text.to_string(); - for _ in 0..MAX_INTERPOLATION { - let Some(next) = interpolate_once(&text, properties) else { - break; - }; - if next == text { - break; +/// The trimmed text of `body`'s own `` child (depth 0), never one +/// nested deeper (a ``'s `` inside a ``). +fn direct_child_text(body: &str, name: &str) -> Option { + let mut depth = 0usize; + let mut from = 0; + while let Some(rel) = body[from..].find('<') { + let lt = from + rel; + let gt = lt + body[lt..].find('>')?; + let tag = &body[lt + 1..gt]; + from = gt + 1; + if tag.starts_with('!') || tag.starts_with('?') || tag.ends_with('/') { + continue; + } + if tag.starts_with('/') { + depth = depth.saturating_sub(1); + continue; + } + let tag_name = tag.split(|c: char| c.is_ascii_whitespace()).next()?; + if depth == 0 && tag_name == name { + let end = from + body[from..].find(&format!(") -> Option { - let mut out = String::with_capacity(text.len()); - let mut rest = text; - while let Some(open) = rest.find("${") { - if out.len() > MAX_INTERPOLATED_LEN { - return None; - } - out.push_str(&rest[..open]); - let after = &rest[open + 2..]; - match after - .find('}') - .map(|close| (&after[..close], close)) - .filter(|(name, _)| is_property_name(name)) - .and_then(|(name, close)| properties.get(name).map(|v| (v, close))) - { - Some((value, close)) => { - out.push_str(value); - rest = &after[close + 1..]; - } - None => { - out.push_str("${"); - rest = after; - } +/// Each `` inside `` (outside ignored sections) as +/// `name -> trimmed value`, with the `` element that holds it. +fn profile_properties( + text: &str, + ignored: &[Element], + profiles: &[Element], +) -> Result, String> { + let live = |pos: usize| inside(pos, profiles) && !inside(pos, ignored); + // A `` no `` is found around (a scan this simple + // cannot place) belongs to no profile: it is then only ever an + // alternative, never a declaration's own, which reads more versions + // into [`PomDep::version_alternatives`], not fewer. + let holders: Vec = elements(text, "profile") + .unwrap_or_default() + .into_iter() + .filter(|p| live(p.start)) + .collect(); + let mut out = Vec::new(); + for props in elements(text, "properties")? { + if !live(props.start) { + continue; } + let holder = holders + .iter() + .find(|p| props.start >= p.start && props.start < p.end) + .copied(); + // Maven names a profile without an `` `default`, as the + // vendored reactor does. + let id = holder + .and_then(|p| direct_child_text(p.inner(text), "id")) + .filter(|id| !id.is_empty()) + .unwrap_or_else(|| "default".to_string()); + let mut map = BTreeMap::new(); + read_properties(props.inner(text), &mut map)?; + out.push(ProfileProperties { + holder, + id, + props: map, + }); } - out.push_str(rest); - (out.len() <= MAX_INTERPOLATED_LEN).then_some(out) + Ok(out) } /// The model references a sibling declaration commonly uses @@ -379,13 +753,12 @@ fn interpolate_once(text: &str, properties: &BTreeMap) -> Option /// `${groupId}`, `${project.parent.groupId}`), read from the project's own /// `` / `` / `` and its ``'s; groupId /// and version fall back to the parent's, which the project inherits when -/// it omits them. A coordinate written through a property is resolved from -/// `properties` (never inherited instead: Maven interpolates a present -/// element), and one that stays unresolved is not bound. -fn model_refs( - masked: &str, - properties: &BTreeMap, -) -> Result, String> { +/// it omits them. Each is bound raw: one written through a property +/// (`${revision}`) is interpolated wherever it is read, +/// with the user properties and active profiles of that read, as Maven +/// interpolates the model itself (never inherited instead: Maven +/// interpolates a present element). +fn model_refs(masked: &str) -> Result, String> { let Some(project) = elements(masked, "project")?.into_iter().next() else { return Ok(BTreeMap::new()); }; @@ -410,15 +783,11 @@ fn model_refs( ] { own = blank_elements(&own, section)?; } - let usable = |v: Option| { - v.map(|v| interpolate(&v, properties)) - .filter(|v| !v.is_empty() && !v.contains("${")) - }; let mut refs = BTreeMap::new(); for (field, inherited) in [("groupId", true), ("artifactId", false), ("version", true)] { - let parent_value = usable(parent_text(field)?); + let parent_value = parent_text(field)?; let value = match child_text(&own, field)? { - Some(v) => usable(Some(v)), + Some(v) => Some(v), None if inherited => parent_value.clone(), None => None, }; @@ -586,6 +955,37 @@ pub(crate) fn is_variant(type_text: Option<&str>, classifier: Option<&str>) -> b || type_text.is_some_and(|t| !t.is_empty() && t != "jar" && t != "pom") } +/// Which copy of its GA a declaration's `` / `` read as +/// when a profile moves its coordinates: `Some(None)` the main jar, +/// `Some(Some(c))` the classifier copy `c`, `None` no jar on the classpath. +/// An empty `` is Maven's default `jar`, `test-jar` is the `tests` +/// copy, an explicit classifier names the copy whatever the type, and a +/// `${…}` type may be `jar`. +pub(crate) fn classpath_copy<'a>( + type_text: Option<&'a str>, + classifier: Option<&'a str>, +) -> Option> { + match (type_text, classifier) { + (None | Some("" | "jar"), c) => Some(c), + (Some(t), c) if t.contains("${") => Some(c), + (Some("test-jar"), None) => Some(Some("tests")), + (Some(_), Some(c)) => Some(Some(c)), + _ => None, + } +} + +/// How Maven keys a `` entry besides its GA: by +/// classifier and type, an empty or `jar` type being the default. +pub(crate) fn management_key<'a>( + type_text: Option<&'a str>, + classifier: Option<&'a str>, +) -> (Option<&'a str>, Option<&'a str>) { + ( + classifier.filter(|c| !c.is_empty()), + type_text.filter(|t| !t.is_empty() && *t != "jar"), + ) +} + /// The label a variant ([`is_variant`]) is reported by: its classifier, /// else its type. pub(crate) fn variant_label<'a>( @@ -659,8 +1059,18 @@ fn blank_elements(text: &str, name: &str) -> Result { #[cfg(test)] mod tests { + use std::collections::BTreeMap; + use super::PomScope; + /// `.mvn/maven.config`-style user properties from `(name, value)` pairs. + fn user_props(pairs: &[(&str, &str)]) -> BTreeMap { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() + } + #[test] fn scope_skips_comments_and_plugin_sections_and_flags_profiles() { let pom = "\ @@ -722,7 +1132,7 @@ mod tests { let deps = PomScope::new(&pom).unwrap().dependencies().unwrap(); let group = deps[0].group.as_deref().unwrap(); assert!( - group.len() <= super::MAX_INTERPOLATED_LEN, + group.len() <= super::properties::MAX_RESOLVED_LEN, "{}", group.len() ); @@ -805,7 +1215,455 @@ mod tests { let scope = PomScope::new(pom).unwrap(); let deps = scope.dependencies().unwrap(); assert_eq!(deps[0].group.as_deref(), Some("com.acme")); - assert!(!scope.coordinate_refs.contains_key("project.version")); + let dep = super::parse_pom(pom).unwrap().deps.remove(0); + assert_eq!( + dep.build_version.as_deref(), + Some("${project.version}"), + "an unresolvable project version is not the parent's" + ); + } + + /// Maven's model interpolator reads user properties (`.mvn/maven.config`'s + /// `-D`) before the pom's own ``, for a `` just as + /// for a coordinate: `-Dv=1.0` makes `${v}` the base release whatever + /// the pom defines. + #[test] + fn version_property_reads_user_properties_first() { + let pom = "1.0-socket.777777772\ + \ + ga${v}\ + gb${w}\ + gc${u}\ + "; + let versions = |user: &[(&str, &str)]| { + super::parse_pom_with(pom, &user_props(user)) + .unwrap() + .deps + .into_iter() + .map(|d| (d.version.unwrap(), d.build_version.unwrap())) + .collect::>() + }; + let both = |v: &str| (v.to_string(), v.to_string()); + assert_eq!( + versions(&[]), + [both("1.0-socket.77777777"), both("2"), both("${u}")] + ); + assert_eq!( + versions(&[("v", "1.0"), ("u", "3")]), + [ + ("1.0-socket.77777777".to_string(), "1.0".to_string()), + both("2"), + ("${u}".to_string(), "3".to_string()), + ], + "the build's user property wins over the pom's and defines one it lacks; \ + `version` keeps what the pom spells" + ); + } + + /// Maven reads `${project.*}` / `${pom.*}` from the model before any + /// user property: `-Dproject.version=` does not move a dependency + /// version written through the model. + #[test] + fn model_reference_version_ignores_user_properties() { + let pom = "1\ + ga${project.version}\ + gb${pom.version}\ + "; + let user = user_props(&[("project.version", "9"), ("pom.version", "9")]); + let deps = super::parse_pom_with(pom, &user).unwrap().deps; + for d in &deps { + assert_eq!(d.build_version, d.version, "{d:?}"); + assert!( + d.build_version.as_deref().is_some_and(|v| v != "9"), + "{d:?}" + ); + } + } + + /// A `${property}` version is interpolated through every property it + /// names, user properties first at each level; a cycle, an undefined + /// name or a chain deeper than [`super::MAX_INTERPOLATION_DEPTH`] + /// leaves it as written. + #[test] + fn version_properties_resolve_recursively_and_fail_closed() { + // (as the pom spells it, as the build resolves it) + let both = |props: &str, user: &[(&str, &str)], text: &str| { + let pom = format!( + "{props}\ + ga\ + {text}" + ); + let dep = super::parse_pom_with(&pom, &user_props(user)) + .unwrap() + .deps + .remove(0); + assert!(dep.version_alternatives.is_empty(), "{props}"); + (dep.version.unwrap(), dep.build_version.unwrap()) + }; + let version = |props: &str, user: &[(&str, &str)], text: &str| { + let (spelled, built) = both(props, user, text); + if user.is_empty() { + assert_eq!(spelled, built, "{props}"); + } + built + }; + assert_eq!( + both("${b}1.0", &[("b", "2.0")], "${a}"), + ("1.0".to_string(), "2.0".to_string()), + "a nested user property moves the build's version, not the pom's" + ); + // `${p1}` ... `1.0`. + let chain = |n: usize| -> String { + (0..n) + .map(|i| match i + 1 == n { + true => format!("1.0"), + false => format!("${{p{}}}", i + 1), + }) + .collect() + }; + assert_eq!( + version("${b}${c}1.0", &[], "${a}"), + "1.0" + ); + assert_eq!( + version("${b}1.0", &[("b", "2.0")], "${a}"), + "2.0" + ); + assert_eq!(version("10", &[], "${a}.${b}-x"), "1.0-x"); + assert_eq!( + version("", &[], "${project.version}"), + "${project.version}", + "no project version here" + ); + assert_eq!(version(&chain(16), &[], "${p0}"), "1.0"); + assert_eq!(version(&chain(17), &[], "${p0}"), "${p0}", "too deep"); + for cyclic in [ + "${a}", + "${b}${a}", + "x${b}${a}y", + ] { + assert_eq!(version(cyclic, &[], "${a}"), "${a}", "{cyclic}"); + } + assert_eq!(version("${b}", &[], "${a}"), "${a}", "undefined"); + assert_eq!(version("1", &[], "${a"), "${a", "unterminated"); + } + + /// The versions a profile's `` may move a declaration to: + /// every profile, and every set of profiles active together, counts; a + /// declaration inside a profile reads that profile's own first; user + /// properties and model references no profile can redefine. + #[test] + fn profile_properties_give_version_alternatives() { + fn values(alternatives: Vec) -> Vec { + alternatives.into_iter().map(|a| a.value).collect() + } + let resolve = |props: &str, profiles: &[&str], user: &[(&str, &str)], deps: &str| { + let profiles: String = profiles + .iter() + .map(|p| format!("{p}")) + .collect(); + let pom = format!( + "9{props}\ + {deps}{profiles}" + ); + super::parse_pom_with(&pom, &user_props(user)) + .unwrap() + .deps + .into_iter() + .map(|d| (d.build_version.unwrap(), values(d.version_alternatives))) + .collect::>() + }; + let dep = |v: &str| { + format!( + "ga\ + {v}" + ) + }; + let one = |props, profiles: &[&str], user: &[(&str, &str)]| { + resolve(props, profiles, user, &dep("${v}")).remove(0) + }; + let s = |v: &[&str]| v.iter().map(|v| v.to_string()).collect::>(); + assert_eq!(one("1", &["2"], &[]), ("1".into(), s(&["2"]))); + assert_eq!(one("1", &["1"], &[]), ("1".into(), s(&[]))); + assert_eq!(one("1", &["2"], &[]), ("1".into(), s(&[]))); + assert_eq!( + one("${w}1", &["2", "3"], &[]), + ("1".into(), s(&["2", "3"])) + ); + // Two profiles that move it only together. + assert_eq!( + one("11", &["${w}", "2"], &[]), + ("1".into(), s(&["2"])) + ); + // A profile value this pom cannot resolve, or a cycle. + assert_eq!( + one("1", &["${nope}"], &[]), + ("1".into(), s(&["${v}"])) + ); + assert_eq!( + one("1", &["${v}"], &[]), + ("1".into(), s(&["${v}"])) + ); + // User properties and model references win over every profile's. + assert_eq!( + one("1", &["2"], &[("v", "3")]), + ("3".into(), s(&[])) + ); + assert_eq!( + resolve( + "", + &["2"], + &[], + &dep("${project.version}") + ) + .remove(0), + ("9".into(), s(&[])) + ); + // More alternatives than are enumerated: unresolved. + let many: Vec = (0..17).map(|i| format!("{i}")).collect(); + let many: Vec<&str> = many.iter().map(String::as_str).collect(); + assert_eq!(one("x", &many, &[]), ("x".into(), s(&["${v}"]))); + + // A profile's own declaration reads its own properties first. + let pom = format!( + "1{}\ + a2\ + {}\ + b3", + dep("${v}"), + dep("${v}") + ); + let deps: Vec<_> = super::parse_pom(&pom) + .unwrap() + .deps + .into_iter() + .map(|d| { + ( + d.in_profile, + d.build_version.unwrap(), + d.version_alternatives, + ) + }) + .collect(); + let moved = |value: &str, ids: &[&str]| super::Alternative { + value: value.to_string(), + by: super::MovedBy::Profiles(s(ids)), + }; + assert_eq!( + deps, + [ + ( + false, + "1".to_string(), + vec![moved("2", &["a"]), moved("3", &["b"])] + ), + (true, "2".to_string(), vec![moved("3", &["b"])]), + ] + ); + + // `${project.version}` spelled through a property moves with it. + let pom = format!( + "${{revision}}1\ + {}ci\ + 2", + dep("${project.version}") + ); + let user = user_props(&[("revision", "3")]); + for (user, built, alternatives) in [ + (BTreeMap::new(), "1", vec![moved("2", &["ci"])]), + (user, "3", vec![]), + ] { + let d = super::parse_pom_with(&pom, &user).unwrap().deps.remove(0); + assert_eq!(d.version.as_deref(), Some("1")); + assert_eq!(d.build_version.as_deref(), Some(built)); + assert_eq!(d.version_alternatives, alternatives); + } + + // An unreadable profile `` fails a `${…}` closed, and + // only for the reader that weighs profiles. + let pom = format!( + "1{}{}\ + 2", + dep("${v}"), + dep("1") + ); + assert!(PomScope::new(&pom).unwrap().dependencies().is_ok()); + let deps = super::parse_pom(&pom).unwrap().deps; + assert!(matches!( + deps[0].version_alternatives[..], + [super::Alternative { + by: super::MovedBy::Unreadable(_), + .. + }] + )); + assert!(deps[1].version_alternatives.is_empty()); + } + + /// The shared interpolator's work bounds: a value naming the next + /// property many times over fails instead of growing exponentially. + #[test] + fn interpolation_is_bounded() { + let props: std::collections::BTreeMap = (0..12) + .map(|i| (format!("p{i}"), format!("${{p{}}}", i + 1).repeat(8))) + .chain([("p12".to_string(), "x".to_string())]) + .collect(); + let lookup = |name: &str| props.get(name).cloned(); + assert_eq!(super::interpolate_strict("${p0}", &lookup), None); + assert_eq!( + super::interpolate_strict("${p11}", &lookup).as_deref(), + Some("xxxxxxxx") + ); + } + + /// The `(groupId, artifactId)` pairs a profile's `` may move + /// a `${property}` coordinate to: every combination of profiles counts, + /// both coordinates read under the same one, a declaration inside a + /// profile reads its own first, a value left unresolved stays as + /// written, and user properties and model references no profile can + /// redefine. + #[test] + fn profile_properties_give_coordinate_alternatives() { + let pairs = |alternatives: Vec| { + alternatives + .into_iter() + .map(|c| (c.group, c.artifact)) + .collect::>() + }; + let alternatives = |props: &str, profiles: &[&str], user: &[(&str, &str)], deps: &str| { + let profiles: String = profiles + .iter() + .map(|p| format!("{p}")) + .collect(); + let pom = format!( + "org.self{props}\ + {deps}{profiles}" + ); + super::parse_pom_with(&pom, &user_props(user)) + .unwrap() + .deps + .into_iter() + .map(|d| ((d.group, d.artifact), pairs(d.coordinate_alternatives))) + .collect::>() + }; + let dep = |g: &str, a: &str| { + format!( + "{g}{a}\ + 1" + ) + }; + let pair = |g: &str, a: &str| (g.to_string(), a.to_string()); + let one = |props, profiles: &[&str], user: &[(&str, &str)], g: &str, a: &str| { + alternatives(props, profiles, user, &dep(g, a)).remove(0) + }; + assert_eq!( + one("org.a", &["org.b"], &[], "${g}", "x"), + (pair("org.a", "x"), vec![pair("org.b", "x")]) + ); + assert_eq!( + one("org.a", &["org.a"], &[], "${g}", "x"), + (pair("org.a", "x"), vec![]) + ); + assert_eq!( + one("org.a", &["org.b"], &[], "${g}", "x"), + (pair("org.a", "x"), vec![]) + ); + // Both coordinates, read under the same profiles. + assert_eq!( + one("a", &["b"], &[], "org.${v}", "${v}-api").1, + [pair("org.b", "b-api")] + ); + // Nested, and two profiles together. + assert_eq!( + one( + "${w}org.a", + &["org.b", "${w}.c"], + &[], + "${g}", + "x" + ) + .1, + [ + pair("org.b", "x"), + pair("org.a.c", "x"), + pair("org.b.c", "x") + ] + ); + // Unresolved under a profile, or a cycle: kept as written. + assert_eq!( + one("org.a", &["${nope}"], &[], "${g}", "x").1, + [pair("${nope}", "x")] + ); + assert_eq!( + one("org.a", &["${g}"], &[], "${g}", "x").1, + [pair("${g}", "x")] + ); + // An unterminated `${` in one coordinate stays in that one: each is + // read on its own budget, and every reading names its profiles. + let pom = format!( + "x{}\ + qy\ + ", + dep("${g", "${a}") + ); + let d = super::parse_pom(&pom).unwrap().deps.remove(0); + assert_eq!((d.group.as_str(), d.artifact.as_str()), ("${g", "x")); + assert_eq!( + d.coordinate_alternatives, + [super::CoordinateAlternative { + group: "${g".to_string(), + artifact: "y".to_string(), + version: Some("1".to_string()), + by: super::MovedBy::Profiles(vec!["q".to_string()]), + }] + ); + // Undefined with no profile involved: no alternative. + assert_eq!( + one("org.a", &[], &[], "${g}.${nope}", "x"), + (pair("org.a.${nope}", "x"), vec![]) + ); + // User properties and model references win over every profile's. + assert_eq!( + one( + "org.a", + &["org.b"], + &[("g", "org.c")], + "${g}", + "x" + ), + (pair("org.c", "x"), vec![]) + ); + assert_eq!( + one( + "", + &["org.b"], + &[], + "${project.groupId}", + "x" + ), + (pair("org.self", "x"), vec![]) + ); + + // A profile's own declaration reads its own properties first. + let pom = format!( + "org.a{}\ + porg.b\ + {}", + dep("${g}", "x"), + dep("${g}", "x") + ); + let deps: Vec<_> = super::parse_pom(&pom) + .unwrap() + .deps + .into_iter() + .map(|d| (d.in_profile, d.group, pairs(d.coordinate_alternatives))) + .collect(); + assert_eq!( + deps, + [ + (false, "org.a".to_string(), vec![pair("org.b", "x")]), + (true, "org.b".to_string(), vec![]), + ] + ); } #[test] diff --git a/crates/socket-patch-core/src/formats/maven/properties.rs b/crates/socket-patch-core/src/formats/maven/properties.rs new file mode 100644 index 000000000..3f89d67eb --- /dev/null +++ b/crates/socket-patch-core/src/formats/maven/properties.rs @@ -0,0 +1,420 @@ +//! Maven property interpolation, shared by VEX discovery ([`super::PomScope`]) +//! and the vendored reactor planner, so both read a `${…}` the same way: +//! Maven's lookup order ([`lookup_property`]), one bounded interpolator +//! ([`interpolate_strict`] / [`interpolate_lenient`]), and the profile +//! combinations that may change a value ([`profile_combinations`]). Pure. + +use std::collections::{BTreeMap, BTreeSet}; + +/// Nesting depth past which interpolation gives up: a property named +/// through more than this many others (Maven itself fails on a cycle, +/// which this bounds too). +pub(crate) const MAX_INTERPOLATION_DEPTH: usize = 16; + +/// Most lookups one interpolation makes before giving up: a value naming +/// the next property many times over would otherwise cost exponentially +/// many with every level ("billion laughs"). +const MAX_LOOKUPS: usize = 1024; + +/// Longest text one interpolation builds before giving up. +pub(crate) const MAX_RESOLVED_LEN: usize = 4096; + +/// Most profiles whose every combination [`profile_combinations`] lists +/// (2^8 - 1 combinations); a value more profiles may change is not +/// enumerated (the caller fails closed). +pub(crate) const MAX_COMBINED_PROFILES: usize = 8; + +/// A `project.*` / `pom.*` reference: Maven reads it from the model, ahead +/// of any user or pom property of the same name. +fn is_model_reference(name: &str) -> bool { + name.starts_with("project.") || name.starts_with("pom.") +} + +/// One pom's `` as Maven reads them with `profiles` active: +/// each active profile's merged over the pom's own, a later one (in pom +/// order) winning. +pub(crate) struct PomLayer<'a> { + pub(crate) own: &'a BTreeMap, + pub(crate) profiles: Vec<&'a BTreeMap>, +} + +impl PomLayer<'_> { + fn get(&self, name: &str) -> Option<&String> { + self.profiles + .iter() + .rev() + .find_map(|p| p.get(name)) + .or_else(|| self.own.get(name)) + } +} + +/// What `${name}` reads, in Maven's model interpolator's order: a +/// `project.*` / `pom.*` reference the model (`model`) answers, then the +/// build's user properties (`.mvn/maven.config`'s `-D`), then each pom's +/// properties with its active profiles merged in (`layers`, nearest pom +/// first — a child's beat its parent's), then a deprecated bare model +/// reference (`${version}`) `model` answers. The value is returned raw: +/// [`interpolate_strict`] resolves what it names in turn. +pub(crate) fn lookup_property<'a>( + name: &str, + model: &dyn Fn(&str) -> Option, + user: &BTreeMap, + layers: impl IntoIterator>, +) -> Option { + if is_model_reference(name) { + if let Some(v) = model(name) { + return Some(v); + } + } + if let Some(v) = user.get(name) { + return Some(v.clone()); + } + for layer in layers { + if let Some(v) = layer.get(name) { + return Some(v.clone()); + } + } + if is_model_reference(name) { + None + } else { + model(name) + } +} + +/// An interpolation of a text through a lookup: [`interpolate_strict`], +/// or a keep-unresolved one built on [`interpolate_lenient`]. +pub(crate) type Interpolate = fn(&str, &dyn Fn(&str) -> Option) -> Option; + +/// `value` with every `${name}` replaced by `lookup(name)`, itself +/// interpolated the same way, as Maven's model interpolator resolves a +/// property defined through another. `None` when a name is undefined, a +/// `${` is unterminated, a name is reached through itself (a cycle) or +/// through more than [`MAX_INTERPOLATION_DEPTH`] others, or the work +/// bounds are hit: an unresolved value never stands for a version. +pub(crate) fn interpolate_strict( + value: &str, + lookup: &dyn Fn(&str) -> Option, +) -> Option { + let lookups = std::cell::Cell::new(MAX_LOOKUPS); + expand(value, lookup, &mut Vec::new(), &lookups, false) +} + +/// [`interpolate_strict`] for a coordinate, where an unresolved reference +/// must stay visible: an undefined, cyclic or too deeply nested `${name}` +/// (or an unterminated `${`) is kept as written, so +/// [`may_name`](super::may_name) can treat it as unknown text; past the +/// work bounds the whole value is returned as written. +pub(crate) fn interpolate_lenient(value: &str, lookup: &dyn Fn(&str) -> Option) -> String { + let lookups = std::cell::Cell::new(MAX_LOOKUPS); + expand(value, lookup, &mut Vec::new(), &lookups, true).unwrap_or_else(|| value.to_string()) +} + +/// [`interpolate_lenient`] as an [`Interpolate`] (it always gives a text). +pub(crate) fn interpolate_keeping( + value: &str, + lookup: &dyn Fn(&str) -> Option, +) -> Option { + Some(interpolate_lenient(value, lookup)) +} + +fn expand( + value: &str, + lookup: &dyn Fn(&str) -> Option, + stack: &mut Vec, + lookups: &std::cell::Cell, + keep: bool, +) -> Option { + let mut out = String::new(); + let mut rest = value; + while let Some(at) = rest.find("${") { + out.push_str(&rest[..at]); + let after = &rest[at + 2..]; + let Some(close) = after.find('}') else { + if !keep { + return None; + } + out.push_str(&rest[at..]); + rest = ""; + break; + }; + let name = &after[..close]; + let reference = &rest[at..at + close + 3]; + rest = &after[close + 1..]; + let resolved = if stack.len() >= MAX_INTERPOLATION_DEPTH || stack.iter().any(|n| n == name) + { + None + } else { + lookups.set(lookups.get().checked_sub(1)?); + match lookup(name) { + Some(raw) => { + stack.push(name.to_string()); + let v = expand(&raw, lookup, stack, lookups, keep); + stack.pop(); + Some(v?) + } + None => None, + } + }; + match resolved { + Some(v) => out.push_str(&v), + None if keep => out.push_str(reference), + None => return None, + } + if out.len() > MAX_RESOLVED_LEN { + return None; + } + } + out.push_str(rest); + (out.len() <= MAX_RESOLVED_LEN).then_some(out) +} + +/// The names `text` references (`${name}`), in order. +fn references(text: &str) -> impl Iterator { + let mut rest = text; + std::iter::from_fn(move || { + let at = rest.find("${")?; + let after = &rest[at + 2..]; + let close = after.find('}')?; + rest = &after[close + 1..]; + Some(&after[..close]) + }) +} + +/// Where `${name}` may be defined, for [`profile_combinations`]: every raw +/// text it may read under some set of active profiles (the model's, a +/// user property, a pom's, a profile's), and the profiles whose own +/// definition may be the one read (none when something Maven reads first, +/// a model reference or a user property, fixes it). +#[derive(Default)] +pub(crate) struct Definitions { + pub(crate) texts: Vec, + pub(crate) profiles: Vec, +} + +impl Definitions { + /// The one definition that fixes `${name}` whatever profiles are + /// active, read first as [`lookup_property`] reads it: a model + /// reference the model answers, else a user property. + pub(crate) fn fixed( + name: &str, + model: &dyn Fn(&str) -> Option, + user: &BTreeMap, + ) -> Option { + is_model_reference(name) + .then(|| model(name)) + .flatten() + .or_else(|| user.get(name).cloned()) + .map(|v| Definitions { + texts: vec![v], + profiles: Vec::new(), + }) + } +} + +/// Every nonempty combination of the profiles that may change what any of +/// `values` interpolates to — those defining a name reachable from one +/// through any definition ([`Definitions`]) — smallest first, each sorted: +/// Maven activates any number of profiles together, so a value two +/// profiles move only jointly is caught, and the texts of one declaration +/// (its groupId, artifactId and version) are read under the same +/// combinations. Empty when no profile can change them. `None` when more +/// than [`MAX_COMBINED_PROFILES`] may, or the walk exceeds its bound: the +/// caller fails closed. +pub(crate) fn profile_combinations( + values: &[&str], + defs: &dyn Fn(&str) -> Definitions, +) -> Option>> { + let mut seen: BTreeSet = BTreeSet::new(); + let mut queue: Vec = values + .iter() + .flat_map(|v| references(v)) + .map(str::to_string) + .collect(); + let mut relevant: BTreeSet = BTreeSet::new(); + while let Some(name) = queue.pop() { + if !seen.insert(name.clone()) { + continue; + } + if seen.len() > MAX_LOOKUPS { + return None; + } + let d = defs(&name); + relevant.extend(d.profiles); + for text in &d.texts { + queue.extend(references(text).map(str::to_string)); + } + } + if relevant.len() > MAX_COMBINED_PROFILES { + return None; + } + let relevant: Vec = relevant.into_iter().collect(); + let mut masks: Vec = (1..(1u32 << relevant.len())).collect(); + masks.sort_by_key(|m| (m.count_ones(), *m)); + Some( + masks + .into_iter() + .map(|m| { + (0..relevant.len()) + .filter(|i| m & (1 << i) != 0) + .map(|i| relevant[i]) + .collect() + }) + .collect(), + ) +} + +/// The `name -> trimmed value` pairs of a `` body, into `map` +/// (a name's last definition wins, as in Maven's model reader). An element's name is its tag up to +/// whitespace or `/`, so `` and `` define +/// `v`, and `` defines it empty; a comment-blanked or malformed child +/// is an error (fail closed). +pub(crate) fn read_properties( + body: &str, + map: &mut BTreeMap, +) -> Result<(), String> { + let mut from = 0; + while let Some(rel) = body[from..].find('<') { + let lt = from + rel; + let Some(gt) = body[lt..].find('>').map(|r| lt + r) else { + return Err("unterminated tag in ".to_string()); + }; + let tag = &body[lt + 1..gt]; + let name_end = tag + .find(|c: char| c.is_ascii_whitespace() || c == '/') + .unwrap_or(tag.len()); + let name = &tag[..name_end]; + if !super::is_property_name(name) { + from = gt + 1; + continue; + } + // A later definition replaces an earlier one, as Maven's model + // reader's `Properties.put` does. + if tag.ends_with('/') { + map.insert(name.to_string(), String::new()); + from = gt + 1; + continue; + } + // ``, with optional whitespace before the `>`. + let close = format!(" in ")); + }; + let tail = &body[at + close.len()..]; + let ws = tail.len() - tail.trim_start().len(); + if tail[ws..].starts_with('>') { + break (at, at + close.len() + ws + 1); + } + search = at + close.len(); + }; + map.insert(name.to_string(), body[gt + 1..end].trim().to_string()); + from = after; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn map(pairs: &[(&str, &str)]) -> BTreeMap { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() + } + + #[test] + fn strict_and_lenient_share_one_expansion() { + let props = map(&[("a", "${b}"), ("b", "1"), ("c", "${c}"), ("d", "x${e}")]); + let lookup = |n: &str| props.get(n).cloned(); + assert_eq!(interpolate_strict("v${a}", &lookup).as_deref(), Some("v1")); + assert_eq!(interpolate_strict("${c}", &lookup), None, "cycle"); + assert_eq!(interpolate_strict("${d}", &lookup), None, "undefined"); + assert_eq!(interpolate_strict("${a", &lookup), None, "unterminated"); + assert_eq!(interpolate_lenient("v${a}", &lookup), "v1"); + assert_eq!(interpolate_lenient("${c}-${a}", &lookup), "${c}-1"); + assert_eq!(interpolate_lenient("${d}", &lookup), "x${e}"); + assert_eq!(interpolate_lenient("${a", &lookup), "${a"); + } + + #[test] + fn lookup_follows_mavens_order() { + let model = |n: &str| match n { + "project.version" => Some("9".to_string()), + "version" => Some("bare".to_string()), + _ => None, + }; + let user = map(&[("u", "user"), ("project.version", "no"), ("p", "user")]); + let own = map(&[("p", "pom"), ("q", "pom"), ("version", "prop")]); + let first = map(&[("q", "first"), ("r", "first")]); + let second = map(&[("r", "second")]); + let layer = || PomLayer { + own: &own, + profiles: vec![&first, &second], + }; + let get = |n: &str| lookup_property(n, &model, &user, [layer()]); + assert_eq!(get("project.version").as_deref(), Some("9")); + assert_eq!(get("p").as_deref(), Some("user")); + assert_eq!(get("q").as_deref(), Some("first")); + assert_eq!(get("r").as_deref(), Some("second"), "a later profile wins"); + assert_eq!(get("version").as_deref(), Some("prop")); + let empty = BTreeMap::new(); + let bare = lookup_property("version", &model, &empty, []); + assert_eq!(bare.as_deref(), Some("bare")); + assert_eq!(get("project.other"), None); + } + + #[test] + fn combinations_cover_the_relevant_profiles_only() { + // v -> w; profile 0 defines v, profile 1 w, profile 2 only x. + let defs = |n: &str| match n { + "v" => Definitions { + texts: vec!["${w}".into(), "1".into()], + profiles: vec![0], + }, + "w" => Definitions { + texts: vec!["1".into()], + profiles: vec![1], + }, + _ => Definitions { + texts: vec![], + profiles: vec![2], + }, + }; + assert_eq!( + profile_combinations(&["${v}"], &defs), + Some(vec![vec![0], vec![1], vec![0, 1]]) + ); + assert_eq!(profile_combinations(&["1.0"], &defs), Some(vec![])); + let many = |_: &str| Definitions { + texts: vec![], + profiles: (0..=MAX_COMBINED_PROFILES).collect(), + }; + assert_eq!(profile_combinations(&["${v}"], &many), None); + } + + #[test] + fn properties_read_attributed_and_spaced_tags() { + let mut m = BTreeMap::new(); + read_properties( + "123\ + 45", + &mut m, + ) + .unwrap(); + assert_eq!( + m, + map(&[ + ("a", "1"), + ("b", "2"), + ("c", "3"), + ("d", ""), + ("e", ""), + ("f", "5") + ]) + ); + assert!(read_properties("1", &mut BTreeMap::new()).is_err()); + } +} diff --git a/crates/socket-patch-core/src/patch/redirect/maven_index.rs b/crates/socket-patch-core/src/patch/redirect/maven_index.rs index 3d2a024ff..90934251b 100644 --- a/crates/socket-patch-core/src/patch/redirect/maven_index.rs +++ b/crates/socket-patch-core/src/patch/redirect/maven_index.rs @@ -6,7 +6,10 @@ //! shifting offsets, so a pom with many patched dependencies is scanned once, //! not once per dependency. -use crate::formats::maven::PomScope; +use crate::formats::maven::{ + classpath_copy, is_executable_classifier, is_executable_variant, is_variant, management_key, + may_name, may_shadow, variant_label, CoordinateAlternative, PomScope, +}; use crate::formats::xml::{child_text, children, elements, Element}; /// One `` outside ignored sections. @@ -20,6 +23,21 @@ pub(super) struct IndexedDep { pub(super) type_text: Option, pub(super) classifier: Option, pub(super) in_profile: bool, + /// The trimmed `` / `` text as written. + pub(super) group_text: Option, + pub(super) artifact_text: Option, + /// How each combination of profiles that moves its coordinates reads + /// it ([`PomScope::coordinate_alternatives`], as VEX discovery reads + /// it). + pub(super) coordinate_alternatives: Vec, + /// Inside a ``. + pub(super) managed: bool, + /// Every version the build may resolve for it, as VEX discovery reads + /// one ([`PomScope::build_versions`]): with no profile active but the + /// one holding it, then each combination of profiles whose + /// `` move it (as written where one leaves it unresolved). + /// Empty when it has no ``. + pub(super) build_versions: Vec, } /// One live ``. @@ -126,12 +144,26 @@ impl PomIndex { pom: &str, user: &std::collections::BTreeMap, ) -> Result { - let scope = PomScope::with_user_properties(pom, user)?; + let mut scope = PomScope::with_user_properties(pom, user)?; + // Profile `` may move a `${…}` coordinate or version, as + // VEX discovery reads it (one it cannot read fails closed there). + scope.read_profiles(); let masked = &scope.masked; + let managed = elements(masked, "dependencyManagement")?; let deps = scope .dependencies()? .into_iter() .map(|d| IndexedDep { + coordinate_alternatives: scope.coordinate_alternatives(&d), + managed: managed + .iter() + .any(|m| d.element.start >= m.start && d.element.start < m.end), + build_versions: d.version_text.as_deref().map_or_else(Vec::new, |text| { + let (build, alternatives) = scope.build_versions(text, d.element.start); + std::iter::once(build) + .chain(alternatives.into_iter().map(|a| a.value)) + .collect() + }), group: d.group, artifact: d.artifact, version_inner: d.version_inner, @@ -139,6 +171,8 @@ impl PomIndex { type_text: d.type_text, classifier: d.classifier, in_profile: d.in_profile, + group_text: d.group_text, + artifact_text: d.artifact_text, }) .collect(); let mut repos = Vec::new(); @@ -201,6 +235,176 @@ impl PomIndex { }) } + /// Why a pin of `group:artifact` at `served` (the suffixed version) + /// would not hold whenever some combination of profiles is active whose + /// `` redefine a property a `${…}` coordinate names + /// ([`IndexedDep::coordinate_alternatives`]), as VEX discovery weighs + /// it: a live versioned declaration of it (the one a pin is written + /// into) then names another package, or another declaration then names + /// its main jar (as [`may_shadow`] reads one) at a version other than + /// `served`, or one of its executable classifier copies (literally, or + /// through a property this pom does not define, [`may_name`]) + /// (`test-jar` is the `tests` copy) off `served` or with no version of + /// its own. A main jar without a version takes the pin. + pub(super) fn retargeted( + &self, + group: &str, + artifact: &str, + served: Option<&str>, + ) -> Option { + self.deps.iter().find_map(|d| { + let written = || { + format!( + "{}:{}", + d.group_text.as_deref().unwrap_or_default(), + d.artifact_text.as_deref().unwrap_or_default() + ) + }; + if d.group.as_deref() == Some(group) && d.artifact.as_deref() == Some(artifact) { + let moved = d.coordinate_alternatives.first()?; + return (!d.in_profile && d.classifier.is_none() && d.version_text.is_some()).then( + || { + format!( + "{} names {group}:{artifact}, but the of {} make it \ + {}:{}", + written(), + moved.by, + moved.group, + moved.artifact + ) + }, + ); + } + let classifier = classpath_copy(d.type_text.as_deref(), d.classifier.as_deref())?; + d.coordinate_alternatives.iter().find_map(|r| { + let literal = r.group == group && r.artifact == artifact; + let names = match classifier { + None => { + (literal + || may_shadow((&r.group, &r.artifact), None, None, (group, artifact))) + && r.version.is_some() + } + // A coordinate still holding a property this pom does + // not define may be this copy, as discovery weighs it. + Some(c) => { + may_name(&r.group, group) + && may_name(&r.artifact, artifact) + && is_executable_classifier(c) + } + }; + (names && r.version.as_deref() != served).then(|| { + format!( + "{}{} declares {}:{} at {} under the \ + of {}", + written(), + classifier.map_or(String::new(), |c| format!(" (classifier {c})")), + r.group, + r.artifact, + r.version.as_deref().unwrap_or("(none of its own)"), + r.by + ) + }) + }) + }) + } + + /// A `` declaration of `group:artifact`'s main jar (literal, + /// or through a coordinate property this pom does not define, + /// [`may_shadow`]) and a version it may resolve other than `served` + /// ([`IndexedDep::build_versions`]: its own profile's ``, + /// or any combination of profiles'), as VEX discovery weighs one: an + /// active profile's `` merge over the pom's own, so it + /// overrides any pin, and its `` overrides one + /// only where management governs the pin (`pin_managed`). A pom / + /// sources / javadoc typed one carries no code, and one without a + /// version takes the pin. + pub(super) fn profile_bypass( + &self, + group: &str, + artifact: &str, + served: &str, + pin_managed: bool, + ) -> Option<(&IndexedDep, &str)> { + self.deps.iter().find_map(|d| { + let (Some(g), Some(a)) = (d.group.as_deref(), d.artifact.as_deref()) else { + return None; + }; + let main_jar = d.classifier.is_none() + && !d + .type_text + .as_deref() + .is_some_and(|t| matches!(t, "pom" | "java-source" | "javadoc")) + && ((g == group && a == artifact) + || may_shadow((g, a), d.type_text.as_deref(), None, (group, artifact))); + if !d.in_profile || !main_jar || (d.managed && !pin_managed) { + return None; + } + let version = d.build_versions.iter().find(|v| *v != served)?; + Some((d, version.as_str())) + }) + } + + /// The first executable classifier copy of `group:artifact` (not + /// `sources` / `javadoc`; live or inside ``) that may resolve + /// a version other than `served`, with its classifier and that version + /// (`None`: none in this pom), as VEX discovery weighs one: the grant + /// serves only the main jar, and a classifier copy is its own + /// coordinate, which the pin does not retarget. Its versions are its + /// own ([`IndexedDep::build_versions`]), else those of a + /// `` entry with the same classifier (Maven keys + /// management by classifier; a profile's entry while that profile is + /// active), and with no live entry the version comes from outside this + /// pom. A type counts like the classifier it implies + /// ([`is_executable_variant`]: a `test-jar` is the `tests` jar), and the + /// copy is reported by its label ([`variant_label`]). + pub(super) fn unserved_classifier_copy( + &self, + group: &str, + artifact: &str, + served: &str, + ) -> Option<(&str, Option<&str>)> { + fn key(d: &IndexedDep) -> (Option<&str>, Option<&str>) { + management_key(d.type_text.as_deref(), d.classifier.as_deref()) + } + let copies = move |managed: bool| { + self.deps.iter().filter_map(move |d| { + let (t, c) = (d.type_text.as_deref(), d.classifier.as_deref()); + (d.managed == managed + && d.group.as_deref() == Some(group) + && d.artifact.as_deref() == Some(artifact) + && is_variant(t, c) + && is_executable_variant(t, c)) + .then(|| (d, variant_label(t, c))) + }) + }; + // Every version a declaration may resolve (`None`: it has none). + fn versions(d: &IndexedDep) -> Vec> { + match d.build_versions.as_slice() { + [] => vec![None], + all => all.iter().map(|v| Some(v.as_str())).collect(), + } + } + copies(false).find_map(|(d, classifier)| { + let resolved: Vec> = if d.version_text.is_some() { + versions(d) + } else { + let entries = |in_profile: bool| { + copies(true) + .filter(move |(m, _)| key(m) == key(d) && m.in_profile == in_profile) + .flat_map(|(m, _)| versions(m)) + }; + let mut live: Vec> = entries(false).collect(); + if live.is_empty() { + live.push(None); + } + live.extend(entries(true)); + live + }; + let version = resolved.into_iter().find(|v| *v != Some(served))?; + Some((classifier, version)) + }) + } + pub(super) fn dep(&self, i: usize) -> &IndexedDep { &self.deps[i] } @@ -344,6 +548,11 @@ impl PomIndex { type_text: None, classifier: None, in_profile: false, + group_text: Some(group.to_string()), + artifact_text: Some(artifact.to_string()), + coordinate_alternatives: Vec::new(), + managed: true, + build_versions: vec![version.to_string()], }); } diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 89679f10f..e6d5fc83e 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -8805,6 +8805,28 @@ fn rewrite_maven_pom( // unpatched bytes there while the GA counts as redirected and VEX // attests it: the dep is skipped. `sources` / `javadoc` jars are // never executed, so they only warn. + // + // With a suffixed pin, every executable copy is weighed as VEX + // discovery weighs it: one that may resolve anything but the pin + // (another release, a `${property}` a profile moves, or no version + // in this pom) keeps unpatched code on the classpath, so no pin is + // written that VEX could never attest. + if let Some((served, (classifier, version))) = suffixed_version.as_deref().and_then(|s| { + idx.unserved_classifier_copy(&group_id, &artifact_id, s) + .map(|copy| (s, copy)) + }) { + result.warnings.push(RewriteWarning { + code: "redirect_maven_classifier_unsupported".into(), + detail: format!( + "{group_id}:{artifact_id}:{classifier} resolves {}, not \ + the suffixed {served}; the Socket patch covers only the main jar, so it is \ + left as-is and the dep is not redirected (that variant would keep the \ + unpatched code on the classpath)", + version.unwrap_or("(none in this pom)") + ), + }); + continue; + } let mut executable_variant = false; for variant in &variants { let Some(v) = variant.version_text.as_deref() else { @@ -8813,15 +8835,16 @@ fn rewrite_maven_pom( let names_release = v == dep.version || crate::formats::maven::split_socket_version(v) .is_some_and(|(base, _)| base == dep.version); - if names_release { - let classifier = crate::formats::maven::variant_label( - variant.type_text.as_deref(), - variant.classifier.as_deref(), - ); - let executable = crate::formats::maven::is_executable_variant( - variant.type_text.as_deref(), - variant.classifier.as_deref(), - ); + let classifier = crate::formats::maven::variant_label( + variant.type_text.as_deref(), + variant.classifier.as_deref(), + ); + let executable = crate::formats::maven::is_executable_variant( + variant.type_text.as_deref(), + variant.classifier.as_deref(), + ); + // Weighed above when the pin is suffixed. + if names_release && (suffixed_version.is_none() || !executable) { executable_variant |= executable; result.warnings.push(RewriteWarning { code: "redirect_maven_classifier_unsupported".into(), @@ -8851,7 +8874,47 @@ fn rewrite_maven_pom( // skipped rather than reported redirected. A versionless profile // declaration takes the managed version, so the pin covers it. let (profiled, matches): (Vec<_>, Vec<_>) = live.into_iter().partition(|m| m.in_profile); - let profile_version = profiled.iter().find_map(|m| m.version_text.as_deref()); + // One that resolves anything but the suffixed pin (its own literal + // or `${property}`, or what a profile's `` make of it) + // overrides the pin whenever its profile is active, and VEX never + // attests such a pin: none is written. A profile's management + // overrides only a pin management governs — the one written when no + // live direct declaration carries a version. + if let Some(served) = suffixed_version.as_deref() { + let pin_managed = !matches + .iter() + .any(|m| m.version_text.is_some() && !idx.dep(m.idx).managed); + if let Some((d, version)) = + idx.profile_bypass(&group_id, &artifact_id, served, pin_managed) + { + result.warnings.push(RewriteWarning { + code: "redirect_maven_profile_dependency_unpatched".into(), + detail: format!( + "{}:{} {} inside {} resolves {version}, not \ + the suffixed {served}; while that profile is active it overrides any \ + pin, so pom.xml was left as it is and the dep is not counted as \ + redirected", + d.group.as_deref().unwrap_or_default(), + d.artifact.as_deref().unwrap_or_default(), + d.version_text.as_deref().unwrap_or_default(), + if d.managed { + " ()" + } else { + "" + }, + ), + }); + continue; + } + } + // Past that check, a versioned profile declaration beside a live one + // takes (or cannot override) the suffixed pin; it is still reported + // when nothing live is pinned, or on the legacy same-GAV path. + let report_profiles = suffixed_version.is_none() || matches.is_empty(); + let profile_version = profiled + .iter() + .find_map(|m| m.version_text.as_deref()) + .filter(|_| report_profiles); if let Some(profile_version) = profile_version { result.warnings.push(RewriteWarning { code: "redirect_maven_profile_dependency_unpatched".into(), @@ -8895,7 +8958,7 @@ fn rewrite_maven_pom( }); continue; } - if profile_version.is_none() { + if profile_version.is_none() && report_profiles { if let Some(shadow) = idx.placeholder_shadow(&group_id, &artifact_id, true) { result.warnings.push(RewriteWarning { code: "redirect_maven_profile_dependency_unpatched".into(), @@ -8917,6 +8980,21 @@ fn rewrite_maven_pom( } } } + // A `${…}` groupId / artifactId some profile's `` + // redefine may move the pinned declaration off this GA, or make + // another declaration this GA at its own version, whenever that + // profile is active: VEX would never attest such a pin, so none is + // written and the dep is not counted as redirected. + if let Some(why) = idx.retargeted(&group_id, &artifact_id, suffixed_version.as_deref()) { + result.warnings.push(RewriteWarning { + code: "redirect_maven_profile_coordinates_unpatched".into(), + detail: format!( + "{why}; whenever that applies a pin of {group_id}:{artifact_id} would not \ + hold, so pom.xml was left as it is and the dep is not counted as redirected" + ), + }); + continue; + } let has_live_repo = idx.has_repository(&repo_id); // LEGACY same-GAV fallback: no suffixed version means the patched jar is @@ -10319,6 +10397,46 @@ mod tests { r.warnings.iter().map(|w| w.code.as_str()).collect() } + /// Hosted-redirects slf4j-api in a lone `pom.xml`. + fn rewrite_pom(pom: &str) -> RewriteResult { + let files = BTreeMap::from([("pom.xml".to_string(), pom.to_string())]); + rewrite_registry_redirect(&files, &[maven_override()]) + } + + /// A one-line `` with `tail` (a ``, ``, + /// ...) after its optional ``. + fn maven_decl(g: &str, a: &str, v: Option<&str>, tail: &str) -> String { + let v = v.map_or(String::new(), |v| format!("{v}")); + format!( + "{g}{a}{v}{tail}" + ) + } + + /// `pom` is refused whole: nothing written, `code` the only warning. + #[track_caller] + fn assert_refused(pom: &str, code: &str) { + let r = rewrite_pom(pom); + assert!( + r.files.is_empty() && r.edits.is_empty(), + "{pom}: nothing written: {:?}", + r.files + ); + assert_eq!(warning_codes(&r), vec![code], "{pom}"); + } + + /// `pom` gets the suffixed pin, with none of the `absent` warnings; + /// returns the rewritten pom.xml. + #[track_caller] + fn assert_pinned(pom: &str, absent: &[&str]) -> String { + let r = rewrite_pom(pom); + for code in absent { + assert!(!warning_codes(&r).contains(code), "{pom}: {:?}", r.warnings); + } + let out = r.files.get("pom.xml").expect("pom rewritten"); + assert!(out.contains(MAVEN_SUFFIXED), "{pom}: pinned: {out}"); + out.clone() + } + /// A profile's own `` (a property or any literal) beats the /// top-level pin while the profile is active: when the profile holds the /// GA's only versioned declaration nothing is pinned, and beside a @@ -10347,20 +10465,76 @@ mod tests { r.warnings ); + // Beside a top-level declaration the pin would be overridden + // whenever the profile is active, and VEX never attests it: + // nothing is written either. let both = pom_with_dep("\n 1.7.36", "") .replace("\n", &profile(version)); - let files = BTreeMap::from([("pom.xml".to_string(), both)]); - let r = rewrite_registry_redirect(&files, &[maven_override()]); - let out = r.files.get("pom.xml").expect("top-level pinned"); - assert!( - out.contains(&format!("{version}")), - "{out}" - ); - assert!( - warning_codes(&r).contains(&"redirect_maven_profile_dependency_unpatched"), - "{version}: {:?}", - r.warnings - ); + assert_refused(&both, "redirect_maven_profile_dependency_unpatched"); + } + } + + /// The versions a `` declaration may resolve are read as VEX + /// discovery reads them (its own profile's ``, then every + /// combination of profiles'), and a pin is written only when none of + /// them bypasses it: a profile's `` bypasses only + /// a pin management governs (the one written when no live direct + /// declaration carries a version), and a versionless profile + /// declaration takes the pin. + #[test] + fn maven_profile_versions_are_weighed_before_pinning() { + let pom = |top: &str, profiles: &str| { + format!( + "\n \n {top}\n \n \ + {profiles}\n\n" + ) + }; + let dep = |v: Option<&str>| maven_decl("org.slf4j", "slf4j-api", v, ""); + let profile = |id: &str, props: &str, body: &str| { + format!("{id}{props}{body}") + }; + let direct = |v: Option<&str>| format!("{}", dep(v)); + let managed = |v: Option<&str>| { + format!( + "{}", + dep(v) + ) + }; + let own_pin = format!("{MAVEN_SUFFIXED}"); + let refused = [ + // A profile's management, where management governs the pin. + pom(&dep(None), &profile("p", "", &managed(Some("1.7.36")))), + // Its own profile's property resolves the pin, but another + // profile active with it redefines that property. + pom( + &dep(Some("1.7.36")), + &format!( + "{}{}", + profile("p", &own_pin, &direct(Some("${v}"))), + profile("q", "1.7.36", "") + ), + ), + ]; + for pom in &refused { + assert_refused(pom, "redirect_maven_profile_dependency_unpatched"); + } + let pinned = [ + // A profile's management under a direct pin. + pom( + &dep(Some("1.7.36")), + &profile("p", "", &managed(Some("1.7.36"))), + ), + // Versionless: it takes the pin. + pom(&dep(Some("1.7.36")), &profile("p", "", &direct(None))), + // Its own profile's property resolves the pin, and nothing + // else redefines it. + pom( + &dep(Some("1.7.36")), + &profile("p", &own_pin, &direct(Some("${v}"))), + ), + ]; + for pom in &pinned { + assert_pinned(pom, &["redirect_maven_profile_dependency_unpatched"]); } } @@ -10403,6 +10577,77 @@ mod tests { assert!(warning_codes(&r).contains(&"redirect_maven_classifier_unsupported")); } + /// An executable classifier copy that resolves anything but the + /// suffixed pin — another release, a `${property}` a profile moves, no + /// version in this pom (its classifier-keyed management consulted, a + /// profile's too) — keeps unpatched code on the classpath, and VEX never + /// attests that pin: nothing is written. One the + /// management pins to the suffixed version, or a `sources` / `javadoc` + /// one at any version, lets the main jar's pin land. + #[test] + fn maven_executable_classifier_off_the_pin_blocks_the_redirect() { + let pom = |copies: &str, profile: &str| { + format!( + "\n 1.7.30\n \n \ + org.slf4jslf4j-api\ + 1.7.36\n {copies}\n \n \ + p{profile}\n\n" + ) + }; + let copy = |classifier: &str, version: Option<&str>| { + let tail = format!("{classifier}"); + maven_decl("org.slf4j", "slf4j-api", version, &tail) + }; + let managed = |version: &str| { + format!( + "{}", + copy("tests", Some(version)) + ) + }; + let refused = [ + pom(©("tests", Some("1.7.30")), ""), + pom(©("linux-x86_64", Some("${v}")), ""), + pom(©("tests", None), ""), + // A profile's management of a versionless copy, over a live one + // at the pin. + pom(©("tests", None), &managed("1.7.30")).replace( + " ", + &format!(" {}\n ", managed(MAVEN_SUFFIXED)), + ), + // A version a profile's `` move. + pom( + ©("tests", Some("${w}")), + "1.7.30", + ) + .replace( + "1.7.30", + &format!("1.7.30{MAVEN_SUFFIXED}"), + ), + ]; + for pom in &refused { + assert_refused(pom, "redirect_maven_classifier_unsupported"); + } + let pinned = [ + pom(©("sources", Some("1.7.30")), ""), + pom(©("javadoc", None), ""), + pom(©("tests", Some(MAVEN_SUFFIXED)), ""), + // A versionless copy its live management pins to the pin. + pom(©("tests", None), "").replace( + " ", + &format!(" {}\n ", managed(MAVEN_SUFFIXED)), + ), + ]; + for pom in &pinned { + let out = assert_pinned(pom, &[]); + assert!( + out.contains(&format!( + "slf4j-api{MAVEN_SUFFIXED}" + )), + "{out}" + ); + } + } + /// Fail-closed literal pin: the `` is rewritten to the suffixed /// value, the repository + trusted-checksum files are emitted, and a re-run /// over the fully-pinned output records nothing (idempotent). @@ -10750,10 +10995,114 @@ mod tests { } } + /// A `${…}` groupId / artifactId some profile's `` redefine + /// may move the declaration a pin would be written into off the GA, or + /// make another declaration the GA at its own version, whenever that + /// profile is active, and VEX never attests such a pin: hosted scan + /// writes none and says why, as VEX discovery weighs it. A profile that leaves the coordinates alone, or makes an + /// unrelated declaration another unrelated package, does not block it. + #[test] + fn maven_pom_profile_moved_coordinates_refuse_the_dep() { + let pom = |props: &str, deps: &str, profile: &str| { + format!( + "\n {props}\n \n {deps}\n \ + \n p{profile}\ + \n\n" + ) + }; + let decl = |g: &str, a: &str, v: &str| maven_decl(g, a, Some(v), ""); + let h_decl = |v: Option<&str>, tail: &str| maven_decl("${h}", "slf4j-api", v, tail); + let pinned = decl("org.slf4j", "slf4j-api", "1.7.36"); + for (props, deps, profile) in [ + // The declaration a pin goes into moves off the GA. + ( + "org.slf4j", + decl("${g}", "slf4j-api", "1.7.36"), + "org.other", + ), + // Another declaration becomes the GA. + ( + "org.other", + format!("{pinned}{}", decl("${h}", "slf4j-api", "1.7.30")), + "org.slf4j", + ), + // ... with an empty ``, Maven's default `jar`. + ( + "org.other", + pinned.clone() + &h_decl(Some("1.7.30"), ""), + "org.slf4j", + ), + // ... or its executable classifier copy. + ( + "org.other", + pinned.clone() + &h_decl(Some("1.7.36"), "tests"), + "org.slf4j", + ), + // ... a type with an explicit classifier included. + ( + "org.other", + pinned.clone() + + &h_decl( + Some("1.7.30"), + "test-jartests", + ), + "org.slf4j", + ), + // ... or a classifier copy the profile leaves on a property this + // pom does not define, which may be the GA, as discovery weighs it. + ( + "org.other", + pinned.clone() + &h_decl(Some("1.7.30"), "tests"), + "${parent.g}", + ), + ] { + assert_refused( + &pom(props, &deps, profile), + "redirect_maven_profile_coordinates_unpatched", + ); + } + for (props, deps, profile) in [ + ( + "org.slf4j", + decl("${g}", "slf4j-api", "1.7.36"), + "org.slf4j", + ), + ( + "org.other", + format!("{pinned}{}", decl("${h}", "slf4j-api", "1.7.30")), + "org.third", + ), + // Versionless: it takes the pin. + ( + "org.other", + pinned.clone() + &h_decl(None, ""), + "org.slf4j", + ), + ] { + assert_pinned( + &pom(props, &deps, profile), + &["redirect_maven_profile_coordinates_unpatched"], + ); + } + // A profile declaration whose groupId only its own profile's + // `` define, as another group: it is read under its own + // profile, so it never names the GA, and the pin lands. + let own = format!( + "\n \n {pinned}\n \n \ + porg.other{}\ + \n\n", + decl("${g}", "slf4j-api", "2.0") + ); + let r = rewrite_pom(&own); + assert!(warning_codes(&r).is_empty(), "{:?}", r.warnings); + let out = r.files.get("pom.xml").expect("pom rewritten"); + assert!(out.contains(MAVEN_SUFFIXED), "pinned: {out}"); + } + /// A versioned `` declaration through an undefined coordinate /// property may be the GA while its profile is active: reported like a - /// literal profile declaration (#683), pinned beside a top-level - /// literal and skipped when it is the only declaration. + /// literal profile declaration (#683), and skipped beside a top-level + /// literal too, since that pin would never be attested. #[test] fn maven_pom_undefined_coordinate_property_in_a_profile_is_reported() { let profile = "p\ @@ -10762,7 +11111,7 @@ mod tests { for (top, pinned) in [ ( "org.slf4jslf4j-api1.7.36", - true, + false, ), ("", false), ] { 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 d4429b74c..dc5c6e900 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs @@ -11,7 +11,11 @@ use std::ops::Range; use serde_json::{json, Value}; -use crate::formats::maven::maven_config_properties as cli_properties; +use crate::formats::maven::{ + classpath_copy, interpolate_keeping, interpolate_strict, is_executable_classifier, + lookup_property, maven_config_properties as cli_properties, profile_combinations, Definitions, + Interpolate, PomLayer, MAX_COMBINED_PROFILES, MAX_INTERPOLATION_DEPTH, +}; use super::super::state::{WiringAction, WiringRecord}; use super::layout::{self, safe_coordinates}; @@ -51,8 +55,6 @@ const NESTED_MVN_FILES: &[&str] = &[ const SHAPE_UNSUPPORTED: &str = "vendor_jvm_shape_unsupported"; const UPSTREAM_UNAVAILABLE: &str = "vendor_jvm_upstream_unavailable"; const DEGRADED: &str = "vendor_jvm_degraded"; -/// Property interpolation depth cap (Maven itself fails on cycles). -const MAX_INTERPOLATION_DEPTH: usize = 16; /// Whether the pom declares a `` or `` of the project /// or of a profile (plugin configuration, comments and CDATA do not count). @@ -776,7 +778,7 @@ fn restore_versions( let resolve = |v: &str| { reactor .filter(|r| r.poms.contains_key(rel)) - .and_then(|r| r.interpolate(rel, v, 0)) + .and_then(|r| r.interpolate(rel, v)) }; let mut edits = Vec::new(); for (dep, key) in doc.keyed_declarations(c.group_id, c.artifact_id, &resolve) { @@ -1094,30 +1096,6 @@ struct ExternalPom { pom: Pom, } -/// `${name}` interpolation through `lookup`; `None` when a name is -/// undefined or the nesting is too deep. -fn interpolate_by( - value: &str, - lookup: &dyn Fn(&str) -> Option, - depth: usize, -) -> Option { - if depth > MAX_INTERPOLATION_DEPTH { - return None; - } - let mut out = String::new(); - let mut rest = value; - while let Some(at) = rest.find("${") { - out.push_str(&rest[..at]); - let after = &rest[at + 2..]; - let close = after.find('}')?; - let raw = lookup(&after[..close])?; - out.push_str(&interpolate_by(&raw, lookup, depth + 1)?); - rest = &after[close + 1..]; - } - out.push_str(rest); - Some(out) -} - impl Reactor { /// Management of `patch`'s g:a that a pin in local root `root` would /// override and that does not manage it at the patch's base version: @@ -1159,7 +1137,7 @@ impl Reactor { }) }; let resolve = |value: &str, what: &str| -> Result { - interpolate_by(value, &props, 0).ok_or_else(|| { + interpolate_strict(value, &props).ok_or_else(|| { Missing::Unresolved(format!("{rel}: {what} {value} is not defined")) }) }; @@ -1246,8 +1224,7 @@ impl Reactor { ) -> Result, Missing> { let mut chain: Vec = Vec::new(); let mut parent = self.poms[root].parent.as_ref().map(|p| { - let local = - |v: &Option| v.as_deref().and_then(|v| self.interpolate(root, v, 0)); + let local = |v: &Option| v.as_deref().and_then(|v| self.interpolate(root, v)); (local(&p.group), local(&p.artifact), local(&p.version)) }); while let Some((pg, pa, pv)) = parent { @@ -1408,7 +1385,7 @@ fn bom_manages<'b>( chain.iter().find_map(|e| e.pom.props.get(name).cloned()) }; let resolve = |value: &str| -> Result { - interpolate_by(value, &props, 0).ok_or_else(|| { + interpolate_strict(value, &props).ok_or_else(|| { Missing::Unresolved(format!( "the BOM {}:{}:{} manages {g}:{a} at {value}, which it does not define", bom.0, bom.1, bom.2 @@ -1773,7 +1750,7 @@ impl Reactor { std::iter::once(rel.as_str()) .chain(self.inheritors(rel)) .any(|reader| { - let resolve = |v: &str| self.interpolate(reader, v, 0); + let resolve = |v: &str| self.interpolate(reader, v); let value = |name: &str| doc.coordinate(dep, name, &resolve); value("groupId").as_deref() == Some(c.group_id) && value("artifactId").as_deref() == Some(c.artifact_id) @@ -1791,7 +1768,7 @@ impl Reactor { /// outside the checkout (an external parent or BOM) or a transitive /// path — or when it cannot be interpolated. fn managed_version(&self, rel: &str, g: &str, a: &str) -> Option { - let resolve = |v: &str| self.interpolate(rel, v, 0); + let resolve = |v: &str| self.interpolate(rel, v); self.chain(rel) .find_map(|p| { let doc = &self.poms[p].doc; @@ -1818,7 +1795,7 @@ impl Reactor { if self.managed_version(rel, g, a).as_deref() != Some(sv) { return false; } - let resolve = |v: &str| self.interpolate(rel, v, 0); + let resolve = |v: &str| self.interpolate(rel, v); let is_ga = |doc: &Doc, dep: usize| { doc.is_main_jar(dep) && doc.coordinate(dep, "groupId", &resolve).as_deref() == Some(g) @@ -1860,7 +1837,7 @@ impl Reactor { let Some(declared) = doc.child_text(dep, "version") else { return false; }; - let resolve = |v: &str| self.interpolate(rel, v, 0); + let resolve = |v: &str| self.interpolate(rel, v); doc.coordinate(dep, "version", &resolve).as_deref() == Some(sv) && (!declared.contains("${") || self @@ -1873,89 +1850,78 @@ impl Reactor { fn keyed_declarations(&self, rel: &str, g: &str, a: &str) -> Vec<(usize, String)> { self.poms[rel] .doc - .keyed_declarations(g, a, &|v| self.interpolate(rel, v, 0)) + .keyed_declarations(g, a, &|v| self.interpolate(rel, v)) } /// Interpolate every `${name}` in `value` in the context of `rel`; /// `None` when any name is undefined in the checkout. - fn interpolate(&self, rel: &str, value: &str, depth: usize) -> Option { - self.interpolate_with(rel, value, depth, None) + fn interpolate(&self, rel: &str, value: &str) -> Option { + self.interpolate_with(rel, value, &[], interpolate_strict) } - /// [`Self::interpolate`] with `overlay`'s properties (a profile's) - /// layered over its pom's own, as when that profile is active. + /// [`Self::interpolate`] with the `active` profiles' properties layered + /// over their poms' own, as when those profiles are active, through + /// `interpolate` ([`interpolate_strict`] for a version, + /// [`interpolate_keeping`] for coordinates). fn interpolate_with( &self, rel: &str, value: &str, - depth: usize, - overlay: Option>, + active: &[Overlay<'_>], + interpolate: Interpolate, ) -> Option { - if depth > MAX_INTERPOLATION_DEPTH { - return None; - } - let mut out = String::new(); - let mut rest = value; - while let Some(at) = rest.find("${") { - out.push_str(&rest[..at]); - let after = &rest[at + 2..]; - let close = after.find('}')?; - let raw = self.lookup_with(rel, &after[..close], overlay)?; - out.push_str(&self.interpolate_with(rel, &raw, depth + 1, overlay)?); - rest = &after[close + 1..]; - } - out.push_str(rest); - Some(out) + interpolate(value, &|name| self.lookup_with(rel, name, active)) } - /// User properties win over model properties, as in Maven; then the - /// model's own version expressions, then `` up the local - /// chain. + /// Maven's lookup order ([`lookup_property`], shared with VEX + /// discovery): the model's own coordinates, user properties, then + /// `` up the local chain with the `active` profiles merged + /// over their poms', then the deprecated bare `${version}`. fn lookup(&self, rel: &str, name: &str) -> Option { - self.lookup_with(rel, name, None) + self.lookup_with(rel, name, &[]) + } + + fn lookup_with(&self, rel: &str, name: &str, active: &[Overlay<'_>]) -> Option { + let layers = self.chain(rel).map(|p| PomLayer { + own: &self.poms[p].props, + profiles: active + .iter() + .filter(|(at, _)| *at == p) + .map(|(_, props)| *props) + .collect(), + }); + lookup_property(name, &|n| self.model_ref(rel, n), &self.cli_props, layers) } - fn lookup_with(&self, rel: &str, name: &str, overlay: Option>) -> Option { + /// The project model reference `name` of `rel` (`project.version`, + /// `project.groupId`, ...; the deprecated bare `version`), raw. + fn model_ref(&self, rel: &str, name: &str) -> Option { let pom = &self.poms[rel]; // A Maven 4 child may omit its parent's coordinates too: they come // from the inferred local parent. - let version = || { - self.chain(rel) - .find_map(|p| self.poms[p].effective_version()) - .map(str::to_string) - }; match name { - "project.version" | "pom.version" => return version(), - "project.groupId" | "pom.groupId" => { - return self - .chain(rel) - .find_map(|p| self.poms[p].effective_group()) - .map(str::to_string); - } - "project.artifactId" | "pom.artifactId" => return pom.artifact.clone(), - "project.parent.version" => return pom.parent.as_ref()?.version.clone(), - "project.parent.groupId" => return pom.parent.as_ref()?.group.clone(), - _ => {} - } - if let Some(v) = self.cli_props.get(name) { - return Some(v.clone()); - } - if let Some(v) = self.chain(rel).find_map(|p| { - overlay - .filter(|(at, _)| *at == p) - .and_then(|(_, props)| props.get(name)) - .or_else(|| self.poms[p].props.get(name)) - }) { - return Some(v.clone()); + "project.version" | "pom.version" | "version" => self + .chain(rel) + .find_map(|p| self.poms[p].effective_version()) + .map(str::to_string), + "project.groupId" | "pom.groupId" => self + .chain(rel) + .find_map(|p| self.poms[p].effective_group()) + .map(str::to_string), + "project.artifactId" | "pom.artifactId" => pom.artifact.clone(), + "project.parent.version" => pom.parent.as_ref()?.version.clone(), + "project.parent.groupId" => pom.parent.as_ref()?.group.clone(), + _ => None, } - (name == "version").then(version).flatten() } /// A version `declared` (with `${...}`) reaches in a pom that reads - /// it, an inheritor of `rel` or `rel` itself with a profile on its - /// chain active, that is neither the base nor `sv`: the version and - /// where. Profile activation is not evaluated, so every profile counts - /// (one at a time). + /// it, an inheritor of `rel` or `rel` itself with some combination of + /// the profiles on its chain active, that is neither the base nor `sv`: + /// the version and where. Profile activation is not evaluated, so every + /// combination of profiles that may change it counts + /// ([`profile_combinations`], shared with VEX discovery); more of them + /// than are combined fails closed. fn version_override( &self, rel: &str, @@ -1969,37 +1935,153 @@ impl Reactor { /// The first version `declared` reaches in a pom that reads it (an /// inheritor of `rel`, or `rel` or an inheritor with a profile on its /// chain active) for which `moved` holds, and where; an undefined - /// value is passed as `an undefined value`. + /// value is passed as `an undefined value` ([`Self::read_elsewhere`]). fn version_moved( &self, rel: &str, declared: &str, moved: &dyn Fn(&str) -> bool, ) -> Option<(String, String)> { + self.read_elsewhere(rel, &[(declared, interpolate_strict)], &|v| moved(&v[0])) + .map(|(mut v, at)| (v.remove(0), at)) + } + + /// Where `texts` (one declaration's, each read through its own + /// interpolation) read values `hit` accepts, other than in `rel` with + /// no profile active: in an inheritor of `rel` (Maven interpolates + /// after inheritance), or in `rel` or an inheritor with some combination + /// of the profiles on its chain active ([`Self::profile_override`]); + /// with those values (an undefined one reads "an undefined value") and + /// where. + fn read_elsewhere( + &self, + rel: &str, + texts: &[(&str, Interpolate)], + hit: &dyn Fn(&[String]) -> bool, + ) -> Option<(Vec, String)> { std::iter::once(rel) .chain(self.inheritors(rel)) .find_map(|reader| { // `rel` resolves it, so a reader or profile that does not // has redefined something it names: that moves it too. - let undefined = || "an undefined value".to_string(); let plain = (reader != rel) - .then(|| { - self.interpolate(reader, declared, 0) - .unwrap_or_else(undefined) - }) - .filter(|v| moved(v)) + .then(|| self.read_under(reader, texts, &[])) + .filter(|v| hit(v)) .map(|v| (v, reader.to_string())); - plain.or_else(|| { - self.chain(reader).find_map(|at| { - self.poms[at].profile_props.iter().find_map(|(id, props)| { - let v = self - .interpolate_with(reader, declared, 0, Some((at, props))) - .unwrap_or_else(undefined); - moved(&v).then(|| (v, format!("{reader} under profile {id} of {at}"))) - }) - }) - }) + plain.or_else(|| self.profile_override(reader, texts, hit)) + }) + } + + /// What each of `texts` reads in `reader` with the `active` profiles + /// active, through its own interpolation and work budget ("an + /// undefined value" when that fails). + fn read_under( + &self, + reader: &str, + texts: &[(&str, Interpolate)], + active: &[Overlay<'_>], + ) -> Vec { + texts + .iter() + .map(|(text, interpolate)| { + self.interpolate_with(reader, text, active, *interpolate) + .unwrap_or_else(|| "an undefined value".to_string()) }) + .collect() + } + + /// The first combination of the profiles on `reader`'s chain under + /// which `texts` (all read under the same combination, + /// [`Self::read_under`]) read values `moved` accepts, with the values + /// and where; fails closed (undetermined values, whatever `moved` says) + /// when more profiles may change them than are combined, so a caller + /// that weighs only some declarations filters them first. + fn profile_override( + &self, + reader: &str, + texts: &[(&str, Interpolate)], + moved: &dyn Fn(&[String]) -> bool, + ) -> Option<(Vec, String)> { + let profiles: Vec<(&str, &str, &BTreeMap)> = self + .chain(reader) + .flat_map(|at| { + self.poms[at] + .profile_props + .iter() + .map(move |(id, props)| (at, id.as_str(), props)) + }) + .collect(); + let definitions = |name: &str| { + if let Some(fixed) = + Definitions::fixed(name, &|n| self.model_ref(reader, n), &self.cli_props) + { + return fixed; + } + let mut d = Definitions::default(); + d.texts.extend( + self.chain(reader) + .filter_map(|p| self.poms[p].props.get(name).cloned()), + ); + d.texts.extend(self.model_ref(reader, name)); + for (i, (_, _, props)) in profiles.iter().enumerate() { + if let Some(v) = props.get(name) { + d.texts.push(v.clone()); + d.profiles.push(i); + } + } + d + }; + let values: Vec<&str> = texts.iter().map(|(text, _)| *text).collect(); + let Some(combinations) = profile_combinations(&values, &definitions) else { + return Some(( + vec!["an undetermined value".to_string(); texts.len()], + format!( + "{reader} under some combination of the more than {MAX_COMBINED_PROFILES} \ + profiles on its chain that redefine what it names" + ), + )); + }; + combinations.into_iter().find_map(|combination| { + let active: Vec> = combination + .iter() + .map(|&i| (profiles[i].0, profiles[i].2)) + .collect(); + let v = self.read_under(reader, texts, &active); + moved(&v).then(|| { + let under = combination + .iter() + .map(|&i| format!("profile {} of {}", profiles[i].1, profiles[i].0)) + .collect::>() + .join(" + "); + (v, format!("{reader} under {under}")) + }) + }) + } + + /// Where `dep` of `rel`, a declaration named through `${...}` + /// coordinates, reads a groupId and artifactId that `hit` accepts, + /// other than `rel` with no profile active ([`Self::read_elsewhere`], + /// which covers the profile holding `dep`): each read under the same + /// profiles but on its own, an unresolved reference kept as written + /// ([`interpolate_keeping`]). Maven interpolates after inheritance and + /// with the active profiles' `` merged in, then matches + /// management and pins. More profiles than are combined fail closed + /// (accepted whatever `hit` says). + fn coordinates_elsewhere( + &self, + rel: &str, + dep: usize, + hit: &dyn Fn(&str, &str) -> bool, + ) -> Option { + let doc = &self.poms[rel].doc; + let group = doc.child_text(dep, "groupId")?; + let artifact = doc.child_text(dep, "artifactId")?; + let texts: [(&str, Interpolate); 2] = [ + (&group, interpolate_keeping), + (&artifact, interpolate_keeping), + ]; + self.read_elsewhere(rel, &texts, &|v| hit(&v[0], &v[1])) + .map(|(_, at)| at) } /// Every pom in scope that inherits from `rel` (has it on its chain). @@ -2028,7 +2110,7 @@ impl Reactor { ) { let doc = &self.poms[rel].doc; let ga = format!("{}:{}", patch.group_id, patch.artifact_id); - self.warn_unresolved_coordinates(rel, patch, warnings, unpinned, uncertain); + self.warn_property_coordinates(rel, patch, warnings, unpinned, uncertain); for (dep, key) in self.keyed_declarations(rel, patch.group_id, patch.artifact_id) { let at = format!("{rel}:{}", doc.line_of(doc.nodes[dep].start)); let managed_section = doc.section_of(dep).ends_with("dependencyManagement"); @@ -2063,15 +2145,13 @@ impl Reactor { continue; } let root = self.local_root(rel); - // Maven interpolates after inheritance: a pom that inherits this - // declaration may name another artifact through it, which the - // literal SV must not reach. + // Maven interpolates after inheritance and with the active + // profiles: a pom that inherits this declaration, or a profile + // redefining a property it names, may make it another artifact, + // which the literal SV must not reach. if doc.has_property_coordinate(dep) { - let other = self.inheritors(rel).find(|p| { - let resolve = |v: &str| self.interpolate(p, v, 0); - doc.coordinate(dep, "groupId", &resolve).as_deref() != Some(patch.group_id) - || doc.coordinate(dep, "artifactId", &resolve).as_deref() - != Some(patch.artifact_id) + let other = self.coordinates_elsewhere(rel, dep, &|g, a| { + g != patch.group_id || a != patch.artifact_id }); if let Some(p) = other { warnings.push(degraded( @@ -2103,7 +2183,7 @@ impl Reactor { }; let declared = doc.text_of(version); let resolved = if declared.contains("${") { - match self.interpolate(rel, &declared, 0) { + match self.interpolate(rel, &declared) { Some(v) => v, None => { warnings.push(degraded( @@ -2178,11 +2258,21 @@ impl Reactor { } impl Reactor { - /// Warn for each declaration of `rel` that could be `patch`'s g:a but - /// names a `${...}` groupId or artifactId undefined in the checkout: - /// it is left as is, probably unpatched. One with its own version - /// beats any pin, so its local root is not pinned. - fn warn_unresolved_coordinates( + /// Warn for each declaration of `rel` named through `${...}` + /// coordinates that is not `patch`'s g:a in `rel` itself (those + /// `rewrite_declarations` weighs) but may be: one whose property the + /// checkout does not define (`property_unresolved`), or one an + /// inheritor or a combination of profiles makes it + /// (`coordinates_overridden`, [`Self::coordinates_elsewhere`]). It is + /// left as is, probably unpatched; one with its own version beats any + /// pin, so its local root is not pinned. A classifier copy is its own + /// coordinate, which no pin reaches: an executable one is warned about + /// as `classifier_declared`, as `rewrite_declarations` does (`sources` / + /// `javadoc` never run; `test-jar` is the `tests` copy), and any other + /// literal `` but `jar` is not the g:a's jar (a `${…}` one may be). Text that can never + /// read the g:a, whatever its properties say ([`may_interpolate_to`]), + /// is ruled out first, before any inheritor or profile is read. + fn warn_property_coordinates( &self, rel: &str, patch: &JvmPatch<'_>, @@ -2191,7 +2281,8 @@ impl Reactor { uncertain: &mut BTreeSet, ) { let doc = &self.poms[rel].doc; - let resolve = |v: &str| self.interpolate(rel, v, 0); + let resolve = |v: &str| self.interpolate(rel, v); + let ga = format!("{}:{}", patch.group_id, patch.artifact_id); for dep in doc.declarations() { let (Some(g), Some(a)) = ( doc.child_text(dep, "groupId"), @@ -2199,23 +2290,80 @@ impl Reactor { ) else { continue; }; - let unresolved: Vec<&str> = [&g, &a] - .into_iter() - .filter(|c| c.contains("${") && resolve(c).is_none()) - .map(String::as_str) - .collect(); - let could_be = |raw: &str, want: &str| match resolve(raw) { - Some(v) => v == want, - None => may_interpolate_to(raw, want), - }; - if unresolved.is_empty() - || !doc.is_main_jar(dep) - || !could_be(&g, patch.group_id) - || !could_be(&a, patch.artifact_id) + let type_text = doc.child_text(dep, "type").filter(|t| !t.is_empty()); + let classifier_text = doc.child_text(dep, "classifier").filter(|c| !c.is_empty()); + // `test-jar` is the `tests` copy ([`classpath_copy`]); the type + // check below drops any other literal type but `jar`, even with + // an explicit classifier. + let classifier = classpath_copy(type_text.as_deref(), classifier_text.as_deref()) + .flatten() + .map(str::to_string); + if !doc.has_property_coordinate(dep) + || doc.pin_at(dep).is_some() + || classifier + .as_deref() + .is_some_and(|c| !is_executable_classifier(c)) + || !may_interpolate_to(&g, patch.group_id) + || !may_interpolate_to(&a, patch.artifact_id) + // A `${…}` type may be `jar`, as discovery reads it. + || type_text + .as_deref() + .is_some_and(|t| t != "jar" && t != "test-jar" && !t.contains("${")) { continue; } + let (here_g, here_a) = (resolve(&g), resolve(&a)); + let (reason, detail) = match (&here_g, &here_a) { + (Some(hg), Some(ha)) if hg == patch.group_id && ha == patch.artifact_id => { + continue; + } + (Some(hg), Some(ha)) => { + let Some(there) = self.coordinates_elsewhere(rel, dep, &|rg, ra| { + may_interpolate_to(rg, patch.group_id) + && may_interpolate_to(ra, patch.artifact_id) + }) else { + continue; + }; + ( + "coordinates_overridden", + format!("{g}:{a} is {hg}:{ha} here but may be {ga} in {there}"), + ) + } + _ => { + let could_be = |read: &Option, raw: &str, want: &str| match read { + Some(v) => v == want, + None => may_interpolate_to(raw, want), + }; + if !could_be(&here_g, &g, patch.group_id) + || !could_be(&here_a, &a, patch.artifact_id) + { + continue; + } + let unresolved: Vec<&str> = [(&g, &here_g), (&a, &here_a)] + .into_iter() + .filter(|(_, read)| read.is_none()) + .map(|(raw, _)| raw.as_str()) + .collect(); + ( + "property_unresolved", + format!( + "{g}:{a} may be {ga} but {} is not defined in the checkout", + unresolved.join(", ") + ), + ) + } + }; let at = format!("{rel}:{}", doc.line_of(doc.nodes[dep].start)); + if let Some(classifier) = classifier { + warnings.push(degraded( + "classifier_declared", + format!( + "{at}: {detail}; a classifier variant ({classifier}) of {ga} bypasses \ + the pin" + ), + )); + continue; + } let versioned = doc .child_text(dep, "version") .is_some_and(|v| !v.is_empty()); @@ -2226,14 +2374,8 @@ impl Reactor { String::new() }; warnings.push(degraded( - "property_unresolved", - format!( - "{at}: {g}:{a} may be {}:{} but {} is not defined in the checkout; \ - left as is, probably unpatched{unpin}", - patch.group_id, - patch.artifact_id, - unresolved.join(", ") - ), + reason, + format!("{at}: {detail}; left as is, probably unpatched{unpin}"), )); if versioned { unpinned.insert(root); @@ -6036,6 +6178,38 @@ mod tests { } } + /// Profiles that move the version only when active together (one + /// points the property at another, the other redefines that one) are + /// weighed like a single one: VEX discovery and this planner share the + /// combinations (`formats::maven::profile_combinations`). + #[test] + fn profiles_that_move_the_version_only_together_are_weighed() { + let root = with_profile( + &ROOT.replace( + " ", + " 1.10.01.10.0\n \ + ", + ), + "indirect", + "${w}", + ); + let a = with_profile( + &module("a", &dep("${ct.version}")), + "raise", + "1.11.0", + ); + let files = reactor(&root, &a); + let plan = run(&files).unwrap(); + assert_eq!(reasons(&plan), ["conflicting_literal_version"]); + let detail = &plan.warnings[0].detail; + assert!( + detail.contains("profile indirect") && detail.contains("profile raise"), + "{detail}" + ); + let after = applied(&files, &plan); + assert_eq!(text(&after, "a/pom.xml"), a); + } + /// #459: a module's profile overriding the property an inherited /// management declaration reads keeps that declaration. #[test] @@ -6061,6 +6235,260 @@ mod tests { assert!(unwired(&applied(&files, &plan))); } + /// `root` with `{props}` and a profile `corp` + /// whose `` are `profile` (none when empty), before its + /// ``. + fn root_with(props: &str, profile: &str) -> String { + let root = ROOT.replace( + " ", + &format!(" {props}\n "), + ); + match profile { + "" => root, + p => with_corp_profile(&root, p), + } + } + + /// `root` with a profile `corp` whose `` are `props`, before + /// its ``: also how a profile is added to a vendored reactor + /// later. + fn with_corp_profile(root: &str, props: &str) -> String { + root.replace( + " ", + &format!( + " corp{props}\ + \n " + ), + ) + } + + /// The `a` / `b` reactor under `root`, module `a`'s pom being `a` and + /// `b` declaring nothing. + fn reactor(root: &str, a: &str) -> Fs { + fs(&[ + ("pom.xml", root), + ("a/pom.xml", a), + ("b/pom.xml", &module("b", "")), + ]) + } + + /// A declaration whose `${...}` groupId a profile redefines names + /// another artifact whenever that profile is active, which the literal + /// SV must not reach: it is left as is and its root unpinned, as for + /// an inheritor that resolves it differently. A `.mvn/maven.config` + /// user property wins over the profile's. + #[test] + fn a_profile_moving_the_declared_coordinates_is_left_alone() { + let decl = "${ct.group}\ + commons-text1.10.0"; + let a = module("a", decl); + let props = "org.apache.commons"; + for profile in [ + "org.other", + "${nope}", + ] { + let files = reactor(&root_with(props, profile), &a); + let plan = run(&files).unwrap(); + assert_eq!(reasons(&plan), ["coordinates_overridden"], "{profile}"); + assert!( + plan.warnings[0].detail.contains("profile corp"), + "{:?}", + plan.warnings + ); + let after = applied(&files, &plan); + assert_eq!(text(&after, "a/pom.xml"), a); + assert!(!root_pinned(&plan, &files)); + assert!(unwired(&after), "{profile}"); + } + + // A vendored reactor a profile is added to later is not attestable. + let files = reactor(&root_with(props, ""), &a); + let (_, mut after) = vendor(&files); + assert_eq!(attestable(&after), (true, true)); + let root = with_corp_profile(&text(&after, "pom.xml"), "org.other"); + after.insert("pom.xml".to_string(), root.into_bytes()); + assert_eq!(attestable(&after), (true, false)); + + // The same profile, beaten by a user property, or agreeing. + for (profile, config) in [ + ( + "org.other", + "-Dct.group=org.apache.commons\n", + ), + ("org.apache.commons", ""), + ] { + let files = fs(&[ + ("pom.xml", &root_with(props, profile)), + ("a/pom.xml", &a), + ("b/pom.xml", &module("b", "")), + (".mvn/maven.config", config), + ]); + let (plan, after) = vendor(&files); + assert!(plan.warnings.is_empty(), "{:?}", plan.warnings); + assert_eq!(text(&after, "a/pom.xml"), a.replace("1.10.0", SV)); + assert_eq!(attestable(&after), (true, true), "{profile}"); + } + } + + /// A declaration whose `${...}` groupId names another artifact with no + /// profile active, but the patched one under a profile, declares the + /// patched artifact at its own version there, beating the root pin: + /// it is left as is, warned about, and its root unpinned, so a reactor + /// vendored before that profile was added is not attestable. Unrelated + /// coordinate properties change nothing. + #[test] + fn a_profile_turning_a_declaration_into_the_patched_artifact_is_weighed() { + let other = |v: &str| { + format!( + "${{lib.group}}\ + commons-text{v}" + ) + }; + let props = "org.other"; + let a = module( + "a", + &format!("{}{}", dep("1.10.0"), other("1.9")), + ); + for (profile, warned) in [ + ("org.apache.commons", true), + ("${nope}", true), + ("org.third", false), + ("org.apache.commons", false), + ] { + let files = reactor(&root_with(props, profile), &a); + let plan = run(&files).unwrap(); + if warned { + assert_eq!(reasons(&plan), ["coordinates_overridden"], "{profile}"); + assert!( + plan.warnings[0].detail.contains("profile corp") + && plan.warnings[0] + .detail + .contains("org.apache.commons:commons-text"), + "{:?}", + plan.warnings + ); + assert!(!root_pinned(&plan, &files), "{profile}"); + } else { + assert!(plan.warnings.is_empty(), "{profile}: {:?}", plan.warnings); + assert!(root_pinned(&plan, &files), "{profile}"); + } + } + + // A `${…}` type may be `jar`, as discovery reads it: weighed too. + let typed = module( + "a", + &format!( + "{}{}", + dep("1.10.0"), + other("1.9${t}") + ), + ); + let to_commons = "org.apache.commons"; + let files = reactor(&root_with(props, to_commons), &typed); + let plan = run(&files).unwrap(); + assert_eq!( + reasons(&plan), + ["coordinates_overridden"], + "{:?}", + plan.warnings + ); + assert!(!root_pinned(&plan, &files)); + + // No version of its own: the pin applies, so the root stays pinned. + let files = reactor( + &root_with(props, to_commons), + &module("a", &format!("{}{}", dep("1.10.0"), other(""))), + ); + let plan = run(&files).unwrap(); + assert_eq!(reasons(&plan), ["coordinates_overridden"]); + assert!(root_pinned(&plan, &files)); + + // Vendored first, the profile added later: not attestable; a user + // property fixing the group keeps it attestable. + let files = reactor(&root_with(props, ""), &a); + let (_, after) = vendor(&files); + assert_eq!(attestable(&after), (true, true)); + let profiled = with_corp_profile(&text(&after, "pom.xml"), to_commons); + let mut later = after.clone(); + later.insert("pom.xml".to_string(), profiled.into_bytes()); + assert_eq!(attestable(&later), (true, false)); + later.insert( + ".mvn/maven.config".to_string(), + b"-Dlib.group=org.other\n".to_vec(), + ); + assert_eq!(attestable(&later), (true, true)); + } + + /// Coordinates whose text can never read the patched g:a (`${g}:guava`) + /// are not weighed, however many profiles redefine `g`: more than are + /// combined would otherwise fail closed and unpin the root. The same text naming commons-text does fail closed. + #[test] + fn many_profiles_on_an_unrelated_coordinate_are_not_weighed() { + let profiles: String = (0..=MAX_COMBINED_PROFILES) + .map(|i| { + format!("p{i}org.g{i}") + }) + .collect(); + let root = ROOT.replace( + " ", + &format!( + " com.google.guava\n \ + {profiles}\n " + ), + ); + let named = |artifact: &str| { + module( + "a", + &format!( + "{}${{g}}{artifact}\ + 1", + dep("1.10.0") + ), + ) + }; + let files = reactor(&root, &named("guava")); + let plan = run(&files).unwrap(); + assert!(plan.warnings.is_empty(), "{:?}", plan.warnings); + assert!(root_pinned(&plan, &files)); + + let files = reactor(&root, &named("commons-text")); + let plan = run(&files).unwrap(); + assert_eq!(reasons(&plan), ["coordinates_overridden"]); + assert!(!root_pinned(&plan, &files)); + } + + /// A classifier copy a profile retargets onto the patched g:a is its + /// own coordinate, which no pin reaches: warned about as + /// `classifier_declared`, like a literal one, without unpinning the + /// root. + #[test] + fn a_profile_retargeting_a_classifier_copy_warns() { + let classified = "${lib.group}\ + commons-text1.10.0\ + tests"; + // `test-jar` is the `tests` copy too. + let test_jar = "${lib.group}\ + commons-text1.10.0\ + test-jar"; + for copy in [classified, test_jar] { + let files = reactor( + &root_with( + "org.other", + "org.apache.commons", + ), + &module("a", &format!("{}{copy}", dep("1.10.0"))), + ); + let plan = run(&files).unwrap(); + assert_eq!(reasons(&plan), ["classifier_declared"], "{copy}"); + assert!( + plan.warnings[0].detail.contains("profile corp"), + "{:?}", + plan.warnings + ); + assert!(root_pinned(&plan, &files)); + } + } + fn attestable(files: &Fs) -> (bool, bool) { let read = |p: &str| files.get(p).cloned(); let c = Coords { diff --git a/crates/socket-patch-core/src/vex/discover/maven.rs b/crates/socket-patch-core/src/vex/discover/maven.rs index 2beb2ac90..c25830940 100644 --- a/crates/socket-patch-core/src/vex/discover/maven.rs +++ b/crates/socket-patch-core/src/vex/discover/maven.rs @@ -44,13 +44,29 @@ //! A hosted pin in a reactor root (`` / ``) stays //! a ref (rollback / remove find it) but marked unattested: a module's //! own literal `` overrides it, and only the root pom is read here -//! (the rewriter refuses such roots, #261). A `` copy of the -//! GA is its own coordinate, which the classifier-less pin does not -//! retarget and the grant does not serve: a live executable one (anything -//! but `sources` / `javadoc`) that resolves any version other than the pin -//! — its own literal, a classifier-keyed managed entry, or none in this -//! pom — keeps the ref but marks it unattested. A `${property}` -//! version is resolved one level from the root ``. +//! (the rewriter refuses such roots, #261). A `${property}` version is +//! interpolated through every property it names (at most 16 deep; a cycle +//! or an undefined name never resolves to a pin) twice: as the pom spells +//! it (the root ``, what the rewriter writes and rolls back) +//! and as the build resolves it (`.mvn/maven.config`'s `-D` user +//! properties first, Maven's order). A Socket version only the build +//! config supplies is diagnosed, never a ref (hosted mode never writes +//! one; rollback / remove never edit `.mvn/maven.config`). +//! +//! Every pin is then weighed by [`bypasses`], and each way the build may +//! resolve something else keeps the ref but marks it unattested: +//! - an executable classifier copy (anything but `sources` / `javadoc`), +//! live or in a profile, at another version or none in this pom; +//! - a `` declaration of the main jar at another version (a +//! profile's `` only where management governs the +//! pin); every profile counts, as vendored mode treats every profile +//! as live; +//! - profile `` (any combination of profiles) that move the +//! pin's `${property}` version, or a `${property}` groupId / artifactId +//! so the pin names another package or another declaration names this +//! one (a coordinate property this pom cannot resolve may name +//! anything); +//! - a `-D` user property that moves the pin's `${property}` version. //! //! Integrity: when the pom sha256 was known the rewriter also writes Maven //! Trusted Checksums — `.mvn/checksums/checksums.sha256` lines @@ -95,9 +111,11 @@ //! deploy targets) and dependencies inside `` / `` //! (plugin classpaths) are not project resolution and are skipped silently; //! `` are only read when activated, so a Socket repository or pin -//! there is diagnosed, never a ref. Submodule poms and parent poms are not -//! read (root-only). Gradle builds are discovered by `gradle.rs` (the -//! hosted index) and the vendored JVM backend's own probes. +//! there is diagnosed, never a ref (a profile that bypasses a live pin +//! withholds its attestation, [`bypasses`]). Submodule poms and parent +//! poms are not read (root-only). Gradle builds are discovered by +//! `gradle.rs` (the hosted index) and the vendored JVM backend's own +//! probes. use std::collections::{BTreeMap, BTreeSet}; @@ -107,8 +125,9 @@ use super::{ DIAG_REF_UNATTRIBUTABLE, }; use crate::formats::maven::{ - is_maven_coordinate, is_maven_version_text, maven_config_properties, may_shadow, - parse_pom_with, split_socket_version, Pom, PomDep, PomRepo, + classpath_copy, is_executable_variant, is_main_jar, is_maven_coordinate, is_maven_version_text, + is_variant, management_key, maven_config_properties, may_name, may_shadow, parse_pom_with, + split_socket_version, variant_label, MovedBy, Pom, PomDep, PomRepo, }; use crate::patch::redirect::{MVN_CHECKSUMS, MVN_CONFIG, MVN_WRAPPER_PROPERTIES}; use crate::vendor::jvm::layout; @@ -131,7 +150,7 @@ pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { return; }; // `.mvn/maven.config`'s `-D` user properties win over the pom's own - // when Maven interpolates a coordinate. + // when Maven interpolates a coordinate or a version. let config = ctx.read_text(MVN_CONFIG, out).await; let user_properties = match &config { Some(config) => maven_config_properties(config), @@ -163,15 +182,15 @@ pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { } } - let gas = group_by_ga(&pom.deps); + let gas = live_gas(&pom.deps); let reactor = crate::vendor::jvm::maven_reactor::declares_modules(&raw) || (crate::vendor::jvm::maven_reactor::may_discover_subprojects(&raw, config.as_deref()) && !crate::vendor::jvm::maven_reactor::implicit_subprojects_in(&ctx.view) .await .is_empty()); - extract_hosted(ctx, &pom, &gas, &hosted, reactor, out).await; + extract_hosted(ctx, &pom, &gas, &hosted, reactor, config.as_deref(), out).await; if !vendored.is_empty() { - extract_vendored(ctx, &pom.deps, &gas, &vendored, out).await; + extract_vendored(ctx, &pom.deps, &vendored, out).await; } } @@ -180,9 +199,10 @@ pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { async fn extract_hosted( ctx: &DiscoverCtx<'_>, pom: &Pom, - gas: &BTreeMap<(String, String), GaVersions>, + gas: &BTreeSet<(String, String)>, hosted: &BTreeMap, reactor: bool, + config: Option<&str>, out: &mut Discovery, ) { // uuid -> the (purl, g, a, suffixed version) pins that tie to it. @@ -210,8 +230,45 @@ async fn extract_hosted( } } - for (group, artifact) in gas.keys() { - let versions = &ga_versions(&pom.deps, gas, group, artifact); + // A Socket version only a `-D` user property supplies is no pom.xml + // wiring: hosted mode never writes one, and rollback / remove never + // edit `.mvn/maven.config`. + let mut reported = BTreeSet::new(); + for dep in pom.deps.iter().filter(|d| !d.in_profile) { + // A pom spelling that is itself a Socket pin is pom.xml wiring: + // pin detection keeps its ref and reports the -D override + // (`MavenConfigOverride`) instead. + let Some(built) = dep.build_version.as_deref().filter(|v| { + split_socket_version(v).is_some() + && dep + .version + .as_deref() + .and_then(split_socket_version) + .is_none() + }) else { + continue; + }; + // Once per GA and version: its managed entry and classifier copies + // spell the same property. + if !reported.insert((dep.group.clone(), dep.artifact.clone(), built.to_string())) { + continue; + } + out.diag( + DIAG_REF_UNATTRIBUTABLE, + POM, + format!( + "{POM}: {}:{} {} is the Socket version {built} only through \ + a -D user property in {MVN_CONFIG}, which hosted mode never writes and \ + rollback / remove never edit; it is not {POM} wiring", + dep.group, + dep.artifact, + dep.version.as_deref().unwrap_or_default(), + ), + ); + } + + for (group, artifact) in gas { + let versions = &ga_versions(&pom.deps, group, artifact, pom_version); let socket_pins: BTreeSet<&str> = versions .direct .iter() @@ -231,14 +288,7 @@ async fn extract_hosted( ); continue; } - // Maven's own precedence: a direct literal version wins over the - // managed one; the managed version applies only when no direct - // declaration carries a version. - let effective = if versions.direct.is_empty() { - &versions.managed - } else { - &versions.direct - }; + let effective = versions.effective(); let pinned = match effective.iter().collect::>().as_slice() { [only] if split_socket_version(only).is_some() => (*only).clone(), _ => { @@ -303,25 +353,9 @@ async fn extract_hosted( UnattestedKind::MavenReactorRoot, ); } - // An executable classifier copy (tests, a native build) is - // its own coordinate: the classifier-less pin does not - // retarget it and the grant does not serve it, so Maven - // fetches it from the next repository — the public release. - if let Some((classifier, version)) = - unpatched_executable_classifier(&pom.deps, group, artifact, &pinned) + for (kind, detail) in bypasses(&pom.deps, group, artifact, &pinned, Wiring::Hosted) { - out.unattested( - &purl, - uuid, - POM, - format!( - "{POM}: {ga}:{classifier} resolves {}, not the \ - patched {pinned}; the Socket patch covers only the main jar, so that \ - classifier copy keeps the unpatched code on the classpath", - version.unwrap_or("(none in this pom)") - ), - UnattestedKind::MavenClassifierUnpatched, - ); + out.unattested(&purl, uuid, POM, detail, kind); } ties.entry(*uuid).or_default().insert(( purl, @@ -380,7 +414,7 @@ async fn extract_hosted( continue; }; if checksums.is_none() { - checksums = Some(trusted_checksums(ctx, out).await); + checksums = Some(trusted_checksums(ctx, config, out).await); } let jar = layout::artifact_path(group, artifact, pinned, None, "jar"); let integrity = checksums @@ -399,17 +433,22 @@ async fn extract_hosted( } /// `path -> sha256 hex` from `.mvn/checksums/checksums.sha256`, or empty -/// when Maven does not enforce it: `.mvn/maven.config` lacks a setting it -/// reads the file by, or the Maven Wrapper pins a Maven older than 3.9.4. -/// Judged by the hosted rewriter's own rule, and only a line Maven checks -/// attests (`formats::maven::trusted_checksums`). -async fn trusted_checksums(ctx: &DiscoverCtx<'_>, out: &mut Discovery) -> BTreeMap { +/// when Maven does not enforce it: `config` (`.mvn/maven.config`'s text, +/// read once by [`extract`]) lacks a setting it reads the file by, or the +/// Maven Wrapper pins a Maven older than 3.9.4. Judged by the hosted +/// rewriter's own rule, and only a line Maven checks attests +/// (`formats::maven::trusted_checksums`). +async fn trusted_checksums( + ctx: &DiscoverCtx<'_>, + config: Option<&str>, + out: &mut Discovery, +) -> BTreeMap { use crate::formats::maven::trusted_checksums::{enforced, pinned}; - let Some(config) = ctx.read_text(MVN_CONFIG, out).await else { + let Some(config) = config else { return BTreeMap::new(); }; let wrapper = ctx.read_text(MVN_WRAPPER_PROPERTIES, out).await; - if !enforced(&config, wrapper.as_deref()) { + if !enforced(config, wrapper.as_deref()) { return BTreeMap::new(); } ctx.read_text(MVN_CHECKSUMS, out) @@ -423,7 +462,6 @@ async fn trusted_checksums(ctx: &DiscoverCtx<'_>, out: &mut Discovery) -> BTreeM async fn extract_vendored( ctx: &DiscoverCtx<'_>, deps: &[PomDep], - gas: &BTreeMap<(String, String), GaVersions>, vendored: &BTreeSet, out: &mut Discovery, ) { @@ -502,12 +540,8 @@ async fn extract_vendored( // The vendored repository serves the ORIGINAL GAV; a pom that now // pins this GA to another version no longer consumes the artifact. { - let versions = ga_versions(deps, gas, group, artifact); - let effective = if versions.direct.is_empty() { - &versions.managed - } else { - &versions.direct - }; + let versions = ga_versions(deps, group, artifact, pom_version); + let effective = versions.effective(); let conflicting = !effective.is_empty() && !effective.contains(version) && effective.iter().all(|v| !v.contains("${")); @@ -523,6 +557,9 @@ async fn extract_vendored( continue; } } + for (kind, detail) in bypasses(deps, group, artifact, version, Wiring::Vendored) { + out.unattested(&purl, uuid, POM, detail, kind); + } out.push(PatchedRef::vendored(purl, &vref, POM, None)); } } @@ -636,117 +673,472 @@ fn classify_repo(ctx: &DiscoverCtx<'_>, repo: &PomRepo, out: &mut Discovery) -> // ── dependency versions ────────────────────────────────────────────── -/// Distinct literal versions of one `groupId:artifactId`, split by where -/// they are declared (profile-scoped declarations excluded). -#[derive(Debug, Default, Clone)] +/// Distinct versions of one `groupId:artifactId`'s main jar among the +/// declarations Maven always reads (profiles excluded), split by where +/// they are declared. +#[derive(Debug, Default, Clone, PartialEq, Eq)] struct GaVersions { direct: BTreeSet, managed: BTreeSet, } -/// What Maven may resolve for `group:artifact`'s main jar: its own -/// declarations ([`group_by_ga`]) plus the version of every declaration -/// Maven always reads whose groupId or artifactId is a property this pom -/// does not define and may be this GA (#683, -/// [`may_shadow`](crate::formats::maven::may_shadow)) — its version then -/// takes part in Maven's precedence, unseen under the literal key. -fn ga_versions( - deps: &[PomDep], - gas: &BTreeMap<(String, String), GaVersions>, - group: &str, - artifact: &str, -) -> GaVersions { - let mut versions = gas - .get(&(group.to_string(), artifact.to_string())) - .cloned() - .unwrap_or_default(); - for dep in deps.iter().filter(|d| !d.in_profile) { - let Some(version) = &dep.version else { - continue; - }; - if may_shadow( - (&dep.group, &dep.artifact), - dep.type_text.as_deref(), - dep.classifier.as_deref(), - (group, artifact), - ) { - if dep.managed { - versions.managed.insert(version.clone()); - } else { - versions.direct.insert(version.clone()); - } +impl GaVersions { + /// Maven's own precedence: a direct literal version wins over the + /// managed one; the managed version applies only when no direct + /// declaration carries a version. + fn effective(&self) -> &BTreeSet { + if self.direct.is_empty() { + &self.managed + } else { + &self.direct } } - versions } -fn group_by_ga(deps: &[PomDep]) -> BTreeMap<(String, String), GaVersions> { - let mut map: BTreeMap<(String, String), GaVersions> = BTreeMap::new(); - // A variant (a classifier: `sources`, `tests`, a native build; or a - // type such as `test-jar`) is its own artifact, managed apart from the - // main jar: its version neither pins nor shadows the main jar's. - for dep in deps.iter().filter(|d| { - !d.in_profile - && !crate::formats::maven::is_variant(d.type_text.as_deref(), d.classifier.as_deref()) - }) { - let Some(version) = &dep.version else { +/// Which version of a declaration to read: as the pom spells it +/// ([`pom_version`], what the hosted rewriter writes and rolls back) or as +/// the build resolves it ([`build_version`]). +type VersionOf = fn(&PomDep) -> Option<&str>; + +fn pom_version(d: &PomDep) -> Option<&str> { + d.version.as_deref() +} + +fn build_version(d: &PomDep) -> Option<&str> { + d.build_version.as_deref() +} + +/// Every version the build may resolve for `d` (`None` when it has no +/// ``): [`build_version`], then each version a combination of +/// active profiles' `` moves it to +/// ([`PomDep::version_alternatives`]). +fn resolutions(d: &PomDep) -> impl Iterator> { + std::iter::once(build_version(d)).chain( + d.version_alternatives + .iter() + .map(|a| Some(a.value.as_str())), + ) +} + +/// Every GA with a versioned declaration that is not a variant +/// ([`is_variant`]) Maven always reads: the candidates for a pin. +fn live_gas(deps: &[PomDep]) -> BTreeSet<(String, String)> { + deps.iter() + .filter(|d| { + !d.in_profile + && !is_variant(d.type_text.as_deref(), d.classifier.as_deref()) + && d.version.is_some() + }) + .map(|d| (d.group.clone(), d.artifact.clone())) + .collect() +} + +/// The declarations `in_scope` keeps that may be `group:artifact`'s main +/// jar: its own, plus every one whose groupId or artifactId is a property +/// this pom does not define and may be this GA (#683, +/// [`may_shadow`](crate::formats::maven::may_shadow)) — its version then +/// takes part in Maven's precedence, unseen under the literal key. A +/// variant ([`is_variant`]: a classifier such as `sources`, `tests` or a +/// native build, or a type such as `test-jar`) is its own artifact, +/// managed apart from the main jar: it neither pins nor shadows it +/// ([`classifier_declarations`]). +fn main_jar_declarations<'a>( + deps: &'a [PomDep], + group: &'a str, + artifact: &'a str, + in_scope: impl Fn(&PomDep) -> bool + 'a, +) -> impl Iterator + 'a { + deps.iter().filter(move |d| { + in_scope(d) + && !is_variant(d.type_text.as_deref(), d.classifier.as_deref()) + && ((d.group == group && d.artifact == artifact) + || may_shadow( + (&d.group, &d.artifact), + d.type_text.as_deref(), + None, + (group, artifact), + )) + }) +} + +/// The executable variants of `group:artifact` ([`is_variant`] and +/// [`is_executable_variant`]: tests, `test-jar`, a native or JDK-specific +/// build; not `sources` / `javadoc`) that `in_scope` keeps, with the label +/// they are reported by ([`variant_label`]). A groupId or artifactId that +/// is a property this pom does not define may be this GA ([`may_name`]), +/// so it counts too. +fn classifier_declarations<'a>( + deps: &'a [PomDep], + group: &'a str, + artifact: &'a str, + in_scope: impl Fn(&PomDep) -> bool + 'a, +) -> impl Iterator + 'a { + deps.iter() + .filter(move |d| { + in_scope(d) && may_name(&d.group, group) && may_name(&d.artifact, artifact) + }) + .filter_map(|d| { + let (t, c) = (d.type_text.as_deref(), d.classifier.as_deref()); + (is_variant(t, c) && is_executable_variant(t, c)).then(|| (d, variant_label(t, c))) + }) +} + +/// What Maven may resolve for `group:artifact`'s main jar from the +/// declarations it always reads ([`main_jar_declarations`] outside +/// ``), each read through `version_of`. +fn ga_versions(deps: &[PomDep], group: &str, artifact: &str, version_of: VersionOf) -> GaVersions { + let mut versions = GaVersions::default(); + for dep in main_jar_declarations(deps, group, artifact, |d| !d.in_profile) { + let Some(version) = version_of(dep) else { continue; }; - let entry = map - .entry((dep.group.clone(), dep.artifact.clone())) - .or_default(); if dep.managed { - entry.managed.insert(version.clone()); + versions.managed.insert(version.to_string()); } else { - entry.direct.insert(version.clone()); + versions.direct.insert(version.to_string()); } } - map + versions +} + +/// Which wiring serves a GA's pin, for [`bypasses`]. +#[derive(Debug, Clone, Copy)] +enum Wiring { + /// The hosted `-socket.` pin: the grant serves the main + /// jar; a classifier copy AT the pin exists nowhere, so the build fails + /// closed rather than run unpatched code. + Hosted, + /// The pre-v5 single-pom vendored repository: the original GAV's main + /// jar only, so every classifier copy comes from the next repository. + Vendored, +} + +/// Every way the build may bypass the wired `group:artifact` pin `pinned` +/// (the hosted suffixed version, or the vendored repository's original +/// one), with the [`UnattestedKind`] it is reported as: the ref stays (so +/// rollback, remove and list still find the wiring) but is not attested. +fn bypasses( + deps: &[PomDep], + group: &str, + artifact: &str, + pinned: &str, + wiring: Wiring, +) -> Vec<(UnattestedKind, String)> { + let ga = format!("{group}:{artifact}"); + let mut found = Vec::new(); + // `.mvn/maven.config`'s `-D` user properties, which Maven reads before + // the pom's ``, redefine what the pin is spelled through. + // Only a property that moves the build OFF the pin is an override: one + // `.mvn/maven.config` alone defines, at the pinned version, is the pin. + let spelled = ga_versions(deps, group, artifact, pom_version); + let built = ga_versions(deps, group, artifact, build_version); + let resolved = built.effective(); + if resolved != spelled.effective() && !(resolved.len() == 1 && resolved.contains(pinned)) { + let listed = if resolved.is_empty() { + "no version this pom gives".to_string() + } else { + resolved + .iter() + .map(|v| v.as_str()) + .collect::>() + .join(", ") + }; + found.push(( + UnattestedKind::MavenConfigOverride, + format!( + "{POM}: {ga} is wired to {pinned}, but a -D user property in {MVN_CONFIG} \ + (which Maven reads before the pom's ) makes it resolve {listed}" + ), + )); + } + // Each declaration as written, then as each combination of profiles + // that moves its coordinates reads it: what it then declares is weighed + // by the same checks. + let moved: Vec = retargeted(deps).collect(); + let read: std::borrow::Cow<[PomDep]> = if moved.is_empty() { + std::borrow::Cow::Borrowed(deps) + } else { + std::borrow::Cow::Owned(deps.iter().cloned().chain(moved).collect()) + }; + if let Some(detail) = unpatched_classifier_copy(&read, group, artifact, pinned, wiring) { + found.push((UnattestedKind::MavenClassifierUnpatched, detail)); + } + let pin_managed = built.direct.is_empty(); + if let Some(detail) = profile_override(&read, group, artifact, pinned, pin_managed) + .or_else(|| pin_retargeted(deps, group, artifact, pinned, pin_managed)) + { + found.push((UnattestedKind::MavenProfileUnpatched, detail)); + } + found } -/// The first live executable classifier copy of `group:artifact` that does -/// not resolve `pinned`, with the version it resolves (`None` when this pom -/// gives it none). Its version is its own literal, else a -/// `` entry with the same classifier — Maven keys -/// management by classifier, so the classifier-less pin never applies. -fn unpatched_executable_classifier<'a>( - deps: &'a [PomDep], +/// Each declaration's [`PomDep::coordinate_alternatives`] as a declaration +/// of its own: what Maven reads while those profiles are active, so read +/// only then (`in_profile`), at the version it resolves there, and marked +/// with the profiles that give it ([`PomDep::retargeted_by`]). Its `` +/// is read as Maven maps it ([`classpath_copy`]): one that is no jar on +/// the classpath gives no reading. +fn retargeted(deps: &[PomDep]) -> impl Iterator + '_ { + deps.iter().flat_map(|d| { + d.coordinate_alternatives.iter().filter_map(move |r| { + let classifier = classpath_copy(d.type_text.as_deref(), d.classifier.as_deref())? + .map(str::to_string); + let type_text = d + .type_text + .clone() + .filter(|t| t == "jar" || t.contains("${")); + Some(PomDep { + group: r.group.clone(), + artifact: r.artifact.clone(), + coordinate_alternatives: Vec::new(), + version: r.version.clone(), + build_version: r.version.clone(), + version_alternatives: Vec::new(), + classifier, + type_text, + in_profile: true, + retargeted_by: Some(r.by.clone()), + ..d.clone() + }) + }) + }) +} + +/// How a declaration [`retargeted`] reads, for a detail: the declaration as +/// written and the profiles that make it `group:artifact` (or a property +/// it leaves unresolved that may be). +fn retargeted_text(d: &PomDep, by: &MovedBy, group: &str, artifact: &str) -> String { + format!( + "declared {}:{}, whose coordinates the of {by} make {}", + d.group_text, + d.artifact_text, + named(d, group, artifact) + ) +} + +/// `d`'s GA for a detail, with `group:artifact` when it only may be that +/// (through a property this pom leaves unresolved). +fn named(d: &PomDep, group: &str, artifact: &str) -> String { + if d.group == group && d.artifact == artifact { + format!("{group}:{artifact}") + } else { + format!( + "{}:{} (which may be {group}:{artifact})", + d.group, d.artifact + ) + } +} + +/// Why the live main-jar declaration carrying `group:artifact`'s pin +/// `pinned` (a managed one only where management governs it, +/// `pin_managed`) stops naming it whenever some combination of profiles is +/// active whose `` redefine a property its coordinates name +/// ([`PomDep::coordinate_alternatives`]): the pin then no longer applies to +/// `group:artifact`, which resolves from its other declarations or a +/// transitive path. (A declaration that becomes `group:artifact` there is +/// weighed through [`retargeted`].) +fn pin_retargeted( + deps: &[PomDep], group: &str, artifact: &str, pinned: &str, -) -> Option<(&'a str, Option<&'a str>)> { - let of_ga = |d: &&PomDep| !d.in_profile && d.group == group && d.artifact == artifact; + pin_managed: bool, +) -> Option { deps.iter() - .filter(of_ga) - .filter(|d| !d.managed) .filter(|d| { - let (t, c) = (d.type_text.as_deref(), d.classifier.as_deref()); - crate::formats::maven::is_variant(t, c) - && crate::formats::maven::is_executable_variant(t, c) + !d.in_profile + && d.classifier.is_none() + && (!d.managed || pin_managed) + && d.group == group + && d.artifact == artifact + && build_version(d) == Some(pinned) }) .find_map(|d| { - // Management is keyed by type and classifier too. - let version = d.version.as_deref().or_else(|| { - deps.iter() - .filter(of_ga) - .find(|m| { - let ty = |t: &Option| { - t.as_deref() - .filter(|t| !t.is_empty()) - .unwrap_or("jar") - .to_string() - }; - m.managed - && m.classifier == d.classifier - && ty(&m.type_text) == ty(&d.type_text) - }) - .and_then(|m| m.version.as_deref()) - }); - let label = crate::formats::maven::variant_label( - d.type_text.as_deref(), - d.classifier.as_deref(), - ); - (version != Some(pinned)).then_some((label, version)) + let moved = d.coordinate_alternatives.first()?; + Some(format!( + "{POM}: the declaration {}:{} carrying the patched {pinned} names \ + {group}:{artifact}, but the of {} redefine its coordinates to \ + {}:{}; whenever that applies the pin no longer applies to {group}:{artifact}, \ + which Maven resolves from its other declarations instead", + d.group_text, d.artifact_text, moved.by, moved.group, moved.artifact + )) + }) +} + +/// Why the first executable variant of `group:artifact` +/// ([`classifier_declarations`]) — live or inside `` — runs code +/// the wiring does not serve, if one does. A variant is its own +/// coordinate: the main-jar pin does not retarget it. Its version is its +/// own ``, else a `` entry with the same +/// classifier and type (Maven keys management by both); a profile's entry +/// overrides the live one while that profile is active, and with no live +/// entry the version comes from outside this pom (fail closed). A hosted +/// copy is fine only at the pin itself ([`Wiring::Hosted`]); a vendored one +/// never is. +fn unpatched_classifier_copy( + deps: &[PomDep], + group: &str, + artifact: &str, + pinned: &str, + wiring: Wiring, +) -> Option { + let served = match wiring { + Wiring::Hosted => Some(pinned), + Wiring::Vendored => None, + }; + // Each version a declaration may resolve, flagged when a profile gives + // it: the declaration's own profile, or one whose `` move + // it (every resolution after the first). + fn flagged(d: &PomDep, in_profile: bool) -> Vec<(Option<&str>, bool)> { + resolutions(d) + .enumerate() + .map(|(i, v)| (v, in_profile || i > 0)) + .collect() + } + // Each entry also carries whether it names `group:artifact` literally: + // one reached only through an undefined property ([`may_name`]) may + // manage another GA, so it never stands in for this copy's version alone. + fn key(d: &PomDep) -> (Option<&str>, Option<&str>) { + management_key(d.type_text.as_deref(), d.classifier.as_deref()) + } + let managed = |copy: &PomDep, in_profile: bool| -> Vec<(Option<&str>, bool, bool)> { + classifier_declarations(deps, group, artifact, move |d| { + d.managed && d.in_profile == in_profile + }) + .filter(|(m, _)| key(m) == key(copy)) + .flat_map(|(d, _)| { + let literal = d.group == group && d.artifact == artifact; + flagged(d, in_profile) + .into_iter() + .map(move |(v, p)| (v, p, literal)) + }) + .collect() + }; + classifier_declarations(deps, group, artifact, |d| !d.managed).find_map(|(d, classifier)| { + let resolved: Vec<(Option<&str>, bool)> = match build_version(d) { + Some(_) => flagged(d, false), + None => { + let mut live = managed(d, false); + // Without a live entry that surely manages this GA, the + // version may come from outside this pom: fail closed. + if !live.iter().any(|(_, _, literal)| *literal) { + live.push((None, false, true)); + } + // A profile entry with no `` (scope or exclusions + // only) overrides no version. + live.extend(managed(d, true).into_iter().filter(|(v, _, _)| v.is_some())); + live.into_iter().map(|(v, p, _)| (v, p)).collect() + } + }; + let (version, from_profile) = resolved + .into_iter() + .find(|(version, _)| version.is_none() || *version != served)?; + Some(format!( + "{POM}: {group}:{artifact}:{classifier}{} resolves {}, {}", + match &d.retargeted_by { + Some(by) => format!(" ({})", retargeted_text(d, by, group, artifact)), + None if d.in_profile || from_profile => " (inside )".to_string(), + None => String::new(), + }, + version.unwrap_or("(none in this pom)"), + match wiring { + Wiring::Hosted => format!( + "not the patched {pinned}; the Socket patch covers only the main jar, so \ + that classifier copy keeps the unpatched code on the classpath" + ), + Wiring::Vendored => "which the vendored repository does not serve (it holds \ + only the main jar), so Maven fetches the public \ + classifier jar" + .to_string(), + } + )) + }) +} + +/// Why a `` declaration of `group:artifact`'s main jar +/// ([`main_jar_declarations`]) moves it off `pinned` whenever that profile +/// is active, for the first such one: a version other than the pin. A +/// profile's `` merge over the pom's own, so a direct one +/// always overrides the pin; its `` overrides only +/// what management governs, which `pin_managed` (no live direct version) +/// says. Activation is not evaluated, so every profile counts, as in +/// vendored mode. A declaration without a version takes the live one and +/// moves nothing, and a `pom` typed one carries no code (a `java-source` / +/// `javadoc` typed one is a non-executable variant, never a main jar). +/// Every version a profile's `` may give the declaration +/// counts too ([`PomDep::version_alternatives`]). +/// +/// The same holds for a live declaration that resolves `pinned` through a +/// property some profile's `` redefine (or one it names, or +/// several profiles together) to another version: Maven merges an active +/// profile's properties over the pom's own before it interpolates. +/// Vendored mode refuses to pin over such a property (`version_override`). +fn profile_override( + deps: &[PomDep], + group: &str, + artifact: &str, + pinned: &str, + pin_managed: bool, +) -> Option { + main_jar_declarations(deps, group, artifact, |_| true) + .filter(|d| is_main_jar(d.type_text.as_deref(), d.classifier.as_deref())) + .filter(|d| !d.managed || pin_managed) + .find_map(|d| { + let section = if d.managed { + " " + } else { + "" + }; + let named = named(d, group, artifact); + if !d.in_profile { + // Off the pin as built, it is no pin (or another bypass). + // One this pom leaves unresolved (a parent pom's property) + // may be the pin. + let built = build_version(d)?; + let unresolved = built.contains("${"); + if built != pinned && !unresolved { + return None; + } + // The smallest combination of profiles that moves it: for + // an unresolved one, to a version this pom does give. + let moved = d + .version_alternatives + .iter() + .find(|a| a.value != pinned && !(unresolved && a.value.contains("${")))?; + let declared = d.version_text.as_deref().unwrap_or_default(); + let value = if !matches!(moved.by, MovedBy::Profiles(_)) { + "resolve a version this reader cannot work out".to_string() + } else if moved.value.contains("${") { + format!("nothing it can resolve ({})", moved.value) + } else { + moved.value.clone() + }; + return Some(format!( + "{POM}: {section}{named} {declared} {} the \ + patched {pinned}, but the of {} make it {value}; whenever that \ + applies Maven resolves it instead of the pin", + if unresolved { + "may resolve" + } else { + "resolves" + }, + moved.by + )); + } + let version = resolutions(d).find_map(|v| v.filter(|v| *v != pinned))?; + if let Some(by) = &d.retargeted_by { + return Some(format!( + "{POM}: a {section}declaration {} carries {version}, \ + not the patched {pinned}; whenever that applies Maven resolves it instead \ + of the pin", + retargeted_text(d, by, group, artifact) + )); + } + Some(format!( + "{POM}: a {section}declaration of {named} carries \ + {version}, not the patched {pinned}; whenever that profile \ + is active Maven resolves it instead of the pin" + )) }) } @@ -783,9 +1175,35 @@ mod tests { format!("https://patch.socket.dev/patch-registry/maven/{TOKEN}/{uuid}/maven2") } - fn dep(g: &str, a: &str, v: Option<&str>) -> String { + /// The hosted repository for `UUID_A` on the Socket registry. + fn hosted_repo_a() -> String { + hosted_repo(&format!("socket-patch-{UUID_A}"), ®istry_url(UUID_A)) + } + + /// A `` with `tail` (a ``, ``, ...) after + /// its optional ``. + fn decl(g: &str, a: &str, v: Option<&str>, tail: &str) -> String { let v = v.map_or(String::new(), |v| format!("{v}")); - format!("{g}{a}{v}\n") + format!("{g}{a}{v}{tail}\n") + } + + fn dep(g: &str, a: &str, v: Option<&str>) -> String { + decl(g, a, v, "") + } + + /// A slf4j-api `{c}` copy. + fn classified(c: &str, v: Option<&str>) -> String { + decl( + "org.slf4j", + "slf4j-api", + v, + &format!("{c}"), + ) + } + + /// A slf4j-api `{t}` declaration. + fn typed(t: &str, v: Option<&str>) -> String { + decl("org.slf4j", "slf4j-api", v, &format!("{t}")) } fn pom(body: &str) -> String { @@ -1096,13 +1514,6 @@ mod tests { /// but is not attested. `sources` / `javadoc` never run and do not. #[tokio::test] async fn executable_classifier_copy_off_the_pin_is_not_attested() { - fn classified(c: &str, v: Option<&str>) -> String { - let v = v.map_or(String::new(), |v| format!("{v}")); - format!( - "org.slf4jslf4j-api\ - {v}{c}\n" - ) - } fn project(deps: &str, managed: &str) -> Project { let p = Project::new(); p.write( @@ -1112,12 +1523,20 @@ mod tests { \n\n{}{deps}\n\ \n{}\n", dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))), - hosted_repo(&format!("socket-patch-{UUID_A}"), ®istry_url(UUID_A)), + hosted_repo_a(), )), ); p } let pin = suffixed(UUID_A); + let undefined_tests = |v: Option<&str>| { + decl( + "${undefined.group}", + "slf4j-api", + v, + "tests", + ) + }; let unattested = [ // At the base release: the public classifier jar. (classified("tests", Some("1.7.36")), String::new()), @@ -1131,27 +1550,24 @@ mod tests { ), // No version this pom gives it (a parent's): fail closed. (classified("tests", None), String::new()), + // A coordinate property this pom does not define may be the GA. + (undefined_tests(Some("1.7.36")), String::new()), + // Version-less copy whose only managed entry reaches the GA + // through an undefined property: it may manage another GA, so + // the copy's version may come from outside this pom. + (classified("tests", None), undefined_tests(Some(&pin))), // A type implying an executable classifier (the vendored // reactor's rule): `test-jar` is the `tests` jar. - ( - "org.slf4jslf4j-api\ - 1.7.36test-jar\n" - .to_string(), - String::new(), - ), + (typed("test-jar", Some("1.7.36")), String::new()), ]; for (deps, managed) in &unattested { let out = run(&project(deps, managed)).await; - assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); - assert_eq!(out.unattested.len(), 1, "{deps}: {:?}", out.unattested); - let u = &out.unattested[0]; - assert_eq!(u.kind, UnattestedKind::MavenClassifierUnpatched, "{deps}"); - assert_eq!( - (u.purl.as_str(), u.uuid.as_str()), - (FX_PURL, UUID_A), - "{deps}" + assert_withheld( + &out, + UnattestedKind::MavenClassifierUnpatched, + &["org.slf4j:slf4j-api:"], + &format!("{deps} {managed}"), ); - assert!(u.detail.contains("org.slf4j:slf4j-api:"), "{}", u.detail); } let attested = [ @@ -1551,72 +1967,927 @@ mod tests { } } - /// A versioned declaration whose coordinate is a property this pom - /// does not define may be the pinned GA, so the pin is not attested - /// past it (#683). + /// Maven gives `.mvn/maven.config`'s `-D` user properties precedence + /// over the pom's `` for a `` too (but not over + /// the model's own `${project.*}`). A pin the pom spells through a + /// property the build config redefines stays a ref — rollback / remove + /// / list must still find the pom's wiring — but is not attested: the + /// build resolves the unpatched jar. A pin only the build config + /// supplies is no pom.xml wiring at all (hosted mode never writes one, + /// and rollback / remove never edit `.mvn/maven.config`): diagnosed, + /// never a ref. #[tokio::test] - async fn undefined_coordinate_property_is_not_attested_past() { - let repo = hosted_repo(&format!("socket-patch-{UUID_A}"), ®istry_url(UUID_A)); - let p = Project::new(); - p.write( - "pom.xml", - pom(&format!( - "\n{}\n\ - \n{}\n\n{repo}\n", - dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))), - dep("${parent.g}", "slf4j-api", Some("1.7.36")), - )), - ); - let out = run(&p).await; - assert_refs(&out, &[]); - assert!( - diag_codes(&out).contains(&DIAG_REF_INVALID), - "{:?}", - out.diagnostics - ); - assert!( - out.diagnostics - .iter() - .any(|d| d.detail.contains("org.slf4j:slf4j-api") && d.detail.contains("1.7.36")), - "{:?}", - out.diagnostics - ); - - // A placeholder that cannot be the GA (a non-jar type, or literal - // text around the reference that differs) does not. - for other in [ - "${parent.g}${bom}\ - 3pomimport", - "${parent.g}${a}-core\ - 3", + async fn version_property_reads_maven_config_overrides() { + #[derive(Debug, PartialEq)] + enum Expect { + Attested, + Overridden, + ConfigOnly, + NoRef, + } + let repo = hosted_repo_a(); + let pin = suffixed(UUID_A); + let by_prop = dep("org.slf4j", "slf4j-api", Some("${slf4j.version}")); + let by_model = dep("org.slf4j", "slf4j-api", Some("${project.version}")); + for (value, declared, config, expect) in [ + // The build config moves the pin back to the base release. + ( + pin.as_str(), + &by_prop, + "-Dslf4j.version=1.7.36\n".to_string(), + Expect::Overridden, + ), + ( + pin.as_str(), + &by_prop, + "--define slf4j.version=1.7.30\n".to_string(), + Expect::Overridden, + ), + // The build config swaps one Socket pin for another: the pom's + // pin is still pom.xml wiring, so no config-only diagnostic. + ( + pin.as_str(), + &by_prop, + format!("-Dslf4j.version={}\n", suffixed(UUID_B)), + Expect::Overridden, + ), + // The build config alone supplies the pin. + ( + "1.7.36", + &by_prop, + format!("-Dslf4j.version={pin}\n"), + Expect::ConfigOnly, + ), + // `${project.version}` is the model's (1.0.0), whatever -D says. + ( + "1.7.36", + &by_model, + format!("-Dproject.version={pin}\n"), + Expect::NoRef, + ), + // Unrelated user properties leave the pom's own. + ( + pin.as_str(), + &by_prop, + "-Dother=1\n".to_string(), + Expect::Attested, + ), ] { let p = Project::new(); p.write( "pom.xml", pom(&format!( - "\n{}{other}\n\n\n{repo}\n", - dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))), + "{value}\n\ + \n{declared}\n\n{repo}\n", )), ); + p.write(".mvn/maven.config", &config); let out = run(&p).await; - assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + let what = format!( + "{config}: {:?} {:?} {:?}", + out.refs, out.unattested, out.diagnostics + ); + match expect { + Expect::Attested | Expect::Overridden => { + if expect == Expect::Attested { + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert!(out.unattested.is_empty(), "{what}"); + } else { + assert_withheld( + &out, + UnattestedKind::MavenConfigOverride, + &[".mvn/maven.config"], + &what, + ); + } + assert!( + !out.diagnostics + .iter() + .any(|d| d.detail.contains("only through")), + "{what}" + ); + } + Expect::ConfigOnly | Expect::NoRef => { + assert_refs(&out, &[]); + assert!(out.unattested.is_empty(), "{what}"); + assert_eq!( + out.diagnostics + .iter() + .any(|d| d.detail.contains(".mvn/maven.config")), + expect == Expect::ConfigOnly, + "{what}" + ); + } + } } } + /// A `` declaration of the pinned GA applies whenever that + /// profile is active, and the hosted rewriter leaves it as written + /// (`redirect_maven_profile_dependency_unpatched`); vendored mode treats + /// every profile as live. One that moves the GA's main jar off the pin + /// keeps the ref (rollback / remove / list still find it) but is never + /// attested: with the profile on, Maven resolves the unpatched jar. A + /// profile's `` moves it only where management + /// governs (a direct literal `` beats it), and an executable + /// classifier copy — live or in a profile — is judged by the version it + /// resolves, its own or its classifier-keyed managed one. #[tokio::test] - async fn unsafe_coordinates_on_a_socket_pin_are_invalid() { - let p = Project::new(); - p.write( - "pom.xml", - hosted_pom(UUID_A).replace( - "org.slf4j", - "../../etc", - ), + async fn profile_declaration_off_the_pin_is_not_attested() { + let repo = hosted_repo_a(); + let pin = suffixed(UUID_A); + let ga = |v: Option<&str>| dep("org.slf4j", "slf4j-api", v); + // The live pin: a direct literal, a managed one (governing a + // version-less declaration), or a direct literal beside a + // classifier-keyed managed entry at the pin. + let direct_pin = deps(&ga(Some(&pin))); + let managed_pin = format!("{}{}", mgmt(&ga(Some(&pin))), deps(&ga(None))); + let classifier_managed_pin = format!( + "{}{}", + mgmt(&classified("tests", Some(&pin))), + deps(&ga(Some(&pin))) ); - let out = run(&p).await; - assert_refs(&out, &[]); - assert!(diag_codes(&out).contains(&DIAG_REF_INVALID)); - } + let project = |live: &str, profile: &str| { + let p = Project::new(); + p.write( + "pom.xml", + pom(&format!( + "{live}\n{repo}\n\ + p\n{profile}\n", + )), + ); + p + }; + let profile_kind = UnattestedKind::MavenProfileUnpatched; + let classifier_kind = UnattestedKind::MavenClassifierUnpatched; + let tests_unversioned = classified("tests", None); + let unattested = [ + // The main jar at the base release, another release, one this + // pom cannot resolve, another Socket pin. + (&direct_pin, deps(&ga(Some("1.7.36"))), profile_kind), + (&direct_pin, deps(&ga(Some("1.7.30"))), profile_kind), + (&direct_pin, deps(&ga(Some("${undefined}"))), profile_kind), + ( + &direct_pin, + deps(&ga(Some("1.7.36-socket.88888888"))), + profile_kind, + ), + // Management that governs: the live pin is managed too. + (&managed_pin, mgmt(&ga(Some("1.7.36"))), profile_kind), + // A code-carrying type is not the pin's coordinate either: it + // is an executable variant (`test-jar` is the `tests` jar, see + // `is_variant` / `is_executable_variant`). + ( + &direct_pin, + deps(&typed("test-jar", Some("1.7.36"))), + classifier_kind, + ), + // An executable classifier copy off the pin: its own version, + // none at all, or a classifier-keyed managed one. + ( + &direct_pin, + deps(&classified("tests", Some("1.7.36"))), + classifier_kind, + ), + (&direct_pin, deps(&tests_unversioned), classifier_kind), + ( + &direct_pin, + format!( + "{}{}", + mgmt(&classified("tests", Some("1.7.36"))), + deps(&tests_unversioned) + ), + classifier_kind, + ), + // The profile's classifier management overrides the live one. + ( + &classifier_managed_pin, + format!( + "{}{}", + mgmt(&classified("tests", Some("1.7.36"))), + deps(&tests_unversioned) + ), + classifier_kind, + ), + ]; + for (live, profile, kind) in &unattested { + let out = run(&project(live, profile)).await; + assert_withheld( + &out, + *kind, + &["org.slf4j:slf4j-api", ""], + &format!("{live} {profile}"), + ); + } + + let attested = [ + // No version: the live pin applies. + (&direct_pin, deps(&ga(None))), + // The pin itself. + (&direct_pin, deps(&ga(Some(&pin)))), + (&managed_pin, mgmt(&ga(Some(&pin)))), + // Management a direct literal version beats. + (&direct_pin, mgmt(&ga(Some("1.7.36")))), + // Another GA. + ( + &direct_pin, + deps(&dep("org.slf4j", "slf4j-simple", Some("1.7.36"))), + ), + // A non-executable classifier copy, or one on the pin. + (&direct_pin, deps(&classified("sources", Some("1.7.36")))), + (&direct_pin, deps(&classified("tests", Some(&pin)))), + // Classifier management no declaration takes. + (&direct_pin, mgmt(&classified("tests", Some("1.7.36")))), + // A version-less classifier copy the live management pins. + (&classifier_managed_pin, deps(&tests_unversioned)), + // A pom-typed declaration carries no code. + (&direct_pin, deps(&typed("pom", Some("1.7.36")))), + // Profile properties only. + ( + &direct_pin, + "1\n".to_string(), + ), + ]; + for (live, profile) in &attested { + let out = run(&project(live, profile)).await; + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert!(out.unattested.is_empty(), "{profile}: {:?}", out.unattested); + } + } + + /// Whether `out` attests `purl`: a ref no unattested entry withholds. + fn attests(out: &Discovery, purl: &str) -> bool { + out.refs.iter().any(|r| { + r.purl == purl + && !out + .unattested + .iter() + .any(|u| u.purl == r.purl && u.uuid == r.uuid) + }) + } + + /// `out` finds the hosted slf4j-api pin for `UUID_A` but withholds it: + /// exactly one unattested entry, of `kind`, for that pin, whose detail + /// names every one of `needles` (`case` names the case in a failure). + #[track_caller] + fn assert_withheld(out: &Discovery, kind: UnattestedKind, needles: &[&str], case: &str) { + assert_refs(out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert_eq!(out.unattested.len(), 1, "{case}: {:?}", out.unattested); + let u = &out.unattested[0]; + assert_eq!(u.kind, kind, "{case}: {}", u.detail); + assert_eq!( + (u.purl.as_str(), u.uuid.as_str()), + (FX_PURL, UUID_A), + "{case}" + ); + for needle in needles { + assert!( + u.detail.contains(needle), + "{case}: {needle:?}: {}", + u.detail + ); + } + } + + /// A hosted project pinning slf4j-api through `decl` (a + /// `` / `` block), with the root + /// `` `props` and one `` per entry of `profiles` + /// (each a profile body). + fn property_project(props: &str, decl: &str, profiles: &[&str]) -> Project { + let repo = hosted_repo_a(); + let profiles: String = profiles + .iter() + .enumerate() + .map(|(i, body)| format!("p{i}\n{body}\n")) + .collect(); + let p = Project::new(); + p.write( + "pom.xml", + pom(&format!( + "{props}\n{decl}\n{repo}\n\ + \n{profiles}\n" + )), + ); + p + } + + fn deps(d: &str) -> String { + format!("\n{d}\n") + } + + fn mgmt(d: &str) -> String { + format!("{}\n", deps(d)) + } + + fn direct_decl(version: &str) -> String { + deps(&dep("org.slf4j", "slf4j-api", Some(version))) + } + + /// A pin spelled through a property is what Maven resolves only while + /// no active profile's `` redefines that property (or one + /// it names) to anything else: Maven merges an active profile's + /// properties over the pom's own before it interpolates the + /// ``. Vendored mode refuses to pin over such a property + /// (`version_override`), so the ref stays (rollback / remove / list + /// find it) but is never attested. User properties + /// (`.mvn/maven.config`) win over every profile's. + #[tokio::test] + async fn profile_properties_redefining_a_pin_property_are_not_attested() { + let pin = suffixed(UUID_A); + let v = |value: &str| format!("{value}"); + let w = |value: &str| format!("{value}"); + let direct = direct_decl("${slf4j.version}"); + let managed = format!( + "{}{}", + mgmt(&dep("org.slf4j", "slf4j-api", Some("${slf4j.version}"))), + deps(&dep("org.slf4j", "slf4j-api", None)), + ); + let withheld = [ + // The base release. + (v(&pin), &direct, vec![in_props(&v("1.7.36"))]), + (v(&pin), &managed, vec![in_props(&v("1.7.36"))]), + // Through a property the pin's property names. + (v("${w}") + &w(&pin), &direct, vec![in_props(&w("1.7.30"))]), + // A value this pom cannot resolve, or a cycle. + (v(&pin), &direct, vec![in_props(&v("${undefined}"))]), + (v(&pin), &direct, vec![in_props(&v("${slf4j.version}"))]), + // Two profiles that move the pin only together. + ( + v(&pin) + &w(&pin), + &direct, + vec![in_props(&v("${w}")), in_props(&w("1.7.36"))], + ), + ]; + for (root, decl, profiles) in &withheld { + let profiles: Vec<&str> = profiles.iter().map(String::as_str).collect(); + let out = run(&property_project(root, decl, &profiles)).await; + assert_withheld( + &out, + UnattestedKind::MavenProfileUnpatched, + &["org.slf4j:slf4j-api", ""], + &format!("{root} {decl} {profiles:?}"), + ); + } + + for (root, profile, config) in [ + // The pin itself, or an unrelated property. + (v(&pin), in_props(&v(&pin)), None), + (v(&pin), in_props("1"), None), + (v("${w}") + &w(&pin), in_props(&w(&pin)), None), + // A user property wins over every profile's. + ( + v(&pin), + in_props(&v("1.7.36")), + Some(format!("-Dslf4j.version={pin}\n")), + ), + ] { + let p = property_project(&root, &direct, &[&profile]); + if let Some(config) = &config { + p.write(".mvn/maven.config", config); + } + let out = run(&p).await; + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert!( + attests(&out, FX_PURL), + "{root} {profile}: {:?}", + out.unattested + ); + } + } + + /// A `` declaration's `${property}` version reads its own + /// profile's `` first: that profile is active whenever the + /// declaration applies. + #[tokio::test] + async fn profile_declaration_reads_its_own_profile_properties() { + let pin = suffixed(UUID_A); + let profile = |value: &str| { + format!( + "{value}\n\ + \n{}\n", + dep("org.slf4j", "slf4j-api", Some("${slf4j.version}")) + ) + }; + let direct = direct_decl(&pin); + for (root, own, attested) in [ + // The root resolves the pin, the profile the base release. + (pin.as_str(), "1.7.36", false), + // The root resolves the base release, the profile the pin. + ("1.7.36", pin.as_str(), true), + ] { + let p = property_project( + &format!("{root}"), + &direct, + &[&profile(own)], + ); + let out = run(&p).await; + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert_eq!( + attests(&out, FX_PURL), + attested, + "{own}: {:?}", + out.unattested + ); + } + } + + /// One `property_project` case: root ``, the declarations, + /// each profile's body, `.mvn/maven.config`. + type CoordinateCase = (String, String, Vec, Option); + + /// Runs `case` and checks the slf4j-api ref is found, and attested + /// exactly when `attested` (else withheld as a profile override naming + /// the GA and the profile ``). + async fn assert_coordinate_case(case: &CoordinateCase, attested: bool) { + let (props, decl, profiles, config) = case; + let profiles: Vec<&str> = profiles.iter().map(String::as_str).collect(); + let p = property_project(props, decl, &profiles); + if let Some(config) = config { + p.write(".mvn/maven.config", config); + } + let out = run(&p).await; + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + if attested { + assert!( + attests(&out, FX_PURL), + "{props} {decl} {profiles:?}: {:?}", + out.unattested + ); + return; + } + assert_eq!( + out.unattested.len(), + 1, + "{props} {decl} {profiles:?}: {:?}", + out.unattested + ); + let u = &out.unattested[0]; + // A retargeted classifier copy is weighed as one. + assert!( + matches!( + u.kind, + UnattestedKind::MavenProfileUnpatched | UnattestedKind::MavenClassifierUnpatched + ), + "{decl}: {:?}", + u.kind + ); + assert_eq!((u.purl.as_str(), u.uuid.as_str()), (FX_PURL, UUID_A)); + assert!( + u.detail.contains("org.slf4j:slf4j-api") + && u.detail.contains("") + && u.detail.contains("coordinates"), + "{}", + u.detail + ); + } + + fn in_props(body: &str) -> String { + format!("{body}\n") + } + + /// A pin declared through a `${property}` groupId or artifactId is the + /// pin of that GA only while no active profile's `` + /// redefine the property (or one it names): Maven merges them over the + /// pom's own before it interpolates the coordinates, so with such a + /// profile active the pin names another package and slf4j-api resolves + /// from wherever else it is declared (here: transitively, unpinned). + #[tokio::test] + async fn profile_properties_moving_the_pinned_coordinates_are_not_attested() { + let pin = suffixed(UUID_A); + let direct = |g: &str, a: &str| deps(&dep(g, a, Some(&pin))); + let managed = mgmt(&dep("${g}", "slf4j-api", Some(&pin))); + let case = |props: &str, decl: &str, profiles: &[&str], config: Option<&str>| { + ( + props.to_string(), + decl.to_string(), + profiles.iter().map(|p| in_props(p)).collect::>(), + config.map(str::to_string), + ) + }; + let g = "org.slf4j"; + let by_group = direct("${g}", "slf4j-api"); + let withheld = [ + // The groupId, the artifactId, or a managed pin. + case(g, &by_group, &["org.other"], None), + case( + "slf4j-api", + &direct("org.slf4j", "${a}"), + &["slf4j-simple"], + None, + ), + case(g, &managed, &["org.other"], None), + // Through a property the coordinate's names, or partly literal. + case( + "${vendor}org.slf4j", + &by_group, + &["org.other"], + None, + ), + case( + "slf4j", + &direct("org.${v}", "${v}-api"), + &["log4j"], + None, + ), + // A value this pom cannot resolve, or a cycle. + case(g, &by_group, &["${undefined}"], None), + case(g, &by_group, &["${g}"], None), + // Two profiles that move it only together. + case( + "org.slf4jorg.slf4j", + &by_group, + &["${w}", "org.other"], + None, + ), + // A user property in the chain does not fix a name above it. + case( + "${vendor}", + &by_group, + &["org.other"], + Some("-Dvendor=org.slf4j\n"), + ), + ]; + for c in &withheld { + assert_coordinate_case(c, false).await; + } + let attested = [ + // The same GA, or an unrelated property. + case(g, &by_group, &["org.slf4j"], None), + case(g, &by_group, &["org.other"], None), + // A user property wins over every profile's. + case(g, &by_group, &["org.other"], Some("-Dg=org.slf4j\n")), + case( + "${vendor}org.other", + &by_group, + &["org.another"], + Some("-Dvendor=org.slf4j\n"), + ), + ]; + for c in &attested { + assert_coordinate_case(c, true).await; + } + } + + /// Another declaration whose `${property}` coordinates name another + /// package while no profile is active but slf4j-api once a profile's + /// `` redefine them overrides the pin with its own version + /// whenever that profile is active. So does one inside a profile whose + /// own `` make it slf4j-api. + #[tokio::test] + async fn profile_properties_turning_a_declaration_into_the_pinned_ga_are_not_attested() { + let pin = suffixed(UUID_A); + let pinned = dep("org.slf4j", "slf4j-api", Some(&pin)); + let with = |other: &str| format!("\n{pinned}{other}\n"); + let other = |v: Option<&str>| dep("${h}", "slf4j-api", v); + let other_with = |v: &str, tail: &str| decl("${h}", "slf4j-api", Some(v), tail); + let classified = |c: &str, v: Option<&str>| { + decl( + "${h}", + "slf4j-api", + v, + &format!("{c}"), + ) + }; + let h = "org.other"; + let to_slf4j = in_props("org.slf4j"); + let case = |props: &str, decl: String, profiles: Vec, config: Option<&str>| { + ( + props.to_string(), + decl, + profiles, + config.map(str::to_string), + ) + }; + let withheld = [ + // The base release, or another one. + case( + h, + with(&other(Some("1.7.36"))), + vec![to_slf4j.clone()], + None, + ), + case( + h, + with(&other(Some("1.7.30"))), + vec![to_slf4j.clone()], + None, + ), + // An empty `` is Maven's default, `jar`. + case( + h, + with(&other_with("1.7.30", "")), + vec![to_slf4j.clone()], + None, + ), + // Managed, where management governs the pin. + case( + h, + deps(&dep("org.slf4j", "slf4j-api", None)) + + &mgmt(&format!("{pinned}{}", other(Some("1.7.36")))), + vec![to_slf4j.clone()], + None, + ), + // A version the same profile moves too. + case( + &format!("{h}2.0.0"), + with(&other(Some("${v}"))), + vec![in_props("org.slf4j1.7.36")], + None, + ), + // A value the pom cannot resolve may be slf4j-api. + case( + h, + with(&other(Some("1.7.36"))), + vec![in_props("${undefined}")], + None, + ), + // An executable classifier copy, with or without a version. + case( + h, + with(&classified("tests", Some("1.7.36"))), + vec![to_slf4j.clone()], + None, + ), + case( + h, + with(&classified("tests", None)), + vec![to_slf4j.clone()], + None, + ), + // A `test-jar` is the `tests` classifier copy. + case( + h, + with(&other_with("1.7.36", "test-jar")), + vec![to_slf4j.clone()], + None, + ), + // A type with an explicit classifier: that classifier's copy. + case( + h, + with(&other_with( + "1.7.30", + "test-jartests", + )), + vec![to_slf4j.clone()], + None, + ), + // Through a user property lower in the chain. + case( + "${corp}", + with(&other(Some("1.7.36"))), + vec![to_slf4j.clone()], + Some("-Dcorp=org.other\n"), + ), + ]; + for c in &withheld { + assert_coordinate_case(c, false).await; + } + // A profile declaration its own profile's properties retarget: it + // is read under its own profile, so it is a profile declaration of + // the GA itself. + let own = property_project( + h, + &with(""), + &[&(to_slf4j.clone() + &deps(&other(Some("1.7.36"))))], + ); + let out = run(&own).await; + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + let kinds: Vec<_> = out.unattested.iter().map(|u| u.kind).collect(); + assert_eq!( + kinds, + [UnattestedKind::MavenProfileUnpatched], + "{:?}", + out.unattested + ); + let attested = [ + // No version of its own: the live pin applies. + case(h, with(&other(None)), vec![to_slf4j.clone()], None), + // Managed, while a direct version (the pin) governs. + case( + h, + deps(&pinned) + &mgmt(&other(Some("1.7.36"))), + vec![to_slf4j.clone()], + None, + ), + // A non-executable classifier copy, or another type. + case( + h, + with(&classified("sources", Some("1.7.36"))), + vec![to_slf4j.clone()], + None, + ), + case( + h, + with(&other_with("1.7.36", "pom")), + vec![to_slf4j.clone()], + None, + ), + case( + h, + with(&other_with("1.7.36", "war")), + vec![to_slf4j.clone()], + None, + ), + // The same profile moves its coordinates and its version onto + // the pin: read together, it declares the pin there. + case( + &format!("{h}2.0.0"), + with(&other(Some("${v}"))), + vec![in_props(&format!("org.slf4j{pin}"))], + None, + ), + // A user property wins over every profile's. + case( + h, + with(&other(Some("1.7.36"))), + vec![to_slf4j.clone()], + Some("-Dh=org.other\n"), + ), + ]; + for c in &attested { + assert_coordinate_case(c, true).await; + } + } + + /// Coordinate properties that cannot make any declaration the pinned + /// GA, or move the pin off it, withhold nothing: a profile moving an + /// unrelated package to another unrelated one, a partly undefined + /// coordinate no profile touches, and a profile property no coordinate + /// names. + #[tokio::test] + async fn unrelated_coordinate_properties_do_not_withhold() { + let pin = suffixed(UUID_A); + let pinned = dep("org.slf4j", "slf4j-api", Some(&pin)); + let with = |other: &str| format!("\n{pinned}{other}\n"); + let none: Option = None; + for case in [ + ( + "org.other".to_string(), + with(&dep("${h}", "slf4j-api", Some("1.7.36"))), + vec![in_props("org.third")], + none.clone(), + ), + ( + "org.other".to_string(), + with(&dep("org.slf4j", "${h}", Some("1.7.36"))), + vec![in_props("slf4j-simple")], + none.clone(), + ), + ( + "com.corp".to_string(), + with(&dep("${h}.${undefined}", "slf4j-api", Some("1.7.36"))), + vec![in_props("1")], + none.clone(), + ), + ( + "org.other1".to_string(), + with(&dep("${h}", "slf4j-api", Some("1.7.36"))), + vec![in_props("2")], + none.clone(), + ), + ( + "org.slf4j".to_string(), + deps(&dep("${g}", "slf4j-api", Some(&pin))), + vec![in_props("org.other")], + none.clone(), + ), + // A profile declaration whose groupId only its own profile's + // `` define, as another group: whenever it is + // read, it names that group. + ( + String::new(), + with(""), + vec![in_props("org.other") + &deps(&dep("${g}", "slf4j-api", Some("2.0")))], + none.clone(), + ), + ] { + assert_coordinate_case(&case, true).await; + } + } + + /// A `${property}` version resolves through every property it names, + /// with user properties first at each level, as Maven interpolates; a + /// cycle, or a chain deeper than the vendored reactor follows, is + /// never a pin. + #[tokio::test] + async fn version_property_resolves_through_nested_properties() { + let pin = suffixed(UUID_A); + // `${p1}` ... `{end}`. + let chain = |links: usize, end: &str| -> String { + (0..links) + .map(|i| { + let value = if i + 1 == links { + end.to_string() + } else { + format!("${{p{}}}", i + 1) + }; + format!("{value}") + }) + .collect() + }; + let split = format!( + "${{p1}}-socket.${{p2}}1.7.36{}", + &UUID_A[..8] + ); + let user_pin = format!("-Dp1={pin}\n"); + for (props, config, attested) in [ + (chain(2, &pin), None, true), + (chain(3, &pin), None, true), + (split, None, true), + // The deepest chain the vendored reactor resolves, and one more. + (chain(16, &pin), None, true), + (chain(17, &pin), None, false), + // A user property redefines a nested one: off the pin, or onto + // a Socket version only the build config supplies (never a + // pom.xml ref). + (chain(2, &pin), Some("-Dp1=1.7.36\n"), false), + (chain(2, "1.7.36"), Some(user_pin.as_str()), false), + // A cycle. + ("${p1}${p0}".to_string(), None, false), + ("${p0}".to_string(), None, false), + ] { + let p = property_project(&props, &direct_decl("${p0}"), &[]); + if let Some(config) = config { + p.write(".mvn/maven.config", config); + } + let out = run(&p).await; + assert_eq!( + attests(&out, FX_PURL), + attested, + "{props} {config:?}: {:?} {:?} {:?}", + out.refs, + out.unattested, + out.diagnostics + ); + } + } + + /// A versioned declaration whose coordinate is a property this pom + /// does not define may be the pinned GA, so the pin is not attested + /// past it (#683). + #[tokio::test] + async fn undefined_coordinate_property_is_not_attested_past() { + let repo = hosted_repo(&format!("socket-patch-{UUID_A}"), ®istry_url(UUID_A)); + let p = Project::new(); + p.write( + "pom.xml", + pom(&format!( + "\n{}\n\ + \n{}\n\n{repo}\n", + dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))), + dep("${parent.g}", "slf4j-api", Some("1.7.36")), + )), + ); + let out = run(&p).await; + assert_refs(&out, &[]); + assert!( + diag_codes(&out).contains(&DIAG_REF_INVALID), + "{:?}", + out.diagnostics + ); + assert!( + out.diagnostics + .iter() + .any(|d| d.detail.contains("org.slf4j:slf4j-api") && d.detail.contains("1.7.36")), + "{:?}", + out.diagnostics + ); + + // A placeholder that cannot be the GA (a non-jar type, or literal + // text around the reference that differs) does not. + for other in [ + "${parent.g}${bom}\ + 3pomimport", + "${parent.g}${a}-core\ + 3", + ] { + let p = Project::new(); + p.write( + "pom.xml", + pom(&format!( + "\n{}{other}\n\n\n{repo}\n", + dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))), + )), + ); + let out = run(&p).await; + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + } + } + + #[tokio::test] + async fn unsafe_coordinates_on_a_socket_pin_are_invalid() { + let p = Project::new(); + p.write( + "pom.xml", + hosted_pom(UUID_A).replace( + "org.slf4j", + "../../etc", + ), + ); + let out = run(&p).await; + assert_refs(&out, &[]); + assert!(diag_codes(&out).contains(&DIAG_REF_INVALID)); + } #[tokio::test] async fn registry_only_pom_yields_nothing() { @@ -1755,6 +3026,21 @@ mod tests { p } + /// `vendored_project(UUID_A)` with its wired pom.xml passed through + /// `edit`. + fn vendored_project_with(edit: impl FnOnce(&str) -> String) -> Project { + let p = vendored_project(UUID_A); + let wired = std::fs::read_to_string(p.root().join("pom.xml")).expect("read pom"); + p.write("pom.xml", edit(&wired)); + p + } + + /// `pom` with `extra` spliced in just before its closing ``. + fn before_close(pom: &str, extra: &str) -> String { + let at = pom.rfind("").expect("project close"); + format!("{}{extra}{}", &pom[..at], &pom[at..]) + } + #[tokio::test] async fn vendor_backend_wiring_yields_the_committed_jar() { let p = vendored_project(UUID_A); @@ -1768,6 +3054,393 @@ mod tests { assert!(!r.lockfile_basis_ok()); } + /// The retired vendored wiring serves the ORIGINAL GAV, main jar only: + /// a profile that moves the GA to another version bypasses it whenever + /// it is active, and an executable classifier copy (live or in a + /// profile, at any version) resolves from the next repository — the + /// public jar. The ref stays but is not attested. + #[tokio::test] + async fn vendored_ref_bypassed_by_a_profile_or_classifier_is_not_attested() { + let classified = |c: &str, v: &str| { + let tail = format!("{c}"); + decl("org.apache.commons", "commons-text", Some(v), &tail) + }; + let in_profile = |d: &str| { + format!( + "p\n{d}\n" + ) + }; + for (extra, kind) in [ + ( + in_profile(&dep("org.apache.commons", "commons-text", Some("1.10.1"))), + Some(UnattestedKind::MavenProfileUnpatched), + ), + ( + in_profile(&dep("org.apache.commons", "commons-text", Some("1.10.0"))), + None, + ), + ( + deps(&classified("tests", "1.10.0")), + Some(UnattestedKind::MavenClassifierUnpatched), + ), + ( + in_profile(&classified("tests", "1.10.0")), + Some(UnattestedKind::MavenClassifierUnpatched), + ), + (deps(&classified("sources", "1.10.0")), None), + ] { + let p = vendored_project_with(|wired| before_close(wired, &extra)); + let out = run(&p).await; + assert_refs(&out, &[(V_PURL, UUID_A, WiringMode::Vendored)]); + let kinds: Vec<_> = out.unattested.iter().map(|u| u.kind).collect(); + assert_eq!(kinds, kind.into_iter().collect::>(), "{extra}"); + } + } + + /// The same for a profile's `` that move a `${property}` + /// version of the vendored GA off the vendored version. + #[tokio::test] + async fn vendored_ref_under_profile_properties_is_not_attested() { + // `root` is the pom's own ``; none leaves `${ct}` to a + // parent pom this reader never sees, which may give the vendored + // version, while the profile's value is known. + for (root, version, attested) in [ + ("1.10.0", "1.10.1", false), + ("1.10.0", "1.10.0", true), + ("", "1.10.1", false), + ("", "1.10.0", true), + ] { + let p = vendored_project_with(|wired| { + before_close( + &wired.replace("1.10.0", "${ct}"), + &format!( + "{root}\np\ + {version}\n" + ), + ) + }); + let out = run(&p).await; + assert_refs(&out, &[(V_PURL, UUID_A, WiringMode::Vendored)]); + assert_eq!( + attests(&out, V_PURL), + attested, + "{root:?} {version}: {:?}", + out.unattested + ); + } + } + + /// The pre-v5 vendored repository serves only the original GAV's main + /// jar, so an executable classifier copy a profile's `` + /// retarget onto the vendored GA comes from the next repository even at + /// the vendored version; a non-executable one does not + /// withhold. + #[tokio::test] + async fn vendored_ref_under_a_retargeted_classifier_copy_is_not_attested() { + for (classifier, attested) in [("tests", false), ("sources", true)] { + let copy = format!( + "${{h}}commons-text\ + 1.10.0{classifier}\n \ + " + ); + let p = vendored_project_with(|wired| { + before_close( + &wired.replacen("", ©, 1), + "org.other\np\ + org.apache.commons\n", + ) + }); + let out = run(&p).await; + assert_refs(&out, &[(V_PURL, UUID_A, WiringMode::Vendored)]); + assert_eq!( + attests(&out, V_PURL), + attested, + "{classifier}: {:?}", + out.unattested + ); + if !attested { + let u = &out.unattested[0]; + assert_eq!(u.kind, UnattestedKind::MavenClassifierUnpatched); + assert!( + u.detail.contains("coordinates") && u.detail.contains("profile p"), + "{}", + u.detail + ); + } + } + } + + /// A `${project.version}` is the project's own ``, which may + /// itself be spelled through a property (`${revision}`, Maven's + /// CI-friendly versions): a profile or a `-D` user property that + /// redefines that property moves the model reference too. + #[tokio::test] + async fn model_references_move_with_the_properties_they_are_spelled_through() { + let pin = suffixed(UUID_A); + let repo = hosted_repo_a(); + let project = |revision: &str, profile: &str| { + let p = Project::new(); + p.write( + "pom.xml", + format!( + "\n\n4.0.0\n\ + com.exampleapp\ + ${{revision}}\n\ + {revision}\n\ + \n{}\n\n{repo}\n\ + ci{profile}\n\n", + dep("org.slf4j", "slf4j-api", Some("${project.version}")), + ), + ); + p + }; + // A profile that redefines what the project version is spelled + // through moves the pin. + let out = run(&project( + &pin, + "1.7.36", + )) + .await; + assert_withheld(&out, UnattestedKind::MavenProfileUnpatched, &[], ""); + // One that keeps it does not. + let out = run(&project( + &pin, + &format!("{pin}"), + )) + .await; + assert!(attests(&out, FX_PURL), "{:?}", out.unattested); + // A Socket version only `-Drevision=` supplies is no pom.xml ref. + let p = project("1.7.36", ""); + p.write(".mvn/maven.config", format!("-Drevision={pin}\n")); + let out = run(&p).await; + assert!(!attests(&out, FX_PURL), "{:?}", out.refs); + assert!( + out.diagnostics.iter().any( + |d| d.code == DIAG_REF_UNATTRIBUTABLE && d.detail.contains(".mvn/maven.config") + ), + "{:?}", + out.diagnostics + ); + } + + /// A property defined twice is Maven's LAST + /// definition; a profile declaration's coordinates read its own + /// profile's `` as its version does; a profile is named by + /// its own ``, not one nested in it. + #[tokio::test] + async fn duplicate_properties_profile_coordinates_and_profile_ids() { + let pin = suffixed(UUID_A); + let p = property_project( + &format!("{pin}1.7.36"), + &direct_decl("${slf4j.version}"), + &[], + ); + let out = run(&p).await; + assert!(!attests(&out, FX_PURL), "{:?}", out.refs); + + let p = property_project( + "org.other", + &direct_decl(&pin), + &[ + "org.slf4j\n\n\ + ${g}slf4j-api\ + 1.7.30\n\n", + ], + ); + let out = run(&p).await; + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert!(!attests(&out, FX_PURL), "{:?}", out.unattested); + + let repo = hosted_repo_a(); + let p = Project::new(); + p.write( + "pom.xml", + pom(&format!( + "{pin}\n{}\n{repo}\n\ + mirror\ + https://example.test/m2\ + ci1.7.30\n", + direct_decl("${v}"), + )), + ); + let out = run(&p).await; + assert_eq!(out.unattested.len(), 1, "{:?}", out.unattested); + let detail = &out.unattested[0].detail; + assert!( + detail.contains("profile ci") && !detail.contains("mirror"), + "{detail}" + ); + } + + /// A profile property written with attributes (`combine.self`) or + /// whitespace in its tag is still a definition Maven reads. + #[tokio::test] + async fn profile_properties_with_attributes_are_read() { + let pin = suffixed(UUID_A); + for profile in [ + "1.7.36", + "1.7.36", + "\n1.7.36", + ] { + let p = property_project( + &format!("{pin}"), + &direct_decl("${slf4j.version}"), + &[profile], + ); + let out = run(&p).await; + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert!(!attests(&out, FX_PURL), "{profile}: {:?}", out.unattested); + } + } + + /// A nested `${…}` in a profile's value reads that profile's own + /// properties first, as Maven merges the whole profile before it + /// interpolates: a profile that keeps the pin through its own + /// property does not withhold it. + #[tokio::test] + async fn profile_values_resolve_through_their_own_profile() { + let pin = suffixed(UUID_A); + let p = property_project( + &format!("{pin}1.7.36"), + &direct_decl("${slf4j.version}"), + &[&format!( + "${{w}}{pin}" + )], + ); + let out = run(&p).await; + assert!(attests(&out, FX_PURL), "{:?}", out.unattested); + } + + /// A profile `` this reader cannot parse withholds a + /// `${property}` pin (fail closed) instead of failing the whole pom; a + /// literal pin, which no property moves, is still attested. + #[tokio::test] + async fn unreadable_profile_properties_withhold_only_property_pins() { + let pin = suffixed(UUID_A); + let broken = "1.7.36"; + let p = property_project( + &format!("{pin}"), + &direct_decl("${slf4j.version}"), + &[broken], + ); + let out = run(&p).await; + assert_withheld(&out, UnattestedKind::MavenProfileUnpatched, &[], ""); + let p = property_project("", &direct_decl(&pin), &[broken]); + let out = run(&p).await; + assert!( + attests(&out, FX_PURL), + "{:?} {:?}", + out.unattested, + out.diagnostics + ); + } + + /// Profiles that each keep the pin, however many and however deep the + /// chain they spell it through, never withhold it: every combination + /// is checked, not a capped cross product. + #[tokio::test] + async fn many_profiles_that_keep_the_pin_are_attested() { + let pin = suffixed(UUID_A); + // `${p1}` ... `{pin}`. + let chain: String = (0..5) + .map(|i| match i { + 4 => format!("{pin}"), + i => format!("${{p{}}}", i + 1), + }) + .collect(); + let profile = format!("{chain}"); + let profiles = [profile.as_str(); 5]; + let p = property_project(&chain, &direct_decl("${p0}"), &profiles); + let out = run(&p).await; + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert!(attests(&out, FX_PURL), "{:?}", out.unattested); + } + + /// The withheld statement names the profiles that move the pin and + /// the version they move it to. + #[tokio::test] + async fn profile_property_detail_names_the_profile_and_version() { + let pin = suffixed(UUID_A); + let p = property_project( + &format!("{pin}"), + &direct_decl("${slf4j.version}"), + &[ + "1", + "1.7.30", + ], + ); + let out = run(&p).await; + assert_eq!(out.unattested.len(), 1, "{:?}", out.unattested); + let detail = &out.unattested[0].detail; + assert!( + detail.contains("profile p1") && detail.contains("1.7.30") && !detail.contains("p0"), + "{detail}" + ); + } + + /// A `-D` property `.mvn/maven.config` alone + /// defines AT the vendored version is the pin, not an override. + #[tokio::test] + async fn vendored_version_from_maven_config_at_the_pin_is_attested() { + let p = vendored_project_with(|wired| { + let spelled = wired.replacen( + "1.10.0", + "${commons.version}", + 1, + ); + assert_ne!(spelled, wired); + spelled + }); + p.write(".mvn/maven.config", "-Dcommons.version=1.10.0\n"); + let out = run(&p).await; + assert_refs(&out, &[(V_PURL, UUID_A, WiringMode::Vendored)]); + assert!(out.unattested.is_empty(), "{:?}", out.unattested); + p.write(".mvn/maven.config", "-Dcommons.version=1.9\n"); + let out = run(&p).await; + let kinds: Vec<_> = out.unattested.iter().map(|u| u.kind).collect(); + assert_eq!(kinds, [UnattestedKind::MavenConfigOverride]); + assert!( + out.unattested[0].detail.ends_with("makes it resolve 1.9"), + "{}", + out.unattested[0].detail + ); + } + + /// A profile `` entry + /// for a classifier copy that sets no `` (scope, exclusions) + /// overrides no version: the live managed pin still governs. + #[tokio::test] + async fn a_versionless_profile_management_entry_overrides_nothing() { + let pin = suffixed(UUID_A); + let tests = |v: Option<&str>| { + decl( + "org.slf4j", + "slf4j-api", + v, + "teststest", + ) + }; + let p = Project::new(); + p.write( + "pom.xml", + pom(&format!( + "\n\n{}\n\n\ + \n{}{}\n\ + p\n{}\ + \n\ + \n{}\n", + tests(Some(&pin)), + dep("org.slf4j", "slf4j-api", Some(&pin)), + tests(None), + tests(None), + hosted_repo_a(), + )), + ); + let out = run(&p).await; + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert!(out.unattested.is_empty(), "{:?}", out.unattested); + } + #[tokio::test] async fn vendored_url_spellings() { for spelled in [ diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index 5cad4e510..abec79284 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -697,11 +697,25 @@ pub enum UnattestedKind { /// #261): a module's own literal `` overrides it, and only the /// root pom is read, so the reactor may build the upstream jar. MavenReactorRoot, - /// A hosted Maven pin whose GA also has a live executable classifier - /// copy (`tests`, a native build; not `sources` / `javadoc`) at another - /// version: the classifier-less pin does not retarget it and the grant - /// serves only the main jar, so the build runs the public classifier jar. + /// A Maven pin (hosted, or the pre-v5 single-pom vendored repository) + /// whose GA also has an executable classifier copy (`tests`, a native + /// build; not `sources` / `javadoc`), live or inside ``, at + /// another version: the classifier-less pin does not retarget it and + /// the grant serves only the main jar, so the build runs the public + /// classifier jar. MavenClassifierUnpatched, + /// A Maven pin (hosted, or the pre-v5 single-pom vendored repository) + /// that some profile overrides whenever it is active: a `` + /// declaration of the GA at another version, profile `` + /// that move the pin's `${property}` version, or ones that move a + /// `${property}` groupId / artifactId so the pin names another package + /// or another declaration names this one. + MavenProfileUnpatched, + /// A Maven pin (hosted, or the pre-v5 single-pom vendored repository) + /// the root pom spells through a `${property}` that `.mvn/maven.config` + /// redefines (`-D`, which Maven reads before the pom's ``): + /// the build resolves that version, not the pin. + MavenConfigOverride, /// A hosted Cargo pin beside another declaration of the crate (the /// root's or a workspace member's) that is not pinned (no Socket /// registry or `[patch]` redirect reaches it, or a path / git /