diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md
index 23333d7946..bf2818b518 100644
--- a/crates/socket-patch-cli/CLI_CONTRACT.md
+++ b/crates/socket-patch-cli/CLI_CONTRACT.md
@@ -2016,7 +2016,7 @@ Env-only knobs used for hosted upstream restoration and JVM metadata verificatio
|---|---|---|
| `SOCKET_NPM_REGISTRY` | `https://registry.npmjs.org` | Base for npm version documents (`//`, a scoped name's `/` as `%2f`; `dist.tarball` / `integrity` / `shasum`) the npm-family and vlt upstream restore reads, unless the project names another registry (yarn berry `npmRegistryServer`, pnpm's lock-sibling `.npmrc` `registry` / `@scope:registry` or pnpm-workspace.yaml `registry` / `registries` as the pnpm major reads them, vlt's node registry), whose document is read first. |
| `SOCKET_GOPROXY` | `https://proxy.golang.org` | Go module proxy used for upstream restoration, honoring `GOPROXY`, `GONOPROXY` and `GOPRIVATE`. Like every Go setting socket-patch reads (`GOMODCACHE`, `GOPATH`, `GOWORK`, `GOFLAGS`, `GOSUMDB`, `GONOSUMDB`), each resolves as go resolves it: the environment, then the `go env -w` file (`$GOENV`, default `os.UserConfigDir()/go/env`; `GOENV=off` disables it), then go's default. |
-| `SOCKET_MAVEN_REGISTRY` | `https://repo1.maven.org/maven2` | maven2 base for the fallback upstream-pom download. |
+| `SOCKET_MAVEN_REGISTRY` | `https://repo1.maven.org/maven2` | maven2 base for the upstream files the JVM backends read: the fallback upstream-pom download, the upstream jar and checksums vendoring compares a patched jar with, and the original jar an agent-mode `rollback` restores when the project holds no backup. |
| `SOCKET_CRATES_INDEX` | `https://index.crates.io` | v5.0 upstream restore: the crates.io sparse index whose `checksum` a restored `Cargo.lock` entry gets back. |
| `SOCKET_GOSUMDB_URL` | `https://sum.golang.org` | v5.0 upstream restore: the checksum database the restored go.sum lines are checked against. Without it, `GOSUMDB=off` or a module matching `GONOSUMDB` (default `GOPRIVATE`) skips the database and the hashes come from the module proxy's bytes alone (`SOCKET_GOPROXY` above). |
| `SOCKET_PYPI_JSON_API` | `https://pypi.org/pypi` | PyPI's JSON API (`///json`): the release files whose sha256 the upstream restore writes back into every Python lock format. |
@@ -2221,7 +2221,7 @@ command's integration tests check its output.
| `vendor_unwired` | `skipped` | vex: a vendor-ledger entry whose committed artifact no lockfile/config wires any more (reverted lock, leftover ledger or artifact). Applies under `--no-verify` too. |
| `redirect_unwired` | `skipped` | vex: a hosted record (this run's, or a pre-v5 redirect ledger's) whose hosted patch no lockfile wires any more (and no manifest entry owns the purl). Applies under `--no-verify` too. |
| `wiring_conflict` | `skipped` | vex (manifest-less): the lockfiles wire one package to two or more different patches (e.g. a stale sibling lock); which one the build installs is undecidable, so none is attested. |
-| `hash_mismatch` / `not_applied` / `file_not_found` / `package_not_found` / `no_files` / `vendor_*` | `skipped` | vex: verification omissions — the installed copy (agent / hosted) or the committed artifact (`vendor_hash_mismatch`, `vendor_artifact_missing`, `vendor_artifact_unreadable`, `vendor_artifact_non_canonical`, `vendor_inventory_mismatch`, `vendor_uuid_mismatch`, `vendor_path_unsafe`) does not carry the patched bytes, or nothing is installed. `vendor_artifact_non_canonical`: a committed npm tarball holds a second entry the installers would extract over one of the patch's files — the same path under another top-level directory, a second or case-variant spelling of the name, a link, or a non-directory where one of the file's parent directories must be. npm-family installers strip the first path segment whatever it is, extract links as well as files and let a later entry overwrite an earlier one, so such a tarball can hold the patched file where it is checked and install the original (`vendor --check` reports it as a corrupt artifact that `repair` restores). Only the patch's own files are judged: an upstream tarball with a link, a non-ASCII name or a case twin elsewhere, which vendoring accepts, keeps verifying. `vendor_lock_pin_mismatch` (bun): the artifact holds the patch, but the `bun.lock` tuple or `bun.lockb` record that resolves to it carries a digest that is not the tarball's sha512 (a pin under any other algorithm is not one vendoring wrote), so an install does not deliver it — Bun 1.3.10+ fails the integrity check on a cold cache, and Bun 1.4 keys its tarball cache by that digest and installs whatever cached tarball has it. `vendor --check` reports the same as a wiring failure (exit 1) with the remedy, re-running `scan --mode vendored`, which rewrites the pin. A tuple without a digest (the 2-tuple Bun 1.1.39 to 1.3.9 re-save) has no pin to be wrong. `vendor_manifest_unverifiable`: a vendored vlt directory verified without its vendor ledger (from `vlt-lock.json` alone) holds a `package.json` with its devDependencies stripped, and the patched `package.json` blob is not in `.socket/blobs`, so it cannot be checked. A lockfile-pinned hosted reference with nothing installed attests instead of `package_not_found` (see "Manifest-less VEX"). |
+| `hash_mismatch` / `not_applied` / `file_not_found` / `package_not_found` / `no_files` / `vendor_*` | `skipped` | vex: verification omissions — the installed copy (agent / hosted) or the committed artifact (`vendor_hash_mismatch`, `vendor_artifact_missing`, `vendor_artifact_unreadable`, `vendor_artifact_too_large`, `vendor_artifact_non_canonical`, `vendor_inventory_mismatch`, `vendor_uuid_mismatch`, `vendor_path_unsafe`) does not carry the patched bytes, or nothing is installed. `vendor_artifact_too_large` (jars): the committed jar is past the limits jars are read within (see [Vendored JVM support](#vendored-jvm-support-v5)), so its contents were not checked (`vendor --check` reports it as a corrupt artifact that `repair` restores from the recorded jar). `vendor_artifact_non_canonical`: a committed npm tarball holds a second entry the installers would extract over one of the patch's files — the same path under another top-level directory, a second or case-variant spelling of the name, a link, or a non-directory where one of the file's parent directories must be. npm-family installers strip the first path segment whatever it is, extract links as well as files and let a later entry overwrite an earlier one, so such a tarball can hold the patched file where it is checked and install the original (`vendor --check` reports it as a corrupt artifact that `repair` restores). Only the patch's own files are judged: an upstream tarball with a link, a non-ASCII name or a case twin elsewhere, which vendoring accepts, keeps verifying. `vendor_lock_pin_mismatch` (bun): the artifact holds the patch, but the `bun.lock` tuple or `bun.lockb` record that resolves to it carries a digest that is not the tarball's sha512 (a pin under any other algorithm is not one vendoring wrote), so an install does not deliver it — Bun 1.3.10+ fails the integrity check on a cold cache, and Bun 1.4 keys its tarball cache by that digest and installs whatever cached tarball has it. `vendor --check` reports the same as a wiring failure (exit 1) with the remedy, re-running `scan --mode vendored`, which rewrites the pin. A tuple without a digest (the 2-tuple Bun 1.1.39 to 1.3.9 re-save) has no pin to be wrong. `vendor_manifest_unverifiable`: a vendored vlt directory verified without its vendor ledger (from `vlt-lock.json` alone) holds a `package.json` with its devDependencies stripped, and the patched `package.json` blob is not in `.socket/blobs`, so it cannot be checked. A lockfile-pinned hosted reference with nothing installed attests instead of `package_not_found` (see "Manifest-less VEX"). |
| `not_applied` / `hash_mismatch` / `file_not_found` / `no_matching_variant` | `failed` | `apply --check` (v5.0): an installed copy of the patch does not verify (still unpatched; neither the original nor the patched bytes; a patched file missing; a copy of a release-variant base that holds none of the manifest's variants, keyed by the base purl). Exit 1, status `partialFailure`. |
| `redirect_unconfirmed` | `skipped` (`details.mode: "hosted"`) | hosted `scan` / `get` (v5.0, additive): the patch was granted but no lockfile entry pinning it could be rewritten. The status and exit code are unchanged for now, pending the open hosted exit-policy decision (#704); `--silent` hides the human line. |
| `lockfile_unreadable` / `lockfile_unparseable` / `patched_ref_invalid` / `patched_ref_unattributable` | run-level `warnings[]` | vex (every form): lockfile-discovery diagnostics — see "Manifest-less VEX (lockfile discovery)". Never flip the exit on their own. |
@@ -2868,6 +2868,39 @@ entries use ecosystem `jvm` with Maven PURLs. Revert, remove, rollback and repai
share the v5 vendored backend; existing prototype wiring remains readable.
See [the JVM design](../../docs/design/maven-vendoring.md) for supported shapes.
+Vendoring a Maven or Gradle patch takes its jar from the patch service and needs no
+upstream registry for it. The service's jar is checked as it was served (transfer
+integrity, and every member of the patch record at its `afterHash`) and committed. No
+copy of the original jar is downloaded to compare it with, and none is missed: a
+registry that cannot be reached neither refuses the vendoring nor adds a warning.
+
+One comparison is made, because it costs no network and protects the build. When the
+original jar is already in the build's local repository (the Maven local repository
+or a Gradle cache), every entry the JVM would load must hold the same content in it
+and in the service's jar, whatever unix mode the entry carries; the record's members
+and signature files (`META-INF/*.SF`, `.RSA`, `.DSA`, `.EC`) are exempt and directory
+entries may differ. A difference means the project builds with a jar that is not the
+one the patch was made from (an internal rebuild under the same coordinates, say), so
+the service's jar would change more than the patch: the vendoring is refused with
+`vendor_prebuilt_integrity_mismatch`, the detail naming up to three such members, and
+nothing is committed or wired. With no local copy there is nothing to compare. An
+online re-run over a committed tree makes the same comparison with the committed jar
+and needs no registry for the jar either. Upstream metadata (the pom, its parents,
+Gradle module metadata, classifier jars) is still read from the local caches and the
+registry, as before.
+
+Jars are read within fixed limits, counted on the bytes actually inflated and on the
+archive's own entry count, never on the sizes an archive declares: 200,000 entries
+and 64 MiB of central directory (read from the end record the zip reader would take,
+before the directory is parsed), and per pass over one jar 1 GiB inflated and at most 100 times
+the jar's own size (a jar smaller than 655 KiB may still inflate to 64 MiB). A jar
+past a limit is `vendor_artifact_too_large`: a refusal when vendoring (the detail names the limit),
+the `vex` omission tag and the `vendor --check` reason for a committed jar (naming the limit), which
+`repair` restores from the recorded one, and the error of a `repair` whose own
+download is past them. Jar names are read as the JVM
+reads them, so non-ASCII names and names that differ only in case (`a.class` beside
+`A.class`) verify and repair like any other.
+
`vendor --check` is an offline, read-only audit. Healthy entries emit `verified`
with `vendor_check_ok`; drift emits `failed` with `vendor_check_failed`, a
`partialFailure` envelope and exit 1. Drift covers the committed artifact and its
@@ -3190,6 +3223,7 @@ Run-level `warnings[]` entries for these carry an additive `level` field (`info`
| `gradle_build_ignores_m2` | `warn` | The build declares no `mavenLocal()`, and modules its locks (or the manifest) name exist only in `~/.m2`; they are not scanned. |
| `gradle_maven_local_undetermined` | `info` | `mavenLocal()` could not be ruled out (an unreadable script or init script), so `~/.m2` stays a scan root. |
| `gradle_user_home_differs` | `info` | The passwd home differs from `$HOME`, so Gradle's cache is not under `$HOME/.gradle`. Never emitted with `--global-prefix`. |
+| `maven_local_repository_undetermined` | `warn` | A Maven build's `.mvn/maven.config` names one local repository to Maven before 3.9 (which splits the file on whitespace) and another to Maven 3.9 and later (one argument per line), both directories exist, and the project has no Maven Wrapper to say which Maven builds it. Neither is scanned or patched (also reported by `apply`); set `MAVEN_REPO_LOCAL` to the one the build uses. |
A package crawled from a Gradle cache gets an additive `inLock` boolean when the
`--cwd` is a Gradle build whose lock files were read (local and global runs): `true`
@@ -3212,14 +3246,66 @@ across every consumed copy: one download, one backup per distinct original under
patched bytes: never the read-only cache, but also a `~/.m2` copy a Gradle-only build
no longer reads (an earlier apply wrote it while the build declared `mavenLocal()`,
or before v5.0 gated `~/.m2`; leaving it would strand the shared jar patched once
-`remove` drops the record). It restores from the backup, else, online and for a
-Gradle copy only, from an upstream download that hashes to the copy's hash
-directory. Such an unread `~/.m2` copy never fails the run: one that holds bytes
+`remove` drops the record). It restores from the backup in this project's
+`.socket/jvm-originals/`, else, online, from an upstream download. For a Gradle copy
+that is one that hashes to the copy's hash directory. For a `~/.m2` copy it is the
+registry's jar (Maven Central, or `SOCKET_MAVEN_REGISTRY`), taken only when it
+matches the checksum the registry publishes beside it (`.sha512`, else `.sha1`) and
+is the jar the copy was patched from: the record's members at their `beforeHash`,
+every other member the patched copy's own. The `.sha1` beside the jar cannot vouch
+for it, since the swap rewrote that file for the patched jar. This is what restores a
+jar that another project, or an earlier workspace over a persistent `~/.m2`, patched:
+a copy that is already patched when `apply` finds it gets no backup here. The copy
+is read before anything is looked for or downloaded: a `~/.m2` copy that is past the
+jar limits or cannot be read as a jar fails with that cause (`jvm_jar_too_large` for
+the former), never as a missing backup. A Gradle copy's backup is found by its hash
+directory, without reading the copy. Such an
+unread `~/.m2` copy never fails the run: one that holds bytes
that are neither side of the record (another build applied a different patch there,
or `mvn install` rebuilt it), lacks a file, or is a swapped jar whose original this
project never backed up is left as it is with `gradle_m2_copy_not_restored`, and
`remove` still drops the record.
+A project's `.mvn/maven.config` chooses where these commands write. For a Maven
+build, `-Dmaven.repo.local` there names the local repository, so it can point `apply`,
+`rollback` and `remove` at any directory laid out as a Maven repository, one outside
+the project and the home directory included, exactly as it points Maven there when the
+project is built. What socket-patch does in that directory is what it does in
+`~/.m2`: it replaces a jar (or a file of a version directory) whose content is the
+known original of a patch record with the patch service's build of it, rewrites the
+checksum files beside it (`.sha1`, `.md5`) to match, and puts both back on rollback.
+It writes nothing else there. Anyone who points a build's local repository somewhere
+has chosen that for Maven as well. `MAVEN_REPO_LOCAL` takes the choice back: it names
+the repository whatever the project's config says.
+
+Before a swap the service's jar is compared with each installed jar, member by
+member, hashing as it goes: every entry the JVM would load must hold the same content
+in both, whatever unix mode the entry carries (the JVM ignores it, so an entry with
+a symlink's mode bits is a class like any other). The record's members and signature
+files (`META-INF/*.SF`, `.RSA`, `.DSA`, `.EC`) are exempt, and directory entries may
+differ. A copy that differs fails with `jvm_agent_service_jar_mismatch`, naming up
+to three added, missing or changed members, and is left as it is; the other copies
+are still swapped.
+
+Jars are read within fixed limits, counted on the bytes actually inflated and on the
+archive's own entry count, never on the sizes an archive declares: 200,000 entries
+and 64 MiB of central directory (both read from the end record the zip reader would
+take, wherever in the file it sits and whatever follows it, before the directory is
+parsed, so a directory of millions of records is refused unread; an end record inside
+a member's data, such as a jar stored in a fat jar, is not one the reader can take
+and is not counted), and
+per pass over one jar 1 GiB inflated and at most 100 times the jar's own size (a
+jar smaller than 655 KiB may still inflate to 64 MiB). The largest jars measured on
+Maven Central are far inside them (`hive-exec-3.1.3.jar`: 23,728 entries, 93 MiB
+inflated). A jar past a limit is `jvm_jar_too_large`, and the message names the
+limit; hosted mode, which never reads the jar, still applies.
+
+A copy whose patched member is neither the original nor this patch's (another
+revision of the patch applied from another project or workspace, or a rebuilt jar)
+fails as a hash mismatch; the message says so and how to get back to the original
+(roll that patch back where it was applied, or delete the version directory so the
+build downloads the jar again).
+
Run-level `warnings[]` codes (a refusal is also a `failed` event whose `error`
starts with the code):
@@ -3235,10 +3321,11 @@ starts with the code):
| `gradle_jar_locked_by_daemon` | that copy fails | Windows only: the jar is held open (errors 32, 33, 303, or 5 on an existing writable file), normally by a Gradle daemon. Also reported by rollback. Run `gradle --stop` and retry. |
| `jvm_agent_service_required` | refused, exit 1 | A member-keyed record needs the patch service's jar, and the run is offline, the service is disabled or pending, or it did not provide one. Nothing is written. |
| `jvm_agent_service_integrity` | refused, exit 1 | The service jar failed transfer-integrity verification. Nothing is written. |
-| `jvm_agent_service_jar_mismatch` | refused, exit 1 | The service jar does not carry the record's `afterHash` members, is unreadable, or differs from the installed jar outside the patched members. Nothing is written. |
+| `jvm_agent_service_jar_mismatch` | refused, exit 1; or that copy fails | The service jar does not carry the record's `afterHash` members or cannot be read: the swap is refused and nothing is written. Or it differs from one installed jar outside the patched members: that copy fails and is left as it is (its `error` starts with the code and names the members), the other copies are still swapped, and the run exits 1. |
+| `jvm_jar_too_large` | refused, exit 1; or that copy fails | A jar is past the limits jars are read within (above). The service's jar refuses the swap with nothing written; an installed jar fails its copy, which is left as it is. Also reported by `rollback` for a `~/.m2` copy that cannot be compared with a backup or with upstream. The message names the limit that was passed. |
| `jvm_jar_backup_failed` | refused, exit 1 | The original jar could not be backed up before the swap. Nothing is written. |
| `gradle_rollback_hash_mismatch` | rollback: that copy fails | A file restored into a Gradle hash directory does not hash to the directory's name (the sha1 Gradle verified on download): the before-blob is not that download. The file is left as it is and the result fails; delete that hash directory so Gradle downloads it again. |
-| `jvm_jar_backup_missing` | rollback: that copy fails | No backup of the original jar exists (and, for a Gradle copy, no upstream download matched its hash directory, or the run is offline). The copy is left as it is. |
+| `jvm_jar_backup_missing` | rollback: that copy fails | This project's `.socket/jvm-originals/` holds no backup of the original jar (another project or an earlier workspace applied the patch), and no upstream copy could be verified: the run is offline, the registry does not serve the jar or publishes no checksum for it, the download does not match that checksum or is not the jar the copy was patched from, or, for a Gradle copy, it does not hash to the hash directory. The copy is left as it is. The message says which of these it was and how to recover: run the rollback from the project that applied the patch, or delete the version directory so the build downloads the jar again. |
| `gradle_m2_copy_not_restored` | rollback / remove: warning | A `~/.m2` copy this Gradle-only build does not read could not be restored (its bytes are neither side of the record, a file is missing, or it is a swapped jar with no backup in this project). It is left as it is and does not fail the run. A file that is there but cannot be read (permissions, not a regular file) may still hold the patched bytes, so it fails the run and `remove` keeps the record. |
Each patched Gradle copy's sidecar record (`PatchEvent.sidecar`) carries an advisory
@@ -3378,7 +3465,7 @@ with `reason: : `:
|---|---|---|
| `vendor_jvm_shape_unsupported` | refusal, nothing written | `gradle_below_6_8`, `android_or_kmp` (also `available-at` module redirects), `gradle_exclusive_content_conflict` (a user rule claiming the module, in any script), `gradle_range_excludes_vendored` (no declared selector admits the vendored version), `gradle_classifier_computed` (a declaration of the module names its classifier through a variable, such as `${osdetector.classifier}`: the vendored repository would claim that jar without holding it), `gradle_verification_unparseable`, `gradle_index_unreadable`, `build_file_unreadable` (including a non-UTF-8 settings file), `build_file_outside_root`, `not_build_root` (run from a directory an ancestor settings file includes or may include, from a project with no settings file of its own below one, or below an ancestor settings file that is not UTF-8; `repair` refuses there too), `no_build_file` (no `pom.xml`, Gradle, sbt or scala-cli build at the root), `legacy_maven_root` (the root's ledger still holds a pre-v5 single-POM `maven_pom_repository` entry; the whole root is refused until `vendor --revert`, then vendor again) |
| `vendor_jvm_upstream_unavailable` | refusal | `classifier_unavailable` (a declared classifier jar no cache or registry has), `module_unavailable` (the pom declares Gradle module metadata that cannot be sourced), `pom_unavailable`, `verification_metadata_unavailable`; for a suffixed Maven / sbt pom also `suffix_unavailable` (the upstream pom computes its own version), `parent_unavailable` (a first vendoring whose upstream parent poms are in no local cache and cannot be fetched, so the suffixed pom cannot be checked) and `inherited_version_unresolvable` (a parent pom names `${project.version}` where the suffixed pom cannot declare the base version instead: in a profile, a management key or a repository URL) |
-| `vendor_jvm_degraded` | applied, VEX withheld | `gradle_unscanned_build_logic`, `unwired_build_logic` (a nonliteral included build), `settings_plugins_unwired`, `classifier_unpatched_copy` (a classifier jar carries an unpatched copy of a patched member), `verification_parent_chain_unhandled`, `gradle_lock_overrides_vendored` (a dependency lock of the build, buildscript and settings classpath locks included, pins the module at a version no vendored row serves), `gradle_settings_lock_unrouted` (a `settings-gradle.lockfile` locks the module but that build's settings script does not hold the in-block repository entry for it), `gradle_lock_unreadable` (a lock file, or a followed custom `lockFile`, is missing, unreadable, outside the checkout or not UTF-8), `gradle_custom_lock_file` (a `lockFile` location that cannot be followed statically: anything but a literal `file(…)` in a project's own build script), `gradle_wiring_uncommitted` (VEX liveness only, never reported by `vendor`: the committed settings files, index, derived `maven-metadata.xml`, script or verification file lack wiring a re-plan would write, such as a removed apply line or in-block entry; the git hygiene files do not count), `conflicting_managed_version` / `management_unresolved` (Maven reactor: an imported BOM or an out-of-checkout parent manages the artifact at another version, or its POM is unavailable; that local root is not pinned), `selection_undetermined` (Maven reactor: what one or more modules resolve cannot be read, so no pin is written where that is so and one already there is left as it is; one event however many modules, naming the first and counting the rest), `pin_would_move_module` (Maven reactor: a parent pom resolves the base version itself above a module that resolves another version, so the parent takes no pin. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven)) |
+| `vendor_jvm_degraded` | applied, VEX withheld | `gradle_unscanned_build_logic`, `unwired_build_logic` (a nonliteral included build), `settings_plugins_unwired`, `classifier_unpatched_copy` (a classifier jar carries an unpatched copy of a patched member, or cannot be read to check for one), `verification_parent_chain_unhandled`, `gradle_lock_overrides_vendored` (a dependency lock of the build, buildscript and settings classpath locks included, pins the module at a version no vendored row serves), `gradle_settings_lock_unrouted` (a `settings-gradle.lockfile` locks the module but that build's settings script does not hold the in-block repository entry for it), `gradle_lock_unreadable` (a lock file, or a followed custom `lockFile`, is missing, unreadable, outside the checkout or not UTF-8), `gradle_custom_lock_file` (a `lockFile` location that cannot be followed statically: anything but a literal `file(…)` in a project's own build script), `gradle_wiring_uncommitted` (VEX liveness only, never reported by `vendor`: the committed settings files, index, derived `maven-metadata.xml`, script or verification file lack wiring a re-plan would write, such as a removed apply line or in-block entry; the git hygiene files do not count), `conflicting_managed_version` / `management_unresolved` (Maven reactor: an imported BOM or an out-of-checkout parent manages the artifact at another version, or its POM is unavailable; that local root is not pinned), `selection_undetermined` (Maven reactor: what one or more modules resolve cannot be read, so no pin is written where that is so and one already there is left as it is; one event however many modules, naming the first and counting the rest), `pin_would_move_module` (Maven reactor: a parent pom resolves the base version itself above a module that resolves another version, so the parent takes no pin. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven)) |
| `vendor_jvm_note` | applied, informational | `range_declared` (a range, prefix or rich selector lists versions from the derived `maven-metadata.xml`), `ide_sources_unavailable` |
| `vendor_jvm_upstream_unverified` | warning | Upstream metadata was taken offline, or from a local cache while the registry published no checksum for it (a parent pom from a corporate repository), and not authenticated against registry checksums. |
| `vendor_jvm_unattested` | warning (`vendor --check`) | A Maven reactor entry is intact and wired, but a declaration may still build the base release (an executable classifier or type copy, a version a property, profile or unpinned local root may move), so `vex` does not attest it. The entry stays `verified`; the detail names the purl and the declarations (`:`). |
diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs
index 7e577cbcdb..ae5dac9e0a 100644
--- a/crates/socket-patch-cli/src/commands/apply.rs
+++ b/crates/socket-patch-cli/src/commands/apply.rs
@@ -1721,6 +1721,22 @@ pub(crate) async fn run_locked(
// rightly ignores it). It rides the run-warning channel so it
// is never silent.
let mut run_warnings = run_warnings;
+ // A Maven build whose `.mvn/maven.config` could not be read one
+ // way: no local repository was guessed at, so say why its
+ // `~/.m2` copies were not found.
+ let maven = |purl: &str| Ecosystem::from_purl(purl) == Some(Ecosystem::Maven);
+ if !args.common.is_global()
+ && (unmatched.iter().any(|purl| maven(purl))
+ || results.iter().any(|r| maven(&r.package_key)))
+ {
+ use socket_patch_core::crawlers::maven_crawler::JvmEnv;
+ if let Some(why) = JvmEnv::for_project(&args.common.cwd).m2_undetermined {
+ run_warnings.push(RunWarning {
+ code: "maven_local_repository_undetermined".to_string(),
+ detail: why,
+ });
+ }
+ }
// A nested apply's caller (get, scan) already reported the
// overrides it approved; repeating them would double each line.
// Skips are new to `get`, which checked only its selection; a
@@ -3702,10 +3718,19 @@ async fn apply_maven_base(m: &MavenBase<'_>) -> MavenApplied {
};
match Box::pin(jvm_jar::apply_jar_swap(&swap, &dirs, m.service)).await {
Err(refusal) => out.refuse(variant, &dirs[0], refusal.code, refusal.message),
- Ok(results) => {
- for mut result in results {
+ Ok(swapped) => {
+ for copy in swapped {
+ let jvm_jar::SwappedCopy {
+ mut result,
+ refusal,
+ } = copy;
check_derived_copies(&mut out, &mut result, &jar_leaf, args, m.derived)
.await;
+ // A copy's own coded refusal is a run warning too,
+ // as a whole-swap one is.
+ if let Some(refusal) = refusal {
+ out.warn(refusal.code, refusal.message);
+ }
out.record(args, result);
}
}
diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs
index 8f33bdb0f9..43d53274e7 100644
--- a/crates/socket-patch-cli/src/commands/scan/mod.rs
+++ b/crates/socket-patch-cli/src/commands/scan/mod.rs
@@ -1291,6 +1291,11 @@ pub(super) const GRADLE_MAVEN_LOCAL_UNDETERMINED: &str = "gradle_maven_local_und
/// `$HOME/.gradle`.
pub(super) const GRADLE_USER_HOME_DIFFERS: &str = "gradle_user_home_differs";
+/// Run-level warning: the project's `.mvn/maven.config` names one local
+/// repository to Maven before 3.9 and another to later Mavens, both exist
+/// and nothing says which Maven builds it, so neither was scanned.
+pub(crate) const MAVEN_LOCAL_REPOSITORY_UNDETERMINED: &str = "maven_local_repository_undetermined";
+
/// What a scan learned about the Gradle side of discovery.
#[derive(Default)]
struct GradleScan {
@@ -1381,7 +1386,11 @@ async fn gradle_scan(
&cwd,
socket_patch_core::vendor::jvm::layout::BuildTool::Gradle,
);
- let env = JvmEnv::from_process();
+ let env = if global {
+ JvmEnv::from_process()
+ } else {
+ JvmEnv::for_project(&cwd)
+ };
let gate = (!global && gradle_build).then(|| m2_gate(&cwd, &env));
// The cwd's build locks annotate Gradle-cached packages in a global
// run too; without a Gradle build at the cwd there is nothing to
@@ -1455,6 +1464,10 @@ async fn gradle_scan(
}
_ => {}
}
+ if let Some(why) = &env.m2_undetermined {
+ out.notes
+ .push((MAVEN_LOCAL_REPOSITORY_UNDETERMINED.to_string(), why.clone()));
+ }
if let Some((home, passwd)) = mismatch {
out.notes.push((
GRADLE_USER_HOME_DIFFERS.to_string(),
diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs
index f5614ead80..c7fb2cf15d 100644
--- a/crates/socket-patch-cli/src/commands/vex.rs
+++ b/crates/socket-patch-cli/src/commands/vex.rs
@@ -2381,6 +2381,11 @@ fn omission_phrase(reason: &str) -> &'static str {
"go_vendor_content_mismatch" => "the native Go vendor tree does not contain the patch; run go mod vendor (or go work vendor for a workspace)",
"vendor_artifact_missing" => "the vendored artifact is missing",
"vendor_artifact_unreadable" => "the vendored artifact cannot be read",
+ "vendor_artifact_too_large" => {
+ "the vendored jar is past the limits jars are read within (200,000 entries, or 1 GiB \
+ and 100 times its own size inflated), so its contents were not checked; run \
+ socket-patch repair to restore the recorded jar"
+ }
"vendor_artifact_non_canonical" => {
"the vendored tarball holds a second entry the package manager would extract \
over a patched file (another top-level directory, a second spelling of the \
@@ -2683,6 +2688,7 @@ mod tests {
"no_files",
"vendor_hash_mismatch",
"vendor_artifact_missing",
+ "vendor_artifact_too_large",
"vendor_manifest_unverifiable",
"stale_install",
STALE_INSTALL_UNVERIFIED,
diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs
index d98b38bcc7..a87ca3112f 100644
--- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs
+++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs
@@ -1368,14 +1368,15 @@ impl JvmScope {
pub(crate) async fn of(common: &GlobalArgs) -> Self {
use socket_patch_core::crawlers::gradle_cache;
use socket_patch_core::crawlers::maven_crawler::{m2_gate, JvmEnv};
- let env = JvmEnv::from_process();
if common.is_global() {
return Self {
- env,
+ env: JvmEnv::from_process(),
gate: None,
verification_metadata: None,
};
}
+ // A project run: its `.mvn/maven.config` can name the repository.
+ let env = JvmEnv::for_project(&common.cwd);
let cwd = common.cwd.clone();
let probe_env = env.clone();
let probe = move || {
diff --git a/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs
index 6c27c2ea70..83031b7e27 100644
--- a/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs
+++ b/crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs
@@ -38,6 +38,12 @@
//! 5. The source project's `vendor --revert` restores every byte, and
//! nothing is left to attest.
//!
+//! Another test pins which local repository a build uses when the
+//! project's `.mvn/maven.config` names one (`-Dmaven.repo.local`): real
+//! Maven resolves into it rather than the one `MAVEN_OPTS` names, the
+//! command line (`MAVEN_ARGS`, Maven 3.9+) overrides it, and socket-patch
+//! given the same environment patches the artifact in that same repository.
+//!
//! Gated like the other real-toolchain capstones: `#[ignore]` (network to
//! Maven Central for the fixture), toolchain selection and the
//! `SOCKET_PATCH_MAVEN_E2E_{MVN,VERSION,REQUIRED}` gates in
@@ -1252,3 +1258,161 @@ mod mediation {
unselected(Shape::Ranged).expect("the local repository is warm");
}
}
+
+/// Every file under `from`, copied to the same place under `to`.
+fn copy_tree(from: &Path, to: &Path) {
+ std::fs::create_dir_all(to).unwrap();
+ for entry in std::fs::read_dir(from).unwrap() {
+ let entry = entry.unwrap();
+ let target = to.join(entry.file_name());
+ if entry.file_type().unwrap().is_dir() {
+ copy_tree(&entry.path(), &target);
+ } else {
+ std::fs::copy(entry.path(), &target).unwrap();
+ }
+ }
+}
+
+/// The local repository of a build is the one Maven itself takes: the
+/// project's `.mvn/maven.config` (`-Dmaven.repo.local`) over `MAVEN_OPTS`,
+/// and the command line (`MAVEN_ARGS`, which Maven 3.9+ reads) over the
+/// config. Maven is asked first, with no repository on its command line;
+/// socket-patch, in the same environment and with no `MAVEN_REPO_LOCAL`,
+/// then patches and restores the artifact in that same repository.
+#[test]
+#[ignore = "real Maven + Maven Central (fixture); run with --ignored"]
+fn maven_config_local_repository_is_the_one_maven_and_socket_patch_use() {
+ let Some(mvn) = Mvn::detect(SUITE) else {
+ return;
+ };
+ let tmp = tempfile::tempdir().unwrap();
+ let root: PathBuf = tmp.path().canonicalize().unwrap();
+ let proj = root.join("proj");
+ let home = root.join("home");
+ let [from_config, from_opts, from_args] =
+ ["repo-config", "repo-opts", "repo-args"].map(|name| root.join(name));
+ let settings = root.join("settings.xml");
+ write_settings(&settings, &[]);
+ std::fs::create_dir_all(proj.join(".mvn")).unwrap();
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::write(proj.join("pom.xml"), consumer_pom(VERSION)).unwrap();
+ std::fs::write(
+ proj.join(".mvn/maven.config"),
+ format!("-Dmaven.repo.local={}\n", from_config.display()),
+ )
+ .unwrap();
+ // The JVM's own properties. `user.home` keeps a Maven that took none of
+ // these repositories out of the real `~/.m2`.
+ let opts = format!(
+ "-Duser.home={} -Dmaven.repo.local={}",
+ home.display(),
+ from_opts.display()
+ );
+ let goal = format!("{DEPENDENCY_PLUGIN}:copy-dependencies");
+ let resolve = |settings: &Path, extra: &[&str], maven_args: Option<&str>| {
+ let _ = std::fs::remove_dir_all(proj.join("target"));
+ let mut args = vec![goal.as_str(), "-DoutputDirectory=target/deps"];
+ args.extend_from_slice(extra);
+ mvn.run_unpinned(&proj, settings, &args, |cmd| {
+ cmd.env("MAVEN_OPTS", &opts);
+ if let Some(value) = maven_args {
+ cmd.env("MAVEN_ARGS", value);
+ }
+ })
+ };
+ let pom_leaf = format!("{ARTIFACT}-{VERSION}.pom");
+ let cached = |repo: &Path| repo_dir(repo, VERSION).join(&pom_leaf);
+
+ // 1. Maven: the config's repository, not the one MAVEN_OPTS names.
+ let out = with_central_fallback(SUITE, "maven.config resolution", &settings, |s, extra| {
+ resolve(s, extra, None)
+ });
+ if !ok(&out) {
+ skip(
+ SUITE,
+ &format!("resolving against Maven Central failed:\n{}", dump(&out)),
+ );
+ return;
+ }
+ assert!(
+ cached(&from_config).is_file(),
+ "Maven {} did not resolve into the repository .mvn/maven.config names:\n{}",
+ mvn.version,
+ dump(&out)
+ );
+ assert!(
+ !from_opts.exists() && !home.join(".m2/repository").exists(),
+ "Maven {} used another repository as well",
+ mvn.version
+ );
+
+ // 2. socket-patch: the same repository.
+ let pristine = std::fs::read(cached(&from_config)).unwrap();
+ let patched = [
+ pristine.as_slice(),
+ b"\n",
+ ]
+ .concat();
+ stage_manifest_of(
+ &proj,
+ &purl(),
+ &format!("package/{pom_leaf}"),
+ &pristine,
+ &patched,
+ );
+ std::fs::write(
+ proj.join(".socket/blobs").join(git_sha256(&pristine)),
+ &pristine,
+ )
+ .unwrap();
+ // `--preserve-state`: a rollback otherwise drops the record it restored.
+ let agent = |command: &str, maven_args: Option<&str>| {
+ let mut cmd = hermetic::command(&binary());
+ hermetic::scrub_extra(&mut cmd, &[hermetic::Extra::Venv]);
+ prebuilt_common::jvm_env::isolate_cli(&mut cmd);
+ if command == "rollback" {
+ cmd.args(["rollback", "--preserve-state"]);
+ } else {
+ cmd.arg(command);
+ }
+ cmd.args(["--json", "--offline", "--cwd"])
+ .arg(&proj)
+ .env("MAVEN_OPTS", &opts)
+ .env_remove("MAVEN_REPO_LOCAL")
+ .env_remove("M2_HOME");
+ if let Some(value) = maven_args {
+ cmd.env("MAVEN_ARGS", value);
+ }
+ let out = cmd.output().expect("run socket-patch");
+ assert!(out.status.success(), "{command}: {}", dump(&out));
+ };
+ agent("apply", None);
+ assert_eq!(std::fs::read(cached(&from_config)).unwrap(), patched);
+ agent("rollback", None);
+ assert_eq!(std::fs::read(cached(&from_config)).unwrap(), pristine);
+
+ // 3. The command line is merged over the config. Maven before 3.9 does
+ // not read MAVEN_ARGS.
+ if mvn.numeric() < vec![3, 9, 0] {
+ println!(
+ "{SUITE}: Maven {} does not read MAVEN_ARGS; the command-line leg is skipped",
+ mvn.version
+ );
+ return;
+ }
+ copy_tree(&from_config, &from_args);
+ std::fs::remove_dir_all(repo_dir(&from_config, VERSION)).unwrap();
+ let args_value = format!("-Dmaven.repo.local={}", from_args.display());
+ // Offline, only the repository that still holds the artifact resolves.
+ let out = resolve(&settings, &["-o"], Some(&args_value));
+ assert!(
+ ok(&out),
+ "Maven {} did not take the repository MAVEN_ARGS names over the config's:\n{}",
+ mvn.version,
+ dump(&out)
+ );
+ agent("apply", Some(&args_value));
+ assert_eq!(std::fs::read(cached(&from_args)).unwrap(), patched);
+ agent("rollback", Some(&args_value));
+ assert_eq!(std::fs::read(cached(&from_args)).unwrap(), pristine);
+}
diff --git a/crates/socket-patch-cli/tests/gradle_agent_cli.rs b/crates/socket-patch-cli/tests/gradle_agent_cli.rs
index c7f1209e52..660b99b013 100644
--- a/crates/socket-patch-cli/tests/gradle_agent_cli.rs
+++ b/crates/socket-patch-cli/tests/gradle_agent_cli.rs
@@ -1030,32 +1030,107 @@ fn offline_member_record_writes_nothing() {
}
/// A service jar carrying a member the installed jar does not have is not
-/// the installed jar plus the patch: refused, nothing written, no backup.
+/// the installed jar plus the patch: every copy fails with
+/// `jvm_agent_service_jar_mismatch` naming the member, the run carries the
+/// code as a warning, and nothing is written, no backup either. The entry's
+/// unix mode is beside the point: the JVM loads a class from an entry that
+/// carries a symlink's mode bits like any other.
#[test]
fn tampered_service_jar_writes_nothing() {
+ const BACKDOOR: &str = "com/example/Backdoor.class";
+ for symlink_mode in [false, true] {
+ let f = fx(" mavenLocal()\n mavenCentral()\n");
+ f.m2(&as_refs(&pristine_files()));
+ f.gradle(&as_refs(&pristine_files()));
+ f.member_manifest();
+ let before = f.snapshot();
+ let mut honest = zip::ZipArchive::new(std::io::Cursor::new(service_jar())).unwrap();
+ let mut tampered = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let opts = zip::write::SimpleFileOptions::default()
+ .compression_method(zip::CompressionMethod::Stored);
+ for i in 0..honest.len() {
+ use std::io::Read as _;
+ let mut entry = honest.by_index(i).unwrap();
+ let mut buf = Vec::new();
+ entry.read_to_end(&mut buf).unwrap();
+ tampered.start_file(entry.name(), opts).unwrap();
+ tampered.write_all(&buf).unwrap();
+ }
+ if symlink_mode {
+ tampered.add_symlink(BACKDOOR, "evil", opts).unwrap();
+ } else {
+ tampered.start_file(BACKDOOR, opts).unwrap();
+ tampered.write_all(b"evil").unwrap();
+ }
+ let (_rt, server) = service(&tampered.finish().unwrap().into_inner());
+ let out = f.run(&["apply", "--vendor-url", &server.uri()]);
+ out.failed().has("jvm_agent_service_jar_mismatch");
+ let errors: Vec<&str> = out.json["events"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter_map(|e| e["error"].as_str())
+ .collect();
+ assert_eq!(errors.len(), 2, "one per copy: {}", out.json);
+ for error in errors {
+ assert!(
+ error.starts_with(
+ "jvm_agent_service_jar_mismatch: the patch service's jar differs from "
+ ) && error.contains(&format!(
+ "outside the patched members: 1 added (`{BACKDOOR}`)"
+ )),
+ "symlink_mode={symlink_mode}: {error}"
+ );
+ }
+ assert_eq!(f.snapshot(), before, "symlink_mode={symlink_mode}");
+ assert!(!f.proj.join(".socket/jvm-originals").exists());
+ }
+}
+
+/// A jar over the limits jars once shared with Python wheels (10,000
+/// entries, 64 MiB inflated) is patched in every copy, attested, and
+/// rolled back byte for byte.
+#[test]
+fn a_jar_over_the_old_reader_limits_applies_attests_and_rolls_back() {
+ let big = |notice: &[u8]| {
+ let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let opts = zip::write::SimpleFileOptions::default()
+ .compression_method(zip::CompressionMethod::Stored)
+ .last_modified_time(zip::DateTime::default());
+ zw.start_file(NOTICE, opts).unwrap();
+ zw.write_all(notice).unwrap();
+ let mut body = vec![0x5au8; 6800];
+ for i in 0..10_001u64 {
+ body[..8].copy_from_slice(&i.to_le_bytes());
+ zw.start_file(format!("p/C{i}.class"), opts).unwrap();
+ zw.write_all(&body).unwrap();
+ }
+ zw.finish().unwrap().into_inner()
+ };
+ let (pristine, patched) = (big(b"pristine\n"), big(b"patched\n"));
+ assert!(pristine.len() > 64 * 1024 * 1024);
+
let f = fx(" mavenLocal()\n mavenCentral()\n");
- f.m2(&as_refs(&pristine_files()));
- f.gradle(&as_refs(&pristine_files()));
+ let m2 = f.m2(&[(JAR, &pristine), (POM, PRISTINE_POM)]);
+ let version = f.gradle(&[(JAR, &pristine), (POM, PRISTINE_POM)]);
f.member_manifest();
let before = f.snapshot();
- let mut tampered = zip::ZipArchive::new(std::io::Cursor::new(service_jar())).unwrap();
- let mut members = Vec::new();
- for i in 0..tampered.len() {
- use std::io::Read as _;
- let mut entry = tampered.by_index(i).unwrap();
- let mut buf = Vec::new();
- entry.read_to_end(&mut buf).unwrap();
- members.push((entry.name().to_string(), buf));
- }
- members.push(("com/example/Backdoor.class".to_string(), b"evil".to_vec()));
- let refs: Vec<(&str, &[u8])> = members
- .iter()
- .map(|(n, b)| (n.as_str(), b.as_slice()))
+ let (_rt, server) = service(&patched);
+
+ f.run(&["apply", "--vendor-url", &server.uri()]).ok();
+ assert!(std::fs::read(m2.join(JAR)).unwrap() == patched);
+ assert!(hash_copies(&version, JAR)[0].1 == patched);
+ let (out, statements) = f.vex(&[]);
+ out.ok();
+ assert!(statements > 0, "{}", out.json);
+
+ f.run(&["rollback", "--offline"]).ok();
+ let after: BTreeMap = f
+ .snapshot()
+ .into_iter()
+ .filter(|(k, _)| !k.contains(".socket/jvm-originals"))
.collect();
- let (_rt, server) = service(&jar(&refs));
- f.run(&["apply", "--vendor-url", &server.uri()]).failed();
- assert_eq!(f.snapshot(), before);
- assert!(!f.proj.join(".socket/jvm-originals").exists());
+ assert!(after == before, "rollback must restore every copy");
}
/// A swap is one transaction across every consumed copy: when the write of
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 64c5c3fb32..9b2f90f9b9 100644
--- a/crates/socket-patch-cli/tests/maven_build_common/mod.rs
+++ b/crates/socket-patch-cli/tests/maven_build_common/mod.rs
@@ -243,6 +243,31 @@ impl Mvn {
.expect("spawn mvn")
}
+ /// `mvn -B ` in `cwd` with no local repository on the command
+ /// line: the project's `.mvn/maven.config` and the environment
+ /// `configure` sets decide it, as in a developer's own run. `configure`
+ /// must keep the run out of the real `~/.m2` (a `-Duser.home` in
+ /// `MAVEN_OPTS`).
+ pub fn run_unpinned(
+ &self,
+ cwd: &Path,
+ settings: &Path,
+ args: &[&str],
+ configure: impl FnOnce(&mut Command),
+ ) -> Output {
+ let mut cmd = mvn_command(&self.program);
+ configure(&mut cmd);
+ cmd.current_dir(cwd)
+ .arg("-B")
+ .arg("-s")
+ .arg(settings)
+ .arg("-Dstyle.color=never")
+ .arg("-Dmaven.test.skip=true")
+ .args(args)
+ .output()
+ .expect("spawn mvn")
+ }
+
/// Resolve the project's dependencies into `/` (the
/// consumption proof: what Maven fetched is what the build links).
pub fn copy_dependencies(
diff --git a/crates/socket-patch-cli/tests/maven_sidecar_cli.rs b/crates/socket-patch-cli/tests/maven_sidecar_cli.rs
index bda2972440..36dc1d6d06 100644
--- a/crates/socket-patch-cli/tests/maven_sidecar_cli.rs
+++ b/crates/socket-patch-cli/tests/maven_sidecar_cli.rs
@@ -3,6 +3,11 @@
//! matching the pre-patch bytes, they follow the patched bytes on apply
//! and are put back exactly on rollback; absent, none is created; one that
//! never described the file is left alone. Every rollback is byte-exact.
+//!
+//! Also here, as the plain-Maven agent flows that need no build: the local
+//! repository a project's `.mvn/maven.config` names is the one patched, and
+//! a jar a second project finds already patched in the shared repository is
+//! rolled back from the registry's verified copy.
#[path = "common/mod.rs"]
mod common;
@@ -244,6 +249,282 @@ fn mismatched_sidecar_is_untouched() {
assert_eq!(f.m2_files(), before);
}
+/// `socket-patch --json --cwd ` with `env` and no
+/// `MAVEN_REPO_LOCAL`: `(exit status, envelope, stderr)`.
+fn run_plain(
+ proj: &Path,
+ args: &[&str],
+ env: &[(&str, &str)],
+) -> (Option, serde_json::Value, String) {
+ let mut cmd = hermetic::command(Path::new(env!("CARGO_BIN_EXE_socket-patch")));
+ prebuilt_common::jvm_env::isolate_cli(&mut cmd);
+ cmd.args(args)
+ .args(["--json", "--cwd", proj.to_str().unwrap()])
+ .env("SOCKET_TELEMETRY_DISABLED", "1")
+ .env("SOCKET_NO_CONFIG", "1")
+ .env_remove("MAVEN_REPO_LOCAL")
+ .env_remove("M2_HOME");
+ for (key, value) in env {
+ cmd.env(key, value);
+ }
+ let out = cmd.output().unwrap();
+ let stdout = String::from_utf8_lossy(&out.stdout);
+ let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
+ let json = serde_json::from_str(stdout.trim())
+ .unwrap_or_else(|e| panic!("{args:?}: not JSON ({e})\n{stdout}\n{stderr}"));
+ (out.status.code(), json, stderr)
+}
+
+/// `-Dmaven.repo.local` in the project's `.mvn/maven.config` names the
+/// repository its builds use: that is the one patched and rolled back,
+/// from the project and from a module below it, and the one `MAVEN_OPTS`
+/// names (which Maven reads after the config) is left alone. Without the
+/// config the `MAVEN_OPTS` repository is the one patched, so the config is
+/// what moved it.
+#[test]
+fn maven_config_local_repository_is_the_one_patched() {
+ let f = fx(&[]);
+ let decoy = f.proj.parent().unwrap().join("decoy");
+ let decoy_pom = decoy.join("com/example/lib/2.0").join(POM);
+ std::fs::create_dir_all(decoy_pom.parent().unwrap()).unwrap();
+ std::fs::write(&decoy_pom, PRISTINE).unwrap();
+ let config = f.proj.join(".mvn/maven.config");
+ std::fs::create_dir_all(config.parent().unwrap()).unwrap();
+ std::fs::write(
+ &config,
+ format!(
+ "# shared cache\n-B\n-Dmaven.repo.local={}\n",
+ f.m2.display()
+ ),
+ )
+ .unwrap();
+ let opts = format!("-Dmaven.repo.local={}", decoy.display());
+ let env = [("MAVEN_OPTS", opts.as_str())];
+ // `--preserve-state`: a rollback otherwise drops the record it restored.
+ let run = |cwd: &Path, command: &str| {
+ let args: &[&str] = match command {
+ "rollback" => &["rollback", "--offline", "--preserve-state"],
+ _ => &[command, "--offline"],
+ };
+ let (code, json, stderr) = run_plain(cwd, args, &env);
+ assert_eq!(code, Some(0), "{command}: {json}\n{stderr}");
+ };
+ let poms = || {
+ (
+ std::fs::read(f.dir.join(POM)).unwrap(),
+ std::fs::read(&decoy_pom).unwrap(),
+ )
+ };
+
+ run(&f.proj, "apply");
+ assert_eq!(poms(), (PATCHED.to_vec(), PRISTINE.to_vec()));
+ run(&f.proj, "rollback");
+ assert_eq!(poms(), (PRISTINE.to_vec(), PRISTINE.to_vec()));
+
+ // Maven's launcher finds the config from a module directory too.
+ let module = f.proj.join("module");
+ std::fs::create_dir_all(&module).unwrap();
+ for entry in ["pom.xml", ".socket"] {
+ std::fs::rename(f.proj.join(entry), module.join(entry)).unwrap();
+ }
+ run(&module, "apply");
+ assert_eq!(poms(), (PATCHED.to_vec(), PRISTINE.to_vec()));
+ run(&module, "rollback");
+ assert_eq!(poms(), (PRISTINE.to_vec(), PRISTINE.to_vec()));
+
+ std::fs::remove_file(&config).unwrap();
+ run(&module, "apply");
+ assert_eq!(poms(), (PRISTINE.to_vec(), PATCHED.to_vec()));
+}
+
+/// A config that names one repository to Maven before 3.9 and another to
+/// later Mavens, with both on disk and no Maven Wrapper to say which Maven
+/// builds the project: neither is patched, and the run says why.
+#[test]
+fn an_ambiguous_maven_config_patches_nothing_and_says_so() {
+ let f = fx(&[]);
+ let later = PathBuf::from(format!("{} -B", f.m2.display()));
+ let later_pom = later.join("com/example/lib/2.0").join(POM);
+ std::fs::create_dir_all(later_pom.parent().unwrap()).unwrap();
+ std::fs::write(&later_pom, PRISTINE).unwrap();
+ std::fs::create_dir_all(f.proj.join(".mvn")).unwrap();
+ std::fs::write(
+ f.proj.join(".mvn/maven.config"),
+ format!("-Dmaven.repo.local={} -B\n", f.m2.display()),
+ )
+ .unwrap();
+ let (_, json, stderr) = run_plain(&f.proj, &["apply", "--offline"], &[]);
+ let warnings = json["warnings"].to_string();
+ assert!(
+ warnings.contains("maven_local_repository_undetermined")
+ && warnings.contains("to Maven before 3.9"),
+ "{json}\n{stderr}"
+ );
+ assert_eq!(std::fs::read(f.dir.join(POM)).unwrap(), PRISTINE);
+ assert_eq!(std::fs::read(&later_pom).unwrap(), PRISTINE);
+
+ // The wrapper settles it.
+ std::fs::create_dir_all(f.proj.join(".mvn/wrapper")).unwrap();
+ std::fs::write(
+ f.proj.join(".mvn/wrapper/maven-wrapper.properties"),
+ "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.9/apache-maven-3.8.9-bin.zip\n",
+ )
+ .unwrap();
+ let (code, json, stderr) = run_plain(&f.proj, &["apply", "--offline"], &[]);
+ assert_eq!(code, Some(0), "{json}\n{stderr}");
+ assert_eq!(std::fs::read(f.dir.join(POM)).unwrap(), PATCHED);
+ assert_eq!(std::fs::read(&later_pom).unwrap(), PRISTINE);
+}
+
+/// A stored jar of `members`.
+fn jar(members: &[(&str, &[u8])]) -> Vec {
+ use std::io::Write as _;
+ let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let opts =
+ zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+ for (name, bytes) in members {
+ zw.start_file(*name, opts).unwrap();
+ zw.write_all(bytes).unwrap();
+ }
+ zw.finish().unwrap().into_inner()
+}
+
+/// Two projects share one `~/.m2`. The first applies a jar patch and keeps
+/// the original under its own `.socket/`; the second finds the copy already
+/// patched and has no backup. The second project's rollback restores the
+/// jar from the registry (the download matches the registry's checksum and
+/// is the jar the copy was patched from) and puts its `.sha1` back. With no
+/// such copy to be had it fails, says what happened and how to recover, and
+/// leaves the jar as it is; the first project can still roll it back.
+#[test]
+fn a_second_project_rolls_back_a_shared_m2_jar_from_verified_upstream() {
+ const JAR: &str = "lib-2.0.jar";
+ const NOTICE: &str = "META-INF/NOTICE.txt";
+ let class: (&str, &[u8]) = ("com/example/Lib.class", b"\xca\xfe\xba\xbe");
+ let original = jar(&[(NOTICE, b"pristine\n"), class]);
+ let patched = jar(&[(NOTICE, b"patched\n"), class]);
+
+ let f = fx(&[]);
+ let root = f.proj.parent().unwrap().to_path_buf();
+ let sha1 = format!("{}\n", sha1_hex(&original));
+ std::fs::write(f.dir.join(JAR), &original).unwrap();
+ std::fs::write(f.dir.join(format!("{JAR}.sha1")), &sha1).unwrap();
+ let before = f.m2_files();
+ let project = |name: &str| {
+ let proj = root.join(name);
+ std::fs::create_dir_all(proj.join(".socket/blobs")).unwrap();
+ std::fs::copy(f.proj.join("pom.xml"), proj.join("pom.xml")).unwrap();
+ for bytes in [&b"pristine\n"[..], b"patched\n"] {
+ std::fs::write(proj.join(".socket/blobs").join(git_sha256(bytes)), bytes).unwrap();
+ }
+ std::fs::write(
+ proj.join(".socket/manifest.json"),
+ serde_json::to_string_pretty(&serde_json::json!({ "patches": { PURL: {
+ "uuid": UUID,
+ "exportedAt": "2026-01-01T00:00:00Z",
+ "files": { NOTICE: {
+ "beforeHash": git_sha256(b"pristine\n"),
+ "afterHash": git_sha256(b"patched\n"),
+ } },
+ "vulnerabilities": {},
+ "description": "shared jar fixture",
+ "license": "MIT",
+ "tier": "free",
+ } } }))
+ .unwrap(),
+ )
+ .unwrap();
+ proj
+ };
+ let (one, two) = (project("one"), project("two"));
+
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(1)
+ .enable_all()
+ .build()
+ .unwrap();
+ let (server, no_registry) = rt.block_on(async {
+ use wiremock::matchers::{method, path};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+ let server = MockServer::start().await;
+ prebuilt_common::mount_download(&server, PURL, UUID, JAR, &patched).await;
+ let route = format!("/com/example/lib/2.0/{JAR}");
+ Mock::given(method("GET"))
+ .and(path(&route))
+ .respond_with(ResponseTemplate::new(200).set_body_bytes(original.clone()))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path(format!("{route}.sha1")))
+ .respond_with(ResponseTemplate::new(200).set_body_string(sha1_hex(&original)))
+ .mount(&server)
+ .await;
+ (server, MockServer::start().await)
+ });
+ let m2 = f.m2.to_str().unwrap();
+ let apply = |proj: &Path| {
+ let (code, json, stderr) = run_plain(
+ proj,
+ &["apply", "--vendor-url", &server.uri()],
+ &[("MAVEN_REPO_LOCAL", m2)],
+ );
+ assert_eq!(code, Some(0), "{json}\n{stderr}");
+ assert_eq!(std::fs::read(f.dir.join(JAR)).unwrap(), patched);
+ };
+ // `--preserve-state`: a rollback otherwise drops the record it restored.
+ let rollback = |proj: &Path, extra: &[&str], registry: &str| {
+ let args = [&["rollback", "--preserve-state"][..], extra].concat();
+ run_plain(
+ proj,
+ &args,
+ &[
+ ("MAVEN_REPO_LOCAL", m2),
+ ("SOCKET_MAVEN_REGISTRY", registry),
+ ],
+ )
+ };
+
+ apply(&one);
+ assert!(one.join(".socket/jvm-originals").is_dir());
+ apply(&two);
+ assert!(!two.join(".socket/jvm-originals").exists());
+
+ let (code, json, stderr) = rollback(&two, &[], &server.uri());
+ assert_eq!(code, Some(0), "{json}\n{stderr}");
+ assert_eq!(f.m2_files(), before, "the jar and its .sha1 come back");
+ assert!(!two.join(".socket/jvm-originals").exists());
+
+ // No verified upstream copy: the failure says what to do, and the jar
+ // is left for the project that holds the original.
+ apply(&one);
+ apply(&two);
+ for (extra, registry, why) in [
+ (&[][..], no_registry.uri(), "the registry did not serve it"),
+ (
+ &["--offline"][..],
+ server.uri(),
+ "--offline prevents downloading it again",
+ ),
+ ] {
+ let (code, json, stderr) = rollback(&two, extra, ®istry);
+ assert_eq!(code, Some(1), "{json}\n{stderr}");
+ let text = format!("{json}\n{stderr}");
+ for part in [
+ "jvm_jar_backup_missing: ",
+ "has no backup of the original (another project or an earlier workspace applied it)",
+ why,
+ "To recover, run the rollback from the project that applied the patch",
+ "so the build downloads the jar again",
+ ] {
+ assert!(text.contains(part), "missing {part:?}: {text}");
+ }
+ assert_eq!(std::fs::read(f.dir.join(JAR)).unwrap(), patched);
+ }
+ let (code, json, stderr) = rollback(&one, &["--offline"], &server.uri());
+ assert_eq!(code, Some(0), "{json}\n{stderr}");
+ assert_eq!(f.m2_files(), before);
+}
+
#[test]
fn md5_fixture_matches_rfc1321() {
assert_eq!(md5_hex(b"abc"), "900150983cd24fb0d6963f7d28e17f72");
diff --git a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs
index 4046d00d36..331f61200d 100644
--- a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs
+++ b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs
@@ -359,6 +359,74 @@ fn cold_cache_rerun_vex_repair_and_revert() {
}
}
+/// A jar over the limits jars once shared with Python wheels (10,000
+/// entries, 64 MiB inflated) is vendored, held to upstream by an online
+/// re-run, attested by `vex`, passes `vendor --check`, and is rebuilt by
+/// `repair`. Each of those used to stop at the wheel reader's caps.
+#[test]
+fn a_jar_over_the_old_reader_limits_vendors_attests_and_repairs() {
+ let big = {
+ let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let opts = zip::write::SimpleFileOptions::default()
+ .compression_method(zip::CompressionMethod::Stored);
+ zw.start_file(MEMBER, opts).unwrap();
+ zw.write_all(b"NOTICE foo\n").unwrap();
+ let mut body = vec![0x5au8; 6800];
+ for i in 0..10_001u64 {
+ body[..8].copy_from_slice(&i.to_le_bytes());
+ zw.start_file(format!("p/C{i}.class"), opts).unwrap();
+ zw.write_all(&body).unwrap();
+ }
+ zw.finish().unwrap().into_inner()
+ };
+ assert!(big.len() > 64 * 1024 * 1024);
+ for shape in [Shape::Reactor, Shape::Gradle] {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path();
+ fixture(root, shape, &[("foo", FOO_UUID)]);
+ std::fs::write(root.join("m2/org/example/foo/1.0/foo-1.0.jar"), &big).unwrap();
+ let env = ok(root, &["vendor"]);
+ assert_eq!(env["events"][0]["action"], "applied", "{env}");
+ let tree_jar = root.join(if shape == Shape::Reactor {
+ "proj/.socket/vendor/maven2/org/example/foo/1.0-socket.1d3c1fd2/foo-1.0-socket.1d3c1fd2.jar"
+ } else {
+ "proj/.socket/vendor/gradle/org/example/foo/1.0/foo-1.0.jar"
+ });
+ let vendored = std::fs::read(&tree_jar).unwrap();
+ assert!(vendored.len() > 64 * 1024 * 1024);
+
+ let env = ok(root, &["vendor"]);
+ assert_eq!(
+ events(&env),
+ [(
+ purl("foo"),
+ "skipped".to_string(),
+ "already_vendored".to_string()
+ )],
+ "{env}"
+ );
+ ok(root, &["vendor", "--check"]);
+ let vex = root.join("vex.json");
+ ok(
+ root,
+ &[
+ "vex",
+ "-O",
+ vex.to_str().unwrap(),
+ "--product",
+ "pkg:generic/x@1",
+ ],
+ );
+ let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(&vex).unwrap()).unwrap();
+ assert_eq!(doc["statements"][0]["status"], "not_affected", "{doc}");
+
+ std::fs::remove_file(&tree_jar).unwrap();
+ let env = ok(root, &["repair"]);
+ assert_eq!(env["events"][0]["action"], "rebuilt", "{env}");
+ assert!(std::fs::read(&tree_jar).unwrap() == vendored);
+ }
+}
+
/// #656: a file the index does not list in the vendored tree (a Finder
/// `.DS_Store`) fails the Gradle build and `vendor --check`. Re-running
/// `vendor`, the remedy the build error names, and `repair` both sweep
diff --git a/crates/socket-patch-core/src/crawlers/jvm_cache.rs b/crates/socket-patch-core/src/crawlers/jvm_cache.rs
index adecae1b77..26d2f269e6 100644
--- a/crates/socket-patch-core/src/crawlers/jvm_cache.rs
+++ b/crates/socket-patch-core/src/crawlers/jvm_cache.rs
@@ -180,7 +180,7 @@ pub fn project_dependency_set(root: &Path) -> Option {
/// bytes ([`locate_artifact`]), never for discovery. See
/// [`all_local_roots_with`].
pub fn all_local_roots(cwd: &Path) -> Vec {
- all_local_roots_with(cwd, &super::maven_crawler::JvmEnv::from_process())
+ all_local_roots_with(cwd, &super::maven_crawler::JvmEnv::for_project(cwd))
}
/// [`all_local_roots`] under the caches `env` names: the Gradle user home's
diff --git a/crates/socket-patch-core/src/crawlers/maven_crawler.rs b/crates/socket-patch-core/src/crawlers/maven_crawler.rs
index a235fc5c03..334499a0d2 100644
--- a/crates/socket-patch-core/src/crawlers/maven_crawler.rs
+++ b/crates/socket-patch-core/src/crawlers/maven_crawler.rs
@@ -6,6 +6,7 @@ use super::gradle_cache;
use super::jvm_cache::{self, JvmCacheLayout, JvmCacheRoot};
use super::types::{CrawledPackage, CrawlerOptions};
use super::walk_pool::{par_map, run_walk};
+use crate::formats::maven::declared_maven::{release, DeclaredMaven, RootDirectory};
use crate::gradle::graph::MavenLocal;
use crate::gradle::home::GradleHome;
use crate::gradle::{Env, Os};
@@ -532,12 +533,18 @@ fn coursier_repo_root(path: PathBuf) -> JvmCacheRoot {
/// The JVM caches a run resolves against: the Maven local repository and
/// the Gradle user home. [`JvmEnv::from_process`] reads the process
-/// environment; [`JvmEnv::resolve`] an explicit one (tests).
+/// environment, [`JvmEnv::for_project`] also the project's
+/// `.mvn/maven.config`; [`JvmEnv::resolve`] an explicit one (tests).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JvmEnv {
/// The Maven local repository (see [`MavenCrawler::get_maven_repo_paths`]);
/// `None` when nothing names one and there is no usable home.
pub m2_repo: Option,
+ /// Why [`Self::m2_repo`] is `None` although the project names a local
+ /// repository: its `.mvn/maven.config` reads differently to different
+ /// Maven lines and nothing says which one builds the project. No
+ /// repository is guessed at.
+ pub m2_undetermined: Option,
/// The Gradle user home; `None` when none can be resolved.
pub gradle: Option,
}
@@ -548,15 +555,56 @@ impl JvmEnv {
pub fn from_process() -> Self {
Self {
m2_repo: MavenCrawler::m2_repo_path(),
+ m2_undetermined: None,
gradle: gradle_cache::home_from_process_env(),
}
}
+ /// [`Self::from_process`] for the build Maven would run in `project`:
+ /// a `-Dmaven.repo.local` in its `.mvn/maven.config` names the local
+ /// repository too ([`m2_repo_path_in`]). For a project run; a `--global`
+ /// one is about the machine's caches and keeps [`Self::from_process`].
+ pub fn for_project(project: &Path) -> Self {
+ let (m2_repo, m2_undetermined) = m2_repo_in(
+ &gradle_cache::ProcessEnv,
+ Os::current(),
+ None,
+ Some(project),
+ );
+ Self {
+ m2_repo,
+ m2_undetermined,
+ gradle: gradle_cache::home_from_process_env(),
+ }
+ }
+
+ /// The caches of a crawl with `options`: the project's
+ /// ([`Self::for_project`]) unless the crawl is global.
+ pub fn for_crawl(options: &CrawlerOptions) -> Self {
+ if options.global || options.global_prefix.is_some() {
+ Self::from_process()
+ } else {
+ Self::for_project(&options.cwd)
+ }
+ }
+
/// The caches `env` names. `home_dir` is the account's home (on Unix
/// the passwd entry's), which Gradle prefers to `$HOME`.
pub fn resolve(env: &dyn Env, os: Os, home_dir: Option<&Path>) -> Self {
+ Self::resolve_in(env, os, home_dir, None)
+ }
+
+ /// [`Self::resolve`] for the build Maven would run in `project`.
+ pub fn resolve_in(
+ env: &dyn Env,
+ os: Os,
+ home_dir: Option<&Path>,
+ project: Option<&Path>,
+ ) -> Self {
+ let (m2_repo, m2_undetermined) = m2_repo_in(env, os, home_dir, project);
Self {
- m2_repo: m2_repo_path_with(env, os, home_dir),
+ m2_repo,
+ m2_undetermined,
gradle: GradleHome::resolve(env, os, home_dir),
}
}
@@ -596,10 +644,20 @@ pub fn is_ro_root(path: &Path) -> bool {
JvmEnv::from_process().is_ro_root(path)
}
-/// The Maven local repository `env` names, in Maven's own order (#423):
+/// [`m2_repo_path_in`] with no project: the environment alone.
+pub fn m2_repo_path_with(env: &dyn Env, os: Os, home_dir: Option<&Path>) -> Option {
+ m2_repo_path_in(env, os, home_dir, None)
+}
+
+/// The Maven local repository `env` names for a build run in `project`,
+/// in Maven's own order (#423):
///
/// 1. `$MAVEN_REPO_LOCAL` (socket-patch's override);
-/// 2. `-Dmaven.repo.local` in `$MAVEN_ARGS`, then `$MAVEN_OPTS`;
+/// 2. `-Dmaven.repo.local` in `$MAVEN_ARGS`, then in the project's
+/// `.mvn/maven.config` ([`maven_config_repo_local`]), then in
+/// `$MAVEN_OPTS`. Maven puts the config file's arguments before the
+/// command line's, so the command line wins, and both are user
+/// properties, which it reads before the JVM's system properties;
/// 3. `` in the user settings
/// (`/.m2/settings.xml`), then in the global settings
/// (`conf/settings.xml` under `$MAVEN_HOME`, else `$M2_HOME`);
@@ -616,13 +674,32 @@ pub fn is_ro_root(path: &Path) -> bool {
/// when nothing names a repository and there is no usable home: a relative
/// or literal `~` would resolve against the working directory and treat a
/// `~/.m2` inside the scanned project as the user's local repository (B66).
-pub fn m2_repo_path_with(env: &dyn Env, os: Os, home_dir: Option<&Path>) -> Option {
+/// A relative `-Dmaven.repo.local` in `.mvn/maven.config` is the one
+/// exception: it is the project's own statement about the build run there,
+/// and is resolved against `project`, as Maven resolves it.
+pub fn m2_repo_path_in(
+ env: &dyn Env,
+ os: Os,
+ home_dir: Option<&Path>,
+ project: Option<&Path>,
+) -> Option {
+ m2_repo_in(env, os, home_dir, project).0
+}
+
+/// [`m2_repo_path_in`], and why there is no repository when the project's
+/// config names one that cannot be told ([`ConfigRepo::Undetermined`]).
+fn m2_repo_in(
+ env: &dyn Env,
+ os: Os,
+ home_dir: Option<&Path>,
+ project: Option<&Path>,
+) -> (Option, Option) {
use crate::gradle::home::system_property;
use crate::utils::fs::is_usable_home;
let set = |k: &str| env.var(k).filter(|v| !v.is_empty());
if let Some(repo_local) = set("MAVEN_REPO_LOCAL") {
- return Some(PathBuf::from(repo_local));
+ return (Some(PathBuf::from(repo_local)), None);
}
// Later sources override earlier ones on the JVM: command-line `-D`s
// (MAVEN_ARGS) are set over the launcher's MAVEN_OPTS.
@@ -633,6 +710,11 @@ pub fn m2_repo_path_with(env: &dyn Env, os: Os, home_dir: Option<&Path>) -> Opti
.filter(|v| !v.is_empty())
})
};
+ let argument = |k: &str| {
+ set(k)
+ .and_then(|opts| system_property(&opts, "maven.repo.local", os))
+ .filter(|v| !v.is_empty())
+ };
// `user.home` is fixed when the JVM starts: the launcher's MAVEN_OPTS
// can move it, a command-line `-D` (MAVEN_ARGS) comes too late for the
// `~/.m2` paths Maven derives from it.
@@ -652,11 +734,29 @@ pub fn m2_repo_path_with(env: &dyn Env, os: Os, home_dir: Option<&Path>) -> Opti
.filter(|h| is_usable_home(h))
.map(Path::to_path_buf)
});
- if let Some(repo) = property("maven.repo.local")
- .map(PathBuf::from)
- .filter(|p| p.has_root())
- {
- return Some(repo);
+ // The first source that sets the property decides, as in Maven: a
+ // command-line value it cannot use does not fall back to the next.
+ let lookup = |name: &str| match name {
+ "user.home" => user_home.as_ref().map(|h| h.display().to_string()),
+ _ => match name.strip_prefix("env.") {
+ Some(var) => set(var),
+ None => property(name),
+ },
+ };
+ let rooted = |value: Option| value.map(PathBuf::from).filter(|p| p.has_root());
+ // The first source that sets the property decides, as in Maven: the
+ // config's value is used as Maven uses it, and a command-line value
+ // this lookup cannot use does not fall back to the next source.
+ let repo_local = match argument("MAVEN_ARGS") {
+ Some(value) => rooted(Some(value)),
+ None => match project.map_or(ConfigRepo::Unset, |p| maven_config_repo_local(p, &lookup)) {
+ ConfigRepo::Path(repo) => return (Some(repo), None),
+ ConfigRepo::Undetermined(why) => return (None, Some(why)),
+ ConfigRepo::Unset => rooted(argument("MAVEN_OPTS")),
+ },
+ };
+ if let Some(repo) = repo_local {
+ return (Some(repo), None);
}
let maven_home = set("MAVEN_HOME").or_else(|| set("M2_HOME"));
let settings_files = [
@@ -665,19 +765,174 @@ pub fn m2_repo_path_with(env: &dyn Env, os: Os, home_dir: Option<&Path>) -> Opti
.map(|h| h.join(".m2").join("settings.xml")),
maven_home.map(|m| PathBuf::from(m).join("conf").join("settings.xml")),
];
- let lookup = |name: &str| match name {
- "user.home" => user_home.as_ref().map(|h| h.display().to_string()),
- _ => match name.strip_prefix("env.") {
- Some(var) => set(var),
- None => property(name),
- },
- };
for path in settings_files.into_iter().flatten() {
if let Some(repo) = settings_local_repository(&path, &lookup) {
- return Some(repo);
+ return (Some(repo), None);
+ }
+ }
+ (user_home.map(|h| h.join(".m2").join("repository")), None)
+}
+
+/// The largest `.mvn/maven.config` read: it holds a handful of arguments.
+const MAX_MAVEN_CONFIG_BYTES: u64 = 256 * 1024;
+
+/// What a project's `.mvn/maven.config` says of the local repository.
+#[derive(Debug, PartialEq, Eq)]
+enum ConfigRepo {
+ /// No config Maven would read here sets `-Dmaven.repo.local`.
+ Unset,
+ /// The repository Maven uses for it.
+ Path(PathBuf),
+ /// It names one repository to Maven before 3.9 and another to later
+ /// Mavens, both exist, and no Maven Wrapper says which builds this.
+ Undetermined(String),
+}
+
+/// The local repository a `-Dmaven.repo.local=…` in `.mvn/maven.config`
+/// names for the Maven build in `project`, read the way Maven reads it
+/// (checked against 3.6.3, 3.8.9, 3.9.16 and 4.0.0-rc-7).
+///
+/// Only a Maven build reads the file: a Gradle or Scala-tool build's
+/// `mavenLocal()` never does, so a project that is one (alone, or beside a
+/// `pom.xml`) keeps the environment's repository. The file is the one
+/// Maven's launcher finds: `.mvn/maven.config` in the nearest directory at
+/// or above `project` that holds a `.mvn` directory.
+///
+/// * Maven before 3.9 splits the whole file on whitespace and interpolates
+/// nothing; a `#` is an argument like any other (and stops the build).
+/// * Maven 3.9 and later takes one argument per line, skipping blank lines
+/// and lines that start with `#`, so a value runs to the end of its line
+/// (`formats::maven::maven_config_line_properties`, which also reads the
+/// `--define` and quoted spellings). From 3.9.2 on it fills in
+/// `${session.rootDirectory}` and `${maven.multiModuleProjectDirectory}`
+/// (that directory; Maven 4 does not fill in the second, see
+/// [`RootDirectory`]), `${session.topDirectory}` and `${user.dir}`
+/// (`project`) and what `lookup` knows (`${user.home}`, `${env.NAME}`).
+///
+/// For both the last occurrence wins, a placeholder nothing defines stays
+/// in the path as written, a relative path (an empty one included) is
+/// taken from `project`, where Maven runs, and no later source is asked.
+/// The Maven the project declares ([`DeclaredMaven`]: its wrapper's
+/// release, or a root pom only Maven 4 reads) says which reading applies.
+/// When it declares none,
+/// both are made: when they differ, the one whose directory exists is
+/// taken, the newer reading when neither does (nothing is installed in
+/// either), and none when both do.
+fn maven_config_repo_local(project: &Path, lookup: &dyn Fn(&str) -> Option) -> ConfigRepo {
+ const FLAG: &str = "-Dmaven.repo.local=";
+ let Ok(project) = std::path::absolute(project) else {
+ return ConfigRepo::Unset;
+ };
+ if !layout::has_build(&project, BuildTool::Maven)
+ || layout::has_build(&project, BuildTool::Gradle)
+ || layout::is_scala_tool_build(&project)
+ {
+ return ConfigRepo::Unset;
+ }
+ let Some(root) = project.ancestors().find(|dir| dir.join(".mvn").is_dir()) else {
+ return ConfigRepo::Unset;
+ };
+ let read = |rel: &str| {
+ let path = root.join(".mvn").join(rel);
+ // Bounded, and FIFO-safe: the files are in the project's own tree.
+ let small = std::fs::metadata(&path).ok()?.len() <= MAX_MAVEN_CONFIG_BYTES;
+ small
+ .then(|| crate::utils::fs::read_regular_to_string_sync(&path).ok())
+ .flatten()
+ };
+ let Some(text) = read("maven.config") else {
+ return ConfigRepo::Unset;
+ };
+ let at = |value: &str| project.join(value);
+ // Which Maven the project declares: its wrapper's release, or a root
+ // pom only Maven 4 reads (the answer every Maven reader here shares).
+ let root_pom = crate::utils::fs::read_regular_to_string_sync(&root.join("pom.xml")).ok();
+ let declared = DeclaredMaven::of(
+ read("wrapper/maven-wrapper.properties").as_deref(),
+ root_pom.as_deref(),
+ );
+ // Before 3.9: every `-Dmaven.repo.local=` token of the whole file. (The
+ // shared readers answer for 3.9 and later, or merge the two readings;
+ // which reading applies is what is being decided here.)
+ let before_3_9 = text
+ .split_whitespace()
+ .filter_map(|arg| arg.strip_prefix(FLAG))
+ .next_back()
+ .map(at);
+ // 3.9 and later: the shared reader of one argument per line.
+ let per_line =
+ crate::formats::maven::maven_config_line_properties(&text).remove("maven.repo.local");
+ let lookup = |name: &str| {
+ // The two spellings of the root directory, and which of them the
+ // declared Maven does not interpolate.
+ let root_property = [RootDirectory::Session, RootDirectory::Launcher]
+ .into_iter()
+ .find(|property| property.property() == format!("${{{name}}}"));
+ match (root_property, name) {
+ (Some(property), _) if property.unread_by(&declared) => None,
+ (Some(_), _) => Some(root.display().to_string()),
+ (None, "session.topDirectory" | "user.dir") => Some(project.display().to_string()),
+ (None, _) => lookup(name),
+ }
+ };
+ let from_3_9 = |interpolates: bool| {
+ per_line.as_deref().map(|value| match interpolates {
+ true => at(&interpolate_defined(value, &lookup)),
+ false => at(value),
+ })
+ };
+ let version = declared.release().map(release);
+ let found = |repo: Option| repo.map_or(ConfigRepo::Unset, ConfigRepo::Path);
+ match version {
+ // A root pom only Maven 4 reads: whatever the wrapper pins.
+ _ if declared.is_maven_4() => found(from_3_9(true)),
+ Some(version) if version < [3, 9, 0] => found(before_3_9),
+ Some(version) => found(from_3_9(version >= [3, 9, 2])),
+ // A comment line stops Maven before 3.9: the file is for a later one.
+ None if text.lines().any(|line| line.starts_with('#')) => found(from_3_9(true)),
+ None => {
+ let newer = from_3_9(true);
+ let exists = |repo: &Option| repo.as_ref().is_some_and(|p| p.is_dir());
+ match (exists(&before_3_9), exists(&newer)) {
+ _ if before_3_9 == newer => found(newer),
+ (true, false) => found(before_3_9),
+ (true, true) => ConfigRepo::Undetermined(format!(
+ "{} names the local repository {} to Maven before 3.9 and {} to Maven 3.9 \
+ and later, both exist, and the project has no Maven Wrapper to say which \
+ Maven builds it; set MAVEN_REPO_LOCAL to the one the build uses",
+ root.join(".mvn").join("maven.config").display(),
+ before_3_9.as_deref().unwrap_or(Path::new("")).display(),
+ newer.as_deref().unwrap_or(Path::new("")).display()
+ )),
+ _ => found(newer),
+ }
+ }
+ }
+}
+
+/// `text` with every `${name}` `lookup` defines replaced; one it does not
+/// define, or that is not closed, stays as written (Maven 3.9.2 and later
+/// treat a `maven.config` argument so).
+fn interpolate_defined(text: &str, lookup: &dyn Fn(&str) -> Option) -> String {
+ let mut out = String::new();
+ let mut rest = text;
+ while let Some(at) = rest.find("${") {
+ out.push_str(&rest[..at]);
+ let Some(end) = rest[at..].find('}').map(|end| end + at) else {
+ break;
+ };
+ match lookup(&rest[at + 2..end]) {
+ Some(value) => out.push_str(&value),
+ None => out.push_str(&rest[at..=end]),
}
+ rest = &rest[end + 1..];
}
- Some(user_home?.join(".m2").join("repository"))
+ // An unclosed `${` leaves `rest` at the text before it; take it from there.
+ out.push_str(match rest.find("${") {
+ Some(at) => &rest[at..],
+ None => rest,
+ });
+ out
}
/// The `` a Maven `settings.xml` at `path` names, with
@@ -811,13 +1066,13 @@ pub fn m2_gate(cwd: &Path, env: &JvmEnv) -> M2Gate {
/// Whether a Gradle-only build at `cwd` ignores the Maven local repository
/// (process environment; see [`m2_gate`]).
pub fn gradle_m2_ignored(cwd: &Path) -> bool {
- m2_gate(cwd, &JvmEnv::from_process()) == M2Gate::Ignored
+ m2_gate(cwd, &JvmEnv::for_project(cwd)) == M2Gate::Ignored
}
/// Why `mavenLocal()` could not be ruled out for the Gradle build at
/// `cwd`, when m2 is kept for that reason (process environment).
pub fn maven_local_undetermined(cwd: &Path) -> Option {
- match m2_gate(cwd, &JvmEnv::from_process()) {
+ match m2_gate(cwd, &JvmEnv::for_project(cwd)) {
M2Gate::Undetermined(why) => Some(why),
_ => None,
}
@@ -910,7 +1165,7 @@ impl MavenCrawler {
/// its layout ([`Self::get_jvm_cache_roots_with`] over the process
/// environment).
pub async fn get_jvm_cache_roots(&self, options: &CrawlerOptions) -> Vec {
- self.get_jvm_cache_roots_with(options, &JvmEnv::from_process())
+ self.get_jvm_cache_roots_with(options, &JvmEnv::for_crawl(options))
.await
}
@@ -1016,7 +1271,7 @@ impl MavenCrawler {
&self,
options: &CrawlerOptions,
) -> Result, std::io::Error> {
- self.get_maven_repo_paths_with(options, &JvmEnv::from_process())
+ self.get_maven_repo_paths_with(options, &JvmEnv::for_crawl(options))
.await
}
@@ -1042,7 +1297,7 @@ impl MavenCrawler {
&self,
options: &CrawlerOptions,
) -> Result, std::io::Error> {
- self.get_maven_copy_paths_with(options, &JvmEnv::from_process())
+ self.get_maven_copy_paths_with(options, &JvmEnv::for_crawl(options))
.await
}
@@ -1088,7 +1343,8 @@ impl MavenCrawler {
/// #265): another project's cached artifacts are not this project's
/// packages. A root pom that is not readable leaves the crawl unscoped.
pub async fn crawl_all(&self, options: &CrawlerOptions) -> Vec {
- self.crawl_all_with(options, &JvmEnv::from_process()).await
+ self.crawl_all_with(options, &JvmEnv::for_crawl(options))
+ .await
}
/// [`Self::crawl_all`] under the caches `env` names.
@@ -2792,6 +3048,7 @@ mod tests {
}
let env = JvmEnv {
m2_repo: Some(repo.clone()),
+ m2_undetermined: None,
gradle: None,
};
let purls = |packages: Vec| {
diff --git a/crates/socket-patch-core/src/crawlers/maven_crawler/local_repo_tests.rs b/crates/socket-patch-core/src/crawlers/maven_crawler/local_repo_tests.rs
index 3efe0985e0..b3cdba55b6 100644
--- a/crates/socket-patch-core/src/crawlers/maven_crawler/local_repo_tests.rs
+++ b/crates/socket-patch-core/src/crawlers/maven_crawler/local_repo_tests.rs
@@ -2,7 +2,8 @@
//! Maven itself uses (#423): `M2_HOME` is the Maven install, not a local
//! repository; `` in the user or global `settings.xml`
//! and `-Dmaven.repo.local` relocate it; on Windows `user.home` is the
-//! profile directory, whatever `HOME` says.
+//! profile directory, whatever `HOME` says. A project's `.mvn/maven.config`
+//! can relocate it too, for the builds run in that project.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -21,6 +22,11 @@ fn m2_repo(env: &HashMap, os: Os) -> Option {
JvmEnv::resolve(env, os, None).m2_repo
}
+/// The local repository of a build run in `project`.
+fn m2_repo_in(env: &HashMap, project: &Path) -> Option {
+ JvmEnv::resolve_in(env, Os::current(), None, Some(project)).m2_repo
+}
+
fn write(p: &Path, text: &str) {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
@@ -307,3 +313,342 @@ fn maven_args_user_home_does_not_move_the_m2_directory() {
Some(home.path().join(".m2").join("repository"))
);
}
+
+/// A Maven build at `dir`: Maven reads `.mvn/maven.config` for it.
+fn maven_build(dir: &Path) {
+ write(
+ &dir.join("pom.xml"),
+ "4.0.0\n",
+ );
+}
+
+/// The Maven Wrapper of the build rooted at `root`, pinning `version`.
+fn wrapper(root: &Path, version: &str) {
+ write(
+ &root.join(".mvn/wrapper/maven-wrapper.properties"),
+ &format!(
+ "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/\
+ {version}/apache-maven-{version}-bin.zip\n"
+ ),
+ );
+}
+
+/// `-Dmaven.repo.local` in the project's `.mvn/maven.config` is the local
+/// repository of every build run there, in Maven's order: below
+/// `MAVEN_REPO_LOCAL` and the command line (`MAVEN_ARGS`), above
+/// `MAVEN_OPTS` and the settings files.
+#[test]
+fn maven_config_local_repository_is_honoured_in_mavens_order() {
+ let home = tempfile::tempdir().unwrap();
+ let project = tempfile::tempdir().unwrap();
+ let from_settings = tempfile::tempdir().unwrap();
+ let from_config = tempfile::tempdir().unwrap();
+ let from_opts = tempfile::tempdir().unwrap();
+ let from_args = tempfile::tempdir().unwrap();
+ let from_env = tempfile::tempdir().unwrap();
+ maven_build(project.path());
+ write(
+ &home.path().join(".m2").join("settings.xml"),
+ &settings(from_settings.path().to_str().unwrap()),
+ );
+ let config = project.path().join(".mvn").join("maven.config");
+ write(
+ &config,
+ &format!(
+ "# the team's shared cache\n-B\n-Dmaven.repo.local={}\n-T 4\n",
+ from_config.path().display()
+ ),
+ );
+ let mut e = env(&[("HOME", home.path())]);
+ assert_eq!(
+ m2_repo_in(&e, project.path()),
+ Some(from_config.path().to_path_buf())
+ );
+ // Without the project the environment alone decides, as before.
+ assert_eq!(
+ m2_repo(&e, Os::current()),
+ Some(from_settings.path().to_path_buf())
+ );
+
+ e.insert(
+ "MAVEN_OPTS".into(),
+ format!("-Dmaven.repo.local={}", from_opts.path().display()),
+ );
+ assert_eq!(
+ m2_repo_in(&e, project.path()),
+ Some(from_config.path().to_path_buf()),
+ "a user property (maven.config) is read before a JVM one (MAVEN_OPTS)"
+ );
+ e.insert(
+ "MAVEN_ARGS".into(),
+ format!("-Dmaven.repo.local={}", from_args.path().display()),
+ );
+ assert_eq!(
+ m2_repo_in(&e, project.path()),
+ Some(from_args.path().to_path_buf()),
+ "the command line is merged over maven.config"
+ );
+ e.insert(
+ "MAVEN_REPO_LOCAL".into(),
+ from_env.path().to_str().unwrap().into(),
+ );
+ assert_eq!(
+ m2_repo_in(&e, project.path()),
+ Some(from_env.path().to_path_buf())
+ );
+}
+
+/// Only a Maven build reads `.mvn/maven.config`. A Gradle build below a
+/// directory that holds one (a monorepo with a Maven root), or beside a
+/// `pom.xml`, resolves `mavenLocal()` from the environment's repository,
+/// and so does the crawl.
+#[test]
+fn maven_config_is_not_read_for_a_gradle_build() {
+ let home = tempfile::tempdir().unwrap();
+ let root = tempfile::tempdir().unwrap();
+ let from_config = tempfile::tempdir().unwrap();
+ let e = env(&[("HOME", home.path())]);
+ let default = Some(home.path().join(".m2").join("repository"));
+ maven_build(root.path());
+ write(
+ &root.path().join(".mvn/maven.config"),
+ &format!("-Dmaven.repo.local={}\n", from_config.path().display()),
+ );
+ assert_eq!(
+ m2_repo_in(&e, root.path()),
+ Some(from_config.path().to_path_buf())
+ );
+
+ let gradle = root.path().join("tools").join("gradle-app");
+ write(
+ &gradle.join("settings.gradle"),
+ "rootProject.name = 'app'\n",
+ );
+ write(&gradle.join("build.gradle"), "plugins { id 'java' }\n");
+ assert_eq!(m2_repo_in(&e, &gradle), default, "a Gradle-only project");
+ let resolved = JvmEnv::resolve_in(&e, Os::current(), None, Some(&gradle));
+ assert_eq!(resolved.m2_undetermined, None);
+
+ maven_build(&gradle);
+ assert_eq!(m2_repo_in(&e, &gradle), default, "Gradle beside a pom.xml");
+
+ // No build at all: nothing Maven would run here.
+ let bare = root.path().join("docs");
+ std::fs::create_dir_all(&bare).unwrap();
+ assert_eq!(m2_repo_in(&e, &bare), default);
+}
+
+/// The config is the one Maven's launcher finds from a module directory:
+/// in the nearest directory above that holds `.mvn`. A relative value is
+/// taken from the directory Maven runs in, and Maven's own placeholders
+/// resolve.
+#[test]
+fn maven_config_is_found_above_a_module_and_interpolated() {
+ let home = tempfile::tempdir().unwrap();
+ let root = tempfile::tempdir().unwrap();
+ let module = root.path().join("services").join("api");
+ maven_build(root.path());
+ maven_build(&module);
+ let config = root.path().join(".mvn").join("maven.config");
+ let e = env(&[("HOME", home.path())]);
+
+ write(
+ &config,
+ "-Dmaven.repo.local=${session.rootDirectory}/.m2/repository\n",
+ );
+ let in_root = Some(root.path().join(".m2").join("repository"));
+ assert_eq!(m2_repo_in(&e, &module), in_root);
+ assert_eq!(m2_repo_in(&e, root.path()), in_root);
+
+ write(
+ &config,
+ "-Dmaven.repo.local=${user.home}/cache/m2\r\n-B\r\n",
+ );
+ assert_eq!(
+ m2_repo_in(&e, &module),
+ Some(home.path().join("cache").join("m2"))
+ );
+
+ write(
+ &config,
+ "-Dmaven.repo.local=first\n\n-Dmaven.repo.local=.repo\n",
+ );
+ assert_eq!(m2_repo_in(&e, &module), Some(module.join(".repo")));
+ assert_eq!(m2_repo_in(&e, root.path()), Some(root.path().join(".repo")));
+
+ // A nearer `.mvn` is the one the launcher stops at, config or not.
+ std::fs::create_dir_all(module.join(".mvn")).unwrap();
+ assert_eq!(
+ m2_repo_in(&e, &module),
+ Some(home.path().join(".m2").join("repository"))
+ );
+}
+
+/// Maven before 3.9 splits `maven.config` on whitespace and interpolates
+/// nothing; 3.9 and later take a line as one argument, so a value runs to
+/// the end of its line. The Maven Wrapper says which Maven reads the file;
+/// without one, the reading whose directory exists is the build's.
+#[test]
+fn maven_config_is_tokenised_as_the_projects_maven_does() {
+ let home = tempfile::tempdir().unwrap();
+ let e = env(&[("HOME", home.path())]);
+ let default = Some(home.path().join(".m2").join("repository"));
+ let project = || {
+ let dir = tempfile::tempdir().unwrap();
+ maven_build(dir.path());
+ dir
+ };
+ const ONE_LINE: &str = "-Dmaven.repo.local=.m2/repo -B -ntp\n";
+ let (split, whole) = (".m2/repo", ".m2/repo -B -ntp");
+
+ // The wrapper decides, whatever is on disk.
+ for (version, repo) in [
+ ("3.6.3", split),
+ ("3.8.9", split),
+ ("3.9.16", whole),
+ ("4.0.0-rc-7", whole),
+ ] {
+ let p = project();
+ write(&p.path().join(".mvn/maven.config"), ONE_LINE);
+ wrapper(p.path(), version);
+ assert_eq!(
+ m2_repo_in(&e, p.path()),
+ Some(p.path().join(repo)),
+ "{version}"
+ );
+ }
+ // Interpolation came with 3.9.2.
+ for (version, repo) in [
+ ("3.8.9", "${session.rootDirectory}/r"),
+ ("3.9.1", "${session.rootDirectory}/r"),
+ ("3.9.2", "r"),
+ ] {
+ let p = project();
+ write(
+ &p.path().join(".mvn/maven.config"),
+ "-Dmaven.repo.local=${session.rootDirectory}/r\n",
+ );
+ wrapper(p.path(), version);
+ let expected = match repo {
+ "r" => p.path().join("r"),
+ literal => p.path().join(literal),
+ };
+ assert_eq!(m2_repo_in(&e, p.path()), Some(expected), "{version}");
+ }
+
+ // A root pom only Maven 4 reads declares its Maven without a wrapper,
+ // and Maven 4 does not fill in `${maven.multiModuleProjectDirectory}`.
+ let p = project();
+ write(
+ &p.path().join("pom.xml"),
+ "4.1.0\n",
+ );
+ write(&p.path().join(".mvn/maven.config"), ONE_LINE);
+ std::fs::create_dir_all(p.path().join(split)).unwrap();
+ assert_eq!(m2_repo_in(&e, p.path()), Some(p.path().join(whole)));
+ for (config, repo) in [
+ ("-Dmaven.repo.local=${session.rootDirectory}/r\n", "r"),
+ (
+ "-Dmaven.repo.local=${maven.multiModuleProjectDirectory}/r\n",
+ "${maven.multiModuleProjectDirectory}/r",
+ ),
+ // The other spellings of a definition, as the shared reader has them.
+ ("--define maven.repo.local=d\n", "d"),
+ ("-D\nmaven.repo.local=n\n", "n"),
+ ("\"-Dmaven.repo.local=q\"\n", "q"),
+ ] {
+ write(&p.path().join(".mvn/maven.config"), config);
+ assert_eq!(
+ m2_repo_in(&e, p.path()),
+ Some(p.path().join(repo)),
+ "{config}"
+ );
+ }
+
+ // No wrapper: the repository an earlier build left is the one.
+ let p = project();
+ write(&p.path().join(".mvn/maven.config"), ONE_LINE);
+ assert_eq!(
+ m2_repo_in(&e, p.path()),
+ Some(p.path().join(whole)),
+ "neither exists: nothing is installed in either"
+ );
+ std::fs::create_dir_all(p.path().join(split)).unwrap();
+ assert_eq!(m2_repo_in(&e, p.path()), Some(p.path().join(split)));
+ // Both exist: not guessed at, and said.
+ std::fs::create_dir_all(p.path().join(whole)).unwrap();
+ let resolved = JvmEnv::resolve_in(&e, Os::current(), None, Some(p.path()));
+ assert_eq!(resolved.m2_repo, None);
+ let why = resolved.m2_undetermined.expect("the reason");
+ assert!(
+ why.contains("to Maven before 3.9")
+ && why.contains(&p.path().join(whole).display().to_string())
+ && why.contains("set MAVEN_REPO_LOCAL"),
+ "{why}"
+ );
+ std::fs::remove_dir(p.path().join(split)).unwrap();
+ assert_eq!(m2_repo_in(&e, p.path()), Some(p.path().join(whole)));
+
+ // Several arguments on a line that does not start with the property:
+ // only Maven before 3.9 sets it from there.
+ let p = project();
+ write(
+ &p.path().join(".mvn/maven.config"),
+ "-B -Dmaven.repo.local=first -Dmaven.repo.local=.repo -q\n",
+ );
+ assert_eq!(m2_repo_in(&e, p.path()), default);
+ std::fs::create_dir_all(p.path().join(".repo")).unwrap();
+ assert_eq!(m2_repo_in(&e, p.path()), Some(p.path().join(".repo")));
+ // A comment line stops Maven before 3.9, so the file is a later one's.
+ write(
+ &p.path().join(".mvn/maven.config"),
+ "# flags\n-B -Dmaven.repo.local=.repo\n",
+ );
+ assert_eq!(m2_repo_in(&e, p.path()), default);
+}
+
+/// A config that does not set the property, or is not a file, changes
+/// nothing. One that sets it decides, with the value Maven itself makes of
+/// it: an empty one is the directory Maven runs in, and a placeholder
+/// nothing defines stays in the path. `MAVEN_OPTS` is not reached.
+#[test]
+fn a_maven_config_value_is_used_as_maven_uses_it() {
+ let home = tempfile::tempdir().unwrap();
+ let project = tempfile::tempdir().unwrap();
+ let from_opts = tempfile::tempdir().unwrap();
+ maven_build(project.path());
+ let config = project.path().join(".mvn").join("maven.config");
+ let mut e = env(&[("HOME", home.path())]);
+ let default = Some(home.path().join(".m2").join("repository"));
+
+ std::fs::create_dir_all(project.path().join(".mvn")).unwrap();
+ assert_eq!(m2_repo_in(&e, project.path()), default, "no config");
+ e.insert(
+ "MAVEN_OPTS".into(),
+ format!("-Dmaven.repo.local={}", from_opts.path().display()),
+ );
+ let opts = Some(from_opts.path().to_path_buf());
+ for text in [
+ "-B\n-Dmaven.repo.locale=/elsewhere\n",
+ "-Dmaven.repo.local.tail=/a/tail\n",
+ "# -Dmaven.repo.local=/commented\n",
+ ] {
+ write(&config, text);
+ assert_eq!(m2_repo_in(&e, project.path()), opts, "{text:?}");
+ }
+ std::fs::remove_file(&config).unwrap();
+ std::fs::create_dir(&config).unwrap();
+ assert_eq!(m2_repo_in(&e, project.path()), opts, "a directory");
+ std::fs::remove_dir(&config).unwrap();
+
+ write(&config, "-Dmaven.repo.local=${some.build.property}/m2\n");
+ assert_eq!(
+ m2_repo_in(&e, project.path()),
+ Some(project.path().join("${some.build.property}/m2"))
+ );
+ write(&config, "-Dmaven.repo.local=\n");
+ assert_eq!(
+ m2_repo_in(&e, project.path()).as_deref(),
+ Some(project.path())
+ );
+}
diff --git a/crates/socket-patch-core/src/crawlers/maven_selection.rs b/crates/socket-patch-core/src/crawlers/maven_selection.rs
index 5274823082..97f8bc5f82 100644
--- a/crates/socket-patch-core/src/crawlers/maven_selection.rs
+++ b/crates/socket-patch-core/src/crawlers/maven_selection.rs
@@ -144,7 +144,8 @@ impl MavenSelection {
}
/// The selection of the project at `project_root` over the Maven local
- /// repository this process resolves against.
+ /// repository its builds resolve against (the environment's, or the one
+ /// its `.mvn/maven.config` names).
pub fn for_project(project_root: &Path) -> Self {
Self::for_project_in(project_root, None)
}
@@ -154,7 +155,7 @@ impl MavenSelection {
pub fn for_project_in(project_root: &Path, repo: Option<&Path>) -> Self {
let repo = match repo {
Some(repo) => Some(repo.to_path_buf()),
- None => super::maven_crawler::JvmEnv::from_process().m2_repo,
+ None => super::maven_crawler::JvmEnv::for_project(project_root).m2_repo,
};
match repo {
Some(repo) => Self::of(project_root, &repo),
diff --git a/crates/socket-patch-core/src/hash/git_sha256.rs b/crates/socket-patch-core/src/hash/git_sha256.rs
index 515a4a34b7..16e5e583c6 100644
--- a/crates/socket-patch-core/src/hash/git_sha256.rs
+++ b/crates/socket-patch-core/src/hash/git_sha256.rs
@@ -111,18 +111,6 @@ pub(crate) fn compute_git_sha256_from_std_reader(
Ok(hex::encode(hasher.finalize()))
}
-/// Git SHA-256 of the zip member `name`, streamed through
-/// [`compute_git_sha256_from_std_reader`] so the member is never inflated
-/// into memory. `None` when the archive has no such member; `Some(Err)` when
-/// it can't be read whole (a corrupt stream or a size that disagrees with it).
-pub(crate) fn zip_member_git_sha256(
- archive: &mut zip::ZipArchive,
- name: &str,
-) -> Option> {
- let entry = archive.by_name(name).ok()?;
- Some(compute_git_sha256_from_std_reader(entry.size(), entry))
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -417,37 +405,4 @@ mod tests {
let err = result.expect_err("one byte over declared size must error");
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
-
- /// `zip_member_git_sha256` hashes stored, deflated and empty members
- /// exactly as the buffered hash of their bytes, and reports an absent
- /// member as `None`.
- #[test]
- fn test_zip_member_matches_buffered_hash() {
- use std::io::Write as _;
- let members: [(&str, &[u8], zip::CompressionMethod); 3] = [
- ("stored.txt", b"hello world", zip::CompressionMethod::Stored),
- (
- "deflated.txt",
- &[b'a'; 100_000],
- zip::CompressionMethod::Deflated,
- ),
- ("empty.txt", b"", zip::CompressionMethod::Deflated),
- ];
- let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
- for (name, bytes, method) in &members {
- let opts = zip::write::SimpleFileOptions::default().compression_method(*method);
- out.start_file(*name, opts).unwrap();
- out.write_all(bytes).unwrap();
- }
- let jar = out.finish().unwrap().into_inner();
- let mut archive = zip::ZipArchive::new(std::io::Cursor::new(jar)).unwrap();
- for (name, bytes, _) in &members {
- assert_eq!(
- zip_member_git_sha256(&mut archive, name).unwrap().unwrap(),
- compute_git_sha256_from_bytes(bytes),
- "{name}"
- );
- }
- assert!(zip_member_git_sha256(&mut archive, "missing.txt").is_none());
- }
}
diff --git a/crates/socket-patch-core/src/patch/jar_members.rs b/crates/socket-patch-core/src/patch/jar_members.rs
new file mode 100644
index 0000000000..73993b39ce
--- /dev/null
+++ b/crates/socket-patch-core/src/patch/jar_members.rs
@@ -0,0 +1,967 @@
+//! Bounded, streaming reads of a JVM jar.
+//!
+//! The zip reader the vendored-artifact checks share
+//! (`vendor::verify::read_zip_to_map`) was sized for Python wheels: 10,000
+//! entries, 64 MiB inflated, every member held in memory. Released jars pass
+//! both (`hive-exec-3.1.3.jar`: 23,728 entries, 93 MiB;
+//! `poi-ooxml-full-5.2.5.jar`: 15,181 entries), so a patch for one could
+//! never be applied, and comparing two jars through it held every member of
+//! both at once.
+//!
+//! Here each member is inflated through a hasher and dropped, so one pass
+//! holds a digest per member, whatever the jar's size.
+//!
+//! # What counts as a member
+//!
+//! Every entry a JVM can load: any entry whose name does not end in `/`,
+//! **whatever its unix mode**. A class loader reads an entry's bytes by name
+//! and never looks at the mode, so an entry carrying symlink mode bits is as
+//! loadable as any other (the wheel reader skips those). Names are compared
+//! as the raw bytes of the central directory, which is what the JVM matches
+//! on. An archive with two entries of one name is read as its last one: the
+//! `zip` crate and `java.util.zip.ZipFile` both resolve a name to the last
+//! entry that carries it.
+//!
+//! Directory entries are not members: released service jars carry none,
+//! newer ones keep upstream's, and no class loader resolves a class through
+//! one. Signature files (`META-INF/*.SF`, `.RSA`, `.DSA`, `.EC`) are left
+//! out of [`unpatched_difference`]: a repack that changes a member has to
+//! drop them.
+//!
+//! # Limits
+//!
+//! The sizes an archive declares for its entries are the author's claim, so
+//! the byte limits are on what is actually inflated. The entry count and
+//! the central directory's size are read from the archive's end record
+//! before the zip reader parses the directory, since the reader allocates
+//! for whatever that record declares: a directory of millions of tiny
+//! records is refused unread.
+//!
+//! The reader does not take the end record from a fixed place. It looks
+//! for one backwards from the end of the file, however much follows it,
+//! finds a zip64 record forwards from where the locator points, and falls
+//! back to an earlier end record when a directory does not parse. So
+//! [`admit`] walks the same way: it finds the last end record the reader
+//! can take, holds it to the limits, and hides everything below that
+//! record's directory from the reader while the archive is opened
+//! ([`Veiled`]). What the reader can then fall back to lies in the
+//! directory itself, and each such record is held to the limits too. An
+//! end record inside a member's data, as a jar stored inside a fat jar
+//! has, is below the directory: the reader cannot take it, and it is not
+//! looked at.
+//!
+//! * [`MAX_ENTRIES`]: 200,000 entries. Eight times the largest jar measured
+//! above; the jars a 128 MiB download can carry stay well under it.
+//! * [`MAX_CENTRAL_DIRECTORY_BYTES`]: 64 MiB of central directory, some 300
+//! bytes for each of 200,000 entries (the largest measured is 2 MiB).
+//! * [`MAX_INFLATED_BYTES`]: 1 GiB inflated in one pass over one jar. Eleven
+//! times the largest measured, and what a jar at the 128 MiB download cap
+//! inflates to at 8:1, above what class files and resources reach.
+//! * [`MAX_INFLATE_RATIO`]: no more than 100 times the archive's own size,
+//! once past the [`RATIO_FLOOR_BYTES`] (64 MiB, the old limit) every
+//! archive may use. Deflate reaches 1000:1 on a crafted stream; jars sit
+//! around 2:1 to 10:1. This keeps a small hostile archive from spending
+//! the whole 1 GiB.
+//!
+//! A jar past a limit is [`JarError::TooLarge`], and the text says which
+//! limit and by how much.
+
+use std::collections::BTreeMap;
+use std::io::{Read, Seek, SeekFrom};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Arc;
+
+use sha2::{Digest, Sha256};
+
+use crate::hash::git_sha256::compute_git_sha256_from_std_reader;
+
+/// Entries one jar may hold (see the module docs).
+pub(crate) const MAX_ENTRIES: usize = 200_000;
+/// Bytes the central directory of one jar may take.
+pub(crate) const MAX_CENTRAL_DIRECTORY_BYTES: u64 = 64 * 1024 * 1024;
+/// Bytes one pass over one jar may inflate.
+pub(crate) const MAX_INFLATED_BYTES: u64 = 1024 * 1024 * 1024;
+/// Inflated bytes allowed per archive byte, past [`RATIO_FLOOR_BYTES`].
+pub(crate) const MAX_INFLATE_RATIO: u64 = 100;
+/// What any archive may inflate to, however small it is.
+pub(crate) const RATIO_FLOOR_BYTES: u64 = 64 * 1024 * 1024;
+
+/// Why a jar could not be read.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) enum JarError {
+ /// Not a zip archive, or a member whose stream is corrupt.
+ Unreadable(String),
+ /// Past a limit of the module docs; the text names it.
+ TooLarge(String),
+}
+
+impl JarError {
+ pub(crate) fn is_too_large(&self) -> bool {
+ matches!(self, JarError::TooLarge(_))
+ }
+}
+
+impl std::fmt::Display for JarError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ JarError::Unreadable(why) | JarError::TooLarge(why) => f.write_str(why),
+ }
+ }
+}
+
+fn mib(bytes: u64) -> u64 {
+ bytes.div_ceil(1024 * 1024)
+}
+
+/// What one pass over an archive of `archive_len` bytes may inflate.
+fn inflate_budget(archive_len: u64) -> u64 {
+ MAX_INFLATED_BYTES.min(RATIO_FLOOR_BYTES.max(archive_len.saturating_mul(MAX_INFLATE_RATIO)))
+}
+
+/// One pass over a jar: the open archive and what is left of its inflate
+/// budget.
+pub(crate) struct Jar {
+ zip: zip::ZipArchive>,
+ archive_len: u64,
+ budget: u64,
+ left: u64,
+}
+
+impl<'a> Jar> {
+ /// A pass over the jar bytes `jar`.
+ pub(crate) fn of_bytes(jar: &'a [u8]) -> Result {
+ Jar::open(std::io::Cursor::new(jar), jar.len() as u64)
+ }
+}
+
+impl Jar {
+ /// A pass over the archive `reader` holds, `archive_len` bytes long.
+ pub(crate) fn open(mut reader: R, archive_len: u64) -> Result {
+ let floor = Arc::new(AtomicU64::new(admit(&mut reader, archive_len)?));
+ let veiled = Veiled {
+ inner: reader,
+ floor: Arc::clone(&floor),
+ };
+ let zip = zip::ZipArchive::new(veiled)
+ .map_err(|e| JarError::Unreadable(format!("not a readable zip archive ({e})")))?;
+ // The directory is parsed: the members are read from the real bytes.
+ floor.store(0, Ordering::Relaxed);
+ if zip.len() > MAX_ENTRIES {
+ return Err(JarError::TooLarge(format!(
+ "it holds {} entries, over the limit of {MAX_ENTRIES}",
+ zip.len()
+ )));
+ }
+ let budget = inflate_budget(archive_len);
+ Ok(Jar {
+ zip,
+ archive_len,
+ budget,
+ left: budget,
+ })
+ }
+
+ fn over_budget(&self) -> JarError {
+ JarError::TooLarge(if self.budget < MAX_INFLATED_BYTES {
+ format!(
+ "it inflates to more than {} MiB, over {MAX_INFLATE_RATIO} times its own size \
+ ({} MiB) and the {} MiB every jar may use",
+ mib(self.budget),
+ mib(self.archive_len),
+ mib(RATIO_FLOOR_BYTES)
+ )
+ } else {
+ format!(
+ "it inflates to more than {} MiB, over the limit for one jar",
+ mib(MAX_INFLATED_BYTES)
+ )
+ })
+ }
+
+ /// The sha256 of every member's content, keyed by raw name (see the
+ /// module docs for what a member is).
+ pub(crate) fn content_digests(&mut self) -> Result {
+ let mut out = BTreeMap::new();
+ let mut buf = vec![0u8; 64 * 1024];
+ for i in 0..self.zip.len() {
+ let mut entry = self
+ .zip
+ .by_index(i)
+ .map_err(|e| JarError::Unreadable(format!("entry {i} cannot be read ({e})")))?;
+ let name = entry.name_raw().to_vec();
+ if name.last() == Some(&b'/') {
+ continue;
+ }
+ let mut hasher = Sha256::new();
+ loop {
+ let n = entry.read(&mut buf).map_err(|e| {
+ JarError::Unreadable(format!(
+ "member `{}` cannot be inflated ({e})",
+ String::from_utf8_lossy(&name)
+ ))
+ })?;
+ if n == 0 {
+ break;
+ }
+ if n as u64 > self.left {
+ drop(entry);
+ return Err(self.over_budget());
+ }
+ self.left -= n as u64;
+ hasher.update(&buf[..n]);
+ }
+ out.insert(name, hasher.finalize().into());
+ }
+ Ok(Digests(out))
+ }
+
+ /// The git-blob sha256 of the member `name`, `None` when the jar has no
+ /// such member. Counts against the pass's budget.
+ pub(crate) fn member_git_sha256(&mut self, name: &str) -> Result