diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 23333d7946..d507d85fca 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -402,7 +402,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Grant gate (additive).** A reference grant is the patch API's answer, and its fields are written into files the project commits. Each granted reference is therefore checked once, before anything is planned for it (no takeover, no artifact fetch, no rewriter sees one that fails): the patch uuid is a canonical lowercase uuid; the artifact URL and a registry override's index URL are `https` URLs of plain URL characters (no whitespace or control character, no quote, backslash, `$`, `{`, `}`, `<`, `>`, `&`, `#`, `;`, `|` or `^`; cargo's `sparse+` prefix is kept); `sha1` is 40 hex digits, `sha256` 64, `sha512` exactly one `sha512-` token, the Go hashes `h1:` hashes, the yarn berry checksum `/`, the cargo and gem checksums 64 hex digits; the package's name and version, and every identifier of a registry override, are in their ecosystem's coordinate grammar (letters, digits and that ecosystem's punctuation; Maven coordinates as the JVM backends accept them). A Maven grant's sha256 digests may also be spelled `sha256-…` / `sha256:…`: the pom, Gradle and sbt planners read those, and a digest that is still not 64 hex digits writes no checksum pin (`redirect_maven_trusted_checksums_invalid_hash`). An absent or empty optional field is not checked. A grant that fails is refused for that package only: a `skipped` event whose `errorCode` is `redirect_grant_malformed` and whose `reason` names the field (never its value), the same code and detail in `warnings[]`, nothing written for it, the rest of the run and the exit code unchanged. A plain-`http` artifact or index URL is refused the same way with `redirect_grant_insecure_url` (every later install would send the grant token in clear text), unless its origin is the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin (scheme, host and port) or a loopback address (`localhost`, `127.0.0.0/8`, `::1`). The in-memory engine applies the same gate; it has no configured origin. -The rewriter reads a fixed set of candidate files from the project root: the npm-family locks (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `shrinkwrap.yaml`, `yarn.lock`, plus `.yarnrc.yml` for the berry cache-config gate, `bun.lock` / `bun.lockb`, and `vlt-lock.json` with `vlt.json` and `node_modules/.vlt-lock.json` read only), `requirements.txt` / `uv.lock` / `Pipfile.lock` (pipfile-spec 6; see the Pipenv section below) / `poetry.lock` (every Poetry lock generation from 1.0 on — the 0.12 `[metadata.hashes]` layout is refused because that installer ignores URL sources; a Poetry < 1.4 writer additionally gets `redirect_poetry_stale_install_risk`, see `docs/testing/poetry-compatibility.md`) / `pdm.lock` (PDM lock formats `2` and `4.3`–`4.5.1`; the identity-losing `3.1` / `4.0`–`4.2` formats and unknown future formats are refused with `redirect_pdm_refused`, and a lock-format-`2` writer additionally gets `redirect_pdm_legacy_sync_required`, see `docs/testing/pdm-compatibility.md`; when `uv.lock` or `poetry.lock` sits beside it they drive and `pdm.lock` is left alone), `Cargo.toml` / `Cargo.lock` / `.cargo/config.toml` (plus the legacy extensionless `.cargo/config` — cargo reads that spelling in preference when both exist, so the managed `[registries.…]` block is written into whichever one is present; the hosted redirect is a `sparse+` registry, which cargo loads only from **1.68**, so `rust-toolchain.toml` / `rust-toolchain` are read too (never edited) and a project whose declared floor — the lowest `rust-version` of the root and the member manifests read here (a `rust-version.workspace = true` inheritor reads `[workspace.package]`), else the channel rustup picks from the root (the legacy `rust-toolchain` over `rust-toolchain.toml`; a dated `nightly-`/`beta-YYYY-MM-DD` maps to its release train) — is below 1.68 is refused `redirect_cargo_old_cargo` per crate (nothing written, an earlier run's pins left in place with the `rollback` that drops them named; `--mode vendored` builds on cargo 1.41+), while an undeclared or rolling-channel floor still redirects (toolchain files in ancestor directories are not read); **cargo also reads every workspace-member manifest** — the `[workspace] members` globs minus `exclude` — and every in-root path-dependency manifest, recursively, reached without crossing a symbolic link and never under `.socket/`, and pins the crate in each one that declares it, so those `/Cargo.toml` files can appear in `rewrittenFiles`. A crate is redirected only when every declaration pins and every other `Cargo.lock` package depending on it is a planned member: one a registry or git crate — or a path package outside the root or behind a link — also depends on is refused `redirect_cargo_transitive_dependents` (a pin reaches only the declarations it sits on), a crate no manifest declares keeps `redirect_cargo_toml_dep_not_found` with a transitive-only detail naming `--mode vendored`, a crate every declaration of which requires another version (no requirement accepts the patched version) is refused `redirect_cargo_toml_dep_unrewritable`, and so is a requirement that also matches another locked version of the crate — each a transactional skip, never recorded or attested. With NO `Cargo.lock` there is no resolved graph to ask, so the dependents question is answered from the manifests instead: a crate declared beside any other dependency — anything but a path dependency on a manifest this run also pins, or a `workspace = true` inheritor of a table it scans — or beside a workspace member this run did not read (a `members` glob, or a member outside the project or behind a symbolic link, which member discovery drops) is refused `redirect_cargo_lockless_dependents`, whose detail names the remedies (commit a lockfile, or `--mode vendored`); a project whose only dependency is the patched crate has nothing that could pull it in and still redirects. All-CRLF manifests, locks and configs are rewritten with CRLF kept (mixed endings keep refusing where the grammar does not match), and `remove` / rollback match the recorded fragments across a later CRLF↔LF checkout conversion), `composer.lock`, `nuget.config` / `packages.lock.json` (plus, v5.0 #353/#514, every lock a project under the root restores into: a member project's `packages.lock.json`, a per-project `packages..lock.json`, a literal `NuGetLockFilePath` — each pinned with the root config; a `NuGetLockFilePath` it cannot evaluate warns `redirect_nuget_lock_path_unresolved` and a project tree it cannot list warns `redirect_nuget_lock_unreadable`, both skipping the nuget redirect with nothing written), `Gemfile` / `Gemfile.lock`, `pom.xml` (+ `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` for maven Trusted Checksums merge, and, for a Gradle build, every settings, build, `buildSrc`, included-build, applied and plugin-source script, version catalog and lock file the script graph reaches, plus `gradle/verification-metadata.xml`, `gradle/wrapper/gradle-wrapper.properties` and the owned `.socket/gradle/` files), and the sbt build files (`socket-patch.sbt`, `socket-patch-vendor.sbt`, `build.sbt`, `project/build.properties`, `.sbtopts`, `.jvmopts`; `build.sbt.lock` and the Mill / scala-cli build files `build.mill`, `build.mill.yaml`, `build.sc`, `.mill-version`, `project.scala` for their presence only) — read, never edited; `socket-patch.sbt` is the only sbt file hosted mode writes (see **Hosted sbt** below). **npm-family flavor coverage**: package-lock / npm-shrinkwrap (a package the project patches itself with npm ≥ 12.1's native `npm patch` — a root `patchedDependencies` key, or the lock entry's `patched` record — is left on its registry entry in every npm lock, `redirect_npm_patched_dependency_skipped`), pnpm (root OR any nested `*/pnpm-lock.yaml`), yarn classic (a yarn 2+ install migrates a v1 `yarn.lock` and drops its pins, so a run whose v1 lock carries a hosted pin warns `redirect_yarn_classic_berry_migration_risk` — the hosted twin of the vendored `yarn_classic_berry_migration_risk` — unless the root `package.json`, read as advisory input, declares `"packageManager": "yarn@1…"`), **yarn berry** (the pin yarn writes for a root `resolutions` entry: the root `package.json` — edited only beside a berry `yarn.lock` — gains one `"@npm:": ""` selector per locked range (`redirect_yarn_berry_resolution` edits), and only that `yarn.lock` entry is re-keyed `"@"` with the same `resolution:` + `yarnBerry10c0` checksum (`redirect_yarn_berry_entry`), moved to yarn's key order; never an `npm:` locator, whose fetcher sends npm registry auth to the patch host, nor a tarball locator under an `npm:` key, which hardened mode rejects (YN0078). An older release's `npm:::__archiveUrl=` pin is still recognized and is re-pinned on the next run; rollback rebuilds the key from the selectors and drops them. Refused, nothing written: a user-authored `resolutions` entry for the package `redirect_yarn_berry_resolutions_conflict`, no root manifest `redirect_yarn_berry_manifest_missing`, a builtin `patch:` entry wrapping the same descriptor `redirect_yarn_berry_shared_descriptor`, an artifact URL yarn cannot fetch as a tarball `redirect_yarn_berry_artifact_url_unsupported`; cacheKey `10c0` and `.yarnrc.yml compressionLevel 0` gated by `redirect_yarn_berry_cache_unsupported`), and **bun** (text `bun.lock` lockfileVersion 0 to 3 — 0 is the `--save-text-lockfile` opt-in lock of Bun 1.1.39–1.1.45, 1 the 1.2–1.3 default, 2 the 1.4+ default, 3 what Bun 1.4+ writes when `package.json` has a nested override or a yarn-style path resolution (only the lock's head differs: its `overrides` object nests); all four emit one `packages` grammar, so the registry 4-tuple → URL 3-tuple rewrite is version-independent and the lock's own version line is kept. Any other or missing version, or a `packages` section outside bun's single-line grammar, is refused `redirect_bun_lock_unsupported` — the detail is the shared version gate's text (a newer version: update socket-patch, re-locking would reproduce it; no integer: re-lock with Bun ≥ 1.2), identical to the vendored refusal. A version-0 lock holding `workspace:` packages is refused `redirect_bun_workspace_unsupported` (its 2-tuple workspace grammar cannot keep the hosted tuple through a frozen install); the remedy is to delete `bun.lock` and re-run `bun install` with Bun ≥ 1.2, which writes lockfileVersion 1 (accepted). A plain in-place `bun install` bumps the version only when a workspace depends on another workspace (e.g. root → member — the shape the matrix measured); otherwise Bun 1.2.0 keeps version 0 and Bun 1.2.23+ fail to resolve, so the in-place bump is not the documented remedy. Bun lock version, grammar and workspace compatibility are checked before a vendored takeover, including during dry-run: these refusals preserve the existing lock, artifact and vendor ledger. Version-1 and version-2 workspace locks are rewritten, nested versions included. A granted dep with no rewritable entry warns `redirect_bun_entry_not_found` (or `redirect_bun_non_registry_entry_skipped` when the only same-version entry is a user URL / `file:` tarball, #497), a grant without a sha512 `redirect_bun_missing_sha512`; a CRLF lock keeps `\r\n` on the rewritten line, and a hosted URL left by an earlier grant of the same `name@version` is re-pinned in place. **Digest-less re-saves (Bun 1.1.39–1.3.9)**: every text-lock Bun below 1.3.10 re-saves a URL tuple WITHOUT its `sha512` whenever the lock is re-saved for another reason (`bun add`, `bun install` after a package.json or workspace change), leaving the 2-tuple `["name@", {meta}]` — the spec Bun installs from is intact. The CLI treats that spelling as its own wiring: a repeat hosted run counts the dep as redirected (no `redirect_bun_entry_not_found`) and HEALS the line back to the 3-tuple with the current `sha512`, recording the heal as a further `redirect_bun_lock_package` edit whose `original` is the 2-tuple (a stale URL is re-pinned from either spelling); `rollback`, scoped `rollback ` / `remove ` and the vendored takeover accept the digest-less spelling of a recorded `new` line (same key, spec and meta, only the trailing `"sha512-…"` missing) and restore the recorded original over it, so the chain always unwinds to the pristine registry line. Anything else — another uuid/token, another version, a re-laid meta object — is still drift. **Native `bun.lockb`**: when no text `bun.lock` exists, binary format versions 1, 2 and 3 are read and rewritten directly. Socket Patch does not invoke Bun or convert the project to a text lockfile. Exact matching package records are rewritten to hosted tarballs with the granted integrity, preserving dependency resolution IDs, workspace/dependency topology and unrelated package metadata; binary pointers and the package metadata hash are updated. Per-package `redirect_bun_lockb_package` snapshots support scoped rollback, repeat runs, superseding grants and hosted ↔ vendored takeover. A regular binary lock is discoverable even with no Bun runtime or `node_modules`; a dry run previews the same binary edits without writing them. A malformed, unreadable, unsupported or unverified binary structure is `redirect_bun_lockb_invalid` (exit 0, `redirected: 0`), and it refuses the npm rewrite before any takeover or sibling npm-family lock mutation. A symlinked binary write target is `redirect_symlinked_file_unsupported` (exit 1, including dry-run). `bun.lock` wins when both spellings exist. Binary-only projects do not receive `redirect_npm_no_lockfile`. Measured boundaries and the real-Bun matrix: `docs/testing/bun-compatibility.md`), and **vlt** (`vlt-lock.json` without `lockfileVersion`, `0` or `1`; see the vlt hosted-mode contract below). **Rush monorepos**: when `rush.json` is present the rewriter also reads `common/config/rush/pnpm-lock.yaml` and each `common/config/subspaces//pnpm-lock.yaml` (sorted for determinism) under their repo-relative keys and repoints them in place; editing them emits `redirect_rush_repo_state_stale` when the `repo-state.json` beside a rewritten lock exists (`common/config/rush/repo-state.json` for the common lock, `common/config/subspaces//repo-state.json` for a subspace lock; the `pnpmShrinkwrapHash` desync is refreshed by `rush update`, which the redirect survives), and `redirect_pnpm_trust_lockfile` carries the Rush pnpm >=11 install remedy (see the trust paragraph above). **maven** is fail-closed via version suffixing: a `mavenSuffixedVersion` + `mavenPomSha256` override pins the Socket-only `-socket.` by rewriting the literal `` (`redirect_maven_dep_version`) or adding a `` entry (`redirect_maven_dep_management_added`), plus optional Trusted Checksums (`redirect_maven_trusted_checksums`, conflicts as `redirect_maven_trusted_checksums_conflict`; the `.mvn/maven.config` line that names the checksums directory is spelled `${maven.multiModuleProjectDirectory}/.mvn/checksums`, which no Maven 3 build fails on wherever it is started, or `${session.rootDirectory}/.mvn/checksums` for a project that declares Maven 4 (a wrapper that pins it, or a root pom whose model is newer than 4.0.0: its ``, else the version its namespace names), the only form Maven 4 reads. The six settings hosted mode wrote, standing together in the other spelling, are respelled in that one line by every `scan --mode hosted` that reads the file (`redirect_maven_config`, `rewritten`, `key: "trustedChecksumsDirectory"`; the edit that merges the settings in keeps `key: "trustedChecksums"`), whatever the run redirects: with no Maven patch in the run, in a reactor root, in a root another rewriter owns, with no checksum line left, with a later line that switches the pin off. A scan with nothing to redirect reads `.mvn/maven.config` for that alone, and takes the write lock for it when it can. The respelling is never the reason a run fails: when the lock cannot be had, or the file is a symbolic link (which a write would replace), the line is left as it is and nothing is reported for it. This is what removes the line an earlier release wrote for every project, which stops Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the project. A directory line that stands apart from the other five is the user's and is never rewritten. When the respelling takes `${session.rootDirectory}` out of a project that declares no Maven, a Maven 4 build of it stops enforcing the pin (Maven 3.9.4 and later 3.x go on enforcing it): the additive warning `redirect_maven_trusted_checksums_maven3_only` says so, once, with the remedy (declare Maven 4 and scan again). A directory line in the launcher's spelling that the user wrote, in a project that declares Maven 4, names no directory there: it is left as written and reported as `redirect_maven_trusted_checksums_conflict`. Either form is recognised by `vex`, `rollback` and `remove`; when the Maven the project declares does not enforce the pin as the config stands (the wrapper pins a Maven older than 3.9.4, or the project declares Maven 4 and the line is in the spelling Maven 4 does not read), the additive warning `redirect_maven_trusted_checksums_unenforced`, whose detail names the remedy for that case; a grant sha256 that is not 64 hex digits writes no checksum line, `redirect_maven_trusted_checksums_invalid_hash`); a `${property}` version is refused (`redirect_maven_dep_unpinned`), a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`; each such subdirectory's `pom.xml` is read for this, never edited) is refused whole with `redirect_maven_multimodule_unsupported`: `pom.xml` and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the pom pins it too), since a module's own literal `` would shadow a root pin (use `--mode vendored`; `vex` omits a hosted pin in a reactor root as `vex_maven_reactor_root`), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped, with nothing written, when a variant other than `sources` / `javadoc`, live or inside ``, may resolve any version but the suffixed pin — the patched release, another one, a `${property}` a profile moves, or no version in the pom once its classifier-keyed `` (a profile's too) is consulted — since `vex` would never attest that pin: `vex_maven_classifier_unpatched`), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`): when any version it may resolve — its own, or what its own profile's or any combination of profiles' `` make of it, read as `vex` reads it — is not the suffixed pin, the dep is refused with nothing written, since it overrides the pin whenever that profile is active and `vex` would never attest it (a profile `` entry only when management governs the pin, i.e. no live direct declaration carries a version); a versionless one takes the pin, and the dep is also skipped when a profile holds its only declaration, a `${property}` groupId / artifactId resolved from the pom's own `` before matching (one the pom does not define, which may be the patched GA and whose own version would then win, refuses the dep with nothing written: `redirect_maven_coordinate_unresolved`), and a `${property}` groupId / artifactId some profile's `` (or several profiles' together) redefine so that the declaration a pin would go into names another package, or another declaration names the GA's main jar at another version (or one of its executable classifier copies, a `test-jar` included), refuses the dep with nothing written too (`redirect_maven_profile_coordinates_unpatched`): `vex` would never attest that pin (`vex_maven_profile_unpatched`), and a pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). A pin is written only where Maven selects the patch's base version already (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`): see [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). **gradle** (v5.0) is automated wiring, no longer a pasted snippet: the owned settings script `.socket/gradle/socket-patch.hosted.settings.gradle` with its index `.socket/gradle/hosted-index.tsv`, one apply line per build's settings file, every lock entry of the GA moved to the suffixed version, and the suffixed component in an existing `gradle/verification-metadata.xml`. A refused dep writes nothing and keeps `redirect_gradle_manual_snippet` as its fallback; same-GAV grants are refused (`redirect_gradle_same_gav_unsupported`). Rules, refusals and codes: [Gradle builds](#gradle-builds-v50). +The rewriter reads a fixed set of candidate files from the project root: the npm-family locks (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `shrinkwrap.yaml`, `yarn.lock`, plus `.yarnrc.yml` for the berry cache-config gate, `bun.lock` / `bun.lockb`, and `vlt-lock.json` with `vlt.json` and `node_modules/.vlt-lock.json` read only), `requirements.txt` / `uv.lock` / `Pipfile.lock` (pipfile-spec 6; see the Pipenv section below) / `poetry.lock` (every Poetry lock generation from 1.0 on — the 0.12 `[metadata.hashes]` layout is refused because that installer ignores URL sources; a Poetry < 1.4 writer additionally gets `redirect_poetry_stale_install_risk`, see `docs/testing/poetry-compatibility.md`) / `pdm.lock` (PDM lock formats `2` and `4.3`–`4.5.1`; the identity-losing `3.1` / `4.0`–`4.2` formats and unknown future formats are refused with `redirect_pdm_refused`, and a lock-format-`2` writer additionally gets `redirect_pdm_legacy_sync_required`, see `docs/testing/pdm-compatibility.md`; when `uv.lock` or `poetry.lock` sits beside it they drive and `pdm.lock` is left alone), `Cargo.toml` / `Cargo.lock` / `.cargo/config.toml` (plus the legacy extensionless `.cargo/config` — cargo reads that spelling in preference when both exist, so the managed `[registries.…]` block is written into whichever one is present; the hosted redirect is a `sparse+` registry, which cargo loads only from **1.68**, so `rust-toolchain.toml` / `rust-toolchain` are read too (never edited) and a project whose declared floor — the lowest `rust-version` of the root and the member manifests read here (a `rust-version.workspace = true` inheritor reads `[workspace.package]`), else the channel rustup picks from the root (the legacy `rust-toolchain` over `rust-toolchain.toml`; a dated `nightly-`/`beta-YYYY-MM-DD` maps to its release train) — is below 1.68 is refused `redirect_cargo_old_cargo` per crate (nothing written, an earlier run's pins left in place with the `rollback` that drops them named; `--mode vendored` builds on cargo 1.41+), while an undeclared or rolling-channel floor still redirects (toolchain files in ancestor directories are not read); **cargo also reads every workspace-member manifest** — the `[workspace] members` globs minus `exclude` — and every in-root path-dependency manifest, recursively, reached without crossing a symbolic link and never under `.socket/`, and pins the crate in each one that declares it, so those `/Cargo.toml` files can appear in `rewrittenFiles`. A crate is redirected only when every declaration pins and every other `Cargo.lock` package depending on it is a planned member: one a registry or git crate — or a path package outside the root or behind a link — also depends on is refused `redirect_cargo_transitive_dependents` (a pin reaches only the declarations it sits on), a crate no manifest declares keeps `redirect_cargo_toml_dep_not_found` with a transitive-only detail naming `--mode vendored`, a crate every declaration of which requires another version (no requirement accepts the patched version) is refused `redirect_cargo_toml_dep_unrewritable`, and so is a requirement that also matches another locked version of the crate — each a transactional skip, never recorded or attested. With NO `Cargo.lock` there is no resolved graph to ask, so the dependents question is answered from the manifests instead: a crate declared beside any other dependency — anything but a path dependency on a manifest this run also pins, or a `workspace = true` inheritor of a table it scans — or beside a workspace member this run did not read (a `members` glob, or a member outside the project or behind a symbolic link, which member discovery drops) is refused `redirect_cargo_lockless_dependents`, whose detail names the remedies (commit a lockfile, or `--mode vendored`); a project whose only dependency is the patched crate has nothing that could pull it in and still redirects. All-CRLF manifests, locks and configs are rewritten with CRLF kept (mixed endings keep refusing where the grammar does not match), and `remove` / rollback match the recorded fragments across a later CRLF↔LF checkout conversion), `composer.lock`, `nuget.config` / `packages.lock.json` (plus, v5.0 #353/#514, every lock a project under the root restores into: a member project's `packages.lock.json`, a per-project `packages..lock.json`, a literal `NuGetLockFilePath` — each pinned with the root config; a `NuGetLockFilePath` it cannot evaluate warns `redirect_nuget_lock_path_unresolved` and a project tree it cannot list warns `redirect_nuget_lock_unreadable`, both skipping the nuget redirect with nothing written), `Gemfile` / `Gemfile.lock`, `pom.xml` (+ `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` for maven Trusted Checksums merge, and, for a Gradle build, every settings, build, `buildSrc`, included-build, applied and plugin-source script, version catalog and lock file the script graph reaches, plus `gradle/verification-metadata.xml`, `gradle/wrapper/gradle-wrapper.properties` and the owned `.socket/gradle/` files), and the sbt build files (`socket-patch.sbt`, `socket-patch-vendor.sbt`, `build.sbt`, `project/build.properties`, `.sbtopts`, `.jvmopts`; `build.sbt.lock` and the Mill / scala-cli build files `build.mill`, `build.mill.yaml`, `build.sc`, `.mill-version`, `project.scala` for their presence only) — read, never edited; `socket-patch.sbt` is the only sbt file hosted mode writes (see **Hosted sbt** below). **npm-family flavor coverage**: package-lock / npm-shrinkwrap (a package the project patches itself with npm ≥ 12.1's native `npm patch` — a root `patchedDependencies` key, or the lock entry's `patched` record — is left on its registry entry in every npm lock, `redirect_npm_patched_dependency_skipped`), pnpm (root OR any nested `*/pnpm-lock.yaml`), yarn classic (a yarn 2+ install migrates a v1 `yarn.lock` and drops its pins, so a run whose v1 lock carries a hosted pin warns `redirect_yarn_classic_berry_migration_risk` — the hosted twin of the vendored `yarn_classic_berry_migration_risk` — unless the root `package.json`, read as advisory input, declares `"packageManager": "yarn@1…"`), **yarn berry** (the pin yarn writes for a root `resolutions` entry: the root `package.json` — edited only beside a berry `yarn.lock` — gains one `"@npm:": ""` selector per locked range (`redirect_yarn_berry_resolution` edits), and only that `yarn.lock` entry is re-keyed `"@"` with the same `resolution:` + `yarnBerry10c0` checksum (`redirect_yarn_berry_entry`), moved to yarn's key order; never an `npm:` locator, whose fetcher sends npm registry auth to the patch host, nor a tarball locator under an `npm:` key, which hardened mode rejects (YN0078). An older release's `npm:::__archiveUrl=` pin is still recognized and is re-pinned on the next run; rollback rebuilds the key from the selectors and drops them. Refused, nothing written: a user-authored `resolutions` entry for the package `redirect_yarn_berry_resolutions_conflict`, no root manifest `redirect_yarn_berry_manifest_missing`, a builtin `patch:` entry wrapping the same descriptor `redirect_yarn_berry_shared_descriptor`, an artifact URL yarn cannot fetch as a tarball `redirect_yarn_berry_artifact_url_unsupported`; cacheKey `10c0` and `.yarnrc.yml compressionLevel 0` gated by `redirect_yarn_berry_cache_unsupported`), and **bun** (text `bun.lock` lockfileVersion 0 to 3 — 0 is the `--save-text-lockfile` opt-in lock of Bun 1.1.39–1.1.45, 1 the 1.2–1.3 default, 2 the 1.4+ default, 3 what Bun 1.4+ writes when `package.json` has a nested override or a yarn-style path resolution (only the lock's head differs: its `overrides` object nests); all four emit one `packages` grammar, so the registry 4-tuple → URL 3-tuple rewrite is version-independent and the lock's own version line is kept. Any other or missing version, or a `packages` section outside bun's single-line grammar, is refused `redirect_bun_lock_unsupported` — the detail is the shared version gate's text (a newer version: update socket-patch, re-locking would reproduce it; no integer: re-lock with Bun ≥ 1.2), identical to the vendored refusal. A version-0 lock holding `workspace:` packages is refused `redirect_bun_workspace_unsupported` (its 2-tuple workspace grammar cannot keep the hosted tuple through a frozen install); the remedy is to delete `bun.lock` and re-run `bun install` with Bun ≥ 1.2, which writes lockfileVersion 1 (accepted). A plain in-place `bun install` bumps the version only when a workspace depends on another workspace (e.g. root → member — the shape the matrix measured); otherwise Bun 1.2.0 keeps version 0 and Bun 1.2.23+ fail to resolve, so the in-place bump is not the documented remedy. Bun lock version, grammar and workspace compatibility are checked before a vendored takeover, including during dry-run: these refusals preserve the existing lock, artifact and vendor ledger. Version-1 and version-2 workspace locks are rewritten, nested versions included. A granted dep with no rewritable entry warns `redirect_bun_entry_not_found` (or `redirect_bun_non_registry_entry_skipped` when the only same-version entry is a user URL / `file:` tarball, #497), a grant without a sha512 `redirect_bun_missing_sha512`; a CRLF lock keeps `\r\n` on the rewritten line, and a hosted URL left by an earlier grant of the same `name@version` is re-pinned in place. **Digest-less re-saves (Bun 1.1.39–1.3.9)**: every text-lock Bun below 1.3.10 re-saves a URL tuple WITHOUT its `sha512` whenever the lock is re-saved for another reason (`bun add`, `bun install` after a package.json or workspace change), leaving the 2-tuple `["name@", {meta}]` — the spec Bun installs from is intact. The CLI treats that spelling as its own wiring: a repeat hosted run counts the dep as redirected (no `redirect_bun_entry_not_found`) and HEALS the line back to the 3-tuple with the current `sha512`, recording the heal as a further `redirect_bun_lock_package` edit whose `original` is the 2-tuple (a stale URL is re-pinned from either spelling); `rollback`, scoped `rollback ` / `remove ` and the vendored takeover accept the digest-less spelling of a recorded `new` line (same key, spec and meta, only the trailing `"sha512-…"` missing) and restore the recorded original over it, so the chain always unwinds to the pristine registry line. Anything else — another uuid/token, another version, a re-laid meta object — is still drift. **Native `bun.lockb`**: when no text `bun.lock` exists, binary format versions 1, 2 and 3 are read and rewritten directly. Socket Patch does not invoke Bun or convert the project to a text lockfile. Exact matching package records are rewritten to hosted tarballs with the granted integrity, preserving dependency resolution IDs, workspace/dependency topology and unrelated package metadata; binary pointers and the package metadata hash are updated. Per-package `redirect_bun_lockb_package` snapshots support scoped rollback, repeat runs, superseding grants and hosted ↔ vendored takeover. A regular binary lock is discoverable even with no Bun runtime or `node_modules`; a dry run previews the same binary edits without writing them. A malformed, unreadable, unsupported or unverified binary structure is `redirect_bun_lockb_invalid` (exit 0, `redirected: 0`), and it refuses the npm rewrite before any takeover or sibling npm-family lock mutation. A symlinked binary write target is `redirect_symlinked_file_unsupported` (exit 1, including dry-run). `bun.lock` wins when both spellings exist. Binary-only projects do not receive `redirect_npm_no_lockfile`. Measured boundaries and the real-Bun matrix: `docs/testing/bun-compatibility.md`), and **vlt** (`vlt-lock.json` without `lockfileVersion`, `0` or `1`; see the vlt hosted-mode contract below). **Rush monorepos**: when `rush.json` is present the rewriter also reads `common/config/rush/pnpm-lock.yaml` and each `common/config/subspaces//pnpm-lock.yaml` (sorted for determinism) under their repo-relative keys and repoints them in place; editing them emits `redirect_rush_repo_state_stale` when the `repo-state.json` beside a rewritten lock exists (`common/config/rush/repo-state.json` for the common lock, `common/config/subspaces//repo-state.json` for a subspace lock; the `pnpmShrinkwrapHash` desync is refreshed by `rush update`, which the redirect survives), and `redirect_pnpm_trust_lockfile` carries the Rush pnpm >=11 install remedy (see the trust paragraph above). **maven** is fail-closed via version suffixing: a `mavenSuffixedVersion` + `mavenPomSha256` override pins the Socket-only `-socket.` by rewriting the literal `` (`redirect_maven_dep_version`) or adding a `` entry (`redirect_maven_dep_management_added`), plus optional Trusted Checksums (`redirect_maven_trusted_checksums`, conflicts as `redirect_maven_trusted_checksums_conflict`; the `.mvn/maven.config` line that names the checksums directory is spelled `${maven.multiModuleProjectDirectory}/.mvn/checksums`, which no Maven 3 build fails on wherever it is started, or `${session.rootDirectory}/.mvn/checksums` for a project that declares Maven 4 (a wrapper that pins it, or a root pom whose model is newer than 4.0.0: its ``, else the version its namespace names), the only form Maven 4 reads. The six settings hosted mode wrote, standing together in the other spelling, are respelled in that one line by every `scan --mode hosted` that reads the file (`redirect_maven_config`, `rewritten`, `key: "trustedChecksumsDirectory"`; the edit that merges the settings in keeps `key: "trustedChecksums"`), whatever the run redirects: with no Maven patch in the run, in a reactor root, in a root another rewriter owns, with no checksum line left, with a later line that switches the pin off. A scan with nothing to redirect reads `.mvn/maven.config` for that alone, and takes the write lock for it when it can. The respelling is never the reason a run fails: when the lock cannot be had, or the file is a symbolic link (which a write would replace), the line is left as it is and nothing is reported for it. This is what removes the line an earlier release wrote for every project, which stops Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the project. A directory line that stands apart from the other five is the user's and is never rewritten. When the respelling takes `${session.rootDirectory}` out of a project that declares no Maven, a Maven 4 build of it stops enforcing the pin (Maven 3.9.4 and later 3.x go on enforcing it): the additive warning `redirect_maven_trusted_checksums_maven3_only` says so, once, with the remedy (declare Maven 4 and scan again). A directory line in the launcher's spelling that the user wrote, in a project that declares Maven 4, names no directory there: it is left as written and reported as `redirect_maven_trusted_checksums_conflict`. Either form is recognised by `vex`, `rollback` and `remove`; when the Maven the project declares does not enforce the pin as the config stands (the wrapper pins a Maven older than 3.9.4, or the project declares Maven 4 and the line is in the spelling Maven 4 does not read), the additive warning `redirect_maven_trusted_checksums_unenforced`, whose detail names the remedy for that case; a grant sha256 that is not 64 hex digits writes no checksum line, `redirect_maven_trusted_checksums_invalid_hash`); a `${property}` version is wired through the property's own value (`redirect_maven_property`) or a literal that records the text it replaced (`redirect_maven_dep_version` with the `${...}` text as `original`), and stays `redirect_maven_dep_unpinned` only when what it reads cannot be told, a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`) is planned over every pom of the reactor, each module `pom.xml` that takes an edit appearing in `rewrittenFiles` (see [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions)); a reactor one of whose poms cannot be read, and a same-GAV grant in a reactor, are refused whole with `redirect_maven_multimodule_unsupported`: the poms and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the poms pin it too), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped, with nothing written, when a variant other than `sources` / `javadoc`, live or inside ``, may resolve any version but the suffixed pin — the patched release, another one, a `${property}` a profile moves, or no version in the pom once its classifier-keyed `` (a profile's too) is consulted — since `vex` would never attest that pin: `vex_maven_classifier_unpatched`), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`): when any version it may resolve — its own, or what its own profile's or any combination of profiles' `` make of it, read as `vex` reads it — is not the suffixed pin, the dep is refused with nothing written, since it overrides the pin whenever that profile is active and `vex` would never attest it (a profile `` entry only when management governs the pin, i.e. no live direct declaration carries a version); a versionless one takes the pin, and the dep is also skipped when a profile holds its only declaration, a `${property}` groupId / artifactId resolved from the pom's own `` before matching (one the pom does not define, which may be the patched GA and whose own version would then win, refuses the dep with nothing written: `redirect_maven_coordinate_unresolved`), and a `${property}` groupId / artifactId some profile's `` (or several profiles' together) redefine so that the declaration a pin would go into names another package, or another declaration names the GA's main jar at another version (or one of its executable classifier copies, a `test-jar` included), refuses the dep with nothing written too (`redirect_maven_profile_coordinates_unpatched`): `vex` would never attest that pin (`vex_maven_profile_unpatched`), and a pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). A pin is written only where Maven selects the patch's base version already (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`): see [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). **gradle** (v5.0) is automated wiring, no longer a pasted snippet: the owned settings script `.socket/gradle/socket-patch.hosted.settings.gradle` with its index `.socket/gradle/hosted-index.tsv`, one apply line per build's settings file, every lock entry of the GA moved to the suffixed version, and the suffixed component in an existing `gradle/verification-metadata.xml`. A refused dep writes nothing and keeps `redirect_gradle_manual_snippet` as its fallback; same-GAV grants are refused (`redirect_gradle_same_gav_unsupported`). Rules, refusals and codes: [Gradle builds](#gradle-builds-v50). **Hosted sbt (v5.0, additive)**: an sbt build root (`project/build.properties` naming an `sbt.version`, 0.13.18 or later) is wired through ONE generated root file, `socket-patch.sbt` — no user file is edited. It pins every granted Maven patch build-wide (a `ThisBuild` `dependencyOverrides +=` of the Socket-only `-socket.` version plus a `file:` resolver over `.socket/sbt-hosted/maven2/`, moved ahead of the default repositories on sbt 0.13 / 1.x so an unreachable one never blocks it offline), downloads the pinned pom and jar there on the first sbt load (sha256-checked, gitignored by the file itself), and installs a load-time verifier that fails `update` when any project resolves another version or a pinned artifact whose bytes are not pinned. Edits: `redirect_sbt_pin` (added), `redirect_sbt_pin_updated` (an existing row replaced: same GA and base under a new uuid, or the same uuid with new served values; `original` names the previous uuid and version), `redirect_sbt_pin_rechecked` (an existing row re-verified after the build's dependencies changed: its dependency digest is recorded anew, `original`/`new` are `{deps}`). The load-time verifier also fails `update` when a project declares a pinned GA at a version newer than the pin's base (the build-wide override would otherwise force it back down). A new pin is gated on sbt's own resolution records under `target/` (never the machine-wide cache): run-level stops wire nothing, warn once and exit 0 — `redirect_sbt_no_resolution_evidence` (none; run `sbt update` first; always the in-memory engine's answer), `redirect_sbt_resolution_incomplete` (a declared project left no evidence, or the project definitions cannot be read statically), `redirect_sbt_resolution_stale` (a build source is newer than some project's evidence: each project is dated by its own newest record, so a partial `sbt /update` does not vouch for the others). Per-patch refusals (never confirmed): `redirect_sbt_missing_override` (no `maven2` override or no suffixed version), `redirect_sbt_integrity_missing` (jar or pom sha256 missing), `redirect_sbt_unsafe_value` (a value unsafe in a Scala literal, or an index URL not naming the uuid), `redirect_sbt_version_conflict` (some project resolves another version, or a build source declares the GA newer than the patch's base), `redirect_sbt_override_conflict` (two patches for one GA in a run, or another base already pinned), `redirect_sbt_vendored_conflict` (the GA is pinned by `socket-patch-vendor.sbt`, or that file cannot be parsed — then every Maven patch), `redirect_sbt_owned_file_modified` / `redirect_sbt_owned_file_foreign` (`socket-patch.sbt` edited, or not socket-patch's — every Maven patch), `redirect_sbt_owned_file_unreadable` (a whole-run refusal: `socket-patch.sbt` is on disk but cannot be read as UTF-8 text, so writing it would replace it; nothing is written), `redirect_sbt_unsupported_version`, `redirect_sbt_build_root_unknown` (sbt files but no versioned build root — every Maven patch), `redirect_sbt_overrides_assignment` / `redirect_sbt_resolvers_assignment` (a build source reassigns `dependencyOverrides` / `resolvers` with `:=`, `~=`, `--=` or `<<=`), `redirect_sbt_onload_assignment` (a build source reassigns `onLoad`, in any scope, with `:=`, `~=`, `--=` or `<<=` without keeping its previous value — a `:=` reading `(Global / onLoad).value`, or a `~=` that composes with `andThen` / `compose`, keeps it — which drops the generated file's load-time verifier and resolver order), `redirect_sbt_dependency_lock_present` (a `build.sbt.lock`), `redirect_sbt_scala_runtime_unsupported` (`org.scala-lang`), `redirect_sbt_classifier_unsupported`; a GA no library configuration resolves is skipped silently (`redirect_sbt_meta_build_only` when only the meta-build resolves it). Advisories: `redirect_sbt_version_untested` (sbt 2.1+, still wired), `redirect_sbt_override_build_repos` (`sbt.override.build.repos=true`), `redirect_maven_pom_ignored_sbt_build` (a `pom.xml` beside the sbt build, which sbt never reads; the Maven rewriter still edits it for the Maven build). A re-run keeps an existing row and re-checks it. When the build's dependency digest changed since the pin, evidence resolved after the change (fresh, newer than the generated file) re-verifies it and the row's digest is refreshed (`redirect_sbt_pin_rechecked`); the uuid is NOT confirmed on `redirect_sbt_pin_declared_newer` (a build source now declares the GA newer than the pin's base; the row stays, sbt's load-time verifier fails the build, and the remedy is `socket-patch rollback` or declaring the base again), `redirect_sbt_pin_unverifiable` (the digest changed and the evidence predates the change, or the digest cannot be computed: run `sbt update`, then re-run socket-patch), `redirect_sbt_override_shadowed` (the evidence still resolves the base version) or `redirect_sbt_resolved_elsewhere` (the pinned version resolves from outside the pin repository from a file whose sha256 is not the pinned jar's; a copy holding the pinned bytes, such as the Ivy cache a second checkout reads, is fine — at most 64 pinned artifact files of up to 256 MiB are hashed, anything else counts as elsewhere), and also when a build source now reassigns `dependencyOverrides` / `resolvers` / `onLoad` or a `build.sbt.lock` appeared (the same `redirect_sbt_overrides_assignment` / `redirect_sbt_resolvers_assignment` / `redirect_sbt_onload_assignment` / `redirect_sbt_dependency_lock_present` codes; the row stays and sbt's load-time verifier fails the build). For a pure sbt root (no `pom.xml` / Gradle script beside it), maven confirmation is decided only by the sbt rewriter's report; on a mixed root a uuid the sbt rewriter refused is still confirmed by the Maven rewriter's own `pom.xml` pin (the generated sbt files never prove a pin by substring). **Mill and scala-cli** are guidance only: per Maven patch `redirect_mill_manual_snippet` / `redirect_scala_cli_manual_snippet` carry a paste-able snippet (repository + forced suffixed version), nothing is written or confirmed, and a pure Mill / scala-cli root gets no `redirect_maven_no_pom`; there, a Maven patch the server sent without a `maven2` registry override gets `redirect_maven_missing_override` instead of a snippet (with a `pom.xml` beside the Mill / scala-cli files the pom rewriter reports it). `rollback` / `remove` restore `socket-patch.sbt` offline (the rows removed, the file deleted with its last pin; the gitignored downloads are left). Manifest-less VEX reads every strictly parsed pin as a hosted reference but grants it the lockfile basis only when the local evidence shows every recorded version of the GA is the pinned one and every recorded artifact hashes to a pinned sha256 (else `sbt_resolution_unverified`, and the suffixed copy sbt downloaded into `.socket/sbt-hosted` is its only basis). Where the build provably does not use the pinned bytes, that copy proves nothing and the patch is omitted (`vex_sbt_pin_bypassed`): a build source reassigns `dependencyOverrides` (`:=`, `~=`, `--=`; replacing the generated override) or reassigns `onLoad` without keeping its previous value (dropping the installer that holds the load-time verifier and resolver order), whether or not any evidence exists, or a resolution record dated after the generated files and every build source shows the GA's base version (the override shadowed), or the pinned version from outside the pin repository with bytes that are not pinned (judged exactly as the hosted rewriter re-checks a pin, `redirect_sbt_override_shadowed` / `redirect_sbt_resolved_elsewhere`). A record older than the wiring (a project or cross build not re-resolved since) proves nothing, and current records that verify the pin always keep it. A `resolvers` reassignment or `sbt.override.build.repos=true` alone is no bypass: the override still forces the Socket-only version and the load-time verifier checks its bytes, so the build runs the pinned bytes or fails (which is why an `onLoad` reassignment dropping that verifier is one). Stale or partial evidence, project definitions that cannot be read statically and a `build.sbt.lock` only withhold the lockfile basis. A file under a generated name without socket-patch's header is read as the root build definition sbt loads it as. @@ -709,7 +709,7 @@ Recognition rules that hold for every ecosystem: * **Patch hosts.** A hosted reference counts only on `https://patch.socket.dev` or the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin, with no userinfo. The URL must be one every client reads alike: a backslash, whitespace or a control character anywhere in it (after the lock format's own `\/` unescape and the trim of surrounding whitespace) makes it no reference, because URL parsers disagree about the host of a URL such as `https://patch.socket.dev\@evil.example/…`. Its path must be one the patch server serves a patch under: `patch//…`, `patch-registry//…` (`` one of `npm`, `pypi`, `cargo`, `golang`, `gem`, `composer`, `maven`, `nuget`) or `gopatch/…`, first in the path on Socket's own server and under any path prefix on a `--patch-server-url` deployment, with no percent-encoded `/` or `\` (`%2f`, `%5c`) anywhere in it. The uuid is the LAST canonical-uuid segment below that level, because grant tokens may themselves be uuid-shaped. A URL on a patch host that fails these rules is not a hosted pin (`vex` does not attest it; `list`, `rollback`, `remove` and `scan` do not manage it, and a hosted `scan` does not write one), but a uuid in its path still counts as *mentioned* for the liveness gates below, so no ledger record is revived from it. The Go module prefix is fixed. `socket-patch-` registry / repository / source names count only through a pin. For a URL on any other host, see **Patch hosts** above. * **Pins, not definitions.** A registry, index or source *definition* alone (cargo `[registries]`, nuget ``, pom ``, uv index tables, `.npmrc`) never makes a reference, because it survives a reverted pin. Sections the package manager ignores are not read: npm's v2 `dependencies` mirror, a `.cargo/config.toml` shadowed by `.cargo/config`. A Socket pin inside a maven `` is diagnosed, never a reference. * **Contested locks.** When one lock wires a package to a patch and another lock resolves the same `name@version` from a non-Socket source, the build's bytes depend on which package manager runs. The reference is then dropped with a `patched_ref_unattributable` diagnostic naming both files. This applies across npm / pnpm / yarn / bun and across uv / pylock / poetry / pdm / Pipfile.lock / requirements. A PEP 723 script lock is a lock like the others: `uv run` installs its script's dependencies from it, so a script lock that resolves the release from the index contests a project lock's reference and the reverse (both writers rewire script locks, so a re-run clears it). A Python lock also contests itself: another entry of the **same** `uv.lock`, script lock, `pylock*.toml`, `poetry.lock`, `pdm.lock` or `Pipfile.lock` that resolves the wired release from a non-Socket source (a uv marker fork, a Poetry multiple-constraint dependency, a PEP 751 marker split, a PDM extras variant, the other `Pipfile.lock` category) is installed wherever its markers, extras or category select it, so the reference is withheld until `scan` / `vendor` rewires every entry. Requirements and `pyproject.toml` / `hatch.toml` declarations are not lock entries, and a Socket reference there is withheld (`patched_ref_unattributable`, naming the other requirement) while another requirement of the same package can install the same release where the reference does not apply: beside a reference that carries an environment marker, any requirement of the set that is not an exact pin of another release; beside a reference in an extra, a dependency group or a Hatch environment, any requirement of the package in `[project].dependencies` (which `pip install .` reads), or an exact pin of the release in any table not installed together with the reference. A reference and a compatible requirement that pip resolves together (one requirement set, or `[project].dependencies` with the project's extras) resolve to the reference, so an unmarked reference is not contested there. The root `requirements.txt` and its in-root `-r` includes count as one lock here: pip reads them as one requirement set, where a direct reference wins over a compatible `==` pin of the same version in another file of the set (#1086). A PyPI version matches under PEP 440 equality, so a requirements line pinned in any spelling that can only install the wired release (`==1.2.3.0`, `==v1.2.3`, `===1.2.3`) contests it like `==1.2.3` does; a range or wildcard (`~=1.2.3`, `==1.2.*`) does not (#1602). A **bundled** npm copy (`inBundle: true`, or v1 `bundled: true`, beneath a dependency that bundles it; the root project's own bundles install from the lock, #1618) of the same `name@version` contests the reference too, in the same lock, in the other npm lock of a shrinkwrap/package-lock pair, or in any other lock. npm unpacks it from the parent package's tarball, so no rewire reaches it and it stays unpatched. Bun and vlt unpack bundled copies the same way (#469, #471). pnpm unpacks bundled copies too, but its lock cannot tie one to a reference (see **Unattested references** below). For Bun, that is a `bun.lock` entry whose meta is `{ "bundled": true }`, or a `bun.lockb` record that a dependency edge with the `bundled` behavior bit reaches, including one Bun shares with a regular install. Such an entry is never a reference, and it contests the reference the same way. For vlt, the lock records no node for a bundled copy, so the copy is found in the installed store: a real package directory inside a store package's own `node_modules`. yarn classic's `yarn.lock` records nothing about bundled copies either (#758), so for a lock with a Socket wiring they are found in the installed `node_modules`: each package a parent's `bundleDependencies` / `bundledDependencies` names inside the parent's own `node_modules`, the dependencies of those beside them, and everything nested under them. Such a copy contests the reference in `yarn.lock` (the diagnostic names the parent's lock entry and the copy's directory); a lock-only `vex` with no `node_modules` can't see it. Hosted and vendored scans skip these copies with `redirect_bun_bundled_instance_skipped` / `redirect_vlt_bundled_instance_skipped` / `vendor_bundled_instance_skipped`, and a yarn classic hosted scan names one with `redirect_copy_unpatched`. When a bundled copy is the only instance, vendoring refuses with `vendor_lock_entry_not_rewritable`. A reference withheld only because such an unreachable copy installs beside it (a bundled npm / Bun / vlt copy, an npm copy beneath a `hasShrinkwrap` package (#753) or one npm installs from a git / url / `file:` spec, or a yarn classic git or `file:` directory block of the same `name@version`) is still the rewriter's own wiring of exactly one package version: it is never attested, but `rollback`, `remove`, `list` and the hosted → vendored takeover treat it as an ordinary hosted pin and restore its upstream registry entry (#828), rather than refusing it with `hosted_wiring_contested`. Another entry of the **same** npm, Bun or yarn lock that resolves the wired `name@version` from a non-Socket source (for example a workspace member added after the rewire, then `npm install` / `bun install` / `yarn install`; for yarn berry, a registry locator such as `left-pad@npm:1.3.0` beside the hosted `…::__archiveUrl=` one) contests the reference too (#588). The package manager installs both entries, and that copy stays unpatched. Re-running `scan` / `vendor` rewires every copy. -* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Thirteen cases besides Gradle's (`vex_gradle_lock_above_base`) and NuGet's (`vex_nuget_lock_other_version`, see the table above); one of them, a vendored pin in a lock the package manager is told not to read (`vex_lock_not_read`), has its own bullet below; another, **hosted sbt pins a build bypasses** (`vex_sbt_pin_bypassed`), is under **Hosted sbt** above: **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactor roots** (`vex_maven_reactor_root`): a hosted pin in a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers (see the hosted Maven rewriter), is omitted, because a module's own literal `` overrides a root pin and module poms are not read (#261); hosted scan refuses such roots (`redirect_maven_multimodule_unsupported`), so this only covers pins an older release wrote. **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA (or one whose `` implies a classifier or carries code, such as `test-jar`) is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build), live or inside ``, resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier (a profile's overriding the live one), or no version in the root pom — the pin is omitted. A pre-v5 single-pom vendored repository holds only the main jar, so any such copy omits its reference. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep, writing nothing, when an executable copy may resolve anything but the suffixed pin (so it never writes a pin this rule withholds). **Maven profile declarations** (`vex_maven_profile_unpatched`): a `` declaration of a pinned GA's main jar in the root `pom.xml` at any version other than the pin (the base release, another release, a `${property}` the pom does not resolve) overrides the pin whenever that profile is active, so the reference is omitted. A profile `` entry always counts; a profile `` entry counts only when management governs the pin (no direct `` outside ``), since a direct literal version beats management. A declaration without a `` takes the live pin, and a `pom` (or `java-source` / `javadoc`) typed one carries no code; neither withholds the statement. Activation is not evaluated: every profile counts, as in vendored mode, which rewrites profile declarations too; hosted scan leaves them as written and writes no pin they bypass (`redirect_maven_profile_dependency_unpatched`). A pin spelled through a property counts the same way: a `${property}` `` is interpolated through every property it names, the project's own `${project.version}` included (itself often spelled through `${revision}`), at most 16 levels deep (a cycle or an undefined name never resolves to a pin), and when any profile's `` — or any combination of profiles' together, each nested reference read with that combination active, as the vendored planner weighs them too — redefine one of those properties so that it resolves anything other than the pin (or nothing), the reference is omitted too; a `.mvn/maven.config` user property wins over every profile's. A profile declaration reads its own profile's `` first. When more than 8 profiles may change such a version, or a profile's `` cannot be parsed, the reference is omitted (fail closed); the rest of the pom is still read. One pom's `${property}` texts are also given a fixed amount of interpolation in all (about four million property lookups, which a pom reaches only with thousands of different texts that each take hundreds of lookups under many profile combinations); a `${property}` read after that counts as unresolved, the same fail-closed way. The statement names the profiles that move the pin and the version they move it to. Coordinates count the same way: when a profile's `` (or several profiles' together, or the profile holding the declaration) redefine a property a `${property}` `` / `` names, so that the declaration carrying the pin names another package (the pin then no longer applies to the patched GA) or another declaration names the patched GA (its main jar, or an executable classifier copy) at a version other than the pin, or as a classifier copy with no version of its own, the reference is omitted; a profile value the pom cannot resolve may name any package, a user property wins over every profile's, and the same 8-profile and unreadable-profile limits fail closed. Each such reading is weighed like a declaration of its own: a retargeted classifier copy (a `test-jar` is the `tests` copy; an explicit `` names the copy whatever the type) by the classifier rule (`vex_maven_classifier_unpatched`, so a pre-v5 vendored repository, which serves only the main jar, is bypassed even at the vendored version), any other non-`jar` type not at all, and a reading that moves the coordinates and the version onto the pin together does not withhold the statement. Hosted scan refuses such a dep (`redirect_maven_profile_coordinates_unpatched`), and vendored mode leaves the declaration as written and does not pin its root (`coordinates_overridden`), except a retargeted classifier copy, which it reports as `classifier_declared` with the root still pinned. The same holds for a pre-v5 single-pom vendored repository, which serves only the original version. **Maven parent poms** (`vex_maven_parent_declares`): a pin that only the root pom's `` carries, for a package the root pom does not declare in its own `` (what hosted scan adds for a dependency with no literal ``), governs the declaration the build inherits. Maven merges a parent pom's `` into the child, and management fills in only a dependency that declares no version (Maven 3.9.16: with the parent declaring the package at a literal version the build resolves the upstream jar and never asks for the patched version). The parent chain is followed through the checkout (``, default `../pom.xml`, when the pom there is the parent the reference names). When a parent pom, one above it, or a profile of either declares the package with a version, the reference is omitted, naming that pom; declare the package in the root pom with no `` (its own declaration replaces the inherited one and the pin governs it) or drop the version from the parent's declaration. The nearest parent declaring it with no version, or a chain read to a pom with no `` that never declares it, leaves the pin attested. A parent that cannot be read (`` or no pom at the relative path, so Maven resolves it from a repository; a pom outside the git checkout; one that does not parse) may declare it either way, so the reference then attests only from the installed copy of the patched version (`-socket.` in the local repository, hash-verified) and is `package_not_found` until a build has resolved it. A pin on the root pom's own declaration, or one governing a declaration the root pom makes with no version, is not weighed against any parent. **Maven user properties** (`vex_maven_config_override`): Maven resolves a `${property}` `` from `.mvn/maven.config`'s `-D` user properties before the pom's `` (`${project.*}` / `${pom.*}` always come from the model). A pin the pom spells through a property that `.mvn/maven.config` redefines resolves that other version, so the reference is omitted. A Socket version that only a `-D` user property supplies is not `pom.xml` wiring (hosted scan never writes one, and `rollback` / `remove` never edit `.mvn/maven.config`): it is no reference at all, only a diagnostic. **pnpm branch locks** (`vex_pnpm_git_branch_lockfile`): with `gitBranchLockfile` on, pnpm installs a git branch from its own `pnpm-lock..yaml` (the **pnpm per-branch locks** state above), which no wiring reaches. `vex` does not decide whether the setting is on: the presence of any branch lock (at the root, or in a workspace member that installs from its own lock under `sharedWorkspaceLockfile: false`, read from the project's files and never from the environment) omits every reference of the root pnpm lock (`pnpm-lock.yaml`, or `shrinkwrap.yaml` without it) and of each member's own lock, hosted and vendored alike, whatever `gitBranchLockfile` or pnpm's `lockfile` setting says (#556; deterministic and fail-closed). This is checked only when a root or member pnpm lock wires a patch. Hosted mode refuses every pnpm pin when the setting is on and vendored mode refuses the project, so this also covers wiring written before the branch lock appeared. The run warning names the branch lock in the marked lock's own directory. Rush locks are not affected. **Self-patched npm and Bun packages** (`vex_npm_patched_dependency`): a reference in `package-lock.json` / `npm-shrinkwrap.json` / `bun.lock` / `bun.lockb` to a package the project patches itself is omitted, by the hosted rewriters' own per-dependency rule (`redirect_npm_patched_dependency_skipped`, #711; `redirect_bun_patched_dependency_skipped`, #367): a root `package.json` `patchedDependencies` key for its `name@version`, its bare name, or `name@` of any tarball (npm and Bun alike); for npm also a non-null `patched` record on any present npm lock's entry for that `name@version`; for `bun.lock` also the keys it mirrors (the run warning then names `bun.lock` as the key's source). npm applies the user's diff on top of whatever tarball the lock names and Bun applies it only to the resolution it is keyed on, so both modes leave such a package unwired; this covers pins an earlier release wrote, and an npm one fails `npm ci` with `EPATCHFAILED` until `socket-patch rollback ` restores the registry entry (the remedy says so). A key naming the pinned tarball itself (a patch made on top of the pin) is no conflict for the hosted rewriters, which keep the pin, but the reference is omitted all the same: the user's diff runs over the Socket bytes, never the Socket patch alone; a reference with neither a hosted url nor a vendored tarball is matched by its `name@version` and counts every tarball key. Only a reference that survives the lock contests carries this reason. **Packages patched with pnpm, Yarn or patch-package** (`vex_npm_patched_dependency` too): a reference of any npm-family lock (pnpm, Rush, yarn classic and berry, vlt, npm, Bun; hosted or vendored) to a `name@version` the project patches itself is omitted, read from the project, its declared workspace members and (on disk) the ancestor workspace settings up to the git repository root, by the consent gate's own walk: pnpm's `patchedDependencies` (`package.json`'s `pnpm.patchedDependencies`, `pnpm-workspace.yaml`'s `patchedDependencies`, and the `patchedDependencies` map or a `(patch_hash=…)` key suffix in the reference's own pnpm lock or the root one), a yarn berry `patch:` descriptor outside Yarn's builtin compatibility patches (`package.json`'s dependency maps and `resolutions`, or a `patch:` locator `yarn.lock` resolves, including one wrapping the hosted tarball), or a patch-package file (`patches/+.patch`, or under a `--patch-dir` a `package.json` script names; it counts for every version of ``, since patch-package applies it to whichever version is installed). A key's version may be exact, a range or absent (every version), and metadata that cannot be read (an unparseable `package.json`, a `--patch-dir` the script computes) omits every npm reference. This is the `user_patch_conflict` consent gate's evidence (see [Existing project patches](#existing-project-patches)) minus native npm / Bun and the other ecosystems, and the evidence the in-memory hosted engine withholds a package by. The package manager (or the postinstall) applies the user's diff on top of whatever tarball the lock names, so the install never runs the Socket patch alone: the reference is omitted even when an `--allow-patch-conflicts` run wired it, for as long as the patch is declared. Yarn classic and vlt have no patch mechanism of their own (vlt's `vlt.json` `modifiers` rewrite specs, not contents), so patch-package is what is read for them. npm's and Bun's own top-level `patchedDependencies` are judged by the rule above, not here. **Go workspaces** (`go_workspace_override`): a hosted or vendored Go `replace` that the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects, by the same check hosted and vendored modes run before writing one (`redirect_golang_workspace_conflict`, `vendor_go_workspace_conflict`), is omitted under the reason `vex`'s own go.mod gate reports. So is a replace in the root `go.work` while go builds another one. **Unpinned Cargo declarations** (`vex_cargo_unpinned_declaration`): cargo resolves each source on its own, so when one declaration of a crate pins it to `socket-patch-` but another — the root `Cargo.toml`'s or a workspace member's, read as hosted scan reads them — is not pinned, with a version requirement that may select the locked patched version, that declaration builds a separate, unpatched copy, possibly of the very version the pin covers. Not pinned means crates.io or another registry that no Socket `[patch.]` registry entry redirects, a `registry-index`, a path or git — the last three even beside `registry = "socket-patch-"`, which they override (hosted scan's own pinned check). The `Cargo.lock` reference is omitted, naming the unpinned declaration's manifest. Hosted scan pins every declaration, so this is a partial revert or a hand edit; the warning says whether re-running `scan` pins it again (a crates.io declaration whose requirement matches no other locked version of the crate) or cannot (`redirect_cargo_toml_dep_unrewritable`: roll the patch back or change the declaration). A declaration whose requirement excludes the patched version (cargo resolves it to another version), and a `[workspace.dependencies]` entry no manifest inherits, do not withhold the statement. When the lock already holds a same-version copy from another source, the reference is withheld as an unpatched lock copy instead. A declaration pinned to ANOTHER Socket patch, which the lock does not resolve the crate from, adds that patch's `Cargo.toml` reference, so the package is gated as `wiring_conflict`. **Vendored Cargo copies a `[patch]` does not reach** (`vex_cargo_patch_bypassed`): a `[patch.]` entry replaces the crate only in declarations from ``, and `vendor` writes `[patch.crates-io]`. So a vendored reference is omitted when a live declaration of the crate (the root `Cargo.toml`'s or a workspace member's) names another registry, a `registry-index` or a git repository, with a version requirement that may select the patched version, unless a `[patch]` table for its source points at the same copy (`[patch.]` for a registry dependency, `[patch.""]` for a `registry-index` one, `[patch.""]` for a git one; URLs compare as cargo canonicalizes them: the host's case, a lock's `registry+` prefix, one trailing `/` and a `.git` suffix ignored, a GitHub URL case-insensitive, a `sparse+` index another source than the git one, and the crates.io git index is crates.io); cargo builds that declaration's own, unpatched copy. Workspace members are read for this whenever the root manifest or the project cargo config wires a Socket copy through `[patch]`, whatever the lock says. It is also omitted when `Cargo.lock` locks the crate at exactly the patched version from any source (a registry, crates.io included, or git) beside the vendored copy; the warning names that lock entry. A path declaration (the user's own fork) does not withhold the statement. Only `[patch]` entries cargo honors count: a manifest entry the project config or a crates.io URL table replaces covers nothing. The warning ends with the remedy for its evidence: for a declaration, re-running `vendor` does not help (declare the crate from crates.io there, point a `[patch]` table for its source at the copy, or roll the patch back); for a stale lock entry a `[patch]` table at the copy redirects (crates.io under `[patch.crates-io]`, another registry or a git repository under its own table; a registry's table by its index URL, or by its name when the project's cargo config defines that registry), 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. The commands name the entry by its source, because the bare `@` also fits the copy the lock holds at `+socket.` and cargo refuses it as ambiguous. A source with a character a shell would read inside the quotes is not printed: the command then takes the bare crate name, which cargo answers with the specs it accepts. +* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Thirteen cases besides Gradle's (`vex_gradle_lock_above_base`) and NuGet's (`vex_nuget_lock_other_version`, see the table above); one of them, a vendored pin in a lock the package manager is told not to read (`vex_lock_not_read`), has its own bullet below; another, **hosted sbt pins a build bypasses** (`vex_sbt_pin_bypassed`), is under **Hosted sbt** above: **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactors** (`vex_maven_reactor_root`): a hosted patch in a reactor (a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers) is omitted while a module that resolves the patched version, or may, is reached by no pin and no declaration of the patch, or a declaration may still build the unpatched version: a module's own literal `` overrides a pin above it (#261). The note names the module. A reactor one of whose poms cannot be read is omitted the same way, whatever its root pins. See [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA (or one whose `` implies a classifier or carries code, such as `test-jar`) is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build), live or inside ``, resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier (a profile's overriding the live one), or no version in the root pom — the pin is omitted. A pre-v5 single-pom vendored repository holds only the main jar, so any such copy omits its reference. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep, writing nothing, when an executable copy may resolve anything but the suffixed pin (so it never writes a pin this rule withholds). **Maven profile declarations** (`vex_maven_profile_unpatched`): a `` declaration of a pinned GA's main jar in the root `pom.xml` at any version other than the pin (the base release, another release, a `${property}` the pom does not resolve) overrides the pin whenever that profile is active, so the reference is omitted. A profile `` entry always counts; a profile `` entry counts only when management governs the pin (no direct `` outside ``), since a direct literal version beats management. A declaration without a `` takes the live pin, and a `pom` (or `java-source` / `javadoc`) typed one carries no code; neither withholds the statement. Activation is not evaluated: every profile counts, as in vendored mode, which rewrites profile declarations too; hosted scan leaves them as written and writes no pin they bypass (`redirect_maven_profile_dependency_unpatched`). A pin spelled through a property counts the same way: a `${property}` `` is interpolated through every property it names, the project's own `${project.version}` included (itself often spelled through `${revision}`), at most 16 levels deep (a cycle or an undefined name never resolves to a pin), and when any profile's `` — or any combination of profiles' together, each nested reference read with that combination active, as the vendored planner weighs them too — redefine one of those properties so that it resolves anything other than the pin (or nothing), the reference is omitted too; a `.mvn/maven.config` user property wins over every profile's. A profile declaration reads its own profile's `` first. When more than 8 profiles may change such a version, or a profile's `` cannot be parsed, the reference is omitted (fail closed); the rest of the pom is still read. One pom's `${property}` texts are also given a fixed amount of interpolation in all (about four million property lookups, which a pom reaches only with thousands of different texts that each take hundreds of lookups under many profile combinations); a `${property}` read after that counts as unresolved, the same fail-closed way. The statement names the profiles that move the pin and the version they move it to. Coordinates count the same way: when a profile's `` (or several profiles' together, or the profile holding the declaration) redefine a property a `${property}` `` / `` names, so that the declaration carrying the pin names another package (the pin then no longer applies to the patched GA) or another declaration names the patched GA (its main jar, or an executable classifier copy) at a version other than the pin, or as a classifier copy with no version of its own, the reference is omitted; a profile value the pom cannot resolve may name any package, a user property wins over every profile's, and the same 8-profile and unreadable-profile limits fail closed. Each such reading is weighed like a declaration of its own: a retargeted classifier copy (a `test-jar` is the `tests` copy; an explicit `` names the copy whatever the type) by the classifier rule (`vex_maven_classifier_unpatched`, so a pre-v5 vendored repository, which serves only the main jar, is bypassed even at the vendored version), any other non-`jar` type not at all, and a reading that moves the coordinates and the version onto the pin together does not withhold the statement. Hosted scan refuses such a dep (`redirect_maven_profile_coordinates_unpatched`), and vendored mode leaves the declaration as written and does not pin its root (`coordinates_overridden`), except a retargeted classifier copy, which it reports as `classifier_declared` with the root still pinned. The same holds for a pre-v5 single-pom vendored repository, which serves only the original version. **Maven parent poms** (`vex_maven_parent_declares`): a pin that only the root pom's `` carries, for a package the root pom does not declare in its own `` (what hosted scan adds for a dependency with no literal ``), governs the declaration the build inherits. Maven merges a parent pom's `` into the child, and management fills in only a dependency that declares no version (Maven 3.9.16: with the parent declaring the package at a literal version the build resolves the upstream jar and never asks for the patched version). The parent chain is followed through the checkout (``, default `../pom.xml`, when the pom there is the parent the reference names). When a parent pom, one above it, or a profile of either declares the package with a version, the reference is omitted, naming that pom; declare the package in the root pom with no `` (its own declaration replaces the inherited one and the pin governs it) or drop the version from the parent's declaration. The nearest parent declaring it with no version, or a chain read to a pom with no `` that never declares it, leaves the pin attested. A parent that cannot be read (`` or no pom at the relative path, so Maven resolves it from a repository; a pom outside the git checkout; one that does not parse) may declare it either way, so the reference then attests only from the installed copy of the patched version (`-socket.` in the local repository, hash-verified) and is `package_not_found` until a build has resolved it. A pin on the root pom's own declaration, or one governing a declaration the root pom makes with no version, is not weighed against any parent. **Maven user properties** (`vex_maven_config_override`): Maven resolves a `${property}` `` from `.mvn/maven.config`'s `-D` user properties before the pom's `` (`${project.*}` / `${pom.*}` always come from the model). A pin the pom spells through a property that `.mvn/maven.config` redefines resolves that other version, so the reference is omitted. A Socket version that only a `-D` user property supplies is not `pom.xml` wiring (hosted scan never writes one, and `rollback` / `remove` never edit `.mvn/maven.config`): it is no reference at all, only a diagnostic. **pnpm branch locks** (`vex_pnpm_git_branch_lockfile`): with `gitBranchLockfile` on, pnpm installs a git branch from its own `pnpm-lock..yaml` (the **pnpm per-branch locks** state above), which no wiring reaches. `vex` does not decide whether the setting is on: the presence of any branch lock (at the root, or in a workspace member that installs from its own lock under `sharedWorkspaceLockfile: false`, read from the project's files and never from the environment) omits every reference of the root pnpm lock (`pnpm-lock.yaml`, or `shrinkwrap.yaml` without it) and of each member's own lock, hosted and vendored alike, whatever `gitBranchLockfile` or pnpm's `lockfile` setting says (#556; deterministic and fail-closed). This is checked only when a root or member pnpm lock wires a patch. Hosted mode refuses every pnpm pin when the setting is on and vendored mode refuses the project, so this also covers wiring written before the branch lock appeared. The run warning names the branch lock in the marked lock's own directory. Rush locks are not affected. **Self-patched npm and Bun packages** (`vex_npm_patched_dependency`): a reference in `package-lock.json` / `npm-shrinkwrap.json` / `bun.lock` / `bun.lockb` to a package the project patches itself is omitted, by the hosted rewriters' own per-dependency rule (`redirect_npm_patched_dependency_skipped`, #711; `redirect_bun_patched_dependency_skipped`, #367): a root `package.json` `patchedDependencies` key for its `name@version`, its bare name, or `name@` of any tarball (npm and Bun alike); for npm also a non-null `patched` record on any present npm lock's entry for that `name@version`; for `bun.lock` also the keys it mirrors (the run warning then names `bun.lock` as the key's source). npm applies the user's diff on top of whatever tarball the lock names and Bun applies it only to the resolution it is keyed on, so both modes leave such a package unwired; this covers pins an earlier release wrote, and an npm one fails `npm ci` with `EPATCHFAILED` until `socket-patch rollback ` restores the registry entry (the remedy says so). A key naming the pinned tarball itself (a patch made on top of the pin) is no conflict for the hosted rewriters, which keep the pin, but the reference is omitted all the same: the user's diff runs over the Socket bytes, never the Socket patch alone; a reference with neither a hosted url nor a vendored tarball is matched by its `name@version` and counts every tarball key. Only a reference that survives the lock contests carries this reason. **Packages patched with pnpm, Yarn or patch-package** (`vex_npm_patched_dependency` too): a reference of any npm-family lock (pnpm, Rush, yarn classic and berry, vlt, npm, Bun; hosted or vendored) to a `name@version` the project patches itself is omitted, read from the project, its declared workspace members and (on disk) the ancestor workspace settings up to the git repository root, by the consent gate's own walk: pnpm's `patchedDependencies` (`package.json`'s `pnpm.patchedDependencies`, `pnpm-workspace.yaml`'s `patchedDependencies`, and the `patchedDependencies` map or a `(patch_hash=…)` key suffix in the reference's own pnpm lock or the root one), a yarn berry `patch:` descriptor outside Yarn's builtin compatibility patches (`package.json`'s dependency maps and `resolutions`, or a `patch:` locator `yarn.lock` resolves, including one wrapping the hosted tarball), or a patch-package file (`patches/+.patch`, or under a `--patch-dir` a `package.json` script names; it counts for every version of ``, since patch-package applies it to whichever version is installed). A key's version may be exact, a range or absent (every version), and metadata that cannot be read (an unparseable `package.json`, a `--patch-dir` the script computes) omits every npm reference. This is the `user_patch_conflict` consent gate's evidence (see [Existing project patches](#existing-project-patches)) minus native npm / Bun and the other ecosystems, and the evidence the in-memory hosted engine withholds a package by. The package manager (or the postinstall) applies the user's diff on top of whatever tarball the lock names, so the install never runs the Socket patch alone: the reference is omitted even when an `--allow-patch-conflicts` run wired it, for as long as the patch is declared. Yarn classic and vlt have no patch mechanism of their own (vlt's `vlt.json` `modifiers` rewrite specs, not contents), so patch-package is what is read for them. npm's and Bun's own top-level `patchedDependencies` are judged by the rule above, not here. **Go workspaces** (`go_workspace_override`): a hosted or vendored Go `replace` that the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects, by the same check hosted and vendored modes run before writing one (`redirect_golang_workspace_conflict`, `vendor_go_workspace_conflict`), is omitted under the reason `vex`'s own go.mod gate reports. So is a replace in the root `go.work` while go builds another one. **Unpinned Cargo declarations** (`vex_cargo_unpinned_declaration`): cargo resolves each source on its own, so when one declaration of a crate pins it to `socket-patch-` but another — the root `Cargo.toml`'s or a workspace member's, read as hosted scan reads them — is not pinned, with a version requirement that may select the locked patched version, that declaration builds a separate, unpatched copy, possibly of the very version the pin covers. Not pinned means crates.io or another registry that no Socket `[patch.]` registry entry redirects, a `registry-index`, a path or git — the last three even beside `registry = "socket-patch-"`, which they override (hosted scan's own pinned check). The `Cargo.lock` reference is omitted, naming the unpinned declaration's manifest. Hosted scan pins every declaration, so this is a partial revert or a hand edit; the warning says whether re-running `scan` pins it again (a crates.io declaration whose requirement matches no other locked version of the crate) or cannot (`redirect_cargo_toml_dep_unrewritable`: roll the patch back or change the declaration). A declaration whose requirement excludes the patched version (cargo resolves it to another version), and a `[workspace.dependencies]` entry no manifest inherits, do not withhold the statement. When the lock already holds a same-version copy from another source, the reference is withheld as an unpatched lock copy instead. A declaration pinned to ANOTHER Socket patch, which the lock does not resolve the crate from, adds that patch's `Cargo.toml` reference, so the package is gated as `wiring_conflict`. **Vendored Cargo copies a `[patch]` does not reach** (`vex_cargo_patch_bypassed`): a `[patch.]` entry replaces the crate only in declarations from ``, and `vendor` writes `[patch.crates-io]`. So a vendored reference is omitted when a live declaration of the crate (the root `Cargo.toml`'s or a workspace member's) names another registry, a `registry-index` or a git repository, with a version requirement that may select the patched version, unless a `[patch]` table for its source points at the same copy (`[patch.]` for a registry dependency, `[patch.""]` for a `registry-index` one, `[patch.""]` for a git one; URLs compare as cargo canonicalizes them: the host's case, a lock's `registry+` prefix, one trailing `/` and a `.git` suffix ignored, a GitHub URL case-insensitive, a `sparse+` index another source than the git one, and the crates.io git index is crates.io); cargo builds that declaration's own, unpatched copy. Workspace members are read for this whenever the root manifest or the project cargo config wires a Socket copy through `[patch]`, whatever the lock says. It is also omitted when `Cargo.lock` locks the crate at exactly the patched version from any source (a registry, crates.io included, or git) beside the vendored copy; the warning names that lock entry. A path declaration (the user's own fork) does not withhold the statement. Only `[patch]` entries cargo honors count: a manifest entry the project config or a crates.io URL table replaces covers nothing. The warning ends with the remedy for its evidence: for a declaration, re-running `vendor` does not help (declare the crate from crates.io there, point a `[patch]` table for its source at the copy, or roll the patch back); for a stale lock entry a `[patch]` table at the copy redirects (crates.io under `[patch.crates-io]`, another registry or a git repository under its own table; a registry's table by its index URL, or by its name when the project's cargo config defines that registry), 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. The commands name the entry by its source, because the bare `@` also fits the copy the lock holds at `+socket.` and cargo refuses it as ambiguous. A source with a character a shell would read inside the quotes is not printed: the command then takes the bare crate name, which cargo answers with the specs it accepts. * **Shrinkwrap without a twin (#899).** npm >= 12 never reads `npm-shrinkwrap.json`: on a project whose only npm lock is the shrinkwrap it resolves the tree from the registry and writes a fresh `package-lock.json`, so a Socket reference there reaches npm <= 11 only. The reference is still discovered, so `list`, `rollback` and `remove` manage it, but `vex` omits the patch (`vex_npm_shrinkwrap_only`, as a run warning and as the `failed[].reason`). A `package-lock.json` beside it (wired the same way) makes it attestable again. Hosted and vendored runs still rewire the shrinkwrap and warn `redirect_npm_shrinkwrap_only` / `vendor_npm_shrinkwrap_only`. * **Locks the package manager is told not to read.** A reference in a lock the project's own configuration turns off proves nothing about what installs. Read from the project's own rc file only (no user or global config, no environment): npm's `package-lock` or its alias `shrinkwrap` set to `false` / `null` in `.npmrc` (`npm install` then ignores `package-lock.json` and `npm-shrinkwrap.json` and resolves from the registry; only `npm ci` still installs from the lock; a `${VAR}` value counts as off); yarn 1's `--install.no-lockfile`, `--*.no-lockfile` or `--no-lockfile` in `.yarnrc` with any value but `false` (yarn neither reads nor writes `yarn.lock`, `--frozen-lockfile` included); a yarn berry `lockfileFilename` in `.yarnrc.yml` naming another file (yarn 2 and 3 read that file, yarn 4 rejects the setting and installs nothing); and pnpm's `lockfile` setting (**pnpm with its lockfile off** above). A hosted reference of such a lock keeps no lockfile basis: `vex` attests it only from an installed tree whose every copy verifies, and discovery warns `patched_ref_unattributable` naming the setting. A vendored reference stays a reference but is omitted (`vex_lock_not_read`, as a run warning and as the `failed[].reason`), because its basis is the committed artifact and nothing installs it through a lock nothing reads; the pnpm exception is an override that routes the package to the artifact. * **Lockless pins.** With no lock to name a version, a `Cargo.toml` pin (every declaration on `socket-patch-`, that registry defined on the patch host for the same uuid) or an exclusive nuget exact-id mapping is never a reference on its own, so v5.0 does not attest it (nor does `list` show it, or `rollback` / `remove` restore it — restore those files from version control). Only a pre-v5 redirect-ledger record naming a version the pin admits keeps it live. For Cargo, declarations are read as for a locked pin (**Unpinned Cargo declarations**): one that is no pin admits nothing, and its requirement (any version, without one) is excluded from the pin; a `[workspace.dependencies]` template no manifest inherits is no declaration at all. The same holds for a gem wired only in the `Gemfile` (the pre-bundler-2.6 mixed state, lock not converged). @@ -2318,7 +2318,10 @@ command's integration tests check its output. | `redirect_gem_version_not_locked` | `warnings[]` (warning) | scan `--mode hosted` (gem): the crawled gem version is installed on the machine but no `GEM` section of the project's lock resolves it (another project's copy in the shared gem home). The gem is skipped and the Gemfile and lock stay byte-identical. | | `redirect_maven_trusted_checksums_maven3_only` / `maven_trusted_checksums_maven3_only` | `warnings[]` (warning) | scan / get `--mode hosted` (the first code) and rollback / remove (the second), Maven: the Trusted Checksums settings hosted mode wrote into `.mvn/maven.config` named the checksums directory through `${session.rootDirectory}`, which stops Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the project, and this run respelled that line with `${maven.multiModuleProjectDirectory}` in a project that declares no Maven (no Maven Wrapper naming an Apache Maven release, a root pom of model 4.0.0). Maven 3.9.4 and later 3.x enforce the checksums as before; a Maven 4 build of the project no longer does. Reported once, by the run that changes the line. The remedy for a project Maven 4 builds: declare Maven 4 (a wrapper that pins it, or a root pom of model 4.1.0); the next hosted scan then writes the spelling Maven 4 reads. Status and exit code are unchanged. | | `redirect_maven_version_not_selected` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the build does not resolve the artifact at the patch's base version; the detail names the version Maven selects instead, or says that the build does not resolve the artifact. `pom.xml` and `.mvn/` stay byte-identical and the dep is not counted as redirected. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). | -| `redirect_maven_selection_undetermined` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): what the build selects for the artifact cannot be read and `pom.xml` declares no version of it to replace, so no `` pin is written on a guess. `pom.xml` and `.mvn/` stay byte-identical; the detail carries the reason and the remedy (resolve the project once and re-run, or declare the artifact at the base version). | +| `redirect_maven_selection_undetermined` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): what the build selects for the artifact cannot be read and `pom.xml` declares no version of it to replace, so no `` pin is written on a guess. `pom.xml` and `.mvn/` stay byte-identical; the detail carries the reason and the remedy (resolve the project once and re-run, or declare the artifact at the base version). In a reactor it names the first module whose selection cannot be read and counts the rest: those modules get no new pin, while the modules that are certain are still pinned and a declaration that names the base version is still rewritten, so the dep may be counted as redirected beside this warning. | +| `redirect_maven_multimodule_unsupported` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the root `pom.xml` heads a reactor that cannot be planned: a module pom is missing or not readable as a pom, a `` path is a property or leaves the project, or the grant serves the patched artifact under its original version (a same-GAV grant). The detail carries the reason. The poms and `.mvn/` stay byte-identical and the dep is not counted as redirected. A reactor that can be read is patched module by module: see [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). | +| `redirect_maven_pin_would_move_module` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven reactor): a parent pom resolves the base version itself above a module that resolves another version, so the parent takes no pin (Maven's management always reaches the children); the modules below it that select the base version are pinned. Also reported when a pin an earlier run wrote is taken out because a module it reaches now resolves another version, which the pin would hold back (the `redirect_maven_dep_management` edit has `action: "removed"`). Exit 0. | +| `redirect_maven_edit_not_reversible` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): a pom would take an edit that `rollback` could not undo byte for byte from the pom alone. A pin in a `` that holds no entry (which would be left changed or removed) leaves that one pom as it is: the modules it would have wired stay unpatched, and `vex` withholds the statement while one of them resolves the base version. Any other case (a `` section that would not come back as it was) refuses the whole plan for the patch: nothing is written and the dep is not counted as redirected. Exit 0. See [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). | | `redirect_gem_no_checksums_section` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock has no `CHECKSUMS` section (Bundler < 2.6 does not write one), so it cannot record the sha256 of the patched gems. They are redirected all the same (manifest and lock converged, frozen installs accept the pair) and pinned by source alone. Reported once per run, naming the gems; relock with Bundler ≥ 2.6 (`bundle lock --add-checksums`) and re-run to pin the checksums too. | | `redirect_gem_merged_lock_layout` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock was written by Bundler < 2.2 (`BUNDLED WITH`), which lists every gem source in ONE `GEM` section, so this run added the patch registry to that section's `remote:` lines. The pair installs with that Bundler, frozen / deployment mode included. Newer Bundlers deprecate such a section and from 2.5 on refuse the pair under frozen / deployment mode: if a newer Bundler installs the project, run `bundle lock` with it, commit the lock and re-run the hosted scan. Raised only by a run that wrote the lock. | | `redirect_gem_unrecognized_declaration` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the gem's declaration cannot take a `source:` option in place (the detail gives the reason). The gem is skipped and the manifest and lock stay byte-identical for it; write the declaration as one `gem "", …` call with literal arguments on a line of its own, or use `--mode vendored` / `--mode agent`. | @@ -3006,6 +3009,147 @@ not reach that resolves the base version, or whose selection cannot be told on the machine that runs `vex`, withholds the attestation, with the module named. `vendor --check` does not ask this. +### Hosted Maven reactors and property versions + +Hosted mode patches a multi-module reactor, and a declaration whose +`` is a `${property}`, with pom edits only. It plans both with the +reactor planner vendored mode uses, over every pom of the reactor (the modules +the root lists, theirs in turn, and each parent pom a module inherits from +inside the checkout; a single pom is a reactor of one), with the same +selection and the same placement: + +- A declaration that names the base version is rewritten where it stands, in + whichever pom holds it (`redirect_maven_dep_version`, `path` the pom). +- The `` pin goes in the highest pom whose modules all + resolve the artifact at the base version or not at all, down to one module's + own `pom.xml` (`redirect_maven_dep_management`, `redirect_maven_dep_management_added` + naming the pom). A module that resolves another version is never reached. A + module a declaration already wires has no say and needs no pin. The pin is + the entry vendored mode writes, with its comment: + `` on the line before the + ``. A single pom that hosted mode pins without the planner (no + `${property}` version) keeps the uncommented entry earlier releases wrote. +- The `` (`socket-patch-`) goes in the local root each wired + pom inherits from: the reactor root, or a module's own pom when its parent + is not in the checkout. It is absolute, so it resolves the same from the + root, from a module directory, and with `-f`. +- The Trusted Checksums files stay in the project root's `.mvn/`. Maven finds + that directory by walking up from the pom it is started on, so a build + started in a module directory or with `-f` reads it too. A module with a + `.mvn` of its own is reported (`redirect_maven_trusted_checksums_unenforced`): + a Maven started there reads that directory, not the root's, so the checksum + pin is not enforced for that build. The version suffix still is. + +A `${property}` version is wired in the least invasive way that `rollback` +can undo exactly from the pom: + +1. **The property's own value.** When the reactor's poms define the property + once, at top level, as the base version, and every `${name}` in every pom + of the reactor is the whole `` of a declaration of the patched + artifact, the value takes the patched version and the declarations keep + their text (`redirect_maven_property`, `key` the property name). No other + artifact reads it, so none is moved. Not taken when a profile, + `.mvn/maven.config` or the project model defines the name too. +2. **No declaration at all.** A version-less declaration that a parent pom or + a BOM manages through a property is not edited: the `` + pin overrides that management. +3. **The one declaration, with its text recorded.** Otherwise the declaration + takes the literal patched version, and a comment directly after the element + records the text it replaced: + `1.2-socket.0a1b2c3d` + (`redirect_maven_dep_version`, `original` the `${...}` text). The property + and every sibling that reads it are untouched. From then on that one + declaration no longer follows the property. A property no pom of the + checkout defines (a parent resolved from a repository does) is read from + what Maven selects: the declaration is rewritten only when every module + that reads it is certain to select the base version, and is otherwise left + as it is (`redirect_maven_dep_unpinned`). + +No ledger records these edits. Each says what it replaced by its own text: the +base version is the suffix's prefix, a pin is its commented entry (and the +section that held nothing else), a recorded declaration carries its comment. + +**A plan is written whole or not at all.** For each patch the planner plans the +declarations, the property, the pins and the `` together, then +holds the result to one rule before any file is written: + +- no pom names the patched version unless the `` that serves it is + declared in that pom's local root, and a declaration Maven always reads + resolves to it, so `list`, `vex`, `rollback` and `remove` find the patch and + every pom that carries part of it; +- `rollback`, run over the text about to be written, returns every pom the plan + is the first to wire to the bytes it has now. + +A plan that cannot keep the rule writes nothing, and the warning says why: + +- the only declaration of the version sits inside `` + (`redirect_maven_profile_dependency_unpatched`): Maven reads it only while + that profile is active, so nothing would be certain to resolve the patched + version and no rollback would find the edit. Beside a declaration Maven + always reads, a profile's one is rewritten with it; +- the pom that must declare the repository cannot take it + (`redirect_maven_pom_unreadable`); +- a pom could not be put back exactly, for instance a self-closed + `` that would be expanded + (`redirect_maven_edit_not_reversible`). A pin in a `` + that holds no entry is the one case handled pom by pom: that pom is left as + it is under the same code, and the rest of the plan stands. + +The same rule holds for what a later scan takes away. When the last pin of a +patch goes (`redirect_maven_pin_would_move_module`: the module it reached now +resolves another version) and no pom names the patched version any more, its +`` is removed (`redirect_maven_repository`, `action: "removed"`) +and its lines leave `.mvn/checksums/checksums.sha256`. An earlier patch's +repository and checksum lines go only once no pom of the reactor names that +patch's version, whether or not the scan changed that pom. + +`rollback` and `remove` read the reactor themselves and undo a patch in every +pom that carries part of it, whatever `list` showed, or in none: each pom +returns to its bytes before the scan, the `` goes from whichever +pom declares it, and the `.mvn/` lines and files hosted mode wrote are removed. +A pom that still names the patched version and can no longer be read as a pom +refuses the patch, with nothing changed. + +A reactor is read once per run, each pom fetched and parsed once, however many +modules it has. A module pom that is a symbolic link, or that cannot be opened, +counts as missing: the reactor is then refused +(`redirect_maven_multimodule_unsupported`), never the run. A pom of the reactor +that is there but is not UTF-8 text is not missing: its content is unknown, so +the scan refuses the run for it by name (`candidate_file_unreadable`, as for an +undecodable root `pom.xml`), `vex` and `list` report it as unreadable and attest +no pin of that reactor, and `rollback` / `remove` refuse every pin of it with +nothing changed, since that pom may hold part of one. A single pom that +inherits from a parent pom inside the checkout is read with that parent: a +property the parent defines is rewritten there, and the repository goes in the +parent the pom inherits it from. + +A later scan keeps every pin where an earlier one wrote it, so a second scan +changes nothing. It adds a pin only for a module that nothing reaches yet and +that is now certain to select the base version: a first scan over a cold Maven +local repository wires what it can tell (`redirect_maven_selection_undetermined` +names the rest), and the next one, once the project was resolved there, +completes it. A pin of an earlier patch of the same version moves to the new +suffix where it stands (its repository and checksum lines are replaced), and a +pin that now reaches a module resolving another version is taken out and +written where it belongs (`redirect_maven_pin_would_move_module`). + +`vex` attests a hosted patch in a reactor by the vendored rule above: every +module that resolves the base version, or may, is reached by a pin or a +declaration of the patch, and no declaration may still build the base version. +Otherwise the statement is withheld and the module named +(`vex_maven_reactor_root`). What each module selects is read from the Maven +local repository of the machine that runs `vex`. A reactor one of whose poms +cannot be read is read for the pins of the others: they are listed and can be +rolled back, and none is attested. + +A hosted pin an earlier release wrote in a single pom carries no comment. It +is still found, rolled back and removed as before. When that pom has since +come to head a reactor, the pin is kept as it is (no new pin is added, since +the patch is already wired), `vex` weighs it module by module like any other, +and `rollback` restores its version; an entry that release added to +`` is then left at the base version instead of removed, +since in a reactor it cannot be told from the project's own. + Where the pins go is decided when a patch is first wired, and the committed poms are the record of it. A later run over poms that already wire the patch (a pin of its version, or a declaration at its `-socket.` version) keeps @@ -3425,7 +3569,7 @@ match it, withholds the statement: | `vex_gradle_lock_above_base` | run warning and `failed[].reason` | A hosted pin is wired, but a lock file records a release above its base, which that build resolves instead of the patch; no statement until it is re-locked or the patch is rolled back. | | `vex_pnpm_bundled_copy` | run warning and `failed[].reason` | An npm pin is wired, but its pnpm lock names a package whose `bundledDependencies` may ship an unpatched copy of it (the lock does not record that copy's version); no statement while that package bundles it. `vendor --check` and `scan` still treat the wiring as live. | | `vex_deno_lock_copy` | run warning and `failed[].reason` | An npm pin is wired, but `deno.lock` locks the same `name@version`, which `deno install` installs without the wiring; no statement while it does. `vendor --check` and `scan` still treat the wiring as live. | -| `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven pin sits in a root `pom.xml` that declares `` / `` (a profile's included), where a module's own literal `` overrides it; only the root pom is read, so no statement (#261). `list`, `rollback` and `remove` still find the pin. | +| `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven patch is wired in a reactor (`` / ``, a profile's included, or Maven 4 subproject discovery) one of whose modules may build the unpatched version: it resolves the patched version, or its selection cannot be told on the machine that runs `vex`, and no pin or declaration of the patch reaches it; or a declaration may still build the base version; or a pom of the reactor cannot be read. No statement; the note names the module (#261). `list`, `rollback` and `remove` still find the wiring. | | `go_workspace_override` | run warning and `failed[].reason` | A hosted or vendored Go `replace` is wired, but the workspace go resolves (an ancestor's `go.work`, one `GOWORK` names, members outside the project included) overrides, ignores or rejects it, or go builds another `go.work` than the root's that holds it; no statement while it does. `list`, `rollback` and `remove` still find the replace. | | `vex_maven_classifier_unpatched` | run warning and `failed[].reason` | A hosted (or pre-v5 vendored) Maven pin's GA also has an executable `` copy (not `sources` / `javadoc`; live or inside ``) at a version other than the pin, which the classifier-less pin does not retarget and the grant does not serve; no statement while it does. `list`, `rollback` and `remove` still find the pin. | | `vex_maven_profile_unpatched` | run warning and `failed[].reason` | A Maven pin's GA main jar is also declared inside `` in the root `pom.xml` at a version other than the pin (a profile `` entry only where management governs the pin), or a profile's `` redefine a property the pin's `${property}` version names so it resolves another version, or a property a `${property}` groupId / artifactId names so the pin names another package or another declaration becomes the pinned GA off the pin, which overrides the pin whenever that profile is active; no statement while it does. `list`, `rollback` and `remove` still find the pin. | diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 51102707b4..77c0c571b4 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -1577,10 +1577,9 @@ async fn run_redirect_selected_untracked( // What Maven selects in each module, from the poms its local repository // holds: a pin is written only where that is the patch's base version. // Read once per run, off the runtime (the walk reads a pom per artifact - // of the build), and only for a pom the rewriter will edit. + // of the build), for a single pom and for every module of a reactor. let maven_selection_read = if candidates.iter().any(|c| c.dep.ecosystem == "maven") && read.files.contains_key("pom.xml") - && !socket_patch_core::patch::redirect::maven_reactor_root(&read.files) { let cwd = common.cwd.clone(); Some( diff --git a/crates/socket-patch-cli/src/commands/scan/hosted/takeover.rs b/crates/socket-patch-cli/src/commands/scan/hosted/takeover.rs index c1e2e7f84c..785126a270 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted/takeover.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted/takeover.rs @@ -188,7 +188,13 @@ impl Takeover { if let Some(refusal) = socket_patch_core::hosted::engine::undecodable_guard( &read.undecodable_reads, candidates, - ) { + ) + .or_else(|| { + socket_patch_core::hosted::engine::undecodable_maven_guard( + &read.undecodable_maven_poms, + candidates, + ) + }) { return Err(refusal); } } diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index af854e04c4..a269fbcf5b 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -326,8 +326,9 @@ fn unattested_note(kind: UnattestedKind) -> (&'static str, &'static str) { ), UnattestedKind::MavenReactorRoot => ( NOTE_MAVEN_REACTOR_ROOT, - "not attested while the root declares modules (roll it back and re-patch the \ - reactor with `scan --mode vendored`)", + "not attested while a module of the reactor may build the unpatched version \ + (re-run `scan` once that module resolves it, or patch the reactor with `scan \ + --mode vendored`)", ), UnattestedKind::MavenClassifierUnpatched => ( NOTE_MAVEN_CLASSIFIER_UNPATCHED, diff --git a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs index ab03bbb387..0c6606dc24 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs @@ -700,6 +700,8 @@ fn maven_scan_hosted_fresh_checkout_install_and_manifestless_vex() { // ── a pin follows the version Maven selects ───────────────────────────── mod mediation { + use std::collections::BTreeMap; + use super::maven_mediation_common::{self as fixture, Shape}; use super::*; @@ -906,4 +908,728 @@ mod mediation { // and no pom of this project names it: a range selects another. unselected(Shape::Ranged).expect("the local repository is warm"); } + /// What a hosted mediation test runs against: the fixture repository, + /// the patch API and the Socket repository of [`PATCH`] on one server, + /// a cold local repository, and Maven settings without and with the + /// Socket repository mirrored to that server. + struct Bench { + _tmp: tempfile::TempDir, + root: PathBuf, + m2: PathBuf, + plain: PathBuf, + mirrored: PathBuf, + server: Server, + patched_jar: Vec, + suffixed: String, + view: serde_json::Value, + } + + impl Bench { + fn new() -> Bench { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().canonicalize().unwrap(); + let plain = root.join("settings-plain.xml"); + write_settings(&plain, &[]); + let server = Server::start(); + fixture::publish(&server); + let patched_jar = fixture::patched_victim_jar(); + let suffixed = PATCH.suffixed(); + let served_pom = fixture::served_victim_pom(&suffixed).into_bytes(); + let view = patch_view( + UUID, + &fixture::purl(), + &[( + &fixture::victim_jar_name(fixture::BASE), + &git_sha256(&patched_jar), + )], + &[(PATCH.ghsa, &[PATCH.cve])], + ); + hosted_maven_common::mount_api(&server, &PATCH, &patched_jar, &served_pom, &view); + fixture::answer_lookups_only_for(&server, ORG, &fixture::purl()["pkg:maven/".len()..]); + server.serve_repo(&PATCH, &patched_jar, &served_pom, None); + let mirrored = root.join("settings-socket.xml"); + let mirror_url = format!("{}{}", server.uri(), PATCH.repo_path()); + write_settings(&mirrored, &[(&format!("socket-patch-{UUID}"), &mirror_url)]); + Bench { + m2: root.join("m2"), + _tmp: tmp, + root, + plain, + mirrored, + server, + patched_jar, + suffixed, + view, + } + } + + fn scan(&self, proj: &Path) -> (Option, serde_json::Value, String) { + socket( + proj, + &self.m2, + &[ + "scan", + "--mode", + "hosted", + "--json", + "--yes", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + &self.server.uri(), + "--org", + ORG, + "--api-token", + "fake", + ], + ) + } + + /// Roll the project back (Maven's restore needs no network), and + /// check that it is the hosted pin of the victim that went. + fn rollback(&self, proj: &Path) { + let (code, env, stderr) = socket( + proj, + &self.m2, + &[ + "rollback", + "--json", + "--offline", + "--cwd", + proj.to_str().unwrap(), + ], + ); + assert_eq!(code, Some(0), "rollback: {env}\n{stderr}"); + assert_eq!( + rollback_json::hosted_reverted(&env), + serde_json::json!([fixture::purl()]), + "rollback restores the hosted pin: {env}" + ); + } + + /// A second scan finds the wiring of the first and writes nothing. + fn assert_rescan_is_a_no_op(&self, proj: &Path) { + let pinned = fixture::snapshot(proj); + let (code, env, stderr) = self.scan(proj); + assert_eq!(code, Some(0), "rescan: {env}\n{stderr}"); + assert_eq!( + fixture::snapshot(proj), + pinned, + "a rescan is a no-op: {env}" + ); + } + + /// The invariant: `after` holds the artifacts of `before`, the + /// base victim in its patched build and every other jar as it was. + fn assert_only_the_victim_is_patched( + &self, + what: &str, + before: &BTreeMap>, + after: &BTreeMap>, + ) { + assert_eq!( + fixture::unsuffixed(after.keys()), + before.keys().cloned().collect(), + "{what}: the same artifacts, the victim in its patched build" + ); + assert_eq!( + after.get(&fixture::victim_jar_name(&self.suffixed)), + Some(&self.patched_jar), + "{what}: Maven resolves the patched jar: {:?}", + after.keys() + ); + for (name, bytes) in before { + if *name != fixture::victim_jar_name(fixture::BASE) { + assert_eq!(after.get(name), Some(bytes), "{what}: {name} is untouched"); + } + } + } + } + + /// A `${property}` version is patched in hosted mode, with pom edits + /// only, and no artifact that shares the property is moved: + /// + /// - a property only the patched artifact reads is rewritten itself; + /// - a property a sibling artifact reads too stays as it is, and the + /// one declaration takes the patched version, the text it replaced + /// recorded beside it; + /// - so does a declaration whose property a parent pom resolved from a + /// repository defines. + /// + /// In each, Maven resolves what it resolved before but for the patched + /// build of the victim, a second scan writes nothing, and a rollback + /// restores every file byte for byte and leaves none behind. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_patches_a_property_version_and_rolls_back_clean() { + use fixture::Property; + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let bench = Bench::new(); + let suffixed = &bench.suffixed; + for property in [Property::Own, Property::Shared, Property::OfParent] { + let what = property.name(); + let proj = bench.root.join(what); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("pom.xml"), + fixture::property_pom(property, &bench.server), + ) + .unwrap(); + let Some(before) = + fixture::resolve(SUITE, &mvn, &proj, &bench.m2, &bench.plain, "target/before") + else { + return; + }; + assert!( + before.contains_key(&fixture::victim_jar_name(fixture::BASE)), + "{what}: {:?}", + before.keys() + ); + let pristine = fixture::snapshot(&proj); + + let (code, env, stderr) = bench.scan(&proj); + assert_eq!(code, Some(0), "{what}: {env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{what}: {env}"); + let wired = std::fs::read_to_string(proj.join("pom.xml")).unwrap(); + let reference = property.reference(); + match property { + Property::Own => assert!( + wired.contains(&format!("{suffixed}")) + && wired.contains(&format!("{reference}")), + "the property takes the patched version, the declaration keeps its \ + text:\n{wired}" + ), + Property::Shared | Property::OfParent => assert!( + wired.contains(&format!( + "{suffixed}" + )), + "{what}: the declaration takes the patched version, and says what it \ + replaced:\n{wired}" + ), + } + if property == Property::Shared { + assert!( + wired.contains(&format!( + "{}", + fixture::BASE + )) && wired.contains(&fixture::dependency(fixture::SIBLING, &reference, "")), + "the property and the sibling that reads it are as they were:\n{wired}" + ); + } + assert!( + wired.contains(&format!("socket-patch-{UUID}")), + "{what}:\n{wired}" + ); + + let after = + fixture::resolve_warm(&mvn, &proj, &bench.m2, &bench.mirrored, "target/after", &[]); + bench.assert_only_the_victim_is_patched(what, &before, &after); + bench.assert_rescan_is_a_no_op(&proj); + + bench.rollback(&proj); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "{what}: rollback restores every file byte for byte and leaves none behind" + ); + } + } + + /// A multi-module reactor is patched in hosted mode module by module + /// (the table's V3): the module that reaches the base version through + /// another artifact gets the pin in its own pom, the module that + /// declares it has that declaration rewritten, and the module that + /// resolves a newer version is not touched and resolves what it + /// resolved before. The repository and the Trusted Checksums sit at + /// the root every module inherits, so a Maven started in a module + /// directory resolves the patched jar too. `vex` attests the patch + /// while every module that resolves the base version is wired, and + /// withholds it, naming the module, once one is not. A rollback + /// restores every pom byte for byte and removes what the scan created. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_patches_a_reactor_module_by_module_and_rolls_back_clean() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let bench = Bench::new(); + let suffixed = &bench.suffixed; + let proj = bench.root.join("reactor"); + fixture::write_reactor(&proj, &bench.server); + let Some(before) = + fixture::resolve_reactor(SUITE, &mvn, &proj, &bench.m2, &bench.plain, "target/before") + else { + return; + }; + let pristine = fixture::snapshot(&proj); + let was = |rel: &str| String::from_utf8(pristine[rel].clone()).unwrap(); + let now = |rel: &str| std::fs::read_to_string(proj.join(rel)).unwrap(); + + let (code, env, stderr) = bench.scan(&proj); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + assert!( + warning(&env, "redirect_maven_multimodule_unsupported").is_none(), + "{env}" + ); + let a = now("a/pom.xml"); + assert!( + a.contains(&format!( + "", + fixture::GROUP, + fixture::VICTIM, + fixture::BASE + )) && a.contains(&format!("{suffixed}")), + "a reaches the base version through another artifact, and is pinned:\n{a}" + ); + assert_eq!( + now("c/pom.xml"), + was("c/pom.xml").replace( + &format!("{}", fixture::BASE), + &format!("{suffixed}") + ), + "c declares the base version, and only that version text changes" + ); + assert_eq!( + now("b/pom.xml"), + was("b/pom.xml"), + "b resolves another version and is not touched" + ); + let root = now("pom.xml"); + assert!( + root.contains(&format!("socket-patch-{UUID}")) && !root.contains(suffixed), + "the root takes the repository every module inherits, and no pin:\n{root}" + ); + assert!(proj.join(".mvn/checksums/checksums.sha256").is_file()); + for module in ["a", "b", "c"] { + assert!( + !proj.join(module).join(".mvn").exists(), + "{module}: the Trusted Checksums are the root's" + ); + } + + let after = fixture::resolve_reactor( + SUITE, + &mvn, + &proj, + &bench.m2, + &bench.mirrored, + "target/after", + ) + .expect("the local repository is warm"); + for (module, selects, ..) in fixture::REACTOR_MODULES { + if selects == fixture::BASE { + bench.assert_only_the_victim_is_patched(module, &before[module], &after[module]); + } else { + assert_eq!( + after[module], before[module], + "{module} resolves what it resolved before" + ); + } + } + // Started in a module directory, Maven reads the parent pom for the + // repository and the root's `.mvn` for the checksums. + let from_module = fixture::resolve_warm( + &mvn, + &proj.join("a"), + &bench.m2, + &bench.mirrored, + "target/from-module", + &[], + ); + bench.assert_only_the_victim_is_patched( + "a, from its directory", + &before["a"], + &from_module, + ); + bench.assert_rescan_is_a_no_op(&proj); + + // VEX: attested while every module that resolves the base version + // is wired. + let api = PatchApi::start(vec![(UUID.to_string(), bench.view.clone())]); + let run = VexRun { + proxy_url: Some(api.uri()), + ..vex_run(&bench.m2) + }; + let out = run_vex(&binary(), &proj, &run); + assert_eq!(out.code, Some(0), "{out}"); + assert_attested( + out.doc(), + &fixture::purl(), + UUID, + Marker::Redirected, + &[(PATCH.ghsa, &[PATCH.cve])], + ); + // A module that comes to declare the base version itself builds the + // unpatched jar, whatever its siblings are wired to. + let wired_b = now("b/pom.xml"); + std::fs::write( + proj.join("b/pom.xml"), + fixture::module_pom("b", fixture::VICTIM, fixture::BASE), + ) + .unwrap(); + let out = run_vex(&binary(), &proj, &run); + assert_omitted( + &out, + &fixture::purl(), + "vex_maven_reactor_root", + "a module that builds the unpatched version", + ); + assert!( + out.envelope.to_string().contains("b/pom.xml"), + "the note names the module: {out}" + ); + std::fs::write(proj.join("b/pom.xml"), wired_b).unwrap(); + + bench.rollback(&proj); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "rollback restores every pom byte for byte and removes what the scan created" + ); + } + + /// A declaration Maven reads only while a profile is active is not + /// rewritten on its own: the scan would leave a version with no + /// repository to serve it, which a build with that profile could not + /// resolve and no rollback could find. The scan exits 0, says why, and + /// writes nothing; the build with the profile resolves what it did. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_leaves_a_declaration_only_a_profile_holds() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let bench = Bench::new(); + let proj = bench.root.join("profile-only"); + std::fs::create_dir_all(proj.join("a")).unwrap(); + std::fs::create_dir_all(proj.join("b")).unwrap(); + std::fs::write( + proj.join("pom.xml"), + fixture::reactor_root_pom(&["a", "b"], &bench.server), + ) + .unwrap(); + let profiled = fixture::module_pom("a", "lib-old", "1.0").replace( + "", + &format!( + " \n \n with-victim\n \ + \n{} \n \n \n", + fixture::dependency(fixture::VICTIM, fixture::BASE, "") + ), + ); + std::fs::write(proj.join("a/pom.xml"), profiled).unwrap(); + std::fs::write( + proj.join("b/pom.xml"), + fixture::module_pom("b", "lib-new", "1.0"), + ) + .unwrap(); + // Warm the local repository (the dependency plugin, and the base + // version the profile brings in). + if fixture::resolve( + SUITE, + &mvn, + &proj.join("b"), + &bench.m2, + &bench.plain, + "target/warm", + ) + .is_none() + { + return; + } + let with_profile = |out: &str| { + fixture::resolve_warm( + &mvn, + &proj.join("a"), + &bench.m2, + &bench.plain, + out, + &["-Pwith-victim"], + ) + }; + let before = with_profile("target/before"); + assert!( + before.contains_key(&fixture::victim_jar_name(fixture::BASE)), + "{:?}", + before.keys() + ); + let pristine = fixture::snapshot(&proj); + + let (code, env, stderr) = bench.scan(&proj); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "the scan writes nothing: {env}" + ); + assert!( + warning(&env, "redirect_maven_profile_dependency_unpatched").is_some(), + "the scan says why: {env}" + ); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + assert_eq!( + with_profile("target/after"), + before, + "the profile's build resolves what it did" + ); + } + + /// A single pom that inherits from a parent pom inside the checkout + /// (no ``), its version a property that parent defines: the + /// property and the repository are written in the parent's pom, where + /// `rollback` finds them. Maven resolves the patched jar, and the + /// rollback restores both poms byte for byte. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_patches_through_a_parent_pom_of_the_checkout() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let bench = Bench::new(); + let suffixed = &bench.suffixed; + let proj = bench.root.join("local-parent"); + std::fs::create_dir_all(proj.join("parent")).unwrap(); + let property = format!( + " \n {}\n \n", + fixture::BASE + ); + let child = fixture::property_pom(fixture::Property::Own, &bench.server) + .replace(&property, "") + .replace( + " com.example\n", + " \n com.example\n \ + base\n 1.0.0\n \ + parent/pom.xml\n \n \ + com.example\n", + ); + assert!(!child.contains(""), "{child}"); + std::fs::write(proj.join("pom.xml"), &child).unwrap(); + std::fs::write( + proj.join("parent/pom.xml"), + format!( + "\n\ + \n \ + 4.0.0\n com.example\n \ + base\n 1.0.0\n \ + pom\n{property}\n" + ), + ) + .unwrap(); + let Some(before) = + fixture::resolve(SUITE, &mvn, &proj, &bench.m2, &bench.plain, "target/before") + else { + return; + }; + let pristine = fixture::snapshot(&proj); + + let (code, env, stderr) = bench.scan(&proj); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + let parent = std::fs::read_to_string(proj.join("parent/pom.xml")).unwrap(); + assert!( + parent.contains(&format!("{suffixed}")) + && parent.contains(&format!("socket-patch-{UUID}")), + "the parent takes the property and the repository:\n{parent}" + ); + assert_eq!( + std::fs::read_to_string(proj.join("pom.xml")).unwrap(), + child, + "the pom that declares it keeps its text" + ); + let after = + fixture::resolve_warm(&mvn, &proj, &bench.m2, &bench.mirrored, "target/after", &[]); + bench.assert_only_the_victim_is_patched("a local parent", &before, &after); + bench.assert_rescan_is_a_no_op(&proj); + + bench.rollback(&proj); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "rollback restores both poms byte for byte and leaves no file behind" + ); + } + + /// A newer patch of the same version takes the place of an earlier + /// one only where the poms let it. A module that still reads the + /// earlier patch's version (through a property a profile may redefine, + /// which no scan rewrites) keeps resolving it: the earlier patch's + /// repository and checksum lines stay for as long as any pom of the + /// reactor names it, so Maven resolves both modules. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_keeps_an_earlier_patch_served_while_a_module_names_it() { + const NEWER_UUID: &str = "8192a3b4-c5d6-4e7f-8a9b-0c1d2e3f4a5b"; + const NEWER: Hosted = Hosted { + org: ORG, + uuid: NEWER_UUID, + hex8: "8192a3b4", + token: "44444444-5555-4666-8777-888888888888", + ghsa: "GHSA-mediation-maven-newer", + cve: "CVE-2026-7204", + group: fixture::GROUP, + artifact: fixture::VICTIM, + version: fixture::BASE, + title: "maven mediation capstone, superseding", + }; + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let bench = Bench::new(); + let earlier = &bench.suffixed; + let proj = bench.root.join("superseded"); + std::fs::create_dir_all(proj.join("a")).unwrap(); + std::fs::create_dir_all(proj.join("b")).unwrap(); + std::fs::write( + proj.join("pom.xml"), + fixture::reactor_root_pom(&["a", "b"], &bench.server), + ) + .unwrap(); + std::fs::write( + proj.join("a/pom.xml"), + fixture::module_pom("a", "lib-deep", "1.0"), + ) + .unwrap(); + let b = fixture::module_pom("b", fixture::VICTIM, "${victim.version}").replace( + " \n", + &format!( + " \n {}\n \n \ + \n", + fixture::BASE + ), + ); + std::fs::write(proj.join("b/pom.xml"), b).unwrap(); + let resolve_module = |module: &str, settings: &Path, out: &str| { + fixture::resolve_warm(&mvn, &proj.join(module), &bench.m2, settings, out, &[]) + }; + if fixture::resolve( + SUITE, + &mvn, + &proj.join("a"), + &bench.m2, + &bench.plain, + "target/before", + ) + .is_none() + { + return; + } + resolve_module("b", &bench.plain, "target/before"); + + // The earlier patch: both modules resolve its build. + let (code, env, stderr) = bench.scan(&proj); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + let read = |rel: &str| std::fs::read_to_string(proj.join(rel)).unwrap(); + assert!( + read("b/pom.xml").contains(&format!("{earlier}")), + "{}", + read("b/pom.xml") + ); + for module in ["a", "b"] { + let jars = resolve_module(module, &bench.mirrored, "target/earlier"); + assert!( + jars.contains_key(&fixture::victim_jar_name(earlier)), + "{module}: {:?}", + jars.keys() + ); + } + // b's property comes to be redefined by a profile: from here on no + // scan may rewrite it, since that profile's build keeps its own. + let profiled = read("b/pom.xml").replace( + "", + &format!( + " \n \n older\n \n \ + {}\n \n \n \ + \n", + fixture::OLDER + ), + ); + std::fs::write(proj.join("b/pom.xml"), &profiled).unwrap(); + + // The newer patch, from its own server. + let server = Server::start(); + let patched_jar = fixture::patched_victim_jar(); + let newer = NEWER.suffixed(); + let served_pom = fixture::served_victim_pom(&newer).into_bytes(); + let view = patch_view( + NEWER_UUID, + &fixture::purl(), + &[( + &fixture::victim_jar_name(fixture::BASE), + &git_sha256(&patched_jar), + )], + &[(NEWER.ghsa, &[NEWER.cve])], + ); + hosted_maven_common::mount_api(&server, &NEWER, &patched_jar, &served_pom, &view); + fixture::answer_lookups_only_for(&server, ORG, &fixture::purl()["pkg:maven/".len()..]); + server.serve_repo(&NEWER, &patched_jar, &served_pom, None); + let (code, env, stderr) = socket( + &proj, + &bench.m2, + &[ + "scan", + "--mode", + "hosted", + "--json", + "--yes", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + &server.uri(), + "--org", + ORG, + "--api-token", + "fake", + ], + ); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(read("b/pom.xml"), profiled, "b is left as it is: {env}"); + assert!( + read("a/pom.xml").contains(&newer) || read("pom.xml").contains(&newer), + "a moves to the newer patch: {env}" + ); + let root = read("pom.xml"); + assert!( + root.contains(&format!("socket-patch-{UUID}")) + && root.contains(&format!("socket-patch-{NEWER_UUID}")), + "both patches are still served: {root}" + ); + let sums = read(".mvn/checksums/checksums.sha256"); + assert!( + sums.contains(earlier.as_str()) && sums.contains(&newer), + "both patches keep their checksum lines:\n{sums}" + ); + + // Maven resolves both modules, each from the repository of the + // patch its pom names; the earlier one is fetched afresh. + let _ = std::fs::remove_dir_all(fixture::victim_dir(&bench.m2, earlier)); + let both = bench.root.join("settings-both.xml"); + write_settings( + &both, + &[ + ( + &format!("socket-patch-{UUID}"), + &format!("{}{}", bench.server.uri(), PATCH.repo_path()), + ), + ( + &format!("socket-patch-{NEWER_UUID}"), + &format!("{}{}", server.uri(), NEWER.repo_path()), + ), + ], + ); + let a = resolve_module("a", &both, "target/newer"); + assert!( + a.contains_key(&fixture::victim_jar_name(&newer)), + "a builds the newer patch: {:?}", + a.keys() + ); + let b = resolve_module("b", &both, "target/newer"); + assert!( + b.contains_key(&fixture::victim_jar_name(earlier)), + "b still builds the earlier patch, from its repository: {:?}", + b.keys() + ); + } } diff --git a/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs index 8a49bed794..19cf486a65 100644 --- a/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs +++ b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs @@ -14,6 +14,9 @@ //! `lib-range:1.0` → `victim:[1.10.5,1.11.0]`. //! * the artifact-level `maven-metadata.xml` of `victim`, which resolves //! the range. +//! * `sibling:1.10.0`, which shares the victim's base version (and so can +//! share a version property with it), and the parent poms `lib-parent` +//! and `lib-parent-props`, the latter defining [`PARENT_PROPERTY`]. //! //! One [`Shape`] per row of the bug: which version Maven selects for the //! victim, with the base version somewhere else in the graph (deeper, @@ -214,10 +217,11 @@ fn serve(server: &Server, rel: &str, bytes: &[u8]) { /// Serve the fixture repository from `server`. pub fn publish(server: &Server) { - let artifacts: [(&str, &str, &[(&str, &str)]); 8] = [ + let artifacts: [(&str, &str, &[(&str, &str)]); 9] = [ (VICTIM, OLDER, &[]), (VICTIM, BASE, &[]), (VICTIM, NEWER, &[]), + (SIBLING, BASE, &[]), ("lib-base", "1.0", &[(VICTIM, BASE)]), ("lib-new", "1.0", &[(VICTIM, NEWER)]), ("lib-old", "1.0", &[(VICTIM, OLDER)]), @@ -248,6 +252,20 @@ pub fn publish(server: &Server) { ) .as_bytes(), ); + // A parent pom that defines the version property its children read. + serve( + server, + &format!("{GROUP_PATH}/{PARENT_WITH_PROPERTY}/1.0/{PARENT_WITH_PROPERTY}-1.0.pom"), + fixture_pom(PARENT_WITH_PROPERTY, "1.0", &[]) + .replace( + "1.0\n", + &format!( + "1.0\n pom\n \n \ + <{PARENT_PROPERTY}>{BASE}\n \n" + ), + ) + .as_bytes(), + ); let versions: String = [OLDER, BASE, NEWER] .iter() .map(|v| format!(" {v}\n")) @@ -302,30 +320,33 @@ pub fn module_pom(name: &str, artifact: &str, version: &str) -> String { ) } +/// The root pom `com.example:parent:1.0.0` of a reactor over `modules`, +/// which every [`module_pom`] inherits: it names the fixture repository. +pub fn reactor_root_pom(modules: &[&str], server: &Server) -> String { + let modules: String = modules + .iter() + .map(|name| format!(" {name}\n")) + .collect(); + format!( + "\n\ + \n \ + 4.0.0\n com.example\n \ + parent\n 1.0.0\n \ + pom\n \n{modules} \n \ + \n \n fixture\n \ + {}{REPO_ROUTE}\n \n \n\n", + server.uri() + ) +} + /// Write a reactor into `dir` (the table's V3): a parent pom that three /// modules inherit, `a` reaching the base version two levels down, `b` a /// newer version through another artifact, `c` declaring the base version /// itself. pub fn write_reactor(dir: &Path, server: &Server) { - let modules: String = REACTOR_MODULES - .iter() - .map(|(name, ..)| format!(" {name}\n")) - .collect(); + let names: Vec<&str> = REACTOR_MODULES.iter().map(|(name, ..)| *name).collect(); std::fs::create_dir_all(dir).unwrap(); - std::fs::write( - dir.join("pom.xml"), - format!( - "\n\ - \n \ - 4.0.0\n com.example\n \ - parent\n 1.0.0\n \ - pom\n \n{modules} \n \ - \n \n fixture\n \ - {}{REPO_ROUTE}\n \n \n\n", - server.uri() - ), - ) - .unwrap(); + std::fs::write(dir.join("pom.xml"), reactor_root_pom(&names, server)).unwrap(); for (name, _, artifact, version) in REACTOR_MODULES { std::fs::create_dir_all(dir.join(name)).unwrap(); std::fs::write( @@ -369,6 +390,82 @@ pub fn resolve_reactor( /// A parent pom the fixture repository serves. pub const PARENT: &str = "lib-parent"; +/// A parent pom the fixture repository serves that defines +/// [`PARENT_PROPERTY`] as the victim's base version. +pub const PARENT_WITH_PROPERTY: &str = "lib-parent-props"; +pub const PARENT_PROPERTY: &str = "corp.victim.version"; +/// An artifact published at the victim's base version. +pub const SIBLING: &str = "sibling"; + +/// How a project names the victim's version through a property. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Property { + /// The project defines it, and only the victim's declaration reads it. + Own, + /// The project defines it, and [`SIBLING`] reads it too. + Shared, + /// A parent pom resolved from the repository defines it. + OfParent, +} + +impl Property { + pub fn name(self) -> &'static str { + match self { + Property::Own => "property-own", + Property::Shared => "property-shared", + Property::OfParent => "property-of-parent", + } + } + + /// The property the victim's `` reads. + pub fn reference(self) -> String { + match self { + Property::Own => "${victim.version}".to_string(), + Property::Shared => "${fixture.version}".to_string(), + Property::OfParent => format!("${{{PARENT_PROPERTY}}}"), + } + } +} + +/// The `pom.xml` of a project that declares the base victim through +/// `property`. +pub fn property_pom(property: Property, server: &Server) -> String { + let reference = property.reference(); + let pom = project_pom(Shape::Selected, server); + let own = |name: &str| { + format!( + " jar\n \n <{name}>{BASE}\n \ + \n" + ) + }; + let (head, dependencies) = match property { + Property::Own => ( + pom.replace(" jar\n", &own("victim.version")), + dependency(VICTIM, &reference, ""), + ), + Property::Shared => ( + pom.replace(" jar\n", &own("fixture.version")), + [ + dependency(VICTIM, &reference, ""), + dependency(SIBLING, &reference, ""), + ] + .concat(), + ), + Property::OfParent => ( + pom.replace( + " com.example\n", + &format!( + " \n {GROUP}\n \ + {PARENT_WITH_PROPERTY}\n \ + 1.0\n \n \n \ + com.example\n" + ), + ), + dependency(VICTIM, &reference, ""), + ), + }; + head.replace(&dependency("lib-deep", "1.0", ""), &dependencies) +} /// The `pom.xml` of a project that inherits [`PARENT`] from the repository /// and declares the base victim itself. @@ -530,16 +627,29 @@ pub fn plain_settings(path: &Path) { write_settings(path, &[]); } -/// Every file under `dir` (relative, forward slashes) with its bytes. +/// Maven 4's own output directory in a project: it keeps a project-local +/// repository there (`.mvn/target/project-local-repo`), written on every +/// build from the poms as they then read, a wired build's included. +const MAVEN_4_OUTPUT: &str = ".mvn/target"; + +/// Every file under `dir` (relative, forward slashes) with its bytes, but +/// what Maven itself writes under [`MAVEN_4_OUTPUT`]: that is neither the +/// project's nor socket-patch's, and it differs from one build to the next. pub fn snapshot(dir: &Path) -> BTreeMap> { fn walk(base: &Path, dir: &Path, out: &mut BTreeMap>) { for entry in std::fs::read_dir(dir).unwrap() { let path = entry.unwrap().path(); + let rel = path + .strip_prefix(base) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); if path.is_dir() { - walk(base, &path, out); + if rel != MAVEN_4_OUTPUT { + walk(base, &path, out); + } } else { - let rel = path.strip_prefix(base).unwrap().to_string_lossy(); - out.insert(rel.replace('\\', "/"), std::fs::read(&path).unwrap()); + out.insert(rel, std::fs::read(&path).unwrap()); } } } diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 4110117c2f..252e983601 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -619,6 +619,12 @@ pub struct CandidateFiles { /// are left out of `files`; a project whose candidates could rewrite /// one is refused rather than read as if the file were absent. pub undecodable_reads: Vec, + /// Poms of the Maven reactor (a module's, or a parent's inside the + /// checkout, whatever the file is called) that exist but are not UTF-8 + /// text. A Maven candidate could rewrite any of them, so the run is + /// refused like for [`Self::undecodable_reads`], never planned as if + /// the pom were missing. + pub undecodable_maven_poms: Vec, /// Gradle build files the script graph reached that exist but cannot be /// read as text (any view): the hosted Gradle planner refuses the build /// instead of taking them for absent (and creating a settings file over @@ -735,21 +741,98 @@ async fn read_advisory( unreadable: &BTreeSet, rel: &str, ) -> Option { + read_pom_text(view, unreadable, rel).await.ok().flatten() +} + +/// The file `rel` is there, but is not UTF-8 text. +struct Undecodable; + +/// [`read_advisory`] that tells a file which is there but is not UTF-8 +/// text (`Err`) from one that is missing, linked or not readable at all +/// (`Ok(None)`): the first is a file whose content this run does not know, +/// and must never be taken for an absent one. +async fn read_pom_text( + view: &ProjectView<'_>, + unreadable: &BTreeSet, + rel: &str, +) -> Result, Undecodable> { match view { - ProjectView::Disk(_) | ProjectView::Snapshot(_) => view.read_text(rel).await.ok(), + ProjectView::Disk(_) | ProjectView::Snapshot(_) => match view.read_text(rel).await { + Ok(text) => Ok(Some(text)), + Err(e) if e.kind() == std::io::ErrorKind::InvalidData => Err(Undecodable), + Err(_) => Ok(None), + }, ProjectView::Memory(project) if !project.is_symlink(rel) && !unreadable.contains(rel) => { match project.get(rel) { - Some(MemoryEntry::Text(text)) => Some(text.to_string()), - Some(MemoryEntry::Binary(bytes)) => { - std::str::from_utf8(bytes).ok().map(str::to_string) - } - _ => None, + Some(MemoryEntry::Text(text)) => Ok(Some(text.to_string())), + Some(MemoryEntry::Binary(bytes)) => std::str::from_utf8(bytes) + .map(|text| Some(text.to_string())) + .map_err(|_| Undecodable), + _ => Ok(None), } } - ProjectView::Memory(_) => None, + ProjectView::Memory(_) => Ok(None), } } +/// Read every file the Maven reactor planner reads for the root `pom.xml` +/// ([`read_reactor`](crate::vendor::jvm::maven_reactor::read_reactor), the +/// reader discovery and restore share, so each finds what the others +/// wrote): every pom is fetched and parsed once, however many modules. +/// +/// They are advisory input: a module pom that is a symbolic link, or that +/// cannot be opened, is left out, and the planner then finds the reactor +/// incomplete and refuses it with nothing written. That is what a reactor +/// got before module poms were read at all; it never fails the run, as an +/// unreadable root candidate does. A pom that is there but is not UTF-8 +/// text is another matter: its content is unknown, not absent, so it is +/// recorded ([`CandidateFiles::undecodable_maven_poms`]) and the guard +/// refuses the run for it, as for an undecodable root pom. +async fn read_maven_reactor( + view: &ProjectView<'_>, + unreadable: &BTreeSet, + out: &mut CandidateFiles, +) { + let Some(root) = out.files.get("pom.xml") else { + return; + }; + let config = out.files.get(crate::patch::redirect::MVN_CONFIG); + // A pom that is there but is not UTF-8 text is not a missing module: + // its content is unknown, so it is recorded like any other undecodable + // candidate and the run is refused for it (`candidate_file_unreadable`), + // instead of the reactor being reported as short of a pom it has. + let undecodable = std::sync::Mutex::new(Vec::new()); + let read = crate::vendor::jvm::maven_reactor::read_reactor( + view, + root, + config.map(String::as_str), + |rel| { + let undecodable = &undecodable; + async move { + match read_pom_text(view, unreadable, &rel).await { + Ok(text) => text, + Err(Undecodable) => { + undecodable + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(rel); + None + } + } + } + }, + ) + .await; + for (rel, text) in read { + out.files.entry(rel).or_insert(text); + } + let mut undecodable = undecodable + .into_inner() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + undecodable.sort(); + out.undecodable_maven_poms = undecodable; +} + /// An in-memory project's Go files as the hosted engine reads them /// ([`read_advisory`]: a link or an entry without content is unreadable, /// but still exists). @@ -1072,25 +1155,12 @@ pub async fn read_candidate_files( read_go_workspace(view, unreadable, &mut out).await; } - // A Maven 4 root that discovers its subprojects (#1809): each direct - // subdirectory holding a `pom.xml` is a module, which the pom rewriter - // must see to refuse the root as a reactor (it pins only the root pom). - // Advisory: keyed `/pom.xml`, never rewritten, and one that cannot - // be read still counts as present. + // Every pom of a Maven reactor (the modules the root lists, theirs in + // turn, each parent pom one inherits from inside the checkout, and the + // subprojects Maven 4 discovers, #1809): the rewriter pins a patch in + // the poms of the modules that select it. if candidates.iter().any(|c| c.dep.ecosystem == "maven") { - if let Some(pom) = out.files.get("pom.xml") { - let config = out.files.get(crate::patch::redirect::MVN_CONFIG); - if crate::vendor::jvm::maven_reactor::may_discover_subprojects( - pom, - config.map(String::as_str), - ) { - for dir in crate::vendor::jvm::maven_reactor::implicit_subprojects_in(view).await { - let rel = format!("{dir}/pom.xml"); - let text = read_advisory(view, unreadable, &rel).await; - out.files.insert(rel, text.unwrap_or_default()); - } - } - } + read_maven_reactor(view, unreadable, &mut out).await; } // NuGet merges the user config and every parent directory's config @@ -2063,6 +2133,8 @@ pub struct Rewritten { pub symlinked_reads: Vec, pub unreadable_reads: Vec, pub undecodable_reads: Vec, + /// [`CandidateFiles::undecodable_maven_poms`]. + pub undecodable_maven_poms: Vec, /// The rewriters' override slice (the candidates' deps). pub overrides: Vec, pub rewrite: RewriteResult, @@ -2703,6 +2775,7 @@ async fn rewrite_once( symlinked_reads, unreadable_reads, undecodable_reads, + undecodable_maven_poms, gradle_unreadable, gem_refusal, pnpm_refusal, @@ -2751,11 +2824,9 @@ async fn rewrite_once( } else { CratesIoSource::Registry }; - // Asked only for a pom the rewriter will edit: it refuses a reactor - // root whole, whatever Maven selects there. + // Asked only when there is a pom to pin: a single one, or a reactor's. let maven_selection = (rewrite_overrides.iter().any(|o| o.ecosystem == "maven") - && files.contains_key("pom.xml") - && !crate::patch::redirect::maven_reactor_root(&files)) + && files.contains_key("pom.xml")) .then(|| (options.maven_selection)()) .flatten(); let (files, mut rewrite) = if options.blocking { @@ -2987,6 +3058,7 @@ async fn rewrite_once( symlinked_reads, unreadable_reads, undecodable_reads, + undecodable_maven_poms, overrides, rewrite, rewritten, @@ -3867,6 +3939,11 @@ fn confirm( if !gradle || !files.contains_key("pom.xml") { return ProbeStep::Decided(gradle); } + if rewrite.maven_reactor_uuids.contains(uuid) { + return ProbeStep::Decided( + rewrite.confirmed_maven_reactor_uuids.contains(uuid), + ); + } let needles = candidate_presence_needles(&c.dep); return ProbeStep::Decided( final_texts @@ -3875,6 +3952,12 @@ fn confirm( .any(|(_, text)| needles.iter().any(|n| text.contains(n.as_str()))), ); } + // A dep the Maven reactor planner decided: its pin may sit in a + // module pom, a property or a comment-recorded declaration, so + // the planner's own report confirms it. + if rewrite.maven_reactor_uuids.contains(uuid) { + return ProbeStep::Decided(rewrite.confirmed_maven_reactor_uuids.contains(uuid)); + } ProbeStep::Needles(candidate_presence_needles(&c.dep)) }) .collect(); @@ -3964,6 +4047,17 @@ pub fn undecodable_guard(undecodable: &[String], candidates: &[Candidate]) -> Op .map(|rel| undecodable_refusal(rel)) } +/// The non-UTF-8 rule for the poms of a Maven reactor +/// ([`CandidateFiles::undecodable_maven_poms`]): with a Maven candidate, +/// the first of them refuses the run, as an undecodable root `pom.xml` +/// does. A module's pom may be a file of any name, so these are judged by +/// what read them, not by their name. +pub fn undecodable_maven_guard(poms: &[String], candidates: &[Candidate]) -> Option { + poms.first() + .filter(|_| candidates.iter().any(|c| c.dep.ecosystem == "maven")) + .map(|rel| undecodable_refusal(rel)) +} + /// SYMLINK GUARD — fail-closed, whole rewrite, before any write (hosted /// rewrites are transactional). The writer stages next to /// the path and renames over it, which REPLACES a symbolic link with a @@ -3998,6 +4092,9 @@ pub fn guard( if let Some(refusal) = undecodable_guard(&done.undecodable_reads, candidates) { return Some(refusal); } + if let Some(refusal) = undecodable_maven_guard(&done.undecodable_maven_poms, candidates) { + return Some(refusal); + } let candidate_ecosystems: BTreeSet<&str> = candidates .iter() .map(|c| c.dep.ecosystem.as_str()) @@ -6455,21 +6552,24 @@ snapshots: /// #1809: a Maven 4 root whose subprojects Maven discovers (model /// 4.1.0, `pom` packaging, no list) is a reactor once a direct /// subdirectory holds a `pom.xml`. The engine reads that pom beside - /// the root, on disk and in memory, so the pom rewriter refuses the - /// root instead of pinning only it while the module keeps its version. + /// the root, on disk and in memory, so the pom rewriter plans both: a + /// subproject that declares the version itself is not left behind. #[tokio::test] - async fn a_maven_4_implicit_reactor_root_is_refused() { + async fn a_maven_4_implicit_reactor_is_read_and_planned_whole() { let root = "\n 4.1.0\n x\n y\n 1\n pom\n \n \n com.socketfixture\n victim\n 1.10.0\n \n \n\n"; let child = "\n 4.1.0\n \n a\n\n"; - let refused = |read: &CandidateFiles, done: &Rewritten| { + let planned = |read: &CandidateFiles, done: &Rewritten| { assert!( read.files.contains_key("a/pom.xml"), "{:?}", read.files.keys() ); - assert!(!done.rewrite.files.contains_key("pom.xml")); - assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); - assert!(done + assert!( + done.rewrite.files["pom.xml"].contains("1.10.0-socket.4d5e6f70") + ); + assert!(done.rewrite.files["pom.xml"].contains("socket-patch-")); + assert_eq!(done.confirmed.len(), 1, "{:?}", done.rewrite.warnings); + assert!(!done .rewrite .warnings .iter() @@ -6480,7 +6580,21 @@ snapshots: p.insert_text("pom.xml", root); p.insert_text("a/pom.xml", child); let (read, done) = gradle_rewrite(&p).await; - refused(&read, &done); + planned(&read, &done); + assert!(!done.rewrite.files.contains_key("a/pom.xml")); + + // A subproject that declares the version itself is rewritten too. + let declaring = child.replace( + "", + "\n \n \n com.socketfixture\n victim\n 1.10.0\n \n ", + ); + let mut p = MemoryProject::new(); + p.insert_text("pom.xml", root); + p.insert_text("a/pom.xml", declaring.as_str()); + let (read, done) = gradle_rewrite(&p).await; + planned(&read, &done); + assert!(done.rewrite.files["a/pom.xml"].contains("1.10.0-socket.4d5e6f70")); + assert!(!done.rewrite.files["a/pom.xml"].contains("")); let tmp = tempfile::tempdir().unwrap(); std::fs::write(tmp.path().join("pom.xml"), root).unwrap(); @@ -6489,22 +6603,25 @@ snapshots: // A directory without a pom is no subproject. std::fs::create_dir(tmp.path().join("src")).unwrap(); let (read, done) = gradle_rewrite_in(&ProjectView::Disk(tmp.path())).await; - refused(&read, &done); + planned(&read, &done); assert!(!read.files.contains_key("src/pom.xml")); - // A suffixed version an earlier release pinned into the root, or one - // a module names, confirms nothing: the refused root pins nothing. + // A reactor one of whose poms cannot be read is refused whole, and + // a suffixed version an earlier run left in it then confirms + // nothing: the refused root pins nothing. let stale = root.replace("1.10.0", "1.10.0-socket.4d5e6f70"); - let named = child.replace( - "", - "\n 1.10.0-socket.4d5e6f70", - ); - for (r, c) in [(stale.as_str(), child), (root, named.as_str())] { + for r in [root, stale.as_str()] { let mut p = MemoryProject::new(); p.insert_text("pom.xml", r); - p.insert_text("a/pom.xml", c); - let (read, done) = gradle_rewrite(&p).await; - refused(&read, &done); + p.insert_text("a/pom.xml", ""); + let (_, done) = gradle_rewrite(&p).await; + assert!(done.rewrite.files.is_empty(), "{:?}", done.rewrite.files); + assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); + assert!(done + .rewrite + .warnings + .iter() + .any(|w| w.code == "redirect_maven_multimodule_unsupported")); } // Without a subproject the root is a single pom, pinned as before. @@ -6515,6 +6632,140 @@ snapshots: assert_eq!(done.confirmed.len(), 1); } + /// A reactor of hundreds of modules is read and planned whole: every + /// module pom is a candidate file, and each one that declares the + /// version is rewritten. (The reader learned one module per round, and + /// stopped after 64.) + #[tokio::test] + async fn a_reactor_of_hundreds_of_modules_is_read_and_planned_whole() { + let declaring = " \n \n com.socketfixture\n victim\n 1.10.0\n \n \n"; + let names: Vec = (0..200).map(|n| format!("module-{n}")).collect(); + let listed: String = names + .iter() + .map(|name| format!(" {name}\n")) + .collect(); + let mut p = MemoryProject::new(); + p.insert_text( + "pom.xml", + format!( + "\n 4.0.0\n x\n y\n 1\n pom\n \n{listed} \n\n" + ) + .as_str(), + ); + for name in &names { + p.insert_text( + format!("{name}/pom.xml"), + format!( + "\n 4.0.0\n \n x\n y\n 1\n \n {name}\n{declaring}\n" + ) + .as_str(), + ); + } + let (read, done) = gradle_rewrite(&p).await; + for name in &names { + let rel = format!("{name}/pom.xml"); + assert!(read.files.contains_key(&rel), "{rel} was not read"); + assert!( + done.rewrite.files[&rel].contains("1.10.0-socket.4d5e6f70"), + "{rel} was not rewritten: {:?}", + done.rewrite.warnings + ); + } + assert!(done.rewrite.files["pom.xml"].contains("socket-patch-")); + assert_eq!(done.confirmed.len(), 1, "{:?}", done.rewrite.warnings); + } + + /// A module pom that is a symbolic link, or that is there without + /// readable content, is no reason to fail the run: the reactor is left + /// as it is, with the reason, as every reactor was before module poms + /// were read. The guard that refuses a linked or unreadable rewrite + /// target has nothing to refuse. A module pom that is there but is not + /// UTF-8 text is refused by name instead: it must never look absent. + #[tokio::test] + async fn a_reactor_with_an_unreadable_module_pom_is_left_alone_not_failed() { + let root = "\n 4.0.0\n x\n y\n 1\n pom\n \n a\n \n \n \n com.socketfixture\n victim\n 1.10.0\n \n \n\n"; + let left_alone = |view: &ProjectView<'_>, read: &CandidateFiles, done: &Rewritten| { + assert!( + read.symlinked_reads.is_empty() + && read.unreadable_reads.is_empty() + && read.undecodable_reads.is_empty(), + "{read:?}" + ); + assert!(done.rewrite.files.is_empty(), "{:?}", done.rewrite.files); + assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); + assert!(done + .rewrite + .warnings + .iter() + .any(|w| w.code == "redirect_maven_multimodule_unsupported")); + assert!(guard(view, done, &[gradle_candidate()]).is_none()); + }; + for entry in [MemoryEntry::Symlink, MemoryEntry::Present] { + let mut p = MemoryProject::new(); + p.insert_text("pom.xml", root); + p.insert("a/pom.xml", entry); + let view = ProjectView::Memory(&p); + let (read, done) = gradle_rewrite_in(&view).await; + left_alone(&view, &read, &done); + } + + // A pom that is there but is not UTF-8 text is not a missing one: + // its content is unknown, so the run is refused for it by name, + // as for an undecodable root pom, with nothing written. On disk and + // in memory alike. + let undecodable = |view: &ProjectView<'_>, read: &CandidateFiles, done: &Rewritten| { + assert_eq!(read.undecodable_maven_poms, ["a/pom.xml"]); + assert!(done.rewrite.files.is_empty(), "{:?}", done.rewrite.files); + assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); + let refusal = guard(view, done, &[gradle_candidate()]).expect("refused"); + assert_eq!(refusal.code, UNREADABLE_REFUSAL); + assert!(refusal.message.contains("a/pom.xml"), "{}", refusal.message); + }; + let mut p = MemoryProject::new(); + p.insert_text("pom.xml", root); + p.insert( + "a/pom.xml", + MemoryEntry::Binary(vec![0xff, 0xfe, 0x00].into()), + ); + let view = ProjectView::Memory(&p); + let (read, done) = gradle_rewrite_in(&view).await; + undecodable(&view, &read, &done); + + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join("pom.xml"), root).unwrap(); + std::fs::create_dir(tmp.path().join("a")).unwrap(); + std::fs::write(tmp.path().join("a/pom.xml"), [0xff, 0xfe, 0x00]).unwrap(); + let view = ProjectView::Disk(tmp.path()); + let (read, done) = gradle_rewrite_in(&view).await; + undecodable(&view, &read, &done); + // A module pom of another name is one too. + std::fs::write( + tmp.path().join("pom.xml"), + root.replace("a", "a/build.xml"), + ) + .unwrap(); + std::fs::rename(tmp.path().join("a/pom.xml"), tmp.path().join("a/build.xml")).unwrap(); + let (read, done) = gradle_rewrite_in(&view).await; + assert_eq!(read.undecodable_maven_poms, ["a/build.xml"]); + assert!(guard(&view, &done, &[gradle_candidate()]).is_some()); + std::fs::rename(tmp.path().join("a/build.xml"), tmp.path().join("a/pom.xml")).unwrap(); + std::fs::write(tmp.path().join("pom.xml"), root).unwrap(); + // A link, to a pom that would otherwise be planned. + #[cfg(unix)] + { + std::fs::remove_file(tmp.path().join("a/pom.xml")).unwrap(); + std::fs::write( + tmp.path().join("real.xml"), + "\n 4.0.0\n \n x\n y\n 1\n \n a\n\n", + ) + .unwrap(); + std::os::unix::fs::symlink(tmp.path().join("real.xml"), tmp.path().join("a/pom.xml")) + .unwrap(); + let (read, done) = gradle_rewrite_in(&view).await; + left_alone(&view, &read, &done); + } + } + /// An sbt build beside a Gradle build: the Gradle planner pinning a /// uuid the sbt rewriter refused (here: no resolution evidence) does /// not confirm it — the sbt build still loads the upstream artifact. diff --git a/crates/socket-patch-core/src/hosted/memory/mod.rs b/crates/socket-patch-core/src/hosted/memory/mod.rs index 8d3cd30ef6..e0a78a8dd5 100644 --- a/crates/socket-patch-core/src/hosted/memory/mod.rs +++ b/crates/socket-patch-core/src/hosted/memory/mod.rs @@ -1610,6 +1610,7 @@ mod tests { symlinked_reads: Vec::new(), unreadable_reads: Vec::new(), undecodable_reads: Vec::new(), + undecodable_maven_poms: Vec::new(), overrides: Vec::new(), rewrite, rewritten: files.iter().map(|(rel, _)| (*rel).to_string()).collect(), diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 4a8a047429..4ef0d489de 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -411,6 +411,22 @@ pub struct RewriteResult { serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") )] pub refused_gradle_uuids: std::collections::BTreeSet, + /// Maven patch uuids the reactor planner decided (a reactor root, or a + /// single pom's `${property}` version): their pins may sit in module + /// poms, a property or a comment-recorded declaration, so the pom + /// rewriter's own report confirms them, never a substring. + #[cfg_attr( + test, + serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") + )] + pub maven_reactor_uuids: std::collections::BTreeSet, + /// Those of [`Self::maven_reactor_uuids`] some pom wires once the + /// rewrite is written (by this run, or already). + #[cfg_attr( + test, + serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") + )] + pub confirmed_maven_reactor_uuids: std::collections::BTreeSet, /// Patch uuids pinned in `socket-patch.sbt` and verified against the /// build's resolution evidence (kept or added by this run). On a pure /// sbt root ([`sbt::owns_maven_root`]) maven confirmation keys off this @@ -857,6 +873,8 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { gradle_uuids, confirmed_gradle_uuids, refused_gradle_uuids, + maven_reactor_uuids, + confirmed_maven_reactor_uuids, confirmed_sbt_uuids, refused_sbt_uuids, } = delta; @@ -901,6 +919,10 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { result.gradle_uuids.extend(gradle_uuids); result.confirmed_gradle_uuids.extend(confirmed_gradle_uuids); result.refused_gradle_uuids.extend(refused_gradle_uuids); + result.maven_reactor_uuids.extend(maven_reactor_uuids); + result + .confirmed_maven_reactor_uuids + .extend(confirmed_maven_reactor_uuids); result.bundled_skipped_uuids.extend(bundled_skipped_uuids); for (uuid, keys) in alias_skipped_entries { result @@ -9039,30 +9061,14 @@ fn rewrite_maven_pom( return; } let mut pom = files.get("pom.xml").cloned(); - // A reactor root: this rewriter reads only the root pom, and a module's - // own literal `` beats any pin written here, so that module - // would keep the unpatched upstream jar while the dep counts as - // redirected and VEX attests it (#261). Refuse the whole root, untouched; - // vendored mode's reactor planner rewrites each module's declaration. - // Maven 4 subprojects found by discovery count too (#1809): the engine - // reads each direct subdirectory's `pom.xml` beside such a root. - if pom.is_some() && maven_reactor_root(files) { - let gas: Vec = maven - .iter() - .map(|dep| match &dep.namespace { - Some(ns) => format!("{ns}:{}", dep.name), - None => dep.name.clone(), - }) - .collect(); - result.warnings.push(RewriteWarning { - code: "redirect_maven_multimodule_unsupported".into(), - detail: format!( - "pom.xml heads a multi-module reactor (/, or Maven 4 subproject discovery); hosted mode reads only the root pom, so a module's own of {} would stay unpatched. pom.xml and .mvn/ were left as they are and the dep is not counted as redirected; use `scan --mode vendored`, which pins each module's declaration", - gas.join(", ") - ), - }); - return; - } + // A reactor root (`` / ``, or Maven 4 subproject + // discovery, #1809) is planned over all of its poms by the reactor + // planner ([`plan_maven_reactor`]): a module's own `` beats any + // pin in the root pom (#261), so the pins go where each module selects + // the patched version. A single pom is rewritten below, and hands a + // `${property}` version to the same planner. + let reactor_root = pom.is_some() && maven_reactor_root(files); + let mut planner = MavenReactorRewrite::default(); let mut pom_changed = false; // The hosted generations whose `socket-patch-` repository the pom // declared before this run: only a suffixed literal one of these minted @@ -9194,6 +9200,61 @@ fn rewrite_maven_pom( continue; } }; + if reactor_root { + // (Every dep of a reactor is the planner's: the root's index + // is read once, to tell a pom that is not one.) + let _ = idx; + let planned = planner.plan( + files, + pom_text, + ReactorDep { + dep, + group_id: &group_id, + artifact_id: &artifact_id, + suffixed: suffixed_version.as_deref(), + repo_id: &repo_id, + index_url: &ov.index_url, + checksums: checksum_hashes.is_some(), + reactor_root, + refusal: "redirect_maven_multimodule_unsupported", + }, + selection, + &user_properties, + result, + ); + pom_changed |= files.get("pom.xml") != Some(&*pom_text); + let (Some(run), Some(suffixed)) = (planned, suffixed_version.as_deref()) else { + continue; + }; + if checksum_hashes.is_some() && run.wired { + pinned_jar_paths.push(crate::vendor::jvm::layout::artifact_path( + &group_id, + &artifact_id, + suffixed, + None, + "jar", + )); + } + checksum_drops.extend(run.drops); + if run.landed { + pin_maven_checksums( + files, + (&group_id, &artifact_id, suffixed), + checksum_hashes.as_ref(), + bad_checksum_hashes, + &mut MavenChecksumSettings { + config: &mut mvn_config, + changed: &mut mvn_config_changed, + basedir, + declared: &declared, + conflicts: &mut mvn_conflicts, + }, + &mut checksum_entries, + result, + ); + } + continue; + } // A `` pin makes every occurrence of the GA // one version, so it is safe only where Maven selects the patch's // base version already. A build that selects another version (or @@ -9519,20 +9580,67 @@ fn rewrite_maven_pom( continue; } - // A `${property}` version on any match: refuse this dep entirely. - // Editing the literal would break the property reference, and a depMgmt - // pin could strand sibling artifacts sharing the property. - if let Some(prop) = matches + // A `${property}` version on any match: the reactor planner wires + // it (this pom is a reactor of one). It rewrites the property's own + // value when nothing else reads that property, so no sibling + // artifact is stranded; else it replaces the one declaration and + // records the text it replaced beside it. + if matches .iter() - .find(|m| m.version_text.as_deref().is_some_and(|v| v.contains("${"))) + .any(|m| m.version_text.as_deref().is_some_and(|v| v.contains("${"))) { - result.warnings.push(RewriteWarning { - code: "redirect_maven_dep_unpinned".into(), - detail: format!( - "{group_id}:{artifact_id} is a property placeholder ({}); refusing to pin the suffixed version (a property edit could strand sibling artifacts)", - prop.version_text.as_deref().unwrap_or_default() - ), - }); + let planned = planner.plan( + files, + pom_text, + ReactorDep { + dep, + group_id: &group_id, + artifact_id: &artifact_id, + suffixed: Some(&suffixed_version), + repo_id: &repo_id, + index_url: &ov.index_url, + checksums: checksum_hashes.is_some(), + reactor_root, + refusal: "redirect_maven_dep_unpinned", + }, + selection, + &user_properties, + result, + ); + pom_changed |= files.get("pom.xml") != Some(&*pom_text); + index = pom + .as_deref() + .map(|pom| maven_index::PomIndex::build(pom, &user_properties)); + let Some(run) = planned else { + continue; + }; + if checksum_hashes.is_some() && run.wired { + pinned_jar_paths.push(crate::vendor::jvm::layout::artifact_path( + &group_id, + &artifact_id, + &suffixed_version, + None, + "jar", + )); + } + checksum_drops.extend(run.drops); + if run.landed { + pin_maven_checksums( + files, + (&group_id, &artifact_id, &suffixed_version), + checksum_hashes.as_ref(), + bad_checksum_hashes, + &mut MavenChecksumSettings { + config: &mut mvn_config, + changed: &mut mvn_config_changed, + basedir, + declared: &declared, + conflicts: &mut mvn_conflicts, + }, + &mut checksum_entries, + result, + ); + } continue; } @@ -9736,71 +9844,21 @@ fn rewrite_maven_pom( }); } - // Trusted Checksums: only when BOTH the jar sha256 and the served pom - // sha256 are known. Two entries per dep — the jar and the pom — under - // the SUFFIXED version's local-repo path. - if bad_checksum_hashes { - result.warnings.push(RewriteWarning { - code: "redirect_maven_trusted_checksums_invalid_hash".into(), - detail: format!( - "{group_id}:{artifact_id}: the grant's sha256 is not 64 hex digits; \ - no Trusted Checksums pin written to {MVN_CHECKSUMS} (the -socket \ - version suffix still pins the patched artifact)" - ), - }); - } - if let Some((jar, pom_hash)) = &checksum_hashes { - if mvn_conflicts.is_none() { - let (merged, conflicts) = merge_mvn_config(&mvn_config, basedir, &declared); - if merged != mvn_config { - let action = if files.contains_key(MVN_CONFIG) { - "rewritten" - } else { - "added" - }; - mvn_config = merged; - mvn_config_changed = true; - result.edits.push(FileEdit { - path: MVN_CONFIG.into(), - kind: "redirect_maven_config".into(), - action: action.into(), - key: Some("trustedChecksums".into()), - original: None, - new: None, - }); - } - mvn_conflicts = Some(conflicts); - } - for (key, existing_value) in mvn_conflicts.iter().flatten() { - result.warnings.push(RewriteWarning { - code: "redirect_maven_trusted_checksums_conflict".into(), - detail: format!( - "{group_id}:{artifact_id}: {MVN_CONFIG} already sets -D{key}= to a \ - different value (-D{key}={existing_value}); leaving it as-is" - ), - }); - } - checksum_entries.push(( - crate::vendor::jvm::layout::artifact_path( - &group_id, - &artifact_id, - &suffixed_version, - None, - "jar", - ), - jar.clone(), - )); - checksum_entries.push(( - crate::vendor::jvm::layout::artifact_path( - &group_id, - &artifact_id, - &suffixed_version, - None, - "pom", - ), - pom_hash.clone(), - )); - } + pin_maven_checksums( + files, + (&group_id, &artifact_id, &suffixed_version), + checksum_hashes.as_ref(), + bad_checksum_hashes, + &mut MavenChecksumSettings { + config: &mut mvn_config, + changed: &mut mvn_config_changed, + basedir, + declared: &declared, + conflicts: &mut mvn_conflicts, + }, + &mut checksum_entries, + result, + ); } if pom_changed { @@ -9808,6 +9866,7 @@ fn rewrite_maven_pom( result.files.insert("pom.xml".into(), p); } } + result.files.extend(planner.module_poms); if mvn_config_changed { result.files.insert(MVN_CONFIG.into(), mvn_config); } @@ -9860,6 +9919,485 @@ fn rewrite_maven_pom( } } +/// The `.mvn/maven.config` of one run as the Trusted Checksums settings +/// are merged into it: the text, whether it changed, how this project +/// spells the checksums directory (one rule for every path that pins: a +/// literal version, a property, a reactor), and the settings found at +/// another value once the merge has run. +struct MavenChecksumSettings<'a> { + config: &'a mut String, + changed: &'a mut bool, + basedir: trusted_checksums::Basedir, + declared: &'a DeclaredMaven, + conflicts: &'a mut Option>, +} + +/// The Trusted Checksums pin of one dep whose version pin landed this run: +/// only when BOTH the jar sha256 and the served pom sha256 are known. Two +/// entries per dep — the jar and the pom — under the SUFFIXED version's +/// local-repo path. +#[allow(clippy::too_many_arguments)] +fn pin_maven_checksums( + files: &BTreeMap, + (group_id, artifact_id, suffixed_version): (&str, &str, &str), + checksum_hashes: Option<&(String, String)>, + bad_checksum_hashes: bool, + settings: &mut MavenChecksumSettings<'_>, + checksum_entries: &mut Vec<(String, String)>, + result: &mut RewriteResult, +) { + if bad_checksum_hashes { + result.warnings.push(RewriteWarning { + code: "redirect_maven_trusted_checksums_invalid_hash".into(), + detail: format!( + "{group_id}:{artifact_id}: the grant's sha256 is not 64 hex digits; \ + no Trusted Checksums pin written to {MVN_CHECKSUMS} (the -socket \ + version suffix still pins the patched artifact)" + ), + }); + } + let Some((jar, pom_hash)) = checksum_hashes else { + return; + }; + // The settings are merged in once per run, with the first dependency + // that carries checksums; a setting found at another value is + // reported for each such dependency. + if settings.conflicts.is_none() { + let (merged, conflicts) = + merge_mvn_config(settings.config, settings.basedir, settings.declared); + if merged != *settings.config { + let action = if files.contains_key(MVN_CONFIG) { + "rewritten" + } else { + "added" + }; + *settings.config = merged; + *settings.changed = true; + result.edits.push(FileEdit { + path: MVN_CONFIG.into(), + kind: "redirect_maven_config".into(), + action: action.into(), + key: Some("trustedChecksums".into()), + original: None, + new: None, + }); + } + *settings.conflicts = Some(conflicts); + } + for (key, existing_value) in settings.conflicts.iter().flatten() { + result.warnings.push(RewriteWarning { + code: "redirect_maven_trusted_checksums_conflict".into(), + detail: format!( + "{group_id}:{artifact_id}: {MVN_CONFIG} already sets -D{key}= to a \ + different value (-D{key}={existing_value}); leaving it as-is" + ), + }); + } + for (ext, hash) in [("jar", jar), ("pom", pom_hash)] { + checksum_entries.push(( + crate::vendor::jvm::layout::artifact_path( + group_id, + artifact_id, + suffixed_version, + None, + ext, + ), + hash.clone(), + )); + } +} + +/// One dep handed to the reactor planner. +struct ReactorDep<'a> { + dep: &'a DepOverride, + group_id: &'a str, + artifact_id: &'a str, + /// The grant's suffixed version (`None`: a same-GAV grant). + suffixed: Option<&'a str>, + repo_id: &'a str, + index_url: &'a str, + /// The grant carries the hashes of a Trusted Checksums pin. + checksums: bool, + /// The root pom heads a reactor (else the planner reads a single pom). + reactor_root: bool, + /// The code a dep the planner cannot take is reported under: the one + /// the pom rewriter gave that shape before the planner read it. + refusal: &'static str, +} + +/// What the reactor planner did for one dep. +struct ReactorRun { + /// A version, property or pin was written this run. + landed: bool, + /// The poms wire the patch once the run is written. + wired: bool, + /// Trusted-checksum paths nothing names any more: an earlier patch of + /// this version whose pins moved to this one, or this patch's own once + /// its last pin was taken out. + drops: Vec, +} + +/// The hosted warning a reactor planner note, or the reason a plan was +/// refused for, is reported under. +fn reactor_note_code(reason: &str) -> &'static str { + match reason { + "classifier_declared" => "redirect_maven_classifier_unsupported", + "coordinates_overridden" => "redirect_maven_profile_coordinates_unpatched", + "conflicting_literal_version" | "range" => "redirect_maven_dep_version_mismatch", + "selection_undetermined" => "redirect_maven_selection_undetermined", + "pin_would_move_module" => "redirect_maven_pin_would_move_module", + "edit_not_reversible" => "redirect_maven_edit_not_reversible", + "nothing_wired" => "redirect_maven_profile_dependency_unpatched", + "repository_unwritable" => "redirect_maven_pom_unreadable", + _ => "redirect_maven_dep_unpinned", + } +} + +/// The hosted rewriter's `` edits and its restore, as the +/// reactor planner calls them +/// ([`HostedRepository`](crate::vendor::jvm::maven_reactor::HostedRepository)): +/// the same insertion a single pom gets, and the restore `rollback` runs +/// ([`upstream::maven::restore_pom`]), so the planner holds every pom it +/// plans to what a rollback will make of it. `reactor_root` is whether +/// the project heads a reactor, which the restore reads a pom by. +pub(crate) fn with_hosted_repository( + coords: &crate::vendor::jvm::Coords<'_>, + index_url: &str, + user_properties: &BTreeMap, + reactor_root: bool, + run: impl FnOnce(&crate::vendor::jvm::maven_reactor::HostedRepository<'_>) -> R, +) -> R { + use crate::vendor::jvm::maven_reactor::{HostedRepository, RepositoryEdit}; + let repo_id = generation::hosted_pin_name(coords.uuid); + let ensure = |pom: &str| -> Result, String> { + let mut text = pom.to_string(); + let mut index = maven_index::PomIndex::build(&text, user_properties)?; + if !index.has_repository(&repo_id) { + index.insert_repository(&mut text, &repo_id, index_url); + Ok(Some(RepositoryEdit::Added(text))) + } else if index.refresh_repository_url(&mut text, &repo_id, index_url) { + Ok(Some(RepositoryEdit::Refreshed(text))) + } else { + Ok(None) + } + }; + let remove = |pom: &str, uuid: &str| { + upstream::maven::without_repository(pom, &generation::hosted_pin_name(uuid)) + }; + let declared = |pom: &str| -> Vec { + generation::named_generations(pom) + .into_iter() + .filter(|uuid| { + !maven_repositories_with_id(pom, &generation::hosted_pin_name(uuid)).is_empty() + }) + .collect() + }; + let restored = |rel: &str, pom: &str| { + let pin = upstream::maven::PinIn { + group: coords.group_id, + artifact: coords.artifact_id, + base: coords.version, + uuid: coords.uuid, + reactor: reactor_root, + }; + // The repository this run declares is the patch's, whichever host + // the grant names. + let hosted_uuid = |url: &str| (url == index_url).then(|| coords.uuid.to_string()); + upstream::maven::restore_pom(rel, pom, user_properties, &pin, &hosted_uuid) + .map(|done| done.text) + }; + run(&HostedRepository { + ensure: &ensure, + remove: &remove, + declared: &declared, + restored: &restored, + }) +} + +/// The reactor planner's side of one hosted Maven rewrite: the reactor, +/// read once and planned over for every dep of the run, and the module +/// poms the plans changed. +#[derive(Default)] +struct MavenReactorRewrite { + /// The reactor as the plans so far left it (`None`: not read yet). + reactor: Option>, + /// The poms other than the root that a plan changed, as they read now. + module_poms: BTreeMap, + /// The nested-`.mvn` warning was given. + warned_nested_mvn: bool, +} + +impl MavenReactorRewrite { + /// Wire one dep through the reactor planner + /// ([`HostedReactor::plan`](crate::vendor::jvm::maven_reactor::HostedReactor::plan)): + /// over every pom of a reactor root, or over a single pom whose + /// declaration reads a `${property}`. A plan is written whole (the + /// root into `pom_text`, the rest into [`Self::module_poms`]) or not + /// at all: pins, rewritten declarations and properties, and the + /// `` in each local root a wired pom inherits from. `None` + /// when nothing was planned (the warning says why); the `.mvn` files + /// are the caller's. + fn plan( + &mut self, + files: &BTreeMap, + pom_text: &mut String, + of: ReactorDep<'_>, + selection: Option<&MavenSelection>, + user_properties: &BTreeMap, + result: &mut RewriteResult, + ) -> Option { + use crate::vendor::jvm::maven_reactor::{HostedEditKind, HostedReactor}; + let (dep, g, a) = (of.dep, of.group_id, of.artifact_id); + let ga = format!("{g}:{a}"); + let coords = crate::vendor::jvm::Coords { + group_id: g, + artifact_id: a, + version: &dep.version, + uuid: &dep.patch_uuid, + }; + let refuse = |result: &mut RewriteResult, code: &str, why: &str| { + result.warnings.push(RewriteWarning { + code: code.into(), + detail: format!( + "{ga}: {why}; the poms and .mvn/ were left as they are and the dep is not \ + counted as redirected (`scan --mode vendored` commits the patched \ + artifact instead)" + ), + }); + }; + result.maven_reactor_uuids.insert(dep.patch_uuid.clone()); + // The planner writes the suffix the patch uuid gives; a grant that + // serves another one (or none: a same-GAV grant) is not planned. + let suffixed = coords.suffixed_version(); + if of.suffixed != Some(suffixed.as_str()) || dep.patch_uuid.len() != 36 { + let why = match of.suffixed { + Some(served) => { + format!("the grant serves {served}, not the {suffixed} its patch uuid names") + } + None => "the grant serves the patched artifact under its original version, \ + which a pin in one pom cannot keep apart from the upstream one in \ + another" + .to_string(), + }; + refuse(result, of.refusal, &why); + return None; + } + // The reactor: read once, then kept in step with every plan. + if self.reactor.is_none() { + let read = |rel: &str| { + let text = match rel { + "pom.xml" => Some(&*pom_text), + _ => files.get(rel), + }; + text.map(|text| text.as_bytes().to_vec()) + }; + let list = |dir: &str| gradle::key_list(files, dir); + self.reactor = Some(HostedReactor::read(&read, &list).map_err(|refusal| { + refusal + .detail + .strip_prefix("reason: ") + .unwrap_or(&refusal.detail) + .to_string() + })); + } + let reactor = match self.reactor.as_mut().expect("read above") { + Ok(reactor) => reactor, + Err(why) => { + refuse(result, of.refusal, why); + return None; + } + }; + // The single-pom rewriter may have edited the root since. + if reactor.text("pom.xml") != Some(pom_text.as_str()) { + if let Err(refusal) = reactor.set_text("pom.xml", pom_text) { + refuse(result, of.refusal, &refusal.detail); + return None; + } + } + let plan = with_hosted_repository( + &coords, + of.index_url, + user_properties, + of.reactor_root, + |repository| reactor.plan(&coords, selection, repository), + ); + for (reason, detail) in &plan.notes { + result.warnings.push(RewriteWarning { + code: reactor_note_code(reason).into(), + detail: detail.clone(), + }); + } + if let Some((reason, why)) = &plan.refused { + let code = match reason.as_str() { + "unsafe_coordinates" => of.refusal, + reason => reactor_note_code(reason), + }; + refuse(result, code, why); + return None; + } + if let Some(others) = &plan.not_selected { + result.warnings.push(RewriteWarning { + code: "redirect_maven_version_not_selected".into(), + detail: format!( + "{}; the poms were left as they are", + crate::crawlers::maven_selection::not_selected_detail( + g, + a, + &dep.version, + others + ) + ), + }); + return None; + } + // The plan, whole. + for (rel, text) in &plan.poms { + match rel.as_str() { + "pom.xml" => *pom_text = text.clone(), + _ => { + self.module_poms.insert(rel.clone(), text.clone()); + } + } + } + for edit in &plan.edits { + let pinned = || Some(json!({ "groupId": g, "artifactId": a, "version": suffixed })); + let served = || Some(json!({ "id": of.repo_id, "url": of.index_url })); + let version = || Some(Value::String(suffixed.clone())); + let (kind, action, key, new) = match edit.kind { + HostedEditKind::Version => ( + "redirect_maven_dep_version", + "rewritten", + ga.clone(), + version(), + ), + HostedEditKind::Property => ( + "redirect_maven_property", + "rewritten", + edit.property.clone().unwrap_or_default(), + version(), + ), + HostedEditKind::Pin => ( + "redirect_maven_dep_management", + "added", + ga.clone(), + pinned(), + ), + HostedEditKind::PinMoved => ( + "redirect_maven_dep_management", + "rewritten", + ga.clone(), + pinned(), + ), + HostedEditKind::PinRemoved => { + ("redirect_maven_dep_management", "removed", ga.clone(), None) + } + HostedEditKind::Repository => ( + "redirect_maven_repository", + "added", + of.repo_id.to_string(), + served(), + ), + HostedEditKind::RepositoryUrl => ( + "redirect_maven_repository", + "rewritten", + of.repo_id.to_string(), + served(), + ), + HostedEditKind::RepositoryRemoved => match edit.repository.as_deref() { + Some(uuid) if uuid != dep.patch_uuid => ( + "redirect_maven_superseded_repository_removed", + "removed", + generation::hosted_pin_name(uuid), + None, + ), + _ => ( + "redirect_maven_repository", + "removed", + of.repo_id.to_string(), + None, + ), + }, + }; + result.edits.push(FileEdit { + path: edit.rel.clone(), + kind: kind.into(), + action: action.into(), + key: Some(key), + original: edit.original.clone().map(Value::String), + new, + }); + match edit.kind { + HostedEditKind::Pin => result.warnings.push(RewriteWarning { + code: "redirect_maven_dep_management_added".into(), + detail: format!( + "{ga}: added a pin for the suffixed version \ + {suffixed} to {}, where every module selects {} already", + edit.rel, dep.version + ), + }), + HostedEditKind::PinRemoved => result.warnings.push(RewriteWarning { + code: "redirect_maven_pin_would_move_module".into(), + detail: format!( + "{ga}: the pin of {} in {} was removed: a module it reaches now \ + resolves another version, which the pin would hold back", + dep.version, edit.rel + ), + }), + _ => {} + } + } + let landed = plan.edits.iter().any(|edit| { + matches!( + edit.kind, + HostedEditKind::Version + | HostedEditKind::Property + | HostedEditKind::Pin + | HostedEditKind::PinMoved + ) + }); + let gone = plan + .superseded + .iter() + .chain(plan.unnamed.then_some(&suffixed)); + let drops = gone + .flat_map(|version| { + ["jar", "pom"] + .map(|ext| crate::vendor::jvm::layout::artifact_path(g, a, version, None, ext)) + }) + .collect(); + if plan.wired { + result + .confirmed_maven_reactor_uuids + .insert(dep.patch_uuid.clone()); + // Judged on the poms as they stand, so a re-scan says it too. + if of.checksums && !plan.nested_mvn.is_empty() && !self.warned_nested_mvn { + self.warned_nested_mvn = true; + result.warnings.push(RewriteWarning { + code: "redirect_maven_trusted_checksums_unenforced".into(), + detail: format!( + "{} has a .mvn directory of its own: a Maven started there reads that \ + one, not the project root's, so the Trusted Checksums pin in \ + {MVN_CHECKSUMS} is not enforced for such a build (the -socket version \ + suffix still pins the patched artifact)", + plan.nested_mvn.join(", ") + ), + }); + } + } else if plan.notes.is_empty() && plan.edits.is_empty() { + refuse( + result, + of.refusal, + &format!("no pom of the build could take the pin of {}", dep.version), + ); + } + Some(ReactorRun { + landed, + wired: plan.wired, + drops, + }) + } +} + /// Rewrite the Trusted Checksums block of `.mvn/maven.config` to `basedir` /// when it stands in the other spelling /// ([`trusted_checksums::heal_basedir`]): the file and its edit go into @@ -10980,6 +11518,19 @@ mod tests { } } + const MAVEN_UUID: &str = "aaaaaaaa-1111-4222-8333-444444444444"; + + /// [`maven_override`] as the patch service grants it: the suffix is the + /// first eight hex digits of the patch uuid, which is what ties a pin + /// to its repository and what the reactor planner writes. + fn granted_maven_override() -> DepOverride { + let mut dep = maven_override(); + dep.patch_uuid = MAVEN_UUID.into(); + dep.registry_override.as_mut().unwrap().index_url = + format!("https://patch.socket.dev/patch-registry/maven/tok/{MAVEN_UUID}/maven2"); + dep + } + /// A legacy override — no suffixed version, no sha256 (same-GAV serving). fn legacy_maven_override() -> DepOverride { let mut dep = maven_override(); @@ -11387,11 +11938,13 @@ mod tests { /// #1809: a Maven 4 (model 4.1.0) `pom`-packaged root that lists no /// subprojects builds every direct subdirectory holding a `pom.xml`, so - /// it is a reactor like a declared one and refused untouched. Without - /// such a subdirectory, under a 4.0.0 model, or with discovery turned - /// off in `.mvn/maven.config`, it is a single pom and still rewritten. + /// it is a reactor like a declared one: each pom's own declaration of + /// the version is rewritten, and the repository goes in the root they + /// inherit. Without such a subdirectory, under a 4.0.0 model, or with + /// discovery turned off in `.mvn/maven.config`, it is a single pom and + /// rewritten alone. #[test] - fn maven_4_implicit_subprojects_root_is_refused() { + fn maven_4_implicit_subprojects_are_rewritten_with_their_root() { let dep = "\n \n org.slf4j\n slf4j-api\n 1.7.36\n \n \n"; let root = |model: &str| { format!( @@ -11402,23 +11955,35 @@ mod tests { let tree = |model: &str, extra: &[(&str, &str)]| { let mut files = BTreeMap::from([("pom.xml".to_string(), root(model))]); files.extend(extra.iter().map(|(k, v)| (k.to_string(), v.to_string()))); - rewrite_registry_redirect(&files, &[maven_override()]) + rewrite_registry_redirect(&files, &[granted_maven_override()]) }; let r = tree("4.1.0", &[("child/pom.xml", child)]); + for rel in ["pom.xml", "child/pom.xml"] { + let text = r.files.get(rel).map(String::as_str).unwrap_or_default(); + assert!( + text.contains(&format!("{MAVEN_SUFFIXED}")), + "{rel} declares the version itself: {text} {:?}", + r.warnings + ); + } assert!( - r.files.is_empty() && r.edits.is_empty(), - "an implicit reactor root must not be edited: files={:?} edits={:?}", - r.files.keys(), - r.edits + r.files["pom.xml"].contains("socket-patch-") + && !r.files["child/pom.xml"].contains(""), + "one repository, in the root the subproject inherits" + ); + assert!( + !warning_codes(&r).contains(&"redirect_maven_multimodule_unsupported"), + "{:?}", + r.warnings ); + // Nothing of it is planned when a subproject's pom cannot be read. + let r = tree("4.1.0", &[("child/pom.xml", "")]); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.files); assert_eq!( warning_codes(&r), vec!["redirect_maven_multimodule_unsupported"] ); - assert!(r.warnings[0] - .detail - .contains("Maven 4 subproject discovery")); let off = "-Dmaven.project.discoverSubprojects=false\n"; for (case, r) in [ @@ -11443,6 +12008,423 @@ mod tests { } } + /// Hosted-redirects slf4j-api over `files`, each module selecting what + /// `picks` says for it (a module left out does not resolve it). + fn rewrite_poms_selecting( + files: &BTreeMap, + picks: &[(&str, Result<&str, &str>)], + ) -> RewriteResult { + let modules: Vec<&str> = files + .keys() + .map(String::as_str) + .filter(|rel| rel.ends_with("pom.xml")) + .collect(); + let picks: Vec<_> = picks + .iter() + .map(|(pom, pick)| (*pom, "org.slf4j", "slf4j-api", *pick)) + .collect(); + let selection = MavenSelection::answering(&modules, &picks); + rewrite_registry_redirect_with_host( + files, + &[granted_maven_override()], + &BTreeMap::new(), + None, + false, + &std::collections::BTreeSet::new(), + &yarnrc::OuterYarnMirror::default(), + &CratesIoSource::Registry, + Some(&selection), + ) + } + + fn poms(files: &[(&str, &str)]) -> BTreeMap { + files + .iter() + .map(|(rel, text)| (rel.to_string(), text.to_string())) + .collect() + } + + const REACTOR_ROOT: &str = "\n 4.0.0\n \ + com.example\n root\n \ + 1.0.0\n pom\n \n \ + a\n b\n \n\n"; + + /// The module `name` of [`REACTOR_ROOT`], depending on logback (which + /// brings slf4j-api in) and on `more`. + fn reactor_module(name: &str, more: &str) -> String { + format!( + "\n 4.0.0\n \n \ + com.example\n root\n \ + 1.0.0\n \n {name}\n \ + \n \n ch.qos.logback\n \ + logback-classic\n 1.4.14\n \ + \n{more} \n\n" + ) + } + + /// A reactor is pinned module by module: the pin goes in the pom of + /// the module that selects the patch's version, the module that + /// resolves another one is not touched, and the repository and the + /// Trusted Checksums go where the whole reactor reads them. + #[test] + fn maven_reactor_is_pinned_in_the_modules_that_select_the_version() { + let files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let picks = [("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))]; + let r = rewrite_poms_selecting(&files, &picks); + assert_eq!( + r.files.keys().collect::>(), + [MVN_CHECKSUMS, MVN_CONFIG, "a/pom.xml", "pom.xml"], + "b/pom.xml is not written: {:?}", + r.warnings + ); + let pin = format!( + "\n \ + \n org.slf4j\n \ + slf4j-api\n {MAVEN_SUFFIXED}\n \ + " + ); + assert!( + r.files["a/pom.xml"].contains(&pin), + "{}", + r.files["a/pom.xml"] + ); + assert!(!r.files["a/pom.xml"].contains("")); + let root = &r.files["pom.xml"]; + assert!( + root.contains(&format!("socket-patch-{MAVEN_UUID}")) + && !root.contains(MAVEN_SUFFIXED), + "the root takes the repository and no pin: {root}" + ); + assert_eq!( + r.edits + .iter() + .map(|e| (e.path.as_str(), e.kind.as_str(), e.action.as_str())) + .collect::>(), + [ + ("a/pom.xml", "redirect_maven_dep_management", "added"), + ("pom.xml", "redirect_maven_repository", "added"), + (MVN_CONFIG, "redirect_maven_config", "added"), + (MVN_CHECKSUMS, "redirect_maven_trusted_checksums", "added"), + ] + ); + assert_eq!(warning_codes(&r), ["redirect_maven_dep_management_added"]); + assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); + + // A second run over what the first wrote changes nothing, and + // still counts the patch as pinned. + let mut after = files.clone(); + after.extend(r.files.clone()); + let again = rewrite_poms_selecting(&after, &picks); + assert!( + again.files.is_empty() && again.edits.is_empty(), + "{:?} {:?}", + again.files.keys(), + again.edits + ); + assert!(again.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); + + // No module selects the version: nothing is written, and the line + // says what the build selects instead. + let r = rewrite_poms_selecting( + &files, + &[("a/pom.xml", Ok("2.0.9")), ("b/pom.xml", Ok("2.0.9"))], + ); + assert!(r.files.is_empty() && r.edits.is_empty()); + assert_eq!(warning_codes(&r), ["redirect_maven_version_not_selected"]); + assert!(r.warnings[0].detail.contains("2.0.9"), "{:?}", r.warnings); + assert!(r.confirmed_maven_reactor_uuids.is_empty()); + } + + /// A reactor none of whose poms can be told is left as it is, but for + /// a declaration that names the version: that one is rewritten where + /// it stands, which moves nothing. + #[test] + fn maven_reactor_without_a_selection_rewrites_declarations_only() { + let declaring = " \n org.slf4j\n \ + slf4j-api\n 1.7.36\n \ + \n"; + let files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", declaring)), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let r = rewrite_registry_redirect(&files, &[granted_maven_override()]); + assert_eq!( + r.files["a/pom.xml"], + files["a/pom.xml"].replace("1.7.36<", &format!("{MAVEN_SUFFIXED}<")) + ); + assert!(!r.files.contains_key("b/pom.xml")); + assert_eq!( + warning_codes(&r), + ["redirect_maven_selection_undetermined"], + "b may resolve it too, and is not pinned on a guess" + ); + assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); + } + + /// A reactor whose only declaration of the version sits in a module's + /// ``: rewriting it alone would name a version with no + /// repository to serve it, which a build with that profile could not + /// resolve and a rollback could not find. Nothing is written. + #[test] + fn maven_reactor_profile_only_declaration_writes_nothing() { + let profiled = "\n 4.0.0\n \n \ + com.example\n root\n \ + 1.0.0\n \n a\n \n \ + \n extra\n \n \n \ + org.slf4j\n slf4j-api\n \ + 1.7.36\n \n \n \ + \n \n\n"; + let files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", profiled), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let r = rewrite_registry_redirect(&files, &[granted_maven_override()]); + assert!( + r.files.is_empty() && r.edits.is_empty(), + "{:?} {:?}", + r.files.keys(), + r.edits + ); + assert!( + warning_codes(&r).contains(&"redirect_maven_profile_dependency_unpatched"), + "{:?}", + r.warnings + ); + assert!(r.confirmed_maven_reactor_uuids.is_empty()); + } + + /// The whole plan or nothing: a root whose `` cannot + /// take the repository in a form a rollback puts back exactly gets no + /// repository, so the module below gets no pin either. + #[test] + fn maven_reactor_that_cannot_take_the_repository_writes_nothing() { + let files = poms(&[ + ( + "pom.xml", + &REACTOR_ROOT.replace("", " \n"), + ), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let r = rewrite_poms_selecting( + &files, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + assert!( + r.files.is_empty() && r.edits.is_empty(), + "{:?} {:?}", + r.files.keys(), + r.edits + ); + assert_eq!(warning_codes(&r), ["redirect_maven_edit_not_reversible"]); + assert!(r.confirmed_maven_reactor_uuids.is_empty()); + } + + /// When the last pin of a patch is taken out (the module it reached + /// now resolves another version), its repository and its checksum + /// lines go with it: nothing is left that only a rollback could clear, + /// and no rollback would find. + #[test] + fn maven_reactor_last_pin_removed_takes_the_repository_and_checksums() { + let files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let first = rewrite_poms_selecting( + &files, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + let mut wired = files.clone(); + wired.extend(first.files.clone()); + assert!(wired[MVN_CHECKSUMS].contains(MAVEN_SUFFIXED)); + + let r = rewrite_poms_selecting( + &wired, + &[("a/pom.xml", Ok("2.0.9")), ("b/pom.xml", Ok("2.0.9"))], + ); + assert_eq!(r.files["a/pom.xml"], files["a/pom.xml"]); + assert_eq!(r.files["pom.xml"], files["pom.xml"], "the repository went"); + assert!( + !r.files[MVN_CHECKSUMS].contains(MAVEN_SUFFIXED), + "the checksum lines went: {}", + r.files[MVN_CHECKSUMS] + ); + assert!( + warning_codes(&r).contains(&"redirect_maven_pin_would_move_module"), + "{:?}", + r.warnings + ); + assert!(r.confirmed_maven_reactor_uuids.is_empty()); + let removed: Vec<_> = r + .edits + .iter() + .filter(|e| e.action == "removed") + .map(|e| (e.path.as_str(), e.kind.as_str())) + .collect(); + assert_eq!( + removed, + [ + ("a/pom.xml", "redirect_maven_dep_management"), + ("pom.xml", "redirect_maven_repository") + ] + ); + } + + /// A module with a `.mvn` of its own is reported on every scan, not + /// only the one that writes the pin: the condition is judged on the + /// files as they stand. + #[test] + fn maven_reactor_nested_mvn_is_reported_on_every_scan() { + let mut files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + files.insert("a/.mvn/maven.config".to_string(), "-T1\n".to_string()); + let picks = [("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))]; + let first = rewrite_poms_selecting(&files, &picks); + let nested = |r: &RewriteResult| { + r.warnings + .iter() + .filter(|w| w.code == "redirect_maven_trusted_checksums_unenforced") + .filter(|w| w.detail.starts_with("a has a .mvn directory of its own")) + .count() + }; + assert_eq!(nested(&first), 1, "{:?}", first.warnings); + let mut wired = files.clone(); + wired.extend(first.files.clone()); + let again = rewrite_poms_selecting(&wired, &picks); + assert!(again.files.is_empty(), "{:?}", again.files.keys()); + assert_eq!(nested(&again), 1, "{:?}", again.warnings); + } + + /// A single pom that inherits from a parent pom inside the checkout + /// (no ``): a property the parent defines is rewritten there, + /// and the repository goes in the parent the pom inherits it from. + /// Both are written, or neither. + #[test] + fn maven_single_pom_wires_through_its_parent_in_the_checkout() { + let parent = "\n 4.0.0\n \ + com.example\n parent\n \ + 1.0.0\n pom\n \n \ + 1.7.36\n \n\n"; + let child = property_pom("1", "").replace( + " com.example", + " \n com.example\n \ + parent\n 1.0.0\n \ + parent/pom.xml\n \n \ + com.example", + ); + let files = poms(&[("pom.xml", &child), ("parent/pom.xml", parent)]); + let r = rewrite_poms_selecting(&files, &[("pom.xml", Ok("1.7.36"))]); + assert_eq!( + r.files + .keys() + .filter(|rel| rel.ends_with("pom.xml")) + .collect::>(), + ["parent/pom.xml"], + "{:?}", + r.warnings + ); + let wired = &r.files["parent/pom.xml"]; + assert!( + wired.contains(&format!("{MAVEN_SUFFIXED}")) + && wired.contains(&format!("socket-patch-{MAVEN_UUID}")), + "{wired}" + ); + assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); + } + + fn property_pom(properties: &str, more: &str) -> String { + format!( + "\n 4.0.0\n com.example\n \ + app\n 1.0.0\n \n \ + {properties}\n \n \n \n \ + org.slf4j\n slf4j-api\n \ + ${{slf4j.version}}\n \n{more} \ + \n\n" + ) + } + + /// A `${property}` version is wired, no longer refused: the property + /// itself when only this artifact reads it, else the one declaration, + /// with the text it replaced recorded right after it so a rollback + /// can put it back. + #[test] + fn maven_property_version_is_wired_without_stranding_a_sibling() { + let picks = [("pom.xml", Ok("1.7.36"))]; + + let own = poms(&[( + "pom.xml", + &property_pom("1.7.36", ""), + )]); + let r = rewrite_poms_selecting(&own, &picks); + assert!( + r.files["pom.xml"] + .contains(&format!("{MAVEN_SUFFIXED}")) + && r.files["pom.xml"].contains("${slf4j.version}"), + "{}", + r.files["pom.xml"] + ); + assert_eq!(r.edits[0].kind, "redirect_maven_property"); + assert_eq!(r.edits[0].key.as_deref(), Some("slf4j.version")); + assert!(warning_codes(&r).is_empty(), "{:?}", r.warnings); + assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); + + let sibling = " \n org.slf4j\n \ + slf4j-simple\n \ + ${slf4j.version}\n \n"; + let shared = poms(&[( + "pom.xml", + &property_pom("1.7.36", sibling), + )]); + let r = rewrite_poms_selecting(&shared, &picks); + let pom = &r.files["pom.xml"]; + assert!( + pom.contains(&format!( + "slf4j-api\n {MAVEN_SUFFIXED}\ + " + )), + "{pom}" + ); + assert!( + pom.contains("1.7.36") + && pom.contains( + "slf4j-simple\n \ + ${slf4j.version}" + ), + "the property and its other reader are as they were: {pom}" + ); + assert_eq!(r.edits[0].kind, "redirect_maven_dep_version"); + assert_eq!( + r.edits[0].original, + Some(Value::String("${slf4j.version}".into())) + ); + let mut after = shared.clone(); + after.extend(r.files.clone()); + let again = rewrite_poms_selecting(&after, &picks); + assert!( + again.files.is_empty() && again.edits.is_empty(), + "{:?}", + again.edits + ); + + // A property no pom of the checkout defines, in a build whose + // selection is not known: left as it is, with the reason. + let undefined = poms(&[("pom.xml", &property_pom("1", ""))]); + let r = rewrite_registry_redirect(&undefined, &[granted_maven_override()]); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.files); + assert!(warning_codes(&r).contains(&"redirect_maven_dep_unpinned")); + assert!(r.confirmed_maven_reactor_uuids.is_empty()); + } + /// A direct declaration whose groupId / artifactId is a property of /// the pom's own `` is the GA (#683): its literal is /// rewritten, not shadowed by an added `` pin diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs index e6ad05c5e6..c2df568900 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs @@ -7,6 +7,15 @@ //! trusted-checksums resolver lines to `.mvn/maven.config` and the //! suffixed jar/pom lines to `.mvn/checksums/checksums.sha256`. //! +//! In a reactor, and for a `${property}` version, the pins are the reactor +//! planner's (`maven_reactor::plan_hosted`), spread over the poms that +//! take them: a pin tagged with its patch uuid, a declaration with the +//! text it replaced recorded beside it, a property holding the suffixed +//! version. Each says what it replaced, and +//! [`unwire_hosted`](crate::vendor::jvm::maven_reactor::unwire_hosted) +//! puts it back, in every pom discovery found the pin in. What follows is +//! the single pom an earlier release pinned, which carries no such mark. +//! //! Everything but the `.mvn` provenance is derivable from the pom itself: //! the base version is the suffix's prefix, and the added blocks have the //! writer's exact shape. An added `` entry is told @@ -25,7 +34,7 @@ use std::collections::BTreeMap; use regex::Regex; -use super::{by_uuid, read_or_refuse, refuse_all_in, Ctx, FormatResult, HostedPin, View}; +use super::{by_uuid, read_or_refuse, Ctx, FormatResult, HostedPin, View}; use crate::formats::maven::declared_maven::DeclaredMaven; use crate::formats::maven::trusted_checksums; use crate::patch::redirect::{ @@ -140,51 +149,143 @@ fn dm_sections(pom: &str) -> Vec<(usize, usize)> { /// Remove the `socket-patch-` repository of `pom`: the element and /// the line break before it (the rewriter's own insertion), when it sits /// on lines of its own. -fn remove_repository(pom: &str, uuid: &str, ctx: &Ctx<'_>) -> Result { +fn remove_repository( + rel: &str, + pom: &str, + uuid: &str, + hosted_uuid: &dyn Fn(&str) -> Option, +) -> Result { let id = generation::hosted_pin_name(uuid); let (start, end) = match maven_repositories_with_id(pom, &id)[..] { [one] => one, - [] => return Err(format!("pom.xml has no with id {id}")), + [] => return Err(format!("{rel} has no with id {id}")), _ => { return Err(format!( - "pom.xml has several elements with id {id}" + "{rel} has several elements with id {id}" )) } }; let url = maven_tag_text_in(pom, "url", start, end).unwrap_or_default(); - if ctx.hosted_uuid(&url).as_deref() != Some(uuid) { + if hosted_uuid(&url).as_deref() != Some(uuid) { return Err(format!( - "the pom.xml repository {id} does not point at the Socket patch server" + "the {rel} repository {id} does not point at the Socket patch server" )); } remove_maven_repository(pom, &id) - .ok_or_else(|| format!("the pom.xml repository {id} is not on lines of its own")) + .ok_or_else(|| format!("the {rel} repository {id} is not on lines of its own")) +} + +/// `pom` without the `` whose id is `id`, and without the +/// `` section the rewriter authored for it once that holds +/// nothing else; `None` unless exactly one such repository sits on lines +/// of its own. What the rewriter itself runs when it takes a repository +/// out (the last pin of a patch went, or a newer patch superseded it), so +/// a scan leaves what a rollback would. +pub(crate) fn without_repository(pom: &str, id: &str) -> Option { + let mut text = remove_maven_repository(pom, id)?; + if text.contains(EMPTY_REPOSITORIES) && !pom.contains(EMPTY_REPOSITORIES) { + text = text.replacen(EMPTY_REPOSITORIES, "", 1); + } + Some(text) +} + +/// What [`restore_pom`] took out of one pom. +pub(crate) struct Restored { + pub(crate) text: String, + /// The pin's `` was declared here. + pub(crate) repository: bool, + /// A pin, a declaration or a property of the patch was here. + pub(crate) wiring: bool, +} + +/// One pin and where it is restored. +pub(crate) struct PinIn<'a> { + pub(crate) group: &'a str, + pub(crate) artifact: &'a str, + pub(crate) base: &'a str, + pub(crate) uuid: &'a str, + /// The project root heads a reactor: its poms are the reactor + /// planner's to read, none an earlier release pinned. + pub(crate) reactor: bool, +} + +/// The pom `rel` (`pom`) as restoring `pin` leaves it, or why it cannot +/// be restored: the pin taken out ([`restore_pin`]), the wrappers the +/// rewriter authored from scratch gone once emptied, and what is left +/// still a readable pom. `hosted_uuid` says which patch a repository URL +/// serves. It reads nothing but `pom`, so the rewriter runs it over the +/// text it plans to write: an edit this would not take back is not made. +pub(crate) fn restore_pom( + rel: &str, + pom: &str, + user_properties: &BTreeMap, + pin: &PinIn<'_>, + hosted_uuid: &dyn Fn(&str) -> Option, +) -> Result { + let mut done = restore_pin(rel, pom, user_properties, pin, hosted_uuid)?; + // The from-scratch wrappers, once emptied (repositories come last). + for empty in [EMPTY_REPOSITORIES, EMPTY_DEP_MANAGEMENT] { + if done.text.contains(empty) && !pom.contains(empty) { + done.text = done.text.replacen(empty, "", 1); + } + } + crate::formats::maven::parse_pom(&done.text) + .map_err(|why| format!("restoring {rel} would not leave a readable pom: {why}"))?; + Ok(done) } -/// Restore one pin in `pom`, or say why not. +/// Restore one pin in the pom `rel` (`pom`), or say why not. fn restore_pin( + rel: &str, pom: &str, user_properties: &BTreeMap, - group: &str, - artifact: &str, - base: &str, - uuid: &str, - ctx: &Ctx<'_>, -) -> Result { + pin: &PinIn<'_>, + hosted_uuid: &dyn Fn(&str) -> Option, +) -> Result { + let PinIn { + group, + artifact, + base, + uuid, + reactor, + } = *pin; let suffixed = format!("{base}-socket.{}", &uuid[..8]); - let mut text = remove_repository(pom, uuid, ctx)?; + let coords = crate::vendor::jvm::Coords { + group_id: group, + artifact_id: artifact, + version: base, + uuid, + }; + let name = generation::hosted_pin_name(uuid); + let repository = !maven_repositories_with_id(pom, &name).is_empty(); + let mut text = match repository { + true => remove_repository(rel, pom, uuid, hosted_uuid)?, + false => pom.to_string(), + }; + // What the reactor planner wrote. A pom that carries none of its marks + // outside a reactor is one an earlier release may have pinned: there an + // added `` entry is told from a rewritten one + // below, by its shape; anywhere else every suffixed declaration is a + // rewritten one. + let unwire = |text: &str, literals: bool| { + crate::vendor::jvm::maven_reactor::unwire_hosted(text, &coords, false, literals) + .map_err(|why| format!("{rel} is not readable as a pom ({why})")) + }; + let marked = unwire(&text, false)?; + let legacy = !reactor && marked == text; + let unwired = match legacy { + true => marked, + false => unwire(&text, true)?, + }; + let mut wiring = unwired != text; + text = unwired; let scoped = crate::formats::maven::PomScope::with_user_properties(&text, user_properties) .and_then(|s| s.dependencies()); let matches = dep_matches(&text, scoped.as_deref().ok(), group, artifact); - if !matches + wiring |= matches .iter() - .any(|m| m.version_text.as_deref() == Some(suffixed.as_str())) - { - return Err(format!( - "pom.xml declares no {group}:{artifact} {suffixed}" - )); - } + .any(|m| m.version_text.as_deref() == Some(suffixed.as_str())); // The GA's suffixed literals where Maven reads them for the main jar: // not commented out, outside `` / `` / ``, // no classifier — the same scope the rewriter decides "transitive" by. @@ -255,30 +356,18 @@ fn restore_pin( let live = crate::formats::xml::blank_non_markup(&text).unwrap_or_else(|_| text.clone()); if live.contains(&suffixed) { return Err(format!( - "pom.xml still names {suffixed} outside a version (a property or \ - plugin configuration socket-patch did not write)" + "{rel} still names {suffixed} outside a version (a plugin \ + configuration or other text socket-patch did not write)" )); } - let name = generation::hosted_pin_name(uuid); if live.contains(&name) { - return Err(format!("pom.xml still names {name}")); + return Err(format!("{rel} still names {name}")); } - Ok(text) -} - -/// The `` directories a pom lists (plain relative paths only). -fn modules(pom: &str) -> Vec { - let re = Regex::new(r"\s*([^<]*?)\s*").expect("static module regex is valid"); - re.captures_iter(pom) - .map(|c| c[1].trim_end_matches('/').to_string()) - .filter(|m| { - !m.is_empty() - && !m.starts_with('/') - && !m.contains('\\') - && m.split('/') - .all(|seg| !seg.is_empty() && seg != "." && seg != "..") - }) - .collect() + Ok(Restored { + text, + repository, + wiring, + }) } pub(crate) async fn restore( @@ -287,116 +376,206 @@ pub(crate) async fn restore( files: &[String], ctx: &Ctx<'_>, ) -> FormatResult { + use crate::vendor::jvm::maven_reactor::{heads_reactor_in, read_reactor}; + use crate::vendor::lock_inventory::ProjectView; let mut result = FormatResult::default(); let pins = by_uuid(pins); + // `.mvn/maven.config`'s `-D` user properties, which Maven reads over + // the pom's own when it interpolates a coordinate. + let config = view.read(MVN_CONFIG).await.ok().flatten(); + let user_properties = config + .as_deref() + .map(crate::formats::maven::maven_config_properties) + .unwrap_or_default(); + // The reactor, read as the rewriter and discovery read it. A pin is + // restored in every pom of it that carries part of the pin, whether or + // not discovery listed that pom: a reactor discovery could not read + // whole (a module pom since deleted or broken) is found by its root + // alone, and restoring only the root would leave a module naming a + // version nothing serves any more. + let disk = ProjectView::Disk(view.root); + let root_pom = view.read("pom.xml").await.ok().flatten(); + // A pom that is there but is not UTF-8 text is not a missing module: + // it may hold part of a pin, and nothing can tell. + let undecodable = std::sync::Mutex::new(Vec::new()); + let (reactor, reactor_poms) = match &root_pom { + Some(root) => ( + heads_reactor_in(&disk, root, config.as_deref()).await, + read_reactor(&disk, root, config.as_deref(), |rel| { + let undecodable = &undecodable; + async move { + match disk.read_text(&rel).await { + Ok(text) => Some(text), + Err(e) => { + if e.kind() == std::io::ErrorKind::InvalidData { + undecodable + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(rel); + } + None + } + } + } + }) + .await, + ), + None => (false, BTreeMap::new()), + }; + // A pin is restored in every pom that carries part of it, or in none. + // With a pom of the reactor unread, "every" cannot be kept: restoring + // the others would leave that one naming a version whose repository is + // gone. Every pin is refused, and nothing is written. + let mut undecodable = undecodable + .into_inner() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + undecodable.sort(); + if let Some(rel) = undecodable.first() { + for pin in pins.values() { + result.refuse( + &pin.uuid, + format!( + "{rel} is there but is not UTF-8 text, so whether it holds part of the \ + pin cannot be told; re-save it as UTF-8 and re-run" + ), + ); + } + return result; + } + // The poms as they are, and as they read once the pins so far are out. + let mut originals: BTreeMap = BTreeMap::new(); for rel in files { - let Some(original) = read_or_refuse(view, rel, &pins, &mut result).await else { + if let Some(text) = read_or_refuse(view, rel, &pins, &mut result).await { + originals.insert(rel.clone(), text); + } + } + let mut texts = originals.clone(); + // Checksum-file path prefixes of the restored pins. + let mut checksum_dirs: Vec = Vec::new(); + let mut restored: Vec<&str> = Vec::new(); + for pin in pins.values() { + // A file that could not be read refused the pin above. + if pin.files.iter().any(|rel| !originals.contains_key(rel)) { + continue; + } + let Some((name, base)) = pin.name_version() else { + result.refuse(&pin.uuid, format!("{} is not a Maven purl", pin.purl)); continue; }; - let dir = rel - .rsplit_once('/') - .map(|(d, _)| format!("{d}/")) - .unwrap_or_default(); - let module_poms: Vec = modules(&original) - .into_iter() - .map(|m| { - if m.ends_with(".xml") { - format!("{dir}{m}") - } else { - format!("{dir}{m}/pom.xml") - } - }) - .collect(); - let mut text = original.clone(); - // `.mvn/maven.config`'s `-D` user properties, which Maven reads over - // the pom's own when it interpolates a coordinate. - let user_properties = match view.read(&format!("{dir}{MVN_CONFIG}")).await { - Ok(Some(config)) => crate::formats::maven::maven_config_properties(&config), - _ => BTreeMap::new(), + let Some((group, artifact)) = name.split_once('/') else { + result.refuse(&pin.uuid, format!("{} names no groupId", pin.purl)); + continue; }; - // Checksum-file path prefixes of the restored pins. - let mut checksum_dirs: Vec = Vec::new(); - let mut restored: Vec<&str> = Vec::new(); - for pin in pins.values().filter(|p| p.files.contains(rel)) { - let Some((name, base)) = pin.name_version() else { - result.refuse(&pin.uuid, format!("{} is not a Maven purl", pin.purl)); - continue; - }; - let Some((group, artifact)) = name.split_once('/') else { - result.refuse(&pin.uuid, format!("{} names no groupId", pin.purl)); - continue; - }; - if pin.uuid.len() < 8 { - result.refuse(&pin.uuid, format!("{} is not a patch uuid", pin.uuid)); - continue; + if pin.uuid.len() < 8 { + result.refuse(&pin.uuid, format!("{} is not a patch uuid", pin.uuid)); + continue; + } + let suffixed = format!("{base}-socket.{}", &pin.uuid[..8]); + let repository_id = generation::hosted_pin_name(&pin.uuid); + let tag = format!( + "{}{}:", + crate::vendor::jvm::maven_reactor::PIN_TAG, + pin.uuid + ); + let mut poms: Vec = pin.files.clone(); + for (rel, text) in &reactor_poms { + let carries = + text.contains(&suffixed) || text.contains(&repository_id) || text.contains(&tag); + if carries && !rel.contains(".mvn/") && !poms.contains(rel) { + poms.push(rel.clone()); } - let suffixed = format!("{base}-socket.{}", &pin.uuid[..8]); - let mut in_module = None; - for module in &module_poms { - if let Ok(Some(child)) = view.read(module).await { - if child.contains(&suffixed) - || child.contains(&generation::hosted_pin_name(&pin.uuid)) - { - in_module = Some(module.clone()); + } + let of = PinIn { + group, + artifact, + base: &base, + uuid: &pin.uuid, + reactor, + }; + // Every pom the pin is wired in, or none: a pin refused in one of + // its poms is restored in none of them. + let mut staged: BTreeMap = BTreeMap::new(); + let (mut repository, mut wiring) = (false, false); + let mut refusal = None; + for rel in &poms { + let current = match texts.get(rel) { + Some(text) => text.clone(), + None => match view.read(rel).await { + Ok(Some(text)) => { + originals.insert(rel.clone(), text.clone()); + text + } + Ok(None) => continue, + Err(why) => { + refusal = Some(why); break; } + }, + }; + let hosted_uuid = |url: &str| ctx.hosted_uuid(url); + match restore_pom(rel, ¤t, &user_properties, &of, &hosted_uuid) { + Ok(done) => { + repository |= done.repository; + wiring |= done.wiring; + staged.insert(rel.clone(), done.text); } - } - if let Some(module) = in_module { - result.refuse( - &pin.uuid, - format!( - "the module pom {module} also pins {group}:{artifact} {suffixed}, and \ - socket-patch restores only the root {rel}" - ), - ); - continue; - } - match restore_pin( - &text, - &user_properties, - group, - artifact, - &base, - &pin.uuid, - ctx, - ) { - Ok(next) => { - text = next; - checksum_dirs.push(format!( - "{}/", - crate::vendor::jvm::layout::version_dir(group, artifact, &suffixed) - )); - restored.push(&pin.uuid); + Err(why) => { + refusal = Some(why); + break; } - Err(why) => result.refuse(&pin.uuid, why), } } - // The from-scratch wrappers, once emptied (repositories come last). - for empty in [EMPTY_REPOSITORIES, EMPTY_DEP_MANAGEMENT] { - if text.contains(empty) && !original.contains(empty) { - text = text.replacen(empty, "", 1); + let named = poms.join(", "); + let refusal = refusal.or_else(|| { + if !repository { + Some(format!( + "{named} has no with id {repository_id}" + )) + } else if !wiring { + Some(format!( + "{named} declares no {group}:{artifact} {suffixed}" + )) + } else { + None } - } - if restored.is_empty() { + }); + if let Some(why) = refusal { + result.refuse(&pin.uuid, why); continue; } - if let Err(why) = crate::formats::maven::parse_pom(&text) { - refuse_all_in( - &pins, - rel, - &mut result, - format!("restoring {rel} would not leave a readable pom: {why}"), - ); - continue; + texts.extend(staged); + checksum_dirs.push(format!( + "{}/", + crate::vendor::jvm::layout::version_dir(group, artifact, &suffixed) + )); + restored.push(&pin.uuid); + } + if restored.is_empty() { + return result; + } + for (rel, text) in &texts { + if originals.get(rel) != Some(text) { + view.write(rel, text.clone()); } - view.write(rel, text); + } + // The Trusted Checksums files, where the rewriter keeps them: at the + // project root (and beside a pom an earlier release pinned on its own). + let mut dirs: std::collections::BTreeSet = texts + .keys() + .map(|rel| { + rel.rsplit_once('/') + .map(|(d, _)| format!("{d}/")) + .unwrap_or_default() + }) + .collect(); + dirs.insert(String::new()); + for dir in dirs { restore_mvn(view, &dir, &checksum_dirs, &mut result).await; - result - .handled - .extend(restored.into_iter().map(str::to_string)); } result + .handled + .extend(restored.into_iter().map(str::to_string)); + result } /// Drop the restored pins' trusted-checksum lines, and the `.mvn` files @@ -527,6 +706,8 @@ async fn heal_mvn_config( #[cfg(test)] mod tests { use super::super::{restore_upstream, HostedPin, PinStatus, RestoreOptions, RestoreOutcome}; + use super::{generation, MVN_CHECKSUMS, MVN_CONFIG}; + use crate::patch::redirect::RewriteResult; use std::collections::BTreeMap; const UUID: &str = "77777777-7777-7777-7777-777777777777"; @@ -540,39 +721,52 @@ mod tests { std::fs::read_to_string(p).unwrap() } - /// Restore the slf4j pin (offline: Maven needs no network) over - /// `files`; the outcome, and the tree after. - async fn run(files: &[(&str, String)]) -> (RestoreOutcome, BTreeMap) { - let tmp = tempfile::tempdir().unwrap(); + fn write_tree(root: &std::path::Path, files: &[(&str, String)]) { for (rel, text) in files { - let p = tmp.path().join(rel); + let p = root.join(rel); std::fs::create_dir_all(p.parent().unwrap()).unwrap(); std::fs::write(p, text).unwrap(); } - let pins = [HostedPin { - purl: "pkg:maven/org.slf4j/slf4j-api@1.7.36".into(), - uuid: UUID.into(), - files: vec!["pom.xml".into()], - }]; - let opts = RestoreOptions { - offline: true, - ..RestoreOptions::default() - }; - let outcome = restore_upstream(tmp.path(), &pins, &opts).await; + } + + fn read_tree(root: &std::path::Path) -> BTreeMap { let mut after = BTreeMap::new(); - for entry in walkdir::WalkDir::new(tmp.path()) + for entry in walkdir::WalkDir::new(root) .into_iter() .filter_map(Result::ok) { if entry.file_type().is_file() { - let rel = entry.path().strip_prefix(tmp.path()).unwrap(); + let rel = entry.path().strip_prefix(root).unwrap(); after.insert( rel.to_string_lossy().replace('\\', "/"), std::fs::read_to_string(entry.path()).unwrap(), ); } } - (outcome, after) + after + } + + /// Restore the slf4j pin (offline: Maven needs no network) over + /// `files`, wired in every pom among them; the outcome, and the tree + /// after. + async fn run(files: &[(&str, String)]) -> (RestoreOutcome, BTreeMap) { + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), files); + let pins = [HostedPin { + purl: "pkg:maven/org.slf4j/slf4j-api@1.7.36".into(), + uuid: UUID.into(), + files: files + .iter() + .map(|(rel, _)| rel.to_string()) + .filter(|rel| rel.ends_with("pom.xml")) + .collect(), + }]; + let opts = RestoreOptions { + offline: true, + ..RestoreOptions::default() + }; + let outcome = restore_upstream(tmp.path(), &pins, &opts).await; + (outcome, read_tree(tmp.path())) } fn refusal(outcome: &RestoreOutcome) -> String { @@ -800,21 +994,21 @@ mod tests { " pom\n \n core\n ", ); let module_pom = format!("{SUFFIXED}\n"); - let with_property = hosted.replace( + let with_plugin = hosted.replace( " jar", &format!( - " jar\n \n {SUFFIXED}\n " + " jar\n \n app-{SUFFIXED}\n " ), ); let no_repo = fixture("basic", "input", "pom.xml").replace("1.7.36", SUFFIXED); let inline_repo = hosted.replace("\n ", ""); let cases: Vec<(Vec<(&str, String)>, &str)> = vec![ ( - vec![("pom.xml", with_module), ("core/pom.xml", module_pom)], - "module pom core/pom.xml also pins", + vec![("core/pom.xml", module_pom), ("pom.xml", with_module)], + "core/pom.xml still names", ), ( - vec![("pom.xml", with_property)], + vec![("pom.xml", with_plugin)], "outside a version", ), (vec![("pom.xml", no_repo)], "no with id"), @@ -831,13 +1025,480 @@ mod tests { let (outcome, after) = run(&files).await; let why = refusal(&outcome); assert!(why.contains(needle), "{needle}: {why}"); - assert!(why.contains("git checkout -- pom.xml"), "{why}"); + assert!( + why.contains("git checkout -- ") && why.contains("pom.xml"), + "{why}" + ); for (rel, text) in &files { assert_eq!(after.get(*rel), Some(text), "{needle}: {rel}"); } } } + /// A second patch of the same version, which supersedes [`UUID`]'s. + const NEWER: &str = "88888888-8888-4888-8888-888888888888"; + + /// What each module selects for slf4j-api (a module left out does not + /// resolve it). + type Picks<'a> = &'a [(&'a str, Result<&'a str, &'a str>)]; + + /// One hosted scan of the tree at `root` for the slf4j-api patch + /// `uuid`, each module selecting what `picks` says: the rewrite, with + /// its files written. + fn scan(root: &std::path::Path, uuid: &str, picks: Picks<'_>) -> RewriteResult { + use crate::crawlers::maven_selection::MavenSelection; + use crate::patch::redirect::{ + DepOverride, Integrity, RegistryOverride, RegistryOverrideIdentifiers, + }; + let tree = read_tree(root); + let modules: Vec<&str> = tree + .keys() + .map(String::as_str) + .filter(|rel| rel.ends_with("pom.xml")) + .collect(); + let picks: Vec<_> = picks + .iter() + .map(|(pom, pick)| (*pom, "org.slf4j", "slf4j-api", *pick)) + .collect(); + let dep = DepOverride { + ecosystem: "maven".into(), + name: "slf4j-api".into(), + namespace: Some("org.slf4j".into()), + version: "1.7.36".into(), + token: "tok".into(), + patch_uuid: uuid.into(), + artifact_url: format!( + "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/tok/{uuid}/slf4j-api-1.7.36.jar" + ), + registry_override: Some(RegistryOverride { + kind: "maven2".into(), + index_url: format!("https://patch.socket.dev/patch-registry/maven/tok/{uuid}/maven2"), + identifiers: RegistryOverrideIdentifiers { + name: "org.slf4j/slf4j-api".into(), + version: "1.7.36".into(), + maven_group_id: Some("org.slf4j".into()), + maven_artifact_id: Some("slf4j-api".into()), + maven_suffixed_version: Some(format!("1.7.36-socket.{}", &uuid[..8])), + maven_pom_sha256: Some("d".repeat(64)), + ..Default::default() + }, + }), + integrity: Integrity { + sha256: Some("c".repeat(64)), + ..Default::default() + }, + }; + let written = crate::patch::redirect::rewrite_registry_redirect_with_host( + &tree, + &[dep], + &BTreeMap::new(), + None, + false, + &std::collections::BTreeSet::new(), + &Default::default(), + &crate::formats::cargo::source_replacement::CratesIoSource::Registry, + Some(&MavenSelection::answering(&modules, &picks)), + ); + let files: Vec<(&str, String)> = written + .files + .iter() + .map(|(rel, text)| (rel.as_str(), text.clone())) + .collect(); + write_tree(root, &files); + written + } + + /// The hosted pins discovery reads from the tree at `root`. + async fn discovered(root: &std::path::Path) -> Vec { + HostedPin::discover(crate::vendor::lock_inventory::ProjectView::Disk(root), &[]).await + } + + /// THE INVARIANT, on the tree at `root` as a build and a rollback + /// would find it. No pom names a `-socket.` version, and no pom + /// declares a `socket-patch-` repository, but as part of a pin + /// discovery finds in that very pom (so a rollback undoes it); every + /// pin has the checksum lines of its jar and pom; and no checksum line + /// is left for a suffix no pin has. The pins found. + async fn assert_invariant(case: &str, root: &std::path::Path) -> Vec { + let tree = read_tree(root); + let pins = discovered(root).await; + let found = |hex8: &str, rel: &str| { + pins.iter() + .any(|pin| pin.uuid.starts_with(hex8) && pin.files.iter().any(|f| f == rel)) + }; + for (rel, text) in &tree { + if !rel.ends_with(".xml") || rel.contains(".mvn/") { + continue; + } + let live = crate::formats::xml::blank_non_markup(text).unwrap(); + for (at, _) in live.match_indices("-socket.") { + let hex8 = &live[at + 8..at + 16]; + assert!( + found(hex8, rel), + "{case}: {rel} names -socket.{hex8}, which no pin found there covers: \ + {pins:?}\n{text}" + ); + } + for uuid in generation::named_generations(text) { + assert!( + found(&uuid[..8], rel), + "{case}: {rel} declares the repository of {uuid}, which no pin found \ + there uses: {pins:?}\n{text}" + ); + } + } + let sums = tree.get(MVN_CHECKSUMS).cloned().unwrap_or_default(); + for line in sums.lines().filter(|line| line.contains("-socket.")) { + assert!( + pins.iter() + .any(|pin| line.contains(&format!("-socket.{}/", &pin.uuid[..8]))), + "{case}: a checksum line is left for a suffix no pin has: {line}" + ); + } + for pin in &pins { + let suffix = format!("-socket.{}/", &pin.uuid[..8]); + assert_eq!( + sums.lines().filter(|line| line.contains(&suffix)).count(), + 2, + "{case}: the jar and pom checksum lines of {}: {sums}", + pin.uuid + ); + } + pins + } + + /// Roll every hosted pin of the tree at `root` back. + async fn roll_back(case: &str, root: &std::path::Path) { + let pins = discovered(root).await; + if pins.is_empty() { + return; + } + let opts = RestoreOptions { + offline: true, + ..RestoreOptions::default() + }; + let outcome = restore_upstream(root, &pins, &opts).await; + for pin in &outcome.pins { + assert_eq!(pin.status, PinStatus::Restored, "{case}: {}", pin.purl); + } + } + + /// One fixture through the life of a hosted patch, the invariant + /// checked after every step ([`assert_invariant`]): + /// + /// - scanned, scanned again (which writes nothing), rolled back: the + /// tree is `files` again, byte for byte, with no file left over; + /// - scanned, then scanned for a newer patch of the same version + /// (which takes the place of the first everywhere), then with every + /// module resolving another version (which takes out the pins), then + /// rolled back: every pom is as in `files`, and nothing of either + /// patch is left. + /// + /// `wired` is whether the scan is expected to pin the patch at all. + async fn lifecycle(case: &str, files: &[(&str, String)], picks: Picks<'_>, wired: bool) { + let before: BTreeMap = files + .iter() + .map(|(rel, text)| (rel.to_string(), text.clone())) + .collect(); + let suffixed_in = + |tree: &BTreeMap| tree.values().any(|text| text.contains("-socket.")); + + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), files); + let first = scan(tmp.path(), UUID, picks); + assert_eq!( + suffixed_in(&first.files), + wired, + "{case}: {:?}", + first.warnings + ); + let pins = assert_invariant(case, tmp.path()).await; + assert_eq!(pins.len(), usize::from(wired), "{case}: {pins:?}"); + for pin in &pins { + assert_eq!( + (pin.purl.as_str(), pin.uuid.as_str()), + ("pkg:maven/org.slf4j/slf4j-api@1.7.36", UUID) + ); + } + let again = scan(tmp.path(), UUID, picks); + assert!( + again.files.is_empty() && again.edits.is_empty(), + "{case}: a second scan writes nothing: {:?} {:?}", + again.files.keys(), + again.edits + ); + roll_back(case, tmp.path()).await; + assert_eq!( + read_tree(tmp.path()), + before, + "{case}: a rollback puts every file back and leaves none" + ); + + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), files); + scan(tmp.path(), UUID, picks); + scan(tmp.path(), NEWER, picks); + let pins = assert_invariant(&format!("{case}, superseded"), tmp.path()).await; + assert!( + pins.iter().all(|pin| pin.uuid == NEWER) && pins.len() == usize::from(wired), + "{case}: the newer patch takes the place of the first: {pins:?}" + ); + assert!( + !read_tree(tmp.path()) + .values() + .any(|text| text.contains(&UUID[..8])), + "{case}: nothing of the first patch is left: {:#?}", + read_tree(tmp.path()) + ); + let again = scan(tmp.path(), NEWER, picks); + assert!(again.files.is_empty(), "{case}: {:?}", again.files.keys()); + let elsewhere: Vec<(&str, Result<&str, &str>)> = + picks.iter().map(|(pom, _)| (*pom, Ok("2.0.9"))).collect(); + scan(tmp.path(), NEWER, &elsewhere); + assert_invariant(&format!("{case}, moved on"), tmp.path()).await; + roll_back(case, tmp.path()).await; + let after = read_tree(tmp.path()); + assert!(!suffixed_in(&after), "{case}: {after:#?}"); + for (rel, text) in &before { + assert_eq!(after.get(rel), Some(text), "{case}: {rel}"); + } + // (A scan that took out the last pin itself cannot delete the + // `.mvn` files it once wrote: they stay, with no line of a patch.) + for rel in after.keys().filter(|rel| !before.contains_key(*rel)) { + assert!( + [MVN_CONFIG, MVN_CHECKSUMS].contains(&rel.as_str()), + "{case}: {rel} is left over" + ); + } + } + + const REACTOR_ROOT: &str = "\n 4.0.0\n \ + com.example\n root\n \ + 1.0.0\n pom\n \n \ + a\n b\n \n\n"; + + fn reactor_module(name: &str, dependencies: &str) -> String { + format!( + "\n 4.0.0\n \n \ + com.example\n root\n \ + 1.0.0\n \n {name}\n \ + \n{dependencies} \n\n" + ) + } + + fn dependency(group: &str, artifact: &str, version: Option<&str>) -> String { + let version = version.map_or(String::new(), |v| format!("\n {v}")); + format!( + " \n {group}\n \ + {artifact}{version}\n \n" + ) + } + + /// A single pom declaring slf4j-api at `${slf4j.version}`, with + /// `properties` and `more` dependencies. + fn property_pom(properties: &str, more: &str) -> String { + format!( + "\n 4.0.0\n \ + com.example\n app\n \ + 1.0.0\n \n {properties}\n \n \ + \n{}{more} \n\n", + dependency("org.slf4j", "slf4j-api", Some("${slf4j.version}")) + ) + } + + /// A reactor's wiring is spread over its poms (a pin in the module + /// that selects the version, a declaration rewritten where it stands, + /// the repository in the root, the checksums at the root). Through + /// scan, re-scan, a superseding patch, pins taken out and rollback, + /// no pom is ever left naming a version without the repository and + /// checksum lines that serve it and a pin a rollback finds; and a + /// rollback puts every file back byte for byte. + #[tokio::test] + async fn reactor_wiring_keeps_the_invariant_through_its_life() { + let logback = dependency("ch.qos.logback", "logback-classic", Some("1.4.14")); + let declaring = dependency("org.slf4j", "slf4j-api", Some("1.7.36")); + let both = [("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("1.7.36"))]; + lifecycle( + "a pin in one module, its sibling on another version", + &[ + ("pom.xml", REACTOR_ROOT.to_string()), + ("a/pom.xml", reactor_module("a", &logback)), + ("b/pom.xml", reactor_module("b", &logback)), + ], + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + true, + ) + .await; + lifecycle( + "a pin in the root both inherit, beside a declaration", + &[ + ("pom.xml", REACTOR_ROOT.to_string()), + ("a/pom.xml", reactor_module("a", &declaring)), + ("b/pom.xml", reactor_module("b", &logback)), + ], + &both, + true, + ) + .await; + // The root manages the version in the shape an added entry has: + // it is the project's own, and stays. + let managing = REACTOR_ROOT.replace( + "", + &format!( + " \n \n {} \n \ + \n", + declaring.replace("\n ", "\n ") + ), + ); + lifecycle( + "the root's own management", + &[ + ("pom.xml", managing), + ( + "a/pom.xml", + reactor_module("a", &dependency("org.slf4j", "slf4j-api", None)), + ), + ("b/pom.xml", reactor_module("b", &logback)), + ], + &both, + true, + ) + .await; + lifecycle( + "a property of the root the modules read", + &[ + ( + "pom.xml", + REACTOR_ROOT.replace( + " pom\n", + " pom\n \n \ + 1.7.36\n \n", + ), + ), + ( + "a/pom.xml", + reactor_module( + "a", + &dependency("org.slf4j", "slf4j-api", Some("${slf4j.version}")), + ), + ), + ("b/pom.xml", reactor_module("b", &logback)), + ], + &both, + true, + ) + .await; + // The only declaration is one Maven reads while a profile is + // active: nothing is written at any step. + let profiled = reactor_module("a", "").replace( + "", + &format!( + " \n \n extra\n \n\ + {declaring} \n \n \n" + ), + ); + lifecycle( + "a declaration only a profile holds", + &[ + ("pom.xml", REACTOR_ROOT.to_string()), + ("a/pom.xml", profiled), + ("b/pom.xml", reactor_module("b", "")), + ], + &[], + false, + ) + .await; + } + + /// The same for a single pom: a `${property}` version put back as it + /// was written (the property's own value, or the declaration's + /// recorded text), wiring that sits in a parent pom of the checkout, + /// and the pins an earlier release's rewriter still writes. + #[tokio::test] + async fn single_pom_wiring_keeps_the_invariant_through_its_life() { + let picks = [("pom.xml", Ok("1.7.36"))]; + lifecycle( + "a property only the artifact reads", + &[( + "pom.xml", + property_pom("1.7.36", ""), + )], + &picks, + true, + ) + .await; + lifecycle( + "a property a sibling reads too", + &[( + "pom.xml", + property_pom( + "1.7.36", + &dependency("org.slf4j", "slf4j-simple", Some("${slf4j.version}")), + ), + )], + &picks, + true, + ) + .await; + lifecycle( + "a property a parent from a repository defines", + &[( + "pom.xml", + property_pom("1", "").replace( + " com.example", + " \n corp\n parent\n \ + 7\n \n \n \ + com.example", + ), + )], + &picks, + true, + ) + .await; + // The wiring lands in a parent pom the project lists no module + // for: discovery and rollback must read that pom too. + lifecycle( + "a property a parent pom of the checkout defines", + &[ + ( + "pom.xml", + property_pom("1", "").replace( + " com.example", + " \n com.example\n \ + parent\n 1.0.0\n \ + parent/pom.xml\n \n \ + com.example", + ), + ), + ( + "parent/pom.xml", + "\n 4.0.0\n \ + com.example\n parent\n \ + 1.0.0\n pom\n \n \ + 1.7.36\n \n\n" + .to_string(), + ), + ], + &picks, + true, + ) + .await; + lifecycle( + "a literal declaration", + &[("pom.xml", fixture("basic", "input", "pom.xml"))], + &picks, + true, + ) + .await; + lifecycle( + "no declaration: an added management entry", + &[("pom.xml", fixture("transitive-depmgmt", "input", "pom.xml"))], + &picks, + true, + ) + .await; + } + #[tokio::test] async fn crlf_pom_round_trips() { let input = fixture("basic", "input", "pom.xml").replace('\n', "\r\n"); @@ -877,6 +1538,210 @@ mod tests { assert_eq!(after["pom.xml"], input); } + /// A reactor one of whose module poms has gone missing is still read + /// for the pins of the others: the pin in a module's pom is found with + /// the repository in the root, and a rollback takes out both. + #[tokio::test] + async fn a_reactor_with_a_missing_module_is_still_rolled_back_whole() { + let logback = dependency("ch.qos.logback", "logback-classic", Some("1.4.14")); + let files = [ + ("pom.xml", REACTOR_ROOT.to_string()), + ("a/pom.xml", reactor_module("a", &logback)), + ("b/pom.xml", reactor_module("b", &logback)), + ]; + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), &files); + scan( + tmp.path(), + UUID, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + std::fs::remove_file(tmp.path().join("b/pom.xml")).unwrap(); + let pins = discovered(tmp.path()).await; + assert_eq!(pins.len(), 1, "{pins:?}"); + assert_eq!(pins[0].files, ["a/pom.xml", "pom.xml"]); + roll_back("a missing module", tmp.path()).await; + let after = read_tree(tmp.path()); + assert_eq!(after["a/pom.xml"], files[1].1); + assert_eq!(after["pom.xml"], files[0].1); + assert!(!after.contains_key(MVN_CHECKSUMS), "{:?}", after.keys()); + } + + /// A module pom that is there but is not UTF-8 text is not a missing + /// one. Its content is unknown, and here it holds one of the pins: + /// restoring the poms that can be read would take the repository from + /// under it. Discovery still finds the pin in those; the rollback + /// refuses it, names the file, and changes nothing. + #[tokio::test] + async fn a_reactor_with_an_undecodable_module_is_not_rolled_back_in_part() { + let logback = dependency("ch.qos.logback", "logback-classic", Some("1.4.14")); + let root = REACTOR_ROOT.replace( + "b", + "b\n c", + ); + assert_ne!(root, REACTOR_ROOT); + let files = [ + ("pom.xml", root), + ("a/pom.xml", reactor_module("a", &logback)), + ("b/pom.xml", reactor_module("b", &logback)), + ("c/pom.xml", reactor_module("c", &logback)), + ]; + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), &files); + // `a` and `c` select the base version and take a pin each; `b` + // resolves another, so the root takes none. + scan( + tmp.path(), + UUID, + &[ + ("a/pom.xml", Ok("1.7.36")), + ("b/pom.xml", Ok("2.0.9")), + ("c/pom.xml", Ok("1.7.36")), + ], + ); + // The pom of `c`, pin and all, re-saved in another encoding (a + // Latin-1 "é" in a comment). + let pinned = std::fs::read(tmp.path().join("c/pom.xml")).unwrap(); + assert!(String::from_utf8_lossy(&pinned).contains("-socket.")); + let mut latin1 = b"\n".to_vec(); + latin1.extend_from_slice(&pinned); + std::fs::write(tmp.path().join("c/pom.xml"), &latin1).unwrap(); + let bytes = |root: &std::path::Path| -> BTreeMap> { + walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_file()) + .map(|entry| { + let rel = entry.path().strip_prefix(root).unwrap(); + ( + rel.to_string_lossy().replace('\\', "/"), + std::fs::read(entry.path()).unwrap(), + ) + }) + .collect() + }; + let before = bytes(tmp.path()); + + let pins = discovered(tmp.path()).await; + assert_eq!(pins.len(), 1, "{pins:?}"); + let opts = RestoreOptions { + offline: true, + ..RestoreOptions::default() + }; + let outcome = restore_upstream(tmp.path(), &pins, &opts).await; + let why = refusal(&outcome); + assert!( + why.contains("c/pom.xml") && why.contains("not UTF-8"), + "{why}" + ); + assert_eq!(bytes(tmp.path()), before, "nothing was written"); + } + + /// A pin is restored in every pom of the reactor that carries part of + /// it, whatever discovery listed, or in none: restoring the root alone + /// would take the repository from under a module that still names the + /// suffixed version. + #[tokio::test] + async fn a_pin_is_restored_in_every_pom_that_carries_it_or_in_none() { + let logback = dependency("ch.qos.logback", "logback-classic", Some("1.4.14")); + let files = [ + ("pom.xml", REACTOR_ROOT.to_string()), + ("a/pom.xml", reactor_module("a", &logback)), + ("b/pom.xml", reactor_module("b", &logback)), + ]; + let root_only = [HostedPin { + purl: "pkg:maven/org.slf4j/slf4j-api@1.7.36".into(), + uuid: UUID.into(), + files: vec!["pom.xml".into()], + }]; + let opts = RestoreOptions { + offline: true, + ..RestoreOptions::default() + }; + let wire = || { + let tmp = tempfile::tempdir().unwrap(); + write_tree(tmp.path(), &files); + scan( + tmp.path(), + UUID, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + tmp + }; + + // The module's pin goes with the root's repository. + let tmp = wire(); + let outcome = restore_upstream(tmp.path(), &root_only, &opts).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + let after = read_tree(tmp.path()); + for (rel, text) in &files { + assert_eq!(after.get(*rel), Some(text), "{rel}"); + } + + // A module that still names the pin and can no longer be read as + // a pom: nothing is restored, the root keeps its repository. + let tmp = wire(); + let broken = read_tree(tmp.path())["a/pom.xml"].replace("", ""); + std::fs::write(tmp.path().join("a/pom.xml"), &broken).unwrap(); + let wired = read_tree(tmp.path()); + let outcome = restore_upstream(tmp.path(), &root_only, &opts).await; + let why = refusal(&outcome); + assert!(why.contains("a/pom.xml"), "{why}"); + assert_eq!(read_tree(tmp.path()), wired, "nothing changed"); + } + + /// An earlier release's pin is read by its shape only in a single pom. + /// A Maven 4 root that could discover subprojects but has none is one: + /// the entry that release added goes, as before. With a subproject + /// beside it the root heads a reactor, where a managed entry at the + /// suffixed version is a rewritten one of the project's and keeps its + /// place at the base version. + #[tokio::test] + async fn an_earlier_pin_is_told_by_its_shape_only_in_a_single_pom() { + let maven_4 = |pom: String| { + pom.replace("POM/4.0.0", "POM/4.1.0") + .replace("4.0.0", "4.1.0") + .replace("jar", "pom") + }; + let input = maven_4(fixture("transitive-depmgmt", "input", "pom.xml")); + let hosted = maven_4(fixture("transitive-depmgmt", "expected", "pom.xml")); + assert!(hosted.contains("") && !input.contains("Management")); + + let (outcome, after) = run(&[("pom.xml", hosted.clone())]).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + assert_eq!(after["pom.xml"], input, "the added entry goes"); + + let child = "\n 4.1.0\n \n child\n\n"; + let tmp = tempfile::tempdir().unwrap(); + write_tree( + tmp.path(), + &[ + ("pom.xml", hosted.clone()), + ("child/pom.xml", child.to_string()), + ], + ); + let pins = [HostedPin { + purl: "pkg:maven/org.slf4j/slf4j-api@1.7.36".into(), + uuid: UUID.into(), + files: vec!["pom.xml".into()], + }]; + let opts = RestoreOptions { + offline: true, + ..RestoreOptions::default() + }; + let outcome = restore_upstream(tmp.path(), &pins, &opts).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + let after = read_tree(tmp.path()); + assert!( + after["pom.xml"].contains("1.7.36\n \n \n ") + && !after["pom.xml"].contains(SUFFIXED) + && !after["pom.xml"].contains("socket-patch-"), + "the managed entry stays, at the base version: {}", + after["pom.xml"] + ); + assert_eq!(after["child/pom.xml"], child); + } + /// The `.mvn` files hosted mode wrote are removed whichever way the /// checksums directory is spelled: as this release writes it for a /// Maven 3 project, or with the session's root directory, as an diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs index 2be82d88dc..750cbd5dda 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -36,7 +36,7 @@ mod composer; mod gem; mod golang; mod gradle; -mod maven; +pub(crate) mod maven; pub(crate) mod npm; mod nuget; mod pypi; diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs index 855b11dd9b..f1f23a8d40 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs @@ -28,6 +28,14 @@ use super::{ TREE_GITATTRIBUTES, }; +mod hosted; +mod reader; +pub use hosted::{ + unwire_hosted, HostedEdit, HostedEditKind, HostedPlan, HostedReactor, HostedRepository, + HostedSite, RepositoryEdit, ORIGINAL_TAG, +}; +pub use reader::read_reactor; + /// The committed maven2 tree. use super::layout::MAVEN2_TREE as TREE_ROOT; pub const MAVEN_CONFIG: &str = ".mvn/maven.config"; @@ -108,18 +116,46 @@ pub fn may_discover_subprojects(pom: &str, maven_config: Option<&str>) -> bool { pub async fn implicit_subprojects_in( view: &crate::vendor::lock_inventory::ProjectView<'_>, ) -> Vec { + subprojects_in(view, "").await +} + +/// [`implicit_subprojects_in`] under the directory `dir` (`""`: the +/// root), as names relative to it. +async fn subprojects_in( + view: &crate::vendor::lock_inventory::ProjectView<'_>, + dir: &str, +) -> Vec { + let under = |name: &str| match dir { + "" => name.to_string(), + _ => format!("{dir}/{name}"), + }; let mut out = Vec::new(); - for entry in view.list_dir("").await.unwrap_or_default() { - if entry.name == GIT_DIR || !(entry.is_dir || view.is_symlink(&entry.name)) { + for entry in view.list_dir(dir).await.unwrap_or_default() { + let path = under(&entry.name); + if entry.name == GIT_DIR || !(entry.is_dir || view.is_symlink(&path)) { continue; } - if view.is_file(&format!("{}/{}", entry.name, layout::POM_FILE)) { + if view.is_file(&format!("{path}/{}", layout::POM_FILE)) { out.push(entry.name); } } out } +/// Whether the root pom `pom` of the project `view` reads heads a reactor +/// ([`is_reactor_root`], for a caller that holds the pom and reads the +/// project through a view): the one question the hosted rewriter's +/// discovery and its restore both ask. +pub async fn heads_reactor_in( + view: &crate::vendor::lock_inventory::ProjectView<'_>, + pom: &str, + maven_config: Option<&str>, +) -> bool { + declares_modules(pom) + || (may_discover_subprojects(pom, maven_config) + && !implicit_subprojects_in(view).await.is_empty()) +} + /// A checkout's git directory: never a subproject, whatever it holds (the /// planner's reader refuses every path through it). const GIT_DIR: &str = ".git"; @@ -268,6 +304,7 @@ pub fn plan_with_selection( &mut unpinned, &mut managed_roots, &mut BTreeSet::new(), + &|_, _| None, ); } @@ -317,91 +354,21 @@ pub fn plan_with_selection( } // What the modules at and below each pom select, read once. - let under = selection.map(|selection| reactor.under(selection, patch)); + let under = selection.map(|selection| reactor.under(selection, patch, &|_| false)); if let Some(under) = &under { - // A module that declares another version itself resolves that - // version: its declaration is no conflict to report, and the pins - // go where the base version is selected. - warnings.retain(|w| { - !under.iter().any(|(rel, u)| { - u.own == Some(Own::Other) - && w.detail.contains(" is declared at ") - && w.detail - .starts_with(&format!("reason: conflicting_literal_version: {rel}:")) - }) - }); + forget_other_versions(&mut warnings, under); } // Where the pin goes, and the poms whose pin stays as it is. - let mut pins: BTreeSet = BTreeSet::new(); - let mut held: BTreeSet = BTreeSet::new(); let closed = |rel: &String| unpinned.contains(rel) || managed_roots.contains(rel); - // Where the pins go is decided when a patch is first wired, and the - // committed poms are the record of it: what this machine's local - // repository happens to hold must not move them, or the same checkout - // would plan differently from one machine to the next. A patch the - // poms already wire therefore keeps every pin it has and gets no new - // one, with or without a selection. The one exception is a pin that - // is certain to move a module to another version than Maven selects - // for it, which no run should have left: the pins are then placed - // afresh. - let moves = under.as_ref().is_some_and(|under| { - reactor.scope.iter().any(|rel| { - pin_of(&reactor.poms[rel].doc, patch).is_some() - && under.get(rel).is_some_and(|u| u.other.is_some()) - }) - }); - if reactor.wired_before(patch) && !moves { - // (A local root a declaration ruled out stays ruled out.) - held.extend(reactor.scope.iter().filter(|rel| !closed(rel)).cloned()); - } else { - let mut stranded: Vec = Vec::new(); - for root in reactor.wired_roots() { - let open = !closed(&root); - match &under { - None if open => { - pins.insert(root); - } - None => {} - Some(under) => { - let mut placing = Placing { - under, - patch, - pins: &mut pins, - held: &mut held, - stranded: &mut stranded, - }; - reactor.place(&root, open, &mut placing, 0); - } - } - } - warnings.extend( - stranded - .into_iter() - .map(|detail| degraded("pin_would_move_module", detail)), - ); - // One line for every module that cannot be told, however many. - let unknown: Vec<(&String, &String)> = under - .iter() - .flatten() - .filter_map(|(rel, u)| match &u.own { - Some(Own::Unknown(why)) => Some((rel, why)), - _ => None, - }) - .collect(); - if let Some((module, why)) = unknown.first() { - let more = match unknown.len() - 1 { - 0 => String::new(), - n => format!(", and {n} more"), - }; - warnings.push(degraded( - "selection_undetermined", - format!( - "which version of {g}:{a} {module} resolves cannot be told ({why}){more}; \ - no pin is written where that is so, and one already there is left as it is" - ), - )); - } - } + let kept = keeps_placement(&reactor, patch, under.as_ref()); + let (pins, held) = place_pins( + &reactor, + patch, + under.as_ref(), + &closed, + kept, + &mut warnings, + ); let banning = reactor .scope @@ -541,6 +508,130 @@ pub fn plan_with_selection( }) } +/// A module that declares another version itself resolves that version: +/// its declaration is no conflict to report, and the pins go where the +/// base version is selected. +fn forget_other_versions(warnings: &mut Vec, under: &BTreeMap) { + warnings.retain(|w| { + !under.iter().any(|(rel, u)| { + u.own == Some(Own::Other) + && w.detail.contains(" is declared at ") + && w.detail + .starts_with(&format!("reason: conflicting_literal_version: {rel}:")) + }) + }); +} + +/// Where `patch`'s pins go, and the poms whose pin stays as it is (held), +/// by what the modules at and below each pom select (`under`; `None`: not +/// asked). `closed` holds the local roots that take no pin of their own (a +/// declaration ruled them out, or they manage the artifact themselves). +/// +/// Where the pins go is decided when a patch is first wired, and the +/// committed poms are the record of it: what this machine's local +/// repository happens to hold must not move them, or the same checkout +/// would plan differently from one machine to the next. A patch the poms +/// already wire therefore keeps every pin it has and gets no new one, with +/// or without a selection. The one exception is a pin that is certain to +/// move a module to another version than Maven selects for it, which no +/// run should have left: the pins are then placed afresh. `kept` is that +/// decision ([`keeps_placement`]), taken on the poms as they were before +/// the plan rewrote anything. +fn place_pins( + reactor: &Reactor, + patch: &JvmPatch<'_>, + under: Option<&BTreeMap>, + closed: &dyn Fn(&String) -> bool, + kept: bool, + warnings: &mut Vec, +) -> (BTreeSet, BTreeSet) { + let mut pins: BTreeSet = BTreeSet::new(); + let mut held: BTreeSet = BTreeSet::new(); + if kept { + // (A local root a declaration ruled out stays ruled out.) + held.extend(reactor.scope.iter().filter(|rel| !closed(rel)).cloned()); + return (pins, held); + } + let mut stranded: Vec = Vec::new(); + for root in reactor.wired_roots() { + let open = !closed(&root); + match under { + None if open => { + pins.insert(root); + } + None => {} + Some(under) => { + let mut placing = Placing { + under, + patch, + pins: &mut pins, + held: &mut held, + stranded: &mut stranded, + }; + reactor.place(&root, open, &mut placing, 0); + } + } + } + warnings.extend( + stranded + .into_iter() + .map(|detail| degraded("pin_would_move_module", detail)), + ); + warnings.extend(under.and_then(|under| undetermined_note(patch, under))); + (pins, held) +} + +/// Whether the pins of `patch` stay where the poms have them: the poms +/// already wire the patch, and no pin is certain (by `under`) to move a +/// module to another version than Maven selects for it. +fn keeps_placement( + reactor: &Reactor, + patch: &JvmPatch<'_>, + under: Option<&BTreeMap>, +) -> bool { + reactor.wired_before(patch) && !pin_moves(reactor, patch, under) +} + +/// Whether a pin of `patch` is certain (by `under`) to move a module to +/// another version than Maven selects for it. +fn pin_moves( + reactor: &Reactor, + patch: &JvmPatch<'_>, + under: Option<&BTreeMap>, +) -> bool { + under.is_some_and(|under| { + reactor.scope.iter().any(|rel| { + pin_of(&reactor.poms[rel].doc, patch).is_some() + && under.get(rel).is_some_and(|u| u.other.is_some()) + }) + }) +} + +/// One line for every module of `under` whose selection cannot be told, +/// however many: the first, and how many more. +fn undetermined_note(patch: &JvmPatch<'_>, under: &BTreeMap) -> Option { + let (g, a) = (patch.group_id, patch.artifact_id); + let unknown: Vec<(&String, &String)> = under + .iter() + .filter_map(|(rel, u)| match &u.own { + Some(Own::Unknown(why)) => Some((rel, why)), + _ => None, + }) + .collect(); + let (module, why) = unknown.first()?; + let more = match unknown.len() - 1 { + 0 => String::new(), + n => format!(", and {n} more"), + }; + Some(degraded( + "selection_undetermined", + format!( + "which version of {g}:{a} {module} resolves cannot be told ({why}){more}; \ + no pin is written where that is so, and one already there is left as it is" + ), + )) +} + fn op_of_value(op: &Value) -> &str { op.get("op").and_then(Value::as_str).unwrap_or_default() } @@ -848,27 +939,20 @@ pub fn unattestable_checked( list: ListFn<'_>, c: &Coords<'_>, ) -> Result, JvmRefusal> { + Ok(unattestable_in(&Reactor::discover(read, list)?, c)) +} + +/// [`unattestable_checked`] over a reactor already read. +fn unattestable_in(reactor: &Reactor, c: &Coords<'_>) -> Option { let sv = c.suffixed_version(); let ga = format!("{}:{}", c.group_id, c.artifact_id); - let reactor = Reactor::discover(read, list)?; if !reactor.wires(c) { - return Ok(Some(format!( + return Some(format!( "no dependency or dependencyManagement declaration Maven always reads names \ {ga}:{sv}" - ))); + )); } - let patch = JvmPatch { - group_id: c.group_id, - artifact_id: c.artifact_id, - version: c.version, - uuid: c.uuid, - jar: &[], - upstream_pom: &[], - upstream_parents: None, - upstream_module: None, - extra_artifacts: &[], - patched_members: &[], - }; + let patch = coords_patch(c); let mut edits = BTreeMap::new(); let mut uncertain = BTreeSet::new(); for rel in &reactor.scope { @@ -881,11 +965,12 @@ pub fn unattestable_checked( &mut BTreeSet::new(), &mut BTreeSet::new(), &mut uncertain, + &|_, _| None, ); } let mut at: Vec = edits.into_keys().collect(); at.extend(uncertain); - Ok((!at.is_empty()).then(|| { + (!at.is_empty()).then(|| { format!( "{} may still build {ga}:{} rather than {sv}: a base version declared since \ vendoring, a version a property, profile or unpinned root may move, or an \ @@ -893,7 +978,24 @@ pub fn unattestable_checked( at.join(", "), c.version ) - })) + }) +} + +/// `c` as a patch with no bytes: for planning that reads only what a +/// patch is of, never what it holds. +fn coords_patch<'a>(c: &Coords<'a>) -> JvmPatch<'a> { + JvmPatch { + group_id: c.group_id, + artifact_id: c.artifact_id, + version: c.version, + uuid: c.uuid, + jar: &[], + upstream_pom: &[], + upstream_parents: None, + upstream_module: None, + extra_artifacts: &[], + patched_members: &[], + } } /// `` comment, in the poms +//! [`place_pins`] picks (where every module at or below selects the base +//! version already, or does not resolve the artifact). A later scan +//! keeps every pin where it is, and adds one only for a module nothing +//! reaches yet that is certain to select the base version; +//! - a declaration whose version is one `${property}` the reactor's own +//! poms define, with nothing else reading that property, has the +//! property's value rewritten instead: the declaration keeps its text; +//! - any other `${...}` version is replaced by the literal suffixed +//! version, and the text it replaced is recorded in a comment right +//! after the element ([`ORIGINAL_TAG`]); +//! - the `` that serves the suffixed version is declared in +//! the local root of every pom that names it, through the hosted +//! rewriter's own edits ([`HostedRepository`]). +//! +//! # The invariant +//! +//! A plan is whole or it is nothing ([`HostedReactor::plan`]). Once it is +//! written: +//! +//! - no pom names the suffixed version unless the repository that serves +//! it is declared in that pom's local root, and a declaration Maven +//! always reads resolves to it, so discovery ([`HostedReactor::sites`]) +//! finds the patch and every pom that carries part of it; +//! - a rollback returns every pom the plan first wired to the bytes it had +//! ([`HostedRepository::restored`], the restore itself, run over the +//! planned text before anything is written); +//! - when the plan leaves no pom naming the suffixed version (a pin that +//! came to move a module was taken out), the repository goes with it, +//! and the caller drops its checksum lines ([`HostedPlan::unnamed`]); an +//! earlier patch's repository and checksum lines go only once no pom of +//! the reactor names that patch's suffix any more +//! ([`HostedPlan::superseded`]). +//! +//! A plan that cannot keep these is refused ([`HostedPlan::refused`]) and +//! the reactor stays as it was read. + +use std::collections::{BTreeMap, BTreeSet}; +use std::ops::Range; + +use super::{ + apply_edits, coords_patch, degraded, forget_other_versions, is_base_like, line_span, pin_edit, + pin_moves, pin_of, pin_update, place_pins, safe_coordinates, unattestable_in, + undetermined_note, unwired_in, Doc, Edit, Pin, Placing, Pom, Reactor, Role, +}; +use crate::crawlers::maven_selection::{MavenSelection, Standing, Verdict}; +use crate::formats::maven::split_socket_version; +use crate::vendor::jvm::{Coords, JvmRefusal, ListFn, ReadFn}; + +/// The start of the comment that records what a declaration's `` +/// read before hosted mode replaced it with a literal suffixed version: +/// `1.2-socket.0a1b2c3d`. +pub const ORIGINAL_TAG: &str = ""; + +/// What one edit of a [`HostedPlan`] is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HostedEditKind { + /// A declaration's `` now reads the suffixed version. + Version, + /// A property's value now is the suffixed version. + Property, + /// A `` pin was added. + Pin, + /// The pin of an earlier patch of this version moved to this patch. + PinMoved, + /// A pin that would move a module to another version was taken out. + PinRemoved, + /// The patch's `` was declared. + Repository, + /// The patch's `` took its current URL. + RepositoryUrl, + /// A `` nothing names any more was taken out: the patch's + /// own, or an earlier patch's. + RepositoryRemoved, +} + +/// One edit of a [`HostedPlan`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HostedEdit { + /// The pom edited. + pub rel: String, + pub kind: HostedEditKind, + /// The text replaced: a version, a property's value (`None` for a pin + /// or a repository, and for a version an earlier patch had suffixed). + pub original: Option, + /// The property a [`HostedEditKind::Property`] edit rewrote. + pub property: Option, + /// The patch uuid whose repository a repository edit concerns. + pub repository: Option, +} + +impl HostedEdit { + fn of(rel: &str, kind: HostedEditKind) -> HostedEdit { + HostedEdit { + rel: rel.to_string(), + kind, + original: None, + property: None, + repository: None, + } + } +} + +/// A pom with the patch's repository declared. +pub enum RepositoryEdit { + /// The repository was added. + Added(String), + /// It was there, pointing elsewhere (a rotated grant). + Refreshed(String), +} + +/// The hosted rewriter's own edits of a pom's ``, and its +/// restore: the planner decides where the repository goes, and holds +/// every pom it plans to what a rollback makes of it. +pub struct HostedRepository<'a> { + /// `pom` with the patch's repository declared; `Ok(None)` when it is + /// there as it should be, `Err` when it cannot be declared in it. + pub ensure: &'a dyn Fn(&str) -> Result, String>, + /// `pom` without the hosted repository of the patch `uuid`; `None` + /// when it declares none that can be taken out. + pub remove: &'a dyn Fn(&str, &str) -> Option, + /// The patch uuids whose hosted repository `pom` declares. + pub declared: &'a dyn Fn(&str) -> Vec, + /// The pom at the first path, holding the second as its text, as a + /// rollback of the patch leaves it. + pub restored: &'a dyn Fn(&str, &str) -> Result, +} + +/// What hosted mode does to a reactor's poms for one patch. +#[derive(Debug, Default)] +pub struct HostedPlan { + /// The poms that change, with their new text: all of them are written, + /// or (a refused plan holds none) nothing is. + pub poms: BTreeMap, + pub edits: Vec, + /// Why a declaration or a pom was left as it is: the vendored + /// planner's reason word, and the line. + pub notes: Vec<(String, String)>, + /// Whether the poms wire the patch once the plan is written (or did + /// before): a declaration Maven always reads resolves to the suffixed + /// version, and its repository is declared. + pub wired: bool, + /// The patch's suffixed version was named before the plan and no pom + /// names it after: its repository was taken out, and its checksum + /// lines are the caller's to drop. + pub unnamed: bool, + /// The suffixed versions of earlier patches of this version that no + /// pom of the reactor names any more: their checksum lines go. + pub superseded: Vec, + /// The module directories with a `.mvn` of their own. + pub nested_mvn: Vec, + /// No module selects the base version, and every answer is certain: + /// the versions selected instead. Nothing is planned then. + pub not_selected: Option>, + /// Why nothing was planned: the plan could not be written whole + /// without breaking the invariant (the module docs). + pub refused: Option<(String, String)>, +} + +/// One artifact some pom of a reactor builds at a Socket suffixed version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HostedSite { + pub group: String, + pub artifact: String, + /// `-socket.`. + pub suffixed: String, + /// The patch uuid a pin's comment names, when a pin carries it. + pub uuid: Option, + /// Every pom that names the suffixed version outside comments: a + /// declaration, a pin, or a property a declaration reads. + pub rels: BTreeSet, +} + +/// A reactor read once for hosted mode (a single pom is a reactor of +/// one, with the parent poms it inherits from inside the checkout): the +/// rewriter plans every patch of a run over it, and discovery reads every +/// pin from it, each pom parsed once. A plan rewrites it in place, so the +/// next patch is planned over what the last one wrote. +pub struct HostedReactor { + reactor: Reactor, +} + +/// Why a plan is refused: the reason word, and the line. +type Refused = (String, String); + +fn refused(reason: &str, detail: impl Into) -> Refused { + (reason.to_string(), detail.into()) +} + +impl HostedReactor { + /// Read the reactor rooted at `pom.xml`. Unlike vendored mode, a + /// module with a `.mvn` of its own is no refusal. + pub fn read(read: ReadFn<'_>, list: ListFn<'_>) -> Result { + Reactor::discover_for(read, list, true).map(|reactor| HostedReactor { reactor }) + } + + /// [`Self::read`] for finding the wiring a reactor carries, never for + /// planning over it: a module or a parent pom that cannot be found or + /// parsed is left out, and named in the second value. A reactor + /// discovery could not read whole still shows the pins of the poms it + /// could, so they can be listed and rolled back. + pub fn read_what_is_there( + read: ReadFn<'_>, + list: ListFn<'_>, + ) -> Result<(HostedReactor, Vec), JvmRefusal> { + let mut unread = Vec::new(); + let reactor = Reactor::discover_with(read, list, true, Some(&mut unread))?; + Ok((HostedReactor { reactor }, unread)) + } + + /// Every pom read: the reactor's modules, and each parent pom one + /// inherits from inside the checkout. + pub fn scope(&self) -> &[String] { + &self.reactor.scope + } + + /// The reactor's modules, the root first. + pub fn modules(&self) -> &[String] { + &self.reactor.reactor + } + + /// The text of the pom at `rel` as it reads now. + pub fn text(&self, rel: &str) -> Option<&str> { + self.reactor.poms.get(rel).map(|pom| pom.doc.text.as_str()) + } + + /// Take `text` for the pom at `rel` (a pom of the scope): what another + /// rewriter made of it since it was read. + pub fn set_text(&mut self, rel: &str, text: &str) -> Result<(), JvmRefusal> { + let pom = Pom::parse(rel, text.as_bytes().to_vec())?; + self.reactor.poms.insert(rel.to_string(), pom); + Ok(()) + } + + /// The artifacts the poms build at a Socket suffixed version, read as + /// Maven reads them (a `${...}` through the properties of the + /// declaring pom's chain), with the poms that name each. Declarations + /// inside `` are not read: Maven reads those only while + /// their profile is active. + pub fn sites(&self) -> Vec { + let reactor = &self.reactor; + let mut sites: BTreeMap<(String, String, String), Option> = BTreeMap::new(); + for rel in &reactor.scope { + let doc = &reactor.poms[rel].doc; + let resolve = |v: &str| reactor.interpolate(rel, v); + for dep in doc.declarations() { + if doc.section_of(dep).starts_with("profile:") || !doc.is_main_jar(dep) { + continue; + } + let (Some(group), Some(artifact), Some(version)) = ( + doc.coordinate(dep, "groupId", &resolve), + doc.coordinate(dep, "artifactId", &resolve), + doc.coordinate(dep, "version", &resolve), + ) else { + continue; + }; + if split_socket_version(&version).is_none() { + continue; + } + let uuid = doc.pin_at(dep).map(|pin| pin.uuid); + let tagged = sites.entry((group, artifact, version)).or_default(); + if tagged.is_none() { + *tagged = uuid; + } + } + } + sites + .into_iter() + .map(|((group, artifact, suffixed), uuid)| HostedSite { + rels: self.naming(&suffixed).into_iter().collect(), + group, + artifact, + suffixed, + uuid, + }) + .collect() + } + + /// Why `vex` must not attest the hosted patch `c` although the poms + /// wire it, as vendored mode weighs its own wiring: a declaration that + /// may still build the base version ([`unattestable_in`]), or a module + /// that resolves it (or may, by `selection`) and no pin or declaration + /// reaches ([`unwired_in`]). `None` when nothing does. + pub fn unattestable(&self, c: &Coords<'_>, selection: &MavenSelection) -> Option { + unattestable_in(&self.reactor, c).or_else(|| unwired_in(&self.reactor, c, selection)) + } + + /// The poms that name `version` outside comments. + fn naming(&self, version: &str) -> Vec { + let reactor = &self.reactor; + reactor + .scope + .iter() + .filter(|rel| reactor.poms[*rel].doc.masked.contains(version)) + .cloned() + .collect() + } + + /// Every `-socket.` the poms name outside comments. + fn generations(&self, base: &str) -> BTreeSet { + let prefix = format!("{base}-socket."); + let mut found = BTreeSet::new(); + for rel in &self.reactor.scope { + let masked = &self.reactor.poms[rel].doc.masked; + for (at, _) in masked.match_indices(&prefix) { + let hex8 = masked.get(at + prefix.len()..at + prefix.len() + 8); + if let Some(hex8) = hex8.filter(|h| { + h.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) { + found.insert(format!("{prefix}{hex8}")); + } + } + } + found + } + + /// Take `text` for `rel`, keeping what it held when the plan began. + fn replace( + &mut self, + rel: &str, + text: String, + before: &mut BTreeMap, + ) -> Result<(), Refused> { + let pom = Pom::parse(rel, text.into_bytes()).map_err(|refusal| { + refused( + "edit_not_reversible", + format!("{rel} would no longer read as a pom ({})", refusal.detail), + ) + })?; + if let Some(was) = self.reactor.poms.insert(rel.to_string(), pom) { + before.entry(rel.to_string()).or_insert(was.doc.text); + } + Ok(()) + } + + /// Plan the hosted wiring of the patch `c`, whole or not at all (the + /// module docs), and take it: the reactor then reads as the plan + /// leaves it. `selection` is what Maven selects in each module; `None` + /// reads as "cannot be told", which rewrites the declarations that + /// name the base version and pins nothing. A refused plan + /// ([`HostedPlan::refused`]) leaves the reactor as it was. + pub fn plan( + &mut self, + c: &Coords<'_>, + selection: Option<&MavenSelection>, + repository: &HostedRepository<'_>, + ) -> HostedPlan { + let mut plan = HostedPlan { + nested_mvn: self.reactor.nested_mvn.clone(), + ..HostedPlan::default() + }; + let mut before: BTreeMap = BTreeMap::new(); + if let Err(why) = self.plan_into(c, selection, repository, &mut plan, &mut before) { + for (rel, text) in &before { + // It was read from this text. + let _ = self.set_text(rel, text); + } + return HostedPlan { + refused: Some(why), + notes: plan.notes, + nested_mvn: plan.nested_mvn, + ..HostedPlan::default() + }; + } + plan.poms = before + .iter() + .filter_map(|(rel, was)| { + let now = &self.reactor.poms[rel].doc.text; + (now != was).then(|| (rel.clone(), now.clone())) + }) + .collect(); + plan.edits.retain(|edit| plan.poms.contains_key(&edit.rel)); + plan + } + + fn plan_into( + &mut self, + c: &Coords<'_>, + selection: Option<&MavenSelection>, + repository: &HostedRepository<'_>, + plan: &mut HostedPlan, + before: &mut BTreeMap, + ) -> Result<(), Refused> { + let (g, a, base) = (c.group_id, c.artifact_id, c.version); + if !safe_coordinates(g, a, base) { + return Err(refused( + "unsafe_coordinates", + format!("unsafe maven coordinates `{g}:{a}:{base}`"), + )); + } + let patch = coords_patch(c); + let sv = c.suffixed_version(); + let unread; + let selection = match selection { + Some(selection) => selection, + None => { + unread = MavenSelection::unavailable("what Maven selects was not read"); + &unread + } + }; + // What the poms held before this plan rewrote anything. + let was_wired = self.reactor.wired_before(&patch); + let named_before = self.generations(base); + if let Standing::NotSelected(others) = selection.standing(g, a, base) { + if !was_wired { + plan.not_selected = Some(others); + return Ok(()); + } + } + + // The declarations that name the base version. + let mut warnings = Vec::new(); + let mut unpinned = BTreeSet::new(); + let mut managed_roots = BTreeSet::new(); + let rewritten: Vec<(String, String)> = { + let reactor = &self.reactor; + let mut edits: BTreeMap> = BTreeMap::new(); + let told = |rel: &str, dep: usize| { + reactor + .readers_select(rel, dep, selection, c) + .then(|| base.to_string()) + }; + for rel in &reactor.scope { + reactor.rewrite_declarations( + rel, + &patch, + &sv, + &mut edits, + &mut warnings, + &mut unpinned, + &mut managed_roots, + &mut BTreeSet::new(), + &told, + ); + } + forget_other_versions(&mut warnings, &reactor.under(selection, &patch, &|_| false)); + reactor + .settle_properties(edits, c, &mut plan.edits, &mut plan.notes) + .into_iter() + .filter(|(_, edits)| !edits.is_empty()) + .map(|(rel, edits)| { + let text = apply_edits(&reactor.poms[&rel].doc.text, edits); + (rel, text) + }) + .collect() + }; + for (rel, text) in rewritten { + self.replace(&rel, text, before)?; + } + + // The pins: where a module selects the base version and no + // declaration wires it yet. + let pinned: Vec<(String, String, HostedEditKind)> = { + let reactor = &self.reactor; + let under = reactor.under(selection, &patch, &|module| { + reactor.wired_without_pin(module, c) + }); + let closed = |rel: &String| unpinned.contains(rel) || managed_roots.contains(rel); + let kept = was_wired && !pin_moves(reactor, &patch, Some(&under)); + let (mut pins, mut held) = + place_pins(reactor, &patch, Some(&under), &closed, kept, &mut warnings); + // A patch the poms already wire keeps its pins where they are, + // and a module nothing reaches yet that is certain to select + // the base version is pinned all the same: a scan over a cold + // local repository wires what it can tell, and the next one, + // once the project was resolved, completes it. Nothing a pom + // already holds is moved by this. + if kept { + let unreached = + reactor.under(selection, &patch, &|module| reactor.covers(module, c)); + let (mut more, mut ignored, mut stranded) = + (BTreeSet::new(), BTreeSet::new(), Vec::new()); + for root in reactor.wired_roots() { + let mut placing = Placing { + under: &unreached, + patch: &patch, + pins: &mut more, + held: &mut ignored, + stranded: &mut stranded, + }; + reactor.place(&root, !closed(&root), &mut placing, 0); + } + held.retain(|rel| !more.contains(rel)); + pins.extend(more); + warnings.extend( + stranded + .into_iter() + .map(|detail| degraded("pin_would_move_module", detail)), + ); + warnings.extend(undetermined_note(&patch, &unreached)); + } + let mut pinned = Vec::new(); + for rel in &reactor.scope { + let doc = &reactor.poms[rel].doc; + let (wanted, held) = (pins.contains(rel), held.contains(rel)); + let (text, kind) = match pin_of(doc, &patch) { + Some(pin) if !wanted && !held => { + let gav = pin.gav.clone(); + let Some(text) = cut_pins(&doc.text, &|pin| pin.gav == gav) else { + continue; + }; + (text, HostedEditKind::PinRemoved) + } + Some(pin) if pin.uuid == c.uuid => continue, + Some(pin) => ( + apply_edits(&doc.text, vec![pin_update(doc, &pin, &patch)]), + HostedEditKind::PinMoved, + ), + None if wanted && !held => ( + apply_edits(&doc.text, vec![pin_edit(doc, &patch, &sv).0]), + HostedEditKind::Pin, + ), + None => continue, + }; + pinned.push((rel.clone(), text, kind)); + } + pinned + }; + for (rel, text, kind) in pinned { + self.replace(&rel, text, before)?; + plan.edits.push(HostedEdit::of(&rel, kind)); + } + + // No edit of a pom that the pom alone could not take back: such a + // pom is left as it was (its modules stay unpatched, and are named). + for (rel, was) in before.clone() { + let now = &self.reactor.poms[&rel].doc.text; + let undone = unwire_hosted(now, c, true, true); + if undone.is_ok() && undone == unwire_hosted(&was, c, true, true) { + continue; + } + // It was read from this text. + let _ = self.set_text(&rel, &was); + plan.edits.retain(|edit| edit.rel != rel); + plan.notes.push(( + "edit_not_reversible".to_string(), + format!( + "{rel}: the pin of {g}:{a}:{base} could not be removed again without a \ + trace (an empty or one-line , or a version that \ + cannot be recorded); {rel} was left as it is" + ), + )); + } + + // The repository follows the wiring: declared in the local root of + // every pom that names the suffixed version, and gone once none + // does. + let named = self.naming(&sv); + let mut removed: BTreeSet = BTreeSet::new(); + if named.is_empty() { + if named_before.contains(&sv) { + plan.unnamed = true; + removed.insert(c.uuid.to_string()); + } + } else { + let mut roots: Vec = Vec::new(); + for rel in &named { + let root = self.reactor.local_root(rel); + if !roots.contains(&root) { + roots.push(root); + } + } + for root in roots { + let text = self.reactor.poms[&root].doc.text.clone(); + let (text, kind) = match (repository.ensure)(&text) { + Ok(None) => continue, + Ok(Some(RepositoryEdit::Added(text))) => (text, HostedEditKind::Repository), + Ok(Some(RepositoryEdit::Refreshed(text))) => { + (text, HostedEditKind::RepositoryUrl) + } + Err(why) => { + return Err(refused( + "repository_unwritable", + format!( + "{root} cannot take the that serves {g}:{a}:{sv} \ + ({why}), and the poms below it would name a version nothing \ + serves" + ), + )) + } + }; + self.replace(&root, text, before)?; + plan.edits.push(HostedEdit { + repository: Some(c.uuid.to_string()), + ..HostedEdit::of(&root, kind) + }); + } + } + // An earlier patch of this version is gone once no pom of the + // reactor names its suffix: any pom, changed by this plan or not. + let named_after = self.generations(base); + plan.superseded = named_before + .difference(&named_after) + .filter(|old| **old != sv) + .cloned() + .collect(); + let suffix_named = |this: &HostedReactor, hex8: &str| { + let suffix = format!("-socket.{hex8}"); + this.reactor + .scope + .iter() + .any(|rel| this.reactor.poms[rel].doc.masked.contains(&suffix)) + }; + let mut gone: Vec<&str> = plan + .superseded + .iter() + .filter_map(|old| split_socket_version(old).map(|(_, hex8)| hex8)) + .filter(|hex8| !suffix_named(self, hex8)) + .collect(); + gone.dedup(); + for rel in self.reactor.scope.clone() { + let mut text = self.reactor.poms[&rel].doc.text.clone(); + let mut taken = Vec::new(); + for uuid in (repository.declared)(&text) { + let superseded = uuid != c.uuid && gone.iter().any(|hex8| uuid.starts_with(hex8)); + if !superseded && !removed.contains(&uuid) { + continue; + } + match (repository.remove)(&text, &uuid) { + Some(next) => { + text = next; + taken.push(uuid); + } + None if uuid == c.uuid => { + return Err(refused( + "repository_unwritable", + format!( + "{rel} declares the of {g}:{a}:{sv}, which no pom \ + names any more, in a form that cannot be taken out" + ), + )) + } + None => {} + } + } + if taken.is_empty() { + continue; + } + self.replace(&rel, text, before)?; + for uuid in taken { + removed.insert(uuid.clone()); + plan.edits.push(HostedEdit { + repository: Some(uuid), + ..HostedEdit::of(&rel, HostedEditKind::RepositoryRemoved) + }); + } + } + + // The plan as a whole: what names the patch is served and found, + // and what it first wired a rollback takes back exactly. + let wired = !named.is_empty() && self.reactor.wires(c); + if !named.is_empty() { + let found = self + .sites() + .into_iter() + .any(|site| site.group == g && site.artifact == a && site.suffixed == sv); + if !wired || !found { + return Err(refused( + "nothing_wired", + format!( + "{} would name {g}:{a}:{sv} only where Maven does not always read it \ + (inside ), so no build is certain to resolve it and a \ + rollback could not find it", + named.join(", ") + ), + )); + } + for rel in &named { + let root = self.reactor.local_root(rel); + let declared = (repository.declared)(&self.reactor.poms[&root].doc.text); + if !declared.iter().any(|uuid| uuid == c.uuid) { + return Err(refused( + "repository_unwritable", + format!( + "{rel} would name {g}:{a}:{sv} with no for it in {root}" + ), + )); + } + } + } + for (rel, was) in before.iter() { + let now = &self.reactor.poms[rel].doc.text; + if now == was { + continue; + } + let back = (repository.restored)(rel, now).map_err(|why| { + refused( + "edit_not_reversible", + format!("{rel} could not be rolled back once written ({why})"), + ) + })?; + // A pom this plan is the first to wire returns to its bytes. + let fresh = unwire_hosted(was, c, true, true).as_deref() == Ok(was.as_str()) + && !(repository.declared)(was) + .iter() + .any(|uuid| uuid == c.uuid || removed.contains(uuid)); + if fresh && back != *was { + return Err(refused( + "edit_not_reversible", + format!( + "a rollback would not return {rel} to the bytes it has now (a \ + or section in a shape that \ + cannot be told from the one written)" + ), + )); + } + } + plan.wired = wired; + plan.notes + .extend(warnings.into_iter().filter_map(|warning| { + let (reason, detail) = warning.detail.strip_prefix("reason: ")?.split_once(": ")?; + Some((reason.to_string(), detail.to_string())) + })); + Ok(()) + } +} + +/// `text` when it is one `${name}` reference and nothing else: the name. +fn sole_reference(text: &str) -> Option<&str> { + let name = text.trim().strip_prefix("${")?.strip_suffix('}')?; + (!name.is_empty() && !name.contains(['$', '{', '}'])).then_some(name) +} + +/// Whether `text` can be recorded in an XML comment and read back as it +/// is: no `--`, no markup, on one line. +fn recordable(text: &str) -> bool { + !text.is_empty() + && text.trim() == text + && !text.contains("--") + && !text.ends_with('-') + && !text.contains(['<', '>', '\n', '\r']) +} + +impl Reactor { + /// Whether `module` builds `c`'s suffixed version with no pin: from a + /// declaration it makes or inherits, or from the project's own + /// management nearest on its chain. A pin changes nothing for such a + /// module, so it has no say in where the pins go; one that a pin alone + /// wires still has, or a pin that came to move it would never be seen. + fn wired_without_pin(&self, module: &str, c: &Coords<'_>) -> bool { + let sv = c.suffixed_version(); + let resolve = |v: &str| self.interpolate(module, v); + let names = |doc: &Doc, dep: usize| { + doc.is_main_jar(dep) + && doc.pin_at(dep).is_none() + && doc.coordinate(dep, "groupId", &resolve).as_deref() == Some(c.group_id) + && doc.coordinate(dep, "artifactId", &resolve).as_deref() == Some(c.artifact_id) + }; + let reads = |doc: &Doc, dep: usize| doc.coordinate(dep, "version", &resolve); + let declared = self.chain(module).any(|p| { + let doc = &self.poms[p].doc; + doc.declarations().into_iter().any(|dep| { + doc.section_of(dep) == "dependencies" + && names(doc, dep) + && reads(doc, dep).as_deref() == Some(sv.as_str()) + }) + }); + declared + || self + .chain(module) + .find_map(|p| { + let doc = &self.poms[p].doc; + doc.declarations() + .into_iter() + .find(|&dep| doc.is_top_level_managed(dep) && names(doc, dep)) + .map(|dep| reads(doc, dep)) + }) + .flatten() + .as_deref() + == Some(sv.as_str()) + } + + /// Whether every reactor module that reads the declaration `dep` of + /// `rel` (the module itself, and each module inheriting its pom) + /// selects the base version of `c`: the declaration then reads it in + /// each, whatever defines its `${...}` version outside the checkout. + /// Only a declaration Maven always reads as the module's own direct + /// dependency is told this way: a managed entry, or one in a profile, + /// decides nothing on its own. + fn readers_select( + &self, + rel: &str, + dep: usize, + selection: &MavenSelection, + c: &Coords<'_>, + ) -> bool { + if self.poms[rel].doc.section_of(dep) != "dependencies" { + return false; + } + let mut readers = std::iter::once(rel) + .chain(self.inheritors(rel)) + .filter(|reader| self.reactor.iter().any(|module| module == reader)) + .peekable(); + readers.peek().is_some() + && readers.all(|reader| { + selection.verdict(reader, c.group_id, c.artifact_id, c.version) == Verdict::Selected + }) + } + + /// The one top-level `` entry of the scope that defines + /// `name`, when rewriting its value reaches the declarations that read + /// it and nothing else can redefine it: its pom, the span of its value + /// and the value (the base version, or an earlier patch's suffixed + /// one). `None` when a profile, the command line or the project model + /// defines the name too, or two poms do. + fn property_site(&self, name: &str, base: &str) -> Option<(String, Range)> { + if self.cli_props.contains_key(name) { + return None; + } + let mut site = None; + for rel in &self.scope { + let pom = &self.poms[rel]; + let in_profile = pom + .profile_props + .iter() + .any(|(_, props)| props.contains_key(name)); + if in_profile || self.model_ref(rel, name).is_some() { + return None; + } + let doc = &pom.doc; + let Some(properties) = doc.child(doc.project, "properties") else { + continue; + }; + let mut defined = doc.nodes[properties] + .children + .iter() + .copied() + .filter(|&n| doc.nodes[n].name == name); + let Some(node) = defined.next() else { + continue; + }; + let span = doc.value_span(node); + let literal = doc.text[span.clone()] == doc.text_of(node); + if defined.next().is_some() + || site.is_some() + || !literal + || !is_base_like(&doc.text[span.clone()], base) + { + return None; + } + site = Some((rel.clone(), span)); + } + site + } + + /// Decide how each `${...}` version among the planned version `edits` + /// is wired (the module docs): the property's own value where every + /// reference to it is one of these declarations, else the literal + /// suffixed version with the replaced text recorded beside it. The + /// edits to write, with what was done in `made` and what was not in + /// `notes`. + fn settle_properties( + &self, + mut edits: BTreeMap>, + c: &Coords<'_>, + made: &mut Vec, + notes: &mut Vec<(String, String)>, + ) -> BTreeMap> { + let sv = c.suffixed_version(); + let ga = format!("{}:{}", c.group_id, c.artifact_id); + // The versions that are one property reference, by its name. + let mut by_name: BTreeMap> = BTreeMap::new(); + for (rel, file_edits) in &edits { + let text = &self.poms[rel].doc.text; + for edit in file_edits { + if let Some(name) = sole_reference(&text[edit.start..edit.end]) { + *by_name + .entry(name.to_string()) + .or_default() + .entry(rel.clone()) + .or_default() += 1; + } + } + } + // A property only these declarations read is rewritten itself. + let mut rewritten: BTreeSet = BTreeSet::new(); + for (name, uses) in &by_name { + let reference = format!("${{{name}}}"); + let only_these = self.scope.iter().all(|rel| { + self.poms[rel].doc.text.matches(&reference).count() + == uses.get(rel).copied().unwrap_or(0) + }); + let Some((rel, span)) = self.property_site(name, c.version).filter(|_| only_these) + else { + continue; + }; + let was = self.poms[&rel].doc.text[span.clone()].to_string(); + edits + .entry(rel.clone()) + .or_default() + .push(Edit::plain(span.start, span.end, &sv)); + made.push(HostedEdit { + rel, + kind: HostedEditKind::Property, + original: (was == c.version).then_some(was), + property: Some(name.clone()), + repository: None, + }); + rewritten.insert(name.clone()); + } + for (rel, file_edits) in edits.iter_mut() { + let doc = &self.poms[rel].doc; + let mut kept = Vec::new(); + for edit in std::mem::take(file_edits) { + let Role::Version { original, .. } = &edit.role else { + kept.push(edit); + continue; + }; + let was = &doc.text[edit.start..edit.end]; + if sole_reference(was).is_some_and(|name| rewritten.contains(name)) { + continue; + } + let at = format!("{rel}:{}", doc.line_of(edit.start)); + if !was.contains("${") { + made.push(HostedEdit { + rel: rel.clone(), + kind: HostedEditKind::Version, + original: original.clone(), + property: None, + repository: None, + }); + kept.push(edit); + continue; + } + // The literal, with the text it replaces recorded right + // after the element. + let rest = &doc.masked[edit.end..]; + let close = rest.len() - rest.trim_start().len(); + let after = edit.end + close + "".len(); + let recorded = doc.text[after.min(doc.text.len())..].starts_with(ORIGINAL_TAG); + if original.is_none() + || !recordable(was) + || !rest[close..].starts_with("") + || recorded + { + notes.push(( + "property_unresolved".to_string(), + format!( + "{at}: {ga} version {was} cannot be replaced and recorded; left as \ + is, probably unpatched" + ), + )); + continue; + } + made.push(HostedEdit { + rel: rel.clone(), + kind: HostedEditKind::Version, + original: Some(was.to_string()), + property: None, + repository: None, + }); + kept.push(Edit::plain( + after, + after, + &format!("{ORIGINAL_TAG}{was}{COMMENT_CLOSE}"), + )); + kept.push(edit); + } + *file_edits = kept; + } + edits + } +} + +/// `text` without the pins `mine` accepts, each cut by its lines, and +/// without the `` section once those pins were all +/// it held; `None` when there is no such pin or `text` is not a pom. +fn cut_pins(text: &str, mine: &dyn Fn(&Pin) -> bool) -> Option { + let doc = Doc::parse(text.to_string()).ok()?; + let mut pins: Vec = doc + .declarations() + .into_iter() + .filter_map(|dep| doc.pin_at(dep)) + .filter(|pin| mine(pin)) + .collect(); + if pins.is_empty() { + return None; + } + pins.sort_by_key(|pin| std::cmp::Reverse(pin.start)); + let mut out = text.to_string(); + for pin in pins { + out.replace_range(pin.start..pin.end, ""); + } + Some(without_empty_management(&out).unwrap_or(out)) +} + +/// `text` without its top-level `` when that holds +/// one `` and no entry, comment or text at all: the section +/// a pin created, once the pin is cut. +fn without_empty_management(text: &str) -> Option { + let doc = Doc::parse(text.to_string()).ok()?; + let dm = doc.child(doc.project, "dependencyManagement")?; + let [deps] = doc.nodes[dm].children[..] else { + return None; + }; + let (dm, deps) = (&doc.nodes[dm], &doc.nodes[deps]); + let blank = |range: Range| text[range].trim().is_empty(); + if deps.name != "dependencies" + || deps.inner_start == deps.end + || !deps.children.is_empty() + || !blank(deps.inner_start..deps.inner_end) + || !blank(dm.inner_start..deps.start) + || !blank(deps.end..dm.inner_end) + { + return None; + } + let (start, end) = line_span(text, dm.start, dm.end); + Some(format!("{}{}", &text[..start], &text[end..])) +} + +/// `text` (one pom) without the hosted wiring of the patch `c` that +/// [`plan_hosted`] writes: its pin, a `${...}` version put back from the +/// comment that records it, and a property holding the suffixed version +/// back at the base version. `literals` also puts every other declaration +/// of the artifact at the suffixed version back at the base version: the +/// caller leaves them out for a pom an earlier release may have pinned, +/// whose own entry is told from a rewritten one by other means. +/// `any_patch` takes out the wiring of every patch of `c`'s version, not +/// `c`'s alone. The `` is not touched. +pub fn unwire_hosted( + text: &str, + c: &Coords<'_>, + any_patch: bool, + literals: bool, +) -> Result { + let gav = format!("{}:{}:{}", c.group_id, c.artifact_id, c.version); + let sv = c.suffixed_version(); + let ours = |version: &str| match any_patch { + true => version != c.version && is_base_like(version, c.version), + false => version == sv, + }; + let with_pins = cut_pins(text, &|pin| { + pin.gav == gav && (any_patch || pin.uuid == c.uuid) + }); + let text = with_pins.as_deref().unwrap_or(text); + let doc = Doc::parse(text.to_string())?; + let mut edits = Vec::new(); + for dep in doc.declarations() { + let Some(version) = doc.child(dep, "version") else { + continue; + }; + let named = |name: &str, want: &str| { + doc.child_text(dep, name) + .is_some_and(|text| text == want || text.contains("${")) + }; + if !ours(&doc.text_of(version)) + || !named("groupId", c.group_id) + || !named("artifactId", c.artifact_id) + { + continue; + } + let span = doc.value_span(version); + let after = doc.nodes[version].end; + let recorded = text[after..].strip_prefix(ORIGINAL_TAG).and_then(|rest| { + let len = rest.find(COMMENT_CLOSE)?; + Some(( + &rest[..len], + after + ORIGINAL_TAG.len() + len + COMMENT_CLOSE.len(), + )) + }); + match recorded { + Some((was, end)) => { + edits.push(Edit::plain(span.start, span.end, was)); + edits.push(Edit::plain(after, end, "")); + } + None if literals => edits.push(Edit::plain(span.start, span.end, c.version)), + None => {} + } + } + let models = + std::iter::once(doc.project).chain((0..doc.nodes.len()).filter(|&n| doc.is_profile(n))); + for model in models { + let Some(properties) = doc.child(model, "properties") else { + continue; + }; + for &property in &doc.nodes[properties].children { + let span = doc.value_span(property); + if ours(&doc.text[span.clone()]) { + edits.push(Edit::plain(span.start, span.end, c.version)); + } + } + } + Ok(apply_edits(text, edits)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs new file mode 100644 index 0000000000..63a0dde72c --- /dev/null +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/hosted/tests.rs @@ -0,0 +1,999 @@ +use super::*; + +const G: &str = "org.x"; +const A: &str = "victim"; +const BASE: &str = "1.10.0"; +const UUID: &str = "4d5e6f70-8192-4a3b-9c4d-5e6f708192a3"; +const SV: &str = "1.10.0-socket.4d5e6f70"; +const TAG: &str = ""; + +type Fs = BTreeMap; + +fn coords() -> Coords<'static> { + Coords { + group_id: G, + artifact_id: A, + version: BASE, + uuid: UUID, + } +} + +fn fs(files: &[(&str, &str)]) -> Fs { + files + .iter() + .map(|(rel, text)| (rel.to_string(), text.to_string())) + .collect() +} + +fn dep(artifact: &str, version: Option<&str>) -> String { + let version = version.map_or(String::new(), |v| format!("\n {v}")); + format!( + " \n {G}\n \ + {artifact}{version}\n \n" + ) +} + +/// The reactor root `t:root:1` over the modules `a` and `b`, with `body`. +fn root(body: &str) -> String { + format!( + "\n 4.0.0\n t\n \ + root\n 1\n \ + pom\n \n a\n \ + b\n \n{body}\n" + ) +} + +/// The module `name` of [`root`], declaring `deps`. +fn module(name: &str, deps: &str) -> String { + format!( + "\n 4.0.0\n \n \ + t\n root\n \ + 1\n \n {name}\n \ + \n{deps} \n\n" + ) +} + +/// A pom on its own (no modules, no parent in the checkout), with `body`. +fn single(body: &str) -> String { + format!( + "\n 4.0.0\n t\n \ + app\n 1\n{body}\n" + ) +} + +fn deps(list: &str) -> String { + format!(" \n{list} \n") +} + +fn properties(list: &[(&str, &str)]) -> String { + let entries: String = list + .iter() + .map(|(name, value)| format!(" <{name}>{value}\n")) + .collect(); + format!(" \n{entries} \n") +} + +/// What each module of `files` selects for the victim: its base version, +/// another one, or why it cannot be told; a module left out does not +/// resolve it. +fn selecting(files: &Fs, picks: &[(&str, Result<&str, &str>)]) -> MavenSelection { + let modules: Vec<&str> = files + .keys() + .map(String::as_str) + .filter(|rel| rel.ends_with("pom.xml")) + .collect(); + let picks: Vec<_> = picks + .iter() + .map(|(pom, pick)| (*pom, G, A, *pick)) + .collect(); + MavenSelection::answering(&modules, &picks) +} + +/// Where the grant serves the patch from. +const INDEX_URL: &str = + "https://patch.socket.dev/patch-registry/maven/tok/4d5e6f70-8192-4a3b-9c4d-5e6f708192a3/maven2"; + +fn reactor(files: &Fs) -> HostedReactor { + let read = |rel: &str| files.get(rel).map(|text| text.clone().into_bytes()); + let list = |dir: &str| { + let bytes: BTreeMap> = files + .iter() + .map(|(rel, text)| (rel.clone(), text.clone().into_bytes())) + .collect(); + crate::vendor::jvm::testing::list_of(&bytes, dir) + }; + HostedReactor::read(&read, &list).expect("a reactor") +} + +/// Whether `files` head a reactor, which is how a rollback reads them. +fn heads_reactor(files: &Fs) -> bool { + files.keys().filter(|rel| rel.ends_with("pom.xml")).count() > 1 +} + +/// The plan for `c` over `files`, with the hosted rewriter's own +/// repository edits and restore. +fn planned_for(files: &Fs, c: &Coords<'_>, selection: Option<&MavenSelection>) -> HostedPlan { + let index_url = INDEX_URL.replace(UUID, c.uuid); + crate::patch::redirect::with_hosted_repository( + c, + &index_url, + &BTreeMap::new(), + heads_reactor(files), + |repository| reactor(files).plan(c, selection, repository), + ) +} + +fn planned(files: &Fs, selection: Option<&MavenSelection>) -> HostedPlan { + planned_for(files, &coords(), selection) +} + +fn written(files: &Fs, plan: &HostedPlan) -> Fs { + let mut out = files.clone(); + out.extend(plan.poms.clone()); + out +} + +/// `files` as a rollback of the patch `c` leaves them: every pom through +/// the restore `rollback` runs. +fn rolled_back_for(files: &Fs, c: &Coords<'_>) -> Fs { + let index_url = INDEX_URL.replace(UUID, c.uuid); + let pin = crate::patch::redirect::upstream::maven::PinIn { + group: c.group_id, + artifact: c.artifact_id, + base: c.version, + uuid: c.uuid, + reactor: heads_reactor(files), + }; + let hosted_uuid = |url: &str| (url == index_url).then(|| c.uuid.to_string()); + files + .iter() + .map(|(rel, text)| { + let done = crate::patch::redirect::upstream::maven::restore_pom( + rel, + text, + &BTreeMap::new(), + &pin, + &hosted_uuid, + ) + .unwrap_or_else(|why| panic!("{rel}: {why}")); + (rel.clone(), done.text) + }) + .collect() +} + +/// Every pom of `after` rolled back, which must be `before`. +fn assert_unwires_to(after: &Fs, before: &Fs) { + assert_eq!(&rolled_back_for(after, &coords()), before); +} + +/// THE INVARIANT, on poms as written: a pom names a `-socket.` +/// version only when a declaration Maven always reads resolves to it (so +/// discovery finds it, in every pom that names it) and its local root +/// declares the repository that serves it; and no pom declares a hosted +/// repository whose suffix no pom names. +fn assert_invariant(files: &Fs) { + let reactor = reactor(files); + let sites = reactor.sites(); + let repositories = |text: &str| -> Vec { + crate::patch::redirect::generation::named_generations(text) + .into_iter() + .collect() + }; + for (rel, text) in files { + let (masked, _) = super::super::mask(text); + for (at, _) in masked.match_indices("-socket.") { + let hex8 = &masked[at + 8..at + 16]; + let site = sites + .iter() + .find(|site| site.suffixed.ends_with(hex8) && site.rels.contains(rel)) + .unwrap_or_else(|| panic!("{rel} names -socket.{hex8}, which discovery cannot find: {sites:?}\n{text}")); + // The root of the chain: the last pom a child inherits from. + let served = files.iter().any(|(_, other)| { + repositories(other) + .iter() + .any(|uuid| uuid.starts_with(hex8)) + }); + assert!( + served, + "{rel} names {} with no repository for it", + site.suffixed + ); + } + for uuid in repositories(text) { + assert!( + sites.iter().any(|site| site.suffixed.ends_with(&uuid[..8])), + "{rel} declares the repository of {uuid}, which no pom names: {text}" + ); + } + } +} + +fn is_repository(kind: HostedEditKind) -> bool { + matches!( + kind, + HostedEditKind::Repository + | HostedEditKind::RepositoryUrl + | HostedEditKind::RepositoryRemoved + ) +} + +/// The pom edits of `plan`, the repository's apart ([`repositories`]). +fn kinds(plan: &HostedPlan) -> Vec<(&str, HostedEditKind)> { + plan.edits + .iter() + .filter(|edit| !is_repository(edit.kind)) + .map(|edit| (edit.rel.as_str(), edit.kind)) + .collect() +} + +fn repositories(plan: &HostedPlan) -> Vec<(&str, HostedEditKind)> { + plan.edits + .iter() + .filter(|edit| is_repository(edit.kind)) + .map(|edit| (edit.rel.as_str(), edit.kind)) + .collect() +} + +fn reasons(plan: &HostedPlan) -> Vec<&str> { + plan.notes + .iter() + .map(|(reason, _)| reason.as_str()) + .collect() +} + +/// Two modules reach the victim through other libraries: `a` resolves the +/// patch's version, `b` a newer one. The pin goes in `a` alone, so `b` +/// keeps what it resolves, and the repository goes in the root both +/// inherit. +#[test] +fn a_pin_goes_in_the_module_that_selects_the_version_and_no_other() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let selection = selecting( + &files, + &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok("1.11.0"))], + ); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("a/pom.xml", HostedEditKind::Pin)]); + assert!(plan.wired); + assert_eq!( + repositories(&plan), + [("pom.xml", HostedEditKind::Repository)] + ); + let a = &plan.poms["a/pom.xml"]; + assert!( + a.contains(&format!( + " \n \n {TAG}\n \n \ + {G}\n {A}\n \ + {SV}\n \n \n \ + \n " + )), + "{a}" + ); + let after = written(&files, &plan); + assert_unwires_to(&after, &files); + // A second run changes nothing, whatever it is told. + for told in [Some(&selection), None] { + let again = planned(&after, told); + assert!( + again.poms.is_empty() && again.edits.is_empty(), + "{:?}", + again.edits + ); + assert!(again.wired); + } +} + +/// Every module selects the version: one pin in the pom they all inherit. +#[test] +fn modules_that_all_select_the_version_are_pinned_in_their_parent() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let selection = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Pin)]); + assert_unwires_to(&written(&files, &plan), &files); +} + +/// A declaration that names the version is rewritten where it stands, and +/// a module it wires needs no pin: nothing but that one version changes. +#[test] +fn a_declaration_of_the_version_is_rewritten_and_needs_no_pin() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep(A, Some(BASE)))), + ("b/pom.xml", &module("b", &dep(A, Some("1.11.0")))), + ]); + let selection = selecting( + &files, + &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok("1.11.0"))], + ); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("a/pom.xml", HostedEditKind::Version)]); + assert_eq!(plan.edits[0].original.as_deref(), Some(BASE)); + assert_eq!( + plan.poms["a/pom.xml"], + files["a/pom.xml"].replace(BASE, SV), + "only the version text changes" + ); + assert_eq!( + repositories(&plan), + [("pom.xml", HostedEditKind::Repository)] + ); + assert!(reasons(&plan).is_empty(), "{:?}", plan.notes); + assert_unwires_to(&written(&files, &plan), &files); + // The declaration is rewritten whatever Maven selects elsewhere, since + // that replaces a version where it stands. + let unread = planned(&files, None); + assert_eq!(kinds(&unread), [("a/pom.xml", HostedEditKind::Version)]); +} + +/// A property only the patched artifact's declarations read is rewritten +/// itself: the declarations keep their `${...}` text. +#[test] +fn a_property_only_the_artifact_reads_is_rewritten_itself() { + let files = fs(&[ + ("pom.xml", &root(&properties(&[("victim.version", BASE)]))), + ( + "a/pom.xml", + &module("a", &dep(A, Some("${victim.version}"))), + ), + ( + "b/pom.xml", + &module("b", &dep(A, Some("${victim.version}"))), + ), + ]); + let selection = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Property)]); + assert_eq!(plan.edits[0].property.as_deref(), Some("victim.version")); + assert_eq!(plan.edits[0].original.as_deref(), Some(BASE)); + assert!( + plan.poms["pom.xml"].contains(&format!("{SV}")) + && !plan.poms.contains_key("a/pom.xml"), + "the property takes the version, the declarations keep their text" + ); + assert!(plan.wired); + let after = written(&files, &plan); + assert_unwires_to(&after, &files); + let again = planned(&after, Some(&selection)); + assert!(again.poms.is_empty() && again.wired, "{:?}", again.edits); +} + +/// A property a sibling artifact reads too is left alone: the one +/// declaration takes the literal, and the text it replaced is recorded +/// right after it. +#[test] +fn a_property_a_sibling_reads_is_left_alone() { + let shared = format!( + "{}{}", + dep(A, Some("${lib.version}")), + dep("sibling", Some("${lib.version}")) + ); + let files = fs(&[( + "pom.xml", + &single(&format!( + "{}{}", + properties(&[("lib.version", BASE)]), + deps(&shared) + )), + )]); + let selection = selecting(&files, &[("pom.xml", Ok(BASE))]); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Version)]); + assert_eq!(plan.edits[0].original.as_deref(), Some("${lib.version}")); + let pom = &plan.poms["pom.xml"]; + assert!( + pom.starts_with( + files["pom.xml"] + .replacen( + "${lib.version}", + &format!( + "{SV}" + ), + 1 + ) + .trim_end_matches("\n") + ), + "{pom}" + ); + assert!( + pom.contains("1.10.0") + && pom.contains( + "sibling\n ${lib.version}" + ), + "the property and the sibling are untouched: {pom}" + ); + let after = written(&files, &plan); + assert_unwires_to(&after, &files); + let again = planned(&after, Some(&selection)); + assert!(again.poms.is_empty() && again.wired, "{:?}", again.edits); +} + +/// A property no pom of the checkout defines (a parent resolved from a +/// repository does): what it reads is what Maven selects for the module +/// that declares it. Certain, the declaration takes the literal with its +/// text recorded; not certain, it is left as it is. +#[test] +fn a_property_of_a_parent_outside_the_checkout_follows_the_selection() { + let parent = + " \n corp\n parent\n \ + 7\n \n \n"; + let files = fs(&[( + "pom.xml", + &single(&format!( + "{parent}{}", + deps(&dep(A, Some("${corp.victim.version}"))) + )), + )]); + let plan = planned(&files, Some(&selecting(&files, &[("pom.xml", Ok(BASE))]))); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Version)]); + assert!( + plan.poms["pom.xml"].contains(&format!( + "{SV}" + )), + "{}", + plan.poms["pom.xml"] + ); + assert_unwires_to(&written(&files, &plan), &files); + + for doubt in [ + Some(selecting( + &files, + &[("pom.xml", Err("a pom is not cached"))], + )), + Some(selecting(&files, &[("pom.xml", Ok("1.11.0"))])), + None, + ] { + let plan = planned(&files, doubt.as_ref()); + assert!(plan.poms.is_empty() && !plan.wired, "{:?}", plan.edits); + if plan.not_selected.is_none() { + assert!( + reasons(&plan).contains(&"property_unresolved"), + "{:?}", + plan.notes + ); + } + } +} + +/// A version-less declaration a parent outside the checkout manages (the +/// usual Spring Boot shape): no declaration is touched, the pin goes in +/// the project's own management. +#[test] +fn a_version_managed_outside_the_checkout_is_pinned_not_rewritten() { + let files = fs(&[("pom.xml", &single(&deps(&dep(A, None))))]); + let plan = planned(&files, Some(&selecting(&files, &[("pom.xml", Ok(BASE))]))); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::Pin)]); + assert!(plan.wired); + assert_unwires_to(&written(&files, &plan), &files); +} + +/// No module of the build selects the version: nothing is planned, and +/// the plan says what is selected instead. +#[test] +fn a_version_no_module_selects_is_not_planned() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let selection = selecting( + &files, + &[("a/pom.xml", Ok("1.11.0")), ("b/pom.xml", Ok("1.9"))], + ); + let plan = planned(&files, Some(&selection)); + assert_eq!( + plan.not_selected, + Some(vec!["1.9".to_string(), "1.11.0".to_string()]) + ); + assert!(plan.poms.is_empty() && plan.edits.is_empty() && !plan.wired); +} + +/// A module whose selection cannot be told gets no pin (a pin there would +/// be a guess), and the one beside it that is certain still gets its own. +#[test] +fn an_undetermined_module_is_not_pinned_and_its_sibling_is() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let selection = selecting( + &files, + &[ + ("a/pom.xml", Ok(BASE)), + ("b/pom.xml", Err("lib-y:1.0 is not cached")), + ], + ); + let plan = planned(&files, Some(&selection)); + assert_eq!(kinds(&plan), [("a/pom.xml", HostedEditKind::Pin)]); + assert_eq!(reasons(&plan), ["selection_undetermined"]); + + // Told nothing at all, nothing is pinned. + let unread = planned(&files, None); + assert!( + unread.poms.is_empty() && !unread.wired, + "{:?}", + unread.edits + ); + assert_eq!(reasons(&unread), ["selection_undetermined"]); +} + +/// A scan over a cold local repository wires what it can tell; the next +/// one, once Maven has resolved the project, pins the module the first +/// could not, and moves nothing the first wrote. Told nothing new, it +/// writes nothing. +#[test] +fn a_later_scan_completes_what_an_earlier_one_could_not_tell() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep(A, Some(BASE)))), + ]); + let cold = selecting( + &files, + &[ + ("a/pom.xml", Err("lib-x:1.0 is not cached")), + ("b/pom.xml", Ok(BASE)), + ], + ); + let first = planned(&files, Some(&cold)); + assert_eq!(kinds(&first), [("b/pom.xml", HostedEditKind::Version)]); + assert_eq!(reasons(&first), ["selection_undetermined"]); + let after = written(&files, &first); + let again = planned( + &after, + Some(&selecting( + &after, + &[("a/pom.xml", Err("still")), ("b/pom.xml", Ok(BASE))], + )), + ); + assert!(again.poms.is_empty(), "{:?}", again.edits); + assert_eq!(reasons(&again), ["selection_undetermined"]); + + let warm = selecting(&after, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let second = planned(&after, Some(&warm)); + // (In the root: both modules select the version now.) + assert_eq!(kinds(&second), [("pom.xml", HostedEditKind::Pin)]); + assert!(reasons(&second).is_empty(), "{:?}", second.notes); + let done = written(&after, &second); + assert_unwires_to(&done, &files); + let third = planned(&done, Some(&warm)); + assert!(third.poms.is_empty() && third.wired, "{:?}", third.edits); +} + +/// A pin that now reaches a module resolving another version is taken out +/// again (it would hold that module back), leaving the pom as it was +/// before the pin. +#[test] +fn a_pin_that_would_move_a_module_is_taken_out() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let both = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let pinned = written(&files, &planned(&files, Some(&both))); + assert!(pinned["pom.xml"].contains(TAG)); + + let moved = selecting( + &pinned, + &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok("1.11.0"))], + ); + let plan = planned(&pinned, Some(&moved)); + assert_eq!( + kinds(&plan), + [ + ("pom.xml", HostedEditKind::PinRemoved), + ("a/pom.xml", HostedEditKind::Pin) + ] + ); + assert!( + !plan.poms["pom.xml"].contains(SV) && plan.poms["pom.xml"].contains(""), + "the pin goes from the root, the repository a still needs stays" + ); + let after = written(&pinned, &plan); + assert_invariant(&after); + assert_unwires_to(&after, &files); + + // No module selects the version any more: the last pin goes, and the + // repository with it, so nothing of the patch is left to roll back. + let none = selecting( + &after, + &[("a/pom.xml", Ok("1.11.0")), ("b/pom.xml", Ok("1.11.0"))], + ); + let plan = planned(&after, Some(&none)); + assert_eq!(kinds(&plan), [("a/pom.xml", HostedEditKind::PinRemoved)]); + assert_eq!( + repositories(&plan), + [("pom.xml", HostedEditKind::RepositoryRemoved)] + ); + assert!(plan.unnamed && !plan.wired); + assert_eq!(written(&after, &plan), files, "as before the first scan"); +} + +/// A pin of an earlier patch of the same version moves to this patch +/// where it stands. +#[test] +fn a_pin_of_an_earlier_patch_moves_to_this_one() { + let files = fs(&[("pom.xml", &single(&deps(&dep(A, None))))]); + let selection = selecting(&files, &[("pom.xml", Ok(BASE))]); + let pinned = written(&files, &planned(&files, Some(&selection))); + let earlier = fs(&[( + "pom.xml", + &pinned["pom.xml"] + .replace(UUID, "0a1b2c3d-8192-4a3b-9c4d-5e6f708192a3") + .replace(SV, "1.10.0-socket.0a1b2c3d"), + )]); + let plan = planned(&earlier, Some(&selection)); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::PinMoved)]); + assert_eq!( + repositories(&plan), + [ + ("pom.xml", HostedEditKind::Repository), + ("pom.xml", HostedEditKind::RepositoryRemoved) + ] + ); + assert_eq!(plan.superseded, ["1.10.0-socket.0a1b2c3d"]); + assert_eq!(plan.poms["pom.xml"], pinned["pom.xml"]); +} + +/// An edit that could not be taken back exactly is not made: a pin in a +/// `` that holds nothing would leave the section +/// changed (or gone) once removed. +#[test] +fn a_pin_that_could_not_be_removed_without_a_trace_is_not_written() { + for management in [ + " \n", + " \n", + " \n \n \n \ + \n", + ] { + let files = fs(&[( + "pom.xml", + &single(&format!("{management}{}", deps(&dep(A, None)))), + )]); + let plan = planned(&files, Some(&selecting(&files, &[("pom.xml", Ok(BASE))]))); + assert!( + plan.poms.is_empty() && !plan.wired, + "{management}: {:?}", + plan.poms + ); + assert_eq!(reasons(&plan), ["edit_not_reversible"], "{management}"); + } +} + +/// Unwiring takes out one patch's wiring and leaves another's, and leaves +/// a plain suffixed declaration to the caller when asked to. +#[test] +fn unwiring_takes_out_only_what_it_is_asked_for() { + let files = fs(&[( + "pom.xml", + &single(&format!( + "{}{}", + properties(&[("lib.version", BASE)]), + deps(&format!( + "{}{}", + dep(A, Some("${lib.version}")), + dep("sibling", Some("${lib.version}")) + )) + )), + )]); + let selection = selecting(&files, &[("pom.xml", Ok(BASE))]); + let after = written(&files, &planned(&files, Some(&selection))); + let other = Coords { + uuid: "0a1b2c3d-8192-4a3b-9c4d-5e6f708192a3", + ..coords() + }; + assert_eq!( + unwire_hosted(&after["pom.xml"], &other, false, true).as_deref(), + Ok(after["pom.xml"].as_str()) + ); + let unwired = unwire_hosted(&after["pom.xml"], &other, true, true).unwrap(); + assert!( + !unwired.contains(SV) + && !unwired.contains(ORIGINAL_TAG) + && unwired.matches("${lib.version}").count() == 2, + "{unwired}" + ); + + let literal = single(&deps(&dep(A, Some(SV)))); + assert_eq!( + unwire_hosted(&literal, &coords(), false, false).as_deref(), + Ok(literal.as_str()) + ); + assert_eq!( + unwire_hosted(&literal, &coords(), false, true), + Ok(literal.replace(SV, BASE)) + ); +} + +/// What the poms build at a suffixed version is found wherever it is +/// wired: a declaration, a property a declaration of another pom reads, +/// or a pin, which names its patch. +#[test] +fn the_wiring_of_a_reactor_is_found_in_every_pom_that_carries_it() { + let files = fs(&[ + ("pom.xml", &root(&properties(&[("victim.version", BASE)]))), + ( + "a/pom.xml", + &module("a", &dep(A, Some("${victim.version}"))), + ), + ("b/pom.xml", &module("b", &dep(A, Some(BASE)))), + ]); + let selection = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let after = written(&files, &planned(&files, Some(&selection))); + let sites = |files: &Fs| reactor(files).sites(); + let site = |uuid: Option<&str>, rels: &[&str]| HostedSite { + group: G.to_string(), + artifact: A.to_string(), + suffixed: SV.to_string(), + uuid: uuid.map(str::to_string), + rels: rels.iter().map(|rel| rel.to_string()).collect(), + }; + assert_eq!( + sites(&after), + [site(None, &["b/pom.xml", "pom.xml"])], + "the property in the root, the declaration in b: {after:#?}" + ); + assert!(sites(&files).is_empty()); + + let pinned = fs(&[("pom.xml", &single(&deps(&dep(A, None))))]); + let selection = selecting(&pinned, &[("pom.xml", Ok(BASE))]); + let pinned = written(&pinned, &planned(&pinned, Some(&selection))); + assert_eq!(sites(&pinned), [site(Some(UUID), &["pom.xml"])]); +} + +/// A declaration Maven reads only while a profile is active wires +/// nothing on its own: rewriting it would name a version no build is +/// certain to resolve and no discovery reads, with no repository to serve +/// it. The plan is refused whole, and the reactor is as it was read. +#[test] +fn a_declaration_only_a_profile_holds_is_not_rewritten_alone() { + let profiled = format!( + "\n 4.0.0\n \n t\n \ + root\n 1\n \n \ + a\n \n \n extra\n \ + \n {} \n \n \n\n", + dep(A, Some(BASE)) + ); + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &profiled), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + for selection in [None, Some(selecting(&files, &[("b/pom.xml", Err("cold"))]))] { + let mut reactor = reactor(&files); + let plan = crate::patch::redirect::with_hosted_repository( + &coords(), + INDEX_URL, + &BTreeMap::new(), + true, + |repository| reactor.plan(&coords(), selection.as_ref(), repository), + ); + assert_eq!( + plan.refused.as_ref().map(|(reason, _)| reason.as_str()), + Some("nothing_wired"), + "{:?}", + plan.notes + ); + assert!(plan.poms.is_empty() && plan.edits.is_empty() && !plan.wired); + for (rel, text) in &files { + assert_eq!( + reactor.text(rel), + Some(text.as_str()), + "{rel} is as it was read" + ); + } + } + // Beside a declaration Maven always reads, the profile's one is + // rewritten with it: the repository then serves both. + let both = fs(&[ + ("pom.xml", &root("")), + ( + "a/pom.xml", + &profiled.replace( + " ", + &format!("{} ", deps(&dep(A, Some(BASE)))), + ), + ), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let plan = planned(&both, None); + assert!(plan.wired && plan.refused.is_none(), "{:?}", plan.refused); + assert_eq!(plan.poms["a/pom.xml"].matches(SV).count(), 2); + let after = written(&both, &plan); + assert_invariant(&after); + assert_unwires_to(&after, &both); +} + +/// A plan is written whole or not at all. When the pom that must declare +/// the repository cannot take it, nothing is written: not the pin in the +/// module below, which would name a version nothing serves. +#[test] +fn a_plan_whose_repository_cannot_be_declared_writes_nothing() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep(A, Some(BASE)))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let selection = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let mut reactor = reactor(&files); + let plan = crate::patch::redirect::with_hosted_repository( + &coords(), + INDEX_URL, + &BTreeMap::new(), + true, + |real| { + let unreadable = HostedRepository { + ensure: &|_| Err("not readable as a pom".to_string()), + remove: real.remove, + declared: real.declared, + restored: real.restored, + }; + reactor.plan(&coords(), Some(&selection), &unreadable) + }, + ); + assert_eq!( + plan.refused.as_ref().map(|(reason, _)| reason.as_str()), + Some("repository_unwritable") + ); + assert!(plan.poms.is_empty() && plan.edits.is_empty() && !plan.wired); + for (rel, text) in &files { + assert_eq!( + reactor.text(rel), + Some(text.as_str()), + "{rel} is as it was read" + ); + } + + // A `` in a shape a rollback could not put back (a + // self-closed one is expanded to take the repository) refuses the + // plan the same way. + let self_closed = fs(&[ + ("pom.xml", &root(" \n")), + ("a/pom.xml", &module("a", &dep(A, Some(BASE)))), + ("b/pom.xml", &module("b", &dep("lib-y", Some("1.0")))), + ]); + let plan = planned(&self_closed, Some(&selection)); + assert_eq!( + plan.refused.as_ref().map(|(reason, _)| reason.as_str()), + Some("edit_not_reversible"), + "{:?}", + plan.poms + ); + assert!(plan.poms.is_empty()); +} + +/// An earlier patch's repository goes only once no pom of the reactor +/// names that patch's suffix: a pom this plan did not change counts. Here +/// module b still reads the earlier suffix through a property a profile +/// may redefine, which this plan leaves alone, while the pin moves on. +#[test] +fn an_earlier_patch_keeps_its_repository_while_any_pom_names_it() { + const EARLIER: &str = "0a1b2c3d-8192-4a3b-9c4d-5e6f708192a3"; + const EARLIER_SV: &str = "1.10.0-socket.0a1b2c3d"; + let earlier = Coords { + uuid: EARLIER, + ..coords() + }; + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep("lib-x", Some("1.0")))), + ( + "b/pom.xml", + &module("b", &dep(A, Some("${victim.version}"))).replace( + " ", + &format!( + "{} ", + properties(&[("victim.version", BASE)]) + ), + ), + ), + ]); + let selection = selecting(&files, &[("a/pom.xml", Ok(BASE)), ("b/pom.xml", Ok(BASE))]); + let first = planned_for(&files, &earlier, Some(&selection)); + assert!(first.wired, "{:?}", first.refused); + let mut wired = written(&files, &first); + assert!(wired["b/pom.xml"].contains(&format!("{EARLIER_SV}<"))); + assert!( + wired["pom.xml"].contains(EARLIER_SV), + "a is pinned, through the root: {:?}", + first.edits + ); + // b's property comes to be redefined by a profile: no later plan may + // rewrite it, since the profile's build must keep its own version. + let b = wired["b/pom.xml"].replace( + "", + " \n \n old\n \n \ + 1.9\n \n \n \ + \n", + ); + wired.insert("b/pom.xml".to_string(), b); + + // (b's declaration now rules the root out, so the pin is written + // afresh below it; what matters here is what becomes of the earlier + // patch's repository.) + let plan = planned(&wired, Some(&selection)); + assert!(plan.wired, "{:?}", plan.refused); + assert_eq!( + repositories(&plan), + [("pom.xml", HostedEditKind::Repository)] + ); + assert!( + plan.superseded.is_empty(), + "b still names it: {:?}", + plan.superseded + ); + let after = written(&wired, &plan); + assert!( + after["pom.xml"].contains(&format!("socket-patch-{EARLIER}")) + && after["pom.xml"].contains(&format!("socket-patch-{UUID}")), + "both repositories serve a pom: {}", + after["pom.xml"] + ); + assert!( + after["b/pom.xml"].contains(&format!("{EARLIER_SV}<")) + && after["a/pom.xml"].contains(SV), + "b keeps the version it reads, a moves on: {after:#?}" + ); + assert_invariant(&after); + + // Once b moves on too, the earlier repository goes with its last use. + let mut moved = after.clone(); + let b = moved["b/pom.xml"].replace(EARLIER_SV, SV); + moved.insert("b/pom.xml".to_string(), b); + moved.insert("pom.xml".to_string(), wired["pom.xml"].clone()); + let plan = planned(&moved, Some(&selection)); + assert_eq!(kinds(&plan), [("pom.xml", HostedEditKind::PinMoved)]); + assert_eq!(plan.superseded, [EARLIER_SV]); + let after = written(&moved, &plan); + assert!(!after["pom.xml"].contains(EARLIER), "{}", after["pom.xml"]); + assert_invariant(&after); +} + +/// One reactor is read once and planned over for every patch of a run: +/// the second patch is planned over what the first wrote. +#[test] +fn every_patch_of_a_run_is_planned_over_one_reactor() { + let files = fs(&[ + ("pom.xml", &root("")), + ("a/pom.xml", &module("a", &dep(A, Some(BASE)))), + ("b/pom.xml", &module("b", &dep("other", Some("2.0")))), + ]); + let other = Coords { + group_id: G, + artifact_id: "other", + version: "2.0", + uuid: "0a1b2c3d-8192-4a3b-9c4d-5e6f708192a3", + }; + let mut reactor = reactor(&files); + let mut all = files.clone(); + for c in [coords(), other] { + let index_url = INDEX_URL.replace(UUID, c.uuid); + let plan = crate::patch::redirect::with_hosted_repository( + &c, + &index_url, + &BTreeMap::new(), + true, + |repository| reactor.plan(&c, None, repository), + ); + assert!(plan.wired, "{:?}", plan.refused); + all.extend(plan.poms); + } + for (rel, text) in &all { + assert_eq!(reactor.text(rel), Some(text.as_str()), "{rel}"); + } + assert!( + all["pom.xml"].matches("").count() == 2 + && all["b/pom.xml"].contains("2.0-socket.0a1b2c3d") + ); + assert_invariant(&all); +} diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor/reader.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/reader.rs new file mode 100644 index 0000000000..8d1d0c6c8e --- /dev/null +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor/reader.rs @@ -0,0 +1,319 @@ +//! Reads the files of a reactor for a caller that reads a project its own +//! way (a disk, a snapshot of it, an in-memory project). +//! +//! The reactor planner reads through a synchronous function, and stops at +//! the first module pom it cannot find. A caller that learns from it which +//! files to fetch therefore learns one module at a time. [`read_reactor`] +//! walks the same files by itself instead: every pom is parsed once, each +//! pom's modules, parent and (for Maven 4) discovered subprojects are asked +//! for together, and a file that is not there stops nothing. The hosted +//! rewriter, its discovery and its restore all read a reactor through it, +//! so what one of them plans over is what the others find. + +use std::collections::{BTreeMap, BTreeSet}; +use std::future::Future; + +use super::{ + cli_properties, discovery_on, module_refs, normalize, pom_candidates, subprojects_in, Pom, + MAVEN_CONFIG, NESTED_MVN_FILES, +}; +use crate::vendor::jvm::layout::POM_FILE; +use crate::vendor::lock_inventory::ProjectView; + +/// How many files one reactor is read for: far more than any reactor +/// holds, so only a walk gone wrong stops here (the planner then refuses +/// the reactor for the module it cannot find). +const MAX_FILES: usize = 200_000; + +/// One thing the walk asks its caller for. +enum Wanted { + /// The text of a file. + File(String), + /// The subprojects Maven 4 discovers under a directory. + Subprojects(String), +} + +/// The walk: what was read so far, and what to read next. +struct Walk { + texts: BTreeMap, + /// Every path asked for, answered or not. + asked: BTreeSet, + /// The paths that are poms when they are there. + poms: BTreeSet, + /// `/pom.xml` → ``: a `` or `` may name + /// the pom file itself, which is tried once its directory reading has + /// no `pom.xml`. + named_file: BTreeMap, + wanted: Vec, + /// Maven 4 subproject discovery is on (`.mvn/maven.config` may turn it + /// off). + discovery: bool, + listed: BTreeSet, +} + +impl Walk { + fn new(root_pom: &str, maven_config: Option<&str>) -> Walk { + let mut walk = Walk { + texts: BTreeMap::new(), + asked: BTreeSet::from([POM_FILE.to_string(), MAVEN_CONFIG.to_string()]), + poms: BTreeSet::from([POM_FILE.to_string()]), + named_file: BTreeMap::new(), + wanted: Vec::new(), + discovery: discovery_on(&maven_config.map(cli_properties).unwrap_or_default()), + listed: BTreeSet::new(), + }; + if let Some(config) = maven_config { + walk.texts + .insert(MAVEN_CONFIG.to_string(), config.to_string()); + } + walk.supply(POM_FILE.to_string(), Some(root_pom.to_string())); + walk + } + + fn want(&mut self, rel: String) { + if self.asked.len() < MAX_FILES && self.asked.insert(rel.clone()) { + self.wanted.push(Wanted::File(rel)); + } + } + + /// Ask for the pom the normalized `path` names: `/pom.xml`, else + /// the file `path` itself. + fn want_pom(&mut self, path: String) { + let mut candidates = pom_candidates(path).into_iter(); + let Some(first) = candidates.next() else { + return; + }; + if let Some(file) = candidates.next() { + self.named_file.insert(first.clone(), file); + } + self.poms.insert(first.clone()); + self.want(first); + } + + /// The answer for `rel`: its text, or `None` when it is not there (or + /// cannot be read). + fn supply(&mut self, rel: String, text: Option) { + let Some(text) = text else { + if let Some(file) = self.named_file.remove(&rel) { + self.poms.insert(file.clone()); + self.want(file); + } + return; + }; + if self.poms.contains(&rel) { + self.follow(&rel, &text); + } + self.texts.insert(rel, text); + } + + /// Ask for what the pom at `rel` leads the planner to: its modules, + /// its parent in the checkout, the subprojects Maven 4 discovers under + /// it, and whether its directory has a `.mvn` of its own. A pom that + /// does not parse leads nowhere; the planner says so. + fn follow(&mut self, rel: &str, text: &str) { + let Ok(pom) = Pom::parse(rel, text.as_bytes().to_vec()) else { + return; + }; + for module in module_refs(&pom.doc) { + if module.is_empty() || module.contains("${") { + continue; + } + if let Some(path) = normalize(&pom.dir, &module) { + self.want_pom(path); + } + } + if self.discovery && pom.discovers_subprojects && self.listed.insert(pom.dir.clone()) { + self.wanted.push(Wanted::Subprojects(pom.dir.clone())); + } + if !pom.dir.is_empty() { + for file in NESTED_MVN_FILES { + self.want(format!("{}/.mvn/{file}", pom.dir)); + } + } + let relative = match &pom.parent { + None => None, + Some(parent) => match parent.relative_path.as_deref() { + Some("") => None, + Some(path) => Some(path), + None => Some("../pom.xml"), + }, + }; + if let Some(path) = relative.and_then(|path| normalize(&pom.dir, path)) { + self.want_pom(path); + } + } +} + +/// Every file the reactor planner reads for the project whose root pom is +/// `root_pom` (with `.mvn/maven.config` as `maven_config`), by +/// root-relative path: the root pom and the config themselves, the pom of +/// each module (theirs in turn), each parent pom a module inherits from +/// inside the checkout, the subprojects Maven 4 discovers, and the `.mvn` +/// files of a module directory (the planner asks whether they are there). +/// +/// `read` fetches one file as text, `None` when it is missing or not +/// readable; a path the walk asks for may be a directory. A file that is a +/// symbolic link is never read: hosted mode would replace the link with a +/// copy when it rewrote it, and the planner must not plan over a pom it +/// may not write. Its module then reads as missing, and the planner +/// refuses the reactor with nothing written. A subproject Maven 4 +/// discovers whose pom cannot be read is kept, empty, so the reactor is +/// refused the same way and not planned without it. +pub async fn read_reactor( + view: &ProjectView<'_>, + root_pom: &str, + maven_config: Option<&str>, + mut read: F, +) -> BTreeMap +where + F: FnMut(String) -> Fut, + Fut: Future>, +{ + let mut walk = Walk::new(root_pom, maven_config); + while let Some(wanted) = walk.wanted.pop() { + match wanted { + Wanted::File(rel) => { + let text = match view.is_symlink(&rel) { + true => None, + false => read(rel.clone()).await, + }; + walk.supply(rel, text); + } + Wanted::Subprojects(dir) => { + for name in subprojects_in(view, &dir).await { + let rel = match dir.as_str() { + "" => format!("{name}/{POM_FILE}"), + dir => format!("{dir}/{name}/{POM_FILE}"), + }; + if !walk.asked.insert(rel.clone()) { + continue; + } + let text = match view.is_symlink(&rel) { + true => None, + false => read(rel.clone()).await, + }; + walk.poms.insert(rel.clone()); + walk.supply(rel, Some(text.unwrap_or_default())); + } + } + } + } + walk.texts +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::vendor::lock_inventory::{MemoryEntry, MemoryProject}; + + fn pom(artifact: &str, body: &str) -> String { + format!( + "\n 4.0.0\n t\n \ + {artifact}\n 1\n{body}\n" + ) + } + + fn modules(names: &[String]) -> String { + let list: String = names + .iter() + .map(|name| format!(" {name}\n")) + .collect(); + format!(" pom\n \n{list} \n") + } + + /// Read the reactor of `project`, with every path `read` was asked. + async fn read(project: &MemoryProject) -> (BTreeMap, Vec) { + let view = ProjectView::Memory(project); + let root = match project.get("pom.xml") { + Some(MemoryEntry::Text(text)) => text.to_string(), + _ => panic!("no root pom"), + }; + let asked = std::cell::RefCell::new(Vec::new()); + let texts = read_reactor(&view, &root, None, |rel| { + asked.borrow_mut().push(rel.clone()); + let text = match project.get(&rel) { + Some(MemoryEntry::Text(text)) => Some(text.to_string()), + _ => None, + }; + async move { text } + }) + .await; + (texts, asked.into_inner()) + } + + /// A reactor of hundreds of modules, groups of them under their own + /// aggregator, is read whole, each file asked for once: the number of + /// modules bounds nothing, and no pom is fetched or parsed twice. + #[tokio::test] + async fn a_large_reactor_is_read_whole_and_each_file_once() { + let mut project = MemoryProject::new(); + let groups: Vec = (0..20).map(|g| format!("group-{g}")).collect(); + project.insert_text("pom.xml", pom("root", &modules(&groups)).as_str()); + let mut poms = vec!["pom.xml".to_string()]; + for group in &groups { + let members: Vec = (0..10).map(|m| format!("module-{m}")).collect(); + project.insert_text( + format!("{group}/pom.xml"), + pom(group, &modules(&members)).as_str(), + ); + poms.push(format!("{group}/pom.xml")); + for member in &members { + project.insert_text( + format!("{group}/{member}/pom.xml"), + pom(&format!("{group}-{member}"), "").as_str(), + ); + poms.push(format!("{group}/{member}/pom.xml")); + } + } + let (texts, asked) = read(&project).await; + assert_eq!(poms.len(), 221); + for rel in &poms { + assert!(texts.contains_key(rel), "{rel} was not read"); + } + let mut once = asked.clone(); + once.sort(); + once.dedup(); + assert_eq!(asked.len(), once.len(), "a path was asked for twice"); + // What the planner then reads from these files is the whole reactor. + let read = |rel: &str| texts.get(rel).map(|text| text.clone().into_bytes()); + let list = |dir: &str| crate::patch::redirect::gradle::key_list(&texts, dir); + let reactor = super::super::HostedReactor::read(&read, &list).expect("a reactor"); + assert_eq!(reactor.modules().len(), 221); + } + + /// A file that is not there stops nothing: its siblings are read all + /// the same. A module named by its pom file is read; a module pom that + /// is a symbolic link is not; a parent pom outside the module list is. + #[tokio::test] + async fn a_missing_or_linked_module_stops_nothing() { + let mut project = MemoryProject::new(); + let names: Vec = ["gone", "linked", "named/custom.xml", "kept"] + .map(str::to_string) + .into(); + project.insert_text("pom.xml", pom("root", &modules(&names)).as_str()); + project.insert("linked/pom.xml", MemoryEntry::Symlink); + project.insert_text("named/custom.xml", pom("named", "").as_str()); + project.insert_text( + "kept/pom.xml", + pom( + "kept", + " \n t\n base\n \ + 1\n ../base/pom.xml\n \ + \n", + ) + .as_str(), + ); + project.insert_text("base/pom.xml", pom("base", "").as_str()); + let (texts, _) = read(&project).await; + let read: Vec<&str> = texts.keys().map(String::as_str).collect(); + assert_eq!( + read, + [ + "base/pom.xml", + "kept/pom.xml", + "named/custom.xml", + "pom.xml" + ] + ); + } +} diff --git a/crates/socket-patch-core/src/vex/discover/maven.rs b/crates/socket-patch-core/src/vex/discover/maven.rs index df3d1126e9..3afbb9f21b 100644 --- a/crates/socket-patch-core/src/vex/discover/maven.rs +++ b/crates/socket-patch-core/src/vex/discover/maven.rs @@ -1,4 +1,5 @@ -//! Maven — the root `pom.xml`, plus `.mvn/maven.config` + +//! Maven — the root `pom.xml` (and, when it heads a reactor, every pom of +//! the reactor), plus `.mvn/maven.config` + //! `.mvn/checksums/checksums.sha256` for the hosted integrity pin. //! //! Maven has no lockfile: both Socket wirings live in `pom.xml`, and in both @@ -41,10 +42,14 @@ //! literal version wins over ``, so a managed Socket //! pin shadowed by a direct plain version (or a GA declared with several //! different effective versions) is diagnosed, not a ref. -//! A hosted pin in a reactor root (`` / ``) stays -//! a ref (rollback / remove find it) but marked unattested: a module's -//! own literal `` overrides it, and only the root pom is read here -//! (the rewriter refuses such roots, #261). A `${property}` version is +//! A reactor (`` / ``, or Maven 4 subproject +//! discovery) is read whole ([`extract_hosted_reactor`]): its pins sit in +//! the poms of the modules that select the patched version, and the patch +//! is attested only when every module that resolves the base version is +//! reached by one. A reactor whose poms cannot all be read falls back to +//! its root pom: a pin there stays a ref (rollback / remove find it) but +//! marked unattested, since a module's own literal `` overrides +//! it (#261). A `${property}` version is //! interpolated through every property it names (at most 16 deep; a cycle //! or an undefined name never resolves to a pin) twice: as the pom spells //! it (the root ``, what the rewriter writes and rolls back) @@ -136,9 +141,10 @@ //! (plugin classpaths) are not project resolution and are skipped silently; //! `` are only read when activated, so a Socket repository or pin //! there is diagnosed, never a ref (a profile that bypasses a live pin -//! withholds its attestation, [`bypasses`]). Submodule poms are not read, -//! and parent poms only for what they declare of a managed pin's GA -//! ([`Ancestors`]): a Socket repository or pin in one is not wiring here. +//! withholds its attestation, [`bypasses`]). Outside a reactor, submodule +//! poms are not read, and parent poms only for what they declare of a +//! managed pin's GA ([`Ancestors`]): a Socket repository or pin in one is +//! not wiring here. //! Gradle builds are discovered by //! `gradle.rs` (the hosted index) and the vendored JVM backend's own //! probes. @@ -210,21 +216,92 @@ pub(crate) async fn extract(ctx: &DiscoverCtx<'_>, out: &mut Discovery) { } let gas = live_gas(&pom.deps); - let reactor = crate::vendor::jvm::maven_reactor::declares_modules(&raw) - || (crate::vendor::jvm::maven_reactor::may_discover_subprojects(&raw, config.as_deref()) - && !crate::vendor::jvm::maven_reactor::implicit_subprojects_in(&ctx.view) - .await - .is_empty()); - extract_hosted( - ctx, - (&raw, &pom), - &gas, - &hosted, - reactor, - config.as_deref(), - out, - ) + // The project as the hosted rewriter reads it: every pom of a reactor, + // and each parent pom one inherits from inside the checkout. Hosted + // wiring may sit in any of them, so whenever there is more than the + // root pom they are read together. A pom of the reactor that cannot + // be read is left out: the pins of the others are still refs, and + // none is attested. Only a root pom the reactor reader cannot parse + // falls back to the single-pom reading below. + use crate::vendor::jvm::maven_reactor::{heads_reactor_in, read_reactor, HostedReactor}; + // A pom that is there but is not UTF-8 text is reported as unreadable + // (as the root pom is), and stands as a pom of the reactor that could + // not be read: it may hold a pin, or declare the base version. + let undecodable = std::sync::Mutex::new(Vec::new()); + let texts = read_reactor(&ctx.view, &raw, config.as_deref(), |rel| { + let undecodable = &undecodable; + async move { + match ctx.read_text_quiet(&rel).await { + Ok(text) => text, + Err(why) => { + undecodable + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push((rel, why)); + None + } + } + } + }) .await; + let mut undecodable = undecodable + .into_inner() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + undecodable.sort(); + for (rel, why) in &undecodable { + out.diag( + super::DIAG_LOCKFILE_UNREADABLE, + rel, + format!("cannot read {rel}: {why}"), + ); + } + let undecodable: Vec = undecodable + .into_iter() + .map(|(rel, _)| format!("{rel} is there but is not UTF-8 text")) + .collect(); + let heads_reactor = heads_reactor_in(&ctx.view, &raw, config.as_deref()).await; + let reactor = { + let read = |rel: &str| texts.get(rel).map(|text| text.clone().into_bytes()); + let list = |dir: &str| crate::patch::redirect::gradle::key_list(&texts, dir); + HostedReactor::read_what_is_there(&read, &list) + }; + match reactor { + Ok((reactor, unread)) if heads_reactor || reactor.scope().len() > 1 => { + // (The undecodable pom first: the reader below only knows that + // it found no pom there.) + let unread: Vec = undecodable.iter().cloned().chain(unread).collect(); + extract_hosted_reactor( + ctx, + (&reactor, &unread), + &texts, + config.as_deref(), + &user_properties, + &hosted, + out, + ) + .await; + } + reactor => { + let unread = reactor.err().filter(|_| heads_reactor).map(|refusal| { + refusal + .detail + .strip_prefix("reason: ") + .unwrap_or(&refusal.detail) + .to_string() + }); + let unread = undecodable.first().cloned().or(unread); + extract_hosted( + ctx, + (&raw, &pom), + &gas, + &hosted, + unread.as_deref(), + config.as_deref(), + out, + ) + .await; + } + } if !vendored.is_empty() { extract_vendored(ctx, &pom.deps, &vendored, out).await; } @@ -237,7 +314,7 @@ async fn extract_hosted( (raw, pom): (&str, &Pom), gas: &BTreeSet<(String, String)>, hosted: &BTreeMap, - reactor: bool, + unread_reactor: Option<&str>, config: Option<&str>, out: &mut Discovery, ) { @@ -376,19 +453,20 @@ async fn extract_hosted( .await; match candidates.as_slice() { [uuid] => { - // A reactor root's pin stays a ref (rollback, remove and - // list must still find it) but is never attested: a - // module's own , unread here, overrides it (#261). - if reactor { + // The pin of a reactor root whose modules cannot be read + // stays a ref (rollback, remove and list must still find + // it) but is never attested: a module's own , + // unread here, overrides it (#261). + if let Some(why) = unread_reactor { out.unattested( &purl, uuid, POM, format!( "{POM} heads a multi-module reactor (/, or \ - Maven 4 subproject discovery), and a module's own \ - of {ga} overrides this root pin; hosted mode reads only \ - the root pom (re-patch the reactor with `scan --mode vendored`)" + Maven 4 subproject discovery) whose poms cannot all be read \ + ({why}), and a module's own of {ga} overrides this root \ + pin" ), UnattestedKind::MavenReactorRoot, ); @@ -511,6 +589,252 @@ async fn extract_hosted( } } +// ── hosted, in a reactor ───────────────────────────────────────────────── + +/// The hosted pins of a reactor, or of a single pom that inherits from a +/// parent pom inside the checkout (the reactor planner's wiring, +/// `HostedReactor::plan`): read from every pom the planner reads, since a +/// pin sits in the pom of the modules that select the patched version, a +/// declaration is rewritten where it stands, and a `${property}` version +/// may be wired through the property in another pom. The `` (in the local +/// root a wired pom inherits from) names the patch uuid; a pin's comment +/// names it too, and any other suffixed version is tied to it by its +/// 8-hex suffix, as in a single pom. +/// +/// Every pom that carries part of the wiring is a ref's file (rollback and +/// remove undo each). The patch is attested only when every module that +/// resolves the base version, or may, is reached by a pin or a declaration +/// of the patch, and no declaration may still build the base version +/// ([`HostedReactor::unattestable`](crate::vendor::jvm::maven_reactor::HostedReactor::unattestable), +/// the rule vendored mode attests by). What Maven selects is read from the +/// local Maven repository, on disk only: in memory, a module the wiring +/// does not reach withholds the attestation. +async fn extract_hosted_reactor( + ctx: &DiscoverCtx<'_>, + (reactor, unread): (&crate::vendor::jvm::maven_reactor::HostedReactor, &[String]), + texts: &BTreeMap, + config: Option<&str>, + user_properties: &BTreeMap, + root_hosted: &BTreeMap, + out: &mut Discovery, +) { + use crate::crawlers::maven_selection::MavenSelection; + + // uuid -> its repository's url, and the poms that declare it. + let mut hosted: BTreeMap)> = root_hosted + .iter() + .map(|(uuid, url)| { + ( + uuid.clone(), + (url.clone(), BTreeSet::from([POM.to_string()])), + ) + }) + .collect(); + for rel in reactor.scope().iter().filter(|rel| *rel != POM) { + let Some(Ok(pom)) = texts + .get(rel) + .map(|text| parse_pom_with(text, user_properties)) + else { + continue; + }; + for repo in pom.repos.iter().filter(|repo| !repo.in_profile) { + let named = socket_patch_name_uuid(&repo.id, false); + let Some(uuid) = ctx + .hosted_uuid(&repo.url) + .filter(|uuid| named.as_deref() == Some(uuid.as_str())) + else { + continue; + }; + hosted + .entry(uuid) + .or_insert_with(|| (repo.url.clone(), BTreeSet::new())) + .1 + .insert(rel.clone()); + } + } + + let sites = reactor.sites(); + // uuid -> the (purl, g, a, suffixed version, poms) pins that tie to it. + type Tie = (String, String, String, String, BTreeSet); + let mut ties: BTreeMap> = BTreeMap::new(); + for site in sites { + let ga = format!("{}:{}", site.group, site.artifact); + let (base, hex8) = + split_socket_version(&site.suffixed).expect("a site is at a suffixed version"); + let file = site.rels.iter().next().map_or(POM, String::as_str); + let candidates: Vec<&String> = match &site.uuid { + Some(uuid) => hosted.keys().filter(|hosted| *hosted == uuid).collect(), + None => hosted + .keys() + .filter(|uuid| uuid.starts_with(hex8)) + .collect(), + }; + let Some(purl) = maven_purl(&site.group, &site.artifact, base).filter(|_| { + is_maven_coordinate(&site.group) + && is_maven_coordinate(&site.artifact) + && is_maven_version_text(&site.suffixed) + }) else { + out.diag( + DIAG_REF_INVALID, + file, + format!( + "{file}: {ga} {} is not a usable Maven coordinate", + site.suffixed + ), + ); + continue; + }; + match candidates.as_slice() { + [uuid] => ties.entry((*uuid).clone()).or_default().push(( + purl, + site.group, + site.artifact, + site.suffixed, + site.rels, + )), + // A vendored pin (its comment names a patch no hosted + // repository serves), or one whose committed tree serves it: + // attributed through the vendor ledger. + [] if site.uuid.is_some() + || ctx + .exists(&format!( + "{}/{}", + layout::MAVEN2_TREE, + layout::artifact_path( + &site.group, + &site.artifact, + &site.suffixed, + None, + "jar" + ) + )) + .await => {} + [] => out.diag( + DIAG_REF_UNATTRIBUTABLE, + file, + format!( + "{file}: {ga} {} carries a Socket patch suffix but no \ + socket-patch- repository's uuid starts with {hex8}", + site.suffixed + ), + ), + several => out.diag( + DIAG_REF_UNATTRIBUTABLE, + file, + format!( + "{file}: {ga} {} matches several Socket patch \ + repositories ({}); the 8-hex suffix cannot tell which one serves it", + site.suffixed, + several + .iter() + .map(|uuid| uuid.as_str()) + .collect::>() + .join(", ") + ), + ), + } + } + + let mut checksums: Option> = None; + let mut selection: Option = None; + for (uuid, (url, declared_in)) in &hosted { + let file = declared_in.iter().next().map_or(POM, String::as_str); + let Some(pins) = ties.get(uuid) else { + out.diag( + DIAG_REF_UNATTRIBUTABLE, + file, + format!( + "{file}: repository socket-patch-{uuid} is tied to no dependency (no \ + of the reactor carries the -socket.{} suffix; a same-GAV \ + repository cannot be attributed to an artifact)", + &uuid[..8] + ), + ); + continue; + }; + let [(purl, group, artifact, pinned, wired_in)] = &pins[..] else { + let purls: Vec<&str> = pins.iter().map(|(purl, ..)| purl.as_str()).collect(); + out.diag( + DIAG_REF_UNATTRIBUTABLE, + file, + format!( + "{file}: repository socket-patch-{uuid} is pinned by several packages \ + ({}); a Socket patch repository serves exactly one artifact", + purls.join(", ") + ), + ); + continue; + }; + if checksums.is_none() { + // (The root pom is the one whose model declares the Maven.) + let root_pom = texts.get(POM).map(String::as_str).unwrap_or_default(); + checksums = Some(trusted_checksums(ctx, config, root_pom, out).await); + } + let jar = layout::artifact_path(group, artifact, pinned, None, "jar"); + let integrity = checksums + .as_ref() + .and_then(|c| c.get(&jar)) + .map(|hex| LockIntegrity::Sha256Hex(hex.clone())); + for rel in wired_in.iter().chain(declared_in).collect::>() { + out.push(PatchedRef::hosted( + purl.clone(), + uuid.clone(), + rel, + Some(url), + integrity.clone(), + false, + )); + } + // What each module selects, read once and only for a reactor that + // carries a hosted pin. + if selection.is_none() { + selection = Some(match ctx.view.disk_root() { + Some(root) => { + let root = root.to_path_buf(); + tokio::task::spawn_blocking(move || MavenSelection::for_project(&root)) + .await + .unwrap_or_else(|_| { + MavenSelection::unavailable("what Maven selects could not be read") + }) + } + None => MavenSelection::unavailable( + "the project is not on disk, so what Maven selects in each module is \ + not read", + ), + }); + } + let base = split_socket_version(pinned).map_or("", |(base, _)| base); + let coords = crate::vendor::jvm::Coords { + group_id: group, + artifact_id: artifact, + version: base, + uuid, + }; + // A pom that could not be read may declare the base version + // itself, whatever the others are wired to. + let why = match unread.first() { + Some(first) => Some(format!( + "a pom of it cannot be read ({first}), so whether that module builds \ + {group}:{artifact} unpatched is not known" + )), + None => reactor.unattestable(&coords, selection.as_ref().expect("read above")), + }; + if let Some(why) = why { + out.unattested( + purl, + uuid, + wired_in.iter().next().map_or(file, String::as_str), + format!( + "{POM} heads a multi-module reactor, and {why}; the build may resolve the \ + upstream jar there (re-run `scan`, or patch the reactor with `scan --mode \ + vendored`)" + ), + UnattestedKind::MavenReactorRoot, + ); + } + } +} + /// Whether the root pom itself declares `group:artifact`'s main jar among /// the `` Maven always reads, with a version or without. Its /// own declaration replaces any it would inherit, so a managed pin that @@ -1856,7 +2180,7 @@ mod tests { async fn unwired_rewriter_inputs_yield_nothing() { for case in [ "basic", - "property-version-warn", + "property-version", "version-mismatch-skip", "transitive-depmgmt", ] { @@ -2099,13 +2423,229 @@ mod tests { assert!(out.unattested.is_empty(), "{:?}", out.unattested); } + /// The reactor root `com.example:app:1.0.0` over the modules `a` and + /// `b`, carrying the hosted repository of `UUID_A`. + fn reactor_root(more: &str) -> String { + pom(&format!( + "pom\n\na\nb\n\ + \n{more}\n{}\n", + hosted_repo_a() + )) + } + + /// A module of [`reactor_root`] with `body`. + fn reactor_module(name: &str, body: &str) -> String { + format!( + "\n4.0.0\n\n\ + com.example\napp\n\ + 1.0.0\n\n{name}\n{body}\n" + ) + } + + fn sources(out: &Discovery) -> Vec { + let mut files: Vec = out + .refs + .iter() + .map(|r| r.source_file.to_string_lossy().replace('\\', "/")) + .collect(); + files.sort(); + files + } + + /// A reactor's pins are found where the reactor planner writes them: + /// a tagged pin in the pom of the module that selects the version, the + /// repository in the root. Each pom that carries part of the wiring is + /// a file of the ref, so rollback and remove undo every one. The patch + /// is attested while every module that resolves the version is reached. + #[tokio::test] + async fn hosted_pin_in_a_reactor_module_is_found_and_attested() { + let pin = format!( + "\n\n\n{}\n\n", + dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))) + ); + let p = Project::new(); + p.write("pom.xml", reactor_root("")); + p.write("a/pom.xml", reactor_module("a", &pin)); + p.write("b/pom.xml", reactor_module("b", "")); + let out = run(&p).await; + assert_eq!(sources(&out), ["a/pom.xml", "pom.xml"]); + assert!( + out.refs + .iter() + .all(|r| (r.purl.as_str(), r.uuid.as_str(), r.mode) + == (FX_PURL, UUID_A, WiringMode::Hosted)), + "{:?}", + out.refs + ); + assert!(out.unattested.is_empty(), "{:?}", out.unattested); + + // A module that declares the base version itself is not reached by + // the pin in its sibling: the patch is found, and not attested. + p.write( + "b/pom.xml", + reactor_module( + "b", + &format!( + "\n{}\n", + dep("org.slf4j", "slf4j-api", Some("1.7.36")) + ), + ), + ); + let out = run(&p).await; + assert_eq!(sources(&out), ["a/pom.xml", "pom.xml"]); + assert_eq!(out.unattested.len(), 1, "{:?}", out.unattested); + let u = &out.unattested[0]; + assert_eq!(u.kind, UnattestedKind::MavenReactorRoot); + assert!(u.detail.contains("b/pom.xml"), "{}", u.detail); + } + + /// A `${property}` version wired through the property is a pin of the + /// pom that defines it, read by the declarations of other poms; one + /// replaced by a recorded literal is a pin of its own pom. + #[tokio::test] + async fn hosted_property_pins_of_a_reactor_are_found() { + let declaring = |version: &str| { + reactor_module( + "a", + &format!( + "\n{}\n", + dep("org.slf4j", "slf4j-api", Some(version)) + ), + ) + }; + let p = Project::new(); + p.write( + "pom.xml", + reactor_root(&format!( + "\n{}\n\n", + suffixed(UUID_A) + )), + ); + p.write("a/pom.xml", declaring("${slf4j.version}")); + p.write("b/pom.xml", reactor_module("b", "")); + let out = run(&p).await; + assert_eq!(sources(&out), ["pom.xml"]); + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert!(out.unattested.is_empty(), "{:?}", out.unattested); + + let p = Project::new(); + p.write("pom.xml", reactor_root("")); + p.write( + "a/pom.xml", + declaring(&suffixed(UUID_A)).replace( + "", + "", + ), + ); + p.write("b/pom.xml", reactor_module("b", "")); + let out = run(&p).await; + assert_eq!(sources(&out), ["a/pom.xml", "pom.xml"]); + assert!(out.unattested.is_empty(), "{:?}", out.unattested); + } + + /// A single pom that inherits from a parent pom inside the checkout + /// (no ``) may be wired through that parent: the property + /// the declaration reads, and the repository, sit in the parent's pom. + /// Both poms are read, and the parent is a file of the ref, so + /// rollback and remove undo it there. + #[tokio::test] + async fn hosted_wiring_in_a_parent_pom_of_the_checkout_is_found() { + let p = Project::new(); + p.write( + "pom.xml", + format!( + "\n4.0.0\n\n\ + com.example\nparent\n\ + 1.0.0\nparent/pom.xml\n\ + \napp\n\n{}\n\ + \n", + dep("org.slf4j", "slf4j-api", Some("${slf4j.version}")) + ), + ); + p.write( + "parent/pom.xml", + format!( + "\n4.0.0\ncom.example\n\ + parent\n1.0.0\n\ + pom\n\n{}\n\ + \n\n{}\n\n", + suffixed(UUID_A), + hosted_repo_a() + ), + ); + let out = run(&p).await; + assert_eq!(sources(&out), ["parent/pom.xml"]); + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + assert!(out.unattested.is_empty(), "{:?}", out.unattested); + } + + /// A reactor one of whose poms cannot be read is still read for the + /// pins of the others, which stay refs (rollback, remove and list find + /// them) and are not attested: the unread module may declare the base + /// version itself. + #[tokio::test] + async fn hosted_pins_of_a_reactor_with_an_unread_module_are_found_not_attested() { + let pin = format!( + "\n\n\n{}\n\n", + dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))) + ); + let p = Project::new(); + p.write("pom.xml", reactor_root("")); + p.write("a/pom.xml", reactor_module("a", &pin)); + // (b is listed and missing.) + let out = run(&p).await; + assert_eq!(sources(&out), ["a/pom.xml", "pom.xml"]); + assert_eq!(out.unattested.len(), 1, "{:?}", out.unattested); + assert_eq!(out.unattested[0].kind, UnattestedKind::MavenReactorRoot); + assert!( + out.unattested[0].detail.contains("b"), + "{}", + out.unattested[0].detail + ); + } + + /// A module pom that is there but is not UTF-8 text is not a missing + /// module: discovery says it cannot read the file, by name, and the + /// pins of the other poms are refs that are not attested, for that + /// reason and not for a pom the reactor "does not have". + #[tokio::test] + async fn an_undecodable_module_pom_is_reported_unreadable_not_missing() { + let pin = format!( + "\n\n\n{}\n\n", + dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))) + ); + let p = Project::new(); + p.write("pom.xml", reactor_root("")); + p.write("a/pom.xml", reactor_module("a", &pin)); + p.write("b/pom.xml", b"\xff\xfe"); + let out = run(&p).await; + assert_eq!(sources(&out), ["a/pom.xml", "pom.xml"]); + assert_eq!(diag_codes(&out), vec![DIAG_LOCKFILE_UNREADABLE]); + assert!( + out.diagnostics[0].detail.contains("b/pom.xml"), + "{:?}", + out.diagnostics + ); + assert_eq!(out.unattested.len(), 1, "{:?}", out.unattested); + let detail = &out.unattested[0].detail; + assert!( + detail.contains("b/pom.xml is there but is not UTF-8 text"), + "{detail}" + ); + assert!(!detail.contains("has no pom"), "{detail}"); + } + /// #1809: a Maven 4 (model 4.1.0) `pom`-packaged root listing no /// subprojects builds every direct subdirectory holding a `pom.xml`, - /// so its hosted pin is a reactor root's: kept as a ref, never - /// attested. A 4.0.0 model, no such subdirectory, or discovery turned - /// off in `.mvn/maven.config` leaves it a single pom, attested. + /// so its hosted pin is a reactor's: attested while the root's pin + /// reaches every subproject, and not once one declares the base + /// version itself. A 4.0.0 model, no such subdirectory, or discovery + /// turned off in `.mvn/maven.config` leaves it a single pom, attested. #[tokio::test] - async fn hosted_pin_in_a_maven_4_implicit_reactor_root_is_not_attested() { + async fn hosted_pin_in_a_maven_4_implicit_reactor_is_weighed_per_subproject() { let body = format!( "pom\n\n\n{}\n\n\n{}\n", dep("org.slf4j", "slf4j-api", Some(&suffixed(UUID_A))), @@ -2115,12 +2655,25 @@ mod tests { .replace("POM/4.0.0", "POM/4.1.0") .replace("4.0.0", "4.1.0"); let child = "\n4.1.0\n\nchild\n\n"; + let declaring = child.replace( + "", + &format!( + "\n\n{}", + dep("org.slf4j", "slf4j-api", Some("1.7.36")) + ), + ); let off = "-Dmaven.project.discoverSubprojects=false\n"; for (case, root, files, attested) in [ ( - "implicit reactor", + "implicit reactor the pin reaches", &model_4_1, &[("child/pom.xml", child)][..], + true, + ), + ( + "implicit reactor with its own version", + &model_4_1, + &[("child/pom.xml", declaring.as_str())][..], false, ), ("no subproject", &model_4_1, &[][..], true), diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index 07aaade056..5e88dc34f3 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -2303,6 +2303,31 @@ impl<'a> DiscoverCtx<'a> { self.ignored.contains(&rel) } + /// [`Self::read_text`] for a path that may be no file at all (one the + /// Maven reactor reader asks about: a module named by its directory, a + /// module's `.mvn` file): missing, or not a file that can be opened, it + /// is `Ok(None)` with no diagnostic. What is read is recognized and + /// logged all the same. A file that is there but is not UTF-8 text is + /// `Err`, with the reader's message: its content is unknown, which the + /// caller must say rather than take the file for absent. + pub(crate) async fn read_text_quiet(&self, rel: &str) -> Result, String> { + if self.is_ignored(rel) { + return Ok(None); + } + match self.view.read_text(rel).await { + Ok(text) => { + self.log_read(rel, true); + self.recognize_text(rel, &text); + Ok(Some(text)) + } + Err(e) if e.kind() == std::io::ErrorKind::InvalidData => { + self.log_read(rel, false); + Err(e.to_string()) + } + Err(_) => Ok(None), + } + } + /// Guarded UTF-8 read of root-relative `rel`: `None` when missing /// (silent) or unreadable ([`DIAG_LOCKFILE_UNREADABLE`] recorded). The /// content is swept for the Socket identities it mentions BEFORE any diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-edits.json new file mode 100644 index 0000000000..81f6e01732 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "build-parent/pom.xml", + "kind": "redirect_maven_property", + "action": "rewritten", + "key": "slf4j.version", + "original": "1.7.36", + "new": "1.7.36-socket.77777777" + }, + { + "path": "build-parent/pom.xml", + "kind": "redirect_maven_repository", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": { + "id": "socket-patch-77777777-7777-7777-7777-777777777777", + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2" + } + }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "trustedChecksums" + }, + { + "path": ".mvn/checksums/checksums.sha256", + "kind": "redirect_maven_trusted_checksums", + "action": "added" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-warnings.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/expected-edits.json rename to crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-warnings.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 0000000000..71c583f774 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/checksums/checksums.sha256 @@ -0,0 +1,2 @@ +cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar +dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.pom diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/maven.config new file mode 100644 index 0000000000..4f1f947e8c --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/build-parent/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/build-parent/pom.xml new file mode 100644 index 0000000000..0b02b2f633 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/build-parent/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + dev.socket.test + build-parent + 1.0.0 + pom + + 1.7.36-socket.77777777 + + + + socket-patch-77777777-7777-7777-7777-777777777777 + https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2 + + true + fail + + + false + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/build-parent/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/build-parent/pom.xml new file mode 100644 index 0000000000..5825154718 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/build-parent/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + dev.socket.test + build-parent + 1.0.0 + pom + + 1.7.36 + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/pom.xml new file mode 100644 index 0000000000..e54544a892 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/input/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + + dev.socket.test + build-parent + 1.0.0 + build-parent/pom.xml + + consumer + jar + + + org.slf4j + slf4j-api + ${slf4j.version} + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/overrides.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/overrides.json rename to crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/overrides.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-edits.json new file mode 100644 index 0000000000..fe51488c70 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-edits.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-warnings.json new file mode 100644 index 0000000000..3b7af7dfac --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/expected-warnings.json @@ -0,0 +1,3 @@ +[ + "redirect_maven_profile_dependency_unpatched" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/input/pom.xml new file mode 100644 index 0000000000..94d303f0ed --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/input/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + 1.7.36 + + + + slf4j-direct + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/overrides.json new file mode 100644 index 0000000000..53deb25b89 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-property-warn/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-edits.json new file mode 100644 index 0000000000..fe51488c70 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-edits.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-warnings.json new file mode 100644 index 0000000000..d999737674 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/expected-warnings.json @@ -0,0 +1,4 @@ +[ + "redirect_maven_dep_unpinned", + "redirect_maven_selection_undetermined" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/input/pom.xml new file mode 100644 index 0000000000..47b1f18f57 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/input/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + dev.socket.test + company-parent + 7 + + + consumer + 1.0.0 + jar + + + org.slf4j + slf4j-api + ${slf4j.version} + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/overrides.json new file mode 100644 index 0000000000..53deb25b89 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-external-parent-warn/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-edits.json new file mode 100644 index 0000000000..1233a9a57f --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "pom.xml", + "kind": "redirect_maven_dep_version", + "action": "rewritten", + "key": "org.slf4j:slf4j-api", + "original": "${slf4j.version}", + "new": "1.7.36-socket.77777777" + }, + { + "path": "pom.xml", + "kind": "redirect_maven_repository", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": { + "id": "socket-patch-77777777-7777-7777-7777-777777777777", + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2" + } + }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "trustedChecksums" + }, + { + "path": ".mvn/checksums/checksums.sha256", + "kind": "redirect_maven_trusted_checksums", + "action": "added" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-warnings.json new file mode 100644 index 0000000000..fe51488c70 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-warnings.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 0000000000..71c583f774 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/checksums/checksums.sha256 @@ -0,0 +1,2 @@ +cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar +dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.pom diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/maven.config new file mode 100644 index 0000000000..4f1f947e8c --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/pom.xml new file mode 100644 index 0000000000..fa05615f79 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + 1.7.36 + + + + org.slf4j + slf4j-api + 1.7.36-socket.77777777 + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + + + socket-patch-77777777-7777-7777-7777-777777777777 + https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2 + + true + fail + + + false + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/input/pom.xml new file mode 100644 index 0000000000..1efaf2e400 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/input/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + 1.7.36 + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/overrides.json new file mode 100644 index 0000000000..53deb25b89 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-edits.json new file mode 100644 index 0000000000..6e5939b9af --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "pom.xml", + "kind": "redirect_maven_property", + "action": "rewritten", + "key": "slf4j.version", + "original": "1.7.36", + "new": "1.7.36-socket.77777777" + }, + { + "path": "pom.xml", + "kind": "redirect_maven_repository", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": { + "id": "socket-patch-77777777-7777-7777-7777-777777777777", + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2" + } + }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "trustedChecksums" + }, + { + "path": ".mvn/checksums/checksums.sha256", + "kind": "redirect_maven_trusted_checksums", + "action": "added" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-warnings.json new file mode 100644 index 0000000000..fe51488c70 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-warnings.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 0000000000..71c583f774 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/checksums/checksums.sha256 @@ -0,0 +1,2 @@ +cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar +dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.pom diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/maven.config new file mode 100644 index 0000000000..4f1f947e8c --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/pom.xml new file mode 100644 index 0000000000..a5a6942dc2 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + 1.7.36-socket.77777777 + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + + socket-patch-77777777-7777-7777-7777-777777777777 + https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2 + + true + fail + + + false + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/input/pom.xml similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version-warn/input/pom.xml rename to crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/input/pom.xml diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/overrides.json new file mode 100644 index 0000000000..53deb25b89 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-edits.json new file mode 100644 index 0000000000..791f6cc837 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "app/pom.xml", + "kind": "redirect_maven_dep_version", + "action": "rewritten", + "key": "org.slf4j:slf4j-api", + "original": "1.7.36", + "new": "1.7.36-socket.77777777" + }, + { + "path": "pom.xml", + "kind": "redirect_maven_repository", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": { + "id": "socket-patch-77777777-7777-7777-7777-777777777777", + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2" + } + }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "trustedChecksums" + }, + { + "path": ".mvn/checksums/checksums.sha256", + "kind": "redirect_maven_trusted_checksums", + "action": "added" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-warnings.json new file mode 100644 index 0000000000..44c9e80ea1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-warnings.json @@ -0,0 +1,3 @@ +[ + "redirect_maven_selection_undetermined" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 0000000000..71c583f774 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/checksums/checksums.sha256 @@ -0,0 +1,2 @@ +cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar +dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.pom diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/maven.config new file mode 100644 index 0000000000..4f1f947e8c --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/app/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/app/pom.xml new file mode 100644 index 0000000000..38ddc0f432 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/app/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + dev.socket.test + reactor + 1.0.0 + + app + + + org.slf4j + slf4j-api + 1.7.36-socket.77777777 + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/pom.xml new file mode 100644 index 0000000000..15a36eec49 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + dev.socket.test + reactor + 1.0.0 + pom + + app + lib + + + + socket-patch-77777777-7777-7777-7777-777777777777 + https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2 + + true + fail + + + false + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/app/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/app/pom.xml new file mode 100644 index 0000000000..6384d6c609 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/app/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + dev.socket.test + reactor + 1.0.0 + + app + + + org.slf4j + slf4j-api + 1.7.36 + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/lib/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/lib/pom.xml new file mode 100644 index 0000000000..9ea023c121 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/lib/pom.xml @@ -0,0 +1,12 @@ + + + 4.0.0 + + dev.socket.test + reactor + 1.0.0 + + lib + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/pom.xml new file mode 100644 index 0000000000..da6f2b6e21 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/input/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + dev.socket.test + reactor + 1.0.0 + pom + + app + lib + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/overrides.json new file mode 100644 index 0000000000..53deb25b89 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-edits.json new file mode 100644 index 0000000000..6e5939b9af --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "pom.xml", + "kind": "redirect_maven_property", + "action": "rewritten", + "key": "slf4j.version", + "original": "1.7.36", + "new": "1.7.36-socket.77777777" + }, + { + "path": "pom.xml", + "kind": "redirect_maven_repository", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": { + "id": "socket-patch-77777777-7777-7777-7777-777777777777", + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2" + } + }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "trustedChecksums" + }, + { + "path": ".mvn/checksums/checksums.sha256", + "kind": "redirect_maven_trusted_checksums", + "action": "added" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-warnings.json new file mode 100644 index 0000000000..44c9e80ea1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-warnings.json @@ -0,0 +1,3 @@ +[ + "redirect_maven_selection_undetermined" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 0000000000..71c583f774 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/checksums/checksums.sha256 @@ -0,0 +1,2 @@ +cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar +dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.pom diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/maven.config new file mode 100644 index 0000000000..4f1f947e8c --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/pom.xml new file mode 100644 index 0000000000..69d1ba93a7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + dev.socket.test + reactor + 1.0.0 + pom + + 1.7.36-socket.77777777 + + + app + + + + socket-patch-77777777-7777-7777-7777-777777777777 + https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2 + + true + fail + + + false + + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/app/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/app/pom.xml new file mode 100644 index 0000000000..d707c3acb4 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/app/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + dev.socket.test + reactor + 1.0.0 + + app + + + org.slf4j + slf4j-api + ${slf4j.version} + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/pom.xml new file mode 100644 index 0000000000..c21ad09612 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/input/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + dev.socket.test + reactor + 1.0.0 + pom + + 1.7.36 + + + app + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/overrides.json new file mode 100644 index 0000000000..53deb25b89 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/overrides.json @@ -0,0 +1,28 @@ +[ + { + "ecosystem": "maven", + "name": "slf4j-api", + "namespace": "org.slf4j", + "version": "1.7.36", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch/maven/org.slf4j/slf4j-api/1.7.36/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/slf4j-api-1.7.36.jar", + "registryOverride": { + "kind": "maven2", + "indexUrl": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "identifiers": { + "name": "org.slf4j/slf4j-api", + "version": "1.7.36", + "mavenGroupId": "org.slf4j", + "mavenArtifactId": "slf4j-api", + "mavenSuffixedVersion": "1.7.36-socket.77777777", + "mavenPomSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + } + }, + "integrity": { + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "md5": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-maven.json b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-maven.json index 1cbe789682..9ba56a99f4 100644 --- a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-maven.json +++ b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-maven.json @@ -560,6 +560,22 @@ "elsewhere": [], "live_claims": [] }, + "redirect/maven/pom/parent-in-checkout/expected": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/parent-in-checkout/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, "redirect/maven/pom/plugin-dependency/expected": { "refs": [ { @@ -658,6 +674,14 @@ "elsewhere": [], "live_claims": [] }, + "redirect/maven/pom/profile-property-warn/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, "redirect/maven/pom/profile-repositories/expected": { "refs": [ { @@ -703,7 +727,200 @@ "elsewhere": [], "live_claims": [] }, - "redirect/maven/pom/property-version-warn/input": { + "redirect/maven/pom/property-external-parent-warn/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/property-shared-sibling/expected": { + "refs": [ + { + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "source_file": "pom.xml", + "artifact_rel": null, + "locked_integrity": null, + "integrity_required": false, + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "lockfile_basis_ok": true + } + ], + "diagnostics": [], + "recognized": [ + { + "uuid": "11111111-1111-1111-1111-111111111111", + "mode": "hosted", + "file": "pom.xml" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "pom.xml" + } + ], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [ + { + "mode": "hosted", + "uuid": "77777777-7777-7777-7777-777777777777", + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36" + } + ] + }, + "redirect/maven/pom/property-shared-sibling/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/property-version/expected": { + "refs": [ + { + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "source_file": "pom.xml", + "artifact_rel": null, + "locked_integrity": null, + "integrity_required": false, + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "lockfile_basis_ok": true + } + ], + "diagnostics": [], + "recognized": [ + { + "uuid": "11111111-1111-1111-1111-111111111111", + "mode": "hosted", + "file": "pom.xml" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "pom.xml" + } + ], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [ + { + "mode": "hosted", + "uuid": "77777777-7777-7777-7777-777777777777", + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36" + } + ] + }, + "redirect/maven/pom/property-version/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/reactor-module-literal/expected": { + "refs": [ + { + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "source_file": "app/pom.xml", + "artifact_rel": null, + "locked_integrity": null, + "integrity_required": false, + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "lockfile_basis_ok": true + }, + { + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "source_file": "pom.xml", + "artifact_rel": null, + "locked_integrity": null, + "integrity_required": false, + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "lockfile_basis_ok": true + } + ], + "diagnostics": [], + "recognized": [ + { + "uuid": "11111111-1111-1111-1111-111111111111", + "mode": "hosted", + "file": "pom.xml" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "app/pom.xml" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "pom.xml" + } + ], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [ + { + "mode": "hosted", + "uuid": "77777777-7777-7777-7777-777777777777", + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36" + } + ], + "unattested": [ + { + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", + "uuid": "77777777-7777-7777-7777-777777777777", + "file": "app/pom.xml", + "detail": "pom.xml heads a multi-module reactor, and a pom of it cannot be read (module_path_unresolvable: pom.xml: lib has no pom), so whether that module builds org.slf4j:slf4j-api unpatched is not known; the build may resolve the upstream jar there (re-run `scan`, or patch the reactor with `scan --mode vendored`)", + "kind": "MavenReactorRoot" + } + ] + }, + "redirect/maven/pom/reactor-module-literal/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/reactor-root-property/expected": { + "refs": [], + "diagnostics": [ + { + "code": "patched_ref_unattributable", + "file": "pom.xml", + "detail": "pom.xml: repository socket-patch-77777777-7777-7777-7777-777777777777 is tied to no dependency (no of the reactor carries the -socket.77777777 suffix; a same-GAV repository cannot be attributed to an artifact)" + } + ], + "recognized": [ + { + "uuid": "11111111-1111-1111-1111-111111111111", + "mode": "hosted", + "file": "pom.xml" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "pom.xml" + } + ], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/reactor-root-property/input": { "refs": [], "diagnostics": [], "recognized": [], diff --git a/docs/design/lock-model-divergences.md b/docs/design/lock-model-divergences.md index e79113a10a..d645efb335 100644 --- a/docs/design/lock-model-divergences.md +++ b/docs/design/lock-model-divergences.md @@ -29,7 +29,7 @@ follow from the install-tree decision. N11 was decided on 2026-11-05. | # | Question | Hosted today | Decision | |---|---|---|---| | J1 | Does a base-version Maven dependency declared in a `` block block attestation? | Warns, still pins the top level and counts the package as redirected (`patch/redirect/mod.rs` ~8744) | Vendored's rule: any profile declaration at the base version makes the ref unattested (fixed now in discovery), and the merged planner rewrites profile declarations in both modes. | -| J3 | Which Maven poms count? | Refuses a reactor root (~8572) | The reactor reader becomes the shared core, so hosted gains reactor support. | +| J3 | Which Maven poms count? | Reads every pom of a reactor through the vendored reactor planner (`maven_reactor::plan_hosted`); a reactor it cannot read is refused | The reactor reader becomes the shared core, so hosted gains reactor support. | | J12 | scala-cli | Guidance only (`patch/redirect/scala_guidance.rs`) | Back-port: hosted wires scala-cli through the merged planner (a same-GAV Socket repository instead of a suffixed version). | | P3 | Is a shadowed `pdm.lock` rewritten? | Only when it governs (`pdm_drives`, ~564) | Rewrite it like every other tree, per the install-tree decision. | | P4 | Are `-r` includes of `requirements.txt` rewritten? | Root file only (`patch/redirect/requirements.rs` ~208) | Follow includes, per the install-tree decision. An include outside the repository root stays bounded in workspace runs: never read or rewritten (owner, 2026-11-05; #2025 (draft)). | diff --git a/docs/ecosystems.md b/docs/ecosystems.md index b2854ac6c0..02a4f70d1d 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -964,9 +964,9 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: so a resolver that can't reach the Socket repo, or is handed different bytes, has nowhere to fall through to: the build **hard-fails** instead of silently resolving the unpatched upstream artifact. The ``'s `checksumPolicy=fail` still verifies - the transport-level `.jar.sha1` sidecar on top. A `${property}` version is refused - (`redirect_maven_dep_unpinned`) — a literal edit would break the property reference and - a depMgmt pin could strand sibling artifacts sharing the property. A literal version + the transport-level `.jar.sha1` sidecar on top. A `${property}` version is patched + without stranding an artifact that shares the property (see **Property versions** + below). A literal version that matches neither the base nor the suffixed value is skipped (`redirect_maven_dep_version_mismatch`). A `-socket.` literal left by an earlier hosted patch for the same release (the pom declares that patch's @@ -1023,13 +1023,59 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: to patch and is left out of an agent scan. Maven 4 builds, profiles that declare dependencies or management, relocations and dependency cycles are not modelled: the artifacts they touch count as not readable. -* **Multi-module reactors are vendored-only (hosted Maven).** Hosted mode reads only - the root `pom.xml`, and a module's own literal `` always beats a root - `` pin, so a root pin would leave that module on the unpatched - upstream jar. A root that declares `` or `` (directly or in a - profile) is therefore refused with `redirect_maven_multimodule_unsupported` (`pom.xml` and - `.mvn/` are left untouched and the dep is not counted as redirected); use `scan --mode vendored`, whose reactor planner rewrites each module's - declaration. `vex` likewise does not attest a hosted pin found in a reactor root. +* **Multi-module reactors (hosted Maven).** A root that declares `` or + `` (directly or in a profile, or a Maven 4 root whose subprojects Maven + discovers) is patched module by module, with pom edits only, by the planner vendored + mode uses. A declaration that names the patched version is rewritten where it stands, + in whichever pom holds it. The `` pin goes in the highest pom + whose modules all resolve the artifact at that version or not at all: the root when + the whole reactor agrees, else the modules that do, down to one module's own + `pom.xml`. A module that resolves another version is never reached and resolves what + it resolved before. Such a pin carries the comment vendored pins carry + (``), which is how a later run tells it from the + project's own management. The `` goes in the local root every wired pom + inherits (a module whose parent is not in the checkout gets its own), and the Trusted + Checksums stay in the project root's `.mvn/`, which Maven also reads when it is + started in a module directory or with `-f`; a module with a `.mvn` of its own is + reported (`redirect_maven_trusted_checksums_unenforced`), since a Maven started there + reads that one. A reactor one of whose poms cannot be read is left untouched + (`redirect_maven_multimodule_unsupported`, with the reason). A pom that is there but is + not UTF-8 text (re-saved as Latin-1 or UTF-16, say) is never taken for a missing one: + the scan refuses the run and names it (`candidate_file_unreadable`), `vex` reports it + as unreadable and attests no pin of that reactor, and `rollback` / `remove` change + nothing until it is UTF-8 again, since it may hold part of a pin. The plan for a patch is + written whole or not at all: a pom is never left naming a patched version without the + repository that serves it, its checksum lines, and wiring a rollback can find. So a + declaration only a `` holds is not rewritten on its own + (`redirect_maven_profile_dependency_unpatched`), and neither is anything when the pom + that must take the repository cannot (`redirect_maven_pom_unreadable`), or when a + rollback could not put a pom back exactly (`redirect_maven_edit_not_reversible`). When + a later scan takes out the last pin of a patch (the module it reached moved to another + version), the repository and the checksum lines go with it. `vex` attests the patch + only when every module that resolves the patched version, or may, is reached by a pin + or a declaration; otherwise it withholds the statement and names the module + (`vex_maven_reactor_root`). `rollback` and `remove` undo the wiring in every pom that + carries part of it, or in none, and restore each byte for byte. +* **Property versions (hosted Maven).** A declaration whose `` is a + `${property}` is patched in one of two ways, and neither moves another artifact. When + the reactor's own poms define the property once and nothing but declarations of the + patched artifact reads it, the property's value takes the patched version and the + declarations keep their text. Otherwise (a sibling artifact reads it too, a profile or + `.mvn/maven.config` may redefine it, or a parent pom outside the checkout defines it) + the one declaration takes the literal patched version, and the text it replaced is + recorded in a comment right after it: + `1.2-socket.0a1b2c3d`. + Rollback reads that comment back, so the declaration returns to its `${...}` text + exactly. Such a declaration no longer follows the property: bump the property and the + patched artifact stays where it is until the next `scan`. A property no pom of the + checkout defines is read from what Maven selects for the modules that read the + declaration; when that cannot be told (the parent pom is not in the local Maven + repository yet) the declaration is left as it is (`redirect_maven_dep_unpinned`). + A version-less declaration a parent or BOM manages needs no edit of its own: the + `` pin overrides the management. A single pom that inherits + from a parent pom inside the checkout is read together with it: a property that parent + defines is rewritten there, and the repository goes in the parent the pom inherits it + from; `list`, `vex`, `rollback` and `remove` read both poms. * **A parent pom can override a managed pin (hosted Maven).** For a dependency with no literal `` in the root pom (a transitive one, or one whose version a parent manages), hosted mode pins it in the root pom's ``