diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 0b8d58656..e0881876d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -402,7 +402,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Grant gate (additive).** A reference grant is the patch API's answer, and its fields are written into files the project commits. Each granted reference is therefore checked once, before anything is planned for it (no takeover, no artifact fetch, no rewriter sees one that fails): the patch uuid is a canonical lowercase uuid; the artifact URL and a registry override's index URL are `https` URLs of plain URL characters (no whitespace or control character, no quote, backslash, `$`, `{`, `}`, `<`, `>`, `&`, `#`, `;`, `|` or `^`; cargo's `sparse+` prefix is kept); `sha1` is 40 hex digits, `sha256` 64, `sha512` exactly one `sha512-` token, the Go hashes `h1:` hashes, the yarn berry checksum `/`, the cargo and gem checksums 64 hex digits; the package's name and version, and every identifier of a registry override, are in their ecosystem's coordinate grammar (letters, digits and that ecosystem's punctuation; Maven coordinates as the JVM backends accept them). A Maven grant's sha256 digests may also be spelled `sha256-…` / `sha256:…`: the pom, Gradle and sbt planners read those, and a digest that is still not 64 hex digits writes no checksum pin (`redirect_maven_trusted_checksums_invalid_hash`). An absent or empty optional field is not checked. A grant that fails is refused for that package only: a `skipped` event whose `errorCode` is `redirect_grant_malformed` and whose `reason` names the field (never its value), the same code and detail in `warnings[]`, nothing written for it, the rest of the run and the exit code unchanged. A plain-`http` artifact or index URL is refused the same way with `redirect_grant_insecure_url` (every later install would send the grant token in clear text), unless its origin is the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin (scheme, host and port) or a loopback address (`localhost`, `127.0.0.0/8`, `::1`). The in-memory engine applies the same gate; it has no configured origin. -The rewriter reads a fixed set of candidate files from the project root: the npm-family locks (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `shrinkwrap.yaml`, `yarn.lock`, plus `.yarnrc.yml` for the berry cache-config gate, `bun.lock` / `bun.lockb`, and `vlt-lock.json` with `vlt.json` and `node_modules/.vlt-lock.json` read only), `requirements.txt` / `uv.lock` / `Pipfile.lock` (pipfile-spec 6; see the Pipenv section below) / `poetry.lock` (every Poetry lock generation from 1.0 on — the 0.12 `[metadata.hashes]` layout is refused because that installer ignores URL sources; a Poetry < 1.4 writer additionally gets `redirect_poetry_stale_install_risk`, see `docs/testing/poetry-compatibility.md`) / `pdm.lock` (PDM lock formats `2` and `4.3`–`4.5.1`; the identity-losing `3.1` / `4.0`–`4.2` formats and unknown future formats are refused with `redirect_pdm_refused`, and a lock-format-`2` writer additionally gets `redirect_pdm_legacy_sync_required`, see `docs/testing/pdm-compatibility.md`; when `uv.lock` or `poetry.lock` sits beside it they drive and `pdm.lock` is left alone), `Cargo.toml` / `Cargo.lock` / `.cargo/config.toml` (plus the legacy extensionless `.cargo/config` — cargo reads that spelling in preference when both exist, so the managed `[registries.…]` block is written into whichever one is present; the hosted redirect is a `sparse+` registry, which cargo loads only from **1.68**, so `rust-toolchain.toml` / `rust-toolchain` are read too (never edited) and a project whose declared floor — the lowest `rust-version` of the root and the member manifests read here (a `rust-version.workspace = true` inheritor reads `[workspace.package]`), else the channel rustup picks from the root (the legacy `rust-toolchain` over `rust-toolchain.toml`; a dated `nightly-`/`beta-YYYY-MM-DD` maps to its release train) — is below 1.68 is refused `redirect_cargo_old_cargo` per crate (nothing written, an earlier run's pins left in place with the `rollback` that drops them named; `--mode vendored` builds on cargo 1.41+), while an undeclared or rolling-channel floor still redirects (toolchain files in ancestor directories are not read); **cargo also reads every workspace-member manifest** — the `[workspace] members` globs minus `exclude` — and every in-root path-dependency manifest, recursively, reached without crossing a symbolic link and never under `.socket/`, and pins the crate in each one that declares it, so those `/Cargo.toml` files can appear in `rewrittenFiles`. A crate is redirected only when every declaration pins and every other `Cargo.lock` package depending on it is a planned member: one a registry or git crate — or a path package outside the root or behind a link — also depends on is refused `redirect_cargo_transitive_dependents` (a pin reaches only the declarations it sits on), a crate no manifest declares keeps `redirect_cargo_toml_dep_not_found` with a transitive-only detail naming `--mode vendored`, a crate every declaration of which requires another version (no requirement accepts the patched version) is refused `redirect_cargo_toml_dep_unrewritable`, and so is a requirement that also matches another locked version of the crate — each a transactional skip, never recorded or attested. With NO `Cargo.lock` there is no resolved graph to ask, so the dependents question is answered from the manifests instead: a crate declared beside any other dependency — anything but a path dependency on a manifest this run also pins, or a `workspace = true` inheritor of a table it scans — or beside a workspace member this run did not read (a `members` glob, or a member outside the project or behind a symbolic link, which member discovery drops) is refused `redirect_cargo_lockless_dependents`, whose detail names the remedies (commit a lockfile, or `--mode vendored`); a project whose only dependency is the patched crate has nothing that could pull it in and still redirects. All-CRLF manifests, locks and configs are rewritten with CRLF kept (mixed endings keep refusing where the grammar does not match), and `remove` / rollback match the recorded fragments across a later CRLF↔LF checkout conversion), `composer.lock`, `nuget.config` / `packages.lock.json` (plus, v5.0 #353/#514, every lock a project under the root restores into: a member project's `packages.lock.json`, a per-project `packages..lock.json`, a literal `NuGetLockFilePath` — each pinned with the root config; a `NuGetLockFilePath` it cannot evaluate warns `redirect_nuget_lock_path_unresolved` and a project tree it cannot list warns `redirect_nuget_lock_unreadable`, both skipping the nuget redirect with nothing written), `Gemfile` / `Gemfile.lock`, `pom.xml` (+ `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` for maven Trusted Checksums merge, and, for a Gradle build, every settings, build, `buildSrc`, included-build, applied and plugin-source script, version catalog and lock file the script graph reaches, plus `gradle/verification-metadata.xml`, `gradle/wrapper/gradle-wrapper.properties` and the owned `.socket/gradle/` files), and the sbt build files (`socket-patch.sbt`, `socket-patch-vendor.sbt`, `build.sbt`, `project/build.properties`, `.sbtopts`, `.jvmopts`; `build.sbt.lock` and the Mill / scala-cli build files `build.mill`, `build.mill.yaml`, `build.sc`, `.mill-version`, `project.scala` for their presence only) — read, never edited; `socket-patch.sbt` is the only sbt file hosted mode writes (see **Hosted sbt** below). **npm-family flavor coverage**: package-lock / npm-shrinkwrap (a package the project patches itself with npm ≥ 12.1's native `npm patch` — a root `patchedDependencies` key, or the lock entry's `patched` record — is left on its registry entry in every npm lock, `redirect_npm_patched_dependency_skipped`), pnpm (root OR any nested `*/pnpm-lock.yaml`), yarn classic (a yarn 2+ install migrates a v1 `yarn.lock` and drops its pins, so a run whose v1 lock carries a hosted pin warns `redirect_yarn_classic_berry_migration_risk` — the hosted twin of the vendored `yarn_classic_berry_migration_risk` — unless the root `package.json`, read as advisory input, declares `"packageManager": "yarn@1…"`), **yarn berry** (the pin yarn writes for a root `resolutions` entry: the root `package.json` — edited only beside a berry `yarn.lock` — gains one `"@npm:": ""` selector per locked range (`redirect_yarn_berry_resolution` edits), and only that `yarn.lock` entry is re-keyed `"@"` with the same `resolution:` + `yarnBerry10c0` checksum (`redirect_yarn_berry_entry`), moved to yarn's key order; never an `npm:` locator, whose fetcher sends npm registry auth to the patch host, nor a tarball locator under an `npm:` key, which hardened mode rejects (YN0078). An older release's `npm:::__archiveUrl=` pin is still recognized and is re-pinned on the next run; rollback rebuilds the key from the selectors and drops them. Refused, nothing written: a user-authored `resolutions` entry for the package `redirect_yarn_berry_resolutions_conflict`, no root manifest `redirect_yarn_berry_manifest_missing`, a builtin `patch:` entry wrapping the same descriptor `redirect_yarn_berry_shared_descriptor`, an artifact URL yarn cannot fetch as a tarball `redirect_yarn_berry_artifact_url_unsupported`; cacheKey `10c0` and `.yarnrc.yml compressionLevel 0` gated by `redirect_yarn_berry_cache_unsupported`), and **bun** (text `bun.lock` lockfileVersion 0 to 3 — 0 is the `--save-text-lockfile` opt-in lock of Bun 1.1.39–1.1.45, 1 the 1.2–1.3 default, 2 the 1.4+ default, 3 what Bun 1.4+ writes when `package.json` has a nested override or a yarn-style path resolution (only the lock's head differs: its `overrides` object nests); all four emit one `packages` grammar, so the registry 4-tuple → URL 3-tuple rewrite is version-independent and the lock's own version line is kept. Any other or missing version, or a `packages` section outside bun's single-line grammar, is refused `redirect_bun_lock_unsupported` — the detail is the shared version gate's text (a newer version: update socket-patch, re-locking would reproduce it; no integer: re-lock with Bun ≥ 1.2), identical to the vendored refusal. A version-0 lock holding `workspace:` packages is refused `redirect_bun_workspace_unsupported` (its 2-tuple workspace grammar cannot keep the hosted tuple through a frozen install); the remedy is to delete `bun.lock` and re-run `bun install` with Bun ≥ 1.2, which writes lockfileVersion 1 (accepted). A plain in-place `bun install` bumps the version only when a workspace depends on another workspace (e.g. root → member — the shape the matrix measured); otherwise Bun 1.2.0 keeps version 0 and Bun 1.2.23+ fail to resolve, so the in-place bump is not the documented remedy. Bun lock version, grammar and workspace compatibility are checked before a vendored takeover, including during dry-run: these refusals preserve the existing lock, artifact and vendor ledger. Version-1 and version-2 workspace locks are rewritten, nested versions included. A granted dep with no rewritable entry warns `redirect_bun_entry_not_found` (or `redirect_bun_non_registry_entry_skipped` when the only same-version entry is a user URL / `file:` tarball, #497), a grant without a sha512 `redirect_bun_missing_sha512`; a CRLF lock keeps `\r\n` on the rewritten line, and a hosted URL left by an earlier grant of the same `name@version` is re-pinned in place. **Digest-less re-saves (Bun 1.1.39–1.3.9)**: every text-lock Bun below 1.3.10 re-saves a URL tuple WITHOUT its `sha512` whenever the lock is re-saved for another reason (`bun add`, `bun install` after a package.json or workspace change), leaving the 2-tuple `["name@", {meta}]` — the spec Bun installs from is intact. The CLI treats that spelling as its own wiring: a repeat hosted run counts the dep as redirected (no `redirect_bun_entry_not_found`) and HEALS the line back to the 3-tuple with the current `sha512`, recording the heal as a further `redirect_bun_lock_package` edit whose `original` is the 2-tuple (a stale URL is re-pinned from either spelling); `rollback`, scoped `rollback ` / `remove ` and the vendored takeover accept the digest-less spelling of a recorded `new` line (same key, spec and meta, only the trailing `"sha512-…"` missing) and restore the recorded original over it, so the chain always unwinds to the pristine registry line. Anything else — another uuid/token, another version, a re-laid meta object — is still drift. **Native `bun.lockb`**: when no text `bun.lock` exists, binary format versions 1, 2 and 3 are read and rewritten directly. Socket Patch does not invoke Bun or convert the project to a text lockfile. Exact matching package records are rewritten to hosted tarballs with the granted integrity, preserving dependency resolution IDs, workspace/dependency topology and unrelated package metadata; binary pointers and the package metadata hash are updated. Per-package `redirect_bun_lockb_package` snapshots support scoped rollback, repeat runs, superseding grants and hosted ↔ vendored takeover. A regular binary lock is discoverable even with no Bun runtime or `node_modules`; a dry run previews the same binary edits without writing them. A malformed, unreadable, unsupported or unverified binary structure is `redirect_bun_lockb_invalid` (exit 0, `redirected: 0`), and it refuses the npm rewrite before any takeover or sibling npm-family lock mutation. A symlinked binary write target is `redirect_symlinked_file_unsupported` (exit 1, including dry-run). `bun.lock` wins when both spellings exist. Binary-only projects do not receive `redirect_npm_no_lockfile`. Measured boundaries and the real-Bun matrix: `docs/testing/bun-compatibility.md`), and **vlt** (`vlt-lock.json` without `lockfileVersion`, `0` or `1`; see the vlt hosted-mode contract below). **Rush monorepos**: when `rush.json` is present the rewriter also reads `common/config/rush/pnpm-lock.yaml` and each `common/config/subspaces//pnpm-lock.yaml` (sorted for determinism) under their repo-relative keys and repoints them in place; editing them emits `redirect_rush_repo_state_stale` when the `repo-state.json` beside a rewritten lock exists (`common/config/rush/repo-state.json` for the common lock, `common/config/subspaces//repo-state.json` for a subspace lock; the `pnpmShrinkwrapHash` desync is refreshed by `rush update`, which the redirect survives), and `redirect_pnpm_trust_lockfile` carries the Rush pnpm >=11 install remedy (see the trust paragraph above). **maven** is fail-closed via version suffixing: a `mavenSuffixedVersion` + `mavenPomSha256` override pins the Socket-only `-socket.` by rewriting the literal `` (`redirect_maven_dep_version`) or adding a `` entry (`redirect_maven_dep_management_added`), plus optional Trusted Checksums (`redirect_maven_trusted_checksums`, conflicts as `redirect_maven_trusted_checksums_conflict`; when `.mvn/wrapper/maven-wrapper.properties` pins a Maven older than 3.9.4, which ignores those files, the additive warning `redirect_maven_trusted_checksums_unenforced`; a grant sha256 that is not 64 hex digits writes no checksum line, `redirect_maven_trusted_checksums_invalid_hash`); a `${property}` version is refused (`redirect_maven_dep_unpinned`), a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`; each such subdirectory's `pom.xml` is read for this, never edited) is refused whole with `redirect_maven_multimodule_unsupported`: `pom.xml` and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the pom pins it too), since a module's own literal `` would shadow a root pin (use `--mode vendored`; `vex` omits a hosted pin in a reactor root as `vex_maven_reactor_root`), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped, with nothing written, when a variant other than `sources` / `javadoc`, live or inside ``, may resolve any version but the suffixed pin — the patched release, another one, a `${property}` a profile moves, or no version in the pom once its classifier-keyed `` (a profile's too) is consulted — since `vex` would never attest that pin: `vex_maven_classifier_unpatched`), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`): when any version it may resolve — its own, or what its own profile's or any combination of profiles' `` make of it, read as `vex` reads it — is not the suffixed pin, the dep is refused with nothing written, since it overrides the pin whenever that profile is active and `vex` would never attest it (a profile `` entry only when management governs the pin, i.e. no live direct declaration carries a version); a versionless one takes the pin, and the dep is also skipped when a profile holds its only declaration, a `${property}` groupId / artifactId resolved from the pom's own `` before matching (one the pom does not define, which may be the patched GA and whose own version would then win, refuses the dep with nothing written: `redirect_maven_coordinate_unresolved`), and a `${property}` groupId / artifactId some profile's `` (or several profiles' together) redefine so that the declaration a pin would go into names another package, or another declaration names the GA's main jar at another version (or one of its executable classifier copies, a `test-jar` included), refuses the dep with nothing written too (`redirect_maven_profile_coordinates_unpatched`): `vex` would never attest that pin (`vex_maven_profile_unpatched`), and a pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). 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 refused (`redirect_maven_dep_unpinned`), a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`; each such subdirectory's `pom.xml` is read for this, never edited) is refused whole with `redirect_maven_multimodule_unsupported`: `pom.xml` and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the pom pins it too), since a module's own literal `` would shadow a root pin (use `--mode vendored`; `vex` omits a hosted pin in a reactor root as `vex_maven_reactor_root`), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped, with nothing written, when a variant other than `sources` / `javadoc`, live or inside ``, may resolve any version but the suffixed pin — the patched release, another one, a `${property}` a profile moves, or no version in the pom once its classifier-keyed `` (a profile's too) is consulted — since `vex` would never attest that pin: `vex_maven_classifier_unpatched`), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`): when any version it may resolve — its own, or what its own profile's or any combination of profiles' `` make of it, read as `vex` reads it — is not the suffixed pin, the dep is refused with nothing written, since it overrides the pin whenever that profile is active and `vex` would never attest it (a profile `` entry only when management governs the pin, i.e. no live direct declaration carries a version); a versionless one takes the pin, and the dep is also skipped when a profile holds its only declaration, a `${property}` groupId / artifactId resolved from the pom's own `` before matching (one the pom does not define, which may be the patched GA and whose own version would then win, refuses the dep with nothing written: `redirect_maven_coordinate_unresolved`), and a `${property}` groupId / artifactId some profile's `` (or several profiles' together) redefine so that the declaration a pin would go into names another package, or another declaration names the GA's main jar at another version (or one of its executable classifier copies, a `test-jar` included), refuses the dep with nothing written too (`redirect_maven_profile_coordinates_unpatched`): `vex` would never attest that pin (`vex_maven_profile_unpatched`), and a pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). A pin is written only where Maven selects the patch's base version already (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`): see [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). **gradle** (v5.0) is automated wiring, no longer a pasted snippet: the owned settings script `.socket/gradle/socket-patch.hosted.settings.gradle` with its index `.socket/gradle/hosted-index.tsv`, one apply line per build's settings file, every lock entry of the GA moved to the suffixed version, and the suffixed component in an existing `gradle/verification-metadata.xml`. A refused dep writes nothing and keeps `redirect_gradle_manual_snippet` as its fallback; same-GAV grants are refused (`redirect_gradle_same_gav_unsupported`). Rules, refusals and codes: [Gradle builds](#gradle-builds-v50). **Hosted sbt (v5.0, additive)**: an sbt build root (`project/build.properties` naming an `sbt.version`, 0.13.18 or later) is wired through ONE generated root file, `socket-patch.sbt` — no user file is edited. It pins every granted Maven patch build-wide (a `ThisBuild` `dependencyOverrides +=` of the Socket-only `-socket.` version plus a `file:` resolver over `.socket/sbt-hosted/maven2/`, moved ahead of the default repositories on sbt 0.13 / 1.x so an unreachable one never blocks it offline), downloads the pinned pom and jar there on the first sbt load (sha256-checked, gitignored by the file itself), and installs a load-time verifier that fails `update` when any project resolves another version or a pinned artifact whose bytes are not pinned. Edits: `redirect_sbt_pin` (added), `redirect_sbt_pin_updated` (an existing row replaced: same GA and base under a new uuid, or the same uuid with new served values; `original` names the previous uuid and version), `redirect_sbt_pin_rechecked` (an existing row re-verified after the build's dependencies changed: its dependency digest is recorded anew, `original`/`new` are `{deps}`). The load-time verifier also fails `update` when a project declares a pinned GA at a version newer than the pin's base (the build-wide override would otherwise force it back down). A new pin is gated on sbt's own resolution records under `target/` (never the machine-wide cache): run-level stops wire nothing, warn once and exit 0 — `redirect_sbt_no_resolution_evidence` (none; run `sbt update` first; always the in-memory engine's answer), `redirect_sbt_resolution_incomplete` (a declared project left no evidence, or the project definitions cannot be read statically), `redirect_sbt_resolution_stale` (a build source is newer than some project's evidence: each project is dated by its own newest record, so a partial `sbt /update` does not vouch for the others). Per-patch refusals (never confirmed): `redirect_sbt_missing_override` (no `maven2` override or no suffixed version), `redirect_sbt_integrity_missing` (jar or pom sha256 missing), `redirect_sbt_unsafe_value` (a value unsafe in a Scala literal, or an index URL not naming the uuid), `redirect_sbt_version_conflict` (some project resolves another version, or a build source declares the GA newer than the patch's base), `redirect_sbt_override_conflict` (two patches for one GA in a run, or another base already pinned), `redirect_sbt_vendored_conflict` (the GA is pinned by `socket-patch-vendor.sbt`, or that file cannot be parsed — then every Maven patch), `redirect_sbt_owned_file_modified` / `redirect_sbt_owned_file_foreign` (`socket-patch.sbt` edited, or not socket-patch's — every Maven patch), `redirect_sbt_owned_file_unreadable` (a whole-run refusal: `socket-patch.sbt` is on disk but cannot be read as UTF-8 text, so writing it would replace it; nothing is written), `redirect_sbt_unsupported_version`, `redirect_sbt_build_root_unknown` (sbt files but no versioned build root — every Maven patch), `redirect_sbt_overrides_assignment` / `redirect_sbt_resolvers_assignment` (a build source reassigns `dependencyOverrides` / `resolvers` with `:=`, `~=`, `--=` or `<<=`), `redirect_sbt_onload_assignment` (a build source reassigns `onLoad`, in any scope, with `:=`, `~=`, `--=` or `<<=` without keeping its previous value — a `:=` reading `(Global / onLoad).value`, or a `~=` that composes with `andThen` / `compose`, keeps it — which drops the generated file's load-time verifier and resolver order), `redirect_sbt_dependency_lock_present` (a `build.sbt.lock`), `redirect_sbt_scala_runtime_unsupported` (`org.scala-lang`), `redirect_sbt_classifier_unsupported`; a GA no library configuration resolves is skipped silently (`redirect_sbt_meta_build_only` when only the meta-build resolves it). Advisories: `redirect_sbt_version_untested` (sbt 2.1+, still wired), `redirect_sbt_override_build_repos` (`sbt.override.build.repos=true`), `redirect_maven_pom_ignored_sbt_build` (a `pom.xml` beside the sbt build, which sbt never reads; the Maven rewriter still edits it for the Maven build). A re-run keeps an existing row and re-checks it. When the build's dependency digest changed since the pin, evidence resolved after the change (fresh, newer than the generated file) re-verifies it and the row's digest is refreshed (`redirect_sbt_pin_rechecked`); the uuid is NOT confirmed on `redirect_sbt_pin_declared_newer` (a build source now declares the GA newer than the pin's base; the row stays, sbt's load-time verifier fails the build, and the remedy is `socket-patch rollback` or declaring the base again), `redirect_sbt_pin_unverifiable` (the digest changed and the evidence predates the change, or the digest cannot be computed: run `sbt update`, then re-run socket-patch), `redirect_sbt_override_shadowed` (the evidence still resolves the base version) or `redirect_sbt_resolved_elsewhere` (the pinned version resolves from outside the pin repository from a file whose sha256 is not the pinned jar's; a copy holding the pinned bytes, such as the Ivy cache a second checkout reads, is fine — at most 64 pinned artifact files of up to 256 MiB are hashed, anything else counts as elsewhere), and also when a build source now reassigns `dependencyOverrides` / `resolvers` / `onLoad` or a `build.sbt.lock` appeared (the same `redirect_sbt_overrides_assignment` / `redirect_sbt_resolvers_assignment` / `redirect_sbt_onload_assignment` / `redirect_sbt_dependency_lock_present` codes; the row stays and sbt's load-time verifier fails the build). For a pure sbt root (no `pom.xml` / Gradle script beside it), maven confirmation is decided only by the sbt rewriter's report; on a mixed root a uuid the sbt rewriter refused is still confirmed by the Maven rewriter's own `pom.xml` pin (the generated sbt files never prove a pin by substring). **Mill and scala-cli** are guidance only: per Maven patch `redirect_mill_manual_snippet` / `redirect_scala_cli_manual_snippet` carry a paste-able snippet (repository + forced suffixed version), nothing is written or confirmed, and a pure Mill / scala-cli root gets no `redirect_maven_no_pom`; there, a Maven patch the server sent without a `maven2` registry override gets `redirect_maven_missing_override` instead of a snippet (with a `pom.xml` beside the Mill / scala-cli files the pom rewriter reports it). `rollback` / `remove` restore `socket-patch.sbt` offline (the rows removed, the file deleted with its last pin; the gitignored downloads are left). Manifest-less VEX reads every strictly parsed pin as a hosted reference but grants it the lockfile basis only when the local evidence shows every recorded version of the GA is the pinned one and every recorded artifact hashes to a pinned sha256 (else `sbt_resolution_unverified`, and the suffixed copy sbt downloaded into `.socket/sbt-hosted` is its only basis). Where the build provably does not use the pinned bytes, that copy proves nothing and the patch is omitted (`vex_sbt_pin_bypassed`): a build source reassigns `dependencyOverrides` (`:=`, `~=`, `--=`; replacing the generated override) or reassigns `onLoad` without keeping its previous value (dropping the installer that holds the load-time verifier and resolver order), whether or not any evidence exists, or a resolution record dated after the generated files and every build source shows the GA's base version (the override shadowed), or the pinned version from outside the pin repository with bytes that are not pinned (judged exactly as the hosted rewriter re-checks a pin, `redirect_sbt_override_shadowed` / `redirect_sbt_resolved_elsewhere`). A record older than the wiring (a project or cross build not re-resolved since) proves nothing, and current records that verify the pin always keep it. A `resolvers` reassignment or `sbt.override.build.repos=true` alone is no bypass: the override still forces the Socket-only version and the load-time verifier checks its bytes, so the build runs the pinned bytes or fails (which is why an `onLoad` reassignment dropping that verifier is one). Stale or partial evidence, project definitions that cannot be read statically and a `build.sbt.lock` only withhold the lockfile basis. A file under a generated name without socket-patch's header is read as the root build definition sbt loads it as. @@ -1780,7 +1780,7 @@ v5.0 replaces v4's per-purl reverts and whole-ledger reverse replay (`revert_rem * **pypi** — `Pipfile.lock`, `requirements.txt` (+ in-root `-r` includes), Hatch PEP 508 direct references (`pyproject.toml` / `hatch.toml`), `poetry.lock`, `pdm.lock`, `uv.lock`, PEP 723 script locks and PEP 751 `pylock*.toml` (+ the paired `pyproject.toml` / script metadata): hashes re-derived from PyPI's JSON API (`SOCKET_PYPI_JSON_API`). A restored `requirements.txt` line gets `--hash` options only when the file is in pip's hash-checking mode. The mode is read off the file's other requirement lines (an `-e` / `--editable` line means unhashed). When every requirement is a hosted pin, it is read off the hosted line itself (`--hash` vs a `#sha256=` url fragment) (#410). Refused: a `static_urls` `pdm.lock` whose project installs from an index other than PyPI (a `[[tool.pdm.source]]` in the sibling `pyproject.toml`, a project `pypi.url` (`.pdm.toml`, then `pdm.toml`), or, with neither, another package's file URL in the lock off PyPI's file host), since restoring PyPI's file URLs would make `pdm sync` bypass that index (#413); a `pdm.lock` without `cross_platform`, or a uv / script / pylock lock, whose release has a wheel that is not pure Python 3 (which files the lock keeps is not re-derivable); a uv lock whose options filter files (`exclude-newer`, `no-binary`, `no-build`, or an `exclude-newer-package` cutoff for the restored package; one of `false` exempts it from the global cutoff here and in pylocks, as in uv) (#1604); a pylock from `uv pip compile` whose header command line (`--no-build`, `--only-binary`, `--no-binary`, `--exclude-newer`, `--exclude-newer-package`) or uv settings (the nearest `uv.toml`, else a pyproject's `[tool.uv]` / `[tool.uv.pip]`, then the user's and the system's `uv.toml` unless `UV_NO_CONFIG` is set, merged as uv does with `[pip]` over the top level; none under `--no-config`, and any `--config-file` refuses; `UV_CONFIG_FILE` or `UV_EXCLUDE_NEWER` set in the restoring environment also refuses, since the header does not record uv's environment) filter the restored package's files, or whose header records no `uv pip compile` command line (`--no-header`, `UV_CUSTOM_COMPILE_COMMAND`), since uv 0.9.16 records only the files those filters let through (#1613); a uv lock whose other registry packages name several registries, or one other than PyPI's simple index; a uv 0.2 `[[distribution]]` lock with no other registry package; a pylock whose other registry packages show neither an `index` nor (as `uv pip compile` writes them) only PyPI files with none, which restores the entry without an `index` too. A `[[package]]` uv lock (uv 0.2.35 and later, script locks included) in which every registry package is hosted — a project with one dependency — has no other entry to show its registry or the artifact fields uv records, so the entry is rebuilt on PyPI's default index with the fields uv writes at the lock's `revision` (`url`, `hash`, `size` with no `revision` and at revision 1; those and `upload-time` at revisions 2 and 3), which is byte for byte what `uv lock` wrote except on uv 0.6.15–0.6.17, whose `upload_time` spelling comes back as the `upload-time` they also read; the run warns `upstream_uv_entry_rebuilt`. That rebuild is refused when the lock's `revision` is newer than 3, or when uv is configured with a package index, since the entry's registry is then not known to be PyPI: `index`, `index-url`, `extra-index-url`, `find-links` or `no-index` in the paired `pyproject.toml` / script `[tool.uv]`, in the nearest `uv.toml` (else pyproject `[tool.uv]`) or the user's or system `uv.toml`, or `UV_INDEX` / `UV_DEFAULT_INDEX` / `UV_INDEX_URL` / `UV_EXTRA_INDEX_URL` / `UV_FIND_LINKS` / `UV_NO_INDEX` set in the restoring environment. Restored artifact fields keep the spelling the lock's other entries show, including the `upload_time` that uv 0.6.15–0.6.17 write. A uv 0.2 `[[distribution]]` lock (uv 0.1.45–0.2.34) is restored like a `[[package]]` one, in the grammar the hosted rewrite wrote the entry in, which is the entry's own: its source keeps its spelling (a string `"direct+…"` back to `"registry+…"`, uv ≤ 0.2.17, or an inline table), its artifacts their grammar (`[distribution.sdist]` / `[[distribution.wheel]]` sub-tables, uv ≤ 0.2.5, or inline), and dependents' references, inline or `[[distribution.dependencies]]` tables, are pointed back. Refused there: an entry with an sdist and inline `dependencies` when no other registry entry of the lock carries both (uv 0.2.18–0.2.22 and 0.2.23–0.2.34 order them differently; hosted mode refuses to wire such an entry, `redirect_uv_lock_unsupported`); and, for the inline-artifact grammar, an `exclude-newer` cutoff the lock does not record: the project's settings (`uv.toml`, else the pyproject's `[tool.uv]`), the user's or system `uv.toml`, or `UV_EXCLUDE_NEWER` (uv 0.2.12–0.2.27 apply these without recording them; hosted mode refuses to wire a lock whose project sets one). A cutoff uv 0.2.28–0.2.33 recorded at the lock's top level refuses like an `[options]` one. A cutoff passed to uv 0.2.6–0.2.27 only on the command line leaves no trace and cannot be detected. A restored pylock entry's `upload-time`s are whole seconds, as uv writes them, unless the lock's other entries show fractions. Its artifacts come back in the TOML spelling the other entries use: uv's inline `wheels = [{ … }]`, or the standard tables `pip lock` writes (`[[packages.wheels]]` with a `[packages.wheels.hashes]` sub-table, `[packages.sdist]`). A `pip lock` file (`created-by = "pip"`) records only the artifact pip selected, so the entry is restored with only the release's wheel (its sdist when it has none), and a release with several wheels is refused. A transitive `override-dependencies` entry hosted mode added is removed (`upstream_uv_override_removed`). Hosted mode keeps no ledger, so it marks the entry it adds with a `# socket-patch hosted: …` comment line above it and removes only a marked entry; a user's own `==` override (which the hosted rewrite reuses rather than adding a second one) is kept, and the lock's `[manifest] overrides` record of it gets its specifier back. * **gem** — `Gemfile.lock` / `gems.locked` + `Gemfile` / `gems.rb`: the spec moves back into the upstream `GEM` section (or the Socket remote leaves a merged section), the Socket source comes off the manifest, the `CHECKSUMS` entry is re-pinned from the rubygems.org compact index (`SOCKET_RUBYGEMS_URL`) and the `DEPENDENCIES` pin loses its `!`. **The unwind is exact**: the `, source: ""` option hosted mode appended to the declaration is removed (nothing else of the declaration was ever changed), and the line it added for a transitive gem (marked `# added by socket-patch (transitive dependency)`) is removed with the blank line before it and the gem's `DEPENDENCIES` entry, so the pair is the pre-scan pair byte for byte, for every declaration form and with LF or CRLF files. A pin socket-patch 5.0 / 5.1 wrote as a `source "" do … end` block is undone too (also when a superseding hosted re-scan on a lock with no `CHECKSUMS` section has moved that block to the newer patch of the same name and version while the lock still pins the older one; several such blocks are refused), but that rewrite did not keep the declaration it replaced: the gem comes back as the exact pin `gem "", ""[, ]`, and the run reports `upstream_gem_declaration_pinned` once per manifest, naming each declaration restored that way, so a version range can be put back by hand. For such a block the `DEPENDENCIES` pin keeps its `!` when the declaration comes back inside the user's own `source "…" do` block (Bundler writes the `!` for any dependency declared in one, rubygems.org included). A block 5.0 / 5.1 appended for a transitive gem with a blank line before it is removed with that line and the `DEPENDENCIES` entry; one with no blank line before it can't be told apart from an in-place rewrite, so it comes back as the exact pin. Refused: an ambiguous upstream section, an upstream remote other than rubygems.org. The manifest pair can't make a committed bundler cache upstream: a `-.gem` left in Bundler's cache dir that isn't the upstream archive is named by `upstream_gem_stale_cache`, never deleted. * **composer** — `composer.lock`: `dist` and the deleted `source` block from packagist's composer v2 metadata (`SOCKET_PACKAGIST_URL`). Refused unless the entry is packagist-sourced and packagist still serves the lock's `dist.reference` for the version. - * **maven** — `pom.xml` (the `-socket.` version suffix, the added `` / `` entry) and the `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` lines hosted mode writes: **no network**, so it restores under `--offline` too. `.mvn` files holding anything else keep the resolver lines (`maven_trusted_checksums_left`). + * **maven** — `pom.xml` (the `-socket.` version suffix, the added `` / `` entry) and the `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` lines hosted mode writes: **no network**, so it restores under `--offline` too. `.mvn` files holding anything else keep the resolver lines (`maven_trusted_checksums_left`). In a config that stays, the six settings hosted mode wrote are respelled for the Maven the project declares, as a hosted scan respells them, so the line an earlier release wrote does not go on stopping Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the project; when that takes the pin's enforcement on Maven 4 away, `maven_trusted_checksums_maven3_only` says so. * **nuget** — `nuget.config` loses the `socket-patch-` source and its exact-id mapping; every lock entry of the id at the pinned version, in every lock the root config governs (member projects' and `packages..lock.json` included), gets nuget.org's `contentHash` back (`SOCKET_NUGET_URL`). Refused when the restored config would not resolve the id from nuget.org alone. A config hosted mode created from scratch is kept (`nuget_default_config_left`). * Any other file wiring a pin refuses it (`socket-patch cannot re-derive the upstream entry in `). * **Refusals.** `--offline` refuses every pin whose restore needs a registry lookup (all but maven), as does a registry that does not answer or no longer describes the entry. A refused pin writes nothing; its message is `cannot restore to its upstream registry entry: ; restore it from version control instead (`git checkout -- `)` — `` are the files wiring the pin: for a gem pin the lock AND its manifest (`git checkout -- Gemfile Gemfile.lock`), since hosted mode edits both and restoring the lock alone leaves a pair Bundler refuses frozen; and, for a `uv.lock` or a script lock, the paired `pyproject.toml` / script when it carries the pin's `[tool.uv.sources]` URL (a checkout of the lock alone would leave that source live); for a `bun.lock` / `bun.lockb` followed by `, then run `bun install --force` (a plain `bun install` keeps the patched copy)`, since Bun's hoisted linker does not re-extract a package whose entry returns to the registry copy of the same `name@version` (#764) — human `Error: Cannot restore …` on stderr (even under `--silent`), JSON a `failed` `hosted_restore_refused` event, and exit 1 (`remove`: the `hosted_revert_failed` error). A write failure after every pin resolved is one artifact-level (no `purl`) `failed` `hosted_write_failed` event. @@ -2316,6 +2316,7 @@ command's integration tests check its output. | `upstream_gem_install_refreshed` | `warnings[]` (note); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem): an installed copy or cache-dir archive the unwind replaced with the sha256-verified upstream gem. A wet vendored gem unwind (#2083, #2093): an installed copy only. A human run prints a progress line instead. | | `upstream_gem_install_would_refresh` | `warnings[]` (note) | the same on `--dry-run`: what a wet unwind would replace. | | `redirect_gem_version_not_locked` | `warnings[]` (warning) | scan `--mode hosted` (gem): the crawled gem version is installed on the machine but no `GEM` section of the project's lock resolves it (another project's copy in the shared gem home). The gem is skipped and the Gemfile and lock stay byte-identical. | +| `redirect_maven_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_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. | diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 2cbaaaa08..51102707b 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -1241,14 +1241,34 @@ async fn run_redirect_selected_untracked( gate.stage.may_admit(&purl) || !new.contains(&(purl, c.dep.patch_uuid.clone())) }) }); - let mut lock: Option = if !common.dry_run && !candidates.is_empty() && may_write { + let redirects = !candidates.is_empty() && may_write; + // A run that writes no redirect can still have one write to make: the + // Maven rewriter respells a `.mvn/maven.config` line an earlier release + // wrote, whatever the run redirects (`engine::read_maven_heal_files`). + // That write needs the lock like any other, but is never a reason to + // fail a run that has nothing else to do: when the lock cannot be had + // (another run holds it, the checkout cannot be written) the line + // waits for the next scan. + let heal_pending = !redirects && engine::read_maven_heal_files(&view).await.is_some(); + let mut lock: Option = if common.dry_run { + None + } else if redirects { match acquire_hosted_lock(common, &mut scan_result, &mut telemetry.json_error) { Ok(guard) => Some(guard), Err(code) => return code, } + } else if heal_pending { + crate::commands::lock_cli::acquire_with_status( + &common.socket_dir(), + Duration::from_secs(common.lock_timeout.unwrap_or(0)), + false, + ) + .ok() } else { None }; + // Whether this run may write that respelling, or preview it. + let may_heal = common.dry_run || lock.is_some(); // Re-read project patch declarations under the write lock. A patch added // during API selection must not be lost in a takeover or lock rewrite. @@ -1330,10 +1350,15 @@ async fn run_redirect_selected_untracked( .await; // Read the project's candidate files (through the overlay). Skipped - // when no candidate survived (the rewriters do nothing without a dep); - // everything after the rewrite still runs. + // when no candidate survived (the rewriters redirect nothing without a + // dep), but for the files of a `.mvn/maven.config` to heal, read again + // now that the lock is held; everything after the rewrite still runs. let read = if !candidates.is_empty() { engine::read_candidate_files(&view, &std::collections::BTreeSet::new(), &candidates).await + } else if heal_pending && may_heal { + engine::read_maven_heal_files(&view) + .await + .unwrap_or_default() } else { CandidateFiles::default() }; @@ -1684,6 +1709,13 @@ async fn run_redirect_selected_untracked( Err(code) => return code, } } + // A wet run that never took the lock writes nothing: the one write the + // rewriters plan without a redirect, the `.mvn/maven.config` heal, is + // withheld (every candidate of this run was deferred, and the lock for + // the heal could not be had). + if !may_heal && lock.is_none() { + done.withhold_maven_heal(); + } // Held to the end of the function. let lock = lock; let confirmed = done.confirmed.clone(); diff --git a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs index 525112fae..ab03bbb38 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs @@ -30,9 +30,18 @@ //! patched jar and the commons-lang3 transitive resolves. //! 5. TAMPER probes: a stale `.sha1` is rejected by `checksumPolicy=fail` //! on every Maven line; a jar re-signed with a MATCHING `.sha1` is -//! rejected by the trusted-checksums summary on Maven ≥ 3.9 (older -//! lines ignore the `aether.*` properties — asserted, so a change in -//! either direction is noticed). +//! rejected by the trusted-checksums summary on Maven ≥ 3.9.4 (older +//! lines do not read it: asserted, so a change in either direction +//! is noticed). Both hold when the build is started with +//! `-f /pom.xml` from outside the project, which every +//! Maven must survive: the line naming the checksums directory once +//! stopped Maven 3.9.2 to 3.9.8 from starting there. The project's +//! Maven Wrapper pins the Maven under test, so on Maven 4 the +//! directory is spelled the one way Maven 4 reads. The same checkout +//! without that pin is then scanned again: it takes the default +//! spelling, the scan says what that trades away on Maven 4, and the +//! Maven under test must start and resolve against it (on Maven 4, +//! without enforcing the pin: asserted). //! 6. MANIFEST-LESS VEX over the fresh checkout (`vex_e2e_common`): //! * online → attested from the pom wiring + the API record (the //! installed suffixed copy hash-verifies, `(redirected)`); @@ -390,6 +399,172 @@ fn maven_scan_hosted_fresh_checkout_install_and_manifestless_vex() { assert_eq!(std::fs::read(&installed).unwrap(), patched_jar); std::fs::remove_dir_all(fresh.join("target")).unwrap(); + // 4b. FROM OUTSIDE THE PROJECT: `mvn -f /pom.xml` started in + // another directory, as CI jobs commonly do. The line that names the + // checksums directory must not stop any Maven from starting: spelled + // with `${session.rootDirectory}`, as releases up to 5.1.0 wrote it, + // Maven 3.9.2 to 3.9.8 refuse to start here (`Illegal use of undefined + // property`). And where the pin is enforced it is enforced from here + // too: the re-signed jar is rejected by the same Mavens as in 5b. + let elsewhere = root.join("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + let fresh_pom = fresh.join("pom.xml"); + let goal = format!("{DEPENDENCY_PLUGIN}:copy-dependencies"); + let from_outside = |settings: &Path, out_dir: &Path| { + purge(&m2); + let out_arg = format!("-DoutputDirectory={}", out_dir.display()); + mvn.run( + &elsewhere, + &m2, + settings, + &["-f", fresh_pom.to_str().unwrap(), &goal, &out_arg], + ) + }; + let outside = root.join("outside-dep"); + let out = from_outside(&mirrored, &outside); + assert!( + ok(&out), + "Maven {} started with -f from outside the project:\n{}", + mvn.version, + dump(&out) + ); + assert_eq!( + std::fs::read(outside.join(format!("{ARTIFACT}-{sfx}.jar"))).unwrap(), + patched_jar, + "and it resolves the patched jar" + ); + let out = from_outside(&resigned_settings, &root.join("outside-resigned")); + assert_eq!( + !ok(&out), + mvn.enforces_trusted_checksums(), + "Maven {}: the re-signed jar, with -f from outside the project:\n{}", + mvn.version, + dump(&out) + ); + if !ok(&out) { + let log = dump(&out).to_ascii_lowercase(); + assert!( + log.contains("checksum") && log.contains(&sha256_hex(&patched_jar)), + "the rejection is the trusted sha256 pin, not the line itself:\n{}", + dump(&out) + ); + } + let _ = std::fs::remove_dir_all(fresh.join("target")); + + // 4c. NO MAVEN DECLARED: the same checkout without the Maven Wrapper + // pin, so nothing in it says which Maven builds it, scanned again. It + // then takes the default spelling, the one that stops no Maven 3 from + // starting, which Maven 4 does not read. So on the Maven 4 leg this is + // Maven 4 run against the default spelling: the scan respells the + // line and says what that trades away, the build starts and resolves + // the patched jar, and the re-signed jar is no longer rejected. On a + // Maven 3 leg the line already has that spelling and nothing changes. + let undeclared = root.join("undeclared"); + fresh_checkout(&fresh, &undeclared); + std::fs::remove_file(undeclared.join(".mvn/wrapper/maven-wrapper.properties")).unwrap(); + let config_before = std::fs::read_to_string(undeclared.join(".mvn/maven.config")).unwrap(); + let launcher_line = "basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums"; + let session_line = "basedir=${session.rootDirectory}/.mvn/checksums"; + assert_eq!( + config_before.contains(session_line), + mvn.major() >= 4, + "the wrapper pinned Maven {}:\n{config_before}", + mvn.version + ); + let (code, env, stderr) = socket( + &undeclared, + &m2, + &[ + "scan", + "--mode", + "hosted", + "--json", + "--yes", + "--cwd", + undeclared.to_str().unwrap(), + "--api-url", + &server.uri(), + "--org", + ORG, + "--api-token", + "fake", + ], + ); + assert_eq!(code, Some(0), "rescan without a wrapper: {env}\n{stderr}"); + let config_after = std::fs::read_to_string(undeclared.join(".mvn/maven.config")).unwrap(); + assert!( + config_after.contains(launcher_line) && !config_after.contains(session_line), + "a project that declares no Maven takes the default spelling:\n{config_after}" + ); + let warned = |code: &str| { + env["warnings"] + .as_array() + .into_iter() + .flatten() + .any(|w| w["code"] == code) + }; + assert_eq!( + warned("redirect_maven_trusted_checksums_maven3_only"), + mvn.major() >= 4, + "Maven {}: the scan says so when it trades the pin's enforcement on Maven 4 \ + away, and only then: {env}", + mvn.version + ); + assert!( + !warned("redirect_maven_trusted_checksums_unenforced"), + "no Maven is named, so none is said to ignore the pin: {env}" + ); + assert_eq!( + std::fs::read(undeclared.join("pom.xml")).unwrap(), + std::fs::read(fresh.join("pom.xml")).unwrap(), + "the pin itself is untouched" + ); + let undeclared_pom = undeclared.join("pom.xml"); + let undeclared_from_outside = |settings: &Path, out_dir: &Path| { + purge(&m2); + let out_arg = format!("-DoutputDirectory={}", out_dir.display()); + mvn.run( + &elsewhere, + &m2, + settings, + &["-f", undeclared_pom.to_str().unwrap(), &goal, &out_arg], + ) + }; + let outside = root.join("undeclared-dep"); + let out = undeclared_from_outside(&mirrored, &outside); + assert!( + ok(&out), + "Maven {} against the default spelling, with -f from outside the project:\n{}", + mvn.version, + dump(&out) + ); + assert_eq!( + std::fs::read(outside.join(format!("{ARTIFACT}-{sfx}.jar"))).unwrap(), + patched_jar, + "and it resolves the patched jar" + ); + purge(&m2); + let out = mvn.copy_dependencies(&undeclared, &m2, &mirrored, "target/dep"); + assert!(ok(&out), "and from the project root:\n{}", dump(&out)); + // Enforced by Maven 3.9.4 and later 3.x, as the warning says: a Maven + // 4 build of a project that does not declare Maven 4 runs as if the + // pin were not there. (If a later Maven 4 starts reading the + // launcher's property, this is where it shows.) + let out = undeclared_from_outside(&resigned_settings, &root.join("undeclared-resigned")); + assert_eq!( + !ok(&out), + mvn.enforces_trusted_checksums() && mvn.major() < 4, + "Maven {}: the re-signed jar against the default spelling:\n{}", + mvn.version, + dump(&out) + ); + let _ = std::fs::remove_dir_all(undeclared.join("target")); + + purge(&m2); + let out = mvn.copy_dependencies(&fresh, &m2, &mirrored, "target/dep"); + assert!(ok(&out), "{}", dump(&out)); + std::fs::remove_dir_all(fresh.join("target")).unwrap(); + // 6. MANIFEST-LESS VEX. let api = PatchApi::start(vec![(UUID.to_string(), view.clone())]); let run = vex_run(&m2); diff --git a/crates/socket-patch-cli/tests/in_process_scan.rs b/crates/socket-patch-cli/tests/in_process_scan.rs index 29b03ca07..4e83ffba4 100644 --- a/crates/socket-patch-cli/tests/in_process_scan.rs +++ b/crates/socket-patch-cli/tests/in_process_scan.rs @@ -1815,3 +1815,145 @@ async fn scan_apply_json_dry_run_with_vex_does_not_write_attestation() { "apply dry run must not write the VEX file even when generation would succeed" ); } + +// --------------------------------------------------------------------------- +// --mode hosted with nothing to redirect: the Maven config an earlier +// release wrote is still healed +// --------------------------------------------------------------------------- + +/// The six Trusted Checksums settings as releases up to 5.1.0 wrote them +/// for every project: the directory named through +/// `${session.rootDirectory}`, which stops Maven 3.9.2 to 3.9.8 from +/// starting with `-f` from outside the project. +fn maven_config_of_an_earlier_release() -> String { + [ + "-Daether.artifactResolver.postProcessor.trustedChecksums=true", + "-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256", + "-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false", + "-Daether.trustedChecksumsSource.summaryFile=true", + "-Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums", + "-Daether.trustedChecksumsSource.summaryFile.originAware=false", + "", + ] + .join("\n") +} + +/// A project hosted mode wired once, whose patched dependency has since +/// been bumped past the patch: a crawled package (so the scan reaches the +/// redirect step), no patch for it, a `pom.xml` and the config an earlier +/// release left behind. +fn project_with_a_stale_maven_config(root: &Path) { + write_root_package_json(root); + write_npm_package(root, "in-proc-scan", "1.0.0"); + std::fs::write( + root.join("pom.xml"), + "\n \ + 4.0.0\n t\n \ + app\n 1\n\n", + ) + .unwrap(); + std::fs::create_dir_all(root.join(".mvn")).unwrap(); + std::fs::write( + root.join(".mvn/maven.config"), + maven_config_of_an_earlier_release(), + ) + .unwrap(); +} + +/// A hosted scan that finds no patch to redirect still respells that line: +/// without it a project whose only patched dependency was bumped would +/// keep, for ever, a line that stops some Maven 3.9 builds from starting. +/// A dry run previews and writes nothing. The same scan in a project whose +/// config needs no heal touches nothing, `.socket/` included. +#[tokio::test] +#[serial] +async fn scan_hosted_with_nothing_to_redirect_heals_the_maven_config() { + use socket_patch_cli::commands::scan::ScanMode; + // The project has a pom: keep the machine's Maven repository and JVM + // caches out of the crawl. + let _no_jvm_caches = NoJvmCaches::new(); + let m2 = tempfile::tempdir().unwrap(); + std::env::set_var("MAVEN_REPO_LOCAL", m2.path()); + let server = MockServer::start().await; + mock_batch_empty(&server).await; + let earlier = maven_config_of_an_earlier_release(); + let healed = earlier.replace( + "${session.rootDirectory}", + "${maven.multiModuleProjectDirectory}", + ); + assert_ne!(healed, earlier); + let args_for = |root: &Path, dry_run: bool| { + let mut args = default_args(root); + args.common.api_url = Some(server.uri()); + args.common.dry_run = dry_run; + args.mode = Some(ScanMode::Hosted); + args + }; + let config = |root: &Path| std::fs::read_to_string(root.join(".mvn/maven.config")).unwrap(); + + // Dry: nothing written, no lock taken. + let tmp = tempfile::tempdir().unwrap(); + project_with_a_stale_maven_config(tmp.path()); + assert_eq!(run_scrubbed(args_for(tmp.path(), true)).await, 0); + assert_eq!(config(tmp.path()), earlier); + assert!(!tmp.path().join(".socket").exists()); + + // Wet: the one line is respelled, every other byte of the project kept. + assert_eq!(run_scrubbed(args_for(tmp.path(), false)).await, 0); + assert_eq!(config(tmp.path()), healed); + assert!( + !batch_posts(&recorded(&server).await).is_empty(), + "the scan reached the patch API and found nothing to redirect" + ); + // And again: nothing left to do. + assert_eq!(run_scrubbed(args_for(tmp.path(), false)).await, 0); + assert_eq!(config(tmp.path()), healed); + + // A config with nothing to heal: the run reads it and touches nothing. + let settled = tempfile::tempdir().unwrap(); + project_with_a_stale_maven_config(settled.path()); + std::fs::write(settled.path().join(".mvn/maven.config"), &healed).unwrap(); + assert_eq!(run_scrubbed(args_for(settled.path(), false)).await, 0); + assert_eq!(config(settled.path()), healed); + assert!( + !settled.path().join(".socket").exists(), + "a run with nothing to write takes no lock" + ); +} + +/// The heal is never a reason to fail a run that has nothing else to do: +/// while another run holds the write lock the line is left for the next +/// scan, and the scan still exits 0. +#[tokio::test] +#[serial] +async fn scan_hosted_heal_waits_when_the_lock_is_held() { + use socket_patch_cli::commands::scan::ScanMode; + let _no_jvm_caches = NoJvmCaches::new(); + let m2 = tempfile::tempdir().unwrap(); + std::env::set_var("MAVEN_REPO_LOCAL", m2.path()); + let server = MockServer::start().await; + mock_batch_empty(&server).await; + let earlier = maven_config_of_an_earlier_release(); + let tmp = tempfile::tempdir().unwrap(); + project_with_a_stale_maven_config(tmp.path()); + let run_once = || { + let mut args = default_args(tmp.path()); + args.common.api_url = Some(server.uri()); + args.mode = Some(ScanMode::Hosted); + run_scrubbed(args) + }; + let config = || std::fs::read_to_string(tmp.path().join(".mvn/maven.config")).unwrap(); + { + let _held = socket_patch_core::patch::apply_lock::acquire( + &tmp.path().join(".socket"), + std::time::Duration::ZERO, + ) + .expect("take the lock"); + assert_eq!(run_once().await, 0, "a held lock does not fail the scan"); + assert_eq!(config(), earlier, "and the line waits"); + } + // Released: the next scan heals it. + assert_eq!(run_once().await, 0); + assert_ne!(config(), earlier); + assert!(config().contains("${maven.multiModuleProjectDirectory}/.mvn/checksums")); +} diff --git a/crates/socket-patch-cli/tests/maven_build_common/mod.rs b/crates/socket-patch-cli/tests/maven_build_common/mod.rs index 32ee053f4..64c5c3fb3 100644 --- a/crates/socket-patch-cli/tests/maven_build_common/mod.rs +++ b/crates/socket-patch-cli/tests/maven_build_common/mod.rs @@ -198,12 +198,17 @@ impl Mvn { } /// Maven ≥ 3.9.4 enforces the trusted-checksums summary file the hosted - /// rewriter commits under `.mvn/checksums/` (#258). 3.9.0 / 3.9.1 leave - /// `${session.rootDirectory}` in `maven.config` uninterpolated, so the - /// file is never found; 3.9.2 / 3.9.3 ignore `checksumAlgorithms=SHA-256` - /// and check SHA-1 only; older lines have no trusted-checksums support. - /// Below 3.9.4 only the transport `checksumPolicy=fail` sidecar check - /// protects the download. + /// rewriter commits under `.mvn/checksums/` (#258), wherever the build + /// is started. 3.9.0 / 3.9.1 do not interpolate the directory in + /// `maven.config`, so the file is never found; 3.9.2 / 3.9.3 ignore + /// `checksumAlgorithms=SHA-256` and check SHA-1 only; older lines have + /// no trusted-checksums support. Below 3.9.4 only the transport + /// `checksumPolicy=fail` sidecar check protects the download. + /// + /// Maven 4 reads the directory only when it is spelled with + /// `${session.rootDirectory}`, which the rewriter writes for a project + /// that declares Maven 4. The capstone's project does: its Maven + /// Wrapper pins the Maven under test. pub fn enforces_trusted_checksums(&self) -> bool { self.numeric() >= vec![3, 9, 4] } diff --git a/crates/socket-patch-cli/tests/scan_rollout_e2e.rs b/crates/socket-patch-cli/tests/scan_rollout_e2e.rs index f8f558812..5e8fec0fe 100644 --- a/crates/socket-patch-cli/tests/scan_rollout_e2e.rs +++ b/crates/socket-patch-cli/tests/scan_rollout_e2e.rs @@ -953,6 +953,102 @@ async fn hosted_upgrades_land_with_a_cap_of_zero() { ); } +/// A capped run that may admit nothing new still respells a +/// `.mvn/maven.config` line an earlier release wrote, and takes the write +/// lock for that. The cap is the rollout plan's, not the lock's: every new +/// row is deferred whether or not the run holds the lock, so the respelled +/// line is the only thing the run writes and no pin the cap forbade lands. +#[tokio::test] +async fn a_cap_of_zero_with_a_maven_config_to_heal_writes_nothing_but_the_heal() { + let mock = MockServer::start().await; + mount_api(&mock, |_| Grant::Granted).await; + let tmp = tempfile::tempdir().unwrap(); + let names9: Vec<&str> = PACKAGES.iter().map(|(n, _)| *n).collect(); + write_project(tmp.path(), &names9); + // The six Trusted Checksums settings as releases up to 5.1.0 wrote + // them for every project. + let earlier = [ + "-Daether.artifactResolver.postProcessor.trustedChecksums=true", + "-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256", + "-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false", + "-Daether.trustedChecksumsSource.summaryFile=true", + "-Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums", + "-Daether.trustedChecksumsSource.summaryFile.originAware=false", + "", + ] + .join("\n"); + std::fs::create_dir_all(tmp.path().join(".mvn")).unwrap(); + std::fs::write(tmp.path().join(".mvn/maven.config"), &earlier).unwrap(); + // Every file of the project but the one the heal rewrites and the + // lock's own directory. + let snapshot = |root: &Path| -> std::collections::BTreeMap> { + fn walk(dir: &Path, root: &Path, out: &mut std::collections::BTreeMap>) { + for entry in std::fs::read_dir(dir).unwrap().flatten() { + let path = entry.path(); + let rel = path + .strip_prefix(root) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + if rel == ".socket" || rel == ".mvn/maven.config" { + continue; + } + if path.is_dir() { + walk(&path, root, out); + } else { + out.insert(rel, std::fs::read(&path).unwrap()); + } + } + } + let mut out = std::collections::BTreeMap::new(); + walk(root, root, &mut out); + out + }; + let before = snapshot(tmp.path()); + + let capped = [ + "--mode", + "hosted", + "--max-new-patches", + "0", + "--patch-server-url", + HOST, + ]; + let v = run_json(tmp.path(), &mock, &capped); + // Nothing new was admitted: all nine are deferred, none is pinned. + assert_eq!(counts(&v), (0, 9, 0, 0), "{v}"); + assert_eq!(deferred_names(&v).len(), 9, "{v}"); + assert_eq!(pinned(tmp.path()), Vec::::new(), "{v}"); + assert_eq!( + snapshot(tmp.path()), + before, + "no file but the Maven config changed" + ); + // The heal is what the run wrote. + assert_eq!( + std::fs::read_to_string(tmp.path().join(".mvn/maven.config")).unwrap(), + earlier.replace( + "${session.rootDirectory}", + "${maven.multiModuleProjectDirectory}" + ) + ); + + // With a budget the same project then takes its pins, as ever. + let v = run_json( + tmp.path(), + &mock, + &[ + "--mode", + "hosted", + "--max-new-patches", + "3", + "--patch-server-url", + HOST, + ], + ); + assert_eq!(pinned(tmp.path()), names(&ORDER[..3]), "{v}"); +} + #[tokio::test] async fn a_failed_reference_lookup_defers_new_rows_instead_of_failing() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/socket-patch-core/src/formats/maven/declared_maven.rs b/crates/socket-patch-core/src/formats/maven/declared_maven.rs new file mode 100644 index 000000000..afdcbfd46 --- /dev/null +++ b/crates/socket-patch-core/src/formats/maven/declared_maven.rs @@ -0,0 +1,393 @@ +//! What a Maven project says about the Maven that builds it (the model its +//! root pom declares, the release its Maven Wrapper pins), and the property +//! a `.mvn/maven.config` line has to name the project's root directory +//! through on that Maven. Pure: text in, verdict out. +//! +//! Every reader of "is this a Maven 4 project" goes through here, so the +//! hosted rewriter, its unwind, discovery and the vendored planner cannot +//! answer differently for one pom. + +use crate::formats::xml; + +/// The model version a pom declares, as Maven reads it: its +/// `` (`model_version`, the element's text) when it has one, +/// else the version its namespace names (`project_tag`, the `` +/// open tag: `xmlns="http://maven.apache.org/POM/4.1.0"`). +/// +/// Measured on Maven 3.9.9 and 4.0.0-rc-7: +/// * `4.0.0` under the 4.1.0 namespace is a +/// 4.0.0 pom. Maven 3 never looks at the namespace and builds it; Maven 4 +/// does not discover its subprojects. +/// * A pom with no `` takes the namespace's version on +/// Maven 4 (under the 4.1.0 namespace it discovers subprojects; under the +/// 4.0.0 one it does not). Maven 3 reads no pom without the element. +/// * `4.1.0` is a 4.1.0 pom whatever the +/// namespace says, and Maven 3 refuses it. +pub(crate) fn model_version_of(model_version: Option<&str>, project_tag: &str) -> Option { + let declared = model_version.map(str::trim).filter(|v| !v.is_empty()); + let version = match declared { + Some(version) => version, + None => { + let namespace = xml::attr(project_tag, "xmlns")?; + let (_, version) = namespace.rsplit_once(POM_NAMESPACE)?; + version + } + }; + Some(version.to_string()) +} + +/// What a pom's namespace ends in ahead of its version. +const POM_NAMESPACE: &str = "maven.apache.org/POM/"; + +/// [`model_version_of`] a pom's text. `None` for a pom that declares no +/// model either way, or that does not scan. +pub(crate) fn pom_model_version(pom: &str) -> Option { + let text = xml::blank_non_markup(pom).ok()?; + let project = *xml::elements(&text, "project").ok()?.first()?; + let model = xml::children(&text, &project, "modelVersion") + .ok() + .and_then(|found| found.first().map(|e| e.inner(&text))); + model_version_of(model, project.open_tag(&text)) +} + +/// Whether `version` names a model newer than 4.0.0: one only Maven 4 +/// reads (4.1.0 today). +pub(crate) fn is_maven_4_model(version: &str) -> bool { + let mut parts = version.split('.').map(str::parse::); + matches!( + (parts.next(), parts.next()), + (Some(Ok(major)), Some(Ok(minor))) if (major, minor) > (4, 0) + ) +} + +/// The Apache Maven release a `maven-wrapper.properties` pins, taken from its +/// `distributionUrl` (`…/apache-maven--bin.zip` or `.tar.gz`). None +/// for a missing key or any other distribution (e.g. mvnd). +pub(crate) fn wrapper_maven_version(props: &str) -> Option { + props.lines().find_map(|line| { + let line = line.trim(); + if line.starts_with('#') || line.starts_with('!') { + return None; + } + let rest = line.strip_prefix("distributionUrl")?; + if !rest.starts_with(|c: char| c == '=' || c == ':' || c.is_whitespace()) { + return None; + } + let value = rest + .trim_start() + .strip_prefix(['=', ':']) + .unwrap_or(rest) + .trim(); + let file = value.rsplit('/').next()?; + let version = file + .strip_prefix("apache-maven-")? + .strip_suffix(".zip") + .or_else(|| file.strip_prefix("apache-maven-")?.strip_suffix(".tar.gz"))? + .strip_suffix("-bin")?; + (!version.is_empty()).then(|| version.to_string()) + }) +} + +/// `[major, minor, patch]` of a Maven version (a pre-release suffix such as +/// `-rc-6` compares as its release). +pub(crate) fn release(version: &str) -> [u32; 3] { + let mut parts = [0u32; 3]; + for (slot, part) in parts.iter_mut().zip(version.split(['.', '-'])) { + *slot = part.parse().unwrap_or(0); + } + parts +} + +/// The Maven a project declares: the two things in a checkout that name +/// one. Nothing else does (a Maven on the `PATH` is not the project's), so +/// a project with neither says nothing about its Maven. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct DeclaredMaven { + /// The Apache Maven release the Maven Wrapper pins. + release: Option, + /// The root pom is of a model only Maven 4 reads + /// ([`is_maven_4_model`]). + maven_4_model: bool, +} + +impl DeclaredMaven { + /// Read from the Maven Wrapper's properties file (`wrapper`) and the + /// root pom (`root_pom`), either of which may be absent. + pub(crate) fn of(wrapper: Option<&str>, root_pom: Option<&str>) -> DeclaredMaven { + DeclaredMaven { + release: wrapper.and_then(wrapper_maven_version), + maven_4_model: root_pom + .and_then(pom_model_version) + .is_some_and(|version| is_maven_4_model(&version)), + } + } + + /// The release the Maven Wrapper pins, when it names an Apache Maven. + pub(crate) fn release(&self) -> Option<&str> { + self.release.as_deref() + } + + /// Whether the root pom is of a model only Maven 4 reads. + pub(crate) fn maven_4_model(&self) -> bool { + self.maven_4_model + } + + /// Whether the project declares Maven 4: its wrapper pins Apache Maven + /// 4 or later, or its root pom is of a model only Maven 4 reads (then a + /// wrapper pinning Maven 3 cannot build the project, and whatever does + /// is a Maven 4). + pub(crate) fn is_maven_4(&self) -> bool { + self.maven_4_model + || self + .release() + .is_some_and(|version| release(version)[0] >= 4) + } +} + +/// The property a `.mvn/maven.config` line names the project's root +/// directory through. No property is right on every Maven. Measured with +/// real Maven (3.6.3, 3.8.9, 3.9.0, 3.9.2 to 3.9.9, 3.9.16, 4.0.0-rc-7), +/// from the project root, from a module directory and with +/// `-f /pom.xml` from outside the project: +/// +/// * `${session.rootDirectory}` is undefined on Maven 3.9.2 to 3.9.8 when +/// the build is started with `-f` from outside the project, and Maven +/// then does not start at all (`Illegal use of undefined property: +/// session.rootDirectory`). From 3.9.9 on, and on Maven 4, it is defined +/// in every invocation. Before 3.9.2 it is not interpolated. +/// * `${maven.multiModuleProjectDirectory}` is defined by every Maven 3 +/// launcher in every invocation, so it breaks no build. Maven 4 does not +/// interpolate it: a line that uses it names no directory there. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum RootDirectory { + /// `${maven.multiModuleProjectDirectory}`: breaks no build. The + /// property for every project that does not declare Maven 4. + Launcher, + /// `${session.rootDirectory}`: the property for a project that declares + /// Maven 4, the only Maven that needs it. + Session, +} + +// The two properties as literals, so a setting that embeds one can be a +// `const` (`concat!`) and still cannot drift from [`RootDirectory`]. +macro_rules! launcher_root { + () => { + "${maven.multiModuleProjectDirectory}" + }; +} +macro_rules! session_root { + () => { + "${session.rootDirectory}" + }; +} +pub(crate) use {launcher_root, session_root}; + +impl RootDirectory { + /// The property, as `maven.config` spells it. + pub(crate) const fn property(self) -> &'static str { + match self { + RootDirectory::Launcher => launcher_root!(), + RootDirectory::Session => session_root!(), + } + } + + /// The other property. + pub(crate) const fn other(self) -> RootDirectory { + match self { + RootDirectory::Launcher => RootDirectory::Session, + RootDirectory::Session => RootDirectory::Launcher, + } + } + + /// The property for a project that declares `maven`: + /// [`RootDirectory::Session`] when it declares Maven 4 + /// ([`DeclaredMaven::is_maven_4`]), else [`RootDirectory::Launcher`], + /// which breaks no build. + pub(crate) fn for_maven(maven: &DeclaredMaven) -> RootDirectory { + if maven.is_maven_4() { + RootDirectory::Session + } else { + RootDirectory::Launcher + } + } + + /// Whether the Maven the project declares is known not to interpolate + /// this property: only [`RootDirectory::Launcher`] in a project that + /// declares Maven 4. (A Maven too old to interpolate either is not a + /// difference between the two.) + pub(crate) fn unread_by(self, maven: &DeclaredMaven) -> bool { + self == RootDirectory::Launcher && maven.is_maven_4() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pom(namespace: Option<&str>, model: Option<&str>) -> String { + let xmlns = namespace.map_or(String::new(), |v| { + format!(" xmlns=\"http://maven.apache.org/POM/{v}\"") + }); + let model = model.map_or(String::new(), |v| { + format!(" {v}\n") + }); + format!( + "\n{model} g\n a\n \ + 1\n\n" + ) + } + + /// The cells measured on Maven 3.9.9 and 4.0.0-rc-7 (see + /// [`model_version_of`]). + #[test] + fn the_model_is_the_model_version_else_the_namespace() { + for (namespace, model, want) in [ + (Some("4.0.0"), Some("4.0.0"), Some("4.0.0")), + // A 4.0.0 model under the 4.1.0 namespace: Maven 3 builds it. + (Some("4.1.0"), Some("4.0.0"), Some("4.0.0")), + (Some("4.1.0"), Some("4.1.0"), Some("4.1.0")), + (Some("4.0.0"), Some("4.1.0"), Some("4.1.0")), + (None, Some("4.1.0"), Some("4.1.0")), + // No : the namespace's version. + (Some("4.1.0"), None, Some("4.1.0")), + (Some("4.0.0"), None, Some("4.0.0")), + (None, None, None), + ] { + assert_eq!( + pom_model_version(&pom(namespace, model)).as_deref(), + want, + "{namespace:?} {model:?}" + ); + } + // An empty element is no declaration; a commented-out one is none. + let empty = pom(Some("4.1.0"), Some(" ")); + assert_eq!(pom_model_version(&empty).as_deref(), Some("4.1.0")); + let commented = pom(Some("4.0.0"), None).replace( + " ", + " \n ", + ); + assert_eq!(pom_model_version(&commented).as_deref(), Some("4.0.0")); + // Another attribute that names the namespace is not the namespace. + let schema_only = "\n\n"; + assert_eq!(pom_model_version(schema_only), None); + assert_eq!(pom_model_version("not a pom"), None); + } + + #[test] + fn only_a_model_newer_than_4_0_0_needs_maven_4() { + for (version, want) in [ + ("4.0.0", false), + ("4.1.0", true), + ("4.2.0", true), + ("5.0.0", true), + ("4.0", false), + ("3.0.0", false), + ("", false), + ("four", false), + ] { + assert_eq!(is_maven_4_model(version), want, "{version}"); + } + } + + fn wrapper(version: &str) -> String { + format!( + "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/\ + {version}/apache-maven-{version}-bin.zip\n" + ) + } + + /// The `distributionUrl` parse: escaped or plain `:`, `=`/`:`/space + /// separators, `.tar.gz` distributions, comments and CRLF. + #[test] + fn the_wrapper_release_is_parsed_from_the_distribution_url() { + let escaped = "# Licensed to the Apache Software Foundation (ASF)\nwrapperVersion=3.3.2\n\ + distributionType=only-script\ndistributionUrl=https\\://repo.maven.apache.org/\ + maven2/org/apache/maven/apache-maven/3.9.3/apache-maven-3.9.3-bin.zip\n"; + assert_eq!(wrapper_maven_version(escaped).as_deref(), Some("3.9.3")); + assert_eq!( + wrapper_maven_version( + "distributionUrl : https://archive.apache.org/dist/maven/maven-3/3.9.2/binaries/\ + apache-maven-3.9.2-bin.tar.gz\r\n" + ) + .as_deref(), + Some("3.9.2") + ); + assert_eq!( + wrapper_maven_version( + "! comment\r\ndistributionUrl=https\\://repo/apache-maven-4.0.0-rc-6-bin.zip\r\n" + ) + .as_deref(), + Some("4.0.0-rc-6") + ); + assert_eq!(wrapper_maven_version("wrapperVersion=3.3.2\n"), None); + assert_eq!( + wrapper_maven_version("distributionUrlOld=https://x/apache-maven-3.9.3-bin.zip\n"), + None + ); + assert_eq!( + wrapper_maven_version( + "# distributionUrl=https\\://x/apache-maven/3.9.3/apache-maven-3.9.3-bin.zip\n" + ), + None + ); + assert_eq!(release("3.9.16"), [3, 9, 16]); + assert_eq!(release("4.0.0-rc-7"), [4, 0, 0]); + assert_eq!(release("3.10"), [3, 10, 0]); + } + + #[test] + fn a_project_declares_maven_4_by_its_wrapper_or_its_model() { + let declared = |wrapper: Option<&str>, pom: Option<&str>| DeclaredMaven::of(wrapper, pom); + let nothing = declared(None, None); + assert_eq!(nothing, DeclaredMaven::default()); + assert!(!nothing.is_maven_4()); + assert_eq!(nothing.release(), None); + + let maven_3 = declared( + Some(&wrapper("3.9.9")), + Some(&pom(Some("4.0.0"), Some("4.0.0"))), + ); + assert_eq!(maven_3.release(), Some("3.9.9")); + assert!(!maven_3.is_maven_4()); + + for version in ["4.0.0", "4.0.0-rc-7", "4.1.2", "5.0.0"] { + assert!( + declared(Some(&wrapper(version)), None).is_maven_4(), + "{version}" + ); + } + // The model alone, with no wrapper or under one that pins Maven 3. + let model = pom(Some("4.1.0"), Some("4.1.0")); + assert!(declared(None, Some(&model)).is_maven_4()); + assert!(declared(Some(&wrapper("3.9.9")), Some(&model)).is_maven_4()); + assert!(declared(None, Some(&pom(Some("4.1.0"), None))).is_maven_4()); + // A 4.0.0 model under the 4.1.0 namespace is a pom Maven 3 builds. + assert!(!declared(None, Some(&pom(Some("4.1.0"), Some("4.0.0")))).is_maven_4()); + // Another distribution names no Apache Maven release. + let mvnd = "distributionUrl=https://example.test/maven-mvnd-1.0.2-bin.zip\n"; + assert_eq!(declared(Some(mvnd), None), DeclaredMaven::default()); + } + + #[test] + fn the_root_directory_property_follows_the_declared_maven() { + use RootDirectory::{Launcher, Session}; + let maven_4 = DeclaredMaven::of(Some(&wrapper("4.0.0")), None); + let maven_3 = DeclaredMaven::of(Some(&wrapper("3.9.9")), None); + let unknown = DeclaredMaven::default(); + assert_eq!(RootDirectory::for_maven(&maven_4), Session); + assert_eq!(RootDirectory::for_maven(&maven_3), Launcher); + assert_eq!(RootDirectory::for_maven(&unknown), Launcher); + assert_eq!(Launcher.property(), "${maven.multiModuleProjectDirectory}"); + assert_eq!(Session.property(), "${session.rootDirectory}"); + assert_eq!(Launcher.other(), Session); + assert_eq!(Session.other(), Launcher); + // Only the launcher's property is unread, and only by Maven 4. + assert!(Launcher.unread_by(&maven_4)); + assert!(!Session.unread_by(&maven_4)); + for maven in [&maven_3, &unknown] { + assert!(!Launcher.unread_by(maven)); + assert!(!Session.unread_by(maven)); + } + } +} diff --git a/crates/socket-patch-core/src/formats/maven/mod.rs b/crates/socket-patch-core/src/formats/maven/mod.rs index c78762c15..6db52935b 100644 --- a/crates/socket-patch-core/src/formats/maven/mod.rs +++ b/crates/socket-patch-core/src/formats/maven/mod.rs @@ -17,6 +17,7 @@ pub(crate) use properties::{ use super::xml::{blank_non_markup, child_text, elements, open_tags, Element}; +pub(crate) mod declared_maven; pub(crate) mod trusted_checksums; pub(crate) mod version; diff --git a/crates/socket-patch-core/src/formats/maven/trusted_checksums.rs b/crates/socket-patch-core/src/formats/maven/trusted_checksums.rs index 8216ce34a..fdb0f9fc4 100644 --- a/crates/socket-patch-core/src/formats/maven/trusted_checksums.rs +++ b/crates/socket-patch-core/src/formats/maven/trusted_checksums.rs @@ -15,6 +15,7 @@ use std::collections::{BTreeMap, BTreeSet}; +use super::declared_maven::{launcher_root, release, session_root, DeclaredMaven}; use super::maven_config_line_properties; use crate::utils::digest::{is_hex64_lower, sha256_hex}; @@ -30,9 +31,30 @@ macro_rules! summary_file { "aether.trustedChecksumsSource.summaryFile" }; } -macro_rules! basedir { +// The summary file's directory, under the project's root directory. +macro_rules! checksums_dir { () => { - "${session.rootDirectory}/.mvn/checksums" + "/.mvn/checksums" + }; +} +// The six lines, with the project's root directory named through the +// property `$root` expands to: one definition for both spellings. +macro_rules! config_args { + ($root:ident) => { + &[ + concat!("-D", post_processor!(), "=true"), + concat!("-D", post_processor!(), ".checksumAlgorithms=SHA-256"), + concat!("-D", post_processor!(), ".failIfMissing=false"), + concat!("-D", summary_file!(), "=true"), + concat!( + "-D", + summary_file!(), + ".basedir=", + $root!(), + checksums_dir!() + ), + concat!("-D", summary_file!(), ".originAware=false"), + ] }; } @@ -41,53 +63,214 @@ macro_rules! basedir { pub(crate) const SWITCH_KEY: &str = post_processor!(); const ALGORITHMS_KEY: &str = concat!(post_processor!(), ".checksumAlgorithms"); const SUMMARY_FILE_KEY: &str = summary_file!(); -const BASEDIR_KEY: &str = concat!(summary_file!(), ".basedir"); +pub(crate) const BASEDIR_KEY: &str = concat!(summary_file!(), ".basedir"); const ORIGIN_AWARE_KEY: &str = concat!(summary_file!(), ".originAware"); +/// How `.mvn/maven.config` spells the directory of the summary file: +/// `.mvn/checksums` under the project's root directory, named through one +/// of the two properties a config line can name that directory through +/// ([`RootDirectory`], where the measurements are). Maven reads a relative +/// `basedir` from the local repository, so the directory in the checkout +/// has to be named through a property, and no property is right on every +/// Maven. +/// +/// What the spelling means for the pin, measured with a genuine and a +/// tampered artifact from the project root, from a module directory and +/// with `-f /pom.xml` from outside the project: +/// +/// * [`Basedir::Launcher`] breaks no build, and the pin is enforced from +/// Maven 3.9.4 on wherever the build is started. On Maven 4 the directory +/// is not found, nothing is enforced, and the build runs as if the line +/// were not there. +/// * [`Basedir::Session`] is enforced from Maven 3.9.4 on and on Maven 4, +/// wherever the property is defined; where it is not (`-f` from outside +/// the project on 3.9.2 to 3.9.8) Maven does not start. +/// +/// A Maven that interpolates neither (before 3.9.2) reads no summary file +/// under either spelling. +pub(crate) use super::declared_maven::RootDirectory as Basedir; + +/// The setting's value under `form`. +pub(crate) const fn basedir_value(form: Basedir) -> &'static str { + match form { + Basedir::Launcher => concat!(launcher_root!(), checksums_dir!()), + Basedir::Session => concat!(session_root!(), checksums_dir!()), + } +} + +/// The form whose value is `value`. +pub(crate) fn basedir_of_value(value: &str) -> Option { + [Basedir::Launcher, Basedir::Session] + .into_iter() + .find(|form| basedir_value(*form) == value) +} + /// The `.mvn/maven.config` lines hosted mode writes, one argument each: /// the post-processor on, checking SHA-256, `failIfMissing=false` (a /// dependency without a committed checksum still resolves; only a MISMATCH /// fails), and the summary-file source on, at `.mvn/checksums`, origin -/// unaware (one checksum matches the artifact from any repository). -pub(crate) const CONFIG_ARGS: &[&str] = &[ - concat!("-D", post_processor!(), "=true"), - concat!("-D", post_processor!(), ".checksumAlgorithms=SHA-256"), - concat!("-D", post_processor!(), ".failIfMissing=false"), - concat!("-D", summary_file!(), "=true"), - concat!("-D", summary_file!(), ".basedir=", basedir!()), - concat!("-D", summary_file!(), ".originAware=false"), -]; - -/// Whether `.mvn/maven.config` makes Maven check artifacts against -/// `.mvn/checksums/checksums.sha256` — the one rule every mode shares. +/// unaware (one checksum matches the artifact from any repository). The +/// directory is spelled as [`Basedir::Launcher`]; see [`config_args`]. +pub(crate) const CONFIG_ARGS: &[&str] = config_args!(launcher_root); + +/// Where the directory line stands among the six. +const BASEDIR_AT: usize = 4; + +/// The lines hosted mode writes for a project whose form is `form`. +pub(crate) fn config_args(form: Basedir) -> &'static [&'static str] { + match form { + Basedir::Launcher => CONFIG_ARGS, + Basedir::Session => config_args!(session_root), + } +} + +/// Each line of [`config_args`] as the `(key, value)` it sets. +pub(crate) fn config_settings( + form: Basedir, +) -> impl Iterator { + config_args(form).iter().map(|arg| { + let (key, value) = arg + .strip_prefix("-D") + .and_then(|def| def.split_once('=')) + .expect("every Trusted Checksums line hosted mode writes is -Dkey=value"); + (*arg, key, value) + }) +} + +/// Whether `config` is exactly what hosted mode writes into a file of its +/// own, in either form: such a file is hosted mode's to remove. +pub(crate) fn is_written_config(config: &str) -> bool { + [Basedir::Launcher, Basedir::Session] + .into_iter() + .any(|form| config == format!("{}\n", config_args(form).join("\n"))) +} + +/// `config` with the summary file's directory spelled as `form`, wherever +/// it holds the six lines hosted mode writes in the other form: that one +/// line of each such block is rewritten in place, every other byte kept. +/// `None` when there is nothing to change. +/// +/// The six lines must stand together, in the order hosted mode writes +/// them, as it writes them into a config that set none of them: that block +/// is what tells hosted mode's settings from the user's, whatever else the +/// file holds and whatever a later line sets. A directory line that stands +/// apart was there before hosted mode came (it then appended only the +/// settings that were missing), or is spelled exactly as Maven's own +/// documentation spells it by a user who wrote it, and stays as written. +/// +/// This is how a project wired by an earlier release, whose line stops +/// Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the project, +/// is healed; and how a project that has since declared Maven 4 gets the +/// spelling Maven 4 reads. +pub(crate) fn heal_basedir(config: &str, form: Basedir) -> Option { + let written = config_args(form.other()); + // The cheap test first: almost no config holds the other spelling. + if !config.contains(written[BASEDIR_AT]) { + return None; + } + let lines: Vec<&str> = config.split_inclusive('\n').collect(); + let body = |line: &str| -> usize { line.trim_end_matches(['\r', '\n']).len() }; + let healed: BTreeSet = (0..(lines.len() + 1).checked_sub(written.len())?) + .filter(|&at| { + written + .iter() + .zip(&lines[at..]) + .all(|(arg, line)| &line[..body(line)] == *arg) + }) + .map(|at| at + BASEDIR_AT) + .collect(); + if healed.is_empty() { + return None; + } + let mut out = String::with_capacity(config.len() + 32); + for (i, line) in lines.iter().enumerate() { + if healed.contains(&i) { + out.push_str(config_args(form)[BASEDIR_AT]); + out.push_str(&line[body(line)..]); + } else { + out.push_str(line); + } + } + Some(out) +} + +/// Whether `config` holds the six lines hosted mode writes, standing +/// together, in either spelling: whether some project is healed out of it +/// ([`heal_basedir`]). A substring test for nearly every config, so a +/// caller asks this before it reads anything else to find out which +/// spelling the project takes. +pub(crate) fn holds_written_block(config: &str) -> bool { + [Basedir::Launcher, Basedir::Session] + .into_iter() + .any(|form| heal_basedir(config, form).is_some()) +} + +/// The Trusted Checksums settings of a `.mvn/maven.config`, read once. /// /// `maven.config` is read as Maven 3.9+ reads it (the only line that /// enforces Trusted Checksums at all): one argument per LINE, `#` /// comments, `-Dk=v` / `--define`, `-Dk` alone meaning `true`, a later /// definition winning ([`maven_config_line_properties`]); a `-Dk=v` token -/// inside a longer line is not an argument there. Each setting is then -/// judged as the resolver judges it, with its default when unset: -/// - the post-processor on (`ConfigUtils.getBoolean`, i.e. Java -/// `Boolean.parseBoolean`: `true` in any case; default off); -/// - its comma-separated `checksumAlgorithms` naming `SHA-256` (default -/// `SHA-1`, which never reads a `.sha256` file); -/// - the summary-file source on (default off); -/// - its `basedir` exactly the `.mvn/checksums` hosted mode writes (the -/// default is `.checksums` under the local repository; any other value is -/// not this file); -/// - `originAware` off (default on, which reads a per-repository -/// `checksums-.sha256` instead). -/// -/// `failIfMissing` does not decide whether a committed line is checked. +/// inside a longer line is not an argument there. +pub(crate) struct Settings(BTreeMap); + +impl Settings { + /// Read `config`, a `.mvn/maven.config`'s text. + pub(crate) fn read(config: &str) -> Settings { + Settings(maven_config_line_properties(config)) + } + + /// What the config sets `key` to. + pub(crate) fn get(&self, key: &str) -> Option<&str> { + self.0.get(key).map(String::as_str) + } + + /// The form the directory is spelled in, when it is one hosted mode + /// writes. + pub(crate) fn basedir(&self) -> Option { + self.get(BASEDIR_KEY).and_then(basedir_of_value) + } + + /// Whether the config makes Maven check artifacts against + /// `.mvn/checksums/checksums.sha256` — the one rule every mode shares. + /// + /// Each setting is judged as the resolver judges it, with its default + /// when unset: + /// - the post-processor on (`ConfigUtils.getBoolean`, i.e. Java + /// `Boolean.parseBoolean`: `true` in any case; default off); + /// - its comma-separated `checksumAlgorithms` naming `SHA-256` (default + /// `SHA-1`, which never reads a `.sha256` file); + /// - the summary-file source on (default off); + /// - its `basedir` exactly the `.mvn/checksums` hosted mode writes, in + /// either spelling ([`Basedir`]; the default is `.checksums` under + /// the local repository; any other value is not this file); + /// - `originAware` off (default on, which reads a per-repository + /// `checksums-.sha256` instead). + /// + /// `failIfMissing` does not decide whether a committed line is checked. + /// Whether the Maven that builds the project then reads the directory + /// is [`enforcement`]'s to say. + pub(crate) fn enforce(&self) -> bool { + let is_true = |key: &str| { + self.get(key) + .is_some_and(|v| v.eq_ignore_ascii_case("true")) + }; + is_true(SWITCH_KEY) + && self + .get(ALGORITHMS_KEY) + .is_some_and(|v| v.split(',').any(|a| a.trim() == "SHA-256")) + && is_true(SUMMARY_FILE_KEY) + && self.basedir().is_some() + && self + .get(ORIGIN_AWARE_KEY) + .is_some_and(|v| !v.eq_ignore_ascii_case("true")) + } +} + +/// [`Settings::enforce`] of a config's text. +#[cfg(test)] pub(crate) fn config_enforces(config: &str) -> bool { - let props = maven_config_line_properties(config); - let get = |key: &str| props.get(key).map(String::as_str); - let is_true = |key: &str| get(key).is_some_and(|v| v.eq_ignore_ascii_case("true")); - is_true(SWITCH_KEY) - && get(ALGORITHMS_KEY).is_some_and(|v| v.split(',').any(|a| a.trim() == "SHA-256")) - && is_true(SUMMARY_FILE_KEY) - && get(BASEDIR_KEY) == Some(basedir!()) - && get(ORIGIN_AWARE_KEY).is_some_and(|v| !v.eq_ignore_ascii_case("true")) + Settings::read(config).enforce() } /// Whether any setting hosted mode writes is present in `config`, whatever @@ -96,10 +279,7 @@ pub(crate) fn config_enforces(config: &str) -> bool { /// warning keys on presence, not on enforcement. pub(crate) fn config_has_written_settings(config: &str) -> bool { let props = crate::formats::maven::maven_config_properties(config); - CONFIG_ARGS - .iter() - .filter_map(|arg| arg.strip_prefix("-D")?.split_once('=')) - .any(|(key, _)| props.contains_key(key)) + config_settings(Basedir::Launcher).any(|(_, key, _)| props.contains_key(key)) } /// The first Maven release that enforces the `.mvn/*` Trusted Checksums @@ -109,55 +289,70 @@ pub(crate) fn config_has_written_settings(config: &str) -> bool { /// no Trusted Checksums post-processor at all. const MIN_MAVEN: [u32; 3] = [3, 9, 4]; -/// The Apache Maven release a `maven-wrapper.properties` pins, taken from its -/// `distributionUrl` (`…/apache-maven--bin.zip` or `.tar.gz`). None -/// for a missing key or any other distribution (e.g. mvnd), which is then -/// taken to enforce. -pub(crate) fn wrapper_maven_version(props: &str) -> Option { - props.lines().find_map(|line| { - let line = line.trim(); - if line.starts_with('#') || line.starts_with('!') { - return None; - } - let rest = line.strip_prefix("distributionUrl")?; - if !rest.starts_with(|c: char| c == '=' || c == ':' || c.is_whitespace()) { - return None; +/// Whether the summary file is an enforced pin, as far as the project +/// says which Maven builds it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Enforcement { + /// The config does not make Maven read the summary file + /// ([`Settings::enforce`]). + Off, + /// The Maven Wrapper pins this Apache Maven release, which is older + /// than 3.9.4 and enforces no such file. + TooOld(String), + /// The project declares Maven 4 and the directory is spelled as + /// [`Basedir::Launcher`], which Maven 4 does not interpolate. + UnreadByMaven4, + /// The project declares no Maven and the directory is spelled as + /// [`Basedir::Launcher`]: Maven 3.9.4 and later 3.x enforce the pin, a + /// Maven 4 build does not. Nothing in the checkout says which builds + /// it, so the pin is not known to be enforced. + Maven3Only, + /// The Maven the project declares enforces the pin; or it declares + /// none, and the directory is spelled so that every Maven that + /// enforces Trusted Checksums at all finds it. + Enforced, +} + +/// Whether the Maven the project declares (`maven`) enforces a pin whose +/// directory is spelled as `form`, in a config that otherwise enforces it +/// ([`Settings::enforce`]). The one answer to that question: the conflict +/// check, the heal, the unenforced warning and discovery all ask it here. +/// Never [`Enforcement::Off`]. +pub(crate) fn form_enforcement(form: Basedir, maven: &DeclaredMaven) -> Enforcement { + // A wrapper that pins a Maven 3 cannot build a pom only Maven 4 reads, + // so its release then says nothing about the Maven that does. + if let Some(version) = maven.release().filter(|_| !maven.maven_4_model()) { + if release(version) < MIN_MAVEN { + return Enforcement::TooOld(version.to_string()); } - let value = rest - .trim_start() - .strip_prefix(['=', ':']) - .unwrap_or(rest) - .trim(); - let file = value.rsplit('/').next()?; - let version = file - .strip_prefix("apache-maven-")? - .strip_suffix(".zip") - .or_else(|| file.strip_prefix("apache-maven-")?.strip_suffix(".tar.gz"))? - .strip_suffix("-bin")?; - (!version.is_empty()).then(|| version.to_string()) - }) + } + if form.unread_by(maven) { + Enforcement::UnreadByMaven4 + } else if form == Basedir::Launcher && maven.release().is_none() { + Enforcement::Maven3Only + } else { + Enforcement::Enforced + } } -/// Whether Maven `version` enforces the Trusted Checksums files (≥ 3.9.4; -/// pre-release suffixes such as `-rc-6` compare as their release). -pub(crate) fn maven_enforces(version: &str) -> bool { - let mut parts = [0u32; 3]; - for (slot, part) in parts.iter_mut().zip(version.split(['.', '-'])) { - *slot = part.parse().unwrap_or(0); +/// Whether the summary file is an enforced pin under `settings` in a +/// project that declares `maven`. +pub(crate) fn enforcement(settings: &Settings, maven: &DeclaredMaven) -> Enforcement { + match settings.basedir().filter(|_| settings.enforce()) { + Some(form) => form_enforcement(form, maven), + None => Enforcement::Off, } - parts >= MIN_MAVEN } -/// Whether the summary file is an enforced pin: [`config_enforces`], and a -/// Maven Wrapper (`wrapper`, its properties) that names no Apache Maven -/// release older than 3.9.4. No wrapper, or one naming another -/// distribution, is taken to enforce — the hosted rewriter's rule, which -/// warns only on a release it can name. -pub(crate) fn enforced(config: &str, wrapper: Option<&str>) -> bool { - config_enforces(config) - && wrapper - .and_then(wrapper_maven_version) - .is_none_or(|v| maven_enforces(&v)) +/// Whether `text`, a `.mvn/checksums/checksums.sha256`, still names an +/// artifact hosted mode pins: a path under a `-socket.` +/// version, in any spelling of its line. +pub(crate) fn names_hosted_artifact(text: &str) -> bool { + entries(text).any(|e| { + e.path + .split('/') + .any(|seg| super::split_socket_version(seg).is_some()) + }) } /// One non-comment line of the summary file, read as two fields. @@ -555,19 +750,267 @@ mod tests { assert!(!config_has_written_settings(&format!("# {switch_line}"))); } + fn wrapper(version: &str) -> String { + format!( + "distributionUrl=https\\://repo.maven.apache.org/maven2/org/apache/maven/\ + apache-maven/{version}/apache-maven-{version}-bin.zip\n" + ) + } + + fn pom(model: &str) -> String { + format!( + "\n \ + {model}\n\n" + ) + } + + /// The two spellings are one definition: they differ in the directory + /// line alone, which stands where [`BASEDIR_AT`] says and names the + /// property of its form. #[test] - fn enforced_follows_the_wrapper_maven() { - let all = CONFIG_ARGS.join("\n"); - let wrapper = |v: &str| { - format!("distributionUrl=https://repo/apache-maven/{v}/apache-maven-{v}-bin.zip\n") - }; - assert!(enforced(&all, None)); - assert!(enforced(&all, Some(&wrapper("3.9.4")))); - assert!(enforced( - &all, - Some("distributionUrl=https://x/maven-mvnd-1.0.2.zip\n") + fn the_two_spellings_differ_in_the_directory_line_alone() { + use Basedir::{Launcher, Session}; + let (launcher, session) = (config_args(Launcher), config_args(Session)); + assert_eq!(launcher, CONFIG_ARGS); + assert_eq!(launcher.len(), session.len()); + for (i, (a, b)) in launcher.iter().zip(session).enumerate() { + assert_eq!(a == b, i != BASEDIR_AT, "{a} / {b}"); + } + for form in [Launcher, Session] { + let line = config_args(form)[BASEDIR_AT]; + assert_eq!(line, format!("-D{BASEDIR_KEY}={}", basedir_value(form))); + assert_eq!( + basedir_value(form), + format!("{}/.mvn/checksums", form.property()) + ); + assert_eq!(basedir_of_value(basedir_value(form)), Some(form)); + let keys: Vec<&str> = config_settings(form).map(|(_, key, _)| key).collect(); + assert_eq!(keys[BASEDIR_AT], BASEDIR_KEY); + assert_eq!(keys.len(), 6); + } + assert_eq!(basedir_of_value(".mvn/checksums"), None); + } + + /// One function answers whether the Maven a project declares enforces + /// a spelling: from the wrapper AND the model. + #[test] + fn enforcement_follows_the_maven_the_project_declares() { + use Basedir::{Launcher, Session}; + use Enforcement::{Enforced, Maven3Only, TooOld, UnreadByMaven4}; + let declared = |wrapper: Option<&str>, pom: Option<&str>| DeclaredMaven::of(wrapper, pom); + let by_wrapper = |version: &str| declared(Some(&wrapper(version)), Some(&pom("4.0.0"))); + // Too old for Trusted Checksums, whatever the spelling. + for old in ["3.6.3", "3.8.9", "3.9.0", "3.9.3"] { + for form in [Launcher, Session] { + assert_eq!( + form_enforcement(form, &by_wrapper(old)), + TooOld(old.to_string()), + "{old}" + ); + } + } + // A Maven 3 that enforces reads either spelling. + for maven_3 in ["3.9.4", "3.9.8", "3.9.16", "3.10.0-rc-1"] { + for form in [Launcher, Session] { + assert_eq!(form_enforcement(form, &by_wrapper(maven_3)), Enforced); + } + } + // Maven 4 reads only the session property: declared by the wrapper, + // by the model alone, or by the model under a Maven 3 wrapper that + // cannot build it. + for maven_4 in [ + by_wrapper("4.0.0"), + by_wrapper("4.0.0-rc-7"), + declared(None, Some(&pom("4.1.0"))), + declared(Some(&wrapper("3.9.9")), Some(&pom("4.1.0"))), + declared(Some(&wrapper("3.8.9")), Some(&pom("4.1.0"))), + ] { + assert_eq!(form_enforcement(Session, &maven_4), Enforced, "{maven_4:?}"); + assert_eq!( + form_enforcement(Launcher, &maven_4), + UnreadByMaven4, + "{maven_4:?}" + ); + } + // Nothing declared (no wrapper, another distribution, a 4.0.0 + // model): the launcher spelling is enforced by Maven 3 only, and + // which Maven builds the project is not known. + let mvnd = "distributionUrl=https://x/maven-mvnd-1.0.2-bin.zip\n"; + for unknown in [ + declared(None, None), + declared(None, Some(&pom("4.0.0"))), + declared(Some(mvnd), Some(&pom("4.0.0"))), + ] { + assert_eq!(form_enforcement(Launcher, &unknown), Maven3Only); + assert_eq!(form_enforcement(Session, &unknown), Enforced); + } + } + + #[test] + fn enforcement_needs_a_config_that_reads_the_file() { + use Basedir::{Launcher, Session}; + let written = |form| Settings::read(&config_args(form).join("\n")); + let unknown = DeclaredMaven::default(); + assert_eq!( + enforcement(&written(Launcher), &unknown), + Enforcement::Maven3Only + ); + assert_eq!( + enforcement(&written(Session), &unknown), + Enforcement::Enforced + ); + let maven_3 = DeclaredMaven::of(Some(&wrapper("3.9.9")), None); + assert_eq!( + enforcement(&written(Launcher), &maven_3), + Enforcement::Enforced + ); + // A config that does not enforce is off whatever the Maven, and + // never "too old": there is no pin for a Maven to ignore. + let off = Settings::read(&format!( + "{}\n-D{SWITCH_KEY}=false\n", + CONFIG_ARGS.join("\n") )); - assert!(!enforced(&all, Some(&wrapper("3.9.3")))); - assert!(!enforced("", None)); + let old = DeclaredMaven::of(Some(&wrapper("3.9.0")), None); + for maven in [&unknown, &maven_3, &old] { + assert_eq!(enforcement(&off, maven), Enforcement::Off); + assert_eq!(enforcement(&Settings::read(""), maven), Enforcement::Off); + } + assert_eq!( + enforcement(&written(Launcher), &old), + Enforcement::TooOld("3.9.0".into()) + ); + } + + #[test] + fn the_directory_is_spelled_for_the_maven_the_project_declares() { + use Basedir::{Launcher, Session}; + let form = |wrapper: Option<&str>, pom: Option<&str>| { + Basedir::for_maven(&DeclaredMaven::of(wrapper, pom)) + }; + assert_eq!(form(None, None), Launcher); + assert_eq!(form(None, Some(&pom("4.0.0"))), Launcher); + for maven_3 in ["3.6.3", "3.9.2", "3.9.8", "3.9.16"] { + assert_eq!( + form(Some(&wrapper(maven_3)), Some(&pom("4.0.0"))), + Launcher, + "{maven_3}" + ); + } + for maven_4 in ["4.0.0", "4.0.0-rc-7", "4.1.2"] { + assert_eq!( + form(Some(&wrapper(maven_4)), Some(&pom("4.0.0"))), + Session, + "{maven_4}" + ); + } + // A model only Maven 4 reads, named by the element or the namespace. + assert_eq!(form(None, Some(&pom("4.1.0"))), Session); + let by_namespace = "\n\n"; + assert_eq!(form(None, Some(by_namespace)), Session); + // A 4.0.0 model under the 4.1.0 namespace is a pom Maven 3.9.2 to + // 3.9.8 build, so it must not get the line that stops them. + let mixed = "\n \ + 4.0.0\n\n"; + assert_eq!(form(None, Some(mixed)), Launcher); + // A commented-out model is not the pom's. + let commented = "\n \n \ + 4.0.0\n\n"; + assert_eq!(form(None, Some(commented)), Launcher); + assert_eq!(form(None, Some("not a pom")), Launcher); + } + + #[test] + fn either_spelling_is_hosted_modes_and_one_heals_into_the_other() { + use Basedir::{Launcher, Session}; + let written = |form| format!("{}\n", config_args(form).join("\n")); + for (form, other) in [(Launcher, Session), (Session, Launcher)] { + let config = written(form); + assert!(config_enforces(&config) && is_written_config(&config)); + assert_eq!(Settings::read(&config).basedir(), Some(form)); + assert_eq!(heal_basedir(&config, form), None); + assert_eq!( + heal_basedir(&config, other).as_deref(), + Some(written(other).as_str()) + ); + } + // The user's own lines, the line endings and a missing final line + // break are kept: only the directory changes. + let mixed = format!("-B\r\n{}\r\n# end", config_args(Session).join("\r\n")); + assert_eq!( + heal_basedir(&mixed, Launcher), + Some(mixed.replace(basedir_value(Session), basedir_value(Launcher))) + ); + // A directory line that stands apart from the other five was there + // before hosted mode appended them: the user's, left as written. + let theirs = format!("-D{BASEDIR_KEY}={}\n", basedir_value(Session)); + let appended: Vec<&str> = config_args(Session) + .iter() + .copied() + .filter(|arg| !arg.contains(BASEDIR_KEY)) + .collect(); + let merged = format!("{theirs}{}\n", appended.join("\n")); + assert!(config_enforces(&merged)); + assert_eq!(heal_basedir(&merged, Launcher), None); + assert_eq!(heal_basedir(&theirs, Launcher), None); + assert!(!holds_written_block(&merged) && !holds_written_block(&theirs)); + assert!(holds_written_block(&mixed) && holds_written_block(&written(Launcher))); + assert!(!holds_written_block("")); + assert!(!is_written_config(&merged)); + assert!(!is_written_config(&format!("-B\n{}", written(Launcher)))); + } + + /// The block is what marks the line as hosted mode's, not what the + /// settings come to: the line stops Maven from starting whether or not + /// the pin is enforced. + #[test] + fn the_block_is_healed_whatever_else_the_config_sets() { + use Basedir::{Launcher, Session}; + let block = |form| config_args(form).join("\n"); + for extra in [ + // A later line switches the pin off, or names another directory. + format!("-D{SWITCH_KEY}=false"), + format!("-D{BASEDIR_KEY}=/opt/checksums"), + "-Daether.trustedChecksumsSource.summaryFile.originAware=true".to_string(), + "-T4".to_string(), + ] { + let config = format!("{}\n{extra}\n", block(Session)); + assert_eq!( + heal_basedir(&config, Launcher), + Some(format!("{}\n{extra}\n", block(Launcher))), + "{extra}" + ); + } + // Every block in the file, when an earlier run left two. + let twice = format!("{}\n-B\n{}\n", block(Session), block(Session)); + assert_eq!( + heal_basedir(&twice, Launcher), + Some(format!("{}\n-B\n{}\n", block(Launcher), block(Launcher))) + ); + // Five of the six, or the six in another order, are not the block. + let five = config_args(Session)[1..].join("\n"); + assert_eq!(heal_basedir(&five, Launcher), None); + let mut shuffled = config_args(Session).to_vec(); + shuffled.swap(0, 1); + assert_eq!(heal_basedir(&shuffled.join("\n"), Launcher), None); + // An indented or quoted line is not the line hosted mode wrote. + let indented = block(Session).replace( + "-Daether.trustedChecksumsSource", + " -Daether.trustedChecksumsSource", + ); + assert_eq!(heal_basedir(&indented, Launcher), None); + } + + #[test] + fn a_checksum_file_names_a_hosted_artifact_by_its_suffixed_version() { + assert!(names_hosted_artifact(&format!("{A} {OURS}\n"))); + // In any spelling of the line: it is still hosted mode's path. + assert!(names_hosted_artifact(&format!( + "{}\t*{OURS}\r\n", + A.to_uppercase() + ))); + assert!(!names_hosted_artifact(&format!( + "{A} org/x/1.0/x-1.0.jar\n# {B} {OURS}\n" + ))); + assert!(!names_hosted_artifact("")); } } diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index f492c64af..4110117c2 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -880,6 +880,33 @@ async fn read_go_workspace( } } +/// The files a hosted scan with nothing to redirect still reads, so that +/// the Maven rewriter can heal a `.mvn/maven.config` an earlier release +/// wrote: `None` unless that file holds the Trusted Checksums block in a +/// spelling some project is healed out of +/// ([`crate::formats::maven::trusted_checksums::heal_basedir`]), and then +/// it, the Maven Wrapper's properties and the root pom, which say which +/// spelling this project takes. The line an earlier release wrote stops +/// Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the project +/// whether or not a patch still applies, so a project whose only patched +/// dependency was bumped past the patch must not keep it for ever. +pub async fn read_maven_heal_files(view: &ProjectView<'_>) -> Option { + use crate::formats::maven::trusted_checksums::holds_written_block; + use crate::patch::redirect::{MVN_CONFIG, MVN_WRAPPER_PROPERTIES}; + let none = BTreeSet::new(); + let mut out = CandidateFiles::default(); + if !out.read(view, &none, MVN_CONFIG).await { + return None; + } + if !holds_written_block(out.files.get(MVN_CONFIG)?) { + return None; + } + for rel in [MVN_WRAPPER_PROPERTIES, "pom.xml"] { + out.read(view, &none, rel).await; + } + Some(out) +} + /// Read the project's candidate files: [`REDIRECT_CANDIDATE_FILES`], the /// Cargo workspace members (when a cargo candidate meets a root /// `Cargo.toml`), the Python locks and their scripts, the Rush locks, and @@ -2071,6 +2098,19 @@ pub struct Rewritten { pub final_discovery: Option, } +impl Rewritten { + /// Take the Maven rewriter's respelling of `.mvn/maven.config` back + /// out of what this run writes and reports + /// ([`crate::patch::redirect::withhold_maven_heal`]): for a caller that + /// could not take the write lock. + pub fn withhold_maven_heal(&mut self) { + if crate::patch::redirect::withhold_maven_heal(&mut self.rewrite) { + self.rewritten + .retain(|rel| rel != crate::patch::redirect::MVN_CONFIG); + } + } +} + /// Where [`Rewritten::final_discovery`] lives. #[derive(Debug)] pub enum FinalDiscovery { @@ -2755,6 +2795,19 @@ async fn rewrite_once( ); (files, rewrite) }; + // The Maven rewriter's respelling of `.mvn/maven.config` is a courtesy, + // never the reason a run is refused or fails: where the file cannot be + // replaced (a symbolic link, which the guard refuses for every write; + // a directory that does not take the write) the line is left as it is. + if crate::patch::redirect::carries_maven_heal(&rewrite) { + let writable = match view { + ProjectView::Disk(root) => crate::patch::redirect::maven_config_writable(root).await, + _ => !view.is_symlink(crate::patch::redirect::MVN_CONFIG), + }; + if !writable { + crate::patch::redirect::withhold_maven_heal(&mut rewrite); + } + } // The gem files were withheld on purpose: say why, not "no Gemfile". if let Some(warning) = gem_refusal { rewrite @@ -5981,6 +6034,180 @@ snapshots: (read, done) } + /// A run with nothing to redirect: [`read_maven_heal_files`] then + /// [`rewrite`] with no candidate. + async fn heal_only(view: &ProjectView<'_>) -> Option { + let outer = OuterAllowRemote::default; + let options = RewriteOptions { + dry_run: false, + targets_pipenv_lock: false, + pipenv_major: None, + pipenv_unknown_detail: String::new(), + trust_lockfile_config: true, + npm_allow_remote_config: true, + npm_outer: &outer, + yarn_classic_outer: &OuterYarnMirror::default, + cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, + pnpm_env: &no_env, + blocking: false, + takeover_uuids: Default::default(), + patch_server_origins: Vec::new(), + prior_discovery: None, + }; + let read = read_maven_heal_files(view).await?; + Some(rewrite(view, read, &[], BTreeMap::new(), options).await) + } + + const PLAIN_POM: &str = "\n \ + 4.0.0\n t\n \ + app\n 1\n\n"; + + fn checksums_block(form: crate::formats::maven::trusted_checksums::Basedir) -> String { + format!( + "{}\n", + crate::formats::maven::trusted_checksums::config_args(form).join("\n") + ) + } + + /// A scan that redirects nothing reads the Maven files only when + /// `.mvn/maven.config` holds a block to heal, and then heals it: on + /// disk and in memory alike. + #[tokio::test] + async fn a_run_with_nothing_to_redirect_heals_the_maven_config() { + use crate::formats::maven::trusted_checksums::Basedir::{Launcher, Session}; + use crate::patch::redirect::{MVN_CONFIG, MVN_WRAPPER_PROPERTIES}; + let wrapper_4 = "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/\ + apache-maven/4.0.0/apache-maven-4.0.0-bin.zip\n"; + // (the config, a Maven 4 wrapper, what the heal leaves) + for (config, maven_4, healed) in [ + ( + checksums_block(Session), + false, + Some(checksums_block(Launcher)), + ), + ( + checksums_block(Launcher), + true, + Some(checksums_block(Session)), + ), + ( + format!("-T4\n{}", checksums_block(Session)), + false, + Some(format!("-T4\n{}", checksums_block(Launcher))), + ), + // This project's own spelling, or no block: nothing to do. + (checksums_block(Launcher), false, None), + (checksums_block(Session), true, None), + ("-T4\n".to_string(), false, None), + ] { + let tmp = tempfile::tempdir().unwrap(); + let mut memory = MemoryProject::new(); + let mut put = |rel: &str, text: &str| { + let path = tmp.path().join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + memory.insert_text(rel, text); + }; + put("pom.xml", PLAIN_POM); + put(MVN_CONFIG, &config); + if maven_4 { + put(MVN_WRAPPER_PROPERTIES, wrapper_4); + } + for view in [ProjectView::Disk(tmp.path()), ProjectView::Memory(&memory)] { + let done = heal_only(&view).await; + let Some(healed) = &healed else { + // A block in the other spelling is read, and found to + // be this project's; no block is not read at all. + assert!( + done.is_none_or( + |done| done.rewrite.files.is_empty() && done.rewrite.edits.is_empty() + ), + "{config:?} / Maven 4: {maven_4}" + ); + continue; + }; + let mut done = done.expect("a block to heal"); + assert_eq!( + done.rewrite.files.keys().collect::>(), + [MVN_CONFIG], + "{config:?}" + ); + assert_eq!(&done.rewrite.files[MVN_CONFIG], healed); + assert_eq!(done.rewritten, [MVN_CONFIG]); + assert!(done.confirmed.is_empty()); + assert!(guard(&view, &done, &[]).is_none()); + let codes: Vec<&str> = done + .rewrite + .warnings + .iter() + .map(|w| w.code.as_str()) + .collect(); + // Only the heal that takes the session's property out of a + // project that declares no Maven trades anything away. + let trade: &[&str] = if maven_4 { + &[] + } else { + &["redirect_maven_trusted_checksums_maven3_only"] + }; + assert_eq!(codes, trade, "{config:?}"); + + // A caller that cannot write withholds all of it. + done.withhold_maven_heal(); + assert!(done.rewrite.files.is_empty()); + assert!(done.rewrite.edits.is_empty()); + assert!(done.rewrite.warnings.is_empty()); + assert!(done.rewritten.is_empty()); + } + } + // No config at all: nothing is read. + let empty = tempfile::tempdir().unwrap(); + std::fs::write(empty.path().join("pom.xml"), PLAIN_POM).unwrap(); + assert!(heal_only(&ProjectView::Disk(empty.path())).await.is_none()); + } + + /// The heal is a courtesy, never the reason a run is refused. A write + /// through a symbolic link would replace the link, which the guard + /// refuses for every write: a `.mvn/maven.config` that is a link keeps + /// its line, and the run goes on as if there were nothing to heal. + #[cfg(unix)] + #[tokio::test] + async fn a_symlinked_maven_config_is_left_unhealed_and_refuses_nothing() { + use crate::formats::maven::trusted_checksums::Basedir::Session; + use crate::patch::redirect::MVN_CONFIG; + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join("pom.xml"), PLAIN_POM).unwrap(); + std::fs::create_dir_all(tmp.path().join(".mvn")).unwrap(); + std::fs::create_dir_all(tmp.path().join("ci")).unwrap(); + std::fs::write(tmp.path().join("ci/maven.config"), checksums_block(Session)).unwrap(); + std::os::unix::fs::symlink("../ci/maven.config", tmp.path().join(MVN_CONFIG)).unwrap(); + let view = ProjectView::Disk(tmp.path()); + let done = heal_only(&view).await.expect("the block is read"); + assert!(done.rewrite.files.is_empty(), "{:?}", done.rewrite.files); + assert!(done.rewrite.edits.is_empty() && done.rewrite.warnings.is_empty()); + assert!(done.rewritten.is_empty()); + assert!(guard(&view, &done, &[]).is_none()); + + // Control: the same file, not a link, is healed. + std::fs::remove_file(tmp.path().join(MVN_CONFIG)).unwrap(); + std::fs::write(tmp.path().join(MVN_CONFIG), checksums_block(Session)).unwrap(); + let done = heal_only(&view).await.expect("the block is read"); + assert_eq!(done.rewritten, [MVN_CONFIG]); + + // Nor is it planned into a directory that does not take the write: + // the commit would fail a run that had nothing else to do. (Root + // writes anywhere, so there is nothing to see as root.) + if unsafe { libc::geteuid() } != 0 { + use std::os::unix::fs::PermissionsExt as _; + let dir = tmp.path().join(".mvn"); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap(); + let done = heal_only(&view).await.expect("the block is read"); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(done.rewrite.files.is_empty() && done.rewritten.is_empty()); + assert!(done.rewrite.edits.is_empty() && done.rewrite.warnings.is_empty()); + } + } + /// The Gradle pass reads the script graph's scripts and every build's /// lock files (nested ones included), and the planner pins them. #[tokio::test] diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index ebcc01a76..d1228e82b 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -71,7 +71,10 @@ use crate::formats::gem::hosted::{ merge_gem_lock_remote, refresh_merged_gem_lock_remote, DependencyPin, LockLayout, }; use crate::formats::gem::locked_specs as gem_locked_specs; -use crate::formats::maven::trusted_checksums::{self, CONFIG_ARGS as MVN_CONFIG_ARGS}; +use crate::formats::maven::declared_maven::DeclaredMaven; +use crate::formats::maven::trusted_checksums; +#[cfg(test)] +use crate::formats::maven::trusted_checksums::CONFIG_ARGS as MVN_CONFIG_ARGS; #[cfg(test)] use crate::formats::pnpm::hosted::pnpm_unrewritten_instances; use crate::formats::pnpm::plan_hosted; @@ -8997,6 +9000,31 @@ fn rewrite_maven_pom( .iter() .filter(|o| o.ecosystem == "maven") .collect(); + // Nothing to redirect for Maven and no block hosted mode wrote to + // heal: nothing to do, and no pom to read to find that out. + let holds_block = files + .get(MVN_CONFIG) + .is_some_and(|config| trusted_checksums::holds_written_block(config)); + if maven.is_empty() && !holds_block { + return; + } + // The Maven the project declares, and so how its `.mvn/maven.config` + // spells the Trusted Checksums directory: the form that breaks no + // Maven 3 build, unless the project declares Maven 4. + let declared = DeclaredMaven::of( + files.get(MVN_WRAPPER_PROPERTIES).map(String::as_str), + files.get("pom.xml").map(String::as_str), + ); + let basedir = trusted_checksums::Basedir::for_maven(&declared); + // First, and whatever this run redirects: the block an earlier run or + // an earlier release wrote in the other spelling is rewritten to this + // project's. The line stops Maven 3.9.2 to 3.9.8 from starting with + // `-f` from outside the project whether or not a pin still needs it, + // so no return below (nothing to redirect for Maven, a root another + // rewriter owns, a reactor root) may come before it. + let healed = holds_block + .then(|| heal_mvn_config(files, basedir, &declared, result)) + .flatten(); if maven.is_empty() { return; } @@ -9061,8 +9089,14 @@ fn rewrite_maven_pom( .iter() .filter_map(|(id, _)| generation::pin_name_uuid(id, false).map(str::to_string)) .collect(); - let mut mvn_config = files.get(MVN_CONFIG).cloned().unwrap_or_default(); + let mut mvn_config = healed + .or_else(|| files.get(MVN_CONFIG).cloned()) + .unwrap_or_default(); let mut mvn_config_changed = false; + // The Trusted Checksums settings are merged in once per run, with the + // first dependency that carries checksums; the settings found set to + // another value are reported for each such dependency. + let mut mvn_conflicts: Option> = None; // (local-repo-relative path, bare sha256 hex) entries to merge in. let mut checksum_entries: Vec<(String, String)> = vec![]; // Trusted-checksum paths of superseded generations' suffixed artifacts: @@ -9711,29 +9745,34 @@ fn rewrite_maven_pom( }); } if let Some((jar, pom_hash)) = &checksum_hashes { - let (merged, conflicts) = - merge_mvn_config(&mvn_config, &format!("{group_id}:{artifact_id}")); - for conflict in conflicts { + 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: conflict, - }); - } - if merged != mvn_config { - let action = if files.contains_key(MVN_CONFIG) { - "rewritten" - } else { - "added" - }; - mvn_config = merged; - mvn_config_changed = true; - result.edits.push(FileEdit { - path: MVN_CONFIG.into(), - kind: "redirect_maven_config".into(), - action: action.into(), - key: Some("trustedChecksums".into()), - original: None, - new: None, + 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(( @@ -9794,31 +9833,176 @@ fn rewrite_maven_pom( // The pin is written regardless (a later wrapper upgrade enforces it, and // the version suffix is fail-closed on its own), but a project whose - // wrapper pins a Maven that ignores it must not read it as client-side - // content pinning. Judged on the files as they stand after this run, so a + // declared Maven ignores it must not read it as client-side content + // pinning. Judged on the files as they stand after this run, so a // re-scan of an already-pinned project warns as well. let final_text = |rel: &str| result.files.get(rel).or_else(|| files.get(rel)); - let pin_in_place = final_text(MVN_CONFIG) - .is_some_and(|c| trusted_checksums::config_enforces(c)) - && final_text(MVN_CHECKSUMS).is_some_and(|c| { - let pinned = trusted_checksums::pinned(c); - pinned_jar_paths.iter().any(|p| pinned.contains_key(p)) - }); - if let Some(version) = files - .get(MVN_WRAPPER_PROPERTIES) - .and_then(|props| trusted_checksums::wrapper_maven_version(props)) - .filter(|v| pin_in_place && !trusted_checksums::maven_enforces(v)) - { + let pinned_here = final_text(MVN_CHECKSUMS).is_some_and(|c| { + let pinned = trusted_checksums::pinned(c); + pinned_jar_paths.iter().any(|p| pinned.contains_key(p)) + }); + let enforcement = match final_text(MVN_CONFIG).filter(|_| pinned_here) { + Some(config) => { + trusted_checksums::enforcement(&trusted_checksums::Settings::read(config), &declared) + } + None => trusted_checksums::Enforcement::Off, + }; + if let Some(detail) = unenforced_detail(&enforcement, &declared) { result.warnings.push(RewriteWarning { code: "redirect_maven_trusted_checksums_unenforced".into(), - detail: format!( - "{MVN_WRAPPER_PROPERTIES} pins Maven {version}, which does not enforce the \ - Trusted Checksums pin in {MVN_CHECKSUMS} (Maven enforces it from 3.9.4); \ - only the transport .sha1 check guards the Socket-served artifacts. \ - Upgrade the Maven Wrapper to 3.9.4 or later" - ), + detail, + }); + } +} + +/// 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 +/// `result`, and the healed text is returned. +/// +/// Rewriting `${session.rootDirectory}` to the launcher's property in a +/// project that declares no Maven trades something away: a Maven 4 build +/// enforced the pin before and does not after. That is said, never done +/// silently (`redirect_maven_trusted_checksums_maven3_only`). +fn heal_mvn_config( + files: &BTreeMap, + basedir: trusted_checksums::Basedir, + declared: &DeclaredMaven, + result: &mut RewriteResult, +) -> Option { + let healed = trusted_checksums::heal_basedir(files.get(MVN_CONFIG)?, basedir)?; + result.edits.push(FileEdit { + path: MVN_CONFIG.into(), + kind: "redirect_maven_config".into(), + action: "rewritten".into(), + key: Some(MVN_CONFIG_HEAL_KEY.into()), + original: None, + new: None, + }); + if let Some(detail) = heal_trade_detail(&healed, declared, "") { + result.warnings.push(RewriteWarning { + code: MVN_CONFIG_HEAL_TRADE.into(), + detail, }); } + result.files.insert(MVN_CONFIG.into(), healed.clone()); + Some(healed) +} + +/// The `key` of the `redirect_maven_config` edit that respells the Trusted +/// Checksums directory line ([`heal_mvn_config`]), which tells it from the +/// edit that merges the settings in (`trustedChecksums`). +pub(crate) const MVN_CONFIG_HEAL_KEY: &str = "trustedChecksumsDirectory"; + +/// The warning a heal carries when it trades the pin's enforcement on +/// Maven 4 away ([`heal_trade_detail`]). +const MVN_CONFIG_HEAL_TRADE: &str = "redirect_maven_trusted_checksums_maven3_only"; + +/// Take the respelling of `.mvn/maven.config` back out of `result`: the +/// file, its edit and the warning that goes with it. `true` when there was +/// one. +/// +/// The heal is a courtesy to a project an earlier release wired, never the +/// reason a run fails: a caller that cannot write the file (it is a +/// symbolic link, which a write would replace; the write lock could not be +/// had) leaves the line as it is. A run that heals merges nothing into the +/// config afterwards (the block holds every setting), so the file's whole +/// change is the heal. +pub(crate) fn withhold_maven_heal(result: &mut RewriteResult) -> bool { + if !carries_maven_heal(result) { + return false; + } + result.files.remove(MVN_CONFIG); + result.edits.retain(|edit| !is_maven_heal(edit)); + result.warnings.retain(|w| w.code != MVN_CONFIG_HEAL_TRADE); + true +} + +fn is_maven_heal(edit: &FileEdit) -> bool { + edit.path == MVN_CONFIG && edit.key.as_deref() == Some(MVN_CONFIG_HEAL_KEY) +} + +/// Whether `result` respells `.mvn/maven.config` ([`heal_mvn_config`]). +pub(crate) fn carries_maven_heal(result: &RewriteResult) -> bool { + result.edits.iter().any(is_maven_heal) +} + +/// Whether the writers could replace the `.mvn/maven.config` under `root`: +/// what every staged write is checked for before anything is written +/// ([`staged::preflight`]). A symbolic link (a rename-over would replace +/// it with a detached copy), anything else that is not a regular file, and +/// a directory that does not take the write all refuse the whole run they +/// are part of, which a heal must never do. +pub(crate) async fn maven_config_writable(root: &std::path::Path) -> bool { + let pending = vec![staged::Pending { + rel: MVN_CONFIG, + content: Some(b"".as_slice()), + read: None, + }]; + staged::preflight(root, pending).await.is_ok() +} + +/// What rewriting the Trusted Checksums directory line of the +/// `.mvn/maven.config` under `dir` (`""`, or a path ending in `/`) to the +/// launcher's property traded away, when `healed` (the config after the +/// rewrite) is enforced by Maven 3 only: `None` when nothing was traded (the +/// project declares its Maven, or the config enforces nothing). +pub(crate) fn heal_trade_detail( + healed: &str, + declared: &DeclaredMaven, + dir: &str, +) -> Option { + use trusted_checksums::{basedir_value, Basedir, Enforcement, Settings}; + (trusted_checksums::enforcement(&Settings::read(healed), declared) == Enforcement::Maven3Only) + .then(|| { + format!( + "{dir}{MVN_CONFIG} named the Trusted Checksums directory as {session}, which \ + stops Maven 3.9.2 to 3.9.8 from starting when a build is run with -f from \ + outside the project; the line now names it as {launcher}. Maven 3.9.4 and \ + later 3.x enforce the checksums in {dir}{MVN_CHECKSUMS} as before. A Maven 4 \ + build of this project no longer does: Maven 4 does not read that property. \ + If Maven 4 builds this project, declare it (a Maven Wrapper that pins Maven \ + 4, or a root pom of model 4.1.0): the next hosted scan then writes the form \ + Maven 4 reads", + session = basedir_value(Basedir::Session), + launcher = basedir_value(Basedir::Launcher), + ) + }) +} + +/// Why the Trusted Checksums pin is not enforced by the Maven the project +/// declares, and what changes that; `None` when it is, or when the project +/// declares no Maven to judge by ([`trusted_checksums::Enforcement`]). +fn unenforced_detail( + enforcement: &trusted_checksums::Enforcement, + declared: &DeclaredMaven, +) -> Option { + use trusted_checksums::{basedir_value, Basedir, Enforcement}; + let unguarded = "only the transport .sha1 check guards the Socket-served artifacts"; + match enforcement { + Enforcement::TooOld(version) => Some(format!( + "{MVN_WRAPPER_PROPERTIES} pins Maven {version}, which does not enforce the \ + Trusted Checksums pin in {MVN_CHECKSUMS} (Maven enforces it from 3.9.4); \ + {unguarded}. Upgrade the Maven Wrapper to 3.9.4 or later" + )), + Enforcement::UnreadByMaven4 => { + let declares = match declared.release() { + Some(version) if !declared.maven_4_model() => { + format!("{MVN_WRAPPER_PROPERTIES} pins Maven {version}") + } + _ => "pom.xml is of a model only Maven 4 reads".to_string(), + }; + Some(format!( + "{declares}, and Maven 4 does not read {property}, through which {MVN_CONFIG} \ + names the Trusted Checksums directory, so the pin in {MVN_CHECKSUMS} is not \ + enforced; {unguarded}. Set the line to -D{key}={session}", + property = Basedir::Launcher.property(), + session = basedir_value(Basedir::Session), + key = trusted_checksums::BASEDIR_KEY, + )) + } + Enforcement::Off | Enforcement::Maven3Only | Enforcement::Enforced => None, + } } static MAVEN_REPOSITORY_RE: LazyLock = LazyLock::new(|| { @@ -9867,30 +10051,35 @@ pub(crate) fn maven_repository_removal(pom: &str, id: &str) -> Option<(usize, us /// Merge trusted-checksums resolver args into `.mvn/maven.config` (one arg per /// line). A setting is present when Maven 3.9+ reads it from the file -/// ([`crate::formats::maven::maven_config_line_properties`], the reader -/// discovery's [`trusted_checksums::config_enforces`] uses: `-Dk=v`, +/// ([`trusted_checksums::Settings`], the reader discovery uses: `-Dk=v`, /// `--define k=v`, indented or quoted lines, the last definition winning). /// A present setting is left untouched (existing value wins); a different -/// value is reported as a conflict. Returns the merged text + those -/// conflict messages. Twin of the TS `mergeMvnConfig`. -fn merge_mvn_config(existing: &str, coordinate: &str) -> (String, Vec) { - let present = crate::formats::maven::maven_config_line_properties(existing); +/// value is a conflict. The directory setting in the other spelling hosted +/// mode writes ([`trusted_checksums::Basedir`]) is no conflict where it +/// names the same directory, which is everywhere but in a project that +/// declares Maven 4 (`declared`): Maven 4 does not read the launcher's +/// property, so that line names no directory there. Returns the merged +/// text and each conflicting setting as `(key, the value in place)`. The +/// rewriter's other implementation, in Socket's backend, merges the same +/// way. +fn merge_mvn_config( + existing: &str, + basedir: trusted_checksums::Basedir, + declared: &DeclaredMaven, +) -> (String, Vec<(&'static str, String)>) { + let present = trusted_checksums::Settings::read(existing); let mut conflicts = vec![]; let mut appended: Vec<&str> = vec![]; - for arg in MVN_CONFIG_ARGS { - let (key, value) = arg - .strip_prefix("-D") - .and_then(|def| def.split_once('=')) - .expect("every MVN_CONFIG_ARGS entry is -Dkey=value"); - match present.get(key) { - None => appended.push(arg), - Some(existing_value) if existing_value != value => { - conflicts.push(format!( - "{coordinate}: {MVN_CONFIG} already sets -D{key}= to a different value \ - (-D{key}={existing_value}); leaving it as-is" - )); - } - Some(_) => {} + for (arg, key, value) in trusted_checksums::config_settings(basedir) { + let Some(existing_value) = present.get(key) else { + appended.push(arg); + continue; + }; + let same_directory = key == trusted_checksums::BASEDIR_KEY + && trusted_checksums::basedir_of_value(existing_value) + .is_some_and(|theirs| !theirs.unread_by(declared)); + if existing_value != value && !same_directory { + conflicts.push((key, existing_value.to_string())); } } if appended.is_empty() { @@ -11759,6 +11948,428 @@ mod tests { assert!(checksums.contains(&format!("{} ", "d".repeat(64)))); } + /// The Trusted Checksums directory is spelled so that no Maven the + /// project may be built with refuses to start: through the launcher's + /// property, unless the project declares Maven 4 (its wrapper, or a + /// 4.1.0 model), which reads only the session's. A project an earlier + /// release wired with the session's is healed on its next scan, in + /// that one line; a directory line the user wrote is not. + #[test] + fn maven_checksums_directory_follows_the_maven_the_project_declares() { + use trusted_checksums::Basedir::{Launcher, Session}; + let pom = pom_with_dep("\n 1.7.36", ""); + let run = |files: &BTreeMap| { + rewrite_registry_redirect(files, &[maven_override()]) + }; + let form = + |r: &RewriteResult| trusted_checksums::Settings::read(&r.files[MVN_CONFIG]).basedir(); + let value = trusted_checksums::basedir_value; + let codes = |r: &RewriteResult| -> Vec { + r.warnings.iter().map(|w| w.code.clone()).collect() + }; + let plain = BTreeMap::from([("pom.xml".to_string(), pom.clone())]); + let wired = run(&plain); + assert_eq!(form(&wired), Some(Launcher)); + for (wrapper, expected) in [ + ("3.9.2", Launcher), + ("3.9.8", Launcher), + ("3.9.16", Launcher), + ("4.0.0-rc-7", Session), + ("4.0.0", Session), + ] { + let mut files = plain.clone(); + files.insert(MVN_WRAPPER_PROPERTIES.to_string(), maven_wrapper(wrapper)); + let r = run(&files); + assert_eq!(form(&r), Some(expected), "{wrapper}"); + // Each of those Mavens enforces the form it is given, but the + // two that predate SHA-256 support. + assert_eq!( + codes(&r).contains(&"redirect_maven_trusted_checksums_unenforced".to_string()), + wrapper == "3.9.2", + "{wrapper}: {:?}", + r.warnings + ); + } + let model_4_1 = BTreeMap::from([( + "pom.xml".to_string(), + pom.replace("4.0.0", "4.1.0"), + )]); + assert_ne!(model_4_1["pom.xml"], pom); + assert_eq!(form(&run(&model_4_1)), Some(Session)); + + // An earlier release's wiring: the same files, the session's form. + let mut earlier = plain.clone(); + earlier.extend(wired.files.clone()); + let old = earlier[MVN_CONFIG].replace(value(Launcher), value(Session)); + assert_ne!(old, earlier[MVN_CONFIG]); + earlier.insert(MVN_CONFIG.to_string(), old); + let healed = run(&earlier); + assert_eq!(healed.files.keys().collect::>(), [MVN_CONFIG]); + assert_eq!(healed.files[MVN_CONFIG], wired.files[MVN_CONFIG]); + assert_eq!( + healed + .edits + .iter() + .map(|e| (e.path.as_str(), e.kind.as_str(), e.action.as_str())) + .collect::>(), + [(MVN_CONFIG, "redirect_maven_config", "rewritten")] + ); + // The project declares no Maven, so the heal trades the pin's + // enforcement on Maven 4 for a build that starts everywhere, and + // says so. + assert_eq!( + codes(&healed), + ["redirect_maven_trusted_checksums_maven3_only"], + "{:?}", + healed.warnings + ); + let said = &healed.warnings[0].detail; + for part in [ + "Maven 3.9.2 to 3.9.8", + "Maven 3.9.4 and later 3.x enforce", + "A Maven 4 build of this project no longer does", + "a Maven Wrapper that pins Maven 4, or a root pom of model 4.1.0", + value(Session), + value(Launcher), + ] { + assert!(said.contains(part), "{part}: {said}"); + } + // Once, with the change: the next scan has nothing to say. + let mut settled = earlier.clone(); + settled.extend(healed.files.clone()); + let rescan = run(&settled); + assert!(rescan.files.is_empty()); + assert!(rescan.warnings.is_empty(), "{:?}", rescan.warnings); + // A project whose wrapper names a Maven 3 that enforces either + // spelling trades nothing, so its heal is silent. + let mut maven_3 = earlier.clone(); + maven_3.insert(MVN_WRAPPER_PROPERTIES.to_string(), maven_wrapper("3.9.9")); + let healed_3 = run(&maven_3); + assert_eq!(healed_3.files[MVN_CONFIG], wired.files[MVN_CONFIG]); + assert!(healed_3.warnings.is_empty(), "{:?}", healed_3.warnings); + // The same wiring in a project that declares Maven 4 is right as + // it is, and the launcher's form there is healed the other way. + let mut maven_4 = earlier.clone(); + maven_4.insert( + MVN_WRAPPER_PROPERTIES.to_string(), + maven_wrapper("4.0.0-rc-7"), + ); + assert!(run(&maven_4).files.is_empty()); + maven_4.insert(MVN_CONFIG.to_string(), wired.files[MVN_CONFIG].clone()); + let to_session = run(&maven_4); + assert_eq!(form(&to_session), Some(Session)); + assert!(to_session.warnings.is_empty(), "{:?}", to_session.warnings); + + // A directory line the user wrote, in the form Maven's own + // documentation gives: no conflict (it names the same directory), + // the missing settings are appended, and the line stays theirs. + let theirs = format!("-D{}={}\n", trusted_checksums::BASEDIR_KEY, value(Session)); + let users = BTreeMap::from([ + ("pom.xml".to_string(), pom.clone()), + (MVN_CONFIG.to_string(), theirs.clone()), + ]); + let r = run(&users); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(r.files[MVN_CONFIG].starts_with(&theirs)); + assert_eq!(form(&r), Some(Session)); + assert!(trusted_checksums::config_enforces(&r.files[MVN_CONFIG])); + let mut again = users.clone(); + again.extend(r.files.clone()); + assert!(run(&again).files.is_empty()); + } + + /// The line an earlier release wrote stops Maven 3.9.2 to 3.9.8 from + /// starting whatever this run redirects. So the heal is tied to + /// nothing but the block hosted mode wrote: not to a Maven patch in + /// this run, not to a pin's checksum line, not to a root the pom + /// rewriter edits, not to a config that still enforces anything. + #[test] + fn maven_checksums_block_is_healed_whatever_the_run_redirects() { + use trusted_checksums::Basedir::{Launcher, Session}; + let block = |form| format!("{}\n", trusted_checksums::config_args(form).join("\n")); + let config_edits = |r: &RewriteResult| -> Vec<(String, String)> { + r.edits + .iter() + .filter(|e| e.path == MVN_CONFIG) + .map(|e| (e.kind.clone(), e.action.clone())) + .collect() + }; + let one_rewrite = [("redirect_maven_config".to_string(), "rewritten".to_string())]; + let trade = "redirect_maven_trusted_checksums_maven3_only"; + let pinned = pom_with_dep("\n 1.7.36", ""); + // The dependency was bumped past the patched version: no patch + // applies any more, the block and a stale checksum line stay. + let bumped = BTreeMap::from([ + ( + "pom.xml".to_string(), + pom_with_dep("\n 2.0.9", ""), + ), + (MVN_CONFIG.to_string(), block(Session)), + ( + MVN_CHECKSUMS.to_string(), + format!( + "{} org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar\n", + "a".repeat(64) + ), + ), + ]); + let r = rewrite_registry_redirect(&bumped, &[]); + assert_eq!(r.files.keys().collect::>(), [MVN_CONFIG]); + assert_eq!(r.files[MVN_CONFIG], block(Launcher)); + assert_eq!(config_edits(&r), one_rewrite); + assert_eq!(warning_codes(&r), [trade]); + + // No checksum line names a hosted artifact, or no checksum file is + // there at all (a rollback left the block beside the user's own + // settings): the block alone is the evidence. + for sums in [Some("# mine\n".to_string()), None] { + let mut left = bumped.clone(); + left.insert(MVN_CONFIG.to_string(), format!("-T4\n{}", block(Session))); + match &sums { + Some(text) => left.insert(MVN_CHECKSUMS.to_string(), text.clone()), + None => left.remove(MVN_CHECKSUMS), + }; + let r = rewrite_registry_redirect(&left, &[]); + assert_eq!(r.files.keys().collect::>(), [MVN_CONFIG], "{sums:?}"); + assert_eq!(r.files[MVN_CONFIG], format!("-T4\n{}", block(Launcher))); + assert_eq!(warning_codes(&r), [trade], "{sums:?}"); + } + + // A config that no longer enforces the pin (a later line switches + // it off) still stops those Mavens. Nothing is traded there, so + // nothing is said. + let off = format!( + "{}-D{}=false\n", + block(Session), + trusted_checksums::SWITCH_KEY + ); + let mut unenforcing = bumped.clone(); + unenforcing.insert(MVN_CONFIG.to_string(), off.clone()); + let r = rewrite_registry_redirect(&unenforcing, &[]); + assert_eq!( + r.files[MVN_CONFIG], + off.replace( + trusted_checksums::basedir_value(Session), + trusted_checksums::basedir_value(Launcher) + ) + ); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + + // A reactor root, which the pom rewriter refuses whole. + let reactor = BTreeMap::from([ + ( + "pom.xml".to_string(), + pinned.replace( + " ", + " pom\n \n app\n \n ", + ), + ), + (MVN_CONFIG.to_string(), block(Session)), + ]); + assert!(maven_reactor_root(&reactor)); + let r = rewrite_registry_redirect(&reactor, &[maven_override()]); + assert_eq!(r.files.keys().collect::>(), [MVN_CONFIG]); + assert_eq!(r.files[MVN_CONFIG], block(Launcher)); + assert_eq!( + warning_codes(&r), + [trade, "redirect_maven_multimodule_unsupported"] + ); + + // A root the sbt rewriter owns (no pom.xml beside the build). + let sbt_root = BTreeMap::from([ + ( + "project/build.properties".to_string(), + "sbt.version=1.10.7\n".to_string(), + ), + ("build.sbt".to_string(), "name := \"demo\"\n".to_string()), + (MVN_CONFIG.to_string(), block(Session)), + ]); + assert!(sbt::owns_maven_root(&sbt_root)); + let r = rewrite_registry_redirect(&sbt_root, &[maven_override()]); + assert_eq!(r.files[MVN_CONFIG], block(Launcher)); + assert_eq!(config_edits(&r), one_rewrite); + + // A scan that also pins: one edit of the config, the heal. The + // settings are all there, so nothing is merged after it. + let mut repinned = bumped.clone(); + repinned.insert("pom.xml".to_string(), pinned.clone()); + repinned.remove(MVN_CHECKSUMS); + let r = rewrite_registry_redirect(&repinned, &[maven_override()]); + assert_eq!(r.files[MVN_CONFIG], block(Launcher)); + assert_eq!(config_edits(&r), one_rewrite); + assert!(r.files.contains_key(MVN_CHECKSUMS) && r.files.contains_key("pom.xml")); + assert_eq!(warning_codes(&r), [trade]); + + // The other way, for a project that declares Maven 4 by its model + // alone: the launcher's block gets the spelling Maven 4 reads, and + // nothing is traded. + let maven_4 = BTreeMap::from([ + ( + "pom.xml".to_string(), + pinned.replace("4.0.0", "4.1.0"), + ), + (MVN_CONFIG.to_string(), block(Launcher)), + ]); + let r = rewrite_registry_redirect(&maven_4, &[]); + assert_eq!(r.files[MVN_CONFIG], block(Session)); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + + // Nothing to heal, nothing written: this project's own spelling, + // or no block. + for config in [block(Launcher), "-T4\n".to_string()] { + let mut settled = bumped.clone(); + settled.insert(MVN_CONFIG.to_string(), config); + let r = rewrite_registry_redirect(&settled, &[]); + assert!(r.files.is_empty() && r.edits.is_empty() && r.warnings.is_empty()); + } + } + + /// A launcher-spelled directory line that stands apart is the user's + /// and is never rewritten. In a project that declares Maven 4, which + /// does not read that property, it names no directory: that is a + /// conflict, the pin is reported unenforced with the remedy that works + /// on Maven 4, and it is so whether the wrapper or only the root pom's + /// model declares Maven 4. + #[test] + fn maven_checksums_launcher_line_conflicts_in_a_project_that_declares_maven_4() { + use trusted_checksums::Basedir::{Launcher, Session}; + use trusted_checksums::{basedir_value, Enforcement, Settings, BASEDIR_KEY}; + let theirs = format!("-D{BASEDIR_KEY}={}\n", basedir_value(Launcher)); + let pom = pom_with_dep("\n 1.7.36", ""); + let by_wrapper = BTreeMap::from([ + ("pom.xml".to_string(), pom.clone()), + (MVN_CONFIG.to_string(), theirs.clone()), + (MVN_WRAPPER_PROPERTIES.to_string(), maven_wrapper("4.0.0")), + ]); + let by_model = BTreeMap::from([ + ( + "pom.xml".to_string(), + pom.replace("4.0.0", "4.1.0"), + ), + (MVN_CONFIG.to_string(), theirs.clone()), + ]); + assert_ne!(by_model["pom.xml"], pom); + for (files, declares) in [ + ( + &by_wrapper, + format!("{MVN_WRAPPER_PROPERTIES} pins Maven 4.0.0"), + ), + ( + &by_model, + "pom.xml is of a model only Maven 4 reads".to_string(), + ), + ] { + let r = rewrite_registry_redirect(files, &[maven_override()]); + // The user's line stays; the five other settings are appended. + let config = &r.files[MVN_CONFIG]; + assert!(config.starts_with(&theirs), "{config}"); + assert!(!config.contains(basedir_value(Session)), "{config}"); + assert_eq!( + warning_codes(&r), + [ + "redirect_maven_trusted_checksums_conflict", + "redirect_maven_trusted_checksums_unenforced" + ], + "{declares}" + ); + let conflict = &r.warnings[0].detail; + assert!( + conflict.contains(&format!("-D{BASEDIR_KEY}={}", basedir_value(Launcher))), + "{conflict}" + ); + let unenforced = &r.warnings[1].detail; + for part in [ + declares.as_str(), + "Maven 4 does not read", + "is not enforced", + &format!("-D{BASEDIR_KEY}={}", basedir_value(Session)), + ] { + assert!(unenforced.contains(part), "{part}: {unenforced}"); + } + assert!( + !unenforced.contains("Upgrade the Maven Wrapper"), + "{unenforced}" + ); + // What discovery reads the same files as: not enforced. + let declared = DeclaredMaven::of( + files.get(MVN_WRAPPER_PROPERTIES).map(String::as_str), + files.get("pom.xml").map(String::as_str), + ); + assert_eq!( + trusted_checksums::enforcement(&Settings::read(config), &declared), + Enforcement::UnreadByMaven4 + ); + // A rescan merges nothing, and still says the pin is inert. + let mut again = files.clone(); + again.extend(r.files.clone()); + let rescan = rewrite_registry_redirect(&again, &[maven_override()]); + assert!(rescan.files.is_empty(), "{declares}"); + assert_eq!( + warning_codes(&rescan), + ["redirect_maven_trusted_checksums_unenforced"] + ); + } + // The same line in a project that declares a Maven 3, or none: it + // names the directory there, so it is no conflict. + let mut maven_3 = by_wrapper.clone(); + maven_3.insert(MVN_WRAPPER_PROPERTIES.to_string(), maven_wrapper("3.9.9")); + let mut undeclared = by_wrapper.clone(); + undeclared.remove(MVN_WRAPPER_PROPERTIES); + for files in [&maven_3, &undeclared] { + let r = rewrite_registry_redirect(files, &[maven_override()]); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(r.files[MVN_CONFIG].starts_with(&theirs)); + } + } + + /// Several patched dependencies in one run merge the settings once and + /// report a setting the user holds at another value for each of them. + #[test] + fn maven_checksums_conflict_is_reported_for_each_dependency() { + let mut second = maven_override(); + second.name = "slf4j-simple".into(); + second.patch_uuid = "uuid2".into(); + let ov = second.registry_override.as_mut().unwrap(); + ov.index_url = ov.index_url.replace("/uuid/", "/uuid2/"); + ov.identifiers.name = "org.slf4j/slf4j-simple".into(); + ov.identifiers.maven_artifact_id = Some("slf4j-simple".into()); + ov.identifiers.maven_suffixed_version = Some("1.7.36-socket.88888888".into()); + let pom = pom_with_dep("\n 1.7.36", "").replace( + " ", + " \n org.slf4j\n slf4j-simple\n 1.7.36\n \n ", + ); + let files = BTreeMap::from([ + ("pom.xml".to_string(), pom), + ( + MVN_CONFIG.to_string(), + "-Daether.trustedChecksumsSource.summaryFile.originAware=true\n".to_string(), + ), + ]); + let r = rewrite_registry_redirect(&files, &[maven_override(), second]); + let conflicts: Vec<&str> = r + .warnings + .iter() + .filter(|w| w.code == "redirect_maven_trusted_checksums_conflict") + .map(|w| w.detail.as_str()) + .collect(); + assert_eq!(conflicts.len(), 2, "{:?}", r.warnings); + assert!( + conflicts[0].starts_with("org.slf4j:slf4j-api: "), + "{conflicts:?}" + ); + assert!( + conflicts[1].starts_with("org.slf4j:slf4j-simple: "), + "{conflicts:?}" + ); + assert_eq!( + r.edits + .iter() + .filter(|e| e.kind == "redirect_maven_config") + .count(), + 1 + ); + } + /// A user `.mvn/maven.config` key set to a different value is preserved /// (never overridden) and a conflict warning is emitted. /// A Maven Wrapper `maven-wrapper.properties` with the given @@ -11865,45 +12476,6 @@ mod tests { } } - /// The `distributionUrl` parse: escaped or plain `:`, `=`/`:`/space - /// separators, `.tar.gz` distributions, comments and CRLF. - #[test] - fn maven_wrapper_version_parses_distribution_url() { - assert_eq!( - trusted_checksums::wrapper_maven_version(&maven_wrapper("3.9.3")).as_deref(), - Some("3.9.3") - ); - assert_eq!( - trusted_checksums::wrapper_maven_version( - "distributionUrl : https://archive.apache.org/dist/maven/maven-3/3.9.2/binaries/apache-maven-3.9.2-bin.tar.gz\r\n" - ) - .as_deref(), - Some("3.9.2") - ); - assert_eq!( - trusted_checksums::wrapper_maven_version( - "! comment\r\ndistributionUrl=https\\://repo/apache-maven-4.0.0-rc-6-bin.zip\r\n" - ) - .as_deref(), - Some("4.0.0-rc-6") - ); - assert_eq!( - trusted_checksums::wrapper_maven_version("wrapperVersion=3.3.2\n"), - None - ); - assert_eq!( - trusted_checksums::wrapper_maven_version( - "distributionUrlOld=https://x/apache-maven-3.9.3-bin.zip\n" - ), - None - ); - assert!(!trusted_checksums::maven_enforces("3.9.3")); - assert!(trusted_checksums::maven_enforces("3.9.4")); - assert!(trusted_checksums::maven_enforces("3.10.0-rc-1")); - assert!(trusted_checksums::maven_enforces("4.0.0")); - assert!(!trusted_checksums::maven_enforces("3.8.9")); - } - #[test] fn maven_pom_trusted_checksums_conflict() { let mut files = BTreeMap::new(); diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs index c7011a609..e6ad05c5e 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs @@ -26,10 +26,12 @@ use std::collections::BTreeMap; use regex::Regex; use super::{by_uuid, read_or_refuse, refuse_all_in, Ctx, FormatResult, HostedPin, View}; +use crate::formats::maven::declared_maven::DeclaredMaven; use crate::formats::maven::trusted_checksums; use crate::patch::redirect::{ - generation, maven_repositories_with_id, maven_tag_inner_range, maven_tag_text_in, - remove_maven_repository, MAVEN_DEPENDENCY_BLOCK_RE, MVN_CHECKSUMS, MVN_CONFIG, MVN_CONFIG_ARGS, + generation, heal_trade_detail, maven_repositories_with_id, maven_tag_inner_range, + maven_tag_text_in, remove_maven_repository, MAVEN_DEPENDENCY_BLOCK_RE, MVN_CHECKSUMS, + MVN_CONFIG, MVN_WRAPPER_PROPERTIES, }; /// The line break and indent `insert_maven_dependency_management` writes @@ -398,17 +400,42 @@ pub(crate) async fn restore( } /// Drop the restored pins' trusted-checksum lines, and the `.mvn` files -/// themselves when nothing but hosted mode's content is left. +/// themselves when nothing but hosted mode's content is left. A config +/// that stays is healed ([`heal_mvn_config`]). async fn restore_mvn( view: &mut View<'_>, dir: &str, checksum_dirs: &[String], result: &mut FormatResult, ) { - let sums_rel = format!("{dir}{MVN_CHECKSUMS}"); let config_rel = format!("{dir}{MVN_CONFIG}"); + let config = view.read(&config_rel).await.ok().flatten(); + let removed = drop_checksums( + view, + dir, + &config_rel, + config.as_deref(), + checksum_dirs, + result, + ) + .await; + if let Some(config) = config.filter(|_| !removed) { + heal_mvn_config(view, dir, &config_rel, &config, result).await; + } +} + +/// The checksum half of [`restore_mvn`]. Whether it removed the config. +async fn drop_checksums( + view: &mut View<'_>, + dir: &str, + config_rel: &str, + config: Option<&str>, + checksum_dirs: &[String], + result: &mut FormatResult, +) -> bool { + let sums_rel = format!("{dir}{MVN_CHECKSUMS}"); let Ok(Some(sums)) = view.read(&sums_rel).await else { - return; + return false; }; let rest = trusted_checksums::edit( &sums, @@ -416,31 +443,24 @@ async fn restore_mvn( &[], ); if rest == sums { - return; + return false; } - let config = view.read(&config_rel).await.ok().flatten(); - let written_config = format!("{}\n", MVN_CONFIG_ARGS.join("\n")); // Whether settings hosted mode may have written are left over, read as - // `trusted_checksums::config_enforces` reads them but by presence: a - // partial or switched-off set is still lines the user may want gone. - let has_resolver_lines = config - .as_deref() - .is_some_and(trusted_checksums::config_has_written_settings); + // `trusted_checksums::Settings` reads them but by presence: a partial + // or switched-off set is still lines the user may want gone. + let has_resolver_lines = config.is_some_and(trusted_checksums::config_has_written_settings); if rest.trim().is_empty() { view.remove(&sums_rel); - if config.as_deref() == Some(written_config.as_str()) { - view.remove(&config_rel); - return; + // (In either spelling of the directory: the one this release + // writes, or an earlier release's.) + if config.is_some_and(trusted_checksums::is_written_config) { + view.remove(config_rel); + return true; } } else { view.write(&sums_rel, rest.clone()); } - let other_hosted = trusted_checksums::entries(&rest).any(|e| { - e.path - .split('/') - .any(|seg| crate::formats::maven::split_socket_version(seg).is_some()) - }); - if has_resolver_lines && !other_hosted { + if has_resolver_lines && !trusted_checksums::names_hosted_artifact(&rest) { result.warnings.push(( "maven_trusted_checksums_left", format!( @@ -450,6 +470,58 @@ async fn restore_mvn( ), )); } + false +} + +/// The block hosted mode wrote into a `.mvn/maven.config` that stays +/// (`config`, at `config_rel`), respelled for the Maven the project under +/// `dir` declares ([`trusted_checksums::heal_basedir`]): the lines are left +/// in place, but the one an earlier release wrote must not go on stopping +/// Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the project. +/// What that trades away on Maven 4 is said, as the scan says it. Left out +/// where the config cannot be written ([`View::write_if_writable`]). +async fn heal_mvn_config( + view: &mut View<'_>, + dir: &str, + config_rel: &str, + config: &str, + result: &mut FormatResult, +) { + use trusted_checksums::Basedir; + // The cheap test first: only a config that holds a block in either + // spelling is worth reading the wrapper and the pom for. + if !trusted_checksums::holds_written_block(config) { + return; + } + // The flush refuses a write through a symbolic link, and the whole + // restore with it: a linked config keeps its line, as a scan keeps it. + let path = view.root().join(config_rel); + if crate::utils::containment::linked_level(view.root(), &path).is_some() { + return; + } + let wrapper = view + .read(&format!("{dir}{MVN_WRAPPER_PROPERTIES}")) + .await + .ok() + .flatten(); + let pom = view.read(&format!("{dir}pom.xml")).await.ok().flatten(); + let declared = DeclaredMaven::of(wrapper.as_deref(), pom.as_deref()); + let Some(healed) = trusted_checksums::heal_basedir(config, Basedir::for_maven(&declared)) + else { + return; + }; + let trade = heal_trade_detail(&healed, &declared, dir); + // A courtesy, never the reason a restore is refused: a config the + // flush would not write (a symbolic link, say) keeps its line, as it + // did before there was a heal, and the pins are restored all the same. + if !view.write_if_writable(config_rel, healed).await { + return; + } + if let Some(detail) = trade { + result + .warnings + .push(("maven_trusted_checksums_maven3_only", detail)); + } } #[cfg(test)] @@ -805,11 +877,43 @@ mod tests { assert_eq!(after["pom.xml"], input); } + /// 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 + /// earlier release wrote it and as a Maven 4 project still has it. + #[tokio::test] + async fn the_mvn_files_are_removed_in_either_spelling_of_the_directory() { + use super::trusted_checksums::{ + self, + Basedir::{Launcher, Session}, + }; + for form in [Launcher, Session] { + let config = format!("{}\n", trusted_checksums::config_args(form).join("\n")); + let files = vec![ + ("pom.xml", fixture("basic", "expected", "pom.xml")), + (".mvn/maven.config", config), + ( + ".mvn/checksums/checksums.sha256", + fixture("basic", "expected", ".mvn/checksums/checksums.sha256"), + ), + ]; + let (outcome, after) = run(&files).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored, "{form:?}"); + assert_eq!( + after.keys().collect::>(), + ["pom.xml"], + "{form:?}: {:?}", + outcome.warnings + ); + assert_eq!(after["pom.xml"], fixture("basic", "input", "pom.xml")); + } + } + #[tokio::test] async fn existing_mvn_lines_are_kept_and_warned() { let config = format!( "-Dmaven.test.skip=true\n{}\n", - super::MVN_CONFIG_ARGS.join("\n") + super::trusted_checksums::CONFIG_ARGS.join("\n") ); let files = vec![ ("pom.xml", fixture("basic", "expected", "pom.xml")), @@ -834,6 +938,208 @@ mod tests { ); } + /// A rollback that leaves hosted mode's settings beside the user's + /// own must not leave the line an earlier release wrote, which stops + /// Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the + /// project: the block is respelled for the Maven the project declares, + /// and what that trades away on Maven 4 is said. + #[tokio::test] + async fn a_block_the_rollback_leaves_is_healed() { + use super::trusted_checksums::{ + self, basedir_value, + Basedir::{Launcher, Session}, + BASEDIR_KEY, + }; + let beside = |form| { + format!( + "-Dmaven.test.skip=true\n{}\n", + trusted_checksums::config_args(form).join("\n") + ) + }; + let wrapper = |version: &str| { + format!( + "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/\ + apache-maven/{version}/apache-maven-{version}-bin.zip\n" + ) + }; + let files = |config: String, maven: Option<&str>| { + let mut files = vec![ + ("pom.xml", fixture("basic", "expected", "pom.xml")), + (".mvn/maven.config", config), + ( + ".mvn/checksums/checksums.sha256", + fixture("basic", "expected", ".mvn/checksums/checksums.sha256"), + ), + ]; + if let Some(version) = maven { + files.push((".mvn/wrapper/maven-wrapper.properties", wrapper(version))); + } + files + }; + let codes = |outcome: &RestoreOutcome| -> Vec<&'static str> { + outcome.warnings.iter().map(|(code, _)| *code).collect() + }; + let (left, trade) = ( + "maven_trusted_checksums_left", + "maven_trusted_checksums_maven3_only", + ); + + // No Maven declared: healed to the form that breaks no build, and + // the trade is said beside the leftover-lines warning. + let (outcome, after) = run(&files(beside(Session), None)).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + assert_eq!(after["pom.xml"], fixture("basic", "input", "pom.xml")); + assert_eq!(after[".mvn/maven.config"], beside(Launcher)); + assert_eq!(codes(&outcome), [left, trade], "{:?}", outcome.warnings); + let said = &outcome.warnings[1].1; + assert!( + said.contains("A Maven 4 build of this project no longer does") + && said.contains(".mvn/maven.config"), + "{said}" + ); + + // A Maven 3 named by the wrapper enforces either spelling: healed, + // nothing traded. + let (outcome, after) = run(&files(beside(Session), Some("3.9.9"))).await; + assert_eq!(after[".mvn/maven.config"], beside(Launcher)); + assert_eq!(codes(&outcome), [left]); + + // A project that declares Maven 4 keeps the spelling Maven 4 + // reads, and gets it when the block is in the launcher's. + let (outcome, after) = run(&files(beside(Session), Some("4.0.0"))).await; + assert_eq!(after[".mvn/maven.config"], beside(Session)); + assert_eq!(codes(&outcome), [left]); + let (outcome, after) = run(&files(beside(Launcher), Some("4.0.0"))).await; + assert_eq!(after[".mvn/maven.config"], beside(Session)); + assert_eq!(codes(&outcome), [left]); + + // Already this project's spelling: the bytes are not touched. + let (outcome, after) = run(&files(beside(Launcher), None)).await; + assert_eq!(after[".mvn/maven.config"], beside(Launcher)); + assert_eq!(codes(&outcome), [left]); + + // A directory line that stands apart is the user's, and stays. + let theirs = format!( + "-D{BASEDIR_KEY}={}\n-Dmaven.test.skip=true\n", + basedir_value(Session) + ); + let (outcome, after) = run(&files(theirs.clone(), None)).await; + assert_eq!(after[".mvn/maven.config"], theirs); + assert_eq!(codes(&outcome), [left]); + } + + /// A leftover block in a `.mvn/maven.config` that is a symbolic link is + /// not healed: the flush refuses a linked file, so the heal would + /// refuse a restore that has nothing else against it. + #[cfg(unix)] + #[tokio::test] + async fn a_linked_config_the_rollback_leaves_is_not_healed() { + use super::trusted_checksums::{self, Basedir::Session}; + let config = format!( + "-Dmaven.test.skip=true\n{}\n", + trusted_checksums::config_args(Session).join("\n") + ); + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + std::fs::create_dir_all(root.join(".mvn/checksums")).unwrap(); + std::fs::create_dir_all(root.join("ci")).unwrap(); + std::fs::write( + root.join("pom.xml"), + fixture("basic", "expected", "pom.xml"), + ) + .unwrap(); + std::fs::write( + root.join(".mvn/checksums/checksums.sha256"), + fixture("basic", "expected", ".mvn/checksums/checksums.sha256"), + ) + .unwrap(); + std::fs::write(root.join("ci/maven.config"), &config).unwrap(); + std::os::unix::fs::symlink("../ci/maven.config", root.join(".mvn/maven.config")).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(root, &pins, &opts).await; + assert_eq!(outcome.flush_error, None); + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + assert_eq!( + std::fs::read_to_string(root.join("pom.xml")).unwrap(), + fixture("basic", "input", "pom.xml") + ); + assert!(root.join(".mvn/maven.config").is_symlink()); + assert_eq!( + std::fs::read_to_string(root.join("ci/maven.config")).unwrap(), + config + ); + } + + /// The same holds for anything else the flush will not write, which + /// is all or nothing: a `.mvn` directory that does not take the write + /// keeps the config as it is, and the pins are restored all the same, + /// as they were before there was a heal. (Root writes anywhere, so + /// there is nothing to see as root.) + #[cfg(unix)] + #[tokio::test] + async fn a_config_the_flush_could_not_write_is_not_healed() { + use super::trusted_checksums::{self, Basedir::Session}; + use std::os::unix::fs::PermissionsExt as _; + if unsafe { libc::geteuid() } == 0 { + return; + } + let config = format!( + "-Dmaven.test.skip=true\n{}\n", + trusted_checksums::config_args(Session).join("\n") + ); + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + std::fs::create_dir_all(root.join(".mvn/checksums")).unwrap(); + std::fs::write( + root.join("pom.xml"), + fixture("basic", "expected", "pom.xml"), + ) + .unwrap(); + std::fs::write( + root.join(".mvn/checksums/checksums.sha256"), + fixture("basic", "expected", ".mvn/checksums/checksums.sha256"), + ) + .unwrap(); + std::fs::write(root.join(".mvn/maven.config"), &config).unwrap(); + // The config's own directory is read-only; the checksums + // directory below it still takes the removal of its file. + let mvn = root.join(".mvn"); + std::fs::set_permissions(&mvn, std::fs::Permissions::from_mode(0o555)).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(root, &pins, &opts).await; + std::fs::set_permissions(&mvn, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert_eq!(outcome.flush_error, None); + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + assert_eq!( + std::fs::read_to_string(root.join("pom.xml")).unwrap(), + fixture("basic", "input", "pom.xml") + ); + assert_eq!( + std::fs::read_to_string(root.join(".mvn/maven.config")).unwrap(), + config + ); + // The leftover lines are reported; no trade is claimed for a line + // that was not changed. + let codes: Vec<&str> = outcome.warnings.iter().map(|(code, _)| *code).collect(); + assert_eq!(codes, ["maven_trusted_checksums_left"]); + } + #[tokio::test] async fn other_checksum_lines_keep_their_order() { let other = format!( 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 fb0054d4a..2be82d88d 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -745,6 +745,29 @@ impl<'a> View<'a> { self.staged.insert(rel.to_string(), None); } + /// Stage `content` for `rel` only when the flush could write it; + /// `false` when it was left out. For a write that is a courtesy and + /// must never be the reason a restore is refused: the flush is all or + /// nothing, and one file it will not write (a symbolic link, a + /// directory that does not take the write, a file edited since it was + /// read) leaves every pin unrestored. + pub(crate) async fn write_if_writable(&mut self, rel: &str, content: String) -> bool { + let read = self + .originals + .get(rel) + .map(|original| original.as_deref().map(str::as_bytes)); + let pending = vec![Pending { + rel, + content: Some(content.as_bytes()), + read, + }]; + if preflight(self.root, pending).await.is_err() { + return false; + } + self.write(rel, content); + true + } + /// Files whose staged state differs from what was read from disk. fn changed(&self) -> Staged { self.staged 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 8a039bd90..855b11dd9 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs @@ -13,9 +13,10 @@ use serde_json::{json, Value}; use crate::crawlers::maven_selection::{MavenSelection, Verdict}; use crate::formats::maven::{ - classpath_copy, interpolate_keeping, interpolate_strict, is_executable_classifier, - lookup_property, maven_config_properties as cli_properties, profile_combinations, Definitions, - Interpolate, PomLayer, MAX_COMBINED_PROFILES, MAX_INTERPOLATION_DEPTH, + classpath_copy, declared_maven, interpolate_keeping, interpolate_strict, + is_executable_classifier, lookup_property, maven_config_properties as cli_properties, + profile_combinations, Definitions, Interpolate, PomLayer, MAX_COMBINED_PROFILES, + MAX_INTERPOLATION_DEPTH, }; use super::super::state::{WiringAction, WiringRecord}; @@ -2075,10 +2076,8 @@ impl Pom { }) .filter(|(_, props)| !props.is_empty()) .collect(); - let infers_parent = doc.child_text(project, "modelVersion").as_deref() == Some("4.1.0") - || doc.masked.contains("maven.apache.org/POM/4.1.0"); Ok(Pom { - infers_parent, + infers_parent: doc.is_maven_4_model(), discovers_subprojects: discovers_subprojects(&doc), dir: rel.rsplit_once('/').map_or("", |(d, _)| d).to_string(), group: doc.child_text(project, "groupId"), @@ -2983,30 +2982,22 @@ fn module_refs(doc: &Doc) -> Vec { const DISCOVER_SUBPROJECTS: &str = "maven.project.discoverSubprojects"; /// Whether Maven 4 discovers the subprojects of this pom on its own -/// (`DefaultModelBuilder`, "subprojects discovery"): its model version is -/// not 4.0.0 (the ``, else the POM namespace), it is -/// packaged `pom`, and it lists no top-level `` or -/// `` entry. Maven 3 never discovers, and reads no 4.1.0 pom. +/// (`DefaultModelBuilder`, "subprojects discovery"): its model is newer +/// than 4.0.0 ([`Doc::is_maven_4_model`]), it is packaged `pom`, and it +/// lists no top-level `` or `` entry. Maven 3 never +/// discovers, and reads no 4.1.0 pom. fn discovers_subprojects(doc: &Doc) -> bool { let project = doc.project; - let model = doc.child_text(project, "modelVersion").or_else(|| { - let at = doc.masked.find(POM_NAMESPACE)? + POM_NAMESPACE.len(); - let rest = &doc.masked[at..]; - let end = rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '.'))?; - Some(rest[..end].to_string()) - }); let lists = |list: &str, item: &str| { doc.child(project, list) .is_some_and(|l| doc.children(l, item).next().is_some()) }; - model.is_some_and(|v| v != "4.0.0") + doc.is_maven_4_model() && doc.child_text(project, "packaging").as_deref() == Some("pom") && !lists("subprojects", "subproject") && !lists("modules", "module") } -const POM_NAMESPACE: &str = "maven.apache.org/POM/"; - /// The subprojects Maven 4 discovers under the pom at `dir`: every direct /// subdirectory holding a `pom.xml`, hidden ones included, as /// `` names relative to `dir`. Probed through the listing, not @@ -3779,6 +3770,19 @@ impl Doc { self.child(n, name).map(|c| self.text_of(c)) } + /// Whether the pom is of a model only Maven 4 reads: the one reading + /// of a pom's model version every mode shares + /// ([`declared_maven::model_version_of`]: the ``, else + /// the version the namespace names). + fn is_maven_4_model(&self) -> bool { + let project = &self.nodes[self.project]; + declared_maven::model_version_of( + self.child_text(self.project, "modelVersion").as_deref(), + &self.masked[project.start..project.inner_start], + ) + .is_some_and(|version| declared_maven::is_maven_4_model(&version)) + } + /// The span of a text element's value: the trimmed text outside /// comments, or the whole content when it holds CDATA (whose masked /// copy is blank). @@ -8673,6 +8677,21 @@ mod tests { assert_eq!(tree(&empty_list, &[]), all); let namespace_only = IMPLICIT_ROOT.replace(" 4.1.0\n", ""); assert_eq!(tree(&namespace_only, &[]), all); + // A 4.0.0 model under the 4.1.0 namespace is a 4.0.0 pom: Maven 4 + // discovers nothing for it (measured on 4.0.0-rc-7), and Maven 3, + // which never looks at the namespace, builds it. + let model_4_0_under_4_1 = + IMPLICIT_ROOT.replace("4.1.0", "4.0.0"); + assert_ne!(model_4_0_under_4_1, IMPLICIT_ROOT); + assert_eq!(tree(&model_4_0_under_4_1, &[]), ["pom.xml"]); + // The namespace named only by another attribute is not the pom's. + let schema_only = namespace_only.replace( + "xmlns=\"http://maven.apache.org/POM/4.1.0\"", + "xsi:schemaLocation=\"http://maven.apache.org/POM/4.1.0 \ + https://maven.apache.org/xsd/maven-4.1.0.xsd\"", + ); + assert_ne!(schema_only, namespace_only); + assert_eq!(tree(&schema_only, &[]), ["pom.xml"]); for (value, discovers) in [ ("true", true), ("TRUE", true), diff --git a/crates/socket-patch-core/src/vex/discover/maven.rs b/crates/socket-patch-core/src/vex/discover/maven.rs index eb09ef71d..df3d1126e 100644 --- a/crates/socket-patch-core/src/vex/discover/maven.rs +++ b/crates/socket-patch-core/src/vex/discover/maven.rs @@ -95,10 +95,12 @@ //! ` ///-.jar` under the SUFFIXED version, made //! effective by `-Daether.artifactResolver.postProcessor.trustedChecksums=true` //! in `.mvn/maven.config`. That jar line becomes -//! [`LockIntegrity::Sha256Hex`] only while Maven enforces the file -//! ([`crate::formats::maven::trusted_checksums::enforced`]: every setting -//! hosted writes, read as Maven 3.9+ reads `maven.config`, and no wrapper -//! pinning a Maven older than 3.9.4). +//! [`LockIntegrity::Sha256Hex`] only while the pin is known to be enforced +//! ([`crate::formats::maven::trusted_checksums::enforcement`]: every +//! setting hosted writes, read as Maven 3.9+ reads `maven.config`, and a +//! directory spelling the Maven the project declares reads; a project that +//! declares no Maven is known to enforce only the spelling every enforcing +//! Maven reads, `${session.rootDirectory}`). //! `integrity_required` is FALSE (but for a managed pin under an unread //! parent, above): the rewriter writes checksums only when both hashes are //! known, and the suffixed version itself is the fail-closed pin (no other @@ -485,7 +487,7 @@ async fn extract_hosted( continue; }; if checksums.is_none() { - checksums = Some(trusted_checksums(ctx, config, out).await); + checksums = Some(trusted_checksums(ctx, config, raw, out).await); } let jar = layout::artifact_path(group, artifact, pinned, None, "jar"); let integrity = checksums @@ -671,22 +673,36 @@ impl Ancestors { } /// `path -> sha256 hex` from `.mvn/checksums/checksums.sha256`, or empty -/// when Maven does not enforce it: `config` (`.mvn/maven.config`'s text, -/// read once by [`extract`]) lacks a setting it reads the file by, or the -/// Maven Wrapper pins a Maven older than 3.9.4. Judged by the hosted -/// rewriter's own rule, and only a line Maven checks attests -/// (`formats::maven::trusted_checksums`). +/// unless the pin is known to be enforced +/// ([`crate::formats::maven::trusted_checksums::Enforcement::Enforced`]): +/// `config` (`.mvn/maven.config`'s text, read once by [`extract`]) holds +/// every setting Maven reads the file by, and the Maven the project +/// declares (its Maven Wrapper, the model of its root pom `pom`) reads +/// the directory as the config spells it. A pin that only Maven 3 enforces, +/// in a project that does not say which Maven builds it, is not known to +/// be enforced, so it is not recorded as the content the lock pins. +/// Judged by the hosted rewriter's own rule, and only a line Maven checks +/// attests (`formats::maven::trusted_checksums`). async fn trusted_checksums( ctx: &DiscoverCtx<'_>, config: Option<&str>, + pom: &str, out: &mut Discovery, ) -> BTreeMap { - use crate::formats::maven::trusted_checksums::{enforced, pinned}; + use crate::formats::maven::declared_maven::DeclaredMaven; + use crate::formats::maven::trusted_checksums::{enforcement, pinned, Enforcement, Settings}; let Some(config) = config else { return BTreeMap::new(); }; + let settings = Settings::read(config); + // The cheap test first: a config that enforces nothing needs no + // wrapper read. + if !settings.enforce() { + return BTreeMap::new(); + } let wrapper = ctx.read_text(MVN_WRAPPER_PROPERTIES, out).await; - if !enforced(config, wrapper.as_deref()) { + let declared = DeclaredMaven::of(wrapper.as_deref(), Some(pom)); + if enforcement(&settings, &declared) != Enforcement::Enforced { return BTreeMap::new(); } ctx.read_text(MVN_CHECKSUMS, out) @@ -1493,17 +1509,26 @@ mod tests { "self-closed-repositories", "depmgmt-comment", "self-closed-depmgmt", + // A project that declares Maven 4 (a 4.1.0 model), wired with + // the spelling Maven 4 reads. + "maven4-model", ] { let out = run(&fixture(case)).await; assert_refs(&out, &[(FX_PURL, FX_UUID, WiringMode::Hosted)]); assert!(out.diagnostics.is_empty(), "{case}: {:?}", out.diagnostics); let r = &out.refs[0]; assert_eq!(r.source_file, std::path::PathBuf::from("pom.xml"), "{case}"); - // mvn-config-merge keeps the user's `originAware=true`, under - // which Maven reads a per-repository summary file, not this one: - // its checksums pin nothing. + // The checksum is the content the lock pins only where the pin + // is known to be enforced. The fixtures that declare no Maven + // carry the default spelling, which Maven 3 enforces and Maven + // 4 does not: nothing says which builds them, so nothing is + // recorded. (mvn-config-merge besides keeps the user's + // `originAware=true`, under which Maven reads a per-repository + // summary file, not this one.) Only the project that declares + // Maven 4 and has the spelling Maven 4 reads is known to + // enforce its pin. let integrity = - (case != "mvn-config-merge").then(|| LockIntegrity::Sha256Hex(FX_JAR_SHA.into())); + (case == "maven4-model").then(|| LockIntegrity::Sha256Hex(FX_JAR_SHA.into())); assert_eq!(r.locked_integrity, integrity, "{case}"); assert!(!r.integrity_required, "{case}"); assert!(r.lockfile_basis_ok(), "{case}"); @@ -1521,6 +1546,17 @@ mod tests { p.copy_fixture("redirect/maven/pom/rerun-noop/input"); let out = run(&p).await; assert_refs(&out, &[(FX_PURL, FX_UUID, WiringMode::Hosted)]); + // Wired, and attested from the pin alone: the checksum counts as + // the content the lock pins once the project names a Maven that + // enforces the spelling it carries. + assert!(out.refs[0].lockfile_basis_ok()); + assert_eq!(out.refs[0].locked_integrity, None); + p.write( + ".mvn/wrapper/maven-wrapper.properties", + "distributionUrl=https://repo/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip\n" + .to_string(), + ); + let out = run(&p).await; assert!(out.refs[0].locked_integrity.is_some()); } @@ -1845,75 +1881,166 @@ mod tests { ); } - /// Integrity attests only what Maven enforces, judged by the hosted - /// rewriter's own rule: every `maven.config` setting Maven reads the - /// summary file by, each a whole-line argument (CRLF and a bare `-Dk` - /// switch count); no wrapper Maven older than 3.9.4; and a jar line in - /// the exact lowercase ` ` shape. A tolerated spelling - /// (one space, a `*` marker, uppercase hex) is a line Maven skips or - /// fails on, so it pins nothing. + /// Integrity attests only what Maven is known to enforce, judged by the + /// hosted rewriter's own rule: every `maven.config` setting Maven reads + /// the summary file by, each a whole-line argument (CRLF and a bare + /// `-Dk` switch count); a directory spelling the Maven the project + /// declares reads, and no wrapper Maven older than 3.9.4; and a jar + /// line in the exact lowercase ` ` shape. A tolerated + /// spelling (one space, a `*` marker, uppercase hex) is a line Maven + /// skips or fails on, so it pins nothing. #[tokio::test] async fn checksums_attest_only_what_maven_enforces() { - use crate::formats::maven::trusted_checksums::{CONFIG_ARGS, SWITCH_KEY}; + use crate::formats::maven::trusted_checksums::{ + config_args, + Basedir::{Launcher, Session}, + SWITCH_KEY, + }; let jar = "org/slf4j/slf4j-api/1.7.36-socket.77777777/slf4j-api-1.7.36-socket.77777777.jar"; - let all = CONFIG_ARGS.join("\n"); + // The spelling every enforcing Maven reads, so the rows below that + // name no Maven turn on the one thing each changes. + let all = config_args(Session).join("\n"); + let launcher = config_args(Launcher).join("\n"); let switch = format!("-D{SWITCH_KEY}=true"); let wrapper = |v: &str| { format!("distributionUrl=https://repo/apache-maven/{v}/apache-maven-{v}-bin.zip\n") }; let line = format!("{FX_JAR_SHA} {jar}\n"); let upper = FX_JAR_SHA.to_uppercase(); - for (config, wrapper, sums, attests) in [ + // (maven.config, the wrapper's Maven, a 4.1.0 root pom, the + // checksums, attested) + for (config, wrapper, model_4_1, sums, attests) in [ ( - CONFIG_ARGS.join("\r\n"), + config_args(Session).join("\r\n"), None, + false, format!("{FX_JAR_SHA} {jar}\r\n"), true, ), ( all.replace(&switch, &format!("-D{SWITCH_KEY}")), None, + false, format!("# pins\n{FX_JAR_SHA} {jar}"), true, ), - (all.clone(), Some(wrapper("3.9.4")), line.clone(), true), - (all.clone(), Some(wrapper("3.9.3")), line.clone(), false), - (switch.clone(), None, line.clone(), false), + ( + all.clone(), + Some(wrapper("3.9.4")), + false, + line.clone(), + true, + ), + ( + all.clone(), + Some(wrapper("3.9.3")), + false, + line.clone(), + false, + ), + (switch.clone(), None, false, line.clone(), false), ( all.replace(&switch, &format!("-B {switch}")), None, + false, line.clone(), false, ), ( all.replace("originAware=false", "originAware=true"), None, + false, line.clone(), false, ), ( format!("{all}\n-D{SWITCH_KEY}=false"), None, + false, line.clone(), false, ), - (all.clone(), None, format!("{FX_JAR_SHA} {jar}\n"), false), - (all.clone(), None, format!("{FX_JAR_SHA} *{jar}\n"), false), - (all.clone(), None, format!("{upper} {jar}\n"), false), + ( + all.clone(), + None, + false, + format!("{FX_JAR_SHA} {jar}\n"), + false, + ), + ( + all.clone(), + None, + false, + format!("{FX_JAR_SHA} *{jar}\n"), + false, + ), + (all.clone(), None, false, format!("{upper} {jar}\n"), false), + // The launcher's spelling, which hosted mode writes by default: + // a Maven 3 the wrapper names enforces it. With no Maven named + // it is enforced by Maven 3 only, and nothing says which Maven + // builds the project, so it is not attested. + ( + launcher.clone(), + Some(wrapper("3.9.4")), + false, + line.clone(), + true, + ), + ( + launcher.clone(), + Some(wrapper("3.9.16")), + false, + line.clone(), + true, + ), + ( + launcher.clone(), + Some(wrapper("3.9.3")), + false, + line.clone(), + false, + ), + (launcher.clone(), None, false, line.clone(), false), + // A project that declares Maven 4, by its wrapper or by its + // model alone: Maven 4 reads only the session's spelling. + ( + launcher.clone(), + Some(wrapper("4.0.0")), + false, + line.clone(), + false, + ), + (launcher.clone(), None, true, line.clone(), false), + ( + all.clone(), + Some(wrapper("4.0.0")), + false, + line.clone(), + true, + ), + (all.clone(), None, true, line.clone(), true), ] { let p = fixture("basic"); p.write(".mvn/maven.config", config.clone()); if let Some(props) = &wrapper { p.write(".mvn/wrapper/maven-wrapper.properties", props.clone()); } + if model_4_1 { + let pom = std::fs::read_to_string(p.root().join("pom.xml")).expect("pom"); + let newer = pom.replace("4.0.0", "4.1.0"); + assert_ne!(newer, pom); + p.write("pom.xml", newer); + } p.write(".mvn/checksums/checksums.sha256", sums.clone()); let out = run(&p).await; assert_refs(&out, &[(FX_PURL, FX_UUID, WiringMode::Hosted)]); assert_eq!( out.refs[0].locked_integrity, attests.then(|| LockIntegrity::Sha256Hex(FX_JAR_SHA.into())), - "{config:?} / {wrapper:?} / {sums:?}" + "{config:?} / {wrapper:?} / model 4.1.0: {model_4_1} / {sums:?}" ); + // The pin itself never needs the checksum. + assert!(out.refs[0].lockfile_basis_ok()); } } diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/basic/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/basic/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/basic/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/basic/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-depmgmt/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-depmgmt/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-depmgmt/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-depmgmt/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-repositories/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-repositories/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-repositories/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-repositories/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/expected-edits.json new file mode 100644 index 000000000..7931d28d7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/expected-edits.json @@ -0,0 +1,8 @@ +[ + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "rewritten", + "key": "trustedChecksumsDirectory" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/expected-warnings.json new file mode 100644 index 000000000..9807a1734 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/expected-warnings.json @@ -0,0 +1 @@ +["redirect_maven_trusted_checksums_maven3_only"] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/expected/.mvn/maven.config new file mode 100644 index 000000000..4f1f947e8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/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/heals-basedir-without-a-patch/input/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/input/.mvn/checksums/checksums.sha256 new file mode 100644 index 000000000..71c583f77 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/input/.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/heals-basedir-without-a-patch/input/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/input/.mvn/maven.config new file mode 100644 index 000000000..d3b91570d --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/input/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/input/pom.xml new file mode 100644 index 000000000..ca3349c03 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/input/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + + org.slf4j + slf4j-api + 2.0.9 + + + + + 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/heals-basedir-without-a-patch/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/overrides.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/heals-basedir-without-a-patch/overrides.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected-edits.json new file mode 100644 index 000000000..3a8160e03 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "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": "rewritten", + "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/maven4-launcher-line-conflict/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected-warnings.json new file mode 100644 index 000000000..6825ca526 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected-warnings.json @@ -0,0 +1 @@ +["redirect_maven_trusted_checksums_conflict", "redirect_maven_trusted_checksums_unenforced"] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 000000000..71c583f77 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/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/maven4-launcher-line-conflict/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected/.mvn/maven.config new file mode 100644 index 000000000..e2dba7d24 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums +-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.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected/pom.xml new file mode 100644 index 000000000..b5989daf3 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + + org.slf4j + slf4j-api + 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/maven4-launcher-line-conflict/input/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/input/.mvn/maven.config new file mode 100644 index 000000000..1b4387005 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/input/.mvn/maven.config @@ -0,0 +1 @@ +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/input/.mvn/wrapper/maven-wrapper.properties b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/input/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..05f664579 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/input/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https\://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/4.0.0/apache-maven-4.0.0-bin.zip diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/input/pom.xml new file mode 100644 index 000000000..c38ca6357 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/input/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + + org.slf4j + slf4j-api + 1.7.36 + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/overrides.json new file mode 100644 index 000000000..53deb25b8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/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/maven4-model/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected-edits.json new file mode 100644 index 000000000..ba20ca8b9 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected-edits.json @@ -0,0 +1,31 @@ +[ + { + "path": "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/maven4-model/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected-warnings.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected-warnings.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected/.mvn/checksums/checksums.sha256 new file mode 100644 index 000000000..71c583f77 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/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/maven4-model/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected/.mvn/maven.config new file mode 100644 index 000000000..d3b91570d --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected/pom.xml new file mode 100644 index 000000000..a459b5174 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected/pom.xml @@ -0,0 +1,30 @@ + + + 4.1.0 + dev.socket.test + consumer + 1.0.0 + jar + + + org.slf4j + slf4j-api + 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/maven4-model/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/input/pom.xml new file mode 100644 index 000000000..4db3b575a --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/input/pom.xml @@ -0,0 +1,17 @@ + + + 4.1.0 + dev.socket.test + consumer + 1.0.0 + jar + + + org.slf4j + slf4j-api + 1.7.36 + + + diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/overrides.json new file mode 100644 index 000000000..53deb25b8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/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/mvn-config-merge/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/mvn-config-merge/expected/.mvn/maven.config index 75171442c..3d46044f7 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/mvn-config-merge/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/mvn-config-merge/expected/.mvn/maven.config @@ -4,4 +4,4 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/expected-edits.json new file mode 100644 index 000000000..7931d28d7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/expected-edits.json @@ -0,0 +1,8 @@ +[ + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "rewritten", + "key": "trustedChecksumsDirectory" + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/expected-warnings.json new file mode 100644 index 000000000..9807a1734 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/expected-warnings.json @@ -0,0 +1 @@ +["redirect_maven_trusted_checksums_maven3_only"] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/expected/.mvn/maven.config new file mode 100644 index 000000000..4f1f947e8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/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/rerun-heals-basedir/input/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/input/.mvn/checksums/checksums.sha256 new file mode 100644 index 000000000..71c583f77 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/input/.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/rerun-heals-basedir/input/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/input/.mvn/maven.config new file mode 100644 index 000000000..d3b91570d --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/input/.mvn/maven.config @@ -0,0 +1,6 @@ +-Daether.artifactResolver.postProcessor.trustedChecksums=true +-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 +-Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false +-Daether.trustedChecksumsSource.summaryFile=true +-Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/input/pom.xml new file mode 100644 index 000000000..b5989daf3 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/input/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + dev.socket.test + consumer + 1.0.0 + jar + + + org.slf4j + slf4j-api + 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/rerun-heals-basedir/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/overrides.json new file mode 100644 index 000000000..53deb25b8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-heals-basedir/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/rerun-noop/input/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-noop/input/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-noop/input/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/rerun-noop/input/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/transitive-depmgmt/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/transitive-depmgmt/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/transitive-depmgmt/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/transitive-depmgmt/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected/.mvn/maven.config index d3b91570d..4f1f947e8 100644 --- a/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected/.mvn/maven.config @@ -2,5 +2,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256 -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true --Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums +-Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false diff --git a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-maven.json b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-maven.json index 9d433d65e..1cbe78968 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 @@ -7,7 +7,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -52,7 +52,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -97,7 +97,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -142,7 +142,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -187,7 +187,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -232,7 +232,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -277,7 +277,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -322,7 +322,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -359,6 +359,129 @@ "elsewhere": [], "live_claims": [] }, + "redirect/maven/pom/heals-basedir-without-a-patch/expected": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/heals-basedir-without-a-patch/input": { + "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 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/maven4-launcher-line-conflict/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/maven4-launcher-line-conflict/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/maven4-model/expected": { + "refs": [ + { + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "source_file": "pom.xml", + "artifact_rel": null, + "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "integrity_required": false, + "url": "https://patch.socket.dev/patch-registry/maven/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/maven2", + "lockfile_basis_ok": true + } + ], + "diagnostics": [], + "recognized": [ + { + "uuid": "11111111-1111-1111-1111-111111111111", + "mode": "hosted", + "file": "pom.xml" + }, + { + "uuid": "77777777-7777-7777-7777-777777777777", + "mode": "hosted", + "file": "pom.xml" + } + ], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [ + { + "mode": "hosted", + "uuid": "77777777-7777-7777-7777-777777777777", + "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36" + } + ] + }, + "redirect/maven/pom/maven4-model/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, "redirect/maven/pom/mvn-config-merge/expected": { "refs": [ { @@ -445,7 +568,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -490,7 +613,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -543,7 +666,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -588,7 +711,15 @@ "elsewhere": [], "live_claims": [] }, - "redirect/maven/pom/rerun-noop/input": { + "redirect/maven/pom/rerun-heals-basedir/expected": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/maven/pom/rerun-heals-basedir/input": { "refs": [ { "purl": "pkg:maven/org.slf4j/slf4j-api@1.7.36", @@ -625,6 +756,43 @@ } ] }, + "redirect/maven/pom/rerun-noop/input": { + "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/self-closed-depmgmt/expected": { "refs": [ { @@ -633,7 +801,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -678,7 +846,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 @@ -723,7 +891,7 @@ "mode": "hosted", "source_file": "pom.xml", "artifact_rel": null, - "locked_integrity": "Sha256Hex(\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\")", + "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 diff --git a/crates/socket-patch-core/tests/upstream_restore_golden.rs b/crates/socket-patch-core/tests/upstream_restore_golden.rs index edcaf1989..2cd3209dc 100644 --- a/crates/socket-patch-core/tests/upstream_restore_golden.rs +++ b/crates/socket-patch-core/tests/upstream_restore_golden.rs @@ -3503,8 +3503,9 @@ async fn vlt_goldens_round_trip() { #[tokio::test] #[serial] async fn maven_goldens_round_trip() { - // mvn-config-merge: `.mvn/maven.config` existed, so whether the appended - // resolver lines were the user's is not derivable; they stay (warned). + // mvn-config-merge, maven4-launcher-line-conflict: `.mvn/maven.config` + // existed, so whether the appended resolver lines were the user's is + // not derivable; they stay (warned). // no-suffix-fallback: a same-GAV repository is tied to no artifact, so // discovery reports no pin to restore. // self-closed-repositories / self-closed-depmgmt: the rewriter expanded @@ -3513,6 +3514,7 @@ async fn maven_goldens_round_trip() { // maven unit tests). let not_invertible = [ "mvn-config-merge", + "maven4-launcher-line-conflict", "no-suffix-fallback", "self-closed-repositories", "self-closed-depmgmt", diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 2e0c021f6..a02293eee 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1056,14 +1056,67 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: Older releases leave the `.mvn/*` files inert, and only the transport `.sha1` check guards the Socket-served bytes. The version suffixing above still fails closed on its own. - - **3.9.0 / 3.9.1** do not interpolate the `${session.rootDirectory}` basedir the config - uses, so the summary file is never found. + - **3.9.0 / 3.9.1** do not interpolate the basedir the config uses, so the summary + file is never found. - **3.9.2 / 3.9.3** ignore `checksumAlgorithms=SHA-256` and check SHA-1 only. - **Below 3.9** there is no Trusted Checksums post-processor. - - When `.mvn/wrapper/maven-wrapper.properties` pins a Maven older than 3.9.4, the rewriter - still writes the files and warns `redirect_maven_trusted_checksums_unenforced`. Without - a Maven Wrapper, the CLI can't tell which Maven builds the project, so it doesn't warn. + - **Maven 4** enforces the pin only in a project that declares Maven 4 (below). + + **How the directory is named.** Maven reads a relative `basedir` from the local + repository, so the config names `.mvn/checksums` through a property, and no property + is right on every Maven: + - `${maven.multiModuleProjectDirectory}/.mvn/checksums` is what hosted mode writes by + default. Every Maven 3 launcher defines it wherever the build is started (the + project root, a module directory, `mvn -f /pom.xml` from another + directory), so the line breaks no build and the pin is enforced from 3.9.4 on. + Maven 4 does not interpolate it: a Maven 4 build of such a project runs as if the + pin were not there. + - `${session.rootDirectory}/.mvn/checksums` is written for a project that declares + Maven 4: its Maven Wrapper pins Apache Maven 4, or its root `pom.xml` is of a model + newer than 4.0.0 (its ``, or with none, the version its namespace + names; `4.0.0` under the 4.1.0 namespace is a 4.0.0 pom, + which Maven 3 builds). Maven 4 defines the property in every invocation. Releases up + to 5.1.0 wrote this form for every project, which stopped **Maven 3.9.2 to 3.9.8** + from starting at all with `-f` from outside the project (`Illegal use of undefined + property: session.rootDirectory`). + + If Maven 4 builds your project and nothing in the checkout says so, declare it: with + the default form a Maven 4 build does not enforce the pin, and the CLI cannot see + which Maven you run. + + **A project wired by an earlier release is healed.** Every `scan --mode hosted` that + finds the six settings standing together as hosted mode wrote them, in the spelling + that is not this project's, rewrites that one line in place (`redirect_maven_config`, + `rewritten`, `key: "trustedChecksumsDirectory"`). It does so whatever the scan + redirects: when no patch applies any more (a dependency bumped past its patched + version), in a reactor root, when no checksum line is left, when a later line switches + the pin off. A scan with nothing to redirect reads `.mvn/maven.config` for this alone + and takes the write lock for the change when it can. The heal never fails a run: when + the lock is held elsewhere, or `.mvn/maven.config` is a symbolic link, the line is + left for a later scan. `rollback` and `remove` do the same to a config they leave in + place. A directory line you wrote yourself (one + that stands apart from the other five) is yours and is left alone, as is any other + setting; `rollback` and `remove` recognise either form. + + The heal can trade something away, and says so. Taking `${session.rootDirectory}` out + of a project that declares no Maven means a Maven 4 build of it no longer enforces the + pin (Maven 3.9.4 and later 3.x still do). The run that changes the line warns + `redirect_maven_trusted_checksums_maven3_only` (`maven_trusted_checksums_maven3_only` + from `rollback` / `remove`). Declare Maven 4 and scan again to get the form Maven 4 + reads back. + + When the Maven the project declares does not enforce the pin as the config stands, the + rewriter still writes the files and warns `redirect_maven_trusted_checksums_unenforced`, + on every scan while that holds: + - `.mvn/wrapper/maven-wrapper.properties` pins a Maven older than 3.9.4 (upgrade the + wrapper); + - the project declares Maven 4 and the directory line is one you wrote in the + launcher's spelling, which Maven 4 does not read (set it to + `${session.rootDirectory}/.mvn/checksums`). The scan that first meets that line also + reports it as `redirect_maven_trusted_checksums_conflict`. + + Without a Maven Wrapper or a newer model, the CLI can't tell which Maven builds the + project, so it doesn't warn. On Maven **3.9.4–3.9.8** a *mismatch* is enforced but reported unclearly; the readability fix landed in **3.9.9** ([MNG-8182](https://issues.apache.org/jira/browse/MNG-8182)). The args are @@ -1071,10 +1124,16 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: from any repository and a dependency with no committed checksum still resolves — only a *mismatch* fails. A grant whose sha256 is not 64 hex digits writes no checksum line (and drops any line an earlier run wrote for that suffixed version) and warns - `redirect_maven_trusted_checksums_invalid_hash`. `vex` attests a pin's checksum only - when `maven.config` enforces the file as Maven 3.9+ reads it (all five settings above - with the values hosted writes; `failIfMissing` aside) and the wrapper, if any, pins - Maven 3.9.4 or later. + `redirect_maven_trusted_checksums_invalid_hash`. `vex` takes a pin's checksum as the + content the project pins only when the pin is known to be enforced: `maven.config` + enforces the file as Maven 3.9+ reads it (all five settings above with the values + hosted writes, the directory in either form; `failIfMissing` aside), and the Maven the + project declares reads the directory as the config spells it (a wrapper that pins + Maven 3.9.4 or later, and below Maven 4 for the default form; Maven 4, by the wrapper + or the model, for the `${session.rootDirectory}` form). A project that declares no + Maven and carries the default form is enforced by Maven 3 only, so its checksum is not + taken; the statement itself does not depend on it, since the suffixed version is the + pin. * **A Maven project's scan is scoped to its dependency graph.** The Maven local repository is shared by every project on the machine, so in project mode (no `--global` / `--global-prefix`) a Maven build's crawl (a `pom.xml`, no Gradle or