diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8f2665cba..376a1ae63 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -402,7 +402,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Grant gate (additive).** A reference grant is the patch API's answer, and its fields are written into files the project commits. Each granted reference is therefore checked once, before anything is planned for it (no takeover, no artifact fetch, no rewriter sees one that fails): the patch uuid is a canonical lowercase uuid; the artifact URL and a registry override's index URL are `https` URLs of plain URL characters (no whitespace or control character, no quote, backslash, `$`, `{`, `}`, `<`, `>`, `&`, `#`, `;`, `|` or `^`; cargo's `sparse+` prefix is kept); `sha1` is 40 hex digits, `sha256` 64, `sha512` exactly one `sha512-` token, the Go hashes `h1:` hashes, the yarn berry checksum `/`, the cargo and gem checksums 64 hex digits; the package's name and version, and every identifier of a registry override, are in their ecosystem's coordinate grammar (letters, digits and that ecosystem's punctuation; Maven coordinates as the JVM backends accept them). A Maven grant's sha256 digests may also be spelled `sha256-…` / `sha256:…`: the pom, Gradle and sbt planners read those, and a digest that is still not 64 hex digits writes no checksum pin (`redirect_maven_trusted_checksums_invalid_hash`). An absent or empty optional field is not checked. A grant that fails is refused for that package only: a `skipped` event whose `errorCode` is `redirect_grant_malformed` and whose `reason` names the field (never its value), the same code and detail in `warnings[]`, nothing written for it, the rest of the run and the exit code unchanged. A plain-`http` artifact or index URL is refused the same way with `redirect_grant_insecure_url` (every later install would send the grant token in clear text), unless its origin is the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin (scheme, host and port) or a loopback address (`localhost`, `127.0.0.0/8`, `::1`). The in-memory engine applies the same gate; it has no configured origin. -The rewriter reads a fixed set of candidate files from the project root: the npm-family locks (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `shrinkwrap.yaml`, `yarn.lock`, plus `.yarnrc.yml` for the berry cache-config gate, `bun.lock` / `bun.lockb`, and `vlt-lock.json` with `vlt.json` and `node_modules/.vlt-lock.json` read only), `requirements.txt` / `uv.lock` / `Pipfile.lock` (pipfile-spec 6; see the Pipenv section below) / `poetry.lock` (every Poetry lock generation from 1.0 on — the 0.12 `[metadata.hashes]` layout is refused because that installer ignores URL sources; a Poetry < 1.4 writer additionally gets `redirect_poetry_stale_install_risk`, see `docs/testing/poetry-compatibility.md`) / `pdm.lock` (PDM lock formats `2` and `4.3`–`4.5.1`; the identity-losing `3.1` / `4.0`–`4.2` formats and unknown future formats are refused with `redirect_pdm_refused`, and a lock-format-`2` writer additionally gets `redirect_pdm_legacy_sync_required`, see `docs/testing/pdm-compatibility.md`; when `uv.lock` or `poetry.lock` sits beside it they drive and `pdm.lock` is left alone), `Cargo.toml` / `Cargo.lock` / `.cargo/config.toml` (plus the legacy extensionless `.cargo/config` — cargo reads that spelling in preference when both exist, so the managed `[registries.…]` block is written into whichever one is present; the hosted redirect is a `sparse+` registry, which cargo loads only from **1.68**, so `rust-toolchain.toml` / `rust-toolchain` are read too (never edited) and a project whose declared floor — the lowest `rust-version` of the root and the member manifests read here (a `rust-version.workspace = true` inheritor reads `[workspace.package]`), else the channel rustup picks from the root (the legacy `rust-toolchain` over `rust-toolchain.toml`; a dated `nightly-`/`beta-YYYY-MM-DD` maps to its release train) — is below 1.68 is refused `redirect_cargo_old_cargo` per crate (nothing written, an earlier run's pins left in place with the `rollback` that drops them named; `--mode vendored` builds on cargo 1.41+), while an undeclared or rolling-channel floor still redirects (toolchain files in ancestor directories are not read); **cargo also reads every workspace-member manifest** — the `[workspace] members` globs minus `exclude` — and every in-root path-dependency manifest, recursively, reached without crossing a symbolic link and never under `.socket/`, and pins the crate in each one that declares it, so those `/Cargo.toml` files can appear in `rewrittenFiles`. A crate is redirected only when every declaration pins and every other `Cargo.lock` package depending on it is a planned member: one a registry or git crate — or a path package outside the root or behind a link — also depends on is refused `redirect_cargo_transitive_dependents` (a pin reaches only the declarations it sits on), a crate no manifest declares keeps `redirect_cargo_toml_dep_not_found` with a transitive-only detail naming `--mode vendored`, a crate every declaration of which requires another version (no requirement accepts the patched version) is refused `redirect_cargo_toml_dep_unrewritable`, and so is a requirement that also matches another locked version of the crate — each a transactional skip, never recorded or attested. With NO `Cargo.lock` there is no resolved graph to ask, so the dependents question is answered from the manifests instead: a crate declared beside any other dependency — anything but a path dependency on a manifest this run also pins, or a `workspace = true` inheritor of a table it scans — or beside a workspace member this run did not read (a `members` glob, or a member outside the project or behind a symbolic link, which member discovery drops) is refused `redirect_cargo_lockless_dependents`, whose detail names the remedies (commit a lockfile, or `--mode vendored`); a project whose only dependency is the patched crate has nothing that could pull it in and still redirects. All-CRLF manifests, locks and configs are rewritten with CRLF kept (mixed endings keep refusing where the grammar does not match), and `remove` / rollback match the recorded fragments across a later CRLF↔LF checkout conversion), `composer.lock`, `nuget.config` / `packages.lock.json` (plus, v5.0 #353/#514, every lock a project under the root restores into: a member project's `packages.lock.json`, a per-project `packages..lock.json`, a literal `NuGetLockFilePath` — each pinned with the root config; a `NuGetLockFilePath` it cannot evaluate warns `redirect_nuget_lock_path_unresolved` and a project tree it cannot list warns `redirect_nuget_lock_unreadable`, both skipping the nuget redirect with nothing written), `Gemfile` / `Gemfile.lock`, `pom.xml` (+ `.mvn/maven.config` / `.mvn/checksums/checksums.sha256` for maven Trusted Checksums merge, and, for a Gradle build, every settings, build, `buildSrc`, included-build, applied and plugin-source script, version catalog and lock file the script graph reaches, plus `gradle/verification-metadata.xml`, `gradle/wrapper/gradle-wrapper.properties` and the owned `.socket/gradle/` files), and the sbt build files (`socket-patch.sbt`, `socket-patch-vendor.sbt`, `build.sbt`, `project/build.properties`, `.sbtopts`, `.jvmopts`; `build.sbt.lock` and the Mill / scala-cli build files `build.mill`, `build.mill.yaml`, `build.sc`, `.mill-version`, `project.scala` for their presence only) — read, never edited; `socket-patch.sbt` is the only sbt file hosted mode writes (see **Hosted sbt** below). **npm-family flavor coverage**: package-lock / npm-shrinkwrap (a package the project patches itself with npm ≥ 12.1's native `npm patch` — a root `patchedDependencies` key, or the lock entry's `patched` record — is left on its registry entry in every npm lock, `redirect_npm_patched_dependency_skipped`), pnpm (root OR any nested `*/pnpm-lock.yaml`), yarn classic (a yarn 2+ install migrates a v1 `yarn.lock` and drops its pins, so a run whose v1 lock carries a hosted pin warns `redirect_yarn_classic_berry_migration_risk` — the hosted twin of the vendored `yarn_classic_berry_migration_risk` — unless the root `package.json`, read as advisory input, declares `"packageManager": "yarn@1…"`), **yarn berry** (the pin yarn writes for a root `resolutions` entry: the root `package.json` — edited only beside a berry `yarn.lock` — gains one `"@npm:": ""` selector per locked range (`redirect_yarn_berry_resolution` edits), and only that `yarn.lock` entry is re-keyed `"@"` with the same `resolution:` + `yarnBerry10c0` checksum (`redirect_yarn_berry_entry`), moved to yarn's key order; never an `npm:` locator, whose fetcher sends npm registry auth to the patch host, nor a tarball locator under an `npm:` key, which hardened mode rejects (YN0078). An older release's `npm:::__archiveUrl=` pin is still recognized and is re-pinned on the next run; rollback rebuilds the key from the selectors and drops them. Refused, nothing written: a user-authored `resolutions` entry for the package `redirect_yarn_berry_resolutions_conflict`, no root manifest `redirect_yarn_berry_manifest_missing`, a builtin `patch:` entry wrapping the same descriptor `redirect_yarn_berry_shared_descriptor`, an artifact URL yarn cannot fetch as a tarball `redirect_yarn_berry_artifact_url_unsupported`; cacheKey `10c0` and `.yarnrc.yml compressionLevel 0` gated by `redirect_yarn_berry_cache_unsupported`), and **bun** (text `bun.lock` lockfileVersion 0 to 3 — 0 is the `--save-text-lockfile` opt-in lock of Bun 1.1.39–1.1.45, 1 the 1.2–1.3 default, 2 the 1.4+ default, 3 what Bun 1.4+ writes when `package.json` has a nested override or a yarn-style path resolution (only the lock's head differs: its `overrides` object nests); all four emit one `packages` grammar, so the registry 4-tuple → URL 3-tuple rewrite is version-independent and the lock's own version line is kept. Any other or missing version, or a `packages` section outside bun's single-line grammar, is refused `redirect_bun_lock_unsupported` — the detail is the shared version gate's text (a newer version: update socket-patch, re-locking would reproduce it; no integer: re-lock with Bun ≥ 1.2), identical to the vendored refusal. A version-0 lock holding `workspace:` packages is refused `redirect_bun_workspace_unsupported` (its 2-tuple workspace grammar cannot keep the hosted tuple through a frozen install); the remedy is to delete `bun.lock` and re-run `bun install` with Bun ≥ 1.2, which writes lockfileVersion 1 (accepted). A plain in-place `bun install` bumps the version only when a workspace depends on another workspace (e.g. root → member — the shape the matrix measured); otherwise Bun 1.2.0 keeps version 0 and Bun 1.2.23+ fail to resolve, so the in-place bump is not the documented remedy. Bun lock version, grammar and workspace compatibility are checked before a vendored takeover, including during dry-run: these refusals preserve the existing lock, artifact and vendor ledger. Version-1 and version-2 workspace locks are rewritten, nested versions included. A granted dep with no rewritable entry warns `redirect_bun_entry_not_found` (or `redirect_bun_non_registry_entry_skipped` when the only same-version entry is a user URL / `file:` tarball, #497), a grant without a sha512 `redirect_bun_missing_sha512`; a CRLF lock keeps `\r\n` on the rewritten line, and a hosted URL left by an earlier grant of the same `name@version` is re-pinned in place. **Digest-less re-saves (Bun 1.1.39–1.3.9)**: every text-lock Bun below 1.3.10 re-saves a URL tuple WITHOUT its `sha512` whenever the lock is re-saved for another reason (`bun add`, `bun install` after a package.json or workspace change), leaving the 2-tuple `["name@", {meta}]` — the spec Bun installs from is intact. The CLI treats that spelling as its own wiring: a repeat hosted run counts the dep as redirected (no `redirect_bun_entry_not_found`) and HEALS the line back to the 3-tuple with the current `sha512`, recording the heal as a further `redirect_bun_lock_package` edit whose `original` is the 2-tuple (a stale URL is re-pinned from either spelling); `rollback`, scoped `rollback ` / `remove ` and the vendored takeover accept the digest-less spelling of a recorded `new` line (same key, spec and meta, only the trailing `"sha512-…"` missing) and restore the recorded original over it, so the chain always unwinds to the pristine registry line. Anything else — another uuid/token, another version, a re-laid meta object — is still drift. **Native `bun.lockb`**: when no text `bun.lock` exists, binary format versions 1, 2 and 3 are read and rewritten directly. Socket Patch does not invoke Bun or convert the project to a text lockfile. Exact matching package records are rewritten to hosted tarballs with the granted integrity, preserving dependency resolution IDs, workspace/dependency topology and unrelated package metadata; binary pointers and the package metadata hash are updated. Per-package `redirect_bun_lockb_package` snapshots support scoped rollback, repeat runs, superseding grants and hosted ↔ vendored takeover. A regular binary lock is discoverable even with no Bun runtime or `node_modules`; a dry run previews the same binary edits without writing them. A malformed, unreadable, unsupported or unverified binary structure is `redirect_bun_lockb_invalid` (exit 0, `redirected: 0`), and it refuses the npm rewrite before any takeover or sibling npm-family lock mutation. A symlinked binary write target is `redirect_symlinked_file_unsupported` (exit 1, including dry-run). `bun.lock` wins when both spellings exist. Binary-only projects do not receive `redirect_npm_no_lockfile`. Measured boundaries and the real-Bun matrix: `docs/testing/bun-compatibility.md`), and **vlt** (`vlt-lock.json` without `lockfileVersion`, `0` or `1`; see the vlt hosted-mode contract below). **Rush monorepos**: when `rush.json` is present the rewriter also reads `common/config/rush/pnpm-lock.yaml` and each `common/config/subspaces//pnpm-lock.yaml` (sorted for determinism) under their repo-relative keys and repoints them in place; editing them emits `redirect_rush_repo_state_stale` when the `repo-state.json` beside a rewritten lock exists (`common/config/rush/repo-state.json` for the common lock, `common/config/subspaces//repo-state.json` for a subspace lock; the `pnpmShrinkwrapHash` desync is refreshed by `rush update`, which the redirect survives), and `redirect_pnpm_trust_lockfile` carries the Rush pnpm >=11 install remedy (see the trust paragraph above). **maven** is fail-closed via version suffixing: a `mavenSuffixedVersion` + `mavenPomSha256` override pins the Socket-only `-socket.` by rewriting the literal `` (`redirect_maven_dep_version`) or adding a `` entry (`redirect_maven_dep_management_added`), plus optional Trusted Checksums (`redirect_maven_trusted_checksums`, conflicts as `redirect_maven_trusted_checksums_conflict`; the `.mvn/maven.config` line that names the checksums directory is spelled `${maven.multiModuleProjectDirectory}/.mvn/checksums`, which no Maven 3 build fails on wherever it is started, or `${session.rootDirectory}/.mvn/checksums` for a project that declares Maven 4 (a wrapper that pins it, or a root pom whose model is newer than 4.0.0: its ``, else the version its namespace names), the only form Maven 4 reads. The six settings hosted mode wrote, standing together in the other spelling, are respelled in that one line by every `scan --mode hosted` that reads the file (`redirect_maven_config`, `rewritten`, `key: "trustedChecksumsDirectory"`; the edit that merges the settings in keeps `key: "trustedChecksums"`), whatever the run redirects: with no Maven patch in the run, in a reactor root, in a root another rewriter owns, with no checksum line left, with a later line that switches the pin off. A scan with nothing to redirect reads `.mvn/maven.config` for that alone, and takes the write lock for it when it can. The respelling is never the reason a run fails: when the lock cannot be had, or the file is a symbolic link (which a write would replace), the line is left as it is and nothing is reported for it. This is what removes the line an earlier release wrote for every project, which stops Maven 3.9.2 to 3.9.8 from starting with `-f` from outside the project. A directory line that stands apart from the other five is the user's and is never rewritten. When the respelling takes `${session.rootDirectory}` out of a project that declares no Maven, a Maven 4 build of it stops enforcing the pin (Maven 3.9.4 and later 3.x go on enforcing it): the additive warning `redirect_maven_trusted_checksums_maven3_only` says so, once, with the remedy (declare Maven 4 and scan again). A directory line in the launcher's spelling that the user wrote, in a project that declares Maven 4, names no directory there: it is left as written and reported as `redirect_maven_trusted_checksums_conflict`. Either form is recognised by `vex`, `rollback` and `remove`; when the Maven the project declares does not enforce the pin as the config stands (the wrapper pins a Maven older than 3.9.4, or the project declares Maven 4 and the line is in the spelling Maven 4 does not read), the additive warning `redirect_maven_trusted_checksums_unenforced`, whose detail names the remedy for that case; a grant sha256 that is not 64 hex digits writes no checksum line, `redirect_maven_trusted_checksums_invalid_hash`); a `${property}` version is wired through the property's own value (`redirect_maven_property`) or a literal that records the text it replaced (`redirect_maven_dep_version` with the `${...}` text as `original`), and stays `redirect_maven_dep_unpinned` only when what it reads cannot be told, a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`) is planned over every pom of the reactor, each module `pom.xml` that takes an edit appearing in `rewrittenFiles` (see [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions)); a reactor one of whose poms cannot be read, and a same-GAV grant in a reactor, are refused whole with `redirect_maven_multimodule_unsupported`: the poms and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the poms pin it too), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped, with nothing written, when a variant other than `sources` / `javadoc`, live or inside ``, may resolve any version but the suffixed pin — the patched release, another one, a `${property}` a profile moves, or no version in the pom once its classifier-keyed `` (a profile's too) is consulted — since `vex` would never attest that pin: `vex_maven_classifier_unpatched`), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`): when any version it may resolve — its own, or what its own profile's or any combination of profiles' `` make of it, read as `vex` reads it — is not the suffixed pin, the dep is refused with nothing written, since it overrides the pin whenever that profile is active and `vex` would never attest it (a profile `` entry only when management governs the pin, i.e. no live direct declaration carries a version); a versionless one takes the pin, and the dep is also skipped when a profile holds its only declaration, a `${property}` groupId / artifactId resolved from the pom's own `` before matching (one the pom does not define, which may be the patched GA and whose own version would then win, refuses the dep with nothing written: `redirect_maven_coordinate_unresolved`), and a `${property}` groupId / artifactId some profile's `` (or several profiles' together) redefine so that the declaration a pin would go into names another package, or another declaration names the GA's main jar at another version (or one of its executable classifier copies, a `test-jar` included), refuses the dep with nothing written too (`redirect_maven_profile_coordinates_unpatched`): `vex` would never attest that pin (`vex_maven_profile_unpatched`), and a pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). A pin is written only where Maven selects the patch's base version already (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`): see [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). **gradle** (v5.0) is automated wiring, no longer a pasted snippet: the owned settings script `.socket/gradle/socket-patch.hosted.settings.gradle` with its index `.socket/gradle/hosted-index.tsv`, one apply line per build's settings file, every lock entry of the GA moved to the suffixed version, and the suffixed component in an existing `gradle/verification-metadata.xml`. A refused dep writes nothing and keeps `redirect_gradle_manual_snippet` as its fallback; same-GAV grants are refused (`redirect_gradle_same_gav_unsupported`). Rules, refusals and codes: [Gradle builds](#gradle-builds-v50). +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, the `.mvn/socket-patch/prefixes-socket-patch-.txt` repository filter files, `.mvn/jvm.config` read only, 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. The repository filter's directory line (`.mvn/socket-patch`) is spelled by the same rule and respelled the same way, under `key: "repositoryFilterDirectory"` (see [Hosted Maven repository filter](#hosted-maven-repository-filter)). When the respelling takes `${session.rootDirectory}` out of a project that declares no Maven, a Maven 4 build of it stops enforcing the pin (Maven 3.9.4 and later 3.x go on enforcing it): the additive warning `redirect_maven_trusted_checksums_maven3_only` says so, once, with the remedy (declare Maven 4 and scan again). A directory line in the launcher's spelling that the user wrote, in a project that declares Maven 4, names no directory there: it is left as written and reported as `redirect_maven_trusted_checksums_conflict`. Either form is recognised by `vex`, `rollback` and `remove`; when the Maven the project declares does not enforce the pin as the config stands (the wrapper pins a Maven older than 3.9.4, or the project declares Maven 4 and the line is in the spelling Maven 4 does not read), the additive warning `redirect_maven_trusted_checksums_unenforced`, whose detail names the remedy for that case; a grant sha256 that is not 64 hex digits writes no checksum line, `redirect_maven_trusted_checksums_invalid_hash`); a `${property}` version is wired through the property's own value (`redirect_maven_property`) or a literal that records the text it replaced (`redirect_maven_dep_version` with the `${...}` text as `original`), and stays `redirect_maven_dep_unpinned` only when what it reads cannot be told, a reactor root (a `` / `` declaration, a profile's included, or a Maven 4 root that lists none but whose subprojects Maven discovers: model version not `4.0.0`, `pom` packaging, a direct subdirectory holding a `pom.xml`, and `maven.project.discoverSubprojects` not turned off in `.mvn/maven.config`) is planned over every pom of the reactor, each module `pom.xml` that takes an edit appearing in `rewrittenFiles` (see [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions)); a reactor one of whose poms cannot be read, and a same-GAV grant in a reactor, are refused whole with `redirect_maven_multimodule_unsupported`: the poms and `.mvn/` are left untouched and the dep is not counted as redirected (a Gradle build beside it is still planned by the Gradle rewriter, but a dep in a root with a `pom.xml` is confirmed only when the poms pin it too), a non-matching literal skipped (`redirect_maven_dep_version_mismatch`), a `` variant (sources, tests, a native build) left at its version (`redirect_maven_classifier_unsupported`; the grant serves the main jar only, and the dep is skipped, with nothing written, when a variant other than `sources` / `javadoc`, live or inside ``, may resolve any version but the suffixed pin — the patched release, another one, a `${property}` a profile moves, or no version in the pom once its classifier-keyed `` (a profile's too) is consulted — since `vex` would never attest that pin: `vex_maven_classifier_unpatched`), a versioned declaration inside `` (a literal or a `${property}`) left as-is (`redirect_maven_profile_dependency_unpatched`): when any version it may resolve — its own, or what its own profile's or any combination of profiles' `` make of it, read as `vex` reads it — is not the suffixed pin, the dep is refused with nothing written, since it overrides the pin whenever that profile is active and `vex` would never attest it (a profile `` entry only when management governs the pin, i.e. no live direct declaration carries a version); a versionless one takes the pin, and the dep is also skipped when a profile holds its only declaration, a `${property}` groupId / artifactId resolved from the pom's own `` before matching (one the pom does not define, which may be the patched GA and whose own version would then win, refuses the dep with nothing written: `redirect_maven_coordinate_unresolved`), and a `${property}` groupId / artifactId some profile's `` (or several profiles' together) redefine so that the declaration a pin would go into names another package, or another declaration names the GA's main jar at another version (or one of its executable classifier copies, a `test-jar` included), refuses the dep with nothing written too (`redirect_maven_profile_coordinates_unpatched`): `vex` would never attest that pin (`vex_maven_profile_unpatched`), and a pom not readable as one left untouched (`redirect_maven_pom_unreadable`). Matches and anchors skip comments, CDATA, ``, ``, ``, `` and `` (the scope `vex` reads), and an existing self-closed `` / `` is expanded in place, never duplicated; an override without a suffixed version falls back to same-GAV repository injection (`redirect_maven_same_gav_fallback`, NOT fail-closed). A pin is written only where Maven selects the patch's base version already (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`): see [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). **gradle** (v5.0) is automated wiring, no longer a pasted snippet: the owned settings script `.socket/gradle/socket-patch.hosted.settings.gradle` with its index `.socket/gradle/hosted-index.tsv`, one apply line per build's settings file, every lock entry of the GA moved to the suffixed version, and the suffixed component in an existing `gradle/verification-metadata.xml`. A refused dep writes nothing and keeps `redirect_gradle_manual_snippet` as its fallback; same-GAV grants are refused (`redirect_gradle_same_gav_unsupported`). Rules, refusals and codes: [Gradle builds](#gradle-builds-v50). **Hosted sbt (v5.0, additive)**: an sbt build root (`project/build.properties` naming an `sbt.version`, 0.13.18 or later) is wired through ONE generated root file, `socket-patch.sbt` — no user file is edited. It pins every granted Maven patch build-wide (a `ThisBuild` `dependencyOverrides +=` of the Socket-only `-socket.` version plus a `file:` resolver over `.socket/sbt-hosted/maven2/`, moved ahead of the default repositories on sbt 0.13 / 1.x so an unreachable one never blocks it offline), downloads the pinned pom and jar there on the first sbt load (sha256-checked, gitignored by the file itself), and installs a load-time verifier that fails `update` when any project resolves another version or a pinned artifact whose bytes are not pinned. Edits: `redirect_sbt_pin` (added), `redirect_sbt_pin_updated` (an existing row replaced: same GA and base under a new uuid, or the same uuid with new served values; `original` names the previous uuid and version), `redirect_sbt_pin_rechecked` (an existing row re-verified after the build's dependencies changed: its dependency digest is recorded anew, `original`/`new` are `{deps}`). The load-time verifier also fails `update` when a project declares a pinned GA at a version newer than the pin's base (the build-wide override would otherwise force it back down). A new pin is gated on sbt's own resolution records under `target/` (never the machine-wide cache): run-level stops wire nothing, warn once and exit 0 — `redirect_sbt_no_resolution_evidence` (none; run `sbt update` first; always the in-memory engine's answer), `redirect_sbt_resolution_incomplete` (a declared project left no evidence, or the project definitions cannot be read statically), `redirect_sbt_resolution_stale` (a build source is newer than some project's evidence: each project is dated by its own newest record, so a partial `sbt /update` does not vouch for the others). Per-patch refusals (never confirmed): `redirect_sbt_missing_override` (no `maven2` override or no suffixed version), `redirect_sbt_integrity_missing` (jar or pom sha256 missing), `redirect_sbt_unsafe_value` (a value unsafe in a Scala literal, or an index URL not naming the uuid), `redirect_sbt_version_conflict` (some project resolves another version, or a build source declares the GA newer than the patch's base), `redirect_sbt_override_conflict` (two patches for one GA in a run, or another base already pinned), `redirect_sbt_vendored_conflict` (the GA is pinned by `socket-patch-vendor.sbt`, or that file cannot be parsed — then every Maven patch), `redirect_sbt_owned_file_modified` / `redirect_sbt_owned_file_foreign` (`socket-patch.sbt` edited, or not socket-patch's — every Maven patch), `redirect_sbt_owned_file_unreadable` (a whole-run refusal: `socket-patch.sbt` is on disk but cannot be read as UTF-8 text, so writing it would replace it; nothing is written), `redirect_sbt_unsupported_version`, `redirect_sbt_build_root_unknown` (sbt files but no versioned build root — every Maven patch), `redirect_sbt_overrides_assignment` / `redirect_sbt_resolvers_assignment` (a build source reassigns `dependencyOverrides` / `resolvers` with `:=`, `~=`, `--=` or `<<=`), `redirect_sbt_onload_assignment` (a build source reassigns `onLoad`, in any scope, with `:=`, `~=`, `--=` or `<<=` without keeping its previous value — a `:=` reading `(Global / onLoad).value`, or a `~=` that composes with `andThen` / `compose`, keeps it — which drops the generated file's load-time verifier and resolver order), `redirect_sbt_dependency_lock_present` (a `build.sbt.lock`), `redirect_sbt_scala_runtime_unsupported` (`org.scala-lang`), `redirect_sbt_classifier_unsupported`; a GA no library configuration resolves is skipped silently (`redirect_sbt_meta_build_only` when only the meta-build resolves it). Advisories: `redirect_sbt_version_untested` (sbt 2.1+, still wired), `redirect_sbt_override_build_repos` (`sbt.override.build.repos=true`), `redirect_maven_pom_ignored_sbt_build` (a `pom.xml` beside the sbt build, which sbt never reads; the Maven rewriter still edits it for the Maven build). A re-run keeps an existing row and re-checks it. When the build's dependency digest changed since the pin, evidence resolved after the change (fresh, newer than the generated file) re-verifies it and the row's digest is refreshed (`redirect_sbt_pin_rechecked`); the uuid is NOT confirmed on `redirect_sbt_pin_declared_newer` (a build source now declares the GA newer than the pin's base; the row stays, sbt's load-time verifier fails the build, and the remedy is `socket-patch rollback` or declaring the base again), `redirect_sbt_pin_unverifiable` (the digest changed and the evidence predates the change, or the digest cannot be computed: run `sbt update`, then re-run socket-patch), `redirect_sbt_override_shadowed` (the evidence still resolves the base version) or `redirect_sbt_resolved_elsewhere` (the pinned version resolves from outside the pin repository from a file whose sha256 is not the pinned jar's; a copy holding the pinned bytes, such as the Ivy cache a second checkout reads, is fine — at most 64 pinned artifact files of up to 256 MiB are hashed, anything else counts as elsewhere), and also when a build source now reassigns `dependencyOverrides` / `resolvers` / `onLoad` or a `build.sbt.lock` appeared (the same `redirect_sbt_overrides_assignment` / `redirect_sbt_resolvers_assignment` / `redirect_sbt_onload_assignment` / `redirect_sbt_dependency_lock_present` codes; the row stays and sbt's load-time verifier fails the build). For a pure sbt root (no `pom.xml` / Gradle script beside it), maven confirmation is decided only by the sbt rewriter's report; on a mixed root a uuid the sbt rewriter refused is still confirmed by the Maven rewriter's own `pom.xml` pin (the generated sbt files never prove a pin by substring). **Mill and scala-cli** are guidance only: per Maven patch `redirect_mill_manual_snippet` / `redirect_scala_cli_manual_snippet` carry a paste-able snippet (repository + forced suffixed version), nothing is written or confirmed, and a pure Mill / scala-cli root gets no `redirect_maven_no_pom`; there, a Maven patch the server sent without a `maven2` registry override gets `redirect_maven_missing_override` instead of a snippet (with a `pom.xml` beside the Mill / scala-cli files the pom rewriter reports it). `rollback` / `remove` restore `socket-patch.sbt` offline (the rows removed, the file deleted with its last pin; the gitignored downloads are left). Manifest-less VEX reads every strictly parsed pin as a hosted reference but grants it the lockfile basis only when the local evidence shows every recorded version of the GA is the pinned one and every recorded artifact hashes to a pinned sha256 (else `sbt_resolution_unverified`, and the suffixed copy sbt downloaded into `.socket/sbt-hosted` is its only basis). Where the build provably does not use the pinned bytes, that copy proves nothing and the patch is omitted (`vex_sbt_pin_bypassed`): a build source reassigns `dependencyOverrides` (`:=`, `~=`, `--=`; replacing the generated override) or reassigns `onLoad` without keeping its previous value (dropping the installer that holds the load-time verifier and resolver order), whether or not any evidence exists, or a resolution record dated after the generated files and every build source shows the GA's base version (the override shadowed), or the pinned version from outside the pin repository with bytes that are not pinned (judged exactly as the hosted rewriter re-checks a pin, `redirect_sbt_override_shadowed` / `redirect_sbt_resolved_elsewhere`). A record older than the wiring (a project or cross build not re-resolved since) proves nothing, and current records that verify the pin always keep it. A `resolvers` reassignment or `sbt.override.build.repos=true` alone is no bypass: the override still forces the Socket-only version and the load-time verifier checks its bytes, so the build runs the pinned bytes or fails (which is why an `onLoad` reassignment dropping that verifier is one). Stale or partial evidence, project definitions that cannot be read statically and a `build.sbt.lock` only withhold the lockfile basis. A file under a generated name without socket-patch's header is read as the root build definition sbt loads it as. @@ -1781,7 +1781,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 `!`. A gem hosted as platform builds has every entry of its Socket section moved back to where Bundler sorts it (by full name: `nokogiri (1.18.10)` before `nokogiri (1.18.10-arm64-darwin)`), and each `CHECKSUMS` entry re-pinned to its own build's upstream sha256, the index's `-` line (one `info/` request per gem). **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` (or a platform build's `--.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`). 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. + * **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. The repository filter goes too: the `.mvn/socket-patch/prefixes-socket-patch-.txt` file of each restored pin, any such file whose repository no pom declares any more, and, once that directory holds nothing, the two `aether.remoteRepositoryFilter.prefixes` lines in `.mvn/maven.config`, in either spelling of their directory (byte for byte; anything else in that directory keeps them, and the user's own `prefixes=true` with no `.mvn/socket-patch` line beside it is never taken). Where the lines stay, the directory line is respelled for the Maven the project declares like the six settings, and `maven_repository_filter_maven3_only` says so when that takes the filter on Maven 4 away. A config the restore cannot write keeps the two lines, and a filter directory it cannot list is left whole; the pin is restored all the same (`maven_repository_filter_left`). * **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. @@ -2323,6 +2323,12 @@ command's integration tests check its output. | `redirect_maven_multimodule_unsupported` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the root `pom.xml` heads a reactor that cannot be planned: a module pom is missing or not readable as a pom, a `` path is a property or leaves the project, or the grant serves the patched artifact under its original version (a same-GAV grant). The detail carries the reason. The poms and `.mvn/` stay byte-identical and the dep is not counted as redirected. A reactor that can be read is patched module by module: see [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). | | `redirect_maven_pin_would_move_module` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven reactor): a parent pom resolves the base version itself above a module that resolves another version, so the parent takes no pin (Maven's management always reaches the children); the modules below it that select the base version are pinned. Also reported when a pin an earlier run wrote is taken out because a module it reaches now resolves another version, which the pin would hold back (the `redirect_maven_dep_management` edit has `action: "removed"`). Exit 0. | | `redirect_maven_edit_not_reversible` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): a pom would take an edit that `rollback` could not undo byte for byte from the pom alone. A pin in a `` that holds no entry (which would be left changed or removed) leaves that one pom as it is: the modules it would have wired stay unpatched, and `vex` withholds the statement while one of them resolves the base version. Any other case (a `` section that would not come back as it was) refuses the whole plan for the patch: nothing is written and the dep is not counted as redirected. Exit 0. See [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). | +| `redirect_maven_repository_filter_conflict` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the pin landed, but `.mvn/maven.config`, `.mvn/jvm.config` or the environment of the scanning machine (`MAVEN_OPTS`, `MAVEN_ARGS`, `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS`) already configures Maven Resolver's `prefixes` repository filter (`aether.remoteRepositoryFilter.prefixes`, or its `.basedir`, with a value other than the two hosted mode writes, in either spelling of the directory). That filter reads its files from one directory per build, so hosted mode writes neither its two lines nor the `.mvn/socket-patch/prefixes-socket-patch-.txt` file and leaves the configuration as it is: the Socket repository is not filtered, and Maven asks it for every artifact the local repository does not hold. Once per patch; the detail names the setting found, the patch's repository and the path to list in a `prefixes-socket-patch-.txt` file of the user's own filter directory. The dep is still counted as redirected. See [Hosted Maven repository filter](#hosted-maven-repository-filter) | +| `redirect_maven_repository_filter_enabled` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): this run added the two `aether.remoteRepositoryFilter.prefixes` lines to `.mvn/maven.config`. The filter reads its files from one directory per build, so every build of the project now reads prefix files from `.mvn/socket-patch/` only: a prefix file kept anywhere else is no longer read unless a build names its directory on the command line. Once, by the run that adds the lines; a run that finds them in place says nothing. Status and exit code are unchanged. See [Hosted Maven repository filter](#hosted-maven-repository-filter) | +| `redirect_maven_repository_filter_skipped` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the pin landed without the repository filter, because the filter could not be written: `.mvn/maven.config` cannot take the two lines (it is a symbolic link, or its directory does not take the write; once per run), or a link or a directory stands under the name of the patch's filter file (once per patch). The Socket repository is not filtered. The dep is still counted as redirected. See [Hosted Maven repository filter](#hosted-maven-repository-filter) | +| `redirect_maven_repository_filter_unread` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the repository filter is in place for a pin of this run, but the Maven the project declares does not read it: its Maven Wrapper pins a Maven older than 3.9.2, or the project declares Maven 4 and the directory line in `.mvn/maven.config` names `${maven.multiModuleProjectDirectory}`, which Maven 4 does not interpolate (a line in a spelling of the argument the respelling leaves alone). Maven then asks each Socket repository for every artifact its local repository does not hold. The files are written all the same. Once per run, on the scan that writes the file and on every later one; the detail names the remedy (a wrapper at 3.9.2 or later; the line set to the `${session.rootDirectory}` spelling). The dep is still counted as redirected. See [Hosted Maven repository filter](#hosted-maven-repository-filter) | +| `redirect_maven_repository_filter_maven3_only` / `maven_repository_filter_maven3_only` | `warnings[]` (warning) | scan / get `--mode hosted` (the first code) and rollback / remove (the second), Maven: the repository filter's directory line in `.mvn/maven.config` named the 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 it with `${maven.multiModuleProjectDirectory}` in a project that declares no Maven, with the filter switched on. Maven 3.9.2 and later 3.x ask the Socket repositories for the patched versions only, as before; a Maven 4 build of the project no longer does. Reported once, by the run that changes the line, and not by a scan that takes the two lines out in the same run. The remedy is that of `redirect_maven_trusted_checksums_maven3_only`: declare Maven 4, and the next hosted scan writes the spelling Maven 4 reads. Status and exit code are unchanged. | +| `maven_repository_filter_left` | `warnings[]` (warning) | rollback / remove (Maven): the pins were restored, and something of the repository filter was left where it was: the two lines in a `.mvn/maven.config` the restore could not write (a symbolic link, a directory that does not take the write, a file edited since it was read), which then name a directory with no file in it; or the whole of a `.mvn/socket-patch/` that could not be listed. The detail says which, and what to remove by hand. Status and exit code are unchanged. | | `redirect_maven_mirror_captures_repository` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven, on disk): the Maven settings of the scanning machine declare a `` whose `` matches the `socket-patch-` repository the pin needs (`*`, `external:*`, or a list without `!socket-patch-`), without naming that repository itself (alone, or as one id of a list). The mirror does not hold the patched version, so the build could not resolve it: nothing is written for the dep, `pom.xml` and `.mvn/` stay byte-identical, and the dep is not counted as redirected or attested by the same run's `--vex`, whatever an earlier run left in the poms. Exit 0. Reported only for a dep that would get (or already has) the repository. The detail names the mirror id, its ``, the settings file and the exclusion to add, and says that only this machine's settings were read. It offers `scan --mode vendored` with its bound: vendored mode gets past a mirror through `maven.repo.local.tail`, which Maven reads from 3.9.2 on. When the project's Maven Wrapper pins an older Maven the detail does not offer it as the project stands, and says what makes it work (a wrapper at 3.9.2 or later, or the mirror also leaving `socket-patch-vendor` out). See [Hosted Maven behind a mirror](#hosted-maven-behind-a-mirror) | | `redirect_gem_no_checksums_section` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock has no `CHECKSUMS` section (Bundler < 2.6 does not write one), so it cannot record the sha256 of the patched gems. They are redirected all the same (manifest and lock converged, frozen installs accept the pair) and pinned by source alone. Reported once per run, naming the gems; relock with Bundler ≥ 2.6 (`bundle lock --add-checksums`) and re-run to pin the checksums too. | | `redirect_gem_merged_lock_layout` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock was written by Bundler < 2.2 (`BUNDLED WITH`), which lists every gem source in ONE `GEM` section, so this run added the patch registry to that section's `remote:` lines. The pair installs with that Bundler, frozen / deployment mode included. Newer Bundlers deprecate such a section and from 2.5 on refuse the pair under frozen / deployment mode: if a newer Bundler installs the project, run `bundle lock` with it, commit the lock and re-run the hosted scan. Raised only by a run that wrote the lock. | @@ -3012,6 +3018,157 @@ not reach that resolves the base version, or whose selection cannot be told on the machine that runs `vex`, withholds the attestation, with the module named. `vendor --check` does not ask this. +### Hosted Maven repository filter + +Maven asks a `` a pom declares, before Maven Central, for every +artifact and parent pom its local repository does not hold yet. A hosted pin +adds one such repository per patch, which serves one version of one artifact. +With each pin that lands, `scan --mode hosted` therefore writes, for Maven +Resolver's `prefixes` repository filter: + +* `.mvn/socket-patch/prefixes-socket-patch-.txt`, one file per patch, + named for its repository id. It holds the header Maven 4 requires + (`## repository-prefixes/2.0`), a comment, and the one path the repository + serves: `///-socket.` + (`redirect_maven_repository_filter`, `action` `added`, `key` the repository + id, `new` the path); +* two lines appended to `.mvn/maven.config` + (`redirect_maven_config`, `key` `repositoryFilter`): + `-Daether.remoteRepositoryFilter.prefixes=true` and + `-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch`. + The directory is named through the property the Trusted Checksums + directory is named through, by the same rule: + `${maven.multiModuleProjectDirectory}`, which no Maven 3 build fails on + wherever it is started, or `${session.rootDirectory}` for a project that + declares Maven 4 (a wrapper that pins it, or a root pom whose model is + newer than 4.0.0), the only form Maven 4 reads. + +Maven 3.9.2 and later 3.x then ask the Socket repository for the pinned +version's jar and pom (and their checksums) and for nothing else, from the +project root, a module directory or with `-f /pom.xml` from outside +the project. So does Maven 4 in a project that declares it. The filter +abstains for a repository that has no file in that directory, so no other +repository is filtered. Every other build runs as before, unfiltered: before +3.9 the properties mean nothing, 3.9.0 / 3.9.1 interpolate neither +root-directory property, and Maven 4 does not interpolate +`${maven.multiModuleProjectDirectory}`, so a Maven 4 build of a project that +does not declare Maven 4 finds no file. A mirror gives the repository its own +id, under which no file exists, so nothing is filtered behind one. + +The filter is an extra: it never keeps a pin from landing and never refuses +a run. Where it cannot be had the pin lands without it, the Socket repository +stays unfiltered, as before there was a filter, and the run says so. + +Rules: + +* The file is written with the pin, from the pin's coordinates, and only for a + suffixed version (a same-GAV grant gets none). A file that did not list the + pinned version would fail the build + (`Prefix … NOT allowed from socket-patch-`). A file is read for what + it lists, not compared byte for byte: one that is there with the header + and the pinned path is left as it is, whatever its line endings (a CRLF + checkout) and whatever comment or other path someone added. One that does + not list the path is rewritten with the pin + (`redirect_maven_repository_filter`, `action` `rewritten`). +* A pin an earlier run wrote is left as it is, and so is its file: a re-run + writes nothing, and a pin of an earlier release gets no file until it is + rolled back and scanned again. +* The run that adds the two lines says what they change for the whole build: + `redirect_maven_repository_filter_enabled`, once. The filter reads its + files from one directory per build, so from then on every build of the + project reads prefix files from `.mvn/socket-patch/` only. A run that finds + the lines in place says nothing. +* The directory line is respelled when it stands in the other spelling + (`redirect_maven_config`, `rewritten`, `key: "repositoryFilterDirectory"`), + by every `scan --mode hosted` that reads the file and whatever the run + redirects, as the Trusted Checksums line is: a line that names the + directory through `${session.rootDirectory}` stops Maven 3.9.2 to 3.9.8 + from starting with `-f` from outside the project, and a project that has + since declared Maven 4 gets the spelling Maven 4 reads. The line is hosted + mode's wherever it stands, with or without the switch beside it, because + it names a directory nothing else uses; a line in another spelling of the + argument (`--define …`, quoted, indented) is left as written. When the + respelling takes `${session.rootDirectory}` out of a project that declares + no Maven, a Maven 4 build of it stops filtering: + `redirect_maven_repository_filter_maven3_only` says so, once, with the + remedy. The respelling is never the reason a run fails: when the lock + cannot be had, or the file cannot be written, the line is left as it is. +* What the project's Maven makes of the filter is said. When the Maven + Wrapper pins a Maven older than 3.9.2, or the project declares Maven 4 and + the directory line names `${maven.multiModuleProjectDirectory}`, the files + are written all the same (a later wrapper upgrade reads them, and a filter + Maven does not read restricts nothing) and the run warns + `redirect_maven_repository_filter_unread`, on the scan that writes the + file and on every later one, with the remedy. +* The filter is left to whoever configured it. With the switch on, either + spelling of hosted mode's directory line is in place and nothing is + appended. When `.mvn/maven.config` already sets + `aether.remoteRepositoryFilter.prefixes` or its `.basedir` to anything + else (in any spelling some Maven reads), when `.mvn/jvm.config` names the + property, or when the environment of the machine that scans does + (`MAVEN_OPTS`, `MAVEN_ARGS`, `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS`: + Maven 3.9.9 and 4.0.0-rc-7 honour the property in each), nothing is + written for the filter and the run warns + `redirect_maven_repository_filter_conflict` for each patch, naming what + configures it, that patch's repository and the path to list for it. The + pin lands all the same. Only the scanning machine's environment is known. +* The filter is skipped where it cannot be written + (`redirect_maven_repository_filter_skipped`), and the pin lands without + it. When `.mvn/maven.config` cannot take a write (it is a symbolic link, + which a write would replace, or its directory does not take the write) + and does not hold the two lines yet, neither the lines nor a filter file + are written; said once per run. A config that already holds the lines + needs no write, and its pins get their files. When a link or a directory + stands under the name of a pin's filter file, that file is not written; + said for that patch. Before, either case refused the whole hosted run. +* A scan writes files and removes none, and it never empties one. When it + takes a Socket repository out of the poms (a newer patch of the same + version replaced it, or its last pin went), that repository's file is left + exactly as it is: no pom names its repository, so Maven does not read it, + and it is the right file if the wiring comes back by another road (a + pom-only revert, a merge). It stays until `rollback` or `remove` deletes + it. Whether a pom still declares a repository is asked of every pom the + reactor read, whatever its file name. +* When a scan takes out the last Socket repository that has a filter file, + it takes the two lines out of `.mvn/maven.config` as well + (`redirect_maven_config`, `action` `removed`, `key` `repositoryFilter`), + since no later rollback would find anything to undo. It leaves them when a + pom still names a repository with a filter file, when the directory holds + anything that is not hosted mode's own file (a prefix file of the user's + is read through those lines) or could not be listed, and when the config + cannot take the write: the rule a rollback follows. +* `rollback` and `remove` delete the file of each pin they restore and every + such file whose repository no pom declares. Once the directory holds no + file, they remove the two lines from `.mvn/maven.config`, in either + spelling of the directory (and the file, if nothing else is left in it), + restoring its bytes. Where the lines stay, the directory line is respelled + as a scan respells it (`maven_repository_filter_maven3_only` when that + takes the filter on Maven 4 away). Only hosted mode's own + files are touched: regular files named + `prefixes-socket-patch-.txt`. Anything else in `.mvn/socket-patch/` + (a file of the user's, a subdirectory, a link) stays, and keeps the lines. + The lines are hosted mode's by the directory they name: a + `-Daether.remoteRepositoryFilter.prefixes=true` with no + `.mvn/socket-patch` line beside it is the user's and is never removed. +* Taking the filter out is never the reason a restore is refused + (`maven_repository_filter_left`). A config the restore could not write (a + symbolic link, a directory that does not take the write, a file edited + since it was read) keeps the two lines, which then name a directory with + no file in it and filter nothing; the pins are restored all the same. A + directory that could not be listed to its end is left whole, files and + lines, since what it holds is not known. Each is said, with what to remove + by hand. + +A build that switches the `prefixes` filter on from outside the checkout and +keeps its prefix files in the local repository's default directory stops +reading those files once the two lines are committed, because `maven.config` +then names another directory. A scan sees that only on the machine it runs +on, in the four environment variables above; a flag on a CI job's command +line, or the environment of another machine, it cannot see. That is what +`redirect_maven_repository_filter_enabled` is for. A +`-Daether.remoteRepositoryFilter.prefixes.basedir=…` on the same command line +wins over `maven.config`. + ### Hosted Maven behind a mirror A `` in Maven's `settings.xml` replaces every repository its diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 982fc4d71..f0e6fa2ac 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -1796,6 +1796,17 @@ impl EjectSnapshot { .iter() .map(|s| s.to_string()), ); + // A hosted Maven pin's restore also removes the repository filter + // files hosted mode keeps for it, one per patch: its own regular + // files only. Anything else in that directory (a subdirectory, a + // link, a file of the user's) is not the restore's to touch, and + // must not be read as a file here. + let disk = socket_patch_core::vendor::lock_inventory::ProjectView::Disk(root); + planned.extend( + socket_patch_core::patch::redirect::hosted_maven_filter_dir(&disk) + .await + .owned, + ); let mut files = std::collections::BTreeMap::new(); for rel in root_files.iter().chain(planned.iter()) { if files.contains_key(rel) { @@ -8298,6 +8309,39 @@ mod eject_snapshot_tests { let err = taken.err().expect("a FIFO must fail the snapshot"); assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); } + + /// The snapshot takes hosted Maven's own filter files, which the + /// restore of a hosted pin removes, and nothing else of that + /// directory: a subdirectory or a FIFO there (not hosted mode's, and + /// not a file) must not fail the eject of every ecosystem. + #[cfg(unix)] + #[tokio::test] + async fn snapshot_takes_only_hosted_maven_filter_files_of_their_directory() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join(".mvn/socket-patch"); + std::fs::create_dir_all(dir.join("notes")).unwrap(); + let ours = "prefixes-socket-patch-77777777-7777-4777-8777-777777777777.txt"; + std::fs::write(dir.join(ours), "## repository-prefixes/2.0\n").unwrap(); + std::fs::write(dir.join("prefixes-central.txt"), "/org\n").unwrap(); + let fifo = dir.join("prefixes-socket-patch-88888888-8888-4888-8888-888888888888.txt"); + let c = std::ffi::CString::new(fifo.to_str().unwrap()).unwrap(); + assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o644) }, 0); + let snapshot = tokio::time::timeout( + std::time::Duration::from_secs(10), + EjectSnapshot::take(tmp.path(), &[]), + ) + .await + .expect("nothing in the filter directory wedges the snapshot") + .expect("nor fails it"); + let taken: Vec<&str> = snapshot + .planned + .iter() + .map(String::as_str) + .filter(|rel| rel.starts_with(".mvn/socket-patch/")) + .collect(); + assert_eq!(taken, [format!(".mvn/socket-patch/{ours}").as_str()]); + assert!(snapshot.files[&format!(".mvn/socket-patch/{ours}")].is_some()); + } } #[cfg(test)] 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 832c3f0e2..00724b7a1 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs @@ -512,6 +512,14 @@ fn maven_scan_hosted_fresh_checkout_install_and_manifestless_vex() { config_after.contains(launcher_line) && !config_after.contains(session_line), "a project that declares no Maven takes the default spelling:\n{config_after}" ); + // The repository filter's directory follows the same rule, in the same + // run: no line of the config names `${session.rootDirectory}` now. + assert!( + config_after + .contains("prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch") + && !config_after.contains("${session.rootDirectory}"), + "both directories take the default spelling:\n{config_after}" + ); let warned = |code: &str| { env["warnings"] .as_array() @@ -526,9 +534,16 @@ fn maven_scan_hosted_fresh_checkout_install_and_manifestless_vex() { away, and only then: {env}", mvn.version ); + assert_eq!( + warned("redirect_maven_repository_filter_maven3_only"), + mvn.major() >= 4, + "Maven {}: and when it trades the repository filter on Maven 4 away: {env}", + mvn.version + ); assert!( - !warned("redirect_maven_trusted_checksums_unenforced"), - "no Maven is named, so none is said to ignore the pin: {env}" + !warned("redirect_maven_trusted_checksums_unenforced") + && !warned("redirect_maven_repository_filter_unread"), + "no Maven is named, so none is said to ignore the pin or the filter: {env}" ); assert_eq!( std::fs::read(undeclared.join("pom.xml")).unwrap(), @@ -704,7 +719,12 @@ fn maven_scan_hosted_fresh_checkout_install_and_manifestless_vex() { pristine_pom, "rollback restores the pom byte-for-byte" ); - for rel in [".mvn/checksums/checksums.sha256", ".mvn/maven.config"] { + let filter = format!(".mvn/socket-patch/prefixes-socket-patch-{UUID}.txt"); + for rel in [ + ".mvn/checksums/checksums.sha256", + ".mvn/maven.config", + filter.as_str(), + ] { assert!( !proj.join(rel).exists(), "rollback removes the {rel} hosted mode wrote" @@ -1673,6 +1693,357 @@ mod mediation { } } + /// A pom's `` is asked, before Maven Central, for every + /// artifact and parent pom the local repository does not hold yet. The + /// hosted scan therefore commits, with each pin, the prefix file that + /// limits its Socket repository to the pinned version + /// (`.mvn/socket-patch/prefixes-socket-patch-.txt`) and the two + /// resolver lines that make Maven read it. + /// + /// The line that names the file's directory takes the property the + /// Trusted Checksums directory takes: the launcher's, which stops no + /// Maven 3 from starting, unless the project declares Maven 4, which + /// reads only the session's. + /// + /// For a single pom and for a reactor, on a local repository that + /// holds none of the project's artifacts: + /// + /// - Maven 3.9.2 and later 3.x ask the Socket repository for the + /// patched version's jar and pom and their checksums, and for nothing + /// else, from the project root and with `-f /pom.xml` from + /// outside it (where a line naming `${session.rootDirectory}` stops + /// Maven 3.9.2 to 3.9.8 from starting at all); + /// - an older Maven reads no such file and asks it for the rest too, + /// and still builds (asserted, so a change either way is noticed). + /// So does Maven 4 while the project does not declare it; + /// - once the project declares the Maven under test, the next scan + /// leaves a Maven 3 project as it is and respells a Maven 4 project's + /// line, and Maven 4 then asks for nothing else either; + /// - without the file (the wiring of an earlier release) every Maven + /// asks for the rest, which also shows the repository was cold; + /// - a rollback takes the file and the lines out again, byte for byte. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_asks_the_socket_repository_only_for_the_patched_version() { + use std::collections::BTreeSet; + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let b = Bench::new(); + // The prefix file is read by repository id, and a mirror gives a + // repository its own: this one keeps the id the pom declares, as + // the repository has on a machine that reaches patch.socket.dev. + let id = format!("socket-patch-{UUID}"); + let settings = b.root.join("settings-socket-id.xml"); + let mirror_url = format!("{}{}", b.server.uri(), PATCH.repo_path()); + write_settings_with_ids(&settings, &[(&id, &id, &mirror_url)]); + let repo = format!("{}/", PATCH.repo_path()); + let victim: BTreeSet = ["jar", "jar.sha1", "pom", "pom.sha1"] + .iter() + .map(|ext| PATCH.served_path(ext)[repo.len()..].to_string()) + .collect(); + // What Maven asked of the Socket repository since request `mark`. + let asked = |mark: usize| -> BTreeSet { + b.server.paths()[mark..] + .iter() + .filter_map(|path| path.strip_prefix(repo.as_str()).map(str::to_string)) + .collect() + }; + + for reactor in [false, true] { + let name = if reactor { "reactor" } else { "single" }; + let proj = b.root.join(name); + if reactor { + fixture::write_reactor(&proj, &b.server); + } else { + fixture::write_project(&proj, Shape::Selected, &b.server); + } + // Warm the dependency plugin, and resolve what the scan reads + // the selection from. + let warmed = if reactor { + fixture::resolve_reactor(SUITE, &mvn, &proj, &b.m2, &b.plain, "target/before") + .is_some() + } else { + fixture::resolve(SUITE, &mvn, &proj, &b.m2, &b.plain, "target/before").is_some() + }; + if !warmed { + return; + } + // The wired project, resolved into the local repository `m2` + // (no fallback: nothing here may reach beyond the test's + // server), from the project root, or with `-f` from a directory + // outside the project. + let elsewhere = b.root.join(format!("elsewhere-{name}")); + std::fs::create_dir_all(&elsewhere).unwrap(); + let root_pom = proj.join("pom.xml"); + let goal = format!("{DEPENDENCY_PLUGIN}:copy-dependencies"); + let resolve = |m2: &Path, outside: bool, what: &str| { + let out = if outside { + let out_dir = format!("-DoutputDirectory={}", elsewhere.join("dep").display()); + let args = ["-f", root_pom.to_str().unwrap(), &goal, &out_dir]; + mvn.run(&elsewhere, m2, &settings, &args) + } else { + mvn.copy_dependencies(&proj, m2, &settings, "target/after") + }; + assert!( + ok(&out), + "{name}, Maven {}, {what}:\n{}", + mvn.version, + dump(&out) + ); + let _ = std::fs::remove_dir_all(proj.join("target")); + for (module, ..) in fixture::REACTOR_MODULES { + let _ = std::fs::remove_dir_all(proj.join(module).join("target")); + } + }; + let pristine = fixture::snapshot(&proj); + + let (code, env, stderr) = b.scan(&proj); + assert_eq!(code, Some(0), "{name}: {env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{name}: {env}"); + let filter = proj.join(format!(".mvn/socket-patch/prefixes-{id}.txt")); + let listed = std::fs::read_to_string(&filter) + .unwrap_or_else(|e| panic!("{name}: {}: {e}", filter.display())); + assert_eq!( + listed.lines().last(), + Some( + format!( + "/{}/{}/{}", + fixture::GROUP_PATH, + fixture::VICTIM, + b.suffixed + ) + .as_str() + ), + "{name}: {listed}" + ); + assert!( + warning(&env, "redirect_maven_repository_filter_conflict").is_none(), + "{name}: {env}" + ); + // The project declares no Maven: the directory is named through + // the launcher's property, which Maven 4 does not read. + let config = || std::fs::read_to_string(proj.join(".mvn/maven.config")).unwrap(); + let names_dir = |property: &str| { + let line = format!( + "-Daether.remoteRepositoryFilter.prefixes.basedir={property}/.mvn/socket-patch" + ); + config().lines().any(|l| l == line) + }; + let (launcher, session) = ( + "${maven.multiModuleProjectDirectory}", + "${session.rootDirectory}", + ); + assert!( + names_dir(launcher) && !config().contains(session), + "{name}:\n{}", + config() + ); + let reads_launcher = mvn.filters_repositories() && mvn.major() < 4; + + // A local repository with the dependency plugin and none of + // the project's artifacts. + let cold = |tag: &str| -> PathBuf { + let m2 = b.root.join(format!("m2-{name}-{tag}")); + copy_tree(&b.m2, &m2); + std::fs::remove_dir_all(m2.join("com").join("socketfixture")).unwrap(); + m2 + }; + let rest = |asked: &BTreeSet| -> Vec { + asked.difference(&victim).cloned().collect() + }; + + // From the project root, then with `-f` from outside it, where + // Maven 3.9.2 to 3.9.8 would not start at all on a line that + // named the directory through `${session.rootDirectory}`. + for (outside, tag, whence) in [ + (false, "filtered", "from the project root"), + (true, "outside", "with -f from outside the project"), + ] { + let mark = b.server.paths().len(); + resolve(&cold(tag), outside, whence); + let filtered = asked(mark); + assert!( + filtered.is_superset(&victim), + "{name}, {whence}: the patched version comes from the Socket repository: \ + {filtered:?}" + ); + if reads_launcher { + assert_eq!( + rest(&filtered), + Vec::::new(), + "{name}, {whence}: Maven {} asks the Socket repository for nothing else", + mvn.version + ); + } else { + assert!( + !rest(&filtered).is_empty(), + "{name}, {whence}: Maven {} does not read the prefix file of a project \ + that does not declare it: {filtered:?}", + mvn.version + ); + } + } + + // The project declares the Maven under test (its Maven Wrapper + // pins it) and is scanned again. A Maven 3 keeps the line; a + // Maven 4 gets the spelling it reads, and filters from then on, + // from the root and from outside. A Maven too old to read the + // filter is told so. + let wrapper = proj.join(".mvn/wrapper/maven-wrapper.properties"); + std::fs::create_dir_all(wrapper.parent().unwrap()).unwrap(); + std::fs::write( + &wrapper, + format!( + "distributionUrl=https\\://repo.maven.apache.org/maven2/org/apache/maven/\ + apache-maven/{v}/apache-maven-{v}-bin.zip\n", + v = mvn.version + ), + ) + .unwrap(); + let (code, env, stderr) = b.scan(&proj); + assert_eq!(code, Some(0), "{name}, declared: {env}\n{stderr}"); + let declares_4 = mvn.major() >= 4; + assert!( + names_dir(session) == declares_4 && names_dir(launcher) != declares_4, + "{name}: a project that declares Maven {}:\n{}", + mvn.version, + config() + ); + assert_eq!( + warning(&env, "redirect_maven_repository_filter_unread").is_some(), + !mvn.filters_repositories(), + "{name}: Maven {}: {env}", + mvn.version + ); + if declares_4 { + for (outside, tag, whence) in [ + (false, "declared", "from the project root"), + (true, "declared-outside", "with -f from outside the project"), + ] { + let mark = b.server.paths().len(); + resolve(&cold(tag), outside, whence); + let filtered = asked(mark); + assert!( + filtered.is_superset(&victim) && rest(&filtered).is_empty(), + "{name}, {whence}: Maven {}, declared, asks the Socket repository for \ + the patched version only: {filtered:?}", + mvn.version + ); + } + } + + std::fs::remove_file(&filter).unwrap(); + let mark = b.server.paths().len(); + resolve(&cold("unfiltered"), false, "without the prefix file"); + let unfiltered = asked(mark); + assert!( + unfiltered.is_superset(&victim) && !rest(&unfiltered).is_empty(), + "{name}: without the file every Maven asks for the rest: {unfiltered:?}" + ); + std::fs::write(&filter, listed).unwrap(); + + b.rollback(&proj); + // (The wrapper pin is the test's own, not the scan's.) + std::fs::remove_file(&wrapper).unwrap(); + let after = fixture::snapshot(&proj); + let differ: BTreeSet<&String> = after + .keys() + .chain(pristine.keys()) + .filter(|rel| after.get(*rel) != pristine.get(*rel)) + .collect(); + assert!( + differ.is_empty(), + "{name}: a rollback takes the filter and its lines out again; these differ: \ + {differ:?}" + ); + } + } + + /// The repository filter is an extra, and a pin never waits for it. A + /// project whose `.mvn/maven.config` is a symbolic link cannot take the + /// filter's two lines: a write would replace the link, which a scan + /// refuses for every file. The scan lands the pin without the filter, + /// exits 0 and says so, where the two lines used to refuse the whole + /// run. Maven reads the config through the link and resolves the + /// patched jar, a re-scan writes nothing, and a rollback puts every + /// file back. + #[cfg(unix)] + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_lands_the_pin_where_the_config_is_a_link() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let b = Bench::new(); + let proj = b.root.join("linked"); + fixture::write_project(&proj, Shape::Selected, &b.server); + let Some(before) = fixture::resolve(SUITE, &mvn, &proj, &b.m2, &b.plain, "target/before") + else { + return; + }; + // The team keeps its Maven arguments in one place and links them + // in: a setting of its own, and the Trusted Checksums settings (an + // earlier scan wrote them before the file was moved), so the + // filter's two lines are the only write the config would take. + let config = [ + "-B", + "-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", + "", + ] + .join("\n"); + std::fs::create_dir_all(proj.join("ci")).unwrap(); + std::fs::create_dir_all(proj.join(".mvn")).unwrap(); + std::fs::write(proj.join("ci/maven.config"), &config).unwrap(); + let link = proj.join(".mvn/maven.config"); + std::os::unix::fs::symlink("../ci/maven.config", &link).unwrap(); + let pristine = fixture::snapshot(&proj); + + let (code, env, stderr) = b.scan(&proj); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + let wired = std::fs::read_to_string(proj.join("pom.xml")).unwrap(); + assert!( + wired.contains(&b.suffixed) && wired.contains(&format!("socket-patch-{UUID}")), + "the pin landed:\n{wired}" + ); + let skipped = warning(&env, "redirect_maven_repository_filter_skipped") + .unwrap_or_else(|| panic!("the scan says the filter was skipped: {env}")); + assert!( + skipped["detail"] + .as_str() + .is_some_and(|detail| detail.contains(".mvn/maven.config cannot be written")), + "{skipped}" + ); + assert!(link.is_symlink(), "the link is still a link"); + assert_eq!( + std::fs::read_to_string(proj.join("ci/maven.config")).unwrap(), + config, + "and nothing was written through it" + ); + assert!( + !proj.join(".mvn/socket-patch").exists(), + "no filter file without the lines that would make Maven read it" + ); + + let after = fixture::resolve_warm(&mvn, &proj, &b.m2, &b.mirrored, "target/after", &[]); + b.assert_only_the_victim_is_patched("behind a linked config", &before, &after); + b.assert_rescan_is_a_no_op(&proj); + + b.rollback(&proj); + assert!(link.is_symlink()); + assert_eq!( + fixture::snapshot(&proj), + pristine, + "rollback restores every file byte for byte and leaves none behind" + ); + } + /// A company's `*` sends every repository to its /// repository manager, the Socket one included, and the manager does /// not hold the patched version: diff --git a/crates/socket-patch-cli/tests/in_process_scan.rs b/crates/socket-patch-cli/tests/in_process_scan.rs index 4e83ffba4..ec17fe580 100644 --- a/crates/socket-patch-cli/tests/in_process_scan.rs +++ b/crates/socket-patch-cli/tests/in_process_scan.rs @@ -1921,6 +1921,62 @@ async fn scan_hosted_with_nothing_to_redirect_heals_the_maven_config() { ); } +/// The same for the repository filter's directory line, here with no +/// Trusted Checksums block beside it: the scan that redirects nothing +/// reads the config for that line alone and respells it, so it does not go +/// on stopping Maven 3.9.2 to 3.9.8 from starting with `-f` from outside +/// the project. +#[tokio::test] +#[serial] +async fn scan_hosted_with_nothing_to_redirect_heals_the_maven_filter_line() { + 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 lines = |property: &str| { + format!( + "-B\n-Daether.remoteRepositoryFilter.prefixes=true\n\ + -Daether.remoteRepositoryFilter.prefixes.basedir={property}/.mvn/socket-patch\n" + ) + }; + let earlier = lines("${session.rootDirectory}"); + let healed = lines("${maven.multiModuleProjectDirectory}"); + 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(); + + let tmp = tempfile::tempdir().unwrap(); + project_with_a_stale_maven_config(tmp.path()); + std::fs::write(tmp.path().join(".mvn/maven.config"), &earlier).unwrap(); + // Dry: nothing written, no lock taken. + 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, and a second run has nothing to do. + assert_eq!(run_scrubbed(args_for(tmp.path(), false)).await, 0); + assert_eq!(config(tmp.path()), healed); + assert_eq!(run_scrubbed(args_for(tmp.path(), false)).await, 0); + assert_eq!(config(tmp.path()), healed); + + // This project's own spelling: 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. 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 64c5c3fb3..eb57cdff6 100644 --- a/crates/socket-patch-cli/tests/maven_build_common/mod.rs +++ b/crates/socket-patch-cli/tests/maven_build_common/mod.rs @@ -213,6 +213,21 @@ impl Mvn { self.numeric() >= vec![3, 9, 4] } + /// Maven ≥ 3.9.2 reads the repository prefix file the hosted rewriter + /// commits under `.mvn/socket-patch/`, and asks a Socket repository for + /// nothing but the version it lists. 3.9.0 / 3.9.1 interpolate neither + /// root-directory property in `maven.config`, so the file is never + /// found; older lines have no such filter. Below 3.9.2 the Socket + /// repository is asked for every artifact the local repository lacks, + /// like any repository a pom declares. + /// + /// Maven 4 finds the directory only when it is named through + /// `${session.rootDirectory}`, which the rewriter writes for a project + /// that declares Maven 4; under the default spelling it runs unfiltered. + pub fn filters_repositories(&self) -> bool { + self.numeric() >= vec![3, 9, 2] + } + /// `mvn -B ` in `cwd` against the local repository `m2`, with the /// user settings file `settings`. pub fn run(&self, cwd: &Path, m2: &Path, settings: &Path, args: &[&str]) -> Output { diff --git a/crates/socket-patch-cli/tests/scan_rollout_e2e.rs b/crates/socket-patch-cli/tests/scan_rollout_e2e.rs index 5e8fec0fe..33060bc34 100644 --- a/crates/socket-patch-cli/tests/scan_rollout_e2e.rs +++ b/crates/socket-patch-cli/tests/scan_rollout_e2e.rs @@ -966,7 +966,9 @@ async fn a_cap_of_zero_with_a_maven_config_to_heal_writes_nothing_but_the_heal() 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. + // them for every project, and the repository filter's two lines with + // their directory named through the same property: both directory + // lines are healed, and they are all the run writes. let earlier = [ "-Daether.artifactResolver.postProcessor.trustedChecksums=true", "-Daether.artifactResolver.postProcessor.trustedChecksums.checksumAlgorithms=SHA-256", @@ -974,6 +976,8 @@ async fn a_cap_of_zero_with_a_maven_config_to_heal_writes_nothing_but_the_heal() "-Daether.trustedChecksumsSource.summaryFile=true", "-Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums", "-Daether.trustedChecksumsSource.summaryFile.originAware=false", + "-Daether.remoteRepositoryFilter.prefixes=true", + "-Daether.remoteRepositoryFilter.prefixes.basedir=${session.rootDirectory}/.mvn/socket-patch", "", ] .join("\n"); diff --git a/crates/socket-patch-core/src/formats/maven/declared_maven.rs b/crates/socket-patch-core/src/formats/maven/declared_maven.rs index afdcbfd46..b5e8e814b 100644 --- a/crates/socket-patch-core/src/formats/maven/declared_maven.rs +++ b/crates/socket-patch-core/src/formats/maven/declared_maven.rs @@ -218,6 +218,50 @@ impl RootDirectory { pub(crate) fn unread_by(self, maven: &DeclaredMaven) -> bool { self == RootDirectory::Launcher && maven.is_maven_4() } + + /// What the Maven the project declares (`maven`) makes of a + /// `.mvn/maven.config` line that names a directory of the checkout + /// through this property, for a setting Maven acts on from the release + /// `since` on. The one answer for every such line hosted mode writes: + /// the Trusted Checksums directory and the repository filter's. + pub(crate) fn read_by(self, maven: &DeclaredMaven, since: [u32; 3]) -> Reads { + // 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) < since { + return Reads::TooOld(version.to_string()); + } + } + if self.unread_by(maven) { + Reads::UnreadByMaven4 + } else if self == RootDirectory::Launcher && maven.release().is_none() { + Reads::Maven3Only + } else { + Reads::Read + } + } +} + +/// What the Maven a project declares makes of a `.mvn/maven.config` line +/// that names a directory of the checkout through a root-directory property +/// ([`RootDirectory::read_by`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Reads { + /// The Maven Wrapper pins this Apache Maven release, which is older + /// than the first that acts on the setting. + TooOld(String), + /// The project declares Maven 4 and the line names the directory + /// through [`RootDirectory::Launcher`], which Maven 4 does not + /// interpolate. + UnreadByMaven4, + /// The project declares no Maven and the line names the directory + /// through [`RootDirectory::Launcher`]: Maven 3 reads it, a Maven 4 + /// build does not, and nothing in the checkout says which builds it. + Maven3Only, + /// The Maven the project declares reads the line; or it declares none, + /// and the line is spelled so that every Maven that acts on the + /// setting at all finds the directory. + Read, } #[cfg(test)] diff --git a/crates/socket-patch-core/src/formats/maven/mod.rs b/crates/socket-patch-core/src/formats/maven/mod.rs index e16444076..474aa6e1b 100644 --- a/crates/socket-patch-core/src/formats/maven/mod.rs +++ b/crates/socket-patch-core/src/formats/maven/mod.rs @@ -17,8 +17,9 @@ pub(crate) use properties::{ use super::xml::{blank_non_markup, child_text, elements, open_tags, Element}; -pub(crate) mod mirror; pub(crate) mod declared_maven; +pub(crate) mod mirror; +pub(crate) mod repository_filter; pub(crate) mod trusted_checksums; pub(crate) mod version; @@ -1005,6 +1006,38 @@ pub(crate) fn maven_config_properties(config: &str) -> BTreeMap props } +/// `config` (a `.mvn/maven.config`) with `args` appended, one per line: +/// the one way hosted mode adds settings to that file. With `keep_ending` +/// a file that ends without a line break still does, so the lines can be +/// taken out again byte for byte ([`repository_filter`]); without it the +/// result always ends with one, as the Trusted Checksums settings have +/// always been written (and as the rewriter's other implementation +/// writes them). +pub(crate) fn append_config_args(config: &str, args: &[&str], keep_ending: bool) -> String { + let block = args.join("\n"); + if config.is_empty() { + format!("{block}\n") + } else if config.ends_with('\n') { + format!("{config}{block}\n") + } else if keep_ending { + format!("{config}\n{block}") + } else { + format!("{config}\n{block}\n") + } +} + +/// Whether `config` (a `.mvn/maven.config`) holds lines hosted mode wrote +/// that name a directory of the checkout through a root-directory +/// property, in either spelling: the Trusted Checksums block +/// ([`trusted_checksums::holds_written_block`]) or the repository filter's +/// directory line ([`repository_filter::holds_written_line`]). Such lines +/// are respelled for the Maven the project declares, so a caller asks this +/// (a substring test for nearly every config) before it reads the Maven +/// Wrapper and the root pom to find out which spelling the project takes. +pub(crate) fn holds_respellable_lines(config: &str) -> bool { + trusted_checksums::holds_written_block(config) || repository_filter::holds_written_line(config) +} + /// Java's `String.trim`: every char up to U+0020, nothing beyond. fn java_trim(s: &str) -> &str { s.trim_matches(|c: char| c <= ' ') diff --git a/crates/socket-patch-core/src/formats/maven/repository_filter.rs b/crates/socket-patch-core/src/formats/maven/repository_filter.rs new file mode 100644 index 000000000..7e0ecd7e3 --- /dev/null +++ b/crates/socket-patch-core/src/formats/maven/repository_filter.rs @@ -0,0 +1,639 @@ +//! Maven Resolver's remote repository filtering, as hosted mode uses it to +//! keep Maven from asking a Socket repository for anything but the one +//! artifact it serves. Pure: text in, text out. The hosted rewriter and its +//! unwind both judge the files through here. +//! +//! A `` in a pom is asked, in declaration order and before +//! Maven Central, for every artifact and parent pom the local repository +//! does not hold yet. The resolver's `prefixes` filter restricts one +//! repository to the paths a file lists: +//! +//! * `/prefixes-.txt`, one path prefix per line, +//! `#` comments. Maven 4 (Resolver 2) reads a file only when its first +//! line is [`MAGIC`]; Maven 3.9 (Resolver 1.9) takes that line for a +//! comment. +//! * A repository with no file is not filtered, on every Maven: the filter +//! abstains. So a file named for a Socket repository restricts that +//! repository and no other. +//! * `` defaults to a directory in the local repository. The two +//! lines of [`config_args`] switch the filter on (it is off by default on +//! Maven 3.9, on from Maven 4) and move the basedir into the checkout. +//! +//! The basedir line has to name the checkout through a property, and no +//! property is right on every Maven ([`RootDirectory`], where the +//! measurements are). So the line takes the property the Trusted Checksums +//! directory takes, by the same rule ([`RootDirectory::for_maven`]): the +//! launcher's, which breaks no build, unless the project declares Maven 4. +//! +//! Measured with real Maven (3.6.3, 3.8.9, 3.9.0 to 3.9.4, 3.9.16, +//! 4.0.0-rc-7): from 3.9.2 on the Socket repository is asked for the +//! pinned version's jar and pom only, wherever the build is started +//! (`-f /pom.xml` from outside the project included). Before 3.9 +//! the properties mean nothing, and 3.9.0 / 3.9.1 interpolate neither +//! root-directory property, so the file is never found; both build as they +//! did, unfiltered. So does Maven 4 under the launcher's property, which it +//! does not interpolate: it filters under the session's. +//! +//! The basedir is one per build, not one per repository: a build that +//! switches the filter on from outside the checkout and keeps its own +//! files in the local repository's default directory stops reading them +//! once these lines are in `.mvn/maven.config`. Hence [`merge_config`] +//! writes nothing over a setting the checkout already holds, and the +//! directory is one only hosted mode uses, so its lines can be told from a +//! user's, respelled ([`heal_basedir`]) and taken out again. +//! +//! A file that does not list the pinned version's path FAILS the build +//! (`Prefix … NOT allowed from socket-patch-…`): it is written with the pin +//! it belongs to, from the same coordinates, or not at all. + +use super::declared_maven::{launcher_root, session_root, DeclaredMaven, Reads, RootDirectory}; +use super::{maven_config_line_properties, maven_config_properties}; + +// The directory, under the project's root directory, as a literal: the +// path and the two spellings of the line that names it cannot drift apart. +macro_rules! dir { + () => { + ".mvn/socket-patch" + }; +} +macro_rules! filter { + () => { + "aether.remoteRepositoryFilter.prefixes" + }; +} +// The two 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", filter!(), "=true"), + concat!("-D", filter!(), ".basedir=", $root!(), "/", dir!()), + ] + }; +} + +/// The directory, under the project root, that holds the filter files. +pub(crate) const DIR: &str = dir!(); + +const SWITCH_KEY: &str = filter!(); +pub(crate) const BASEDIR_KEY: &str = concat!(filter!(), ".basedir"); + +/// Where the directory line stands among the two. +const BASEDIR_AT: usize = 1; + +/// The first Maven release that reads the filter files from the checkout: +/// 3.9.0 and 3.9.1 interpolate neither root-directory property, and older +/// lines have no such filter. +const MIN_MAVEN: [u32; 3] = [3, 9, 2]; + +const FORMS: [RootDirectory; 2] = [RootDirectory::Launcher, RootDirectory::Session]; + +/// The directory setting's value under `form`. +pub(crate) const fn basedir_value(form: RootDirectory) -> &'static str { + match form { + RootDirectory::Launcher => concat!(launcher_root!(), "/", dir!()), + RootDirectory::Session => concat!(session_root!(), "/", dir!()), + } +} + +/// The form whose value is `value`. +fn basedir_of_value(value: &str) -> Option { + FORMS.into_iter().find(|form| basedir_value(*form) == value) +} + +/// The `.mvn/maven.config` lines hosted mode writes for a project whose +/// form is `form`, one argument each: the prefixes filter on, reading its +/// files from [`DIR`]. +pub(crate) fn config_args(form: RootDirectory) -> &'static [&'static str] { + match form { + RootDirectory::Launcher => config_args!(launcher_root), + RootDirectory::Session => config_args!(session_root), + } +} + +/// The first line of a prefix file Maven 4 accepts. +const MAGIC: &str = "## repository-prefixes/2.0"; + +/// The filter file of the repository `repository_id`, project-relative. +pub(crate) fn file_rel(repository_id: &str) -> String { + format!("{DIR}/prefixes-{repository_id}.txt") +} + +/// The Socket repository id whose filter the file `file_name` of [`DIR`] +/// is, when the name is one hosted mode writes: +/// `prefixes-socket-patch-.txt`. Any other name (a file of +/// the user's, another filter's) is none of hosted mode's. +pub(crate) fn owned(file_name: &str) -> Option<&str> { + let id = file_name.strip_prefix("prefixes-")?.strip_suffix(".txt")?; + crate::patch::redirect::generation::pin_name_uuid(id, false).map(|_| id) +} + +/// The Socket repository id whose filter the project-relative path `rel` +/// is: a file of [`DIR`] under a name hosted mode writes ([`owned`]). +pub(crate) fn owned_rel(rel: &str) -> Option<&str> { + rel.strip_prefix(DIR)?.strip_prefix('/').and_then(owned) +} + +/// The path prefix of one version of an artifact, as the maven2 layout +/// spells it: `///`. +pub(crate) fn prefix(group_id: &str, artifact_id: &str, version: &str) -> String { + format!( + "/{}", + crate::vendor::jvm::layout::version_dir(group_id, artifact_id, version) + ) +} + +/// The filter file that restricts `repository_id` to one version of one +/// artifact. Call only with coordinates that passed +/// [`crate::vendor::jvm::layout::safe_coordinates`]. +pub(crate) fn file_text( + repository_id: &str, + group_id: &str, + artifact_id: &str, + version: &str, +) -> String { + format!( + "{MAGIC}\n# Written by socket-patch: Maven asks the {repository_id} repository for this \ + path only.\n{}\n", + prefix(group_id, artifact_id, version) + ) +} + +/// Whether the filter file `text` lets its repository serve `prefix` on +/// every Maven that reads such a file: its first line is the header Maven 4 +/// requires, and one of its lines is the path. Read as Maven reads it, line +/// by line with the line ending off, so a file checked out with CRLF line +/// endings, or one someone added a comment or another path to, says the +/// same as the bytes hosted mode wrote. +pub(crate) fn lists(text: &str, prefix: &str) -> bool { + let mut lines = text.lines(); + lines.next() == Some(MAGIC) && lines.any(|line| line == prefix) +} + +/// What `.mvn/maven.config` needs for Maven to read the filter files. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Config { + /// Both settings are there, on and naming [`DIR`], in either spelling + /// of the directory ([`form`]). + InPlace, + /// Neither setting is there: the config with both lines appended. + Appended(String), + /// The checkout already configures the filter another way (why). + Conflict(String), +} + +/// The spelling of the directory under which `config` makes Maven read the +/// filter files of [`DIR`]: the filter on and its basedir that directory, +/// as Maven 3.9 and later read the file (one argument per line). `None` +/// when the config does not. +pub(crate) fn form(config: &str) -> Option { + let lines = maven_config_line_properties(config); + lines.get(SWITCH_KEY).filter(|on| *on == "true")?; + lines.get(BASEDIR_KEY).and_then(|dir| basedir_of_value(dir)) +} + +/// What the Maven the project declares (`maven`) makes of the filter as +/// `config` sets it: whether a Socket repository is filtered there. `None` +/// when the config does not point Maven at [`DIR`] at all ([`form`]). +pub(crate) fn read_by(config: &str, maven: &DeclaredMaven) -> Option { + form(config).map(|form| form.read_by(maven, MIN_MAVEN)) +} + +/// `existing` with the two lines of `form` appended, unless the checkout +/// already sets either property. +/// +/// The two settings in place, naming [`DIR`] in either spelling, are +/// hosted mode's own and no conflict: both spellings name the same +/// directory (what the project's Maven makes of the one in place is +/// [`read_by`]'s to say). A setting found in any spelling some Maven +/// reads, with any other value (or only one of the two), is the user's own +/// filter configuration: moving its basedir would stop Maven reading the +/// files they keep, so nothing is written and the Socket repository stays +/// unfiltered. +/// +/// The lines are appended in the file's own shape: a file that ends +/// without a line break still does, so [`strip_config`] gives back its +/// bytes. +pub(crate) fn merge_config(existing: &str, form: RootDirectory) -> Config { + if self::form(existing).is_some() { + return Config::InPlace; + } + let any = maven_config_properties(existing); + for key in [SWITCH_KEY, BASEDIR_KEY] { + if let Some(value) = any.get(key) { + return Config::Conflict(format!("-D{key}={value}")); + } + } + Config::Appended(super::append_config_args(existing, config_args(form), true)) +} + +/// Whether `text` (a `.mvn/jvm.config`, or any other argument list) names +/// one of the two properties: a JVM-level setting of the same filter, +/// which a `maven.config` line would override. +pub(crate) fn mentions_filter(text: &str) -> bool { + text.contains(SWITCH_KEY) +} + +/// A line of a config without its line ending: the argument it holds. +fn arg(line: &str) -> &str { + line.trim_end_matches(['\r', '\n']) +} + +/// `config` with the directory line spelled as `form`, wherever it stands +/// in the other spelling: that line is rewritten in place, every other +/// byte kept. `None` when there is nothing to change. +/// +/// The line is hosted mode's wherever it stands, with or without the +/// switch beside it: it names [`DIR`], which nothing else uses. (The +/// Trusted Checksums directory is one Maven's own documentation names, so +/// only the whole block is respelled there: +/// [`super::trusted_checksums::heal_basedir`].) +/// +/// This is how a project whose line names the directory through +/// `${session.rootDirectory}`, which 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: RootDirectory) -> Option { + let written = config_args(form.other())[BASEDIR_AT]; + // The cheap test first: almost no config holds the other spelling. + if !config.contains(written) { + return None; + } + let mut healed = false; + let mut out = String::with_capacity(config.len() + 32); + for line in config.split_inclusive('\n') { + let body = arg(line); + if body == written { + healed = true; + out.push_str(config_args(form)[BASEDIR_AT]); + out.push_str(&line[body.len()..]); + } else { + out.push_str(line); + } + } + healed.then_some(out) +} + +/// Whether `config` holds the directory line hosted mode writes, 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_line(config: &str) -> bool { + FORMS + .into_iter() + .any(|form| heal_basedir(config, form).is_some()) +} + +/// `config` without the lines hosted mode wrote ([`config_args`] in either +/// spelling, each a whole line): `None` when they are not there. A file +/// whose last line was one of them, with no line break after it, gets back +/// the ending it had before [`merge_config`] appended to it. +/// +/// What marks the pair as hosted mode's is the directory line: it names +/// [`DIR`], which nothing else uses. The switch on its own +/// (`…prefixes=true`) is a line anyone may have written, and +/// [`merge_config`] never adds it to a config that holds it: without the +/// directory line beside it, it is the user's and is left alone. +pub(crate) fn strip_config(config: &str) -> Option { + let names_dir = |line: &str| { + FORMS + .into_iter() + .any(|form| arg(line) == config_args(form)[BASEDIR_AT]) + }; + // (The switch is spelled alike under both forms.) + let is_ours = |line: &str| names_dir(line) || arg(line) == config_args!(launcher_root)[0]; + if !config.split_inclusive('\n').any(names_dir) { + return None; + } + let ended_on_ours = config + .split_inclusive('\n') + .next_back() + .is_some_and(|last| !last.ends_with('\n') && is_ours(last)); + let mut rest: String = config + .split_inclusive('\n') + .filter(|line| !is_ours(line)) + .collect(); + if ended_on_ours && rest.ends_with('\n') { + rest.pop(); + if rest.ends_with('\r') { + rest.pop(); + } + } + Some(rest) +} + +#[cfg(test)] +mod tests { + use super::RootDirectory::{Launcher, Session}; + use super::*; + + const ID: &str = "socket-patch-77777777-7777-7777-7777-777777777777"; + + /// The two lines under `form`, as one block. + fn block(form: RootDirectory) -> String { + config_args(form).join("\n") + } + + 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" + ) + } + + #[test] + fn the_file_names_its_repository_and_lists_one_version() { + let rel = file_rel(ID); + assert_eq!( + rel, + ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt" + ); + assert_eq!(owned(rel.rsplit('/').next().unwrap()), Some(ID)); + // Only the names hosted mode writes are its own. + for theirs in [ + "groupId-central.txt", + "prefixes-central.txt", + "prefixes-socket-patch-not-a-uuid.txt", + "prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt.bak", + ] { + assert_eq!(owned(theirs), None, "{theirs}"); + } + assert_eq!(owned_rel(&rel), Some(ID)); + for theirs in [ + ".mvn/socket-patch/prefixes-central.txt", + ".mvn/socket-patchy/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + ".mvn/socket-patch", + ] { + assert_eq!(owned_rel(theirs), None, "{theirs}"); + } + let text = file_text(ID, "org.slf4j", "slf4j-api", "1.7.36-socket.77777777"); + let mut lines = text.lines(); + // Maven 4 discards a file whose first line is anything else. + assert_eq!(lines.next(), Some("## repository-prefixes/2.0")); + let listed: Vec<&str> = lines.filter(|l| !l.starts_with('#')).collect(); + assert_eq!(listed, ["/org/slf4j/slf4j-api/1.7.36-socket.77777777"]); + assert!(text.ends_with('\n')); + } + + /// A file is judged by what Maven reads in it, not by its bytes: the + /// header first, and the pinned path on a line of its own. + #[test] + fn a_file_lists_a_path_whatever_its_line_endings_and_comments() { + let path = "/org/slf4j/slf4j-api/1.7.36-socket.77777777"; + let written = file_text(ID, "org.slf4j", "slf4j-api", "1.7.36-socket.77777777"); + assert!(lists(&written, path)); + for same in [ + written.replace('\n', "\r\n"), + written.trim_end().to_string(), + format!("{written}# kept for the audit\n"), + format!("{written}/com/example/other/1.0\n"), + format!("## repository-prefixes/2.0\n\n{path}\n"), + ] { + assert!(lists(&same, path), "{same:?}"); + } + for other in [ + String::new(), + // No header: Maven 4 discards the file. + format!("{path}\n"), + format!("# mine\n{written}"), + // Another version, a longer path, the path commented out. + written.replace("77777777", "88888888"), + written.replace(path, &format!("{path}/extra")), + written.replace(path, &format!("# {path}")), + written.replace(path, &format!("{path} ")), + ] { + assert!(!lists(&other, path), "{other:?}"); + } + } + + /// The directory is named through the property the project's Maven + /// reads, the one rule the Trusted Checksums directory follows. + #[test] + fn the_directory_line_takes_the_projects_root_directory_property() { + assert_eq!( + config_args(Launcher), + [ + "-Daether.remoteRepositoryFilter.prefixes=true", + "-Daether.remoteRepositoryFilter.prefixes.basedir=\ + ${maven.multiModuleProjectDirectory}/.mvn/socket-patch", + ] + ); + assert_eq!( + config_args(Session), + [ + "-Daether.remoteRepositoryFilter.prefixes=true", + "-Daether.remoteRepositoryFilter.prefixes.basedir=\ + ${session.rootDirectory}/.mvn/socket-patch", + ] + ); + for form in FORMS { + let value = basedir_value(form); + assert_eq!(value, format!("{}/{DIR}", form.property())); + assert_eq!(basedir_of_value(value), Some(form)); + assert!(config_args(form)[BASEDIR_AT].ends_with(value)); + // The form a project takes is the one its checksums take. + assert_eq!(self::form(&block(form)), Some(form)); + } + assert_eq!(basedir_of_value("${session.rootDirectory}/.mvn/rrf"), None); + } + + #[test] + fn the_lines_are_appended_once_in_the_shape_of_the_file() { + for form in FORMS { + let block = block(form); + assert_eq!( + merge_config("", form), + Config::Appended(format!("{block}\n")) + ); + assert_eq!( + merge_config("-B\n", form), + Config::Appended(format!("-B\n{block}\n")) + ); + assert_eq!( + merge_config("-B", form), + Config::Appended(format!("-B\n{block}")) + ); + let [switch, dir] = config_args(form) else { + panic!("two lines"); + }; + for written in [ + format!("{block}\n"), + format!("-B\n{block}"), + format!("{dir}\n-B\n{switch}\n"), + ] { + // In place whichever spelling this project would write: + // both name the one directory. + for wanted in FORMS { + assert_eq!(merge_config(&written, wanted), Config::InPlace, "{written}"); + } + } + } + } + + #[test] + fn a_filter_the_checkout_configures_is_never_written_over() { + for theirs in [ + // Switched on with the files left in the local repository. + "-Daether.remoteRepositoryFilter.prefixes=true\n", + // Another directory, the one Maven's own documentation names. + "-Daether.remoteRepositoryFilter.prefixes=true\n\ + -Daether.remoteRepositoryFilter.prefixes.basedir=${session.rootDirectory}/.mvn/rrf\n", + // Switched off. + "-Daether.remoteRepositoryFilter.prefixes=false\n", + // Only the directory. + "-Daether.remoteRepositoryFilter.prefixes.basedir=/srv/filters\n", + // The spelling Maven before 3.9 reads. + "-B -Daether.remoteRepositoryFilter.prefixes=true\n", + "--define aether.remoteRepositoryFilter.prefixes=true\n", + ] { + for form in FORMS { + assert!( + matches!(merge_config(theirs, form), Config::Conflict(_)), + "{theirs}" + ); + } + assert_eq!(self::form(theirs), None, "{theirs}"); + assert!(!holds_written_line(theirs), "{theirs}"); + } + // Another filter of the resolver is not this one. + let group = "-Daether.remoteRepositoryFilter.groupId=true\n"; + assert!(matches!(merge_config(group, Launcher), Config::Appended(_))); + assert!(mentions_filter( + "-Xmx2g -Daether.remoteRepositoryFilter.prefixes=true" + )); + assert!(!mentions_filter("-Xmx2g")); + } + + /// A line written under the other property is respelled in place, and + /// nothing else in the file moves. + #[test] + fn the_directory_line_is_healed_in_place_to_the_projects_form() { + for form in FORMS { + let other = form.other(); + for (before, after) in [ + (format!("{}\n", block(other)), format!("{}\n", block(form))), + // No final line break, CRLF, lines around it. + ( + format!("-B\r\n{}", block(other).replace('\n', "\r\n")), + format!("-B\r\n{}", block(form).replace('\n', "\r\n")), + ), + ( + format!("# mine\n{}\n-T1C\n", block(other)), + format!("# mine\n{}\n-T1C\n", block(form)), + ), + // The line alone (its switch since removed): the property + // it names is what stops a Maven from starting. + ( + format!("-B\n{}\n", config_args(other)[BASEDIR_AT]), + format!("-B\n{}\n", config_args(form)[BASEDIR_AT]), + ), + ] { + assert_eq!(heal_basedir(&before, form).as_deref(), Some(after.as_str())); + assert!(holds_written_line(&before) && holds_written_line(&after)); + // Healed once: the result is this form's own. + assert_eq!(heal_basedir(&after, form), None, "{after:?}"); + assert_eq!(heal_basedir(&before, other), None, "{before:?}"); + } + } + // A line that is not the one hosted mode writes stays as written: + // another directory, another spelling of the argument, a comment. + for theirs in [ + "-Daether.remoteRepositoryFilter.prefixes.basedir=${session.rootDirectory}/.mvn/rrf\n" + .to_string(), + format!(" {}\n", config_args(Session)[BASEDIR_AT]), + format!("# {}\n", config_args(Session)[BASEDIR_AT]), + format!("-B {}\n", config_args(Session)[BASEDIR_AT]), + String::new(), + ] { + assert_eq!(heal_basedir(&theirs, Launcher), None, "{theirs:?}"); + assert!(!holds_written_line(&theirs), "{theirs:?}"); + } + } + + /// Whether a Socket repository is filtered is judged for the Maven the + /// project declares, by the rule the Trusted Checksums pin is judged + /// by, with this filter's own first release. + #[test] + fn the_filter_is_judged_for_the_maven_the_project_declares() { + let declares = |wrapper: Option| DeclaredMaven::of(wrapper.as_deref(), None); + let none = declares(None); + let maven_4 = declares(Some(wrapper("4.0.0-rc-7"))); + let reads = |form, maven: &DeclaredMaven| read_by(&format!("{}\n", block(form)), maven); + // No Maven declared: the launcher's form filters on Maven 3 only. + assert_eq!(reads(Launcher, &none), Some(Reads::Maven3Only)); + assert_eq!(reads(Session, &none), Some(Reads::Read)); + // The first release that finds the directory is 3.9.2. + for (version, read) in [("3.8.9", false), ("3.9.1", false), ("3.9.2", true)] { + let maven = declares(Some(wrapper(version))); + let expected = if read { + Reads::Read + } else { + Reads::TooOld(version.to_string()) + }; + assert_eq!(reads(Launcher, &maven), Some(expected), "{version}"); + } + // Maven 4 reads the session's property only. + assert_eq!(reads(Launcher, &maven_4), Some(Reads::UnreadByMaven4)); + assert_eq!(reads(Session, &maven_4), Some(Reads::Read)); + // A config that does not point Maven at the directory says nothing. + for config in [ + "", + "-Daether.remoteRepositoryFilter.prefixes=true\n", + "-Daether.remoteRepositoryFilter.prefixes=false\n\ + -Daether.remoteRepositoryFilter.prefixes.basedir=\ + ${session.rootDirectory}/.mvn/socket-patch\n", + ] { + assert_eq!(read_by(config, &maven_4), None, "{config}"); + } + } + + #[test] + fn stripping_gives_back_the_bytes_the_lines_were_appended_to() { + for form in FORMS { + for original in [ + "", + "-B\n", + "-B", + "-B\r\n-T1C\r\n", + "-B\r\n-T1C", + "# note\n\n-B\n", + ] { + let Config::Appended(written) = merge_config(original, form) else { + panic!("{original:?} takes the lines"); + }; + assert_eq!( + strip_config(&written).as_deref(), + Some(original), + "{original:?}" + ); + assert_eq!(strip_config(original), None, "{original:?}"); + } + // Lines the user added after ours stay, in place. + let block = block(form); + assert_eq!( + strip_config(&format!("-B\n{block}\n-T1C\n")).as_deref(), + Some("-B\n-T1C\n") + ); + // The directory line alone (its switch since removed) still + // goes. + assert_eq!( + strip_config(&format!("-B\n{}\n", config_args(form)[BASEDIR_AT])).as_deref(), + Some("-B\n") + ); + } + // A line that only resembles ours is not ours. + let other = "-Daether.remoteRepositoryFilter.prefixes=true # mine\n"; + assert_eq!(strip_config(other), None); + // The switch alone is the user's own (hosted mode writes it only + // together with its directory, and never into a config that holds + // it): a rollback must not take it. + let theirs = format!("-B\n{}\n", config_args(Launcher)[0]); + assert!(matches!( + merge_config(&theirs, Launcher), + Config::Conflict(_) + )); + assert_eq!(strip_config(&theirs), None); + } +} 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 fdb0f9fc4..e994e2ead 100644 --- a/crates/socket-patch-core/src/formats/maven/trusted_checksums.rs +++ b/crates/socket-patch-core/src/formats/maven/trusted_checksums.rs @@ -15,7 +15,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use super::declared_maven::{launcher_root, release, session_root, DeclaredMaven}; +use super::declared_maven::{launcher_root, session_root, DeclaredMaven, Reads}; use super::maven_config_line_properties; use crate::utils::digest::{is_hex64_lower, sha256_hex}; @@ -319,19 +319,11 @@ pub(crate) enum Enforcement { /// 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()); - } - } - if form.unread_by(maven) { - Enforcement::UnreadByMaven4 - } else if form == Basedir::Launcher && maven.release().is_none() { - Enforcement::Maven3Only - } else { - Enforcement::Enforced + match form.read_by(maven, MIN_MAVEN) { + Reads::TooOld(version) => Enforcement::TooOld(version), + Reads::UnreadByMaven4 => Enforcement::UnreadByMaven4, + Reads::Maven3Only => Enforcement::Maven3Only, + Reads::Read => Enforcement::Enforced, } } diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 91c343d39..7728fec5d 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -869,6 +869,77 @@ fn read_maven_mirrors( } } +/// The variables of the environment a Maven build takes JVM or Maven +/// arguments from. Measured on Maven 3.9.9 and 4.0.0-rc-7: a +/// `-Daether.remoteRepositoryFilter.prefixes…` in any of them configures +/// the repository filter of the build. +const MAVEN_ARGUMENT_VARIABLES: [&str; 4] = [ + "MAVEN_OPTS", + "MAVEN_ARGS", + "JAVA_TOOL_OPTIONS", + "JDK_JAVA_OPTIONS", +]; + +/// What the Maven rewriter weighs for the repository filter, beside the +/// poms: the filter files hosted mode keeps under `.mvn/socket-patch/`, one +/// per patch (one already there is not written again), Maven's JVM +/// arguments (a filter set there is the user's, which the rewriter leaves +/// alone), and what it cannot see for itself +/// ([`MAVEN_FILTER_KEY`](crate::patch::redirect::MAVEN_FILTER_KEY)): whether +/// the directory holds anything else, whether the environment of the +/// machine that scans configures the filter, and whether +/// `.mvn/maven.config` can take a write. Advisory, like the module poms: +/// the filter is an extra, and nothing here keeps a pin from landing. +async fn read_maven_filter( + view: &ProjectView<'_>, + unreadable: &BTreeSet, + env: &(dyn crate::gradle::Env + Sync), + out: &mut CandidateFiles, +) { + use crate::formats::maven::repository_filter; + use crate::patch::redirect::{ + hosted_maven_filter_dir, maven_config_writable, MavenFilterAround, MAVEN_FILTER_KEY, + MVN_CONFIG, MVN_JVM_CONFIG, + }; + let dir = hosted_maven_filter_dir(view).await; + for rel in std::iter::once(MVN_JVM_CONFIG.to_string()).chain(dir.owned.iter().cloned()) { + if out.files.contains_key(&rel) { + continue; + } + if let Some(text) = read_advisory(view, unreadable, &rel).await { + out.files.insert(rel, text); + } + } + let around = MavenFilterAround { + keeps_lines: dir.others || dir.unlistable, + // Only a machine has an environment (a memory view has none). + env: view.disk_root().and_then(|_| { + MAVEN_ARGUMENT_VARIABLES + .iter() + .find(|name| { + env.var(name) + .is_some_and(|value| repository_filter::mentions_filter(&value)) + }) + .map(|name| name.to_string()) + }), + config_unwritable: match view.disk_root() { + // A config that is not there yet is created, its directory + // with it; one that is there is replaced where it stands. + Some(root) => { + let there = tokio::fs::symlink_metadata(root.join(".mvn")).await.is_ok(); + there && !maven_config_writable(root).await + } + None => view.is_symlink(MVN_CONFIG), + }, + occupied: dir.occupied, + }; + if around != MavenFilterAround::default() { + if let Ok(json) = serde_json::to_string(&around) { + out.files.insert(MAVEN_FILTER_KEY.to_string(), json); + } + } +} + /// An in-memory project's Go files as the hosted engine reads them /// ([`read_advisory`]: a link or an entry without content is unreadable, /// but still exists). @@ -1001,23 +1072,23 @@ 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 +/// wrote: `None` unless that file holds lines some project is healed out +/// of (the Trusted Checksums block, the repository filter's directory +/// line: [`crate::formats::maven::holds_respellable_lines`]), 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::formats::maven::holds_respellable_lines; 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)?) { + if !holds_respellable_lines(out.files.get(MVN_CONFIG)?) { return None; } for rel in [MVN_WRAPPER_PROPERTIES, "pom.xml"] { @@ -1217,6 +1288,7 @@ pub async fn read_candidate_files_in( // the poms of the modules that select it. if candidates.iter().any(|c| c.dep.ecosystem == "maven") { read_maven_reactor(view, unreadable, &mut out).await; + read_maven_filter(view, unreadable, env, &mut out).await; read_maven_mirrors(view, env, &mut out); } @@ -6304,36 +6376,72 @@ snapshots: } /// 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. + /// `.mvn/maven.config` holds lines to heal (the Trusted Checksums + /// block, the repository filter's directory line), and then heals + /// them: on disk and in memory alike. #[tokio::test] async fn a_run_with_nothing_to_redirect_heals_the_maven_config() { + use crate::formats::maven::repository_filter; 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 [ + let filter_lines = |form| format!("{}\n", repository_filter::config_args(form).join("\n")); + let checksums = "redirect_maven_trusted_checksums_maven3_only"; + let filter = "redirect_maven_repository_filter_maven3_only"; + // (the config, a Maven 4 wrapper, what the heal leaves, what it + // says it traded away: only a heal that takes the session's + // property out of a project that declares no Maven trades anything) + let cases: [(String, bool, Option, &[&str]); 11] = [ ( checksums_block(Session), false, Some(checksums_block(Launcher)), + &[checksums], ), ( checksums_block(Launcher), true, Some(checksums_block(Session)), + &[], ), ( format!("-T4\n{}", checksums_block(Session)), false, Some(format!("-T4\n{}", checksums_block(Launcher))), + &[checksums], ), - // 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), - ] { + // The filter's directory line on its own, and beside the block. + ( + filter_lines(Session), + false, + Some(filter_lines(Launcher)), + &[filter], + ), + ( + filter_lines(Launcher), + true, + Some(filter_lines(Session)), + &[], + ), + ( + format!("{}{}", checksums_block(Session), filter_lines(Session)), + false, + Some(format!( + "{}{}", + checksums_block(Launcher), + filter_lines(Launcher) + )), + &[checksums, filter], + ), + // This project's own spelling, or no such line: nothing to do. + (checksums_block(Launcher), false, None, &[]), + (checksums_block(Session), true, None, &[]), + (filter_lines(Launcher), false, None, &[]), + (filter_lines(Session), true, None, &[]), + ("-T4\n".to_string(), false, None, &[]), + ]; + for (config, maven_4, healed, trade) in cases { let tmp = tempfile::tempdir().unwrap(); let mut memory = MemoryProject::new(); let mut put = |rel: &str, text: &str| { @@ -6376,13 +6484,6 @@ snapshots: .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. @@ -6685,6 +6786,202 @@ snapshots: assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); } + /// A pin that lands writes the filter file of its Socket repository, + /// and the engine reads what the rewriter weighs for it: the filter + /// files the checkout already holds (one whose repository goes is + /// retired, none is written twice) and Maven's JVM arguments (a + /// prefix filter set there is the user's, and is left to them). On + /// disk and in memory alike. + #[tokio::test] + async fn the_maven_repository_filter_is_written_with_what_the_checkout_holds() { + use crate::formats::maven::repository_filter::file_rel; + let pom = "\n 4.0.0\n x\n y\n 1\n \n \n com.socketfixture\n victim\n 1.10.0\n \n \n\n"; + let filter = file_rel(&format!("socket-patch-{GRADLE_UUID}")); + let earlier = file_rel("socket-patch-11111111-2222-4333-8444-555555555555"); + let jvm = crate::patch::redirect::MVN_JVM_CONFIG; + let check = |read: &CandidateFiles, done: &Rewritten, theirs: bool| { + let files = &done.rewrite.files; + assert!(files["pom.xml"].contains("1.10.0-socket.4d5e6f70")); + assert_eq!(read.files.contains_key(jvm), theirs); + assert_eq!( + files.get(&filter).and_then(|text| text.lines().last()), + (!theirs).then_some("/com/socketfixture/victim/1.10.0-socket.4d5e6f70"), + "{:?}", + done.rewrite.warnings + ); + assert_eq!( + done.rewrite + .warnings + .iter() + .any(|w| w.code == "redirect_maven_repository_filter_conflict"), + theirs + ); + // A file for a repository no pom declares is read, and left. + assert!(read.files.contains_key(&earlier), "{:?}", read.files.keys()); + assert!(!files.contains_key(&earlier)); + }; + for theirs in [false, true] { + let mut p = MemoryProject::new(); + p.insert_text("pom.xml", pom); + p.insert_text(&earlier, ""); + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join("pom.xml"), pom).unwrap(); + std::fs::create_dir_all(tmp.path().join(".mvn/socket-patch")).unwrap(); + std::fs::write(tmp.path().join(&earlier), "").unwrap(); + if theirs { + let args = "-Xmx1g -Daether.remoteRepositoryFilter.prefixes=true\n"; + p.insert_text(jvm, args); + std::fs::write(tmp.path().join(jvm), args).unwrap(); + } + for view in [ProjectView::Memory(&p), ProjectView::Disk(tmp.path())] { + let (read, done) = gradle_rewrite_in(&view).await; + check(&read, &done, theirs); + } + } + } + + /// The repository filter is an extra: nothing around it keeps a pin + /// from landing or refuses a run. The engine tells the rewriter what it + /// cannot see for itself, and the pin lands without the filter where + /// the filter cannot be had: + /// + /// - `.mvn/maven.config` is a symbolic link (a write would replace it, + /// and the guard refuses the whole run for one), here to a file that + /// already holds the checksum settings, so the filter's two lines + /// are the only write it would take; + /// - the environment of the machine that scans configures the filter; + /// - a link stands where the pin's filter file would go. + #[cfg(unix)] + #[tokio::test] + async fn the_maven_filter_never_keeps_a_pin_from_landing() { + use crate::formats::maven::repository_filter::file_rel; + use crate::formats::maven::trusted_checksums::Basedir::Launcher; + use crate::patch::redirect::{MavenFilterAround, MAVEN_FILTER_KEY, MVN_CONFIG}; + let pom = "\n 4.0.0\n x\n y\n 1\n \n \n com.socketfixture\n victim\n 1.10.0\n \n \n\n"; + let filter = file_rel(&format!("socket-patch-{GRADLE_UUID}")); + let candidates = vec![gradle_candidate()]; + let around = |read: &CandidateFiles| -> MavenFilterAround { + read.files + .get(MAVEN_FILTER_KEY) + .map(|json| serde_json::from_str(json).unwrap()) + .unwrap_or_default() + }; + let codes = |done: &Rewritten| -> Vec { + done.rewrite + .warnings + .iter() + .map(|w| w.code.clone()) + .collect() + }; + let landed_unfiltered = |view: &ProjectView<'_>, done: &Rewritten, why: &str| { + let files = &done.rewrite.files; + assert!(files["pom.xml"].contains("1.10.0-socket.4d5e6f70"), "{why}"); + assert!(!files.contains_key(&filter), "{why}: {:?}", files.keys()); + assert!( + !files + .get(MVN_CONFIG) + .is_some_and(|config| config.contains(".mvn/socket-patch")), + "{why}" + ); + assert!( + guard(view, done, &candidates).is_none(), + "{why}: the run is not refused" + ); + }; + let project = || { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join("pom.xml"), pom).unwrap(); + std::fs::create_dir_all(tmp.path().join(".mvn")).unwrap(); + tmp + }; + + // Control: nothing to say of the surroundings, and the filter is + // written with the pin. + let tmp = project(); + let view = ProjectView::Disk(tmp.path()); + let (read, done) = gradle_rewrite_in(&view).await; + assert_eq!(around(&read), MavenFilterAround::default()); + assert!(done.rewrite.files.contains_key(&filter)); + assert!(done.rewrite.files[MVN_CONFIG].contains(".mvn/socket-patch")); + + // A linked config. + let tmp = project(); + std::fs::create_dir_all(tmp.path().join("ci")).unwrap(); + std::fs::write( + tmp.path().join("ci/maven.config"), + checksums_block(Launcher), + ) + .unwrap(); + std::os::unix::fs::symlink("../ci/maven.config", tmp.path().join(MVN_CONFIG)).unwrap(); + let view = ProjectView::Disk(tmp.path()); + let (read, done) = gradle_rewrite_in(&view).await; + assert!(around(&read).config_unwritable); + landed_unfiltered(&view, &done, "a linked config"); + assert!(!done.rewrite.files.contains_key(MVN_CONFIG)); + assert!(!done.rewritten.iter().any(|rel| rel == MVN_CONFIG)); + assert_eq!(codes(&done), ["redirect_maven_repository_filter_skipped"]); + + // The filter named in the environment of the machine that scans. + let tmp = project(); + let view = ProjectView::Disk(tmp.path()); + let env = BTreeMap::from([( + "MAVEN_OPTS".to_string(), + "-Xmx1g -Daether.remoteRepositoryFilter.prefixes=true".to_string(), + )]); + let (read, done) = gradle_rewrite_with(&view, &env).await; + assert_eq!(around(&read).env.as_deref(), Some("MAVEN_OPTS")); + landed_unfiltered(&view, &done, "the environment"); + let conflict = done + .rewrite + .warnings + .iter() + .find(|w| w.code == "redirect_maven_repository_filter_conflict") + .expect("the conflict is said"); + assert!( + conflict.detail.contains("MAVEN_OPTS"), + "{}", + conflict.detail + ); + // (A project held in memory has no machine, and so no environment.) + let mut memory = MemoryProject::new(); + memory.insert_text("pom.xml", pom); + let (read, done) = gradle_rewrite_with(&ProjectView::Memory(&memory), &env).await; + assert_eq!(around(&read), MavenFilterAround::default()); + assert!(done.rewrite.files.contains_key(&filter)); + + // A file of the user's in the directory, and a link where this + // pin's own file would go: the link is not read and not written + // through, and the directory is known to hold more than ours. + let tmp = project(); + std::fs::create_dir_all(tmp.path().join(".mvn/socket-patch")).unwrap(); + std::fs::write( + tmp.path().join(".mvn/socket-patch/prefixes-central.txt"), + "## repository-prefixes/2.0\n/org\n", + ) + .unwrap(); + std::fs::write(tmp.path().join("elsewhere.txt"), "/org\n").unwrap(); + std::os::unix::fs::symlink("../../elsewhere.txt", tmp.path().join(&filter)).unwrap(); + let view = ProjectView::Disk(tmp.path()); + let (read, done) = gradle_rewrite_in(&view).await; + let seen = around(&read); + assert!(seen.keeps_lines); + assert_eq!(seen.occupied, [filter.clone()]); + assert!(!read.files.contains_key(&filter), "{:?}", read.files.keys()); + let files = &done.rewrite.files; + assert!(files["pom.xml"].contains("1.10.0-socket.4d5e6f70")); + assert!(!files.contains_key(&filter), "{:?}", files.keys()); + assert!(guard(&view, &done, &candidates).is_none()); + assert!( + codes(&done).contains(&"redirect_maven_repository_filter_skipped".to_string()), + "{:?}", + done.rewrite.warnings + ); + assert_eq!( + std::fs::read_to_string(tmp.path().join("elsewhere.txt")).unwrap(), + "/org\n" + ); + } + /// On disk the engine reads the mirrors of the Maven settings the /// build would be started with, and a project whose Socket repository /// one of them would take over is left alone: nothing written, nothing diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 78a61276f..995756103 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -71,7 +71,7 @@ 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::declared_maven::DeclaredMaven; +use crate::formats::maven::declared_maven::{DeclaredMaven, Reads, RootDirectory}; use crate::formats::maven::trusted_checksums; #[cfg(test)] use crate::formats::maven::trusted_checksums::CONFIG_ARGS as MVN_CONFIG_ARGS; @@ -9063,6 +9063,45 @@ pub(crate) const MVN_CHECKSUMS: &str = ".mvn/checksums/checksums.sha256"; /// `distributionUrl` names the Maven release the project builds with, so the /// rewriter can tell when the Trusted Checksums files it writes are inert. pub(crate) const MVN_WRAPPER_PROPERTIES: &str = ".mvn/wrapper/maven-wrapper.properties"; +/// Maven's JVM arguments. Read only, never edited: a resolver filter set +/// there is the user's, and the lines hosted mode adds would override it. +pub(crate) const MVN_JVM_CONFIG: &str = ".mvn/jvm.config"; +/// Engine-supplied input: what the rewriter cannot see of the repository +/// filter's surroundings, as the JSON of [`MavenFilterAround`]. Absent +/// when there is nothing to say. +pub const MAVEN_FILTER_KEY: &str = ""; + +/// What surrounds a project's repository filter beyond the files the +/// rewriter is handed. The filter is an extra: none of this ever keeps a +/// pin from landing. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MavenFilterAround { + /// The filter directory holds something that is not hosted mode's own + /// file (a prefix file of the user's, a subdirectory, a link), or could + /// not be listed. The two resolver lines are then never taken out: they + /// may be what makes Maven read that file, as on a rollback. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub keeps_lines: bool, + /// The variable of the scanning machine's environment that names the + /// `prefixes` filter (`MAVEN_OPTS`, `MAVEN_ARGS`, `JAVA_TOOL_OPTIONS`, + /// `JDK_JAVA_OPTIONS`: Maven 3.9.9 and 4.0.0-rc-7 honour the property + /// in each). Builds started there configure the filter themselves, and + /// the lines hosted mode adds would move the directory their files are + /// read from: a conflict, like a setting in `.mvn/jvm.config`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub env: Option, + /// `.mvn/maven.config` cannot take a write (it is a symbolic link, or + /// its directory does not take the write). The two resolver lines are + /// then not added, and not taken out. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub config_unwritable: bool, + /// The paths in the filter directory that carry a name hosted mode + /// writes and are not regular files (a link, a directory). No filter + /// file is written there: a write through a link would replace it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub occupied: Vec, +} /// Engine-supplied input: the `settings.xml` mirrors Maven is configured /// with on the machine that scans, as the JSON of /// [`settings_mirror_sets`](crate::crawlers::maven_crawler::settings_mirror_sets). @@ -9270,30 +9309,32 @@ fn rewrite_maven_poms( .iter() .filter(|o| o.ecosystem == "maven") .collect(); - // Nothing to redirect for Maven and no block hosted mode wrote to + // Nothing to redirect for Maven and no line 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)); + .is_some_and(|config| crate::formats::maven::holds_respellable_lines(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. + // names the two directories hosted mode keeps in the checkout (the + // Trusted Checksums' and the repository filter's): through the + // property 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 + // First, and whatever this run redirects: the lines an earlier run or + // an earlier release wrote in the other spelling are rewritten to this + // project's. Such a 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)) + .then(|| heal_mvn_config(files, &declared, result)) .flatten(); if maven.is_empty() { return; @@ -9356,6 +9397,14 @@ fn rewrite_maven_poms( // Trusted-checksum paths of superseded generations' suffixed artifacts: // their pins moved to the new generation this run, so the entries go. let mut checksum_drops: Vec = vec![]; + // The repository filter files of the pins that land this run. + let mut scope = MavenScope { + around: files + .get(MAVEN_FILTER_KEY) + .and_then(|json| serde_json::from_str(json).ok()) + .unwrap_or_default(), + ..MavenScope::default() + }; let gradle_build_present = gradle::gradle_build_present(files); let mut warned_no_pom = false; // Local-repo paths of the suffixed jars this run's Trusted Checksums pin @@ -9469,33 +9518,27 @@ fn rewrite_maven_poms( let (Some(run), Some(suffixed)) = (planned, suffixed_version.as_deref()) else { continue; }; - if checksum_hashes.is_some() && run.wired { - pinned_jar_paths.push(crate::vendor::jvm::layout::artifact_path( - &group_id, - &artifact_id, - suffixed, - None, - "jar", - )); - } - checksum_drops.extend(run.drops); - if run.landed { - pin_maven_checksums( - files, - (&group_id, &artifact_id, suffixed), - checksum_hashes.as_ref(), - bad_checksum_hashes, - &mut MavenChecksumSettings { - config: &mut mvn_config, - changed: &mut mvn_config_changed, - basedir, - declared: &declared, - conflicts: &mut mvn_conflicts, - }, - &mut checksum_entries, - result, - ); - } + let still_declared = |id: &str| planner.declares(id, pom_text); + settle_maven_plan( + files, + run, + &still_declared, + &repo_id, + (&group_id, &artifact_id, suffixed), + (checksum_hashes.as_ref(), bad_checksum_hashes), + &mut MavenChecksumSettings { + config: &mut mvn_config, + changed: &mut mvn_config_changed, + basedir, + declared: &declared, + conflicts: &mut mvn_conflicts, + }, + &mut checksum_entries, + &mut checksum_drops, + &mut pinned_jar_paths, + &mut scope, + result, + ); continue; } // A `` pin makes every occurrence of the GA @@ -9857,33 +9900,28 @@ fn rewrite_maven_poms( let Some(run) = planned else { continue; }; - if checksum_hashes.is_some() && run.wired { - pinned_jar_paths.push(crate::vendor::jvm::layout::artifact_path( - &group_id, - &artifact_id, - &suffixed_version, - None, - "jar", - )); - } - checksum_drops.extend(run.drops); - if run.landed { - pin_maven_checksums( - files, - (&group_id, &artifact_id, &suffixed_version), - checksum_hashes.as_ref(), - bad_checksum_hashes, - &mut MavenChecksumSettings { - config: &mut mvn_config, - changed: &mut mvn_config_changed, - basedir, - declared: &declared, - conflicts: &mut mvn_conflicts, - }, - &mut checksum_entries, - result, - ); - } + let root = pom.as_deref().unwrap_or_default(); + let still_declared = |id: &str| planner.declares(id, root); + settle_maven_plan( + files, + run, + &still_declared, + &repo_id, + (&group_id, &artifact_id, &suffixed_version), + (checksum_hashes.as_ref(), bad_checksum_hashes), + &mut MavenChecksumSettings { + config: &mut mvn_config, + changed: &mut mvn_config_changed, + basedir, + declared: &declared, + conflicts: &mut mvn_conflicts, + }, + &mut checksum_entries, + &mut checksum_drops, + &mut pinned_jar_paths, + &mut scope, + result, + ); continue; } @@ -10029,6 +10067,7 @@ fn rewrite_maven_poms( let old_id = generation::hosted_pin_name(&old_uuid); if idx.remove_repository(pom_text, &old_id) { pom_changed = true; + scope.retire(files, &old_id, result); result.edits.push(FileEdit { path: "pom.xml".into(), kind: "redirect_maven_superseded_repository_removed".into(), @@ -10070,8 +10109,15 @@ fn rewrite_maven_poms( // A pin landed this run: inject the repository (idempotent via the // guard) and emit trusted checksums. When the pin was already present // from a prior run, `pin_landed` stays false and both are skipped, - // keeping a re-run edit-free. + // keeping a re-run edit-free. (A filter file that is there and does + // not list the pinned version is mended all the same: it would stop + // Maven from resolving the pin.) if !pin_landed { + if versioned.iter().any(|(_, _, v)| *v == suffixed_version) + && idx.has_repository(&repo_id) + { + scope.in_place(files, &repo_id); + } continue; } if !idx.has_repository(&repo_id) { @@ -10102,14 +10148,56 @@ fn rewrite_maven_poms( &mut checksum_entries, result, ); + scope.repository( + files, + &repo_id, + (&group_id, &artifact_id, &suffixed_version), + (&mut mvn_config, &mut mvn_config_changed, basedir), + result, + ); } + // A run that took the last Socket repository with a filter file out of + // the poms takes the two resolver lines out as well: no later run would + // (nothing is left to roll back), and they would name a directory whose + // files no repository reads. Asked of the poms as this run leaves them. + // The lines stay where something else in the directory may need them, + // as on a rollback, and where the config cannot take the write. + let strips = scope.retired + && !scope.around.keeps_lines + && !scope.around.config_unwritable + && scope.serves_none(files, &|id| { + planner.declares(id, pom.as_deref().unwrap_or_default()) + }); if pom_changed { if let Some(p) = pom { result.files.insert("pom.xml".into(), p); } } result.files.extend(planner.module_poms); + if strips { + if let Some(rest) = crate::formats::maven::repository_filter::strip_config(&mvn_config) { + mvn_config = rest; + mvn_config_changed = true; + // A directory line this run respelled first went out with the + // rest: the run reports the removal, not a respelling too. + let respelled = MavenConfigLines::Filter; + result.edits.retain(|e| { + !(e.path == MVN_CONFIG && e.key.as_deref() == Some(respelled.heal_key())) + }); + result.warnings.retain(|w| w.code != respelled.scan_trade()); + result.edits.push(FileEdit { + path: MVN_CONFIG.into(), + kind: "redirect_maven_config".into(), + action: "removed".into(), + key: Some("repositoryFilter".into()), + original: None, + new: None, + }); + } + } + let filter_files = scope.pinned; + result.files.extend(scope.files); if mvn_config_changed { result.files.insert(MVN_CONFIG.into(), mvn_config); } @@ -10154,12 +10242,29 @@ fn rewrite_maven_poms( } None => trusted_checksums::Enforcement::Off, }; + // The same for the repository filter: its files are written regardless + // (a later wrapper upgrade reads them, and a filter Maven does not read + // restricts nothing), but a project whose declared Maven does not read + // them must not take its Socket repositories for filtered. + let filtered_here = filter_files + .iter() + .any(|rel| final_text(rel).is_some_and(|text| !text.is_empty())); + let unfiltered = final_text(MVN_CONFIG) + .filter(|_| filtered_here) + .and_then(|config| crate::formats::maven::repository_filter::read_by(config, &declared)) + .and_then(|reads| unfiltered_detail(&reads, &declared)); if let Some(detail) = unenforced_detail(&enforcement, &declared) { result.warnings.push(RewriteWarning { code: "redirect_maven_trusted_checksums_unenforced".into(), detail, }); } + if let Some(detail) = unfiltered { + result.warnings.push(RewriteWarning { + code: "redirect_maven_repository_filter_unread".into(), + detail, + }); + } } /// The `.mvn/maven.config` of one run as the Trusted Checksums settings @@ -10250,6 +10355,394 @@ fn pin_maven_checksums( } } +/// The repository filter of one run ([`repository_filter`]). +#[derive(Default)] +struct MavenScope { + /// What the engine saw around the filter ([`MAVEN_FILTER_KEY`]). + around: MavenFilterAround, + /// The filter files to write, by project-relative path. + files: BTreeMap, + /// A Socket repository whose filter file the checkout holds went out + /// of the poms this run. + retired: bool, + /// The filter files of the pins this run wired or found wired, by + /// project-relative path: the ones the run answers for when it says + /// whether the project's Maven reads the filter. + pinned: std::collections::BTreeSet, + /// The run already said that the lines were added. + said_enabled: bool, + /// The run already said that the filter was skipped. + said_skipped: bool, +} + +/// The edit kind of a filter file. +const MAVEN_FILTER_EDIT: &str = "redirect_maven_repository_filter"; + +impl MavenScope { + /// The file as this run leaves it: what is pending for it, else what + /// the checkout holds. + fn live<'f>(&'f self, files: &'f BTreeMap, rel: &str) -> Option<&'f String> { + self.files.get(rel).or_else(|| files.get(rel)) + } + + /// Keep Maven from asking the Socket repository `repo_id` for anything + /// but the suffixed version of the artifact it serves, for a dep whose + /// pin landed this run: the two resolver lines in `.mvn/maven.config`, + /// which name the filter's directory through the property this project + /// takes (`form`, the one its Trusted Checksums directory takes), and + /// the repository's prefix file. A pin an earlier run wrote gets no + /// new file, like its Trusted Checksums, so a re-run stays edit-free. + /// + /// The file lists the one path the pin resolves, from the coordinates + /// the pin was written with: a file that listed anything else would + /// fail the build. One that is there and lists the path already is + /// left as it is, whatever its line endings and comments. + /// + /// The filter is an extra, and the pin lands without it wherever it + /// cannot be had: where the filter is configured already (in the + /// checkout, or in the environment of the machine that scans), where + /// `.mvn/maven.config` cannot take the two lines, and for coordinates a + /// path or a line cannot hold. The Socket repository then stays + /// unfiltered, as it was, and the run says so. + fn repository( + &mut self, + files: &BTreeMap, + repo_id: &str, + (group_id, artifact_id, suffixed_version): (&str, &str, &str), + (mvn_config, mvn_config_changed, form): (&mut String, &mut bool, RootDirectory), + result: &mut RewriteResult, + ) { + use crate::formats::maven::repository_filter::{self, Config}; + if generation::pin_name_uuid(repo_id, false).is_none() + || !crate::vendor::jvm::layout::safe_coordinates( + group_id, + artifact_id, + suffixed_version, + ) + { + return; + } + let rel = repository_filter::file_rel(repo_id); + // Something that is no file of hosted mode's stands where this + // repository's would go. + if self.around.occupied.contains(&rel) { + result.warnings.push(RewriteWarning { + code: "redirect_maven_repository_filter_skipped".into(), + detail: format!( + "{group_id}:{artifact_id}: {rel} is not a regular file (a link or a \ + directory stands there), so no filter file was written for the {repo_id} \ + repository. The pin landed all the same: Maven asks that repository for \ + every artifact its local repository does not hold, not for the patched \ + version only" + ), + }); + return; + } + // A setting outside `maven.config` is the user's as well: the lines + // would move the directory their own files are read from. + let outside = if files + .get(MVN_JVM_CONFIG) + .is_some_and(|jvm| repository_filter::mentions_filter(jvm)) + { + Some(format!("a setting in {MVN_JVM_CONFIG}")) + } else { + self.around + .env + .as_ref() + .map(|var| format!("a setting in the {var} environment variable of this machine")) + }; + let merged = match outside { + Some(theirs) => Config::Conflict(theirs), + None => repository_filter::merge_config(mvn_config, form), + }; + let listed = repository_filter::prefix(group_id, artifact_id, suffixed_version); + match merged { + // Said for each patch: each has a repository and a path of its + // own to list. + Config::Conflict(theirs) => { + result.warnings.push(RewriteWarning { + code: "redirect_maven_repository_filter_conflict".into(), + detail: format!( + "{group_id}:{artifact_id}: Maven's repository prefix filter is already \ + configured ({theirs}); leaving it as-is, so the {repo_id} repository is \ + not filtered: Maven asks it for every artifact the local repository \ + does not hold, though it serves only {suffixed_version}. To filter it, \ + list {listed} in a prefixes-{repo_id}.txt file of that filter's \ + directory" + ), + }); + return; + } + // The lines are a write to a file that cannot take one. The + // pin has landed; it stays, unfiltered. + Config::Appended(_) if self.around.config_unwritable => { + if !std::mem::replace(&mut self.said_skipped, true) { + result.warnings.push(RewriteWarning { + code: "redirect_maven_repository_filter_skipped".into(), + detail: format!( + "{MVN_CONFIG} cannot be written (it is a symbolic link, or its \ + directory does not take the write), so the two lines that point \ + Maven at the repository filter in {dir} were not added and no \ + filter file was written. The pins landed all the same: Maven asks \ + each Socket repository for every artifact its local repository \ + does not hold, not for the patched version only", + dir = repository_filter::DIR, + ), + }); + } + return; + } + Config::Appended(config) => { + let action = if files.contains_key(MVN_CONFIG) { + "rewritten" + } else { + "added" + }; + *mvn_config = config; + *mvn_config_changed = true; + result.edits.push(FileEdit { + path: MVN_CONFIG.into(), + kind: "redirect_maven_config".into(), + action: action.into(), + key: Some("repositoryFilter".into()), + original: None, + new: None, + }); + // The directory is one per build, not one per repository: + // said once, by the run that moves it. + if !std::mem::replace(&mut self.said_enabled, true) { + result.warnings.push(RewriteWarning { + code: "redirect_maven_repository_filter_enabled".into(), + detail: format!( + "{MVN_CONFIG} now switches Maven's repository prefix filter on and \ + names {dir} as its directory, so every build of this project reads \ + prefix files from {dir} only. A prefix file kept anywhere else (the \ + local repository's default directory, say) is no longer read unless \ + a build names its directory on the command line: move it into {dir}", + dir = repository_filter::DIR, + ), + }); + } + } + Config::InPlace => {} + } + self.pinned.insert(rel.clone()); + // By what the file says, not by its bytes: a checkout with CRLF + // line endings, or a comment someone added, lists the path too. + if self + .live(files, &rel) + .is_some_and(|text| repository_filter::lists(text, &listed)) + { + return; + } + let action = if files.contains_key(&rel) { + "rewritten" + } else { + "added" + }; + result.edits.push(FileEdit { + path: rel.clone(), + kind: MAVEN_FILTER_EDIT.into(), + action: action.into(), + key: Some(repo_id.to_string()), + original: None, + new: Some(Value::String(listed)), + }); + let text = repository_filter::file_text(repo_id, group_id, artifact_id, suffixed_version); + self.files.insert(rel, text); + } + + /// Note the filter file of a pin that is in place and was not written + /// this run, when it has one. Nothing is written for it: a re-run + /// stays edit-free, and a pin without a file is left without one. + fn in_place(&mut self, files: &BTreeMap, repo_id: &str) { + use crate::formats::maven::repository_filter; + if generation::pin_name_uuid(repo_id, false).is_none() { + return; + } + let rel = repository_filter::file_rel(repo_id); + if self.live(files, &rel).is_some() { + self.pinned.insert(rel); + } + } + + /// Retire the filter file of a Socket repository this run took out of + /// the poms (a patch another superseded, or one whose last pin went). + /// + /// The file is left exactly as it is. It is inert while no pom declares + /// its repository, and it is the right file if the wiring comes back by + /// another road (a pom-only revert, a merge): emptied, it would fail + /// that build (`Prefix … NOT allowed`) until the next scan. `rollback` + /// and `remove` delete it. A file this same run planned for the + /// repository is taken back, as if never written. + fn retire( + &mut self, + files: &BTreeMap, + repo_id: &str, + result: &mut RewriteResult, + ) { + use crate::formats::maven::repository_filter; + if generation::pin_name_uuid(repo_id, false).is_none() { + return; + } + let rel = repository_filter::file_rel(repo_id); + self.pinned.remove(&rel); + if self.files.remove(&rel).is_some() { + result + .edits + .retain(|e| !(e.kind == MAVEN_FILTER_EDIT && e.path == rel)); + } + // Only a file the checkout holds is left behind by this run. + if files.contains_key(&rel) { + self.retired = true; + } + } + + /// Whether, once this run is written, no filter file of hosted mode + /// belongs to a repository a pom still names (`declared`): the two + /// resolver lines then serve no file of hosted mode's. + fn serves_none( + &self, + files: &BTreeMap, + declared: &dyn Fn(&str) -> bool, + ) -> bool { + use crate::formats::maven::repository_filter; + !files + .keys() + .chain(self.files.keys()) + .filter_map(|rel| repository_filter::owned_rel(rel)) + .any(declared) + } +} + +/// The `.mvn` files of one dep once the reactor planner planned it, +/// wherever the plan was asked for (a reactor root, or a single pom's +/// `${property}` version): the Trusted Checksums of a pin that landed, the +/// checksum lines and the filter file of a repository the plan took out +/// (`still_declared` says whether a pom of the project still names it), and +/// the filter file of the pin's own repository. +#[allow(clippy::too_many_arguments)] +fn settle_maven_plan( + files: &BTreeMap, + run: ReactorRun, + still_declared: &dyn Fn(&str) -> bool, + repo_id: &str, + (group_id, artifact_id, suffixed_version): (&str, &str, &str), + (checksum_hashes, bad_checksum_hashes): (Option<&(String, String)>, bool), + settings: &mut MavenChecksumSettings<'_>, + checksum_entries: &mut Vec<(String, String)>, + checksum_drops: &mut Vec, + pinned_jar_paths: &mut Vec, + scope: &mut MavenScope, + result: &mut RewriteResult, +) { + let coords = (group_id, artifact_id, suffixed_version); + if checksum_hashes.is_some() && run.wired { + pinned_jar_paths.push(crate::vendor::jvm::layout::artifact_path( + group_id, + artifact_id, + suffixed_version, + None, + "jar", + )); + } + checksum_drops.extend(run.drops); + for id in &run.unserved { + if !still_declared(id) { + scope.retire(files, id, result); + } + } + if run.landed { + pin_maven_checksums( + files, + coords, + checksum_hashes, + bad_checksum_hashes, + settings, + checksum_entries, + result, + ); + } + // (A plan that only took pins out wires nothing.) + if run.landed && run.wired { + scope.repository( + files, + repo_id, + coords, + ( + &mut *settings.config, + &mut *settings.changed, + settings.basedir, + ), + result, + ); + } else if run.wired { + scope.in_place(files, repo_id); + } +} + +/// The repository filter files hosted mode keeps under a project +/// ([`repository_filter::DIR`]), as every reader of that directory sees it: +/// the engine before a scan, the restore, and the vendored eject. +#[derive(Debug, Default)] +pub struct MavenFilterDir { + /// Hosted mode's own files, project-relative, sorted: regular files + /// named `prefixes-socket-patch-.txt`. + pub owned: Vec, + /// The directory holds something else (a file of the user's, a + /// subdirectory, a link). + pub others: bool, + /// The entries among those others that carry a name hosted mode + /// writes, project-relative, sorted: a link or a directory where a + /// filter file would go. + pub occupied: Vec, + /// The directory could not be listed to its end (and is not simply + /// absent): what it holds is not known, so nothing in it is hosted + /// mode's to delete and the lines that name it are not taken out. + pub unlistable: bool, +} + +/// List [`MavenFilterDir`] for the project `view` shows. A missing +/// directory is an empty one. A listing that fails part-way is no listing: +/// the files seen so far are not reported. +pub async fn hosted_maven_filter_dir( + view: &crate::vendor::lock_inventory::ProjectView<'_>, +) -> MavenFilterDir { + use crate::formats::maven::repository_filter; + let mut found = MavenFilterDir::default(); + let entries = match view.list_dir_strict(repository_filter::DIR).await { + Ok(entries) => entries, + Err(e) => { + found.unlistable = e.kind() != std::io::ErrorKind::NotFound; + return found; + } + }; + for entry in entries { + let rel = format!("{}/{}", repository_filter::DIR, entry.name); + // Ours is a regular file under a name hosted mode writes: never a + // directory, a link (a linked file is not ours to delete or to + // write through) or anything else a name can stand for. + let regular = !entry.is_dir + && match view.disk_root() { + Some(root) => tokio::fs::symlink_metadata(root.join(&rel)) + .await + .is_ok_and(|meta| meta.file_type().is_file()), + None => !view.is_symlink(&rel), + }; + match (repository_filter::owned(&entry.name).is_some(), regular) { + (true, true) => found.owned.push(rel), + (true, false) => { + found.others = true; + found.occupied.push(rel); + } + (false, _) => found.others = true, + } + } + found.owned.sort(); + found.occupied.sort(); + found +} + /// Why a dep is not wired behind `mirror`, and the ways forward. The /// settings read are the scanning machine's, which the line says: the /// machine that builds may be configured otherwise. @@ -10336,6 +10829,8 @@ struct ReactorRun { /// this version whose pins moved to this one, or this patch's own once /// its last pin was taken out. drops: Vec, + /// The ids of the Socket repositories the plan took out of the poms. + unserved: Vec, } /// The hosted warning a reactor planner note, or the reason a plan was @@ -10429,6 +10924,18 @@ struct MavenReactorRewrite { } impl MavenReactorRewrite { + /// Whether a pom of the project, as the plans so far leave it, names + /// `id`: every pom the planner read (a module's pom may be a file of + /// any name, so they are taken from the reactor, not told by name), + /// and `root`, the root pom as it reads now. + fn declares(&self, id: &str, root: &str) -> bool { + root.contains(id) + || matches!(&self.reactor, Some(Ok(reactor)) if reactor + .scope() + .iter() + .any(|rel| reactor.text(rel).is_some_and(|pom| pom.contains(id)))) + } + /// Wire one dep through the reactor planner /// ([`HostedReactor::plan`](crate::vendor::jvm::maven_reactor::HostedReactor::plan)): /// over every pom of a reactor root, or over a single pom whose @@ -10691,79 +11198,244 @@ impl MavenReactorRewrite { &format!("no pom of the build could take the pin of {}", dep.version), ); } + let mut unserved: Vec = plan + .edits + .iter() + .filter(|edit| matches!(edit.kind, HostedEditKind::RepositoryRemoved)) + .map(|edit| match edit.repository.as_deref() { + Some(uuid) => generation::hosted_pin_name(uuid), + None => of.repo_id.to_string(), + }) + .collect(); + unserved.sort(); + unserved.dedup(); Some(ReactorRun { landed, wired: plan.wired, drops, + unserved, }) } } -/// 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. +/// Rewrite the lines of `.mvn/maven.config` that stand in the other +/// spelling to the one this project takes ([`heal_maven_config`]): the file +/// and one edit for each group of lines 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`). +/// enforced the pin, or asked the Socket repositories for the patched +/// versions only, before and does not after. That is said, never done +/// silently ([`MavenConfigLines::scan_trade`]). 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, + let healed = heal_maven_config(files.get(MVN_CONFIG)?, declared, "")?; + for (lines, trade) in healed.lines { + result.edits.push(FileEdit { + path: MVN_CONFIG.into(), + kind: "redirect_maven_config".into(), + action: "rewritten".into(), + key: Some(lines.heal_key().into()), + original: None, + new: None, }); + if let Some(detail) = trade { + result.warnings.push(RewriteWarning { + code: lines.scan_trade().into(), + detail, + }); + } + } + result.files.insert(MVN_CONFIG.into(), healed.text.clone()); + Some(healed.text) +} + +/// The lines hosted mode writes into `.mvn/maven.config` that name a +/// directory of the checkout through a root-directory property +/// ([`RootDirectory`]), and so are spelled for the Maven the project +/// declares and respelled when that changes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum MavenConfigLines { + /// The six Trusted Checksums settings, by their directory line + /// ([`trusted_checksums::heal_basedir`]). + Checksums, + /// The repository filter's directory line + /// ([`crate::formats::maven::repository_filter::heal_basedir`]). + Filter, +} + +impl MavenConfigLines { + const ALL: [MavenConfigLines; 2] = [MavenConfigLines::Checksums, MavenConfigLines::Filter]; + + /// The `key` of the `redirect_maven_config` edit that respells the + /// lines, which tells it from the edit that merges them in + /// (`trustedChecksums`, `repositoryFilter`). + pub(crate) const fn heal_key(self) -> &'static str { + match self { + MavenConfigLines::Checksums => MVN_CONFIG_HEAL_KEY, + MavenConfigLines::Filter => "repositoryFilterDirectory", + } + } + + /// The warning a scan's respelling carries when it trades Maven 4 away + /// ([`Self::trade_detail`]). + const fn scan_trade(self) -> &'static str { + match self { + MavenConfigLines::Checksums => "redirect_maven_trusted_checksums_maven3_only", + MavenConfigLines::Filter => "redirect_maven_repository_filter_maven3_only", + } + } + + /// The same warning, as the restore of a pin reports it. + pub(crate) const fn restore_trade(self) -> &'static str { + match self { + MavenConfigLines::Checksums => "maven_trusted_checksums_maven3_only", + MavenConfigLines::Filter => "maven_repository_filter_maven3_only", + } + } + + /// `config` with these lines spelled as `form`; `None` when they do + /// not stand in the other spelling. + fn heal(self, config: &str, form: RootDirectory) -> Option { + match self { + MavenConfigLines::Checksums => trusted_checksums::heal_basedir(config, form), + MavenConfigLines::Filter => { + crate::formats::maven::repository_filter::heal_basedir(config, form) + } + } + } + + /// What respelling these lines 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 read by Maven + /// 3 only: `None` when nothing was traded (the project declares its + /// Maven, or the config does not switch the setting on). + fn trade_detail(self, healed: &str, declared: &DeclaredMaven, dir: &str) -> Option { + use crate::formats::maven::repository_filter; + use trusted_checksums::{Enforcement, Settings}; + let (traded, named, session, launcher, before, after) = match self { + MavenConfigLines::Checksums => ( + trusted_checksums::enforcement(&Settings::read(healed), declared) + == Enforcement::Maven3Only, + "the Trusted Checksums directory", + trusted_checksums::basedir_value(RootDirectory::Session), + trusted_checksums::basedir_value(RootDirectory::Launcher), + format!( + "Maven 3.9.4 and later 3.x enforce the checksums in {dir}{MVN_CHECKSUMS} as \ + before" + ), + "Maven 4 does not read that property", + ), + MavenConfigLines::Filter => ( + repository_filter::read_by(healed, declared) == Some(Reads::Maven3Only), + "the repository filter's directory", + repository_filter::basedir_value(RootDirectory::Session), + repository_filter::basedir_value(RootDirectory::Launcher), + "Maven 3.9.2 and later 3.x ask each Socket repository for the patched version \ + only, as before" + .to_string(), + "Maven 4 does not read that property, so it asks them for every artifact its \ + local repository does not hold", + ), + }; + traded.then(|| { + format!( + "{dir}{MVN_CONFIG} named {named} 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}. {before}. A Maven 4 build of this project no \ + longer does: {after}. 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" + ) + }) } - 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`). +/// Checksums directory line ([`MavenConfigLines::heal_key`]). 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"; +/// A `.mvn/maven.config` with the lines hosted mode wrote respelled. +pub(crate) struct HealedMavenConfig { + /// The config after the respelling. + pub(crate) text: String, + /// The lines that were respelled, each with what that traded away on + /// Maven 4 ([`MavenConfigLines::trade_detail`]). + pub(crate) lines: Vec<(MavenConfigLines, Option)>, +} + +/// `config`, the `.mvn/maven.config` under `dir` (`""`, or a path ending in +/// `/`), with every line hosted mode wrote in the other spelling respelled +/// for the Maven the project declares ([`RootDirectory::for_maven`]): +/// `None` when there is nothing to change. The one heal of that file, for +/// a scan and for the restore of a pin alike. +pub(crate) fn heal_maven_config( + config: &str, + declared: &DeclaredMaven, + dir: &str, +) -> Option { + let form = RootDirectory::for_maven(declared); + let mut text: Option = None; + let mut healed = vec![]; + for lines in MavenConfigLines::ALL { + if let Some(next) = lines.heal(text.as_deref().unwrap_or(config), form) { + text = Some(next); + healed.push(lines); + } + } + let text = text?; + // (Judged on the file as the whole respelling leaves it.) + let lines = healed + .into_iter() + .map(|lines| (lines, lines.trade_detail(&text, declared, dir))) + .collect(); + Some(HealedMavenConfig { text, lines }) +} /// 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. +/// file, its edits and the warnings that go with them. `true` when it was +/// taken out. /// /// 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. +/// had) leaves the lines as they are. +/// +/// That holds where the heal is the file's whole change. A run that also +/// writes the file for a pin (the repository filter's lines go in with a +/// pin that lands, and come out with the last filter file) has a write of +/// its own to make there: nothing is taken out, and that write stands or +/// is refused exactly as it would be with no heal beside it. pub(crate) fn withhold_maven_heal(result: &mut RewriteResult) -> bool { if !carries_maven_heal(result) { return false; } + let other_write = result + .edits + .iter() + .any(|edit| edit.path == MVN_CONFIG && !is_maven_heal(edit)); + if other_write { + 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); + result.warnings.retain(|w| { + !MavenConfigLines::ALL + .iter() + .any(|lines| lines.scan_trade() == w.code) + }); true } fn is_maven_heal(edit: &FileEdit) -> bool { - edit.path == MVN_CONFIG && edit.key.as_deref() == Some(MVN_CONFIG_HEAL_KEY) + edit.path == MVN_CONFIG + && MavenConfigLines::ALL + .iter() + .any(|lines| edit.key.as_deref() == Some(lines.heal_key())) } /// Whether `result` respells `.mvn/maven.config` ([`heal_mvn_config`]). @@ -10786,34 +11458,6 @@ pub(crate) async fn maven_config_writable(root: &std::path::Path) -> bool { 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`]). @@ -10829,26 +11473,55 @@ fn unenforced_detail( 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::UnreadByMaven4 => 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}", + declares = how_maven_4_is_declared(declared), + property = Basedir::Launcher.property(), + session = basedir_value(Basedir::Session), + key = trusted_checksums::BASEDIR_KEY, + )), Enforcement::Off | Enforcement::Maven3Only | Enforcement::Enforced => None, } } +/// Why the repository filter is not read by the Maven the project +/// declares, and what changes that; `None` when it is, or when the project +/// declares no Maven to judge by ([`Reads`]). +fn unfiltered_detail(reads: &Reads, declared: &DeclaredMaven) -> Option { + use crate::formats::maven::repository_filter::{basedir_value, BASEDIR_KEY, DIR}; + let unfiltered = "Maven asks each Socket repository for every artifact its local repository \ + does not hold, not for the patched version only"; + match reads { + Reads::TooOld(version) => Some(format!( + "{MVN_WRAPPER_PROPERTIES} pins Maven {version}, which does not read the repository \ + filter in {DIR} (Maven reads it from 3.9.2); {unfiltered}. Upgrade the Maven \ + Wrapper to 3.9.2 or later" + )), + Reads::UnreadByMaven4 => Some(format!( + "{declares}, and Maven 4 does not read {property}, through which {MVN_CONFIG} \ + names the repository filter's directory, so the filter in {DIR} is not read; \ + {unfiltered}. Set the line to -D{BASEDIR_KEY}={session}", + declares = how_maven_4_is_declared(declared), + property = RootDirectory::Launcher.property(), + session = basedir_value(RootDirectory::Session), + )), + Reads::Maven3Only | Reads::Read => None, + } +} + +/// How a project that declares Maven 4 says so, for a line that tells the +/// user their Maven does not read a setting. +fn how_maven_4_is_declared(declared: &DeclaredMaven) -> String { + 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(), + } +} + static MAVEN_REPOSITORY_RE: LazyLock = LazyLock::new(|| { Regex::new(r"(?s).*?").expect("static repository regex is valid") }); @@ -10929,14 +11602,10 @@ fn merge_mvn_config( if appended.is_empty() { return (existing.to_string(), conflicts); } - let base = if existing.is_empty() { - String::new() - } else if existing.ends_with('\n') { - existing.to_string() - } else { - format!("{existing}\n") - }; - (format!("{base}{}\n", appended.join("\n")), conflicts) + ( + crate::formats::maven::append_config_args(existing, &appended, false), + conflicts, + ) } // ── golang (go.mod fork-replace + go.sum pin) ──────────────────────────────── @@ -11820,6 +12489,677 @@ mod tests { } const MAVEN_UUID: &str = "aaaaaaaa-1111-4222-8333-444444444444"; + /// The repository filter file of [`granted_maven_override`]. + const MAVEN_FILTER: &str = + ".mvn/socket-patch/prefixes-socket-patch-aaaaaaaa-1111-4222-8333-444444444444.txt"; + /// What the run that adds the filter's two lines says, once. + const MAVEN_FILTER_ENABLED: &str = "redirect_maven_repository_filter_enabled"; + + /// A pin that lands keeps Maven from asking its Socket repository for + /// anything but the pinned version: the prefix file Maven reads for + /// that repository id, and the two resolver lines that point Maven at + /// it, after the Trusted Checksums ones. + #[test] + fn maven_pin_scopes_its_repository_to_the_pinned_version() { + use crate::formats::maven::repository_filter; + let files = BTreeMap::from([( + "pom.xml".to_string(), + pom_with_dep("\n 1.7.36", ""), + )]); + let r = rewrite_registry_redirect(&files, &[granted_maven_override()]); + assert_eq!( + r.files[MAVEN_FILTER], + format!( + "## repository-prefixes/2.0\n# Written by socket-patch: Maven asks the \ + socket-patch-{MAVEN_UUID} repository for this path only.\n\ + /org/slf4j/slf4j-api/{MAVEN_SUFFIXED}\n" + ) + ); + let mut lines: Vec<&str> = MVN_CONFIG_ARGS.to_vec(); + // (No Maven is declared, so both directories take the launcher's + // property: the one that stops no Maven 3 build from starting.) + lines.extend(repository_filter::config_args(RootDirectory::Launcher)); + assert_eq!(r.files[MVN_CONFIG], format!("{}\n", lines.join("\n"))); + assert_eq!( + r.edits + .iter() + .filter(|e| e.path != "pom.xml") + .map(|e| (e.path.as_str(), e.kind.as_str(), e.key.as_deref())) + .collect::>(), + [ + ( + MVN_CONFIG, + "redirect_maven_config", + Some("trustedChecksums") + ), + ( + MVN_CONFIG, + "redirect_maven_config", + Some("repositoryFilter") + ), + ( + MAVEN_FILTER, + "redirect_maven_repository_filter", + Some(format!("socket-patch-{MAVEN_UUID}").as_str()) + ), + (MVN_CHECKSUMS, "redirect_maven_trusted_checksums", None), + ] + ); + // The run that adds the two lines says what they change for the + // whole build; nothing else is said. + assert_eq!( + warning_codes(&r), + [MAVEN_FILTER_ENABLED], + "{:?}", + r.warnings + ); + // A second run finds all of it and writes nothing. + let mut wired = files.clone(); + wired.extend(r.files.clone()); + let again = rewrite_registry_redirect(&wired, &[granted_maven_override()]); + assert!( + again.files.is_empty() && again.edits.is_empty(), + "{:?}", + again.edits + ); + // Nor does it add the filter to a pin an earlier release wrote + // without one: a re-run stays edit-free, as for the checksums. + let mut earlier = wired.clone(); + earlier.remove(MAVEN_FILTER); + earlier.insert( + MVN_CONFIG.to_string(), + format!("{}\n", MVN_CONFIG_ARGS.join("\n")), + ); + let again = rewrite_registry_redirect(&earlier, &[granted_maven_override()]); + assert!(again.files.is_empty(), "{:?}", again.files.keys()); + // A same-GAV grant names no version of its own to list. + let legacy = rewrite_registry_redirect(&files, &[legacy_maven_override()]); + assert_eq!(legacy.files.keys().collect::>(), ["pom.xml"]); + } + + /// The filter's directory is one per build. A checkout that already + /// configures the prefix filter, in `maven.config` or as a JVM + /// argument, keeps its configuration: the pin lands, the Socket + /// repository is left unfiltered, and one warning says so. + #[test] + fn maven_filter_is_left_to_a_checkout_that_configures_its_own() { + let pom = pom_with_dep("\n 1.7.36", ""); + let theirs = "-Daether.remoteRepositoryFilter.prefixes=true\n"; + for (rel, text) in [ + (MVN_CONFIG, theirs), + ( + MVN_CONFIG, + "-Daether.remoteRepositoryFilter.prefixes.basedir=${session.rootDirectory}/.mvn/rrf\n", + ), + ( + MVN_JVM_CONFIG, + "-Xmx1g -Daether.remoteRepositoryFilter.prefixes=true\n", + ), + ] { + let files = BTreeMap::from([ + ("pom.xml".to_string(), pom.clone()), + (rel.to_string(), text.to_string()), + ]); + let r = rewrite_registry_redirect(&files, &[granted_maven_override()]); + assert!(r.files["pom.xml"].contains(MAVEN_SUFFIXED), "{rel}: {text}"); + assert!( + !r.files.keys().any(|k| k.starts_with(".mvn/socket-patch/")), + "{rel}: {:?}", + r.files.keys() + ); + let config = &r.files[MVN_CONFIG]; + assert!( + !config.contains(".mvn/socket-patch"), + "{rel}: no line of ours: {config}" + ); + if rel == MVN_CONFIG { + assert!(config.starts_with(text), "their lines stay: {config}"); + } + assert_eq!( + warning_codes(&r), + ["redirect_maven_repository_filter_conflict"], + "{rel}" + ); + } + } + + /// The conflict is said for each patch, since each has a repository + /// and a path of its own to list, and reads as one line of prose. + #[test] + fn maven_filter_conflict_is_said_for_each_patch_and_names_its_path() { + let second_uuid = "88888888-8888-4888-8888-888888888888"; + let mut second = granted_maven_override(); + second.name = "slf4j-simple".into(); + second.patch_uuid = second_uuid.into(); + let ov = second.registry_override.as_mut().unwrap(); + ov.index_url = + format!("https://patch.socket.dev/patch-registry/maven/tok/{second_uuid}/maven2"); + 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.remoteRepositoryFilter.prefixes=true\n".to_string(), + ), + ]); + let r = rewrite_registry_redirect(&files, &[granted_maven_override(), second]); + let conflicts: Vec<&str> = r + .warnings + .iter() + .filter(|w| w.code == "redirect_maven_repository_filter_conflict") + .map(|w| w.detail.as_str()) + .collect(); + assert_eq!(conflicts.len(), 2, "{:?}", r.warnings); + for (detail, (artifact, uuid, suffixed)) in conflicts.iter().zip([ + ("slf4j-api", MAVEN_UUID, MAVEN_SUFFIXED), + ("slf4j-simple", second_uuid, "1.7.36-socket.88888888"), + ]) { + assert!( + detail.starts_with(&format!("org.slf4j:{artifact}: ")), + "{detail}" + ); + for part in [ + "-Daether.remoteRepositoryFilter.prefixes=true".to_string(), + format!("prefixes-socket-patch-{uuid}.txt"), + format!("/org/slf4j/{artifact}/{suffixed}"), + ] { + assert!(detail.contains(&part), "{part}: {detail}"); + } + assert!(!detail.contains(" "), "one line of prose: {detail:?}"); + } + assert!(!r.files.keys().any(|k| k.starts_with(".mvn/socket-patch/"))); + } + + /// The engine-supplied surroundings of the filter ([`MAVEN_FILTER_KEY`]). + fn maven_filter_around(around: &MavenFilterAround) -> (String, String) { + ( + MAVEN_FILTER_KEY.to_string(), + serde_json::to_string(around).unwrap(), + ) + } + + /// A filter file is read for what it says, not compared byte for byte. + /// A checkout with CRLF line endings, or a file someone added a + /// comment to, lists the pinned path all the same: a re-scan reports + /// no rewrite, and a pin that lands again leaves the file as it is. + /// One that does not list the path is rewritten with the pin, since + /// Maven would refuse the pin otherwise (`Prefix … NOT allowed`). + #[test] + fn maven_filter_file_is_judged_by_what_it_lists() { + let files = BTreeMap::from([( + "pom.xml".to_string(), + pom_with_dep("\n 1.7.36", ""), + )]); + let dep = granted_maven_override(); + let first = rewrite_registry_redirect(&files, std::slice::from_ref(&dep)); + let mut wired = files.clone(); + wired.extend(first.files.clone()); + let written = wired[MAVEN_FILTER].clone(); + for theirs in [ + written.replace('\n', "\r\n"), + format!("{written}# reviewed 2026-11\n"), + ] { + assert_ne!(theirs, written); + // The pin in place: nothing lands, nothing is written. + let mut again = wired.clone(); + again.insert(MAVEN_FILTER.to_string(), theirs.clone()); + let r = rewrite_registry_redirect(&again, std::slice::from_ref(&dep)); + assert!(r.files.is_empty(), "{theirs:?}: {:?}", r.files.keys()); + assert!(r.edits.is_empty(), "{theirs:?}: {:?}", r.edits); + // The pom reverted on its own, the pin lands again: the file + // there already lists its path. + again.insert("pom.xml".to_string(), files["pom.xml"].clone()); + let r = rewrite_registry_redirect(&again, std::slice::from_ref(&dep)); + assert_eq!( + r.files.keys().collect::>(), + ["pom.xml"], + "{theirs:?}" + ); + assert!( + !r.edits.iter().any(|e| e.kind == MAVEN_FILTER_EDIT), + "{theirs:?}: {:?}", + r.edits + ); + } + // A file that does not list the path: left alone while the pin is + // in place (a re-run is edit-free), rewritten when the pin lands. + for broken in [ + "", + "## repository-prefixes/2.0\n/org/slf4j/slf4j-api/1.7.36-socket.bbbbbbbb\n", + ] { + let mut again = wired.clone(); + again.insert(MAVEN_FILTER.to_string(), broken.to_string()); + let r = rewrite_registry_redirect(&again, std::slice::from_ref(&dep)); + assert!(r.files.is_empty(), "{broken:?}: {:?}", r.files.keys()); + again.insert("pom.xml".to_string(), files["pom.xml"].clone()); + let r = rewrite_registry_redirect(&again, std::slice::from_ref(&dep)); + assert_eq!(r.files[MAVEN_FILTER], written, "{broken:?}"); + assert!( + r.edits.iter().any(|e| e.kind == MAVEN_FILTER_EDIT + && e.path == MAVEN_FILTER + && e.action == "rewritten"), + "{broken:?}: {:?}", + r.edits + ); + } + } + + /// The scope object, one repository at a time. A repository that goes + /// out of the poms leaves its filter file exactly as it is: nothing is + /// written for it and nothing reported. Only a file the checkout holds + /// counts as left behind; one this same run planned is taken back, as + /// if never written, and leaves nothing behind. + #[test] + fn maven_scope_retires_a_file_without_touching_it() { + use crate::formats::maven::repository_filter; + let id = format!("socket-patch-{MAVEN_UUID}"); + let coords = ("org.slf4j", "slf4j-api", MAVEN_SUFFIXED); + let rel = repository_filter::file_rel(&id); + assert_eq!(rel, MAVEN_FILTER); + let text = repository_filter::file_text(&id, coords.0, coords.1, coords.2); + let form = RootDirectory::Launcher; + let lines = format!("{}\n", repository_filter::config_args(form).join("\n")); + let nobody = |_: &str| false; + let this_one = |declared: &str| declared == id; + + // In the checkout, retired, then wired again within the run. + let files = BTreeMap::from([ + (rel.clone(), text.clone()), + (MVN_CONFIG.to_string(), lines.clone()), + ]); + let mut scope = MavenScope::default(); + let mut result = RewriteResult::default(); + scope.retire(&files, &id, &mut result); + assert!(scope.retired); + assert!(scope.files.is_empty() && result.edits.is_empty()); + assert!(scope.serves_none(&files, &nobody)); + let (mut config, mut changed) = (lines.clone(), false); + scope.repository( + &files, + &id, + coords, + (&mut config, &mut changed, form), + &mut result, + ); + assert!(scope.files.is_empty(), "{:?}", scope.files); + assert!(result.edits.is_empty(), "{:?}", result.edits); + assert!(!changed && config == lines); + // Its repository is declared again, so the lines still serve it. + assert!(!scope.serves_none(&files, &this_one)); + + // Not in the checkout: written, then retired. Nothing was there + // before the run and nothing is after it, so nothing is left + // behind for the lines to be taken out over. + let empty = BTreeMap::from([(MVN_CONFIG.to_string(), lines.clone())]); + let mut scope = MavenScope::default(); + let mut result = RewriteResult::default(); + scope.repository( + &empty, + &id, + coords, + (&mut config, &mut changed, form), + &mut result, + ); + assert_eq!(scope.files.get(&rel), Some(&text)); + assert_eq!(result.edits.len(), 1); + assert!(scope.pinned.contains(&rel)); + scope.retire(&empty, &id, &mut result); + assert!(scope.files.is_empty(), "{:?}", scope.files); + assert!(result.edits.is_empty(), "{:?}", result.edits); + assert!(!scope.retired && scope.pinned.is_empty()); + + // A repository with no file at all retires nothing. + let mut scope = MavenScope::default(); + scope.retire(&BTreeMap::new(), &id, &mut result); + assert!(!scope.retired); + } + + /// The two resolver lines are one setting for the whole directory. A + /// scan that takes the last Socket repository out of the poms takes + /// them out too, but not while the directory holds anything that is + /// not hosted mode's own file: a prefix file of the user's is read + /// through those lines, and a rollback keeps them for it as well. + #[test] + fn maven_filter_lines_stay_while_the_directory_holds_anything_else() { + let files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let first = rewrite_poms_selecting( + &files, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + let mut wired = files.clone(); + wired.extend(first.files.clone()); + let gone = [("a/pom.xml", Ok("2.0.9")), ("b/pom.xml", Ok("2.0.9"))]; + + // Control: with the directory hosted mode's alone, the lines go. + let r = rewrite_poms_selecting(&wired, &gone); + assert_eq!(r.files["pom.xml"], files["pom.xml"], "the repository went"); + assert!(!r.files[MVN_CONFIG].contains(".mvn/socket-patch")); + + // The engine saw a file of the user's there (or could not list + // the directory): the pin goes all the same, the lines stay. + let mut theirs = wired.clone(); + theirs.extend([maven_filter_around(&MavenFilterAround { + keeps_lines: true, + ..Default::default() + })]); + let r = rewrite_poms_selecting(&theirs, &gone); + assert_eq!(r.files["pom.xml"], files["pom.xml"], "the repository went"); + assert!( + !r.files.contains_key(MVN_CONFIG), + "{:?}", + r.files.get(MVN_CONFIG) + ); + assert!( + !r.edits + .iter() + .any(|e| e.key.as_deref() == Some("repositoryFilter")), + "{:?}", + r.edits + ); + } + + /// The filter is an extra, and a pin never waits for it. Where + /// `.mvn/maven.config` cannot take a write (a symbolic link, say) the + /// two lines are not added and no filter file is written: the pin + /// lands as it does without the filter, and one line says so. A config + /// that already holds the lines needs no write, and gets its file. + #[test] + fn maven_pin_lands_without_the_filter_where_the_config_cannot_be_written() { + use crate::formats::maven::repository_filter; + let checksums = format!("{}\n", MVN_CONFIG_ARGS.join("\n")); + let unwritable = maven_filter_around(&MavenFilterAround { + config_unwritable: true, + ..Default::default() + }); + let second_uuid = "88888888-8888-4888-8888-888888888888"; + let mut second = granted_maven_override(); + second.name = "slf4j-simple".into(); + second.patch_uuid = second_uuid.into(); + let ov = second.registry_override.as_mut().unwrap(); + ov.index_url = + format!("https://patch.socket.dev/patch-registry/maven/tok/{second_uuid}/maven2"); + 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 ", + ); + // The checksum settings are in place (an earlier scan's), so the + // filter's lines are the only write the config would take. + let files = BTreeMap::from([ + ("pom.xml".to_string(), pom), + (MVN_CONFIG.to_string(), checksums.clone()), + unwritable.clone(), + ]); + let r = rewrite_registry_redirect(&files, &[granted_maven_override(), second.clone()]); + assert!(r.files["pom.xml"].contains(MAVEN_SUFFIXED)); + assert!(r.files["pom.xml"].contains("1.7.36-socket.88888888")); + assert!(r.files.contains_key(MVN_CHECKSUMS)); + assert!( + !r.files.contains_key(MVN_CONFIG), + "the config is not written" + ); + assert!( + !r.files.keys().any(|k| k.starts_with(".mvn/socket-patch/")), + "{:?}", + r.files.keys() + ); + assert!( + !r.edits.iter().any(|e| e.path == MVN_CONFIG), + "{:?}", + r.edits + ); + // Once for the run, however many pins landed. + assert_eq!( + warning_codes(&r), + ["redirect_maven_repository_filter_skipped"], + "{:?}", + r.warnings + ); + let detail = &r.warnings[0].detail; + for part in [ + ".mvn/maven.config cannot be written", + "The pins landed all the same", + ] { + assert!(detail.contains(part), "{part}: {detail}"); + } + + // The lines already there: the file is written, no line is. + let lines = format!( + "{checksums}{}\n", + repository_filter::config_args(RootDirectory::Launcher).join("\n") + ); + let mut in_place = files.clone(); + in_place.insert(MVN_CONFIG.to_string(), lines); + let r = rewrite_registry_redirect(&in_place, &[granted_maven_override()]); + assert!(r.files.contains_key(MAVEN_FILTER)); + assert!(!r.files.contains_key(MVN_CONFIG)); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + + // Nor are the lines taken out of a config that cannot be written. + let reactor = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let first = rewrite_poms_selecting( + &reactor, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + let mut wired = reactor.clone(); + wired.extend(first.files.clone()); + wired.extend([unwritable]); + let r = rewrite_poms_selecting( + &wired, + &[("a/pom.xml", Ok("2.0.9")), ("b/pom.xml", Ok("2.0.9"))], + ); + assert_eq!( + r.files["pom.xml"], reactor["pom.xml"], + "the repository went" + ); + assert!(!r.files.contains_key(MVN_CONFIG)); + } + + /// A build started on the scanning machine that names the prefix + /// filter in its environment configures the filter itself, like a + /// setting in `.mvn/jvm.config`: the lines would move the directory + /// its files are read from. The pin lands, nothing is written for the + /// filter, and the conflict names the variable. + #[test] + fn maven_filter_is_left_to_the_environment_that_configures_it() { + let files = BTreeMap::from([ + ( + "pom.xml".to_string(), + pom_with_dep("\n 1.7.36", ""), + ), + maven_filter_around(&MavenFilterAround { + env: Some("MAVEN_OPTS".to_string()), + ..Default::default() + }), + ]); + let r = rewrite_registry_redirect(&files, &[granted_maven_override()]); + assert!(r.files["pom.xml"].contains(MAVEN_SUFFIXED)); + assert!(!r.files.keys().any(|k| k.starts_with(".mvn/socket-patch/"))); + assert!(!r.files[MVN_CONFIG].contains(".mvn/socket-patch")); + assert_eq!( + warning_codes(&r), + ["redirect_maven_repository_filter_conflict"] + ); + let detail = &r.warnings[0].detail; + assert!( + detail.contains("a setting in the MAVEN_OPTS environment variable of this machine"), + "{detail}" + ); + } + + /// The filter's directory is one per build. The run that adds the two + /// lines says, once, that Maven now reads prefix files from that + /// directory only; a run that finds them in place says nothing. + #[test] + fn maven_scan_says_when_it_moves_the_filter_directory() { + let files = BTreeMap::from([( + "pom.xml".to_string(), + pom_with_dep("\n 1.7.36", ""), + )]); + let r = rewrite_registry_redirect(&files, &[granted_maven_override()]); + assert_eq!( + warning_codes(&r), + [MAVEN_FILTER_ENABLED], + "{:?}", + r.warnings + ); + let detail = &r.warnings[0].detail; + for part in [ + ".mvn/maven.config now switches Maven's repository prefix filter on", + "reads prefix files from .mvn/socket-patch only", + "move it into .mvn/socket-patch", + ] { + assert!(detail.contains(part), "{part}: {detail}"); + } + let mut wired = files.clone(); + wired.extend(r.files.clone()); + let again = rewrite_registry_redirect(&wired, &[granted_maven_override()]); + assert!(again.warnings.is_empty(), "{:?}", again.warnings); + } + + /// A module's pom may be a file of any name. Whether a repository is + /// still declared, before its filter file is retired, is asked of + /// every pom the reactor read, not of the files named `pom.xml`. + #[test] + fn maven_reactor_asks_every_pom_it_read_whether_a_repository_is_declared() { + let id = format!("socket-patch-{MAVEN_UUID}"); + let root = "\n 4.0.0\n t\n \ + root\n 1\n \ + pom\n \n \ + tools/build-tools.xml\n \n\n"; + let tools = format!( + "\n 4.0.0\n t\n \ + tools\n 1\n \n \ + \n {id}\n https://patch.socket.dev/x\n \ + \n \n\n" + ); + let files = poms(&[("pom.xml", root), ("tools/build-tools.xml", &tools)]); + let read = |rel: &str| files.get(rel).map(|t| t.as_bytes().to_vec()); + let list = |dir: &str| gradle::key_list(&files, dir); + let reactor = crate::vendor::jvm::maven_reactor::HostedReactor::read(&read, &list) + .ok() + .expect("the reactor reads"); + assert!( + reactor + .scope() + .iter() + .any(|rel| rel == "tools/build-tools.xml"), + "{:?}", + reactor.scope() + ); + let planner = MavenReactorRewrite { + reactor: Some(Ok(reactor)), + ..Default::default() + }; + assert!(!root.contains(&id)); + assert!(planner.declares(&id, root)); + assert!(!planner.declares("socket-patch-00000000-0000-4000-8000-000000000000", root)); + // The root itself, as it reads now, counts as well. + assert!(planner.declares("in-the-root", "in-the-root")); + } + + /// Every reader of the filter directory lists it one way: hosted + /// mode's own regular files, and whether anything else is there. A + /// link or a directory under a name of hosted mode's is not its file; + /// a directory that cannot be listed is not an empty one. + #[test] + fn the_filter_directory_lists_only_hosted_modes_own_regular_files() { + use crate::vendor::lock_inventory::{MemoryEntry, MemoryProject, ProjectView}; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let tmp = tempfile::tempdir().unwrap(); + let listed = || runtime.block_on(hosted_maven_filter_dir(&ProjectView::Disk(tmp.path()))); + // No directory is an empty one. + let none = listed(); + assert!(none.owned.is_empty() && !none.others && !none.unlistable); + + let dir = tmp.path().join(".mvn/socket-patch"); + std::fs::create_dir_all(&dir).unwrap(); + let ours = format!("prefixes-socket-patch-{MAVEN_UUID}.txt"); + std::fs::write(dir.join(&ours), "## repository-prefixes/2.0\n").unwrap(); + let only_ours = listed(); + assert_eq!(only_ours.owned, [format!(".mvn/socket-patch/{ours}")]); + assert!(!only_ours.others && !only_ours.unlistable); + + // A file of the user's, and a directory under a name of ours. + std::fs::write(dir.join("prefixes-central.txt"), "/org\n").unwrap(); + std::fs::create_dir( + dir.join("prefixes-socket-patch-99999999-9999-4999-8999-999999999999.txt"), + ) + .unwrap(); + let mixed = listed(); + assert_eq!(mixed.owned, [format!(".mvn/socket-patch/{ours}")]); + assert!(mixed.others && !mixed.unlistable); + assert_eq!( + mixed.occupied, + [".mvn/socket-patch/prefixes-socket-patch-99999999-9999-4999-8999-999999999999.txt"] + ); + + // A link under a name of ours is not ours either: it is not read, + // not deleted, and nothing is written through it. + #[cfg(unix)] + { + let linked = tempfile::tempdir().unwrap(); + let dir = linked.path().join(".mvn/socket-patch"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(linked.path().join("elsewhere.txt"), "/org\n").unwrap(); + std::os::unix::fs::symlink("../../elsewhere.txt", dir.join(&ours)).unwrap(); + let found = + runtime.block_on(hosted_maven_filter_dir(&ProjectView::Disk(linked.path()))); + assert!(found.owned.is_empty() && found.others && !found.unlistable); + assert_eq!(found.occupied, [format!(".mvn/socket-patch/{ours}")]); + + // A directory that is there and cannot be read: what it holds + // is not known. (Root reads anything, so nothing to see there.) + if unsafe { libc::geteuid() } != 0 { + use std::os::unix::fs::PermissionsExt as _; + let dir = tmp.path().join(".mvn/socket-patch"); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o000)).unwrap(); + let unread = listed(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(unread.unlistable && unread.owned.is_empty()); + } + } + + // The same reading of a project held in memory. + let mut project = MemoryProject::new(); + project.insert_text( + &format!(".mvn/socket-patch/{ours}"), + "## repository-prefixes/2.0\n", + ); + let memory = runtime.block_on(hosted_maven_filter_dir(&ProjectView::Memory(&project))); + assert_eq!(memory.owned, [format!(".mvn/socket-patch/{ours}")]); + assert!(!memory.others && !memory.unlistable); + project.insert( + ".mvn/socket-patch/prefixes-socket-patch-99999999-9999-4999-8999-999999999999.txt", + MemoryEntry::Symlink, + ); + let memory = runtime.block_on(hosted_maven_filter_dir(&ProjectView::Memory(&project))); + assert_eq!(memory.owned, [format!(".mvn/socket-patch/{ours}")]); + assert!(memory.others); + } /// The engine-supplied mirrors of one settings file. fn maven_mirrors(mirrors: &[(&str, &str)]) -> (String, String) { @@ -12168,7 +13508,10 @@ mod tests { ); assert_eq!( warning_codes(&r), - ["redirect_maven_mirror_captures_repository"] + [ + "redirect_maven_mirror_captures_repository", + MAVEN_FILTER_ENABLED + ] ); assert!(r.warnings[0].detail.starts_with("org.slf4j:slf4j-api: ")); assert!(r.maven_reactor_uuids.contains(MAVEN_UUID)); @@ -12732,10 +14075,22 @@ mod tests { let r = rewrite_poms_selecting(&files, &picks); assert_eq!( r.files.keys().collect::>(), - [MVN_CHECKSUMS, MVN_CONFIG, "a/pom.xml", "pom.xml"], + [ + MVN_CHECKSUMS, + MVN_CONFIG, + MAVEN_FILTER, + "a/pom.xml", + "pom.xml" + ], "b/pom.xml is not written: {:?}", r.warnings ); + // Maven is kept from asking the Socket repository for anything but + // the pinned version, wherever in the reactor the pin sits. + assert_eq!( + r.files[MAVEN_FILTER].lines().last(), + Some(format!("/org/slf4j/slf4j-api/{MAVEN_SUFFIXED}").as_str()) + ); let pin = format!( "\n \ \n org.slf4j\n \ @@ -12763,10 +14118,15 @@ mod tests { ("a/pom.xml", "redirect_maven_dep_management", "added"), ("pom.xml", "redirect_maven_repository", "added"), (MVN_CONFIG, "redirect_maven_config", "added"), + (MVN_CONFIG, "redirect_maven_config", "added"), + (MAVEN_FILTER, "redirect_maven_repository_filter", "added"), (MVN_CHECKSUMS, "redirect_maven_trusted_checksums", "added"), ] ); - assert_eq!(warning_codes(&r), ["redirect_maven_dep_management_added"]); + assert_eq!( + warning_codes(&r), + ["redirect_maven_dep_management_added", MAVEN_FILTER_ENABLED] + ); assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); // A second run over what the first wrote changes nothing, and @@ -12815,7 +14175,10 @@ mod tests { assert!(!r.files.contains_key("b/pom.xml")); assert_eq!( warning_codes(&r), - ["redirect_maven_selection_undetermined"], + [ + "redirect_maven_selection_undetermined", + MAVEN_FILTER_ENABLED + ], "b may resolve it too, and is not pinned on a guess" ); assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); @@ -12882,9 +14245,11 @@ mod tests { } /// When the last pin of a patch is taken out (the module it reached - /// now resolves another version), its repository and its checksum - /// lines go with it: nothing is left that only a rollback could clear, - /// and no rollback would find. + /// now resolves another version), its repository, its checksum lines, + /// the path its filter file listed and, with the last filter file, the + /// two resolver lines that point Maven at them go with it: nothing is + /// left that only a rollback could clear, and no rollback would find. + /// (A rewrite removes no file: the filter file stays, empty.) #[test] fn maven_reactor_last_pin_removed_takes_the_repository_and_checksums() { let files = poms(&[ @@ -12927,9 +14292,489 @@ mod tests { removed, [ ("a/pom.xml", "redirect_maven_dep_management"), - ("pom.xml", "redirect_maven_repository") + ("pom.xml", "redirect_maven_repository"), + (MVN_CONFIG, "redirect_maven_config"), + ] + ); + // The filter file is left exactly as it is: no pom names its + // repository, so Maven does not read it, and it is the right file + // should the wiring come back by a pom-only revert or a merge. + assert!(!r.files.contains_key(MAVEN_FILTER), "{:?}", r.files.keys()); + // No pom names a repository with a filter file now, so the two + // resolver lines that named their directory go; the Trusted + // Checksums lines stay as they were. + assert!(wired[MVN_CONFIG].contains(".mvn/socket-patch")); + assert_eq!( + r.files[MVN_CONFIG], + format!("{}\n", MVN_CONFIG_ARGS.join("\n")) + ); + // The pin coming back writes the path, and the lines, again. + let mut unpinned = wired.clone(); + unpinned.extend(r.files.clone()); + let back = rewrite_poms_selecting( + &unpinned, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + // (The file is still there and lists the path: it is not written.) + assert!(!back.files.contains_key(MAVEN_FILTER)); + assert_eq!(back.files[MVN_CONFIG], wired[MVN_CONFIG]); + assert_eq!(back.files["a/pom.xml"], wired["a/pom.xml"]); + // And the wiring coming back with no scan at all (the poms alone + // reverted to the wired ones) builds: the file lists the pin. + assert!(crate::formats::maven::repository_filter::lists( + &unpinned[MAVEN_FILTER], + &format!("/org/slf4j/slf4j-api/{MAVEN_SUFFIXED}") + )); + } + + /// The resolver lines stay while a pom still names another Socket + /// repository that has a filter file: the lines serve that one. + #[test] + fn maven_filter_lines_stay_while_another_filter_file_is_in_use() { + use crate::formats::maven::repository_filter; + let other_id = "socket-patch-99999999-9999-4999-8999-999999999999"; + // Module `b` is wired for another patch, by an earlier run of it. + let other_repository = format!( + " \n \n {other_id}\n \ + https://patch.socket.dev/patch-registry/maven/tok/x/maven2\n \ + \n \n" + ); + let b = reactor_module("b", "").replace("", &other_repository); + assert!(b.contains(other_id)); + let files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &b), + ]); + let first = rewrite_poms_selecting( + &files, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + let mut wired = files.clone(); + wired.extend(first.files.clone()); + let other = repository_filter::file_rel(other_id); + wired.insert( + other.clone(), + repository_filter::file_text(other_id, "com.example", "other", "2.0.0-socket.99999999"), + ); + let r = rewrite_poms_selecting( + &wired, + &[("a/pom.xml", Ok("2.0.9")), ("b/pom.xml", Ok("2.0.9"))], + ); + assert_eq!( + r.files["pom.xml"], files["pom.xml"], + "this patch's repository went" + ); + assert!( + !r.files.keys().any(|k| k.starts_with(".mvn/socket-patch/")), + "no filter file is touched: {:?}", + r.files.keys() + ); + assert!( + !r.files.contains_key(MVN_CONFIG), + "the lines still serve {other}: {:?}", + r.files.get(MVN_CONFIG) + ); + } + + /// The filter's directory line names the checkout through the + /// property the Trusted Checksums directory takes, by the same rule: + /// the launcher's, which stops no Maven 3 build from starting, unless + /// the project declares Maven 4 (its wrapper, or a 4.1.0 model), which + /// reads only the session's. What the declared Maven makes of the + /// filter is said on the scan that writes it and on every later one. + #[test] + fn maven_filter_directory_follows_the_maven_the_project_declares() { + use crate::formats::maven::repository_filter; + use RootDirectory::{Launcher, Session}; + let pom = pom_with_dep("\n 1.7.36", ""); + let run = |files: &BTreeMap| { + rewrite_registry_redirect(files, &[granted_maven_override()]) + }; + let form = |r: &RewriteResult| repository_filter::form(&r.files[MVN_CONFIG]); + let checksums_form = + |r: &RewriteResult| trusted_checksums::Settings::read(&r.files[MVN_CONFIG]).basedir(); + let unread = "redirect_maven_repository_filter_unread"; + let plain = BTreeMap::from([("pom.xml".to_string(), pom.clone())]); + let wired = run(&plain); + assert_eq!(form(&wired), Some(Launcher)); + // (Nothing but the line the first wiring says of the directory.) + assert_eq!(warning_codes(&wired), [MAVEN_FILTER_ENABLED]); + for (wrapper, expected, read) in [ + ("3.6.3", Launcher, false), + ("3.9.1", Launcher, false), + ("3.9.2", Launcher, true), + ("3.9.8", Launcher, true), + ("3.9.16", Launcher, true), + ("4.0.0-rc-7", Session, true), + ("4.0.0", Session, true), + ] { + 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}"); + // One property for both directories. + assert_eq!(checksums_form(&r), Some(expected), "{wrapper}"); + assert_eq!( + r.files[MAVEN_FILTER], wired.files[MAVEN_FILTER], + "{wrapper}: the file is written whichever Maven reads it" + ); + // The first Maven that finds the directory is 3.9.2: an older + // one the wrapper pins is named, with the remedy. + let said: Vec<&str> = r + .warnings + .iter() + .filter(|w| w.code == unread) + .map(|w| w.detail.as_str()) + .collect(); + assert_eq!( + said.len(), + usize::from(!read), + "{wrapper}: {:?}", + r.warnings + ); + for detail in &said { + for part in [ + format!("pins Maven {wrapper}"), + "Maven reads it from 3.9.2".to_string(), + ".mvn/socket-patch".to_string(), + "Upgrade the Maven Wrapper to 3.9.2 or later".to_string(), + ] { + assert!(detail.contains(&part), "{part}: {detail}"); + } + } + // Judged on the files as they stand: a re-scan says it too. + let mut again = files.clone(); + again.extend(r.files.clone()); + let rescan = run(&again); + assert!( + rescan.files.is_empty(), + "{wrapper}: {:?}", + rescan.files.keys() + ); + assert_eq!( + warning_codes(&rescan).contains(&unread), + !read, + "{wrapper}: {:?}", + rescan.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); + let r = run(&model_4_1); + assert_eq!(form(&r), Some(Session)); + assert_eq!(warning_codes(&r), [MAVEN_FILTER_ENABLED]); + + // A directory line in another spelling of the argument is not one + // the heal rewrites. Under the launcher's property in a project + // that declares Maven 4 it names no directory there: the pin and + // its file land (the line needs one edit to work), and the run + // says that Maven 4 does not read the filter, with that edit. + let define = format!( + "{}\n--define {}={}\n", + repository_filter::config_args(Launcher)[0], + repository_filter::BASEDIR_KEY, + repository_filter::basedir_value(Launcher) + ); + let mut users = model_4_1.clone(); + users.insert(MVN_CONFIG.to_string(), define.clone()); + let r = run(&users); + assert!(r.files[MVN_CONFIG].starts_with(&define), "their lines stay"); + assert_eq!(r.files[MAVEN_FILTER], wired.files[MAVEN_FILTER]); + assert_eq!(warning_codes(&r), [unread], "{:?}", r.warnings); + let detail = &r.warnings[0].detail; + for part in [ + "pom.xml is of a model only Maven 4 reads", + "${maven.multiModuleProjectDirectory}", + "Set the line to -Daether.remoteRepositoryFilter.prefixes.basedir=\ + ${session.rootDirectory}/.mvn/socket-patch", + ] { + assert!(detail.contains(part), "{part}: {detail}"); + } + // The same line in a project that declares no Maven is read by + // every Maven 3 that reads the filter at all: nothing to say. + let mut undeclared = plain.clone(); + undeclared.insert(MVN_CONFIG.to_string(), define); + let r = run(&undeclared); + assert_eq!(r.files[MAVEN_FILTER], wired.files[MAVEN_FILTER]); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + } + + /// A directory line in the other spelling is respelled on the next + /// scan, in that one line, whatever the run redirects. Under + /// `${session.rootDirectory}` the line stops Maven 3.9.2 to 3.9.8 from + /// starting with `-f` from outside the project; a project that has + /// since declared Maven 4 gets the spelling Maven 4 reads. + #[test] + fn maven_filter_line_is_healed_whatever_the_run_redirects() { + use crate::formats::maven::repository_filter; + use RootDirectory::{Launcher, Session}; + let value = repository_filter::basedir_value; + let pom = pom_with_dep("\n 1.7.36", ""); + let run = |files: &BTreeMap| { + rewrite_registry_redirect(files, &[granted_maven_override()]) + }; + fn config_edits(r: &RewriteResult) -> Vec<(&str, &str, Option<&str>)> { + r.edits + .iter() + .filter(|e| e.path == MVN_CONFIG) + .map(|e| (e.kind.as_str(), e.action.as_str(), e.key.as_deref())) + .collect() + } + let respelled = [( + "redirect_maven_config", + "rewritten", + Some("repositoryFilterDirectory"), + )]; + let trade = "redirect_maven_repository_filter_maven3_only"; + let plain = BTreeMap::from([("pom.xml".to_string(), pom.clone())]); + let wired = run(&plain); + // An earlier run's wiring: the same files, the filter's directory + // under the session's property. + 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.clone()); + + let healed = run(&earlier); + assert_eq!(healed.files.keys().collect::>(), [MVN_CONFIG]); + assert_eq!(healed.files[MVN_CONFIG], wired.files[MVN_CONFIG]); + assert_eq!(config_edits(&healed), respelled); + // The project declares no Maven, so the heal trades the filter on + // Maven 4 for a build that starts everywhere, and says so. + assert_eq!(warning_codes(&healed), [trade], "{:?}", healed.warnings); + let said = &healed.warnings[0].detail; + for part in [ + "the repository filter's directory", + "Maven 3.9.2 to 3.9.8", + "Maven 3.9.2 and later 3.x ask each Socket repository for the patched version only", + "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() && rescan.warnings.is_empty()); + + // With no patch in the run at all (the dependency was bumped past + // it), and with the line alone, its switch since removed. + let mut bumped = earlier.clone(); + bumped.insert( + "pom.xml".to_string(), + pom_with_dep("\n 2.0.9", ""), + ); + let r = rewrite_registry_redirect(&bumped, &[]); + assert_eq!(r.files.keys().collect::>(), [MVN_CONFIG]); + assert_eq!(r.files[MVN_CONFIG], wired.files[MVN_CONFIG]); + assert_eq!(config_edits(&r), respelled); + assert_eq!(warning_codes(&r), [trade]); + let alone = format!("-T4\n{}\n", repository_filter::config_args(Session)[1]); + let mut lone = bumped.clone(); + lone.insert(MVN_CONFIG.to_string(), alone); + let r = rewrite_registry_redirect(&lone, &[]); + assert_eq!( + r.files[MVN_CONFIG], + format!("-T4\n{}\n", repository_filter::config_args(Launcher)[1]) + ); + // (The filter was off, so nothing was traded.) + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + + // A wrapper that names a Maven 3 which reads 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 r = run(&maven_3); + assert_eq!(r.files[MVN_CONFIG], wired.files[MVN_CONFIG]); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + + // A project that declares Maven 4 keeps the session's spelling, + // and the launcher's there is healed the other way, silently. + let mut maven_4 = earlier.clone(); + maven_4.insert( + MVN_WRAPPER_PROPERTIES.to_string(), + maven_wrapper("4.0.0-rc-7"), + ); + // (Its Trusted Checksums block is the launcher's here, so that one + // is healed; the filter's line is already right.) + let r = run(&maven_4); + assert_eq!( + config_edits(&r), + [( + "redirect_maven_config", + "rewritten", + Some(MVN_CONFIG_HEAL_KEY) + )] + ); + assert_eq!(repository_filter::form(&r.files[MVN_CONFIG]), Some(Session)); + maven_4.insert(MVN_CONFIG.to_string(), wired.files[MVN_CONFIG].clone()); + let r = run(&maven_4); + assert_eq!(repository_filter::form(&r.files[MVN_CONFIG]), Some(Session)); + assert_eq!( + config_edits(&r), + [ + ( + "redirect_maven_config", + "rewritten", + Some(MVN_CONFIG_HEAL_KEY) + ), + respelled[0], + ], + "both directories, one edit each" + ); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + + // Both in the session's spelling, as a project that declares no + // Maven would hold them: one run respells both and says what each + // trades away. + let mut both = earlier.clone(); + both.insert( + MVN_CONFIG.to_string(), + old.replace( + trusted_checksums::basedir_value(Launcher), + trusted_checksums::basedir_value(Session), + ), + ); + assert!(!both[MVN_CONFIG].contains("multiModuleProjectDirectory")); + let r = run(&both); + assert_eq!(r.files.keys().collect::>(), [MVN_CONFIG]); + assert_eq!(r.files[MVN_CONFIG], wired.files[MVN_CONFIG]); + assert_eq!( + warning_codes(&r), + ["redirect_maven_trusted_checksums_maven3_only", trade] + ); + } + + /// A caller that cannot write `.mvn/maven.config` takes the heal back + /// out, and the run goes on without it. That is only right where the + /// heal is the file's whole change: a run that also puts the filter's + /// lines in for a pin that lands has a write of its own to make, and + /// taking the file out would leave a filter file no line points at + /// and an edit that reports a write that was not made. + #[test] + fn maven_config_heal_is_withheld_only_where_it_is_the_whole_change() { + use crate::formats::maven::repository_filter; + use RootDirectory::{Launcher, Session}; + let pom = pom_with_dep("\n 1.7.36", ""); + let session_block = format!("{}\n", trusted_checksums::config_args(Session).join("\n")); + // A project an earlier release wired for another patch: its block + // in the session's spelling, no filter line. + let earlier = BTreeMap::from([ + ("pom.xml".to_string(), pom.clone()), + (MVN_CONFIG.to_string(), session_block.clone()), + ]); + let keys = |r: &RewriteResult| -> Vec> { + r.edits + .iter() + .filter(|e| e.path == MVN_CONFIG) + .map(|e| e.key.clone()) + .collect() + }; + + // Nothing to redirect: the heal is all the run writes there. + let mut alone = rewrite_registry_redirect(&earlier, &[]); + assert!(carries_maven_heal(&alone)); + assert!(withhold_maven_heal(&mut alone)); + assert!(alone.files.is_empty() && alone.edits.is_empty() && alone.warnings.is_empty()); + // The same for the filter's line on its own. + let filter_only = BTreeMap::from([ + ("pom.xml".to_string(), pom.clone()), + ( + MVN_CONFIG.to_string(), + format!("{}\n", repository_filter::config_args(Session).join("\n")), + ), + ]); + let mut alone = rewrite_registry_redirect(&filter_only, &[]); + assert_eq!( + keys(&alone), + [Some("repositoryFilterDirectory".to_string())] + ); + assert!(withhold_maven_heal(&mut alone)); + assert!(alone.files.is_empty() && alone.edits.is_empty() && alone.warnings.is_empty()); + + // A pin lands in the same run: the heal, then the filter's lines. + let mut both = rewrite_registry_redirect(&earlier, &[granted_maven_override()]); + assert_eq!( + keys(&both), + [ + Some(MVN_CONFIG_HEAL_KEY.to_string()), + Some("repositoryFilter".to_string()) ] ); + let written = both.files[MVN_CONFIG].clone(); + assert_eq!( + written, + format!( + "{}\n{}\n", + trusted_checksums::config_args(Launcher).join("\n"), + repository_filter::config_args(Launcher).join("\n") + ) + ); + let (edits, warnings) = (both.edits.len(), both.warnings.len()); + assert!( + !withhold_maven_heal(&mut both), + "the file has another write" + ); + assert_eq!(both.files[MVN_CONFIG], written); + assert!(both.files.contains_key(MAVEN_FILTER)); + assert_eq!((both.edits.len(), both.warnings.len()), (edits, warnings)); + } + + /// A run that takes the filter's lines out (its last filter file was + /// retired) reports the removal alone, also when the directory line + /// stood in the other spelling: a line that is gone was not respelled, + /// and nothing was traded for it. + #[test] + fn maven_filter_lines_in_the_other_spelling_go_with_the_last_file() { + use crate::formats::maven::repository_filter; + use RootDirectory::{Launcher, Session}; + let files = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let first = rewrite_poms_selecting( + &files, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))], + ); + let mut wired = files.clone(); + wired.extend(first.files.clone()); + let old = wired[MVN_CONFIG].replace( + repository_filter::basedir_value(Launcher), + repository_filter::basedir_value(Session), + ); + assert_ne!(old, wired[MVN_CONFIG]); + wired.insert(MVN_CONFIG.to_string(), old); + + let r = rewrite_poms_selecting( + &wired, + &[("a/pom.xml", Ok("2.0.9")), ("b/pom.xml", Ok("2.0.9"))], + ); + assert!(!r.files.contains_key(MAVEN_FILTER)); + assert_eq!( + r.files[MVN_CONFIG], + format!("{}\n", MVN_CONFIG_ARGS.join("\n")) + ); + let config_edits: Vec<_> = r + .edits + .iter() + .filter(|e| e.path == MVN_CONFIG) + .map(|e| (e.action.as_str(), e.key.as_deref())) + .collect(); + assert_eq!(config_edits, [("removed", Some("repositoryFilter"))]); + assert!( + !warning_codes(&r).contains(&"redirect_maven_repository_filter_maven3_only"), + "{:?}", + r.warnings + ); } /// A module with a `.mvn` of its own is reported on every scan, not @@ -13030,7 +14875,12 @@ mod tests { ); assert_eq!(r.edits[0].kind, "redirect_maven_property"); assert_eq!(r.edits[0].key.as_deref(), Some("slf4j.version")); - assert!(warning_codes(&r).is_empty(), "{:?}", r.warnings); + assert_eq!( + warning_codes(&r), + [MAVEN_FILTER_ENABLED], + "{:?}", + r.warnings + ); assert!(r.confirmed_maven_reactor_uuids.contains(MAVEN_UUID)); let sibling = " \n org.slf4j\n \ @@ -34479,8 +36329,12 @@ mod owned_pin_generation_matrix { gone: &str, ) -> (BTreeMap, RewriteResult) { let (wired, result) = plan(&files, first); + // (A first Maven pin adds the filter's two lines, and says so.) assert!( - result.warnings.is_empty(), + result + .warnings + .iter() + .all(|w| w.code == "redirect_maven_repository_filter_enabled"), "first pin: {:?}", result.warnings ); @@ -34490,7 +36344,11 @@ mod owned_pin_generation_matrix { ); let (repinned, result) = plan(&wired, second); assert!(result.warnings.is_empty(), "re-pin: {:?}", result.warnings); - for (path, text) in &repinned { + // (A filter file is never emptied: the superseded generation's + // stays as it is, read by no pom, until a rollback removes it.) + let retired = + |path: &str| crate::formats::maven::repository_filter::owned_rel(path).is_some(); + for (path, text) in repinned.iter().filter(|(path, _)| !retired(path)) { assert!( !text.contains(gone), "{path} kept the superseded generation `{gone}`:\n{text}" @@ -34731,6 +36589,23 @@ mod owned_pin_generation_matrix { let checksums = &repinned[MVN_CHECKSUMS]; assert!(!checksums.contains("aaaaaaaa"), "{checksums}"); assert_eq!(checksums.lines().count(), 2, "{checksums}"); + // The filter file follows its repository. The superseded one's is + // left as it was (a rewrite cannot remove a file, and no pom names + // its repository any more, so Maven does not read it), and the new + // repository is limited to the new version. + use crate::formats::maven::repository_filter::file_rel; + assert_eq!( + repinned[&file_rel(&format!("socket-patch-{A}"))] + .lines() + .last(), + Some("/org/apache/commons/commons-lang3/3.12.0-socket.aaaaaaaa") + ); + assert_eq!( + repinned[&file_rel(&format!("socket-patch-{B}"))] + .lines() + .last(), + Some("/org/apache/commons/commons-lang3/3.12.0-socket.bbbbbbbb") + ); } /// Another artifact's live pin whose uuid shares the superseded @@ -34875,7 +36750,17 @@ mod owned_pin_generation_matrix { let mut files = pom_project(); files.insert(MVN_CHECKSUMS.into(), format!("{}\n", user.join("\n"))); let (wired, result) = plan(&files, &maven(A, tok)); - assert!(result.warnings.is_empty(), "{:?}", result.warnings); + // (The first pin adds the filter's two lines, and says so.) + assert_eq!( + result + .warnings + .iter() + .map(|w| w.code.as_str()) + .collect::>(), + ["redirect_maven_repository_filter_enabled"], + "{:?}", + result.warnings + ); let (repinned, _) = plan(&wired, &maven(B, tok)); for (stage, tree) in [("pin", &wired), ("re-pin", &repinned)] { let checksums = &tree[MVN_CHECKSUMS]; diff --git a/crates/socket-patch-core/src/patch/redirect/staged.rs b/crates/socket-patch-core/src/patch/redirect/staged.rs index b2903acf3..057ffcba6 100644 --- a/crates/socket-patch-core/src/patch/redirect/staged.rs +++ b/crates/socket-patch-core/src/patch/redirect/staged.rs @@ -385,6 +385,12 @@ mod tests { /// A hosted Maven pin wired through three files, which the restore /// flushes in this order: [`SUMS`] (deleted), [`CONFIG`] (deleted), /// [`POM`] (rewritten). + /// + /// The config holds the Trusted Checksums settings and nothing else, + /// as a pin wired without the repository filter leaves it: removing + /// that file is part of the restore. (Taking the filter's two lines + /// out of a config is a courtesy the restore leaves undone where the + /// file cannot be written, so it would refuse nothing here.) fn maven_project() -> tempfile::TempDir { let tmp = tempfile::tempdir().unwrap(); for rel in [SUMS, CONFIG, POM] { @@ -396,6 +402,11 @@ mod tests { std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::copy(fixture, path).unwrap(); } + let config = tmp.path().join(CONFIG); + let wired = std::fs::read_to_string(&config).unwrap(); + let checksums_only = crate::formats::maven::repository_filter::strip_config(&wired) + .expect("the fixture is wired with the filter"); + std::fs::write(&config, checksums_only).unwrap(); tmp } 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 c2df56890..047cbfed1 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/maven.rs @@ -38,7 +38,7 @@ use super::{by_uuid, read_or_refuse, Ctx, FormatResult, HostedPin, View}; use crate::formats::maven::declared_maven::DeclaredMaven; use crate::formats::maven::trusted_checksums; use crate::patch::redirect::{ - generation, heal_trade_detail, maven_repositories_with_id, maven_tag_inner_range, + generation, heal_maven_config, 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, }; @@ -569,8 +569,10 @@ pub(crate) async fn restore( }) .collect(); dirs.insert(String::new()); + let unscoped = unscope(view, &restored, &texts, &reactor_poms, &mut result).await; for dir in dirs { - restore_mvn(view, &dir, &checksum_dirs, &mut result).await; + let unscoped = unscoped && dir.is_empty(); + restore_mvn(view, &dir, &checksum_dirs, unscoped, &mut result).await; } result .handled @@ -578,17 +580,113 @@ pub(crate) async fn restore( result } +/// Remove the repository filter files (`.mvn/socket-patch/`) of the +/// `restored` pins, and any whose repository no pom declares once the +/// restore is written: a scan writes files and never removes one, so a +/// patch it superseded or took out leaves its file behind. `true` when the +/// directory then holds nothing, so the resolver lines that point Maven at +/// it serve no file. +/// +/// A directory that cannot be listed to its end may hold anything: no +/// file in it is deleted, the lines stay, and the restore says so. +async fn unscope( + view: &mut View<'_>, + restored: &[&str], + texts: &BTreeMap, + reactor_poms: &BTreeMap, + result: &mut FormatResult, +) -> bool { + use crate::formats::maven::repository_filter; + let disk = crate::vendor::lock_inventory::ProjectView::Disk(view.root()); + let dir = crate::patch::redirect::hosted_maven_filter_dir(&disk).await; + if dir.unlistable { + result.warnings.push(( + MAVEN_FILTER_LEFT, + format!( + "{dir} could not be listed, so the repository filter files in it and the two \ + lines of {MVN_CONFIG} that name it were left as they are; remove them by hand \ + once the directory can be read, if nothing else needs them", + dir = repository_filter::DIR, + ), + )); + return false; + } + let declared = |id: &str| { + let after = texts.iter().chain( + reactor_poms + .iter() + .filter(|(rel, _)| !texts.contains_key(*rel)), + ); + after.into_iter().any(|(_, pom)| pom.contains(id)) + }; + // Anything in the directory that is not hosted mode's own file (a file + // of the user's, a subdirectory, a link) is left, and so are the lines. + let mut left = dir.others; + for rel in dir.owned { + let ours = rel + .rsplit('/') + .next() + .and_then(repository_filter::owned) + .and_then(|id| generation::pin_name_uuid(id, false).map(|uuid| (id, uuid))) + .is_some_and(|(id, uuid)| restored.contains(&uuid) || !declared(id)); + // Read first: the flush then knows the bytes it removes. + if ours && matches!(view.read(&rel).await, Ok(Some(_))) { + view.remove(&rel); + } else { + left = true; + } + } + !left +} + +/// The restore left something of the repository filter where it was, and +/// says what and why. +const MAVEN_FILTER_LEFT: &str = "maven_repository_filter_left"; + /// Drop the restored pins' trusted-checksum lines, and the `.mvn` files -/// themselves when nothing but hosted mode's content is left. A config -/// that stays is healed ([`heal_mvn_config`]). +/// themselves when nothing but hosted mode's content is left. With +/// `unscoped`, the repository filter's resolver lines go first: they name +/// a directory only hosted mode uses, so they are told from the user's. +/// A config that stays is healed ([`heal_mvn_config`]). async fn restore_mvn( view: &mut View<'_>, dir: &str, checksum_dirs: &[String], + unscoped: bool, result: &mut FormatResult, ) { let config_rel = format!("{dir}{MVN_CONFIG}"); - let config = view.read(&config_rel).await.ok().flatten(); + let mut config = view.read(&config_rel).await.ok().flatten(); + if unscoped { + let stripped = config + .as_deref() + .and_then(crate::formats::maven::repository_filter::strip_config); + // Taking the lines out is a courtesy, never the reason a restore + // is refused: the flush is all or nothing, and a config it would + // not write (a symbolic link, a directory that does not take the + // write, a file edited since it was read) keeps the lines. They + // then name a directory that holds no file, which filters nothing. + if let Some(rest) = stripped { + let staged = if rest.is_empty() { + view.remove_if_writable(&config_rel).await + } else { + view.write_if_writable(&config_rel, rest.clone()).await + }; + if staged { + config = Some(rest).filter(|rest| !rest.is_empty()); + } else { + result.warnings.push(( + MAVEN_FILTER_LEFT, + format!( + "{config_rel} could not be written, so it keeps the two repository \ + filter lines hosted mode added (`-Daether.remoteRepositoryFilter.…`); \ + the filter files they name were removed, so they filter nothing. \ + Remove them by hand if nothing else needs them" + ), + )); + } + } + } let removed = drop_checksums( view, dir, @@ -652,13 +750,15 @@ async fn drop_checksums( false } -/// The block hosted mode wrote into a `.mvn/maven.config` that stays +/// The lines 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`]). +/// `dir` declares ([`heal_maven_config`]: the Trusted Checksums block, and +/// the repository filter's directory line where a file of the user's keeps +/// it). They are left in place, but one that names its directory through +/// `${session.rootDirectory}` 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, @@ -666,10 +766,9 @@ async fn heal_mvn_config( config: &str, result: &mut FormatResult, ) { - use trusted_checksums::Basedir; - // The cheap test first: only a config that holds a block in either + // The cheap test first: only a config that holds such lines in either // spelling is worth reading the wrapper and the pom for. - if !trusted_checksums::holds_written_block(config) { + if !crate::formats::maven::holds_respellable_lines(config) { return; } // The flush refuses a write through a symbolic link, and the whole @@ -685,21 +784,19 @@ async fn heal_mvn_config( .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 { + let Some(healed) = heal_maven_config(config, &declared, dir) 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 { + if !view.write_if_writable(config_rel, healed.text).await { return; } - if let Some(detail) = trade { - result - .warnings - .push(("maven_trusted_checksums_maven3_only", detail)); + for (lines, trade) in healed.lines { + if let Some(detail) = trade { + result.warnings.push((lines.restore_trade(), detail)); + } } } @@ -1164,6 +1261,34 @@ mod tests { pin.uuid ); } + // A repository filter file lists the one version its repository + // serves, whether or not a pom still declares that repository: one + // that listed anything else, or nothing, would fail the build of a + // pin, also of one that comes back by a pom-only revert. A scan + // never empties a file. + use crate::formats::maven::repository_filter; + for (rel, text) in &tree { + let Some(id) = repository_filter::owned_rel(rel) else { + assert!(!rel.starts_with(".mvn/socket-patch/"), "{case}: {rel}"); + continue; + }; + let uuid = generation::pin_name_uuid(id, false).expect("a filter file"); + assert!( + repository_filter::lists( + text, + &format!("/org/slf4j/slf4j-api/1.7.36-socket.{}", &uuid[..8]) + ), + "{case}: {rel}: {text:?}" + ); + } + // And every pin a scan of this release wired has one. + let scoped = tree + .get(MVN_CONFIG) + .is_some_and(|config| config.contains(repository_filter::DIR)); + for pin in pins.iter().filter(|_| scoped) { + let rel = repository_filter::file_rel(&generation::hosted_pin_name(&pin.uuid)); + assert!(tree.contains_key(&rel), "{case}: no {rel}"); + } pins } @@ -1200,8 +1325,14 @@ mod tests { .iter() .map(|(rel, text)| (rel.to_string(), text.clone())) .collect(); - let suffixed_in = - |tree: &BTreeMap| tree.values().any(|text| text.contains("-socket.")); + // (A filter file a scan retired aside: it names its patch for as + // long as it stays, and no pom reads it.) + let retired = + |rel: &str| crate::formats::maven::repository_filter::owned_rel(rel).is_some(); + let suffixed_in = |tree: &BTreeMap| { + tree.iter() + .any(|(rel, text)| !retired(rel) && text.contains("-socket.")) + }; let tmp = tempfile::tempdir().unwrap(); write_tree(tmp.path(), files); @@ -1245,9 +1376,9 @@ mod tests { ); assert!( !read_tree(tmp.path()) - .values() - .any(|text| text.contains(&UUID[..8])), - "{case}: nothing of the first patch is left: {:#?}", + .iter() + .any(|(rel, text)| !retired(rel) && text.contains(&UUID[..8])), + "{case}: nothing of the first patch is left but its retired filter file: {:#?}", read_tree(tmp.path()) ); let again = scan(tmp.path(), NEWER, picks); @@ -1263,13 +1394,20 @@ mod tests { assert_eq!(after.get(rel), Some(text), "{case}: {rel}"); } // (A scan that took out the last pin itself cannot delete the - // `.mvn` files it once wrote: they stay, with no line of a patch.) + // `.mvn` files it once wrote: they stay, with no line of a patch, + // and the filter files as they were, which no pom reads.) for rel in after.keys().filter(|rel| !before.contains_key(*rel)) { assert!( - [MVN_CONFIG, MVN_CHECKSUMS].contains(&rel.as_str()), + [MVN_CONFIG, MVN_CHECKSUMS].contains(&rel.as_str()) || retired(rel), "{case}: {rel} is left over" ); } + assert!( + !after + .get(MVN_CONFIG) + .is_some_and(|config| config.contains(".mvn/socket-patch")), + "{case}: the lines that named the retired files went with the last pin" + ); } const REACTOR_ROOT: &str = "\n 4.0.0\n \ @@ -1803,6 +1941,348 @@ mod tests { ); } + /// A scan that met the user's own filter switch wrote no line and no + /// file beside it (`redirect_maven_repository_filter_conflict`). The + /// rollback of that pin must leave the switch: nothing marks it as + /// hosted mode's, and it was there before. + #[tokio::test] + async fn the_users_own_filter_switch_survives_a_rollback() { + let switch = "-Daether.remoteRepositoryFilter.prefixes=true"; + // What the scan left: the user's line, then the Trusted Checksums + // settings it appended. + let config = format!( + "{switch}\n{}\n", + super::trusted_checksums::CONFIG_ARGS.join("\n") + ); + let files = vec![ + ("pom.xml", fixture("basic", "expected", "pom.xml")), + (".mvn/maven.config", config.clone()), + ( + ".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); + assert_eq!(after["pom.xml"], fixture("basic", "input", "pom.xml")); + assert_eq!(after[".mvn/maven.config"], config); + // Nor the directory line of another filter directory of theirs. + let theirs = format!( + "{switch}\n-Daether.remoteRepositoryFilter.prefixes.basedir=\ + ${{session.rootDirectory}}/.mvn/rrf\n{}\n", + super::trusted_checksums::CONFIG_ARGS.join("\n") + ); + let mut files = files; + files[1].1 = theirs.clone(); + let (_, after) = run(&files).await; + assert_eq!(after[".mvn/maven.config"], theirs); + } + + /// The repository filter is taken out with its pin: the pin's file, a + /// file whose repository no pom declares any more (a scan retires one + /// and cannot remove it), and the two resolver lines, which name a + /// directory only hosted mode uses. A line of the user's stays where + /// it was, and so do the trusted-checksums lines beside it. + #[tokio::test] + async fn the_repository_filter_goes_with_its_pin() { + const FILTER: &str = + ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt"; + const RETIRED: &str = + ".mvn/socket-patch/prefixes-socket-patch-66666666-6666-4666-8666-666666666666.txt"; + let config = format!("-B\n{}", fixture("basic", "expected", ".mvn/maven.config")); + assert!(config.contains(".mvn/socket-patch"), "{config}"); + let tree = |more: &[(&'static str, String)]| { + let mut files = vec![ + ("pom.xml", fixture("basic", "expected", "pom.xml")), + (".mvn/maven.config", config.clone()), + ( + ".mvn/checksums/checksums.sha256", + fixture("basic", "expected", ".mvn/checksums/checksums.sha256"), + ), + (FILTER, fixture("basic", "expected", FILTER)), + (RETIRED, String::new()), + ]; + files.extend(more.iter().cloned()); + files + }; + let in_dir = |after: &BTreeMap| -> Vec { + after + .keys() + .filter(|rel| rel.starts_with(".mvn/socket-patch/")) + .cloned() + .collect() + }; + + let (outcome, after) = run(&tree(&[])).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + assert_eq!(after["pom.xml"], fixture("basic", "input", "pom.xml")); + assert_eq!(in_dir(&after), Vec::::new()); + assert_eq!( + after[".mvn/maven.config"], + format!("-B\n{}\n", super::trusted_checksums::CONFIG_ARGS.join("\n")) + ); + + // A file of the user's in that directory keeps the lines that make + // Maven read it. + const THEIRS: &str = ".mvn/socket-patch/prefixes-central.txt"; + let theirs = "## repository-prefixes/2.0\n/org\n".to_string(); + let (outcome, after) = run(&tree(&[(THEIRS, theirs)])).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + assert_eq!(in_dir(&after), [THEIRS]); + assert_eq!(after[".mvn/maven.config"], config); + } + + /// The filter's lines are hosted mode's in either spelling of their + /// directory: a rollback takes the session's out as it takes the + /// launcher's, byte for byte. Where a file of the user's keeps them, + /// the directory line that stays is respelled for the Maven the + /// project declares, like the Trusted Checksums block beside it, and + /// what that trades away on Maven 4 is said. + #[tokio::test] + async fn filter_lines_in_either_spelling_go_or_are_healed() { + use crate::formats::maven::declared_maven::RootDirectory::{Launcher, Session}; + use crate::formats::maven::{repository_filter, trusted_checksums}; + const FILTER: &str = + ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt"; + const THEIRS: &str = ".mvn/socket-patch/prefixes-central.txt"; + // (The fixture declares no Maven: both directories are named + // through the launcher's property.) + let wired = fixture("basic", "expected", ".mvn/maven.config"); + assert_eq!(repository_filter::form(&wired), Some(Launcher)); + let in_session = wired.replace( + repository_filter::basedir_value(Launcher), + repository_filter::basedir_value(Session), + ); + assert_eq!(repository_filter::form(&in_session), Some(Session)); + let tree = |config: &str, more: &[(&'static str, String)]| { + let mut files = vec![ + ("pom.xml", fixture("basic", "expected", "pom.xml")), + (".mvn/maven.config", config.to_string()), + ( + ".mvn/checksums/checksums.sha256", + fixture("basic", "expected", ".mvn/checksums/checksums.sha256"), + ), + (FILTER, fixture("basic", "expected", FILTER)), + ]; + files.extend(more.iter().cloned()); + files + }; + let codes = |outcome: &RestoreOutcome| -> Vec<&'static str> { + outcome.warnings.iter().map(|(code, _)| *code).collect() + }; + + // Nothing of the user's: all the scan wrote goes, whichever + // spelling the directory line stands in. + for config in [&wired, &in_session] { + let (outcome, after) = run(&tree(config, &[])).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + assert_eq!(after.keys().collect::>(), ["pom.xml"], "{config}"); + assert_eq!(after["pom.xml"], fixture("basic", "input", "pom.xml")); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); + } + + // The lines go and a setting of the user's keeps the config: what + // stays is the Trusted Checksums block, healed in the same restore + // (an earlier release's spelling here), and nothing is said about + // a filter line that is gone. + let both_in_session = format!( + "-B\n{}", + in_session.replace( + trusted_checksums::basedir_value(Launcher), + trusted_checksums::basedir_value(Session), + ) + ); + assert!(!both_in_session.contains("multiModuleProjectDirectory")); + let (outcome, after) = run(&tree(&both_in_session, &[])).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + assert_eq!( + after[".mvn/maven.config"], + format!("-B\n{}\n", trusted_checksums::CONFIG_ARGS.join("\n")) + ); + assert_eq!( + codes(&outcome), + [ + "maven_trusted_checksums_left", + "maven_trusted_checksums_maven3_only" + ], + "{:?}", + outcome.warnings + ); + + // A file of the user's in the directory keeps the lines. The one + // that names it through the session's property is respelled. + let theirs = (THEIRS, "## repository-prefixes/2.0\n/org\n".to_string()); + let (outcome, after) = run(&tree(&in_session, &[theirs.clone()])).await; + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + assert_eq!(after[".mvn/maven.config"], wired); + assert_eq!( + codes(&outcome), + [ + "maven_trusted_checksums_left", + "maven_repository_filter_maven3_only" + ], + "{:?}", + outcome.warnings + ); + let said = &outcome.warnings[1].1; + assert!( + said.contains("the repository filter's directory") + && said.contains("A Maven 4 build of this project no longer does"), + "{said}" + ); + + // This project's own spelling: the bytes are not touched. + let (outcome, after) = run(&tree(&wired, &[theirs.clone()])).await; + assert_eq!(after[".mvn/maven.config"], wired); + assert_eq!(codes(&outcome), ["maven_trusted_checksums_left"]); + + // A project that declares Maven 4 gets the spelling Maven 4 reads, + // for both directories, and nothing is traded. + let wrapper = ( + ".mvn/wrapper/maven-wrapper.properties", + "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/\ + apache-maven/4.0.0/apache-maven-4.0.0-bin.zip\n" + .to_string(), + ); + let (outcome, after) = run(&tree(&wired, &[theirs, wrapper])).await; + let config = &after[".mvn/maven.config"]; + assert_eq!(repository_filter::form(config), Some(Session), "{config}"); + assert_eq!( + trusted_checksums::Settings::read(config).basedir(), + Some(Session), + "{config}" + ); + assert_eq!(codes(&outcome), ["maven_trusted_checksums_left"]); + } + + /// Taking the filter's lines out is a courtesy, never the reason a + /// restore is refused. The flush is all or nothing, so a config it + /// would not write (here a symbolic link) keeps the lines: the pin is + /// restored all the same, the filter file goes, and the restore says + /// which lines it left. + #[cfg(unix)] + #[tokio::test] + async fn a_linked_config_keeps_the_filter_lines_and_refuses_no_restore() { + const FILTER: &str = + ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt"; + // The user's own line keeps the config a file of its own. + let config = format!("-B\n{}", fixture("basic", "expected", ".mvn/maven.config")); + assert!(config.contains(".mvn/socket-patch"), "{config}"); + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_tree( + root, + &[ + ("pom.xml", fixture("basic", "expected", "pom.xml")), + ( + ".mvn/checksums/checksums.sha256", + fixture("basic", "expected", ".mvn/checksums/checksums.sha256"), + ), + (FILTER, fixture("basic", "expected", FILTER)), + ("ci/maven.config", config.clone()), + ], + ); + 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(FILTER).exists(), "the pin's filter file goes"); + assert!(root.join(".mvn/maven.config").is_symlink()); + assert_eq!( + std::fs::read_to_string(root.join("ci/maven.config")).unwrap(), + config, + "the linked config is not written through" + ); + let left: Vec<&str> = outcome + .warnings + .iter() + .filter(|(code, _)| *code == "maven_repository_filter_left") + .map(|(_, detail)| detail.as_str()) + .collect(); + assert_eq!(left.len(), 1, "{:?}", outcome.warnings); + assert!( + left[0].contains(".mvn/maven.config could not be written") + && left[0].contains("they filter nothing"), + "{}", + left[0] + ); + } + + /// A filter directory that cannot be listed may hold anything: no file + /// in it is deleted and the lines that name it stay, the pin is + /// restored all the same, and the restore says what it left. (Root + /// reads anything, so there is nothing to see as root.) + #[cfg(unix)] + #[tokio::test] + async fn an_unlistable_filter_directory_is_left_and_said_so() { + use std::os::unix::fs::PermissionsExt as _; + if unsafe { libc::geteuid() } == 0 { + return; + } + const FILTER: &str = + ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt"; + let config = format!("-B\n{}", fixture("basic", "expected", ".mvn/maven.config")); + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_tree( + root, + &[ + ("pom.xml", fixture("basic", "expected", "pom.xml")), + (".mvn/maven.config", config.clone()), + ( + ".mvn/checksums/checksums.sha256", + fixture("basic", "expected", ".mvn/checksums/checksums.sha256"), + ), + (FILTER, fixture("basic", "expected", FILTER)), + ], + ); + let dir = root.join(".mvn/socket-patch"); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o000)).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(&dir, 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!(root.join(FILTER).is_file(), "nothing in it is deleted"); + let after = std::fs::read_to_string(root.join(".mvn/maven.config")).unwrap(); + assert!( + after.contains(".mvn/socket-patch"), + "the lines stay: {after}" + ); + assert!( + outcome.warnings.iter().any(|(code, detail)| { + *code == "maven_repository_filter_left" && detail.contains("could not be listed") + }), + "{:?}", + outcome.warnings + ); + } + /// 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 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 6341e44ad..578a6295c 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -752,19 +752,30 @@ impl<'a> View<'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 { + self.stage_if_writable(rel, Some(content)).await + } + + /// [`Self::write_if_writable`] for a removal. + pub(crate) async fn remove_if_writable(&mut self, rel: &str) -> bool { + self.stage_if_writable(rel, None).await + } + + /// Stage `content` for `rel` (`None`: its removal) only when the flush + /// could carry it out. + async fn stage_if_writable(&mut self, rel: &str, content: Option) -> 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()), + content: content.as_deref().map(str::as_bytes), read, }]; if preflight(self.root, pending).await.is_err() { return false; } - self.write(rel, content); + self.staged.insert(rel.to_string(), content); true } diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/basic/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/basic/expected-edits.json index ba20ca8b9..3ffbf4603 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/basic/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/basic/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/basic/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/basic/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/basic/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected-edits.json index 23df82ecd..0580ec615 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected-edits.json @@ -26,6 +26,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected-warnings.json index 414c0a5a5..0c115a0a6 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected-warnings.json @@ -1,4 +1,5 @@ [ "redirect_maven_classifier_unsupported", - "redirect_maven_dep_management_added" + "redirect_maven_dep_management_added", + "redirect_maven_repository_filter_enabled" ] 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-only-transitive-main/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected-edits.json index ba20ca8b9..3ffbf4603 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected-warnings.json index 7fa3ab269..c92d9fb82 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected-warnings.json @@ -1,3 +1,4 @@ [ - "redirect_maven_classifier_unsupported" + "redirect_maven_classifier_unsupported", + "redirect_maven_repository_filter_enabled" ] 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/classifier-sources-sibling/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected-edits.json index 23df82ecd..0580ec615 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected-edits.json @@ -26,6 +26,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected-warnings.json index fe7c5067d..e1ed0188b 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected-warnings.json @@ -1,3 +1,4 @@ [ - "redirect_maven_dep_management_added" + "redirect_maven_dep_management_added", + "redirect_maven_repository_filter_enabled" ] 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/comment-dependency/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected-edits.json index ba20ca8b9..3ffbf4603 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected-warnings.json index fe51488c7..e04e519ba 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected-warnings.json @@ -1 +1,3 @@ -[] +[ + "redirect_maven_repository_filter_enabled" +] 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/commented-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected-edits.json index 23df82ecd..0580ec615 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected-edits.json @@ -26,6 +26,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected-warnings.json index fe7c5067d..e1ed0188b 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected-warnings.json @@ -1,3 +1,4 @@ [ - "redirect_maven_dep_management_added" + "redirect_maven_dep_management_added", + "redirect_maven_repository_filter_enabled" ] 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/depmgmt-comment/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-depmgmt/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-depmgmt/expected-edits.json index ba20ca8b9..3ffbf4603 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-depmgmt/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-depmgmt/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-repositories/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-repositories/expected-edits.json index ba20ca8b9..3ffbf4603 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-repositories/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-repositories/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/existing-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 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 index 3a8160e03..399979945 100644 --- 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 @@ -23,6 +23,19 @@ "action": "rewritten", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "rewritten", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", 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 index 6825ca526..3fe5e7a04 100644 --- 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 @@ -1 +1,5 @@ -["redirect_maven_trusted_checksums_conflict", "redirect_maven_trusted_checksums_unenforced"] +[ + "redirect_maven_trusted_checksums_conflict", + "redirect_maven_repository_filter_enabled", + "redirect_maven_trusted_checksums_unenforced" +] 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 index e2dba7d24..9e6053683 100644 --- 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 @@ -4,3 +4,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${session.rootDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-launcher-line-conflict/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 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 index ba20ca8b9..3ffbf4603 100644 --- 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 @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", 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 index fe51488c7..e04e519ba 100644 --- 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 @@ -1 +1,3 @@ -[] +[ + "redirect_maven_repository_filter_enabled" +] 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 index d3b91570d..913ad0e02 100644 --- 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${session.rootDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${session.rootDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/maven4-model/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/mvn-config-merge/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/mvn-config-merge/expected-edits.json index 6ea0d4738..435dc9614 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/mvn-config-merge/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/mvn-config-merge/expected-edits.json @@ -23,6 +23,19 @@ "action": "rewritten", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "rewritten", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", 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 3d46044f7..6f4395517 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 @@ -5,3 +5,5 @@ -Daether.artifactResolver.postProcessor.trustedChecksums.failIfMissing=false -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/mvn-config-merge/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/mvn-config-merge/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/mvn-config-merge/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-edits.json index 81f6e0173..c633853a8 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-warnings.json index fe51488c7..e04e519ba 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected-warnings.json @@ -1 +1,3 @@ -[] +[ + "redirect_maven_repository_filter_enabled" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/maven.config index 4f1f947e8..1d18f03ce 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/maven.config @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/parent-in-checkout/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected-edits.json index ba20ca8b9..3ffbf4603 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected-warnings.json index fe51488c7..e04e519ba 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected-warnings.json @@ -1 +1,3 @@ -[] +[ + "redirect_maven_repository_filter_enabled" +] 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/plugin-dependency/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected-edits.json index 23df82ecd..0580ec615 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected-edits.json @@ -26,6 +26,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected-warnings.json index fe7c5067d..e1ed0188b 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected-warnings.json @@ -1,3 +1,4 @@ [ - "redirect_maven_dep_management_added" + "redirect_maven_dep_management_added", + "redirect_maven_repository_filter_enabled" ] 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected-edits.json index ba20ca8b9..3ffbf4603 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected-warnings.json index fe51488c7..e04e519ba 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected-warnings.json @@ -1 +1,3 @@ -[] +[ + "redirect_maven_repository_filter_enabled" +] 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/profile-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-edits.json index 1233a9a57..40df78d95 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-warnings.json index fe51488c7..e04e519ba 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected-warnings.json @@ -1 +1,3 @@ -[] +[ + "redirect_maven_repository_filter_enabled" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/maven.config index 4f1f947e8..1d18f03ce 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/maven.config @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-shared-sibling/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-edits.json index 6e5939b9a..d85597fd6 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-warnings.json index fe51488c7..e04e519ba 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected-warnings.json @@ -1 +1,3 @@ -[] +[ + "redirect_maven_repository_filter_enabled" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/maven.config index 4f1f947e8..1d18f03ce 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/maven.config @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/property-version/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-edits.json index 791f6cc83..5c58f8193 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-warnings.json index 44c9e80ea..ccc631b4c 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected-warnings.json @@ -1,3 +1,4 @@ [ - "redirect_maven_selection_undetermined" + "redirect_maven_selection_undetermined", + "redirect_maven_repository_filter_enabled" ] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/maven.config index 4f1f947e8..1d18f03ce 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/maven.config @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-module-literal/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-edits.json index 6e5939b9a..d85597fd6 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-warnings.json index 44c9e80ea..ccc631b4c 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected-warnings.json @@ -1,3 +1,4 @@ [ - "redirect_maven_selection_undetermined" + "redirect_maven_selection_undetermined", + "redirect_maven_repository_filter_enabled" ] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/maven.config index 4f1f947e8..1d18f03ce 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/maven.config +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/maven.config @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/reactor-root-property/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/expected-edits.json new file mode 100644 index 000000000..3a8160e03 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-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/repository-filter-conflict/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/expected-warnings.json new file mode 100644 index 000000000..0630523d4 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/expected-warnings.json @@ -0,0 +1,3 @@ +[ + "redirect_maven_repository_filter_conflict" +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/expected/.mvn/checksums/checksums.sha256 b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-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/repository-filter-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/repository-filter-conflict/expected/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/expected/.mvn/maven.config new file mode 100644 index 000000000..a5a2bc7f5 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/expected/.mvn/maven.config @@ -0,0 +1,8 @@ +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${session.rootDirectory}/.mvn/rrf +-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/repository-filter-conflict/expected/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/expected/pom.xml new file mode 100644 index 000000000..b5989daf3 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-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/repository-filter-conflict/input/.mvn/maven.config b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/input/.mvn/maven.config new file mode 100644 index 000000000..01e3b84f9 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/input/.mvn/maven.config @@ -0,0 +1,2 @@ +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${session.rootDirectory}/.mvn/rrf diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/input/pom.xml b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/input/pom.xml new file mode 100644 index 000000000..c38ca6357 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-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/repository-filter-conflict/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-conflict/overrides.json new file mode 100644 index 000000000..53deb25b8 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/repository-filter-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/self-closed-depmgmt/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected-edits.json index 23df82ecd..0580ec615 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected-edits.json @@ -26,6 +26,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected-warnings.json index fe7c5067d..e1ed0188b 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected-warnings.json @@ -1,3 +1,4 @@ [ - "redirect_maven_dep_management_added" + "redirect_maven_dep_management_added", + "redirect_maven_repository_filter_enabled" ] 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected-edits.json index ba20ca8b9..3ffbf4603 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected-warnings.json index fe51488c7..e04e519ba 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected-warnings.json @@ -1 +1,3 @@ -[] +[ + "redirect_maven_repository_filter_enabled" +] 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/self-closed-repositories/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/transitive-depmgmt/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/transitive-depmgmt/expected-edits.json index 23df82ecd..0580ec615 100644 --- a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/transitive-depmgmt/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/transitive-depmgmt/expected-edits.json @@ -26,6 +26,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-77777777-7777-7777-7777-777777777777", + "new": "/org/slf4j/slf4j-api/1.7.36-socket.77777777" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/transitive-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/transitive-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt new file mode 100644 index 000000000..a020296d1 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/maven/pom/transitive-depmgmt/expected/.mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-77777777-7777-7777-7777-777777777777 repository for this path only. +/org/slf4j/slf4j-api/1.7.36-socket.77777777 diff --git a/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected-edits.json b/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected-edits.json index 93724ee25..812f2a0b8 100644 --- a/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected-edits.json +++ b/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected-edits.json @@ -23,6 +23,19 @@ "action": "added", "key": "trustedChecksums" }, + { + "path": ".mvn/maven.config", + "kind": "redirect_maven_config", + "action": "added", + "key": "repositoryFilter" + }, + { + "path": ".mvn/socket-patch/prefixes-socket-patch-abcdef12-0000-4000-8000-000000000001.txt", + "kind": "redirect_maven_repository_filter", + "action": "added", + "key": "socket-patch-abcdef12-0000-4000-8000-000000000001", + "new": "/org/apache/commons/commons-lang3/3.11-socket.abcdef12" + }, { "path": ".mvn/checksums/checksums.sha256", "kind": "redirect_maven_trusted_checksums", diff --git a/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected-warnings.json index 6da55c8a8..ecb00b4d9 100644 --- a/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected-warnings.json +++ b/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected-warnings.json @@ -1,3 +1,4 @@ [ + "redirect_maven_repository_filter_enabled", "redirect_maven_pom_ignored_sbt_build" ] 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 4f1f947e8..1d18f03ce 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 @@ -4,3 +4,5 @@ -Daether.trustedChecksumsSource.summaryFile=true -Daether.trustedChecksumsSource.summaryFile.basedir=${maven.multiModuleProjectDirectory}/.mvn/checksums -Daether.trustedChecksumsSource.summaryFile.originAware=false +-Daether.remoteRepositoryFilter.prefixes=true +-Daether.remoteRepositoryFilter.prefixes.basedir=${maven.multiModuleProjectDirectory}/.mvn/socket-patch diff --git a/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected/.mvn/socket-patch/prefixes-socket-patch-abcdef12-0000-4000-8000-000000000001.txt b/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected/.mvn/socket-patch/prefixes-socket-patch-abcdef12-0000-4000-8000-000000000001.txt new file mode 100644 index 000000000..e0e90d548 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present/expected/.mvn/socket-patch/prefixes-socket-patch-abcdef12-0000-4000-8000-000000000001.txt @@ -0,0 +1,3 @@ +## repository-prefixes/2.0 +# Written by socket-patch: Maven asks the socket-patch-abcdef12-0000-4000-8000-000000000001 repository for this path only. +/org/apache/commons/commons-lang3/3.11-socket.abcdef12 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 9ba56a99f..019b07786 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 @@ -928,6 +928,51 @@ "elsewhere": [], "live_claims": [] }, + "redirect/maven/pom/repository-filter-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/repository-filter-conflict/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, "redirect/maven/pom/rerun-heals-basedir/expected": { "refs": [], "diagnostics": [], diff --git a/crates/socket-patch-core/tests/upstream_restore_golden.rs b/crates/socket-patch-core/tests/upstream_restore_golden.rs index 9bdc28d05..11002d28a 100644 --- a/crates/socket-patch-core/tests/upstream_restore_golden.rs +++ b/crates/socket-patch-core/tests/upstream_restore_golden.rs @@ -3711,10 +3711,14 @@ async fn maven_goldens_round_trip() { // the user's `` to hold its entry; the restore removes the entry and // leaves the equivalent empty `` (asserted in the upstream // maven unit tests). + // repository-filter-conflict: like mvn-config-merge, `.mvn/maven.config` + // existed (it configures Maven's prefix filter), so the trusted-checksums + // lines stay. let not_invertible = [ "mvn-config-merge", "maven4-launcher-line-conflict", "no-suffix-fallback", + "repository-filter-conflict", "self-closed-repositories", "self-closed-depmgmt", ]; @@ -3746,9 +3750,22 @@ async fn maven_config_merge_keeps_the_resolver_lines() { for rel in ["pom.xml", ".mvn/checksums/checksums.sha256"] { assert_eq!(after.get(rel), case.input.get(rel), "{rel}"); } - assert_eq!( - after.get(".mvn/maven.config"), - case.expected.get(".mvn/maven.config") + // The trusted-checksums lines stay: whether they were the user's is not + // recorded. The repository filter's two go, with its file: they name a + // directory only hosted mode uses. + let kept: String = case.expected[".mvn/maven.config"] + .lines() + .filter(|line| !line.contains("remoteRepositoryFilter")) + .map(|line| format!("{line}\n")) + .collect(); + assert_ne!(kept, case.expected[".mvn/maven.config"]); + assert_eq!(after.get(".mvn/maven.config"), Some(&kept)); + assert!( + !after + .keys() + .any(|rel| rel.starts_with(".mvn/socket-patch/")), + "{:?}", + after.keys() ); } diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 236ad6665..7e1c753da 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1180,6 +1180,78 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: 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. +* **The Socket repository is asked only for the patched version (hosted Maven 3.9.2+, + and Maven 4 in a project that declares it).** + Maven asks a `` a pom declares, before Maven Central, for every artifact + and parent pom its local repository does not hold yet. With each pin, hosted mode + therefore also writes a prefix file for + [Maven Resolver's remote repository filter](https://maven.apache.org/resolver/remote-repository-filtering.html), + `.mvn/socket-patch/prefixes-socket-patch-.txt`, listing the one path that + repository serves (`///-socket.`), and two lines + in `.mvn/maven.config` that switch the `prefixes` filter on and point it at + `.mvn/socket-patch`. Maven then asks the Socket repository for the patched version's + jar and pom and for nothing else, from the project root, a module directory or with + `-f /pom.xml` from outside the project. A repository with no file of its own + in that directory is not filtered. This needs **Maven 3.9.2 or later**. Before 3.9 the + two properties mean nothing, and 3.9.0 / 3.9.1 do not interpolate the directory, so + the file is never found: those builds run as before, unfiltered. Behind a mirror the + repository takes the mirror's id, so its file is not read and nothing is filtered. + - **The directory follows the project's Maven, like the checksums directory.** The + line names `.mvn/socket-patch` through `${maven.multiModuleProjectDirectory}`, which + no Maven 3 build fails on wherever it is started. Maven 4 does not read that + property, so a project that declares Maven 4 (a Maven Wrapper that pins it, or a + root pom of model 4.1.0) gets `${session.rootDirectory}` instead, the only form + Maven 4 reads; a Maven 4 build of a project that does not declare it runs + unfiltered. A line in the other spelling is respelled by the next hosted scan (and + by a `rollback` that leaves it), whatever the scan redirects: under + `${session.rootDirectory}` it stops Maven 3.9.2 to 3.9.8 from starting with `-f` + from outside the project. When that takes the filter away from a Maven 4 build of a + project that declares no Maven, `redirect_maven_repository_filter_maven3_only` + (`maven_repository_filter_maven3_only` on a rollback) says so. When the Maven + Wrapper pins a Maven older than 3.9.2, the files are written all the same and + `redirect_maven_repository_filter_unread` says that this Maven does not read them. + - **One directory per build.** The filter reads its files from one directory, so + once the two lines are committed every build of the project reads prefix files + from `.mvn/socket-patch/` only. The scan that adds the lines says so, once + (`redirect_maven_repository_filter_enabled`): a prefix file you keep anywhere else + (the local repository's default directory, say) is no longer read. Move it into + `.mvn/socket-patch/`, or name its directory on the build's command line + (`-Daether.remoteRepositoryFilter.prefixes.basedir=...`, which wins over + `maven.config`). + - **Left to whoever configured it.** When `.mvn/maven.config` or `.mvn/jvm.config` + already configures the prefix filter, or the environment of the machine that scans + does (`MAVEN_OPTS`, `MAVEN_ARGS`, `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS`), hosted + mode writes neither the lines nor the file and warns + `redirect_maven_repository_filter_conflict` for each patch; the pin still lands and + the Socket repository stays unfiltered. To filter it yourself, list the path the + warning names in a `prefixes-socket-patch-.txt` file of your own directory. + Only the scanning machine's environment is known: a flag a CI job passes is not. + - **Never in the way of a pin.** The filter is an extra. Where it cannot be written, + the pin lands without it and the scan says so + (`redirect_maven_repository_filter_skipped`): a `.mvn/maven.config` that is a + symbolic link or sits in a directory that does not take the write and does not hold + the two lines yet, or a link or a directory under the name of a pin's filter file. + - **Written with the pin.** A file that did not list the pinned version would fail + the build, so it is written from the pin's own coordinates, in the same run. A file + that is there and lists the path is left as it is, whatever its line endings and + whatever comment you added. A pin an earlier release wrote gets no file on a + re-scan (a re-run stays edit-free, as for the Trusted Checksums): `rollback`, then + `scan`, writes it. + - **Never emptied.** When a scan takes a Socket repository out of the poms (a newer + patch replaced it, or its last pin went), that repository's file stays exactly as + it is: a scan writes files and removes none. No pom names its repository, so Maven + does not read it, and it is the right file if the wiring comes back by a pom-only + revert or a merge. `rollback` and `remove` delete it. With the last such repository + gone, the scan takes the two lines out of `.mvn/maven.config`, unless the directory + holds a file of your own, which is read through those lines. + - **Taken out with the pin.** `rollback` and `remove` delete the files of the pins + they restore, and any whose repository no pom declares any more. Once the directory + is empty they also take the two lines out of `.mvn/maven.config`, byte for byte + (the lines name a directory only hosted mode uses, so they are told from yours); a + file of your own in that directory keeps them. A config they cannot write (a + symbolic link, say) keeps the lines too, and a directory they cannot list is left + whole; the pins are restored all the same, and `maven_repository_filter_left` says + what to remove by hand. * **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