diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 7501152c80..48ce9e23eb 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -473,7 +473,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), it is under the `--patch-mirror-url` / `SOCKET_PATCH_MIRROR_URL` base, or its host is 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. Since that respelling is decided by the file and by no dep, a Maven reason code that says *the run writes nothing for the dep* means that dep in that run: no pin in a pom, and no line or file under `.mvn/`, the checksum lines a malformed grant hash would drop included. It says nothing of wiring an earlier run left in the poms, nor of that one respelled line. 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 run writes nothing for the dep and it 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, and the run writes nothing for it, 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, and the run writes nothing for it, 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, and the run writes nothing for it: `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 the same way (`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)). Since that respelling is decided by the file and by no dep, a Maven reason code that says *the run writes nothing for the dep* means that dep in that run: no pin in a pom, and no line or file under `.mvn/`, the checksum lines a malformed grant hash would drop included. It says nothing of wiring an earlier run left in the poms, nor of a directory line respelled this way. 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 run writes nothing for the dep and it 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, and the run writes nothing for it, 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, and the run writes nothing for it, 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, and the run writes nothing for it: `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 the same way (`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. @@ -2088,7 +2088,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; a `CHECKSUMS` entry to re-pin for a gem whose upstream remote is neither rubygems.org nor the server `SOCKET_RUBYGEMS_URL` names (a `source` line naming a private gem server). That refusal names the setting (unless the remote is plain `http` to another host, which the setting refuses): with `SOCKET_RUBYGEMS_URL=` the entry is re-pinned from the server's own compact index and the pair is restored as for 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. @@ -2677,6 +2677,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 run writes nothing for the dep and it 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: the run writes nothing for the dep and it 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` 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), or the two lines would have to be added and `.mvn/jvm.config` or the environment of the scanning machine (`MAVEN_OPTS`, `MAVEN_ARGS`, `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS`) names that filter. 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. Also given, in words of its own, where hosted mode's directory line stands beside a switch set to anything but `true` (the filter is switched off, and stays so; the remedy is to remove that setting and scan again). Lines that are in place are no conflict, whatever `.mvn/jvm.config` or the environment says. 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`, or the switch alone beside a directory line of hosted mode's that stood there without it. 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), `.mvn/socket-patch` cannot take a file (it cannot be listed or written, or something that is not a directory stands under its name; once per run), or a link, a directory or a file that cannot be read stands under the name of the patch's filter file (once per patch). The Socket repository is not filtered. Also given for a pin in place whose filter file does not list the pinned path and could not be rewritten; the detail then says that Maven 3.9.2 and later refuse the pinned version over that file. 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; a filter file that could not be removed (it cannot be read, its directory does not take the write, or the file was edited since it was read), with the two lines; 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: the run writes nothing for the dep, and the dep is not counted as redirected or attested by the same run's `--vex`. Wiring an earlier run left in the poms stays in place; the detail then says so, says that a build behind the mirror fails on it, and names the command that takes it out (`socket-patch rollback `). 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. | @@ -3516,6 +3522,188 @@ 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 a file that lists + its path: a re-run writes nothing, and a pin of an earlier release gets no + file until it is rolled back and scanned again. A file that is there and + does not list the pinned path is the one thing a re-scan mends for a pin in + place (`redirect_maven_repository_filter`, `action` `rewritten`): with the + filter on, Maven 3.9.2 and later refuse the pinned version over it, and no + later scan would land the pin again to rewrite it. +* 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: lines in place are the project's own configuration, and a pin + that lands there gets its file whatever `.mvn/jvm.config` or the + environment of the scanning machine says. When `.mvn/maven.config` + already sets `aether.remoteRepositoryFilter.prefixes` or its `.basedir` + to anything else (in any spelling some Maven reads), nothing is written + for the filter. The same holds where the two lines would have to be added + and `.mvn/jvm.config` names the property, or 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). 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 directory line has one owner, hosted mode, for a scan as for the + respelling and for `rollback`, which takes the line out wherever it + stands. Where it names the directory Maven would read and no line sets + the switch, the switch went missing: the run of a pin that lands puts it + back, alone (`redirect_maven_config`, `key` `repositoryFilter`, and + `redirect_maven_repository_filter_enabled`), and writes the pin's file. + A switch set to anything but `true` is the user's, as it is for a + `rollback`, which leaves it: the filter is switched off and stays so, + nothing is written for it, and `redirect_maven_repository_filter_conflict` + says so for each patch in words of its own. +* 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 `.mvn/socket-patch` + cannot take a file (it cannot be listed or written, or something that is + not a directory stands under its name; where it is not there yet, the + directory it would be created in decides), no filter file is written and + the two lines are not added for one; said once per run. A file that is + there and lists its pin's path needs no write. When a link, a directory + or a file that cannot be read (in memory, one listed without its + content) stands under the name of a pin's filter file, that file is not + written; said for that patch. Before, each of these 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. As on a rollback, the + switch stays where a later line names another directory. +* `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. + Nor is it where a later line names another directory: the user has taken + the filter over, and only the `.mvn/socket-patch` line, which Maven no + longer reads, is taken out. +* 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 + filter file the restore could not remove (it cannot be read, its + directory does not take the write, or the file was edited since it was + read) stays, and the two lines with it; no pom declares its repository + any more, so Maven does not read it. 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 @@ -3566,7 +3754,8 @@ then says so and names the command that takes the wiring out file is touched for a gated dep, `.mvn/checksums/checksums.sha256` included. The other patches of the run are unaffected. So is the respelling of a `.mvn/maven.config` line an earlier release wrote (`redirect_maven_config`, -`key: "trustedChecksumsDirectory"`): the file decides it, not a dep, so a run +`key: "trustedChecksumsDirectory"`, or `"repositoryFilterDirectory"` for the +repository filter's directory line): the file decides it, not a dep, so a run that gates every Maven patch makes it all the same. The gate applies only where a repository is at stake. A dep the rewriter diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 80f7065e06..bded691774 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -1994,6 +1994,24 @@ 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. Nor is one of its own files + // that cannot be read: the restore leaves such a file where it is, + // and it must not refuse the eject of every pin. + let disk = socket_patch_core::vendor::lock_inventory::ProjectView::Disk(root); + let filters = socket_patch_core::patch::redirect::hosted_maven_filter_dir(&disk).await; + for rel in filters.owned { + let path = root.join(&rel); + if socket_patch_core::utils::fs::read_regular_to_bytes(&path) + .await + .is_ok() + { + planned.insert(rel); + } + } let mut files = std::collections::BTreeMap::new(); for rel in root_files.iter().chain(planned.iter()) { if files.contains_key(rel) { @@ -9312,6 +9330,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_bazel_build/maven.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs index 40d0eaafaf..0a4d278c8e 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs @@ -181,15 +181,25 @@ const PLACEHOLDER: &str = "http://socket-fixture.invalid/maven2"; /// The route prefixes of the stand-in, one per host it plays. const UPSTREAM: &str = "maven2"; const PATCH_HOST: &str = "patch.socket.dev"; -/// The file of the block, and the files hosted mode writes in a checkout -/// that Maven builds too: those of a Maven pin, and that one. +/// The file of the block. const MODULE: &str = "MODULE.bazel"; -const PINNED: [&str; 4] = [ - ".mvn/checksums/checksums.sha256", - ".mvn/maven.config", - MODULE, - "pom.xml", -]; +/// The warning of the run that switches Maven's repository filter on, which +/// the first Maven pin of a checkout does. +const FILTER_ENABLED: &str = "redirect_maven_repository_filter_enabled"; + +/// The files hosted mode writes for the patch `uuid` in a checkout that +/// Maven builds too: those of a Maven pin (the pom, the Trusted Checksums +/// and the repository filter file of the patch's own repository), and the +/// file of the block. +fn pinned_files(uuid: &str) -> [String; 5] { + [ + ".mvn/checksums/checksums.sha256".to_string(), + ".mvn/maven.config".to_string(), + format!(".mvn/socket-patch/prefixes-socket-patch-{uuid}.txt"), + MODULE.to_string(), + "pom.xml".to_string(), + ] +} /// What the command says after its reason when it writes no entry. const KEEPS: &str = "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps \ the upstream jar"; @@ -692,16 +702,29 @@ impl Pinned { self.pinned(&get, &self.patch, before, files) } + /// [`Pinned::pins`] in a checkout that Maven builds too: the command + /// writes the files of a Maven pin and the block ([`pinned_files`]). + fn pins_the_pom_too(&self, before: &Tree) -> Tree { + let files = pinned_files(&self.patch.uuid); + self.pins(before, &files.each_ref().map(String::as_str)) + } + /// What a finished hosted command did for `patch`: it reports the /// patch applied, rewrote `files` and no other file of `before`, and - /// gave no warning. `MODULE.bazel` is the one of before with the block - /// after one blank line, and nothing has asked for the patched jar - /// yet. Gives the files of the checkout. + /// gave no warning but the one of a Maven pin that switches Maven's + /// repository filter on ([`FILTER_ENABLED`]). `MODULE.bazel` is the one + /// of before with the block after one blank line, and nothing has + /// asked for the patched jar yet. Gives the files of the checkout. fn pinned(&self, ran: &Ran, patch: &Granted, before: &Tree, files: &[&str]) -> Tree { let (test, said) = (&self.cell.test, &ran.dump); let purl = format!("pkg:maven/{GROUP}/{VICTIM}@{}", patch.version); let pinned = self.cell.pinned_by(ran, &purl, &patch.uuid, before, files); - assert_eq!(ran.envelope["warnings"], Value::Null, "{test}: {said}"); + let warned: &[&str] = match files.contains(&"pom.xml") { + true => &[FILTER_ENABLED], + false => &[], + }; + let warnings = &ran.envelope["warnings"]; + assert_eq!(codes_in(warnings), warned, "{test}: {said}"); let text = |tree: &Tree| String::from_utf8(tree[MODULE].clone()).expect("a text file"); let with_block = format!("{}\n{}", text(before), block(patch)); assert_eq!(text(&pinned), with_block, "{test}: {said}"); @@ -849,8 +872,8 @@ fn a_pom_patch_beside_a_pinned_hub() { flow.builds_upstream(); let before = flow.names_its_bazel(); - // The three files of a Maven pin, and the block for the hub. - let pinned = flow.pins(&before, &PINNED); + // The files of a Maven pin, and the block for the hub. + let pinned = flow.pins_the_pom_too(&before); flow.builds_patched(&pinned); let undo = flow.socket_patch(&["rollback", "--yes"]); @@ -1522,7 +1545,7 @@ fn an_agent_patch_beside_a_pinned_hub() { // (d) What the documents say to run: the build is patched, and the // document says so. - let pinned = flow.pins(&patched, &PINNED); + let pinned = flow.pins_the_pom_too(&patched); flow.builds_patched(&pinned); let run = |cell: &Cell, args: &[&str]| flow.socket_patch_in(cell, &flow.standin, args); let hosted = Claim::new(PURL, &flow.patch.uuid, How::Hosted); diff --git a/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs b/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs index 08244faea5..bc17d37d0e 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs @@ -685,12 +685,19 @@ fn a_hub_only_tree_says_why_the_hub_is_not_patched() { } } -/// The files of a Maven pin, and the block's. -const POM_FILES: [&str; 3] = [ +/// The files of a Maven pin, and the block's. The pin's repository filter +/// file is named for the patch ([`UUID`]). +const POM_FILES: [&str; 4] = [ "proj/.mvn/checksums/checksums.sha256", "proj/.mvn/maven.config", + "proj/.mvn/socket-patch/prefixes-socket-patch-5e0a7c1d-7b4e-4c1a-9f0e-2a3b4c5d6e7f.txt", "proj/pom.xml", ]; +/// What the run that writes the first Maven pin of a checkout warns of: it +/// switched Maven's repository filter on in `.mvn/maven.config`. It comes +/// before what the run says of the hub, and a run that writes for the hub +/// alone does not give it. +const FILTER_ENABLED: &str = "redirect_maven_repository_filter_enabled"; const MODULE: &str = "proj/MODULE.bazel"; #[test] @@ -720,7 +727,9 @@ fn a_pinned_hub_gets_its_block_and_the_undo_takes_it_out() { "{dry:?}" ); - // The run: applied, no warning, the block after one blank line. + // The run: applied, no warning of the hub (a Maven pin says that + // it switched the repository filter on), the block after one blank + // line. let get = machine.step(COMMANDS[0]); let envelope = get.envelope(); assert_eq!(get.code, Some(0), "{get:?}"); @@ -730,7 +739,11 @@ fn a_pinned_hub_gets_its_block_and_the_undo_takes_it_out() { json!(rewritten), "{get:?}" ); - assert_eq!(envelope["warnings"], Value::Null, "{get:?}"); + assert_eq!( + warning_codes(&envelope), + [FILTER_ENABLED][..usize::from(maven)], + "{get:?}" + ); assert_eq!(get.wrote.keys().collect::>(), files, "{get:?}"); assert_eq!( String::from_utf8_lossy(&get.wrote[MODULE]), @@ -855,7 +868,8 @@ fn a_hosted_run_removes_the_jar_vendored_mode_kept_for_the_hub() { vendored(&machine, true); let ran = machine.step(command); assert_eq!(ran.code, Some(0), "{ran:?}"); - assert_eq!(ran.envelope()["warnings"], Value::Null, "{ran:?}"); + // (Nothing of the hub: the run pins the Maven build beside it.) + assert_eq!(warning_codes(&ran.envelope()), [FILTER_ENABLED], "{ran:?}"); let with_block = format!("{HUB}\n{BLOCK}"); assert_eq!( String::from_utf8_lossy(&ran.wrote[MODULE]), @@ -961,14 +975,14 @@ fn the_hub_gets_its_block_whatever_the_maven_pin_is() { vec![("pom.xml", root.to_string()), ("app/pom.xml", module)], &["app/pom.xml", "pom.xml"], None, - &[], + &[FILTER_ENABLED], ), ( "a property", vec![("pom.xml", property)], &["pom.xml"], None, - &[], + &[FILTER_ENABLED], ), ( "a mirror", @@ -996,12 +1010,12 @@ fn the_hub_gets_its_block_whatever_the_maven_pin_is() { "{shape}: {get:?}" ); assert_eq!(warning_codes(&envelope), warns, "{shape}: {get:?}"); - // The block, the poms of the pin, and the checksum files of a - // Maven pin when there is one. + // The block, the poms of the pin, and the `.mvn` files of a Maven + // pin when there is one: its checksums and its repository filter. let pin: Vec<&str> = [&["MODULE.bazel"], pinned_poms].concat(); let mut wrote: Vec = pin.iter().map(|file| format!("proj/{file}")).collect(); - let checksums = &POM_FILES[..2 * usize::from(!pinned_poms.is_empty())]; - wrote.extend(checksums.iter().map(|file| file.to_string())); + let mvn = &POM_FILES[..3 * usize::from(!pinned_poms.is_empty())]; + wrote.extend(mvn.iter().map(|file| file.to_string())); wrote.sort_unstable(); assert_eq!( get.wrote.keys().collect::>(), @@ -1124,8 +1138,11 @@ fn a_decline_writes_nothing_for_the_hub_and_says_why() { files, "{code}: {ran:?}" ); - assert_eq!(warning_codes(&envelope), [*code], "{ran:?}"); - let detail = envelope["warnings"][0]["detail"] + // The Maven pin that lands says its own line first. + let codes = [FILTER_ENABLED, *code]; + let of_the_hub = 1 - usize::from(maven); + assert_eq!(warning_codes(&envelope), codes[of_the_hub..], "{ran:?}"); + let detail = envelope["warnings"][usize::from(maven)]["detail"] .as_str() .expect("its text"); let said = detail.starts_with(PURL) && detail.contains(why) && detail.ends_with(KEEPS); @@ -1233,13 +1250,17 @@ fn a_decline_names_the_entry_of_another_patch_that_remains() { assert_eq!(ran.code, Some(0), "{ran:?}"); assert_eq!(event_for(&envelope, PURL)["action"], action, "{ran:?}"); assert_eq!(ran.wrote.keys().collect::>(), wrote, "{ran:?}"); - assert_eq!(warning_codes(&envelope), ["maven_bazel_release"], "{ran:?}"); + // The Maven pin that lands says its own line first. + let codes = [FILTER_ENABLED, "maven_bazel_release"]; + let of_the_hub = 1 - usize::from(maven); + assert_eq!(warning_codes(&envelope), codes[of_the_hub..], "{ran:?}"); let remains = format!( "{PURL}: {NO_RELEASE}. socket-patch wrote nothing to MODULE.bazel for it: the entry \ of patch {other} remains there, and where the block is in effect the Bazel build \ takes that patch's jar" ); - assert_eq!(envelope["warnings"][0]["detail"], remains, "{ran:?}"); + let said = &envelope["warnings"][usize::from(maven)]["detail"]; + assert_eq!(*said, remains, "{ran:?}"); } } @@ -1647,7 +1668,7 @@ fn a_hosted_scan_takes_a_stale_entry_out_of_the_block() { // Beside a `pom.xml` that still selects the release: the pin of the // Maven build stays, and the entry alone goes. machine.make(&pinned(), true, false); - assert_eq!(machine.step(COMMANDS[0]).wrote.len(), 4); + assert_eq!(machine.step(COMMANDS[0]).wrote.len(), 1 + POM_FILES.len()); std::fs::write(machine.root.join("proj/maven_install.json"), &moved).expect("the lock"); let scan = machine.step(&SCAN); assert_eq!(scan.wrote.keys().collect::>(), [MODULE], "{scan:?}"); @@ -1822,8 +1843,11 @@ fn a_hosted_scan_leaves_a_stale_entry_of_vendored_mode() { }; let purls = event_triples(&said).into_iter().map(|(purl, ..)| purl); assert_eq!(purls.collect::>(), pins, "{maven}: {scan:?}"); + // (Nothing of the hub: beside it the scan pins the Maven build.) let codes = warning_codes(&said); - assert_eq!((scan.code, codes), (Some(0), vec![]), "{maven}: {scan:?}"); + let pin = [FILTER_ENABLED][..usize::from(maven)].to_vec(); + assert_eq!(scan.code, Some(0), "{maven}: {scan:?}"); + assert_eq!(codes, pin, "{maven}: {scan:?}"); assert_eq!(of_the_hub(&machine), held, "{maven}: {scan:?}"); } } diff --git a/crates/socket-patch-cli/tests/e2e_maven_filter_cli.rs b/crates/socket-patch-cli/tests/e2e_maven_filter_cli.rs new file mode 100644 index 0000000000..54e0984a2f --- /dev/null +++ b/crates/socket-patch-cli/tests/e2e_maven_filter_cli.rs @@ -0,0 +1,466 @@ +#![cfg(unix)] +//! The Maven repository filter through the CLI, without a Maven: what a +//! hosted run and its undo do where the filter cannot be had. +//! +//! The filter is an extra. A hosted pin lands with it or without it, and +//! an undo restores the pin whether or not it can take the filter out. The +//! tests here hold the binary to that where the files of the filter are in +//! the way, and they need no Maven: a command of hosted mode reads and +//! writes the checkout and never starts a build. +//! +//! - The directory of the filter files, `.mvn/socket-patch`, takes no +//! file: a regular file stands under its name, or it is a directory that +//! cannot be written, or not even listed. The run used to fail on the +//! write of the filter file and put every other write back +//! (`lockfile_write_failed`, exit 1). It lands the pin, writes nothing +//! for the filter and says so. +//! - `.mvn` itself does not take a write, so the filter's two lines +//! cannot be added to `.mvn/maven.config`. The same failure, and the +//! same answer. +//! - A filter file cannot be removed, because its directory does not take +//! the write. `rollback` and `remove` used to be refused whole. They +//! restore the pin, leave the file and the lines that name its +//! directory, and say what they left. +//! +//! Root writes into any directory, so the cases that rest on a mode are +//! skipped for root. + +#[path = "common/envelope.rs"] +mod envelope; +#[path = "hosted_memory_common/mod.rs"] +mod hosted_memory_common; + +use std::collections::BTreeMap; +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; + +use envelope::{event_for, warning_codes}; +use hosted_memory_common::{hermetic, mount_api, read_tree, Patch, ORG}; +use serde_json::{json, Value}; + +const PURL: &str = "pkg:maven/dev.socket.fixture/victim@1.10.0"; +const UUID: &str = "5e0a7c1d-7b4e-4c1a-9f0e-2a3b4c5d6e7f"; +const SUFFIXED: &str = "1.10.0-socket.5e0a7c1d"; +/// The artifact's own pom, as a build of the checkout leaves it in the +/// Maven local repository: what Maven selects is read from there. +const POM: &str = + "4.0.0dev.socket.fixture\ + victim1.10.0\n"; +/// The checkout's pom, which declares the artifact. +const PROJECT_POM: &str = "\n 4.0.0\n \ + com.example\n app\n \ + 1\n \n \n \ + dev.socket.fixture\n \ + victim\n 1.10.0\n \ + \n \n\n"; + +/// The directory of the filter files, and the one of the patch. +const DIR: &str = ".mvn/socket-patch"; +const FILTER: &str = + ".mvn/socket-patch/prefixes-socket-patch-5e0a7c1d-7b4e-4c1a-9f0e-2a3b4c5d6e7f.txt"; +const CONFIG: &str = ".mvn/maven.config"; +const CHECKSUMS: &str = ".mvn/checksums/checksums.sha256"; + +const GET: [&str; 6] = ["get", PURL, "--mode", "hosted", "--yes", "--json"]; + +/// What one run of `socket-patch` gave. (`stderr` is there for the message +/// of an assertion that fails, which prints the whole run.) +#[derive(Debug)] +struct Ran { + code: Option, + stdout: String, + #[allow(dead_code)] + stderr: String, +} + +impl Ran { + fn envelope(&self) -> Value { + serde_json::from_str(&self.stdout).unwrap_or_else(|e| panic!("no envelope ({e}): {self:?}")) + } +} + +/// One checkout with a `pom.xml`, the Maven local repository a build of it +/// left, and the Socket API of the patch. +struct Machine { + root: PathBuf, + api: wiremock::MockServer, + // The server runs on it. + _runtime: tokio::runtime::Runtime, + _tmp: tempfile::TempDir, +} + +impl Machine { + fn start() -> Machine { + let tmp = tempfile::tempdir().expect("a directory"); + let root = tmp.path().canonicalize().expect("its real path"); + let runtime = tokio::runtime::Runtime::new().expect("a runtime"); + let api = runtime.block_on(wiremock::MockServer::start()); + // The grant of the hosted patch: the maven2 registry override of + // production, with the version only that registry serves. + let index = format!("https://patch.socket.dev/patch-registry/maven/token/{UUID}/maven2"); + let url = + format!("https://patch.socket.dev/patch/maven/token/{UUID}/victim-{SUFFIXED}.jar"); + let reference = json!({ + "status": "granted", + "url": url, + "purl": PURL, + "artifacts": [{ "kind": "tarball", "url": url, "integrity": { "sha256": "a".repeat(64) } }], + "registryOverride": { "kind": "maven2", "indexUrl": index, "identifiers": { + "name": "dev.socket.fixture/victim", + "version": "1.10.0", + "mavenGroupId": "dev.socket.fixture", + "mavenArtifactId": "victim", + "mavenSuffixedVersion": SUFFIXED, + "mavenPomSha256": "b".repeat(64), + } }, + }); + let patch = Patch { + purl: PURL.to_string(), + uuid: UUID.to_string(), + reference, + }; + runtime.block_on(mount_api(&api, &[patch])); + Machine { + root, + api, + _runtime: runtime, + _tmp: tmp, + } + } + + fn proj(&self) -> PathBuf { + self.root.join("proj") + } + + /// Makes the checkout anew: its `pom.xml`, and the artifact's pom in + /// the Maven local repository. + fn make(&self) { + for dir in ["proj", "m2", "home"] { + let _ = std::fs::remove_dir_all(self.root.join(dir)); + } + let write = |path: PathBuf, text: &str| { + std::fs::create_dir_all(path.parent().expect("a directory")).expect("create it"); + std::fs::write(&path, text).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + }; + std::fs::create_dir_all(self.proj().join(".git")).expect("a checkout"); + write(self.proj().join("pom.xml"), PROJECT_POM); + write( + self.root + .join("m2/dev/socket/fixture/victim/1.10.0/victim-1.10.0.pom"), + POM, + ); + } + + /// Runs `socket-patch ` in the checkout. Nothing of the machine + /// reaches the child: no tool on `PATH`, an empty home, and the Maven + /// local repository of this directory. + fn step(&self, args: &[&str]) -> Ran { + let mut cmd = hermetic::binary_command(); + cmd.env_clear() + .envs(hermetic::FORCED_OPT_OUTS.iter().copied()); + for keep in ["TMPDIR", "TEMP", "TMP", "LLVM_PROFILE_FILE"] { + cmd.envs(std::env::var_os(keep).map(|value| (keep, value))); + } + let home = self.root.join("home"); + std::fs::create_dir_all(&home).expect("a home"); + cmd.current_dir(self.proj()) + .env("PATH", "") + .env("HOME", &home) + .env("MAVEN_REPO_LOCAL", self.root.join("m2")) + .env("GRADLE_USER_HOME", home.join("gradle")) + .env("COURSIER_CACHE", home.join("coursier")) + .args(args) + .args(["--org", ORG, "--api-token", "fake-token"]) + .args(["--api-url", &self.api.uri()]); + let out = cmd.output().expect("spawn socket-patch"); + Ran { + code: out.status.code(), + stdout: String::from_utf8_lossy(&out.stdout).into_owned(), + stderr: String::from_utf8_lossy(&out.stderr).into_owned(), + } + } + + /// The files of the checkout, as text. + fn files(&self) -> BTreeMap { + let files = read_tree(&self.proj()).into_iter(); + files + .filter(|(path, _)| !path.starts_with(".git/") && !path.starts_with(".socket/")) + .map(|(path, bytes)| (path, String::from_utf8_lossy(&bytes).into_owned())) + .collect() + } +} + +fn root_user() -> bool { + // SAFETY: geteuid has no preconditions and cannot fail. + unsafe { libc::geteuid() == 0 } +} + +fn set_mode(path: &Path, mode: u32) { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)) + .unwrap_or_else(|e| panic!("chmod {mode:o} {}: {e}", path.display())); +} + +/// Control: with nothing in the way the pin lands with its filter file +/// and the two lines, and the undo leaves the checkout as it was. +#[test] +fn a_hosted_run_writes_the_filter_with_the_pin_and_the_undo_takes_it_out() { + let machine = Machine::start(); + machine.make(); + let before = machine.files(); + let get = machine.step(&GET); + let envelope = get.envelope(); + assert_eq!(get.code, Some(0), "{get:?}"); + assert_eq!(event_for(&envelope, PURL)["action"], "applied", "{get:?}"); + assert_eq!( + envelope["redirect"]["rewrittenFiles"], + json!([CHECKSUMS, CONFIG, FILTER, "pom.xml"]), + "{get:?}" + ); + assert_eq!( + warning_codes(&envelope), + ["redirect_maven_repository_filter_enabled"], + "{get:?}" + ); + let undo = machine.step(&["rollback", "--yes", "--json"]); + assert_eq!(undo.code, Some(0), "{undo:?}"); + assert_eq!(machine.files(), before, "{undo:?}"); + // Nor is the directory the run made left behind, empty: to Maven an + // empty `.mvn` marks the root directory of a project. + assert!(!machine.proj().join(".mvn").exists(), "{undo:?}"); +} + +/// `.mvn` itself does not take a write, in a checkout that holds the +/// Trusted Checksums settings and not the filter's two lines (an earlier +/// scan's, say): the lines cannot be added. The pin lands all the same, +/// without the filter, and the run says so. It used to plan the lines, +/// fail on the write and put everything back. +#[test] +fn a_hosted_run_lands_the_pin_where_dot_mvn_takes_no_write() { + if root_user() { + return; + } + let machine = Machine::start(); + machine.make(); + assert_eq!(machine.step(&GET).code, Some(0)); + // The checkout as that scan would have left it without the filter, + // its pin since taken out of the pom: the settings and the checksums + // of the artifact are in place, the filter's directory is there. + let proj = machine.proj(); + let wired = machine.files(); + let without_the_filter: String = wired[CONFIG] + .lines() + .filter(|line| !line.contains("remoteRepositoryFilter")) + .map(|line| format!("{line}\n")) + .collect(); + assert_ne!(without_the_filter, wired[CONFIG]); + std::fs::write(proj.join(CONFIG), &without_the_filter).expect("the config"); + std::fs::remove_file(proj.join(FILTER)).expect("the filter file"); + std::fs::write(proj.join("pom.xml"), PROJECT_POM).expect("the pom"); + + let dot_mvn = proj.join(".mvn"); + set_mode(&dot_mvn, 0o555); + let get = machine.step(&GET); + set_mode(&dot_mvn, 0o755); + let envelope = get.envelope(); + assert_eq!(get.code, Some(0), "{get:?}"); + assert_eq!(envelope["status"], "success", "{get:?}"); + assert_eq!(event_for(&envelope, PURL)["action"], "applied", "{get:?}"); + assert_eq!( + envelope["redirect"]["rewrittenFiles"], + json!(["pom.xml"]), + "{get:?}" + ); + assert_eq!( + warning_codes(&envelope), + ["redirect_maven_repository_filter_skipped"], + "{get:?}" + ); + let detail = envelope["warnings"][0]["detail"] + .as_str() + .expect("its text"); + assert!( + detail.starts_with(".mvn/maven.config cannot be written"), + "{detail}" + ); + let pinned = machine.files(); + assert_eq!(pinned["pom.xml"], wired["pom.xml"], "the pin landed"); + assert_eq!(pinned[CONFIG], without_the_filter); + assert_eq!(pinned[CHECKSUMS], wired[CHECKSUMS]); + assert!(!pinned.contains_key(FILTER)); +} + +/// `.mvn/socket-patch` takes no file. The pin lands all the same, with +/// the Trusted Checksums it has always had; no filter file and no line of +/// the filter is written; one warning says so; and the undo restores the +/// checkout, the thing in the way included. +#[test] +fn a_hosted_run_lands_the_pin_where_the_filter_directory_takes_no_file() { + let machine = Machine::start(); + // What stands at `.mvn/socket-patch`: a regular file, or a directory + // of this mode. + let states: &[(&str, Option)] = if root_user() { + &[("a regular file", None)] + } else { + &[ + ("a regular file", None), + ("a directory that cannot be written", Some(0o555)), + ("a directory that cannot be listed", Some(0o000)), + ] + }; + for (state, mode) in states { + machine.make(); + let dir = machine.proj().join(DIR); + std::fs::create_dir_all(dir.parent().expect("`.mvn`")).expect("create it"); + match mode { + None => std::fs::write(&dir, "not a directory\n").expect("the file"), + Some(_) => std::fs::create_dir(&dir).expect("the directory"), + } + let before = machine.files(); + let in_the_way = |mode: u32| { + if dir.is_dir() { + set_mode(&dir, mode); + } + }; + + in_the_way(mode.unwrap_or(0o755)); + let get = machine.step(&GET); + in_the_way(0o755); + let envelope = get.envelope(); + assert_eq!(get.code, Some(0), "{state}: {get:?}"); + assert_eq!(envelope["status"], "success", "{state}: {get:?}"); + assert_eq!( + event_for(&envelope, PURL)["action"], + "applied", + "{state}: {get:?}" + ); + assert_eq!( + envelope["redirect"]["rewrittenFiles"], + json!([CHECKSUMS, CONFIG, "pom.xml"]), + "{state}: {get:?}" + ); + assert_eq!( + warning_codes(&envelope), + ["redirect_maven_repository_filter_skipped"], + "{state}: {get:?}" + ); + let detail = envelope["warnings"][0]["detail"] + .as_str() + .expect("its text"); + assert!( + detail.starts_with(".mvn/socket-patch cannot take a file") + && detail.contains("The pins landed all the same"), + "{state}: {detail}" + ); + let pinned = machine.files(); + assert!( + pinned["pom.xml"].contains(&format!("{SUFFIXED}")), + "{state}: {}", + pinned["pom.xml"] + ); + assert!(!pinned[CONFIG].contains(DIR), "{state}: {}", pinned[CONFIG]); + assert!(pinned.contains_key(CHECKSUMS), "{state}"); + assert!(!pinned.contains_key(FILTER), "{state}"); + if mode.is_none() { + assert_eq!(pinned[DIR], "not a directory\n", "{state}"); + } + + // The pin is one `list` shows and an undo takes out. + in_the_way(mode.unwrap_or(0o755)); + let undo = machine.step(&["rollback", "--yes", "--json"]); + in_the_way(0o755); + assert_eq!(undo.code, Some(0), "{state}: {undo:?}"); + assert_eq!( + undo.envelope()["summary"]["rolledBack"], + 1, + "{state}: {undo:?}" + ); + assert_eq!(machine.files(), before, "{state}: {undo:?}"); + } +} + +/// A filter file that is there and is not UTF-8 text lists nothing, and +/// with the filter on Maven 3.9.2 and later refuse the pinned version over +/// it. The pin is in place, so no later run would land it again and write +/// the file with it: the run that finds the pin mends the file, as it +/// mends any file that does not list its pin's path, and writes nothing +/// else. +#[test] +fn a_hosted_run_mends_a_filter_file_that_is_not_text_for_a_pin_in_place() { + let machine = Machine::start(); + let runs: [&[&str]; 2] = [&["scan", "--mode", "hosted", "--yes", "--json"], &GET]; + for run in runs { + machine.make(); + assert_eq!(machine.step(&GET).code, Some(0)); + let wired = machine.files(); + let filter = machine.proj().join(FILTER); + std::fs::write(&filter, [0xff, 0xfe, b'\n', 0x80, 0x81]).expect("the bytes"); + + let ran = machine.step(run); + let envelope = ran.envelope(); + assert_eq!(ran.code, Some(0), "{run:?}: {ran:?}"); + assert_eq!(envelope["status"], "success", "{run:?}: {ran:?}"); + assert_eq!( + envelope["redirect"]["rewrittenFiles"], + json!([FILTER]), + "{run:?}: {ran:?}" + ); + assert_eq!(warning_codes(&envelope), [""; 0], "{run:?}: {ran:?}"); + assert_eq!( + machine.files(), + wired, + "{run:?}: the file is as the pin wrote it" + ); + } +} + +/// A filter file whose directory does not take the write cannot be +/// removed. `rollback` and `remove` restore the pin all the same: the pom +/// and the Trusted Checksums go back, the filter file and the two lines +/// that name its directory stay, and one warning says what was left. +#[test] +fn an_undo_restores_the_pin_where_it_cannot_remove_the_filter_file() { + if root_user() { + return; + } + let machine = Machine::start(); + let undos: [&[&str]; 2] = [ + &["rollback", "--yes", "--json"], + &["remove", PURL, "--yes", "--json"], + ]; + for undo in undos { + machine.make(); + let get = machine.step(&GET); + assert_eq!(get.code, Some(0), "{get:?}"); + let pinned = machine.files(); + let dir = machine.proj().join(DIR); + + set_mode(&dir, 0o555); + let ran = machine.step(undo); + set_mode(&dir, 0o755); + let envelope = ran.envelope(); + assert_eq!(ran.code, Some(0), "{undo:?}: {ran:?}"); + assert_eq!(envelope["status"], "success", "{undo:?}: {ran:?}"); + // (The Trusted Checksums settings stay beside the lines, and the + // restore says that of them as well.) + let left_behind: Vec<&Value> = envelope["warnings"] + .as_array() + .into_iter() + .flatten() + .filter(|warning| warning["code"] == "maven_repository_filter_left") + .collect(); + assert_eq!(left_behind.len(), 1, "{undo:?}: {ran:?}"); + let detail = left_behind[0]["detail"].as_str().expect("its text"); + assert!( + detail.starts_with(&format!("{FILTER} could not be removed")), + "{undo:?}: {detail}" + ); + let left = machine.files(); + assert_eq!(left["pom.xml"], PROJECT_POM, "{undo:?}: {ran:?}"); + assert!(!left.contains_key(CHECKSUMS), "{undo:?}: {ran:?}"); + assert_eq!(left[FILTER], pinned[FILTER], "{undo:?}: the file stays"); + assert_eq!( + left[CONFIG], pinned[CONFIG], + "{undo:?}: the lines that name its directory stay" + ); + } +} 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 832c3f0e21..00724b7a14 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/e2e_sbt_vendor.rs b/crates/socket-patch-cli/tests/e2e_sbt_vendor.rs index 916adc1c8c..afbf097113 100644 --- a/crates/socket-patch-cli/tests/e2e_sbt_vendor.rs +++ b/crates/socket-patch-cli/tests/e2e_sbt_vendor.rs @@ -874,15 +874,21 @@ fn vendor_takeover_beside_a_pinned_pom_restores_the_pom_and_says_so() { .replace("abcdef12-0000-4000-8000-000000000001", GSON_UUID) .replace("abcdef12", &GSON_UUID[..8]) }; + // What hosted mode wrote for the pom: the pin, and under `.mvn` the + // Trusted Checksums and the repository filter file of the patch. + let filter = format!(".mvn/socket-patch/prefixes-socket-patch-{GSON_UUID}.txt"); let pinned = [ "pom.xml", ".mvn/maven.config", ".mvn/checksums/checksums.sha256", + filter.as_str(), ]; for rel in pinned { let path = fx.proj().join(rel); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, gson(&format!("expected/{rel}"))).unwrap(); + // (The fixture names its filter file for its own patch.) + let of_the_fixture = rel.replace(GSON_UUID, "abcdef12-0000-4000-8000-000000000001"); + std::fs::write(path, gson(&format!("expected/{of_the_fixture}"))).unwrap(); } let (_rt, server) = mock_gson_api(); let uri = server.uri(); diff --git a/crates/socket-patch-cli/tests/in_process_scan.rs b/crates/socket-patch-cli/tests/in_process_scan.rs index 5afca9e02e..987cc5f3d7 100644 --- a/crates/socket-patch-cli/tests/in_process_scan.rs +++ b/crates/socket-patch-cli/tests/in_process_scan.rs @@ -1926,6 +1926,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 9b2f90f9b9..b60ca60260 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 5e8fec0fe6..33060bc34b 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-cli/tests/vendor_eject.rs b/crates/socket-patch-cli/tests/vendor_eject.rs index ade21f42ac..6bc59d7583 100644 --- a/crates/socket-patch-cli/tests/vendor_eject.rs +++ b/crates/socket-patch-cli/tests/vendor_eject.rs @@ -278,6 +278,43 @@ async fn eject_vendors_hosted_pins_and_revert_returns_to_upstream() { assert!(!p.redirect_state().exists()); } +/// One of hosted mode's Maven repository filter files that cannot be read +/// is no reason to refuse an eject, of an npm pin or of any other: a scan +/// and a rollback leave such a file where it is, and so does the eject. +/// (Root reads any file, so there is nothing to see as root.) +#[cfg(unix)] +#[tokio::test] +async fn eject_is_not_refused_over_a_maven_filter_file_it_cannot_read() { + use std::os::unix::fs::PermissionsExt as _; + // SAFETY: geteuid has no preconditions and cannot fail. + if unsafe { libc::geteuid() } == 0 { + return; + } + let p = hosted_project(true).await; + mock_registry(&p).await; + mock_view(&p).await; + let filter = p + .root() + .join(".mvn/socket-patch/prefixes-socket-patch-77777777-7777-4777-8777-777777777777.txt"); + std::fs::create_dir_all(filter.parent().unwrap()).unwrap(); + std::fs::write(&filter, "## repository-prefixes/2.0\n").unwrap(); + let mode = |mode: u32| { + std::fs::set_permissions(&filter, std::fs::Permissions::from_mode(mode)).unwrap() + }; + + mode(0o000); + let (code, env) = p.run_json(&["vendor"]); + mode(0o644); + assert_eq!(code, 0, "the eject is not refused: {env:#}"); + assert_eq!(find_event(&env, "applied", None)["purl"], PURL, "{env:#}"); + assert!(p.artifact().is_file(), "the npm pin is vendored"); + assert_eq!( + std::fs::read_to_string(&filter).unwrap(), + "## repository-prefixes/2.0\n", + "the file is left as it is" + ); +} + /// #1782: an eject that dies before its group commit (a SIGKILL, a Ctrl-C, /// a CI cancel) leaves the project hosted, exactly as found: the upstream /// restore is captured with the vendored wiring and lands only with the 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 afdcbfd462..b5e8e814b6 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 f74b584d9d..474aa6e1b2 100644 --- a/crates/socket-patch-core/src/formats/maven/mod.rs +++ b/crates/socket-patch-core/src/formats/maven/mod.rs @@ -19,6 +19,7 @@ use super::xml::{blank_non_markup, child_text, elements, open_tags, Element}; 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 0000000000..4d5580f12f --- /dev/null +++ b/crates/socket-patch-core/src/formats/maven/repository_filter.rs @@ -0,0 +1,751 @@ +//! 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, + /// The config with what it lacked appended: both lines, or the switch + /// alone beside a directory line hosted mode wrote. + Appended(String), + /// The checkout already configures the filter another way (why). + Conflict(String), + /// The directory line hosted mode wrote stands beside a switch that is + /// not on (the setting found): the user switched the filter off. + SwitchedOff(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, 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 directory line has one owner. A line that names [`DIR`] is hosted +/// mode's wherever it stands, with or without the switch beside it: that +/// is how [`heal_basedir`] respells it and [`strip_config`] takes it out. +/// So where it is the directory Maven would read and no line sets the +/// switch, the switch went missing (a hand edit, a merge) and is put back, +/// alone. A switch set to anything but `true` is the user's, as it is for +/// a rollback, which leaves it: the filter is switched off, and stays so. +/// +/// 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); + let ours = reads_hosted_dir(existing); + match any.get(SWITCH_KEY) { + None if ours => { + let switch = &config_args(form)[..BASEDIR_AT]; + return Config::Appended(super::append_config_args(existing, switch, true)); + } + // (Maven reads the switch as Java parses a boolean: `TRUE` is on, + // and is then a spelling of the user's own, like any other.) + Some(value) if ours && !value.eq_ignore_ascii_case("true") => { + return Config::SwitchedOff(format!("-D{SWITCH_KEY}={value}")); + } + _ => {} + } + 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 the directory `config` makes Maven read the filter files from +/// is [`DIR`], in either spelling: the last line that sets the directory +/// names it. A later line that names another directory is the user's, and +/// makes the filter theirs. +fn reads_hosted_dir(config: &str) -> bool { + maven_config_line_properties(config) + .get(BASEDIR_KEY) + .is_some_and(|dir| basedir_of_value(dir).is_some()) +} + +/// 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. So it is +/// where a later line names another directory ([`reads_hosted_dir`]): the +/// user has taken the filter over, [`merge_config`] leaves it to them, and +/// only the directory line, which Maven no longer reads, goes. +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]) + }; + let switch_is_ours = reads_hosted_dir(config); + // (The switch is spelled alike under both forms.) + let is_ours = |line: &str| { + names_dir(line) || switch_is_ours && 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")); + } + + /// The directory line has one owner, hosted mode: for a scan as for + /// the respelling and the rollback. Where it stands without its switch + /// the switch is put back, alone; beside a switch that is not on, the + /// filter is the user's to switch on again, and a rollback leaves that + /// switch as well. + #[test] + fn a_lone_directory_line_is_hosted_modes_own() { + for form in FORMS { + let [switch, dir] = config_args(form) else { + panic!("two lines"); + }; + for lone in [format!("{dir}\n"), format!("-B\n{dir}")] { + assert_eq!(self::form(&lone), None, "{lone}"); + assert!(holds_written_line(&lone), "{lone}"); + for wanted in FORMS { + let Config::Appended(written) = merge_config(&lone, wanted) else { + panic!("{lone:?} takes the switch"); + }; + assert_eq!( + written, + crate::formats::maven::append_config_args(&lone, &[switch], true) + ); + // The directory line keeps the spelling it has. + assert_eq!(self::form(&written), Some(form), "{written}"); + assert_eq!(merge_config(&written, wanted), Config::InPlace); + // A rollback takes the pair as it takes the line alone. + assert_eq!(strip_config(&written), strip_config(&lone)); + } + } + let off = "-Daether.remoteRepositoryFilter.prefixes=false"; + let config = format!("{off}\n{dir}\n"); + assert_eq!( + merge_config(&config, form), + Config::SwitchedOff(off.to_string()) + ); + assert_eq!( + strip_config(&config), + Some(format!("{off}\n")), + "the switch is theirs" + ); + // On in a spelling of their own: theirs, and not switched off. + let shouted = format!("-Daether.remoteRepositoryFilter.prefixes=TRUE\n{dir}\n"); + assert!( + matches!(merge_config(&shouted, form), Config::Conflict(_)), + "{shouted}" + ); + // Another directory is the one Maven would read: theirs. + let moved = + format!("{dir}\n-Daether.remoteRepositoryFilter.prefixes.basedir=/srv/filters\n"); + assert!( + matches!(merge_config(&moved, form), Config::Conflict(_)), + "{moved}" + ); + } + } + + /// 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 filter the user has since taken over, by a later line that + // names another directory: a scan leaves it to them, and a rollback + // takes the line Maven no longer reads and leaves their switch. + let [switch, dir] = config_args(Launcher) else { + panic!("two lines"); + }; + let theirs = "-Daether.remoteRepositoryFilter.prefixes.basedir=/srv/filters"; + let taken_over = format!("{switch}\n{dir}\n{theirs}\n"); + assert!(matches!( + merge_config(&taken_over, Launcher), + Config::Conflict(_) + )); + assert_eq!( + strip_config(&taken_over), + Some(format!("{switch}\n{theirs}\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 fdb0f9fc4c..e994e2eadc 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 c4f3327c47..166b054cca 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -1155,6 +1155,112 @@ 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, whether `.mvn/maven.config` +/// can take a write, and whether the directory can take a file. Advisory, +/// like the module poms: the filter is an extra, and nothing here keeps a +/// pin from landing. So a file under a name hosted mode writes whose +/// content cannot be read (in memory, one the host lists without content) +/// is told to the rewriter as a path it must not write: the write would +/// fail on disk, and the guard refuses one over content nobody read. One +/// whose bytes are read and are not UTF-8 text is handed over as an empty +/// file: it lists nothing, and is written over or mended like any such. +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, maven_filter_dir_writable, + MavenFilterAround, MAVEN_FILTER_KEY, MVN_CONFIG, MVN_JVM_CONFIG, + }; + let dir = hosted_maven_filter_dir(view).await; + if !out.files.contains_key(MVN_JVM_CONFIG) { + if let Some(text) = read_advisory(view, unreadable, MVN_JVM_CONFIG).await { + out.files.insert(MVN_JVM_CONFIG.to_string(), text); + } + } + let mut occupied = dir.occupied; + for rel in dir.owned { + match read_pom_text(view, unreadable, &rel).await { + Ok(Some(text)) => { + out.files.insert(rel, text); + } + // Not UTF-8 text: a file that is there and lists nothing. The + // rewriter is handed it as an empty one, which it writes over + // with a pin that lands and mends for a pin in place, as it + // does any file that does not list its pin's path. Left out, it + // would read as no file, and a pin in place would keep bytes + // Maven refuses the pinned version over. (Its bytes were read: + // on disk they do not decode, in memory the host gave them. So + // the guard, which refuses a write over content nobody read, + // has nothing to refuse.) + Err(Undecodable) => { + out.files.insert(rel, String::new()); + } + // There, and not to be read. + Ok(None) => occupied.push(rel), + } + } + occupied.sort(); + let keeps_lines = dir.others || dir.unlistable || !occupied.is_empty(); + let dir_unwritable = match view.disk_root() { + Some(root) => dir.unlistable || !maven_filter_dir_writable(root).await, + // In memory a directory is its files: a file under the directory's + // own name leaves no room for one. + None => matches!(view, ProjectView::Memory(project) + if project.contains(repository_filter::DIR)), + }; + let around = MavenFilterAround { + keeps_lines, + // 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_unwritable, + }; + 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). @@ -1287,23 +1393,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"] { @@ -1520,6 +1626,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); } @@ -6091,6 +6198,10 @@ fn confirm( .map(|(name, content)| (name.as_str(), content)), ) .filter(|(name, _)| !crate::patch::redirect::sbt::is_generated_file(name)) + // A Maven repository filter file lists the suffixed version of its + // patch and pins nothing: one is kept on purpose once its pin is + // gone (a superseded patch's, one a rollback could not remove). + .filter(|(name, _)| crate::formats::maven::repository_filter::owned_rel(name).is_none()) .collect(); // Gradle scripts, locks and owned files never confirm by substring: a // pasted snippet or a stale lock line pins nothing (the Gradle planner @@ -12277,36 +12388,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| { @@ -12349,13 +12496,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. @@ -12658,6 +12798,384 @@ 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); + } + } + } + + /// A filter file lists the suffixed version of its patch, and one is + /// kept on purpose once its pin is gone: a superseded patch's stays + /// until a rollback, and a rollback leaves one it cannot remove. Such + /// a file alone pins nothing. A run that lands no pin for the patch + /// (here the pom declares another release) reads the file, and does + /// not take the version in it for the patch redirected. On disk and in + /// memory alike. + #[tokio::test] + async fn a_kept_maven_filter_file_alone_confirms_no_patch() { + use crate::formats::maven::repository_filter::{file_rel, file_text}; + let pom = "\n 4.0.0\n x\n y\n 1\n \n \n com.socketfixture\n victim\n 1.9.0\n \n \n\n"; + let id = format!("socket-patch-{GRADLE_UUID}"); + let filter = file_rel(&id); + let kept = file_text(&id, "com.socketfixture", "victim", "1.10.0-socket.4d5e6f70"); + assert!(kept.contains("1.10.0-socket.4d5e6f70")); + let mut p = MemoryProject::new(); + p.insert_text("pom.xml", pom); + p.insert_text(&filter, kept.as_str()); + 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(&filter), &kept).unwrap(); + for view in [ProjectView::Memory(&p), ProjectView::Disk(tmp.path())] { + let (read, done) = gradle_rewrite_in(&view).await; + assert_eq!(read.files.get(&filter), Some(&kept)); + assert!( + done.rewrite.files.is_empty(), + "{:?}", + done.rewrite.files.keys() + ); + assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); + } + } + + /// A filter file that is there and is not UTF-8 text lists nothing, + /// and with the filter on Maven refuses the pinned version over it. + /// The rewriter is handed it as an empty file: a pin in place has it + /// mended like any file that does not list its path, and nothing else + /// is written. Its bytes were read (in memory the host gave them), so + /// the guard refuses nothing. On disk and in memory alike. + #[tokio::test] + async fn a_maven_filter_file_that_is_not_text_is_mended_for_a_pin_in_place() { + 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 candidates = vec![gradle_candidate()]; + // The project as a first run wires it. + let mut plain = MemoryProject::new(); + plain.insert_text("pom.xml", pom); + let (_, first) = gradle_rewrite_in(&ProjectView::Memory(&plain)).await; + let wired = &first.rewrite.files; + let written = wired[&filter].clone(); + // Its filter file, since overwritten with bytes that are no text. + let garbage: &[u8] = &[0xff, 0xfe, b'\n', 0x80, 0x81]; + assert!(std::str::from_utf8(garbage).is_err()); + let mut p = MemoryProject::new(); + let tmp = tempfile::tempdir().unwrap(); + for (rel, text) in wired { + p.insert_text(rel, text.as_str()); + let path = tmp.path().join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + p.insert(&filter, MemoryEntry::Binary(garbage.into())); + std::fs::write(tmp.path().join(&filter), garbage).unwrap(); + for view in [ProjectView::Memory(&p), ProjectView::Disk(tmp.path())] { + let (read, done) = gradle_rewrite_in(&view).await; + assert_eq!(read.files.get(&filter).map(String::as_str), Some("")); + let files = &done.rewrite.files; + assert_eq!(files.keys().collect::>(), [&filter]); + assert_eq!(files[&filter], written); + let edits: Vec<(&str, &str)> = done + .rewrite + .edits + .iter() + .map(|e| (e.path.as_str(), e.action.as_str())) + .collect(); + assert_eq!(edits, [(filter.as_str(), "rewritten")]); + assert!( + done.rewrite.warnings.is_empty(), + "{:?}", + done.rewrite.warnings + ); + assert!(guard(&view, &done, &candidates).is_none()); + assert_eq!(done.confirmed.len(), 1, "{:?}", done.confirmed); + } + } + + /// 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; + /// - the filter's directory takes no file (a regular file under its + /// name, a directory that cannot be written or listed); + /// - a file under the pin's own name cannot be read (on disk for want + /// of the permission, in memory because the host gave no content). + #[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" + ); + + // The directory itself takes no file: something that is not a + // directory stands under its name, or (for anyone but root, who + // writes anywhere) it cannot be written, or not even listed. The + // write of a filter file there would fail the whole run. + use std::os::unix::fs::PermissionsExt as _; + let root_user = unsafe { libc::geteuid() } == 0; + let modes: &[Option] = if root_user { + &[None] + } else { + &[None, Some(0o555), Some(0o000)] + }; + for mode in modes { + let tmp = project(); + let dir = tmp.path().join(".mvn/socket-patch"); + match mode { + None => std::fs::write(&dir, "not a directory\n").unwrap(), + Some(mode) => { + std::fs::create_dir_all(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(*mode)).unwrap(); + } + } + let view = ProjectView::Disk(tmp.path()); + let (read, done) = gradle_rewrite_in(&view).await; + if mode.is_some() { + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let why = format!("a directory of mode {mode:?}"); + assert!(around(&read).dir_unwritable, "{why}"); + landed_unfiltered(&view, &done, &why); + assert_eq!( + codes(&done), + ["redirect_maven_repository_filter_skipped"], + "{why}" + ); + } + // (A directory that is not there yet is made with the file, where + // `.mvn` takes it.) + if !root_user { + let tmp = project(); + let mvn = tmp.path().join(".mvn"); + std::fs::set_permissions(&mvn, std::fs::Permissions::from_mode(0o555)).unwrap(); + let view = ProjectView::Disk(tmp.path()); + let (read, _) = gradle_rewrite_in(&view).await; + std::fs::set_permissions(&mvn, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(around(&read).dir_unwritable); + } + + // A file under the pin's own name that cannot be read: on disk + // one without the permission, in memory one the host lists + // without its content. Its bytes are not known, so it is no file + // of hosted mode's to write over (in memory the guard refuses a + // write over content nobody read): the pin lands without it. + let unread = |read: &CandidateFiles| { + let seen = around(read); + assert_eq!(seen.occupied, [filter.clone()]); + assert!(seen.keeps_lines && !seen.dir_unwritable); + assert!(!read.files.contains_key(&filter), "{:?}", read.files.keys()); + }; + if !root_user { + let tmp = project(); + std::fs::create_dir_all(tmp.path().join(".mvn/socket-patch")).unwrap(); + let file = tmp.path().join(&filter); + std::fs::write(&file, "## repository-prefixes/2.0\n").unwrap(); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o000)).unwrap(); + let view = ProjectView::Disk(tmp.path()); + let (read, done) = gradle_rewrite_in(&view).await; + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap(); + unread(&read); + landed_unfiltered(&view, &done, "an unreadable file"); + assert_eq!(codes(&done), ["redirect_maven_repository_filter_skipped"]); + } + let mut memory = MemoryProject::new(); + memory.insert_text("pom.xml", pom); + memory.insert_present(&filter); + let view = ProjectView::Memory(&memory); + let (read, done) = gradle_rewrite_in(&view).await; + unread(&read); + landed_unfiltered(&view, &done, "a file without content"); + assert_eq!(codes(&done), ["redirect_maven_repository_filter_skipped"]); + // In memory a directory is its files: a file under the name of the + // directory leaves no room for one in it. + let mut memory = MemoryProject::new(); + memory.insert_text("pom.xml", pom); + memory.insert_text(".mvn/socket-patch", "not a directory\n"); + let view = ProjectView::Memory(&memory); + let (read, done) = gradle_rewrite_in(&view).await; + assert!(around(&read).dir_unwritable); + landed_unfiltered(&view, &done, "a file under the directory's name"); + assert_eq!(codes(&done), ["redirect_maven_repository_filter_skipped"]); + } + /// 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 e133c046e2..6ab7a91182 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -73,7 +73,7 @@ use crate::formats::gem::hosted::{ 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; @@ -9532,6 +9532,55 @@ 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 files it can write as its own: a link, a + /// directory, a file whose content cannot be read (in memory, one the + /// host lists without content). No filter file is written there: a + /// write through a link would replace it, and one over content nobody + /// read is refused. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub occupied: Vec, + /// The filter directory cannot take a file: it cannot be listed, it + /// does not take a write (nor, where it is not there yet, does the + /// directory it would be created in), or something that is not a + /// directory stands under its name. No filter file is written, and + /// the two resolver lines are not added for one. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub dir_unwritable: bool, +} /// 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). @@ -9750,30 +9799,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; @@ -9826,6 +9877,7 @@ fn rewrite_maven_poms( let mut mvn_config = healed .or_else(|| files.get(MVN_CONFIG).cloned()) .unwrap_or_default(); + let mvn_config_at_start = mvn_config.clone(); let mut mvn_config_changed = false; // The Trusted Checksums settings are merged in once per run, with the // first dependency that carries checksums; the settings found set to @@ -9836,6 +9888,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 @@ -9952,36 +10012,28 @@ 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", - )); - } - if run.wired { - checksum_drops.extend(stale_checksums); - } - 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, + stale_checksums, + &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 @@ -10343,36 +10395,29 @@ 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", - )); - } - if run.wired { - checksum_drops.extend(stale_checksums); - } - 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, + stale_checksums, + &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; } @@ -10523,6 +10568,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(), @@ -10564,8 +10610,20 @@ 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. A pin with no file gets none.) if !pin_landed { + if versioned.iter().any(|(_, _, v)| *v == suffixed_version) + && idx.has_repository(&repo_id) + { + scope.in_place( + files, + &repo_id, + (&group_id, &artifact_id, &suffixed_version), + result, + ); + } continue; } if !idx.has_repository(&repo_id) { @@ -10596,14 +10654,64 @@ 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 serves_none = scope.serves_none(files, &|id| { + planner.declares(id, pom.as_deref().unwrap_or_default()) + }); + // The other way round: lines this run added for a filter file it then + // took back (the file's repository went out of the poms again within + // the run). With no other file for them to serve they are taken back + // too, with what the run said of them, as if never written. + if serves_none && scope.take_back_lines(&mut mvn_config, result) { + mvn_config_changed = mvn_config != mvn_config_at_start; + } + let strips = scope.retired + && !scope.around.keeps_lines + && !scope.around.config_unwritable + && serves_none; 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(MAVEN_FILTER_LINES_KEY.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); } @@ -10648,12 +10756,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. + // (Every file the run answers for lists its pin's path: it was + // written, found listing it, or mended.) + let filtered_here = filter_files.iter().any(|rel| final_text(rel).is_some()); + 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 @@ -10744,6 +10869,558 @@ 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 run already said that the directory takes no file. + said_unwritable: bool, + /// `.mvn/maven.config` before and after this run appended to it for + /// the filter ([`Self::take_back_lines`]). + appended: Option<(String, String)>, +} + +/// The edit kind of a filter file. +const MAVEN_FILTER_EDIT: &str = "redirect_maven_repository_filter"; +/// The `key` of the `redirect_maven_config` edit that adds the filter's +/// lines to `.mvn/maven.config`, or takes them out. +const MAVEN_FILTER_LINES_KEY: &str = "repositoryFilter"; + +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 `.mvn/maven.config` configures the filter + /// another way; where the two lines would have to be added and + /// `.mvn/jvm.config` or the environment of the machine that scans + /// names the filter; where `.mvn/maven.config` cannot take the two + /// lines, or the filter's directory a file; and for coordinates a + /// path or a line cannot hold. The Socket repository then stays + /// unfiltered, as it was, and the run says so. Lines that are in place + /// are the project's own: a pin that lands there gets its file, + /// whatever the machine sets beside them. + 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 no file hosted mode can write as its \ + own (a link or a directory stands there, or a file that cannot be read), \ + 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; + } + let listed = repository_filter::prefix(group_id, artifact_id, suffixed_version); + // A file that is there and lists the path needs no write. Any + // other needs one, which a directory that takes none would fail. + let lists = self + .live(files, &rel) + .is_some_and(|text| repository_filter::lists(text, &listed)); + if !lists && self.around.dir_unwritable { + self.say_unwritable(result); + return; + } + // A setting outside `maven.config` is the user's as well: the lines + // would move the directory their own files are read from. It + // stands against adding the lines, and against nothing else: lines + // that are in place are the project's committed configuration, + // whatever the machine that scans sets beside them. + 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 repository_filter::merge_config(mvn_config, form) { + Config::Appended(config) => match outside() { + Some(theirs) => Config::Conflict(theirs), + None => Config::Appended(config), + }, + merged => merged, + }; + 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; + } + // Hosted mode's directory line, and a switch the user set to + // something else: the filter is off, and theirs to switch on. + Config::SwitchedOff(theirs) => { + result.warnings.push(RewriteWarning { + code: "redirect_maven_repository_filter_conflict".into(), + detail: format!( + "{group_id}:{artifact_id}: {MVN_CONFIG} switches Maven's repository \ + prefix filter off ({theirs}) beside the line that names {dir} as its \ + directory; 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, \ + remove that setting and scan again", + dir = repository_filter::DIR, + ), + }); + 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" + }; + let before = std::mem::replace(mvn_config, config); + *mvn_config_changed = true; + self.appended + .get_or_insert_with(|| (before, mvn_config.clone())); + result.edits.push(FileEdit { + path: MVN_CONFIG.into(), + kind: "redirect_maven_config".into(), + action: action.into(), + key: Some(MAVEN_FILTER_LINES_KEY.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 lists { + return; + } + self.write( + files, + repo_id, + rel, + (group_id, artifact_id, suffixed_version), + result, + ); + } + + /// Plan the filter file `rel` of `repo_id`, which lists the one path + /// of the pinned version. + fn write( + &mut self, + files: &BTreeMap, + repo_id: &str, + rel: String, + (group_id, artifact_id, suffixed_version): (&str, &str, &str), + result: &mut RewriteResult, + ) { + use crate::formats::maven::repository_filter; + let action = if files.contains_key(&rel) { + "rewritten" + } else { + "added" + }; + let listed = repository_filter::prefix(group_id, artifact_id, suffixed_version); + 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); + } + + /// Say, once for the run, that the filter directory takes no file. + fn say_unwritable(&mut self, result: &mut RewriteResult) { + if std::mem::replace(&mut self.said_unwritable, true) { + return; + } + result.warnings.push(RewriteWarning { + code: "redirect_maven_repository_filter_skipped".into(), + detail: format!( + "{dir} cannot take a file (it cannot be listed or written, or is not a \ + directory), so no repository filter file was written there. 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 = crate::formats::maven::repository_filter::DIR, + ), + }); + } + + /// The filter file of a pin that is in place and was not written this + /// run, when it has one. A pin without a file is left without one, and + /// a file that lists the pinned path is left as it is: a re-run stays + /// edit-free. A file that is there and does not list the path is + /// mended: with the filter on, Maven 3.9.2 and later refuse the pinned + /// version over it (`Prefix … NOT allowed`), and no later scan would + /// land the pin again to rewrite it. + fn in_place( + &mut self, + files: &BTreeMap, + repo_id: &str, + (group_id, artifact_id, suffixed_version): (&str, &str, &str), + result: &mut RewriteResult, + ) { + use crate::formats::maven::repository_filter; + 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); + let listed = repository_filter::prefix(group_id, artifact_id, suffixed_version); + match self.live(files, &rel) { + None => return, + Some(text) if repository_filter::lists(text, &listed) => {} + Some(_) if self.around.dir_unwritable => { + result.warnings.push(RewriteWarning { + code: "redirect_maven_repository_filter_skipped".into(), + detail: format!( + "{group_id}:{artifact_id}: {rel} does not list {listed}, the path of \ + the pinned version, and could not be rewritten ({dir} does not take \ + the write). With the repository filter on, Maven 3.9.2 and later \ + refuse the pinned version until that file lists the path or is removed", + dir = repository_filter::DIR, + ), + }); + return; + } + Some(_) => self.write( + files, + repo_id, + rel.clone(), + (group_id, artifact_id, suffixed_version), + result, + ), + } + self.pinned.insert(rel); + } + + /// Take the lines this run appended to `.mvn/maven.config` back, with + /// the edit and the warning it gave for them: for a run whose filter + /// files were all taken back again ([`Self::retire`]), so that the + /// lines would name a directory that holds no file of a repository a + /// pom declares. `true` when the config changed. + fn take_back_lines(&mut self, mvn_config: &mut String, result: &mut RewriteResult) -> bool { + let Some((before, after)) = self.appended.take() else { + return false; + }; + *mvn_config = if *mvn_config == after { + before + } else { + // Something else was merged in after them: the lines this run + // appended go where they stand, and no other. (A directory + // line that stood there before the run, beside which the run + // put the switch back, stays.) + let appended = after[before.len()..].lines(); + let appended: Vec<&str> = appended.filter(|line| !line.is_empty()).collect(); + let kept = |line: &&str| !appended.contains(&line.trim_end_matches(['\r', '\n'])); + mvn_config.split_inclusive('\n').filter(kept).collect() + }; + result.edits.retain(|e| { + !(e.path == MVN_CONFIG + && e.action != "removed" + && e.key.as_deref() == Some(MAVEN_FILTER_LINES_KEY)) + }); + result + .warnings + .retain(|w| w.code != "redirect_maven_repository_filter_enabled"); + self.said_enabled = false; + true + } + + /// 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. +/// +/// `stale_checksums` are the checksum lines a grant with a malformed hash +/// must not leave behind. They go with the pin: when the plan wires the +/// dep, this run or an earlier one. A plan that wires nothing drops none +/// of them and gets no filter file and no filter line, so a dep the run +/// does not wire has no `.mvn` file touched for it. +#[allow(clippy::too_many_arguments)] +fn settle_maven_plan( + files: &BTreeMap, + run: ReactorRun, + stale_checksums: Vec, + 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", + )); + } + if run.wired { + checksum_drops.extend(stale_checksums); + } + 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, coords, result); + } +} + +/// 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 +} + /// What a hosted Maven warning says this run did for a dep it did not /// wire: one clause, for the mirror gate and the reactor planner's refusal /// alike. It speaks of the run and of the dep, not of the state of the @@ -10855,6 +11532,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 @@ -10948,6 +11627,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 @@ -11209,79 +11900,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`]). @@ -11295,41 +12151,49 @@ pub(crate) fn carries_maven_heal(result: &RewriteResult) -> bool { /// it with a detached copy), anything else that is not a regular file, and /// a directory that does not take the write all refuse the whole run they /// are part of, which a heal must never do. +/// +/// The directory is asked here as well ([`takes_a_file`]). The preflight +/// leaves it to the commit of a group that captures the path, and a scan +/// asks this with its group open: the answer has to come before that +/// commit, not from it. pub(crate) async fn maven_config_writable(root: &std::path::Path) -> bool { let pending = vec![staged::Pending { rel: MVN_CONFIG, content: Some(b"".as_slice()), read: None, }]; - staged::preflight(root, pending).await.is_ok() + staged::preflight(root, pending).await.is_ok() && takes_a_file(root, ".mvn").await } -/// 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), - ) - }) +/// Whether the writers could put a file into the repository filter's +/// directory under `root` ([`repository_filter::DIR`]). +pub(crate) async fn maven_filter_dir_writable(root: &std::path::Path) -> bool { + takes_a_file(root, crate::formats::maven::repository_filter::DIR).await +} + +/// Whether the writers could put a file into the directory `dir` of the +/// project at `root`: the first of the directory and the ones above it, +/// down to `root`, that is there decides, since a directory that is +/// missing is created with the file. It has to be a directory that takes +/// a write. Something else under the directory's name (a regular file, a +/// link that leads nowhere) takes none, and neither does a directory +/// whose entries cannot be created. +async fn takes_a_file(root: &std::path::Path, dir: &str) -> bool { + let dir = root.join(dir); + for dir in dir.ancestors() { + match tokio::fs::symlink_metadata(dir).await { + Err(e) if e.kind() == std::io::ErrorKind::NotFound && dir != root => continue, + Err(_) => return false, + // (Through a link, as the write goes.) + Ok(_) => { + let is_dir = tokio::fs::metadata(dir) + .await + .is_ok_and(|meta| meta.is_dir()); + return is_dir && staged::entries_writable(dir).is_ok(); + } + } + } + false } /// Why the Trusted Checksums pin is not enforced by the Maven the project @@ -11347,26 +12211,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") }); @@ -11447,14 +12340,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) ──────────────────────────────── @@ -12341,6 +13230,1000 @@ 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 is rewritten: when the pin + // lands, and also while it is in place, since no later scan would + // land it again and Maven refuses the pinned version over such a + // file. Nothing else is written for the pin in place. + let rewritten = |r: &RewriteResult| -> Vec<(String, String)> { + let of_the_filter = r.edits.iter().filter(|e| e.kind == MAVEN_FILTER_EDIT); + of_the_filter + .map(|e| (e.path.clone(), e.action.clone())) + .collect() + }; + let mended = [(MAVEN_FILTER.to_string(), "rewritten".to_string())]; + // (The empty file is also what the engine hands the rewriter for a + // file that is there and is not UTF-8 text: it lists nothing.) + 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_eq!( + r.files.keys().collect::>(), + [MAVEN_FILTER], + "{broken:?}" + ); + assert_eq!(r.files[MAVEN_FILTER], written, "{broken:?}"); + assert_eq!(rewritten(&r), mended, "{broken:?}"); + assert_eq!(r.edits.len(), 1, "{broken:?}: {:?}", r.edits); + assert!(r.warnings.is_empty(), "{broken:?}: {:?}", r.warnings); + 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_eq!(rewritten(&r), mended, "{broken:?}"); + } + // The same for a pin the reactor planner finds in place. + let reactor = poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ]); + let picks = [("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))]; + let first = rewrite_poms_selecting(&reactor, &picks); + let mut pinned = reactor.clone(); + pinned.extend(first.files.clone()); + pinned.insert(MAVEN_FILTER.to_string(), String::new()); + let r = rewrite_poms_selecting(&pinned, &picks); + assert_eq!(r.files.keys().collect::>(), [MAVEN_FILTER]); + assert_eq!(r.files[MAVEN_FILTER], written); + assert_eq!(rewritten(&r), mended); + // A file the directory does not take is said, and nothing written. + pinned.extend([maven_filter_around(&MavenFilterAround { + dir_unwritable: true, + ..Default::default() + })]); + let r = rewrite_poms_selecting(&pinned, &picks); + assert!(r.files.is_empty(), "{:?}", r.files.keys()); + assert_eq!( + warning_codes(&r), + ["redirect_maven_repository_filter_skipped"] + ); + let detail = &r.warnings[0].detail; + assert!( + detail.contains(&format!( + "{MAVEN_FILTER} does not list /org/slf4j/slf4j-api/{MAVEN_SUFFIXED}" + )), + "{detail}" + ); + } + + /// 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()); + // (The lines were there before the run: none to take back.) + assert!(!scope.take_back_lines(&mut config, &mut result)); + assert_eq!(config, lines); + + // The same in a checkout without the lines: the run adds them + // with the file, and says so. Once the file is taken back they + // serve no file, and go the way they came: the config has its + // bytes again, and the run reports nothing of them. + for before in ["", "-B\n", "-B"] { + let bare = match before { + "" => BTreeMap::new(), + before => BTreeMap::from([(MVN_CONFIG.to_string(), before.to_string())]), + }; + let mut scope = MavenScope::default(); + let mut result = RewriteResult::default(); + let (mut config, mut changed) = (before.to_string(), false); + scope.repository( + &bare, + &id, + coords, + (&mut config, &mut changed, form), + &mut result, + ); + assert!(changed && config.contains(repository_filter::DIR)); + assert_eq!(warning_codes(&result), [MAVEN_FILTER_ENABLED]); + assert_eq!(result.edits.len(), 2, "{:?}", result.edits); + scope.retire(&bare, &id, &mut result); + assert!(scope.serves_none(&bare, &this_one)); + assert!(scope.take_back_lines(&mut config, &mut result)); + assert_eq!(config, before); + assert!(result.edits.is_empty(), "{:?}", result.edits); + assert!(result.warnings.is_empty(), "{:?}", result.warnings); + // Another setting merged in after the lines stays. + let mut scope = MavenScope::default(); + let mut config = before.to_string(); + scope.repository( + &bare, + &id, + coords, + (&mut config, &mut changed, form), + &mut result, + ); + config.push_str("\n-T1C\n"); + scope.retire(&bare, &id, &mut result); + assert!(scope.take_back_lines(&mut config, &mut result)); + assert!(!config.contains(repository_filter::DIR), "{config}"); + assert!(config.ends_with("-T1C\n"), "{config}"); + assert!(result.edits.is_empty() && result.warnings.is_empty()); + } + // What is taken back is what the run appended, and no more. The + // directory line stood alone before the run, which put the switch + // back beside it: the switch goes again, the line stays. + let [switch, dir] = repository_filter::config_args(form) else { + panic!("two lines"); + }; + let lone = BTreeMap::from([(MVN_CONFIG.to_string(), format!("{dir}\n"))]); + let mut scope = MavenScope::default(); + let mut result = RewriteResult::default(); + let (mut config, mut changed) = (lone[MVN_CONFIG].clone(), false); + scope.repository( + &lone, + &id, + coords, + (&mut config, &mut changed, form), + &mut result, + ); + assert_eq!(config, format!("{dir}\n{switch}\n")); + config.push_str("-T1C\n"); + scope.retire(&lone, &id, &mut result); + assert!(scope.take_back_lines(&mut config, &mut result)); + assert_eq!(config, format!("{dir}\n-T1C\n")); + assert!(result.edits.is_empty() && result.warnings.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}" + ); + } + + /// [`granted_maven_override`] for a second artifact of the pom + /// [`pom_with_two_deps`] declares, patched by another patch. + fn second_maven_override() -> (DepOverride, String) { + let uuid = "88888888-8888-4888-8888-888888888888"; + let mut second = granted_maven_override(); + second.name = "slf4j-simple".into(); + second.patch_uuid = uuid.into(); + let ov = second.registry_override.as_mut().unwrap(); + ov.index_url = format!("https://patch.socket.dev/patch-registry/maven/tok/{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 filter = format!(".mvn/socket-patch/prefixes-socket-patch-{uuid}.txt"); + (second, filter) + } + + /// [`pom_with_dep`] with `slf4j-simple` declared beside `slf4j-api`. + fn pom_with_two_deps() -> String { + pom_with_dep("\n 1.7.36", "").replace( + " ", + " \n org.slf4j\n \ + slf4j-simple\n 1.7.36\n \ + \n ", + ) + } + + /// The pin never waits for the filter's directory either. Where + /// `.mvn/socket-patch` cannot take a file (it cannot be listed or + /// written, or a file stands under its name) no filter file is planned + /// and the two lines are not added for one: the pins land, and one + /// line says so for the run. A file that is there and lists its pin's + /// path needs no write, and is as good as ever. + #[test] + fn maven_pin_lands_without_the_filter_where_the_directory_takes_no_file() { + let (second, second_filter) = second_maven_override(); + let unwritable = maven_filter_around(&MavenFilterAround { + dir_unwritable: true, + ..Default::default() + }); + let files = BTreeMap::from([ + ("pom.xml".to_string(), pom_with_two_deps()), + unwritable.clone(), + ]); + let deps = [granted_maven_override(), second]; + let r = rewrite_registry_redirect(&files, &deps); + assert!(r.files["pom.xml"].contains(MAVEN_SUFFIXED)); + assert!(r.files["pom.xml"].contains("1.7.36-socket.88888888")); + assert!( + !r.files.keys().any(|k| k.starts_with(".mvn/socket-patch/")), + "{:?}", + r.files.keys() + ); + // The Trusted Checksums settings go in as ever; no line of the + // filter's does. + assert_eq!( + r.files[MVN_CONFIG], + format!("{}\n", MVN_CONFIG_ARGS.join("\n")) + ); + assert_eq!( + warning_codes(&r), + ["redirect_maven_repository_filter_skipped"], + "once for the run: {:?}", + r.warnings + ); + let detail = &r.warnings[0].detail; + for part in [ + ".mvn/socket-patch cannot take a file", + "The pins landed all the same", + ] { + assert!(detail.contains(part), "{part}: {detail}"); + } + + // A checkout an earlier scan wired, whose directory takes no file + // any more: the first pin's file is there and lists its path, so + // nothing is said of it. The second pin lands without a file, and + // the lines, which serve the first, stay as they are. + let plain = BTreeMap::from([("pom.xml".to_string(), pom_with_two_deps())]); + let first = rewrite_registry_redirect(&plain, &deps[..1]); + let mut wired = plain.clone(); + wired.extend(first.files.clone()); + wired.extend([unwritable]); + let r = rewrite_registry_redirect(&wired, &deps); + assert!(r.files["pom.xml"].contains("1.7.36-socket.88888888")); + assert!(!r.files.contains_key(&second_filter)); + assert!(!r.files.contains_key(MAVEN_FILTER)); + assert!(!r.files.contains_key(MVN_CONFIG)); + assert_eq!( + warning_codes(&r), + ["redirect_maven_repository_filter_skipped"] + ); + } + + /// The filter's two lines, once in `.mvn/maven.config`, are the + /// project's own configuration. A `.mvn/jvm.config` or an environment + /// of the scanning machine that names the prefix filter stands against + /// adding them, and against nothing else: a pin that lands where they + /// are in place gets its file like any other, and no conflict is said. + #[test] + fn maven_filter_lines_in_place_are_not_left_to_the_machine() { + let (second, second_filter) = second_maven_override(); + let plain = BTreeMap::from([("pom.xml".to_string(), pom_with_two_deps())]); + let deps = [granted_maven_override(), second]; + let first = rewrite_registry_redirect(&plain, &deps[..1]); + let mut wired = plain.clone(); + wired.extend(first.files.clone()); + assert!(wired[MVN_CONFIG].contains(".mvn/socket-patch")); + let theirs = [ + maven_filter_around(&MavenFilterAround { + env: Some("MAVEN_OPTS".to_string()), + ..Default::default() + }), + ( + MVN_JVM_CONFIG.to_string(), + "-Xmx1g -Daether.remoteRepositoryFilter.prefixes=true\n".to_string(), + ), + ]; + for outside in theirs { + let mut there = wired.clone(); + there.extend([outside.clone()]); + let r = rewrite_registry_redirect(&there, &deps); + assert!(r.warnings.is_empty(), "{}: {:?}", outside.0, r.warnings); + assert_eq!( + r.files[&second_filter].lines().last(), + Some("/org/slf4j/slf4j-simple/1.7.36-socket.88888888"), + "{}", + outside.0 + ); + assert!(!r.files.contains_key(MVN_CONFIG), "{}", outside.0); + // Control: without the lines the same machine is a conflict. + let mut bare = plain.clone(); + bare.extend([outside.clone()]); + let r = rewrite_registry_redirect(&bare, &deps[..1]); + assert_eq!( + warning_codes(&r), + ["redirect_maven_repository_filter_conflict"], + "{}", + outside.0 + ); + } + } + + /// The directory line has one owner. A line that names + /// `.mvn/socket-patch` is hosted mode's with or without the switch + /// beside it, as the respelling and the rollback treat it: where the + /// switch went missing the pin's run puts it back, alone, and writes + /// the file. A switch the user set to something else is theirs, and a + /// rollback leaves it too: the filter is off, the run says so for the + /// patch in words of its own, and writes nothing for the filter. + #[test] + fn maven_lone_filter_directory_line_is_hosted_modes_own() { + use crate::formats::maven::repository_filter; + let [switch, dir] = repository_filter::config_args(RootDirectory::Launcher) else { + panic!("two lines"); + }; + let pom = pom_with_dep("\n 1.7.36", ""); + let checksums = format!("{}\n", MVN_CONFIG_ARGS.join("\n")); + let project = |config: String| { + BTreeMap::from([ + ("pom.xml".to_string(), pom.clone()), + (MVN_CONFIG.to_string(), config), + ]) + }; + + // The switch is missing: it is put back after what is there. + let lone = project(format!("{checksums}{dir}\n")); + let r = rewrite_registry_redirect(&lone, &[granted_maven_override()]); + assert_eq!(r.files[MVN_CONFIG], format!("{checksums}{dir}\n{switch}\n")); + assert!(r.files.contains_key(MAVEN_FILTER), "{:?}", r.files.keys()); + assert_eq!(warning_codes(&r), [MAVEN_FILTER_ENABLED]); + assert!( + r.edits.iter().any(|e| e.path == MVN_CONFIG + && e.action == "rewritten" + && e.key.as_deref() == Some("repositoryFilter")), + "{:?}", + r.edits + ); + // What a rollback takes out of that config is what it takes out + // of the one the lines were appended to whole. + assert_eq!( + repository_filter::strip_config(&r.files[MVN_CONFIG]).as_deref(), + Some(checksums.as_str()) + ); + + // The switch is there, and off. + let off = "-Daether.remoteRepositoryFilter.prefixes=false"; + let switched_off = project(format!("{checksums}{off}\n{dir}\n")); + let r = rewrite_registry_redirect(&switched_off, &[granted_maven_override()]); + assert!(r.files["pom.xml"].contains(MAVEN_SUFFIXED)); + assert!(!r.files.contains_key(MAVEN_FILTER)); + assert!(!r.files.contains_key(MVN_CONFIG)); + assert_eq!( + warning_codes(&r), + ["redirect_maven_repository_filter_conflict"] + ); + let detail = &r.warnings[0].detail; + for part in [ + ".mvn/maven.config switches Maven's repository prefix filter off", + off, + "remove that setting and scan again", + ] { + assert!(detail.contains(part), "{part}: {detail}"); + } + assert!(!detail.contains(" "), "one line of prose: {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) { @@ -12773,6 +14656,125 @@ mod tests { untouched(&r, "redirect_maven_selection_undetermined", "undetermined"); } + /// A dep the reactor planner plans, in a reactor root or in a single + /// pom whose declaration reads a `${property}`, is settled in one place + /// ([`settle_maven_plan`]). The checksum lines that a grant with a + /// malformed hash must not leave behind go with the pin there as they + /// do for a literal version: they are dropped where the plan wires the + /// dep, this run or an earlier one, and left where it wires nothing. + /// A plan that wires nothing touches no `.mvn` file at all: it writes + /// no filter line and no filter file either. + #[test] + fn maven_planned_dep_drops_stale_checksums_only_where_it_is_wired() { + let mut dep = granted_maven_override(); + dep.integrity.sha256 = Some("sha256-q83vEjRWeJA=".into()); + let stale = format!( + "{} org/slf4j/slf4j-api/{MAVEN_SUFFIXED}/slf4j-api-{MAVEN_SUFFIXED}.jar\n", + "c".repeat(64) + ); + let with_stale = |mut files: BTreeMap| { + files.insert(MVN_CHECKSUMS.to_string(), stale.clone()); + files + }; + let run = |files: &BTreeMap, picks: &[(&str, Result<&str, &str>)]| { + let modules: Vec<&str> = files + .keys() + .map(String::as_str) + .filter(|rel| rel.ends_with("pom.xml")) + .collect(); + let picks: Vec<_> = picks + .iter() + .map(|(pom, pick)| (*pom, "org.slf4j", "slf4j-api", *pick)) + .collect(); + let selection = MavenSelection::answering(&modules, &picks); + rewrite_registry_redirect_with_host( + files, + std::slice::from_ref(&dep), + &BTreeMap::new(), + None, + false, + &std::collections::BTreeSet::new(), + &yarnrc::OuterYarnMirror::default(), + &CratesIoSource::Registry, + Some(&selection), + ) + }; + let reactor = with_stale(poms(&[ + ("pom.xml", REACTOR_ROOT), + ("a/pom.xml", &reactor_module("a", "")), + ("b/pom.xml", &reactor_module("b", "")), + ])); + let property = with_stale(poms(&[( + "pom.xml", + &property_pom("1.7.36", ""), + )])); + + // Wired this run: the stale line goes, and the filter comes with + // the pin. Wired by that run and scanned again: a stale line that + // is back goes again, and nothing else is written. + for (what, files, picks, pinned) in [ + ( + "reactor", + &reactor, + &[("a/pom.xml", Ok("1.7.36")), ("b/pom.xml", Ok("2.0.9"))][..], + "a/pom.xml", + ), + ( + "property", + &property, + &[("pom.xml", Ok("1.7.36"))][..], + "pom.xml", + ), + ] { + let landed = run(files, picks); + assert!(landed.files[pinned].contains(MAVEN_SUFFIXED), "{what}"); + assert!( + !landed.files[MVN_CHECKSUMS].contains(MAVEN_SUFFIXED), + "{what}: {}", + landed.files[MVN_CHECKSUMS] + ); + assert!(landed.files.contains_key(MAVEN_FILTER), "{what}"); + + let mut wired = files.clone(); + wired.extend(landed.files.clone()); + let again = run(&with_stale(wired), picks); + assert_eq!( + again.files.keys().collect::>(), + [MVN_CHECKSUMS], + "{what}" + ); + assert!( + !again.files[MVN_CHECKSUMS].contains(MAVEN_SUFFIXED), + "{what}: {}", + again.files[MVN_CHECKSUMS] + ); + } + + // Planned, and not wired: no module's selection can be read and no + // pom names the version, so the plan is a note and nothing else. + let unread = "the pom of ch.qos.logback:logback-classic:1.4.14 is not in the local \ + Maven repository"; + let r = run( + &reactor, + &[("a/pom.xml", Err(unread)), ("b/pom.xml", Err(unread))], + ); + assert!(r.files.is_empty(), "reactor: {:?}", r.files.keys()); + assert!(r.edits.is_empty(), "reactor: {:?}", r.edits); + assert_eq!(warning_codes(&r), ["redirect_maven_selection_undetermined"]); + + // The same for a single pom: a property no pom of the checkout + // defines, in a build whose selection cannot be read. + let undefined = with_stale(poms(&[("pom.xml", &property_pom("1", ""))])); + let r = run(&undefined, &[("pom.xml", Err(unread))]); + assert!(r.files.is_empty(), "property: {:?}", r.files.keys()); + assert!(r.edits.is_empty(), "property: {:?}", r.edits); + assert!( + warning_codes(&r).contains(&"redirect_maven_dep_unpinned"), + "{:?}", + r.warnings + ); + } + /// `plain` as a hosted scan of an earlier release left it, and what /// that scan writes today: the project wired for `dep`, with the /// Trusted Checksums directory named through `${session.rootDirectory}` @@ -12833,7 +14835,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)); @@ -13450,10 +15455,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 \ @@ -13481,10 +15498,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 @@ -13533,7 +15555,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)); @@ -13600,9 +15625,12 @@ 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 + /// and, with the last repository that has a 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 exactly as it is, + /// read through no pom.) #[test] fn maven_reactor_last_pin_removed_takes_the_repository_and_checksums() { let files = poms(&[ @@ -13645,9 +15673,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 @@ -13748,7 +16256,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 \ @@ -35906,8 +38419,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 ); @@ -35917,7 +38434,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}" @@ -36161,6 +38682,147 @@ 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") + ); + } + + /// The filter's two lines, once committed, are the project's own. A + /// re-pin scanned on a machine whose environment names the prefix + /// filter, or beside a `.mvn/jvm.config` that does, used to take the + /// new generation for a conflict: it got no file, the superseded + /// repository went, and with no file left for the lines to serve the + /// run took the committed lines out. The new generation gets its file + /// like any other pin, and the lines stay. + #[test] + fn maven_repin_where_the_machine_names_the_filter_keeps_the_lines() { + use crate::formats::maven::repository_filter::file_rel; + let tok = "22222222-3333-4444-8555-666666666666"; + let (wired, _) = plan(&pom_project(), &maven(A, tok)); + assert!(wired[MVN_CONFIG].contains(".mvn/socket-patch")); + assert!(wired.contains_key(&file_rel(&format!("socket-patch-{A}")))); + let around = MavenFilterAround { + env: Some("MAVEN_OPTS".to_string()), + ..Default::default() + }; + let theirs = [ + ( + MAVEN_FILTER_KEY.to_string(), + serde_json::to_string(&around).unwrap(), + ), + ( + MVN_JVM_CONFIG.to_string(), + "-Daether.remoteRepositoryFilter.prefixes=true\n".to_string(), + ), + ]; + for outside in theirs { + let mut there = wired.clone(); + there.extend([outside.clone()]); + let (repinned, result) = plan(&there, &maven(B, tok)); + let what = &outside.0; + assert!(result.warnings.is_empty(), "{what}: {:?}", result.warnings); + assert!( + repinned["pom.xml"].contains("3.12.0-socket.bbbbbbbb"), + "{what}" + ); + assert_eq!( + repinned[&file_rel(&format!("socket-patch-{B}"))] + .lines() + .last(), + Some("/org/apache/commons/commons-lang3/3.12.0-socket.bbbbbbbb"), + "{what}" + ); + assert!( + !result.edits.iter().any(|e| e.path == MVN_CONFIG), + "{what}: {:?}", + result.edits + ); + assert_eq!(repinned[MVN_CONFIG], wired[MVN_CONFIG], "{what}"); + } + } + + /// A filter file written and then taken back within one run takes + /// the two lines the run added for it back as well. Two patches of one + /// artifact version in one run: the first lands and gets its file and + /// the lines, the second supersedes it, so the first one's repository + /// goes and its planned file is taken back, and the second gets no + /// file because something else stands under its name. With no filter + /// file left for them to serve, the lines go the way they came: the + /// config holds the Trusted Checksums settings alone, and the run + /// reports neither the lines nor that it switched the filter on. + #[test] + fn maven_filter_lines_added_for_a_file_taken_back_go_with_it() { + use crate::formats::maven::repository_filter::file_rel; + let tok = "22222222-3333-4444-8555-666666666666"; + let pom = pom_project()["pom.xml"] + .replace( + "3.12.0", + "${lang.version}", + ) + .replace( + " ", + " \n 3.12.0\n \n \ + ", + ); + assert!(pom.contains("${lang.version}") && pom.contains("")); + let around = MavenFilterAround { + occupied: vec![file_rel(&format!("socket-patch-{B}"))], + ..Default::default() + }; + let files = BTreeMap::from([ + ("pom.xml".to_string(), pom), + ( + MAVEN_FILTER_KEY.to_string(), + serde_json::to_string(&around).unwrap(), + ), + ]); + let r = rewrite_registry_redirect(&files, &[maven(A, tok), maven(B, tok)]); + let pinned = &r.files["pom.xml"]; + assert!( + pinned.contains("3.12.0-socket.bbbbbbbb"), + "{pinned}" + ); + assert!( + pinned.contains(&format!("socket-patch-{B}")) && !pinned.contains(A), + "{pinned}" + ); + assert_eq!( + r.files.keys().collect::>(), + [MVN_CHECKSUMS, MVN_CONFIG, "pom.xml"] + ); + assert_eq!( + r.files[MVN_CONFIG], + format!("{}\n", MVN_CONFIG_ARGS.join("\n")), + "no line of the filter's is left" + ); + let of_the_config: Vec> = r + .edits + .iter() + .filter(|e| e.path == MVN_CONFIG) + .map(|e| e.key.as_deref()) + .collect(); + assert_eq!(of_the_config, [Some("trustedChecksums")], "{:?}", r.edits); + assert!( + !r.edits.iter().any(|e| e.kind == MAVEN_FILTER_EDIT), + "{:?}", + r.edits + ); + let codes: Vec<&str> = r.warnings.iter().map(|w| w.code.as_str()).collect(); + assert_eq!(codes, ["redirect_maven_repository_filter_skipped"]); } /// Another artifact's live pin whose uuid shares the superseded @@ -36305,7 +38967,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 b2903acf3f..aef74700ec 100644 --- a/crates/socket-patch-core/src/patch/redirect/staged.rs +++ b/crates/socket-patch-core/src/patch/redirect/staged.rs @@ -182,7 +182,7 @@ async fn check<'a>(project_root: &Path, file: Pending<'a>) -> Result /// Whether this process may create, replace and remove entries in `dir`, /// asked without writing (a dry run asks too). #[cfg(unix)] -fn entries_writable(dir: &Path) -> std::io::Result<()> { +pub(super) fn entries_writable(dir: &Path) -> std::io::Result<()> { use std::os::unix::ffi::OsStrExt as _; let dir = std::ffi::CString::new(dir.as_os_str().as_bytes()) .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?; @@ -198,7 +198,7 @@ fn entries_writable(dir: &Path) -> std::io::Result<()> { /// only a missing directory is caught up front, and any other failure by /// the flush's put-back. #[cfg(not(unix))] -fn entries_writable(dir: &Path) -> std::io::Result<()> { +pub(super) fn entries_writable(dir: &Path) -> std::io::Result<()> { std::fs::metadata(dir).map(|_| ()) } @@ -212,25 +212,34 @@ fn entries_writable(dir: &Path) -> std::io::Result<()> { /// lock keeps its bits. The now-empty parent directory of a deleted file /// (the `.cargo/` a registry block was written into) is pruned best-effort /// once every file has landed, so a put-back still finds it; the project -/// root itself is never touched. +/// root itself is never touched. The directories are pruned deepest +/// first: one that holds another of them (`.mvn`, over `.mvn/checksums/` +/// and `.mvn/socket-patch/`) is empty only once those have gone. pub(super) async fn flush(checked: &[Checked<'_>]) -> Result<(), FlushError> { for (at, file) in checked.iter().enumerate() { if let Err(failure) = file.write().await { return Err(put_back(&checked[..at], failure).await); } } - for file in checked.iter().filter(|file| file.content.is_none()) { - let in_subdir = Path::new(file.rel) + let in_subdir = |file: &&Checked<'_>| { + Path::new(file.rel) .parent() - .is_some_and(|parent| !parent.as_os_str().is_empty()); - if in_subdir { - if let Some(parent) = file.path.parent() { - // `remove_dir` refuses a non-empty directory, so this only - // ever removes the husk the revert emptied — after a - // vendored run's group commit when the removal was captured. - crate::utils::group_commit::remove_dir_after_commit(parent).await; - } - } + .is_some_and(|parent| !parent.as_os_str().is_empty()) + }; + let mut emptied: Vec<&Path> = checked + .iter() + .filter(|file| file.content.is_none()) + .filter(in_subdir) + .filter_map(|file| file.path.parent()) + .collect(); + let depth = |dir: &Path| dir.components().count(); + emptied.sort_by(|a, b| depth(b).cmp(&depth(a)).then(a.cmp(b))); + emptied.dedup(); + for dir in emptied { + // `remove_dir` refuses a non-empty directory, so this only ever + // removes the husk the revert emptied — after a vendored run's + // group commit when the removal was captured. + crate::utils::group_commit::remove_dir_after_commit(dir).await; } Ok(()) } @@ -380,14 +389,16 @@ mod tests { const SUMS: &str = ".mvn/checksums/checksums.sha256"; const CONFIG: &str = ".mvn/maven.config"; + const FILTER: &str = + ".mvn/socket-patch/prefixes-socket-patch-77777777-7777-7777-7777-777777777777.txt"; const POM: &str = "pom.xml"; - /// A hosted Maven pin wired through three files, which the restore - /// flushes in this order: [`SUMS`] (deleted), [`CONFIG`] (deleted), - /// [`POM`] (rewritten). - fn maven_project() -> tempfile::TempDir { + /// A hosted Maven pin as a scan wires it today, through four files, + /// which the restore flushes in this order: [`SUMS`] (deleted), + /// [`CONFIG`] (deleted), [`FILTER`] (deleted), [`POM`] (rewritten). + fn maven_project_with_filter() -> tempfile::TempDir { let tmp = tempfile::tempdir().unwrap(); - for rel in [SUMS, CONFIG, POM] { + for rel in [SUMS, CONFIG, FILTER, POM] { let fixture = format!( "{}/tests/fixtures/redirect/maven/pom/basic/expected/{rel}", env!("CARGO_MANIFEST_DIR") @@ -399,6 +410,24 @@ mod tests { tmp } + /// That pin wired through three files, without the repository filter: + /// [`SUMS`], [`CONFIG`], [`POM`]. + /// + /// The config holds the Trusted Checksums settings and nothing else: + /// 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 = maven_project_with_filter(); + std::fs::remove_dir_all(tmp.path().join(FILTER).parent().unwrap()).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 + } + async fn restore(root: &Path, dry_run: bool) -> RestoreOutcome { let pins = [HostedPin { purl: "pkg:maven/org.slf4j/slf4j-api@1.7.36".into(), @@ -448,17 +477,26 @@ mod tests { assert_eq!(outcome.reverted_files, [SUMS, CONFIG, POM]); } - /// The fixture restores cleanly: all three files are flushed. + /// The fixture restores cleanly: all three files are flushed. So does + /// the project as a scan wires it today, with its repository filter + /// file: `.mvn`, which the scan made, goes with the last directory + /// under it. (An empty `.mvn` left behind would mark the project's + /// root directory for Maven.) #[tokio::test] async fn the_three_file_restore_lands_whole() { - let tmp = maven_project(); - let outcome = restore(tmp.path(), false).await; - assert_eq!(outcome.flush_error, None); - assert_eq!(outcome.restored().count(), 1); - assert_eq!(outcome.reverted_files, [SUMS, CONFIG, POM]); - let after = tree(tmp.path()); - assert_eq!(after.keys().collect::>(), [POM], "{after:?}"); - assert!(!tmp.path().join(".mvn").exists(), "the emptied dirs go"); + let wired: [(tempfile::TempDir, &[&str]); 2] = [ + (maven_project(), &[SUMS, CONFIG, POM]), + (maven_project_with_filter(), &[SUMS, CONFIG, FILTER, POM]), + ]; + for (tmp, files) in wired { + let outcome = restore(tmp.path(), false).await; + assert_eq!(outcome.flush_error, None); + assert_eq!(outcome.restored().count(), 1); + assert_eq!(outcome.reverted_files, files); + let after = tree(tmp.path()); + assert_eq!(after.keys().collect::>(), [POM], "{after:?}"); + assert!(!tmp.path().join(".mvn").exists(), "the emptied dirs go"); + } } /// File 2 of 3 is a symbolic link: the restore is refused before file 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 f20cb2fdd0..9643fdcab7 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, }; @@ -574,8 +574,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 @@ -583,17 +585,140 @@ 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. +/// +/// Removing a file is a courtesy, like taking the lines out: the flush is +/// all or nothing, and one removal it would not carry out (a directory +/// that does not take the write, a file edited since it was read) would +/// leave every pin unrestored. Such a file stays, like one that cannot be +/// read, and so do the lines; no pom declares its repository, so Maven +/// does not read it, and the restore names each file it left. +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; + let mut kept: Vec = Vec::new(); + 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)); + // Another pin's file, whose repository a pom still declares. + if !ours { + left = true; + continue; + } + // Read first: the flush then knows the bytes it removes. + let read = matches!(view.read(&rel).await, Ok(Some(_))); + if !read || !view.remove_if_writable(&rel).await { + left = true; + kept.push(rel); + } + } + if !kept.is_empty() { + result.warnings.push(( + MAVEN_FILTER_LEFT, + format!( + "{files} could not be removed (the file cannot be read, {dir} does not take \ + the write, or the file changed while the restore was worked out), so it was \ + left where it is, with the two lines of {MVN_CONFIG} that name its directory. \ + No pom declares its repository any more, so Maven does not read it; remove \ + them by hand if nothing else needs them", + files = kept.join(", "), + dir = repository_filter::DIR, + ), + )); + } + !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, @@ -657,13 +782,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, @@ -671,10 +798,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 @@ -690,21 +816,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)); + } } } @@ -1170,6 +1294,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 } @@ -1206,8 +1358,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); @@ -1251,9 +1409,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); @@ -1269,13 +1427,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 \ @@ -1905,6 +2070,435 @@ 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 + ); + } + + /// Nor is removing a filter file the reason a restore is refused. In + /// a directory that can be listed and does not take a write, the + /// pin's file cannot be removed, and the flush is all or nothing: the + /// file stays, with the lines that name its directory, the pin is + /// restored all the same, and the restore says what it left. The same + /// for a file that cannot be read: every file left is named. (Root + /// reads and writes anywhere, so there is nothing to see as root.) + #[cfg(unix)] + #[tokio::test] + async fn a_filter_file_that_cannot_be_removed_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")); + // (The directory does not take the write, or the file cannot be + // read: each is left, and named.) + for (dry_run, in_the_way) in [ + (true, ".mvn/socket-patch"), + (false, ".mvn/socket-patch"), + (false, FILTER), + ] { + 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(in_the_way); + let (shut, open) = match in_the_way { + FILTER => (0o000, 0o644), + _ => (0o555, 0o755), + }; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(shut)).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, + dry_run, + ..RestoreOptions::default() + }; + let outcome = restore_upstream(root, &pins, &opts).await; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(open)).unwrap(); + assert_eq!(outcome.flush_error, None, "dry_run={dry_run}"); + assert_eq!(outcome.pins[0].status, PinStatus::Restored); + 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].starts_with(&format!("{FILTER} could not be removed")), + "{}", + left[0] + ); + assert!(root.join(FILTER).is_file(), "the file stays"); + if dry_run { + continue; + } + assert_eq!( + std::fs::read_to_string(root.join("pom.xml")).unwrap(), + fixture("basic", "input", "pom.xml") + ); + assert!(!root.join(".mvn/checksums/checksums.sha256").exists()); + let after = std::fs::read_to_string(root.join(".mvn/maven.config")).unwrap(); + assert!( + after.contains(".mvn/socket-patch") && after.starts_with("-B\n"), + "the lines stay: {after}" + ); + } + } + /// 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 1006a59d84..7be7d792ad 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -753,19 +753,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 ba20ca8b93..3ffbf4603f 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 23df82ecd2..0580ec6158 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 414c0a5a59..0c115a0a66 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 ba20ca8b93..3ffbf4603f 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 7fa3ab2697..c92d9fb820 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 23df82ecd2..0580ec6158 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 fe7c5067dd..e1ed0188b3 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 ba20ca8b93..3ffbf4603f 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 fe51488c70..e04e519bab 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 23df82ecd2..0580ec6158 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 fe7c5067dd..e1ed0188b3 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 ba20ca8b93..3ffbf4603f 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 ba20ca8b93..3ffbf4603f 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 3a8160e034..3999799450 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 6825ca5267..3fe5e7a04c 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 e2dba7d24f..9e60536836 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 0000000000..a020296d10 --- /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 ba20ca8b93..3ffbf4603f 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 fe51488c70..e04e519bab 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 d3b91570d0..913ad0e025 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 0000000000..a020296d10 --- /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 6ea0d47382..435dc9614a 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 3d46044f76..6f43955173 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 0000000000..a020296d10 --- /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 81f6e01732..c633853a83 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 fe51488c70..e04e519bab 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 ba20ca8b93..3ffbf4603f 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 fe51488c70..e04e519bab 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 23df82ecd2..0580ec6158 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 fe7c5067dd..e1ed0188b3 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 ba20ca8b93..3ffbf4603f 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 fe51488c70..e04e519bab 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 1233a9a57f..40df78d95c 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 fe51488c70..e04e519bab 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 6e5939b9af..d85597fd61 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 fe51488c70..e04e519bab 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 791f6cc837..5c58f8193f 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 44c9e80ea1..ccc631b4c7 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 6e5939b9af..d85597fd61 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 44c9e80ea1..ccc631b4c7 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 0000000000..3a8160e034 --- /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 0000000000..0630523d47 --- /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 0000000000..71c583f774 --- /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 0000000000..a5a2bc7f56 --- /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 0000000000..b5989daf3e --- /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 0000000000..01e3b84f91 --- /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 0000000000..c38ca63578 --- /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 0000000000..53deb25b89 --- /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 23df82ecd2..0580ec6158 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 fe7c5067dd..e1ed0188b3 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 ba20ca8b93..3ffbf4603f 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 fe51488c70..e04e519bab 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 23df82ecd2..0580ec6158 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 4f1f947e8c..1d18f03ce9 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 0000000000..a020296d10 --- /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 93724ee25b..812f2a0b8f 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 6da55c8a8c..ecb00b4d9b 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 4f1f947e8c..1d18f03ce9 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 0000000000..e0e90d548d --- /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 9ba56a99f4..019b07786d 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 7feddd7e69..f888385962 100644 --- a/crates/socket-patch-core/tests/upstream_restore_golden.rs +++ b/crates/socket-patch-core/tests/upstream_restore_golden.rs @@ -3770,10 +3770,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", ]; @@ -3805,9 +3809,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 5773151e4a..793976fb2e 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1617,6 +1617,93 @@ 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` already configures the + prefix filter another way, 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. The same holds where the two + lines are not there yet and `.mvn/jvm.config` names the filter, or the environment + of the machine that scans does (`MAVEN_OPTS`, `MAVEN_ARGS`, `JAVA_TOOL_OPTIONS`, + `JDK_JAVA_OPTIONS`). 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. Once the two lines + are committed they are the project's own: a later pin gets its file on any + machine, whatever that machine's environment says. + - **The directory line is hosted mode's.** If the line that names `.mvn/socket-patch` + is there and the switch beside it went missing (a hand edit, a merge), the next + pin that lands puts the switch back and writes its file. If you set the switch to + anything but `true`, the filter is off and stays off: nothing is written for it, + and `redirect_maven_repository_filter_conflict` says so. Remove that setting and + scan again to filter. `rollback` treats the two the same way: it takes the + directory line out and leaves a switch of your own. + - **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; a `.mvn/socket-patch` that cannot take a file (it cannot be + listed or written, or a file stands under its name); or a link, a directory or an + unreadable file 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. A file that is there and no longer lists the pinned path is + rewritten by the next scan, pin in place or not: with the filter on, Maven 3.9.2 + and later refuse the pinned version over such a file. + - **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, a filter file they cannot remove (it + cannot be read, or its directory does not take the write) stays with the lines, + 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