From 71e9ca17601dac82cf7dd594e773c5c5146e041e Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 12:14:15 -0500 Subject: [PATCH 1/5] Read jars within jar-sized limits and hold every vendored jar to upstream Agent mode and vendored mode read jars through the zip reader written for Python wheels: 10,000 entries and 64 MiB inflated at most, regular-file entries only, both jars held whole in memory. Released jars are past those caps (hive-exec-3.1.3: 23,728 entries, 93 MiB), so agent mode refused them as "the patch service's jar is unreadable", and a vendored one could not be attested, re-vendored online or repaired. Jars now have their own reader (patch/jar_members): member by member, hashing as it inflates, bounded by what is actually inflated and by the archive's own entry count rather than by declared sizes. The limits are 200,000 entries, and per pass 1 GiB inflated and 100 times the jar's size (64 MiB for a small jar). A jar past one is jvm_jar_too_large (agent) or vendor_artifact_too_large (vendored), and the message names the limit. The comparison of a patched jar with the original covers every entry the JVM would load, whatever unix mode it carries: an entry with a symlink's mode bits was skipped, so a class added that way went unseen. Directory entries and signature files stay exempt. A first vendoring makes that comparison too, against the registry-verified upstream jar and before anything is written. It used to run only on an online re-run over a committed tree, so a service jar built from another base was committed and wired. A copy that differs outside the patch now fails with jvm_agent_service_jar_mismatch, naming the members; the per-copy error carried no code. A ~/.m2 jar that another project (or an earlier workspace over a cached repository) patched has no backup in this project. Its rollback now restores the registry's jar when the download matches the registry's checksum and is the jar the copy was patched from, and otherwise says what happened and how to recover, as does an apply over a copy that holds another revision of the patch. -Dmaven.repo.local in the project's .mvn/maven.config names the local repository, between the command line (MAVEN_ARGS) and MAVEN_OPTS, as in Maven 3.6.3, 3.8.9, 3.9.16 and 4.0.0-rc-7. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 68 ++- crates/socket-patch-cli/src/commands/apply.rs | 9 + .../socket-patch-cli/src/commands/scan/mod.rs | 6 +- crates/socket-patch-cli/src/commands/vex.rs | 6 + .../src/ecosystem_dispatch.rs | 5 +- .../tests/e2e_vendor_maven_build.rs | 164 +++++ .../tests/gradle_agent_cli.rs | 115 +++- .../tests/maven_build_common/mod.rs | 25 + .../tests/maven_sidecar_cli.rs | 242 ++++++++ .../socket-patch-cli/tests/vendor_jvm_cli.rs | 68 +++ .../src/crawlers/jvm_cache.rs | 2 +- .../src/crawlers/maven_crawler.rs | 173 +++++- .../maven_crawler/local_repo_tests.rs | 159 ++++- .../src/crawlers/maven_selection.rs | 5 +- .../src/patch/jar_members.rs | 545 +++++++++++++++++ crates/socket-patch-core/src/patch/jvm_jar.rs | 578 +++++++++++++++--- crates/socket-patch-core/src/patch/mod.rs | 1 + .../src/vendor/jvm/gradle.rs | 16 +- .../src/vendor/lock_inventory/tests.rs | 5 + .../src/vendor/maven_repo.rs | 394 +++++++++++- .../src/vendor/redownload.rs | 36 +- .../vendor/test_support/service_fixture.rs | 20 +- crates/socket-patch-core/src/vendor/verify.rs | 97 ++- docs/design/maven-vendoring.md | 2 +- docs/ecosystems.md | 26 +- 25 files changed, 2575 insertions(+), 192 deletions(-) create mode 100644 crates/socket-patch-core/src/patch/jar_members.rs diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 6338d568b..8c46a6bcf 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1978,7 +1978,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. | @@ -2183,7 +2183,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. | @@ -2824,6 +2824,28 @@ 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. +A vendored jar must be upstream's jar outside the patch. Online, the jar (the patch +service's on a first vendoring, the committed one on a re-run) is compared with the +upstream jar before anything is written: a cached copy the registry's checksum +vouches for, else the registry's own download held to the same checksum. Every entry +the JVM would load must hold the same content in both, whatever unix mode it carries; +the record's members and signature files (`META-INF/*.SF`, `.RSA`, `.DSA`, `.EC`) are +exempt and directory entries may differ. A jar that adds, drops or changes anything +else is refused with `vendor_prebuilt_integrity_mismatch`, the detail naming up to +three such members, and a first vendoring commits and wires nothing. When no upstream +jar can be verified the refusal is `vendor_jvm_upstream_unavailable`. + +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 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, 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 @@ -3168,14 +3190,45 @@ 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. 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. +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 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): @@ -3191,10 +3244,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. 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 diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 0681686d7..b7386ed31 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -3703,6 +3703,15 @@ async fn apply_maven_base(m: &MavenBase<'_>) -> MavenApplied { for mut result in results { 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. + let coded = result.error.as_deref().and_then(|error| { + let code = jvm_jar::copy_failure_code(error)?; + Some((code, error[code.len() + 2..].to_string())) + }); + if let Some((code, detail)) = coded { + out.warn(code, detail); + } 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 8f33bdb0f..01eb328a5 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -1381,7 +1381,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 diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 8a891bfe0..ae55f7d4c 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 \ @@ -2682,6 +2687,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 d98b38bcc..a87ca3112 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 6c27c2ea7..83031b7e2 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 c7f1209e5..660b99b01 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 32ee053f4..f6852f94a 100644 --- a/crates/socket-patch-cli/tests/maven_build_common/mod.rs +++ b/crates/socket-patch-cli/tests/maven_build_common/mod.rs @@ -238,6 +238,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 bda297244..25d74a533 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,243 @@ 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 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 4046d00d3..331f61200 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 adecae1b7..26d2f269e 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 a235fc5c0..3984e3235 100644 --- a/crates/socket-patch-core/src/crawlers/maven_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/maven_crawler.rs @@ -532,7 +532,8 @@ 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`]); @@ -552,11 +553,47 @@ impl JvmEnv { } } + /// [`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 { + Self { + m2_repo: m2_repo_path_in( + &gradle_cache::ProcessEnv, + Os::current(), + None, + Some(project), + ), + 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 { Self { - m2_repo: m2_repo_path_with(env, os, home_dir), + m2_repo: m2_repo_path_in(env, os, home_dir, project), gradle: GradleHome::resolve(env, os, home_dir), } } @@ -596,10 +633,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,7 +663,15 @@ 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`. +pub fn m2_repo_path_in( + env: &dyn Env, + os: Os, + home_dir: Option<&Path>, + project: Option<&Path>, +) -> Option { use crate::gradle::home::system_property; use crate::utils::fs::is_usable_home; @@ -633,6 +688,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,10 +712,24 @@ 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()) - { + // 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()); + let repo_local = match argument("MAVEN_ARGS") { + Some(value) => rooted(Some(value)), + None => match project.and_then(|p| maven_config_repo_local(p, &lookup)) { + Some(value) => value, + None => rooted(argument("MAVEN_OPTS")), + }, + }; + if let Some(repo) = repo_local { return Some(repo); } let maven_home = set("MAVEN_HOME").or_else(|| set("M2_HOME")); @@ -665,13 +739,6 @@ 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); @@ -680,6 +747,67 @@ pub fn m2_repo_path_with(env: &dyn Env, os: Os, home_dir: Option<&Path>) -> Opti Some(user_home?.join(".m2").join("repository")) } +/// The largest `.mvn/maven.config` read: it holds a handful of arguments. +const MAX_MAVEN_CONFIG_BYTES: u64 = 256 * 1024; + +/// The local repository a `-Dmaven.repo.local=…` in the `.mvn/maven.config` +/// of the build Maven would run in `project` names. `None` when no config +/// sets the property; `Some(None)` when one does with a value that is not +/// used here: an empty one (Maven then takes the directory it runs in for +/// its repository) or a placeholder nothing here defines. The config still +/// decides, as it does in Maven: no later source is consulted. +/// +/// 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. +/// Each line is one argument (Maven 3.9 and later; `#` starts a comment +/// line); a line that is not the property itself is also split on +/// whitespace, which is how earlier Mavens read the whole file. The last +/// occurrence wins. Maven interpolates the arguments (3.9.2 and later): +/// `${session.rootDirectory}` and `${maven.multiModuleProjectDirectory}` +/// are that directory, `${session.topDirectory}` and `${user.dir}` are +/// `project`, and anything else is asked of `lookup` (`${user.home}`, +/// `${env.NAME}`, a `-D` of the environment). A relative path is taken +/// from `project`, where Maven would run. +fn maven_config_repo_local( + project: &Path, + lookup: &dyn Fn(&str) -> Option, +) -> Option> { + const FLAG: &str = "-Dmaven.repo.local="; + // `.` has no ancestors to search. + let project = std::path::absolute(project).ok()?; + let root = project.ancestors().find(|dir| dir.join(".mvn").is_dir())?; + let config = root.join(".mvn").join("maven.config"); + // Bounded, and FIFO-safe: the file is in the project's own tree. + if std::fs::metadata(&config).ok()?.len() > MAX_MAVEN_CONFIG_BYTES { + return None; + } + let text = crate::utils::fs::read_regular_to_string_sync(&config).ok()?; + let value = text + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .filter_map(|line| match line.strip_prefix(FLAG) { + Some(value) => Some(value), + None => line + .split_whitespace() + .filter_map(|arg| arg.strip_prefix(FLAG)) + .next_back(), + }) + .next_back()? + .trim(); + if value.is_empty() { + return Some(None); + } + let lookup = |name: &str| match name { + "session.rootDirectory" | "maven.multiModuleProjectDirectory" => { + Some(root.display().to_string()) + } + "session.topDirectory" | "user.dir" => Some(project.display().to_string()), + _ => lookup(name), + }; + Some(interpolate(value, &lookup).map(|value| project.join(value))) +} + /// The `` a Maven `settings.xml` at `path` names, with /// `${…}` placeholders resolved through `lookup`. `None` when the file is /// missing, unreadable or not well formed where it matters, sets no @@ -811,13 +939,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 +1038,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 +1144,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 +1170,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 +1216,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. 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 3efe0985e..cf622aeb6 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,154 @@ fn maven_args_user_home_does_not_move_the_m2_directory() { Some(home.path().join(".m2").join("repository")) ); } + +/// `-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(); + 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()) + ); +} + +/// 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"); + std::fs::create_dir_all(&module).unwrap(); + 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\n"); + assert_eq!( + m2_repo_in(&e, &module), + Some(home.path().join("cache").join("m2")) + ); + + // Maven before 3.9 split the whole file on whitespace; the last + // occurrence wins either way. + write( + &config, + "-B -Dmaven.repo.local=first -Dmaven.repo.local=.repo -q\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")) + ); +} + +/// A config that does not set the property, or is not a file, changes +/// nothing. One that sets it to a value not used here (empty, or with a +/// placeholder nothing defines) still decides, as it does in Maven. +#[test] +fn an_unusable_maven_config_changes_nothing() { + let home = tempfile::tempdir().unwrap(); + let project = tempfile::tempdir().unwrap(); + let from_opts = tempfile::tempdir().unwrap(); + 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(); + + // Set, but not used here: Maven takes the config's value, so the + // repository MAVEN_OPTS names (which Maven does not reach) is not it. + for text in [ + "-Dmaven.repo.local=${some.build.property}/m2\n", + "-Dmaven.repo.local=\n", + ] { + write(&config, text); + assert_eq!(m2_repo_in(&e, project.path()), default, "{text:?}"); + } +} diff --git a/crates/socket-patch-core/src/crawlers/maven_selection.rs b/crates/socket-patch-core/src/crawlers/maven_selection.rs index 527482308..97f8bc5f8 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/patch/jar_members.rs b/crates/socket-patch-core/src/patch/jar_members.rs new file mode 100644 index 000000000..e46bc0fdb --- /dev/null +++ b/crates/socket-patch-core/src/patch/jar_members.rs @@ -0,0 +1,545 @@ +//! 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 +//! none of the limits trusts them: the count is the central directory's own, +//! and the byte limits are on what is actually inflated. +//! +//! * [`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_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}; + +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 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(reader: R, archive_len: u64) -> Result { + let zip = zip::ZipArchive::new(reader) + .map_err(|e| JarError::Unreadable(format!("not a readable zip archive ({e})")))?; + 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, JarError> { + if name.ends_with('/') { + return Ok(None); + } + let Some(index) = self.zip.index_for_name(name) else { + return Ok(None); + }; + let entry = self + .zip + .by_index(index) + .map_err(|e| JarError::Unreadable(format!("member `{name}` cannot be read ({e})")))?; + let size = entry.size(); + if size > self.left { + drop(entry); + return Err(self.over_budget()); + } + self.left -= size; + // The reader stops at `size`, so a stream longer than it declares + // costs no more than the budget just taken. + compute_git_sha256_from_std_reader(size, entry) + .map(Some) + .map_err(|e| JarError::Unreadable(format!("member `{name}` cannot be inflated ({e})"))) + } +} + +/// The content digests of a jar's members ([`Jar::content_digests`]). +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct Digests(BTreeMap, [u8; 32]>); + +impl Digests { + /// [`Jar::content_digests`] of the jar bytes `jar`. + pub(crate) fn of_bytes(jar: &[u8]) -> Result { + Jar::of_bytes(jar)?.content_digests() + } + + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + self.0.len() + } + + /// The digest of the member `name`. + #[cfg(test)] + pub(crate) fn get(&self, name: &str) -> Option<&[u8; 32]> { + self.0.get(name.as_bytes()) + } +} + +/// How one jar's members differ from another's ([`unpatched_difference`]): +/// member names, lossily decoded and sorted. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct Difference { + /// In the candidate only. + pub added: Vec, + /// In the original only. + pub missing: Vec, + /// In both, with other content. + pub changed: Vec, +} + +impl Difference { + pub(crate) fn is_empty(&self) -> bool { + self.added.is_empty() && self.missing.is_empty() && self.changed.is_empty() + } + + /// `2 added (`a/X.class`, …), 1 changed (`a/B.class`)`: each kind with + /// its count and its first names. + pub(crate) fn describe(&self) -> String { + const SHOWN: usize = 3; + [ + ("added", &self.added), + ("missing", &self.missing), + ("changed", &self.changed), + ] + .iter() + .filter(|(_, names)| !names.is_empty()) + .map(|(kind, names)| { + let mut shown: Vec = + names.iter().take(SHOWN).map(|n| format!("`{n}`")).collect(); + if names.len() > SHOWN { + shown.push("…".to_string()); + } + format!("{} {kind} ({})", names.len(), shown.join(", ")) + }) + .collect::>() + .join(", ") + } +} + +/// How `candidate` differs from `original` outside the members named in +/// `patched` (manifest keys, already normalized) and signature files: +/// empty when everything else a JVM would load is the same in both. +pub(crate) fn unpatched_difference( + original: &Digests, + candidate: &Digests, + patched: &[&str], +) -> Difference { + let compared = |name: &[u8]| { + !patched.iter().any(|p| p.as_bytes() == name) + && !std::str::from_utf8(name).is_ok_and(crate::vendor::jvm::is_signature) + }; + let text = |name: &[u8]| String::from_utf8_lossy(name).into_owned(); + let mut difference = Difference::default(); + for (name, digest) in original.0.iter().filter(|(name, _)| compared(name)) { + match candidate.0.get(name) { + None => difference.missing.push(text(name)), + Some(other) if other != digest => difference.changed.push(text(name)), + Some(_) => {} + } + } + difference.added = candidate + .0 + .keys() + .filter(|name| compared(name) && !original.0.contains_key(*name)) + .map(|name| text(name)) + .collect(); + difference +} + +#[cfg(test)] +pub(crate) mod testing { + use std::io::Write as _; + + /// A stored (uncompressed) jar of `members`, each `(name, bytes, unix + /// mode)`; a name ending in `/` is a directory entry. + pub(crate) fn jar_with_modes(members: &[(&str, &[u8], Option)]) -> Vec { + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes, mode) in members { + let mut opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Stored); + if let Some(mode) = mode { + opts = opts.unix_permissions(*mode); + } + if name.ends_with('/') { + out.add_directory(*name, opts).unwrap(); + } else if mode.is_some_and(|m| m & 0o170000 == 0o120000) { + out.add_symlink(*name, std::str::from_utf8(bytes).unwrap(), opts) + .unwrap(); + } else { + out.start_file(*name, opts).unwrap(); + out.write_all(bytes).unwrap(); + } + } + out.finish().unwrap().into_inner() + } + + /// [`jar_with_modes`] of plain files. + pub(crate) fn jar(members: &[(&str, &[u8])]) -> Vec { + let members: Vec<(&str, &[u8], Option)> = + members.iter().map(|(n, b)| (*n, *b, None)).collect(); + jar_with_modes(&members) + } + + /// A jar over both of the wheel reader's old limits: `entries` stored + /// members named `p/C.class` whose contents total `bytes`, then + /// `extra`. Each member's content is distinct. + pub(crate) fn big_jar(entries: usize, bytes: u64, extra: &[(&str, &[u8])]) -> Vec { + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Stored); + let each = (bytes / entries as u64) as usize; + let mut body = vec![0x5au8; each.max(16)]; + for i in 0..entries { + body[..8].copy_from_slice(&(i as u64).to_le_bytes()); + out.start_file(format!("p/C{i}.class"), opts).unwrap(); + out.write_all(&body).unwrap(); + } + for (name, content) in extra { + out.start_file(*name, opts).unwrap(); + out.write_all(content).unwrap(); + } + out.finish().unwrap().into_inner() + } +} + +#[cfg(test)] +mod tests { + use super::testing::{big_jar, jar, jar_with_modes}; + use super::*; + use crate::hash::git_sha256::compute_git_sha256_from_bytes; + + /// The wheel reader's limits, which a jar must be able to pass. + const OLD_ENTRIES: usize = 10_000; + const OLD_BYTES: u64 = 64 * 1024 * 1024; + + #[test] + fn a_jar_over_the_wheel_limits_is_read_member_by_member() { + let bytes = big_jar( + OLD_ENTRIES + 1, + OLD_BYTES + 1024 * 1024, + &[("a/B.class", b"code")], + ); + // The reader this module replaces for jars refuses it. + assert!(crate::vendor::verify::read_zip_bytes_to_map(&bytes).is_err()); + let digests = Digests::of_bytes(&bytes).unwrap(); + assert_eq!(digests.len(), OLD_ENTRIES + 2); + let expected: [u8; 32] = Sha256::digest(b"code").into(); + assert_eq!(digests.get("a/B.class"), Some(&expected)); + assert_eq!( + Jar::of_bytes(&bytes) + .unwrap() + .member_git_sha256("a/B.class") + .unwrap(), + Some(compute_git_sha256_from_bytes(b"code")) + ); + assert_eq!( + Jar::of_bytes(&bytes) + .unwrap() + .member_git_sha256("gone") + .unwrap(), + None + ); + } + + #[test] + fn the_entry_limit_names_the_count() { + let members: Vec<(String, &[u8])> = (0..=MAX_ENTRIES) + .map(|i| (format!("c/{i}"), b"".as_slice())) + .collect(); + let members: Vec<(&str, &[u8])> = members.iter().map(|(n, b)| (n.as_str(), *b)).collect(); + let err = Digests::of_bytes(&jar(&members)).unwrap_err(); + assert!(err.is_too_large(), "{err:?}"); + assert_eq!( + err.to_string(), + format!( + "it holds {} entries, over the limit of {MAX_ENTRIES}", + MAX_ENTRIES + 1 + ) + ); + } + + /// What is inflated is bounded, whatever the entry declares: a deflated + /// run of zeros is a few kilobytes of archive. + #[test] + fn the_inflate_limit_is_on_bytes_inflated_and_scales_with_the_archive() { + use std::io::Write as _; + let deflated = |size: u64| { + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + out.start_file("zeros.bin", opts).unwrap(); + std::io::copy(&mut std::io::repeat(0).take(size), &mut out).unwrap(); + out.start_file("a/B.class", opts).unwrap(); + out.write_all(b"code").unwrap(); + out.finish().unwrap().into_inner() + }; + // At the floor: read. + let at_floor = deflated(RATIO_FLOOR_BYTES - 4); + assert!((at_floor.len() as u64) < RATIO_FLOOR_BYTES / MAX_INFLATE_RATIO); + assert_eq!(Digests::of_bytes(&at_floor).unwrap().len(), 2); + // One byte more than a small archive may inflate to: refused, by + // both readers, with the ratio named. + let over = deflated(RATIO_FLOOR_BYTES + 1); + for err in [ + Digests::of_bytes(&over).unwrap_err(), + Jar::of_bytes(&over) + .unwrap() + .member_git_sha256("zeros.bin") + .unwrap_err(), + ] { + assert!(err.is_too_large(), "{err:?}"); + assert_eq!( + err.to_string(), + "it inflates to more than 64 MiB, over 100 times its own size (1 MiB) and the \ + 64 MiB every jar may use" + ); + } + assert_eq!(inflate_budget(0), RATIO_FLOOR_BYTES); + assert_eq!(inflate_budget(2 * 1024 * 1024), 200 * 1024 * 1024); + assert_eq!(inflate_budget(64 * 1024 * 1024), MAX_INFLATED_BYTES); + assert_eq!(inflate_budget(u64::MAX), MAX_INFLATED_BYTES); + } + + #[test] + fn a_file_that_is_not_a_zip_is_unreadable() { + let err = Digests::of_bytes(b"not a jar").unwrap_err(); + assert!(!err.is_too_large(), "{err:?}"); + } + + /// An entry with symlink mode bits is a member like any other: a JVM + /// loads its bytes by name. Directory entries are not members. + #[test] + fn every_loadable_entry_is_a_member_whatever_its_mode() { + let original = jar(&[("a/B.class", b"code"), ("META-INF/MANIFEST.MF", b"m")]); + let smuggled = jar_with_modes(&[ + ("a/", b"", None), + ("a/B.class", b"code", None), + ("META-INF/MANIFEST.MF", b"m", None), + ("a/Backdoor.class", b"evil", Some(0o120777)), + ]); + // The wheel reader does not see the entry at all. + assert!(!crate::vendor::verify::read_zip_bytes_to_map(&smuggled) + .unwrap() + .contains_key("a/Backdoor.class")); + let (original, smuggled) = ( + Digests::of_bytes(&original).unwrap(), + Digests::of_bytes(&smuggled).unwrap(), + ); + assert_eq!(smuggled.len(), 3, "the directory entry is not a member"); + let difference = unpatched_difference(&original, &smuggled, &[]); + assert_eq!(difference.added, ["a/Backdoor.class"]); + assert_eq!(difference.describe(), "1 added (`a/Backdoor.class`)"); + } + + #[test] + fn the_difference_leaves_out_patched_members_and_signature_files() { + let original = jar(&[ + ("META-INF/NOTICE.txt", b"pristine"), + ("META-INF/SIGNER.SF", b"sig"), + ("META-INF/SIGNER.RSA", b"sig"), + ("a/B.class", b"code"), + ("a/C.class", b"more"), + ("a/Gone.class", b"gone"), + ]); + let candidate = jar(&[ + ("META-INF/NOTICE.txt", b"patched"), + ("a/Added.class", b"added by the patch"), + ("a/B.class", b"code"), + ("a/C.class", b"changed"), + ("a/New.class", b"new"), + ]); + let (original, candidate) = ( + Digests::of_bytes(&original).unwrap(), + Digests::of_bytes(&candidate).unwrap(), + ); + let patched = ["META-INF/NOTICE.txt", "a/Added.class"]; + let difference = unpatched_difference(&original, &candidate, &patched); + assert_eq!( + difference, + Difference { + added: vec!["a/New.class".into()], + missing: vec!["a/Gone.class".into()], + changed: vec!["a/C.class".into()], + } + ); + assert_eq!( + difference.describe(), + "1 added (`a/New.class`), 1 missing (`a/Gone.class`), 1 changed (`a/C.class`)" + ); + assert!(unpatched_difference(&original, &original, &patched).is_empty()); + // Without the patch's names, its own members count. + assert_eq!( + unpatched_difference(&original, &candidate, &[]).changed, + ["META-INF/NOTICE.txt", "a/C.class"] + ); + } + + #[test] + fn a_long_difference_shows_its_first_names() { + let difference = Difference { + added: (0..5).map(|i| format!("a/{i}")).collect(), + ..Difference::default() + }; + assert_eq!(difference.describe(), "5 added (`a/0`, `a/1`, `a/2`, …)"); + } +} diff --git a/crates/socket-patch-core/src/patch/jvm_jar.rs b/crates/socket-patch-core/src/patch/jvm_jar.rs index f2d2f9097..dcc961ba3 100644 --- a/crates/socket-patch-core/src/patch/jvm_jar.rs +++ b/crates/socket-patch-core/src/patch/jvm_jar.rs @@ -11,13 +11,17 @@ //! would need a deterministic local repack, which nothing downstream could //! verify, so the whole jar is swapped for the patch service's build of it //! instead ([`apply_jar_swap`]): its patched members must hash to the -//! record's `afterHash`es and every other member must equal the installed -//! jar's. The original jar is kept at +//! record's `afterHash`es and every other member a JVM would load must +//! equal the installed jar's ([`super::jar_members`], which also sets the +//! size limits a jar is read within). The original jar is kept at //! `<.socket>/jvm-originals/.jar` — outside `blobs/`, so no blob //! cleanup ever removes it — and [`rollback_jar_swap`] restores it byte -//! for byte. A Gradle copy without a backup can still be restored from -//! upstream: its hash directory names the pristine jar's sha1, so a -//! download is accepted only when it hashes to exactly that. +//! for byte. A copy this project holds no backup of (another project or +//! an earlier workspace patched it) can still be restored from upstream: +//! a Gradle copy when the download hashes to its hash directory's name, +//! a `~/.m2` copy when the download matches the registry's checksum and +//! is the patched copy's jar with the record's members at their +//! `beforeHash`. //! //! Offline, or without the patch service, a member record writes nothing //! (`jvm_agent_service_required`): vendored or hosted mode carry it instead. @@ -32,6 +36,7 @@ use crate::patch::apply::{ apply_file_patch_at, files_in_order, normalize_file_path, ApplyResult, VerifyResult, VerifyStatus, }; +use crate::patch::jar_members::{unpatched_difference, Digests, JarError}; use crate::patch::rollback::{RollbackResult, VerifyRollbackResult, VerifyRollbackStatus}; use crate::patch::sidecars::{self, maven as maven_sidecars}; use crate::utils::purl::{parse_maven_purl, purl_qualifier}; @@ -40,6 +45,27 @@ use crate::vendor::VendorServiceConfig; /// Where original jars are kept, under the manifest's `.socket/` directory. pub const ORIGINALS_DIR: &str = "jvm-originals"; +/// A jar is past a limit [`super::jar_members`] reads jars within: the +/// service's jar refuses the whole swap, an installed one fails its copy. +pub const JAR_TOO_LARGE: &str = "jvm_jar_too_large"; +/// The service's jar is not the record's patch of an installed jar: it +/// lacks the `afterHash` members or cannot be read (the whole swap is +/// refused), or it differs from one copy outside the patched members (that +/// copy fails). +pub const SERVICE_JAR_MISMATCH: &str = "jvm_agent_service_jar_mismatch"; + +/// The reason code a copy's own failure starts with, when it is one a run +/// reports as a warning too ([`JAR_TOO_LARGE`], [`SERVICE_JAR_MISMATCH`]). +pub fn copy_failure_code(error: &str) -> Option<&'static str> { + [JAR_TOO_LARGE, SERVICE_JAR_MISMATCH] + .into_iter() + .find(|code| { + error + .strip_prefix(code) + .is_some_and(|rest| rest.starts_with(": ")) + }) +} + /// The two shapes of a Maven patch record (see the module docs). #[derive(Debug, Clone, PartialEq, Eq)] pub enum RecordShape { @@ -330,18 +356,9 @@ fn result_for(swap: &JarSwap<'_>, dir: &Path) -> ApplyResult { } } -/// The members of a jar other than `patched` and signature files, for the -/// "everything else is upstream's" comparison. -fn unpatched_members( - jar: &[u8], - patched: &HashMap, -) -> Result>, String> { - let keys: Vec<&str> = patched.keys().map(|k| normalize_file_path(k)).collect(); - let mut members = crate::vendor::verify::read_zip_bytes_to_map(jar)?; - members.retain(|name, _| { - !keys.contains(&name.as_str()) && !crate::vendor::jvm::is_signature(name) - }); - Ok(members) +/// The member names a record patches, as a jar spells them. +fn patched_names(files: &HashMap) -> Vec<&str> { + files.keys().map(|k| normalize_file_path(k)).collect() } fn sha256_hex(bytes: &[u8]) -> String { @@ -464,11 +481,25 @@ pub async fn apply_jar_swap( !matches!(v.status, VerifyStatus::Ready | VerifyStatus::AlreadyPatched) }) .expect("a NotFound or HashMismatch member exists"); - result.error = Some(format!( + let mut error = format!( "Cannot apply patch: {} - {}", bad.file, bad.message.clone().unwrap_or_default() - )); + ); + if bad.status == VerifyStatus::HashMismatch { + // Not the original and not this patch: most often an + // earlier revision of the patch, applied from another + // project or workspace whose backup is not here. + error.push_str(&format!( + ". {} holds neither the original member nor this patch's: another \ + revision of the patch may have been applied from another project or \ + workspace, or the jar was rebuilt. Roll that patch back where it was \ + applied, or delete {} so the build downloads the jar again, then apply.", + dir.join(swap.jar_leaf).display(), + dir.display() + )); + } + result.error = Some(error); } } results.push(result); @@ -478,30 +509,58 @@ pub async fn apply_jar_swap( } let jar = service_jar(service, swap.uuid).await?; + // Every member's content, read within the jar limits before anything + // else inflates the download. + let service_members = Digests::of_bytes(&jar).map_err(|e| match e { + JarError::TooLarge(why) => SwapRefusal::new( + JAR_TOO_LARGE, + format!( + "the patch service's build of {} cannot be checked against the installed jar: \ + {why}. Nothing was written. `--mode hosted` does not read the jar.", + swap.jar_leaf + ), + ), + JarError::Unreadable(why) => SwapRefusal::new( + SERVICE_JAR_MISMATCH, + format!("the patch service's jar cannot be read: {why}"), + ), + })?; + // After the bounded pass: this one inflates only what that one did. if !crate::vendor::common::zip_bytes_match_after_hashes(&jar, swap.files) { return Err(SwapRefusal::new( - "jvm_agent_service_jar_mismatch", + SERVICE_JAR_MISMATCH, "the patch service's jar does not carry the record's patched members", )); } - let service_rest = unpatched_members(&jar, swap.files).map_err(|e| { - SwapRefusal::new( - "jvm_agent_service_jar_mismatch", - format!("the patch service's jar is unreadable: {e}"), - ) - })?; // Per copy: everything the patch does not touch must be upstream's. + let patched = patched_names(swap.files); pending.retain(|(i, original)| { - let same = - unpatched_members(original, swap.files).is_ok_and(|members| members == service_rest); - if !same { - results[*i].error = Some(format!( - "Cannot apply patch: {} - the patch service's jar differs from the installed jar \ - outside the patched members", - swap.jar_leaf - )); - } - same + let path = Path::new(&results[*i].package_path).join(swap.jar_leaf); + let failure = match Digests::of_bytes(original) { + Ok(members) => { + let difference = unpatched_difference(&members, &service_members, &patched); + if difference.is_empty() { + return true; + } + format!( + "{SERVICE_JAR_MISMATCH}: the patch service's jar differs from {} outside the \ + patched members: {}. The two are not the same jar apart from the patch, so \ + that copy was left as it is.", + path.display(), + difference.describe() + ) + } + Err(JarError::TooLarge(why)) => format!( + "{JAR_TOO_LARGE}: {} cannot be checked against the patch service's jar: {why}. \ + It was left as it is. `--mode hosted` does not read the jar.", + path.display() + ), + Err(JarError::Unreadable(why)) => { + format!("Cannot apply patch: {} - {why}", path.display()) + } + }; + results[*i].error = Some(failure); + false }); if swap.dry_run { for (i, _) in &pending { @@ -621,7 +680,7 @@ pub struct JarRestore<'a> { /// member equal to `current`'s, and — for a Gradle hash dir — hashing to the /// directory's name. Backups are tried in name order. async fn find_backup(restore: &JarRestore<'_>, dir: &Path, current: &[u8]) -> Option> { - let rest = unpatched_members(current, restore.files).ok()?; + let current = Digests::of_bytes(current).ok()?; let gradle_hash = maven_sidecars::is_gradle_hash_dir(dir) .then(|| dir.file_name()?.to_str().map(str::to_string)) .flatten(); @@ -642,23 +701,32 @@ async fn find_backup(restore: &JarRestore<'_>, dir: &Path, current: &[u8]) -> Op continue; } } - // Each member at its `beforeHash`; a member the patch adds (empty - // `beforeHash`) must be absent from the original. - let originals = verify_member_bytes(&bytes, restore.files); - if originals.iter().all(|v| { - v.status == VerifyStatus::Ready - && restore - .files - .get(&v.file) - .is_some_and(|i| v.current_hash.as_deref().unwrap_or("") == i.before_hash) - }) && unpatched_members(&bytes, restore.files).is_ok_and(|m| m == rest) - { + if is_original_of(&bytes, ¤t, restore.files) { return Some(bytes); } } None } +/// Whether the jar `candidate` is the original of a patched copy whose +/// members are `patched_copy`: each record member at its `beforeHash` (a +/// member the patch adds, with an empty `beforeHash`, absent), and every +/// other member the patched copy's. +fn is_original_of( + candidate: &[u8], + patched_copy: &Digests, + files: &HashMap, +) -> bool { + verify_member_bytes(candidate, files).iter().all(|v| { + v.status == VerifyStatus::Ready + && files + .get(&v.file) + .is_some_and(|i| v.current_hash.as_deref().unwrap_or("") == i.before_hash) + }) && Digests::of_bytes(candidate).is_ok_and(|members| { + unpatched_difference(&members, patched_copy, &patched_names(files)).is_empty() + }) +} + /// The upstream jar of a Gradle copy, accepted only when it hashes to the /// copy's hash-directory name (the sha1 Gradle verified when it downloaded /// the pristine jar). @@ -679,6 +747,44 @@ async fn upstream_for_gradle_copy(purl: &str, jar_leaf: &str, dir: &Path) -> Opt gradle_cache::hash_eq(hash, &sha1_hex(&bytes)).then_some(bytes) } +/// The upstream jar of a `~/.m2` copy, which no hash directory vouches +/// for: a registry download is accepted only when it matches the checksum +/// the registry publishes beside it (`.sha512`, else `.sha1`) and is the +/// original of the patched copy `current` ([`is_original_of`]: the record's +/// members at their `beforeHash`, every other member the copy's own). The +/// `.sha1` Maven wrote beside the jar cannot vouch for it: the swap rewrote +/// that file for the patched jar. `Err` says what was missing. +async fn upstream_for_m2_copy(restore: &JarRestore<'_>, current: &[u8]) -> Result, String> { + let (group, artifact, version) = + parse_maven_purl(restore.purl).ok_or("its purl names no Maven coordinates")?; + let bytes = crate::vendor::maven_repo::verified_registry_file( + &group, + &artifact, + &version, + restore.jar_leaf, + ) + .await?; + let current = Digests::of_bytes(current).map_err(|e| format!("the copy {e}"))?; + if !is_original_of(&bytes, ¤t, restore.files) { + return Err(format!( + "the registry's {} is not the jar this copy was patched from", + restore.jar_leaf + )); + } + Ok(bytes) +} + +/// What to do about a copy with no original to restore: said with every +/// [`rollback_jar_swap`] failure for want of one. +fn recover_hint(dir: &Path) -> String { + format!( + "To recover, run the rollback from the project that applied the patch (its \ + .socket/{ORIGINALS_DIR} holds the original), or delete {} so the build downloads the \ + jar again.", + dir.display() + ) +} + fn rollback_result(purl: &str, dir: &Path) -> RollbackResult { RollbackResult { package_key: purl.to_string(), @@ -711,11 +817,12 @@ fn rollback_verify(results: &[VerifyResult]) -> Vec { } /// Restore the original jar of every copy in `copies` that holds the -/// patched members: from its [`ORIGINALS_DIR`] backup, else — for a Gradle -/// copy, online — from upstream when the download hashes to the copy's hash -/// directory. A copy with neither fails with `jvm_jar_backup_missing` and -/// is left as it is; so is a copy whose members match neither side. A copy -/// already original is a no-op. One result per copy. +/// patched members: from its [`ORIGINALS_DIR`] backup, else, online, from +/// upstream: a Gradle copy when the download hashes to the copy's hash +/// directory, a `~/.m2` copy when it passes [`upstream_for_m2_copy`]. A +/// copy with neither fails with `jvm_jar_backup_missing`, says why and how +/// to recover, and is left as it is; so is a copy whose members match +/// neither side. A copy already original is a no-op. One result per copy. pub async fn rollback_jar_swap( restore: &JarRestore<'_>, copies: &[PathBuf], @@ -755,28 +862,28 @@ pub async fn rollback_jar_swap( continue; } let gradle = maven_sidecars::is_gradle_hash_dir(dir); + // Why upstream could not stand in for a missing backup. let original = match find_backup(restore, dir, ¤t).await { - Some(bytes) => Some(bytes), - None if gradle && !restore.offline => { - upstream_for_gradle_copy(restore.purl, restore.jar_leaf, dir).await - } - None => None, + Some(bytes) => Ok(bytes), + None if restore.offline => Err("--offline prevents downloading it again".to_string()), + None if gradle => upstream_for_gradle_copy(restore.purl, restore.jar_leaf, dir) + .await + .ok_or_else(|| "no upstream download matches its hash directory".to_string()), + None => upstream_for_m2_copy(restore, ¤t).await, }; - let Some(original) = original else { - result.error = Some(format!( - "jvm_jar_backup_missing: no original of {} under {} (and {})", - path.display(), - restore.socket_dir.join(ORIGINALS_DIR).display(), - if gradle && restore.offline { - "--offline prevents re-downloading it" - } else if gradle { - "no upstream download matches its hash directory" - } else { - "a ~/.m2 copy cannot be re-downloaded and verified" - } - )); - out.push(result); - continue; + let original = match original { + Ok(bytes) => bytes, + Err(why) => { + result.error = Some(format!( + "jvm_jar_backup_missing: {} holds this patch, but {} has no backup of the \ + original (another project or an earlier workspace applied it), and {why}. {}", + path.display(), + restore.socket_dir.join(ORIGINALS_DIR).display(), + recover_hint(dir) + )); + out.push(result); + continue; + } }; if restore.dry_run { result.success = true; @@ -1195,19 +1302,32 @@ mod tests { ("a/Backdoor.class", b"evil"), ]); let wrong_after = jar(&[("META-INF/NOTICE.txt", b"other"), ("a/B.class", b"code")]); - // (served, sri over, whole-swap refusal code or None for a per-copy error) - let cases: Vec<(Vec, Vec, Option<&str>)> = vec![ + // An added class under symlink mode bits: a JVM loads it by name + // whatever its mode, so it counts like any other member. + let smuggled = crate::patch::jar_members::testing::jar_with_modes(&[ + ("META-INF/NOTICE.txt", b"patched", None), + ("a/B.class", b"code", None), + ("a/Backdoor.class", b"evil", Some(0o120777)), + ]); + // (served, sri over, whole-swap refusal code or the difference a + // per-copy failure names) + let cases: Vec<(Vec, Vec, Result<&str, &str>)> = vec![ ( wrong_after.clone(), wrong_after, - Some("jvm_agent_service_jar_mismatch"), + Ok("jvm_agent_service_jar_mismatch"), + ), + (altered.clone(), altered, Err("1 changed (`a/B.class`)")), + (extra.clone(), extra, Err("1 added (`a/Backdoor.class`)")), + ( + smuggled.clone(), + smuggled, + Err("1 added (`a/Backdoor.class`)"), ), - (altered.clone(), altered, None), - (extra.clone(), extra, None), ( patched_jar(), b"not the served bytes".to_vec(), - Some("jvm_agent_service_integrity"), + Ok("jvm_agent_service_integrity"), ), ]; for (served, sri_of, refusal) in cases { @@ -1221,18 +1341,20 @@ mod tests { let out = apply_jar_swap(&swap(&files, &socket, false), &[copy.clone()], Some(&cfg)).await; match refusal { - Some(code) => assert_eq!(out.unwrap_err().code, code), - None => { + Ok(code) => assert_eq!(out.unwrap_err().code, code), + Err(difference) => { let out = out.unwrap(); assert!(!out[0].success); + let error = out[0].error.as_deref().unwrap(); + // The copy's failure carries the contract's code and + // says which members differ. + assert_eq!(copy_failure_code(error), Some(SERVICE_JAR_MISMATCH)); assert!( - out[0] - .error - .as_deref() - .unwrap() - .contains("differs from the installed jar"), - "{:?}", - out[0].error + error.starts_with( + "jvm_agent_service_jar_mismatch: the patch service's jar differs from " + ) && error.contains(&format!("outside the patched members: {difference}.")) + && error.contains("lib-1.0.jar"), + "{error}" ); } } @@ -1283,6 +1405,286 @@ mod tests { assert_eq!(std::fs::read(copy.join("lib-1.0.jar")).unwrap(), original); } + fn restore<'a>( + files: &'a HashMap, + socket: &'a Path, + offline: bool, + ) -> JarRestore<'a> { + JarRestore { + purl: PURL, + jar_leaf: "lib-1.0.jar", + files, + socket_dir: socket, + dry_run: false, + offline, + } + } + + /// A jar over both limits of the wheel reader the swap used to compare + /// through (10,000 entries, 64 MiB inflated) is swapped and rolled back + /// like any other. It used to be refused as "the patch service's jar is + /// unreadable". + #[tokio::test] + async fn a_jar_over_the_wheel_reader_limits_swaps_and_rolls_back() { + use crate::patch::jar_members::testing::big_jar; + const ENTRIES: usize = 10_001; + const BYTES: u64 = 65 * 1024 * 1024; + let original = big_jar(ENTRIES, BYTES, &[("META-INF/NOTICE.txt", b"pristine")]); + let service = big_jar(ENTRIES, BYTES, &[("META-INF/NOTICE.txt", b"patched")]); + assert!(crate::vendor::verify::read_zip_bytes_to_map(&service).is_err()); + let (_server, cfg) = mock_service(&service, &service).await; + + let d = tempfile::tempdir().unwrap(); + let socket = d.path().join(".socket"); + let copy = d.path().join("m2/com/example/lib/1.0"); + std::fs::create_dir_all(©).unwrap(); + std::fs::write(copy.join("lib-1.0.jar"), &original).unwrap(); + let files = record(); + let out = apply_jar_swap(&swap(&files, &socket, false), &[copy.clone()], Some(&cfg)) + .await + .unwrap(); + assert!(out[0].success, "{:?}", out[0].error); + assert!(std::fs::read(copy.join("lib-1.0.jar")).unwrap() == service); + + let back = rollback_jar_swap(&restore(&files, &socket, true), &[copy.clone()]).await; + assert!(back[0].success, "{:?}", back[0].error); + assert!(std::fs::read(copy.join("lib-1.0.jar")).unwrap() == original); + } + + /// A jar past the jar limits says which limit, and whose jar: the + /// service's refuses the whole swap, an installed one fails its copy. + /// Nothing is written either way. + #[tokio::test] + async fn a_jar_past_the_jar_limits_names_the_limit() { + // 65 MiB of zeros deflates to a few kilobytes: over the 64 MiB a + // small archive may inflate to. + let bomb = |notice: &[u8], with_bomb: bool| { + use std::io::Read as _; + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + out.start_file("META-INF/NOTICE.txt", opts).unwrap(); + out.write_all(notice).unwrap(); + out.start_file("a/B.class", opts).unwrap(); + out.write_all(b"code").unwrap(); + if with_bomb { + out.start_file("a/zeros.bin", opts).unwrap(); + std::io::copy(&mut std::io::repeat(0).take(65 * 1024 * 1024), &mut out).unwrap(); + } + out.finish().unwrap().into_inner() + }; + let limit = "it inflates to more than 64 MiB, over 100 times its own size (1 MiB) and \ + the 64 MiB every jar may use"; + let files = record(); + // (service jar, installed jar, whole-swap refusal?) + for (service, installed, whole) in [ + (bomb(b"patched", true), bomb(b"pristine", true), true), + (bomb(b"patched", false), bomb(b"pristine", true), false), + ] { + let (_server, cfg) = mock_service(&service, &service).await; + let d = tempfile::tempdir().unwrap(); + let socket = d.path().join(".socket"); + let copy = d.path().join("m2/com/example/lib/1.0"); + std::fs::create_dir_all(©).unwrap(); + std::fs::write(copy.join("lib-1.0.jar"), &installed).unwrap(); + let out = + apply_jar_swap(&swap(&files, &socket, false), &[copy.clone()], Some(&cfg)).await; + if whole { + let refusal = out.unwrap_err(); + assert_eq!(refusal.code, JAR_TOO_LARGE); + assert!( + refusal.message.starts_with( + "the patch service's build of lib-1.0.jar cannot be checked against the \ + installed jar: it inflates" + ) && refusal.message.contains(limit), + "{}", + refusal.message + ); + } else { + let out = out.unwrap(); + let error = out[0].error.as_deref().unwrap(); + assert!(!out[0].success); + assert_eq!(copy_failure_code(error), Some(JAR_TOO_LARGE)); + assert!( + error.contains("lib-1.0.jar cannot be checked against the patch service's jar") + && error.contains(limit), + "{error}" + ); + } + assert!(std::fs::read(copy.join("lib-1.0.jar")).unwrap() == installed); + assert!(!socket.exists(), "no backup may be written"); + } + } + + /// The reason codes a copy's failure may start with, and nothing else. + #[test] + fn copy_failure_code_reads_only_a_leading_code() { + assert_eq!( + copy_failure_code("jvm_jar_too_large: x.jar: it holds 5 entries"), + Some(JAR_TOO_LARGE) + ); + assert_eq!( + copy_failure_code("jvm_agent_service_jar_mismatch: the patch service's jar differs"), + Some(SERVICE_JAR_MISMATCH) + ); + for other in [ + "Cannot apply patch: x - jvm_jar_too_large: y", + "jvm_jar_too_large", + "jvm_jar_too_larger: x", + "", + ] { + assert_eq!(copy_failure_code(other), None, "{other}"); + } + } + + /// A registry serving `jar` at lib-1.0.jar with the `.sha1` of `summed` + /// (`None`: it publishes no checksum). + async fn registry(jar: &[u8], summed: Option<&[u8]>) -> wiremock::MockServer { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/com/example/lib/1.0/lib-1.0.jar")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(jar.to_vec())) + .mount(&server) + .await; + if let Some(summed) = summed { + Mock::given(method("GET")) + .and(path("/com/example/lib/1.0/lib-1.0.jar.sha1")) + .respond_with(ResponseTemplate::new(200).set_body_string(sha1_hex(summed))) + .mount(&server) + .await; + } + server + } + + /// A `~/.m2` copy another project (or an earlier workspace) patched has + /// no backup under this project's `.socket/`. Its rollback downloads the + /// original, and takes it only when it matches the registry's checksum + /// and is the jar the copy was patched from. The copy and its `.sha1` + /// come back byte for byte. + #[tokio::test] + #[serial_test::serial] + async fn an_m2_copy_patched_elsewhere_is_restored_from_verified_upstream() { + let d = tempfile::tempdir().unwrap(); + let socket = d.path().join("second-project/.socket"); + let copy = d.path().join("m2/com/example/lib/1.0"); + std::fs::create_dir_all(©).unwrap(); + let (original, patched) = (pristine_jar(), patched_jar()); + // What the first project's apply left: the service jar and a + // `.sha1` that describes it. + let patch_copy = || { + std::fs::write(copy.join("lib-1.0.jar"), &patched).unwrap(); + std::fs::write(copy.join("lib-1.0.jar.sha1"), sha1_hex(&patched)).unwrap(); + }; + let files = record(); + + patch_copy(); + let server = registry(&original, Some(&original)).await; + let _registry = EnvGuard::set("SOCKET_MAVEN_REGISTRY", server.uri()); + let back = rollback_jar_swap(&restore(&files, &socket, false), &[copy.clone()]).await; + assert!(back[0].success, "{:?}", back[0].error); + assert_eq!(back[0].files_rolled_back, ["META-INF/NOTICE.txt"]); + assert_eq!(std::fs::read(copy.join("lib-1.0.jar")).unwrap(), original); + assert_eq!( + std::fs::read_to_string(copy.join("lib-1.0.jar.sha1")).unwrap(), + sha1_hex(&original) + ); + assert!(!socket.exists(), "a rollback writes no backup"); + drop(_registry); + + // Anything less leaves the copy as it is and says what to do. + let other_base = jar(&[ + ("META-INF/NOTICE.txt", b"pristine"), + ("a/B.class", b"other"), + ]); + let cases: Vec<(wiremock::MockServer, bool, &str)> = vec![ + ( + registry(&original, Some(b"some other bytes")).await, + false, + "the download does not match the registry's checksum", + ), + ( + registry(&original, None).await, + false, + "the registry publishes no checksum for it", + ), + ( + registry(&other_base, Some(&other_base)).await, + false, + "the registry's lib-1.0.jar is not the jar this copy was patched from", + ), + ( + // The patched jar itself is not its own original. + registry(&patched, Some(&patched)).await, + false, + "the registry's lib-1.0.jar is not the jar this copy was patched from", + ), + ( + wiremock::MockServer::start().await, + false, + "the registry did not serve it", + ), + ( + registry(&original, Some(&original)).await, + true, + "--offline prevents downloading it again", + ), + ]; + for (server, offline, why) in cases { + patch_copy(); + let _registry = EnvGuard::set("SOCKET_MAVEN_REGISTRY", server.uri()); + let back = rollback_jar_swap(&restore(&files, &socket, offline), &[copy.clone()]).await; + let error = back[0].error.as_deref().unwrap(); + assert!(!back[0].success, "{why}"); + assert!( + error.starts_with("jvm_jar_backup_missing: ") + && error.contains("has no backup of the original (another project or an earlier workspace applied it)") + && error.contains(why) + && error.contains("To recover, run the rollback from the project that applied the patch") + && error.contains(&format!("or delete {} so the build downloads the jar again", copy.display())), + "{why}: {error}" + ); + assert_eq!(std::fs::read(copy.join("lib-1.0.jar")).unwrap(), patched); + } + } + + /// A copy that holds another revision of the patch (applied from another + /// project) is neither side of this record: the apply fails that copy + /// and says what the bytes may be and how to get back to the original. + #[tokio::test] + async fn a_copy_holding_another_revision_says_how_to_recover() { + let d = tempfile::tempdir().unwrap(); + let copy = d.path().join("m2/com/example/lib/1.0"); + std::fs::create_dir_all(©).unwrap(); + let other_revision = jar(&[ + ("META-INF/NOTICE.txt", b"an earlier revision"), + ("a/B.class", b"code"), + ]); + std::fs::write(copy.join("lib-1.0.jar"), &other_revision).unwrap(); + let files = record(); + let out = apply_jar_swap( + &swap(&files, &d.path().join(".socket"), false), + &[copy.clone()], + None, + ) + .await + .unwrap(); + let error = out[0].error.as_deref().unwrap(); + assert!(!out[0].success); + assert!( + error.starts_with("Cannot apply patch: META-INF/NOTICE.txt - Jar member hash does not match expected value. ") + && error.contains("holds neither the original member nor this patch's") + && error.contains("another revision of the patch may have been applied from another project or workspace") + && error.contains(&format!("or delete {} so the build downloads the jar again, then apply", copy.display())), + "{error}" + ); + assert_eq!( + std::fs::read(copy.join("lib-1.0.jar")).unwrap(), + other_revision + ); + } + /// A large deflated member is verified by streaming it through the /// shared zip-member hasher: the verdict matches the buffered hash for /// both record states, and an absent member keeps its own status. diff --git a/crates/socket-patch-core/src/patch/mod.rs b/crates/socket-patch-core/src/patch/mod.rs index 548816f0a..0bc36ee26 100644 --- a/crates/socket-patch-core/src/patch/mod.rs +++ b/crates/socket-patch-core/src/patch/mod.rs @@ -6,6 +6,7 @@ pub(crate) mod file_hash; pub mod gem_ext; pub mod gem_refresh; pub(crate) mod gem_source; +pub(crate) mod jar_members; pub mod jvm_jar; pub(crate) mod npm_bin; pub mod package; diff --git a/crates/socket-patch-core/src/vendor/jvm/gradle.rs b/crates/socket-patch-core/src/vendor/jvm/gradle.rs index 1b7413425..56f1f65d4 100644 --- a/crates/socket-patch-core/src/vendor/jvm/gradle.rs +++ b/crates/socket-patch-core/src/vendor/jvm/gradle.rs @@ -189,17 +189,19 @@ pub fn committed_patched(read: ReadFn<'_>, c: &Coords<'_>) -> Vec { /// holds with other content than the patched `jar`: a build consuming that /// classifier stays unpatched (#533). fn unpatched_copy(bytes: &[u8], jar: &[u8], patched: &[String]) -> Option { - use crate::vendor::verify::read_zip_bytes_to_map; - let members = read_zip_bytes_to_map(bytes).ok()?; - let patched_jar = read_zip_bytes_to_map(jar).ok()?; + // Only the patched members are inflated, within the jar limits: the + // wheel-sized reader this went through gave up on a large jar, which + // then passed unchecked. + use crate::patch::jar_members::Jar; + let mut copy = Jar::of_bytes(bytes).ok()?; + let mut patched_jar = Jar::of_bytes(jar).ok()?; let mut names: Vec<&String> = patched.iter().collect(); names.sort(); names .into_iter() - .find(|name| { - members - .get(*name) - .is_some_and(|copy| patched_jar.get(*name) != Some(copy)) + .find(|name| match copy.member_git_sha256(name) { + Ok(Some(held)) => patched_jar.member_git_sha256(name).ok().flatten() != Some(held), + _ => false, }) .cloned() } diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs b/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs index a5baade50..1458f00da 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs @@ -4383,6 +4383,11 @@ const PINNED_REFERENCES: &[(&str, &str, &str)] = &[ "fetch_registry_bytes", "fetch_registry_bytes(url, MAX_POM_BYTES as u64).await", ), + ( + "vendor/maven_repo.rs", + "fetch_registry_bytes", + "let upstream = fetch_registry_bytes(&url, super::registry_fetch::MAX_DOWNLOAD_BYTES).await;", + ), ( "vendor/lock_inventory/mod.rs", "recover_lock_entry", diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index 935e85d5b..20bff82a9 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -1059,14 +1059,33 @@ async fn vendor_maven_jvm( }; let online = service.is_some_and(|s| !s.offline); - if online && was_committed { + // Everything the patch does not touch must be upstream's, checked + // against the registry-verified upstream jar before anything is + // written: on a first vendoring (always online: the jar comes from the + // service) as on an online re-run over a committed tree. A service jar + // built from another base, or one that adds or drops a class, is never + // committed and wired. + if online { let upstream = match acquire_jvm_artifact(&local, &gav, None, "jar", service).await { Ok(bytes) => bytes, - Err(e) => return refused("vendor_jvm_upstream_unavailable", e), + // A cached copy the registry's checksum does not vouch for (the + // jar agent mode patched in `~/.m2`, say) is no baseline: the + // registry's own jar is, held to the same checksum. + Err(_) => { + match acquire_jvm_artifact(&LocalSources::none(), &gav, None, "jar", service).await + { + Ok(bytes) => bytes, + Err(e) => return refused("vendor_jvm_upstream_unavailable", e), + } + } }; - if let Err(e) = verify_unpatched_jar_members(&upstream, &jar_bytes, record) { - return refused("vendor_prebuilt_integrity_mismatch", e); + if let Err((code, detail)) = + verify_unpatched_jar_members(&upstream, &jar_bytes, record, was_committed) + { + return refused(code, detail); } + } + if online && was_committed { pom_bytes = match acquire_jvm_artifact(&local, &gav, None, "pom", service).await { Ok(bytes) => bytes, Err(e) => return refused("vendor_jvm_upstream_unavailable", e), @@ -1461,23 +1480,51 @@ async fn acquire_classifier( Ok(Some(bytes)) } -/// Verify upstream cache/registry bytes against checksums fetched independently over TLS. +/// The patched jar (the service's on a first vendoring, the committed one +/// on a re-run) must be the verified upstream jar outside the record's +/// members and signature files: every other member a JVM would load, the +/// same in both ([`crate::patch::jar_members`], whose limits also bound +/// the read). `Err` is the refusal's `(code, detail)`. fn verify_unpatched_jar_members( upstream: &[u8], patched: &[u8], record: &PatchRecord, -) -> Result<(), String> { - let mut original = super::verify::read_zip_bytes_to_map(upstream)?; - let mut committed = super::verify::read_zip_bytes_to_map(patched)?; - let retain = |name: &String, _: &mut Vec| { - !record.files.contains_key(name) && !super::jvm::is_signature(name) + committed: bool, +) -> Result<(), (&'static str, String)> { + use crate::patch::jar_members::{unpatched_difference, Digests, JarError}; + let whose = if committed { + "the committed jar" + } else { + "the patch service's jar" }; - original.retain(retain); - committed.retain(retain); - if original != committed { - return Err( - "committed jar's unpatched members differ from the verified upstream jar".into(), - ); + let read = |jar: &[u8], whose: &str| { + Digests::of_bytes(jar).map_err(|e| match e { + JarError::TooLarge(why) => ( + super::verify::ARTIFACT_TOO_LARGE, + format!("{whose} cannot be checked: {why}"), + ), + JarError::Unreadable(why) => ( + "vendor_prebuilt_integrity_mismatch", + format!("{whose} cannot be read: {why}"), + ), + }) + }; + let original = read(upstream, "the upstream jar")?; + let candidate = read(patched, whose)?; + let names: Vec<&str> = record + .files + .keys() + .map(|k| crate::patch::apply::normalize_file_path(k)) + .collect(); + let difference = unpatched_difference(&original, &candidate, &names); + if !difference.is_empty() { + return Err(( + "vendor_prebuilt_integrity_mismatch", + format!( + "{whose} differs from the verified upstream jar outside the patched members: {}", + difference.describe() + ), + )); } Ok(()) } @@ -1521,7 +1568,6 @@ async fn check_jvm_upstream( if service.is_none_or(|s| s.offline) { return Ok(UpstreamCheck::Verified); } - use sha2::Digest; // `tests.jar` is the `tests` classifier's jar. let tail = match ext.split_once('.') { Some((classifier, ext)) => format!("-{classifier}.{ext}"), @@ -1532,6 +1578,17 @@ async fn check_jvm_upstream( layout::registry_base(), layout::version_dir(g, a, v) ); + check_published_checksum(bytes, &url, &format!("{g}:{a}:{v}{tail}")).await +} + +/// `bytes` against the checksum the registry publishes beside the file at +/// `url` (`.sha512`, else `.sha1`). `what` names the file in the mismatch. +async fn check_published_checksum( + bytes: &[u8], + url: &str, + what: &str, +) -> Result { + use sha2::Digest; let (checksum, actual) = match fetch_pom_bytes(&format!("{url}.sha512")).await { Ok(sum) => (sum, hex::encode(sha2::Sha512::digest(bytes))), Err(_) => match fetch_pom_bytes(&format!("{url}.sha1")).await { @@ -1545,11 +1602,38 @@ async fn check_jvm_upstream( .next() .ok_or("upstream checksum is empty")?; if !expected.eq_ignore_ascii_case(&actual) { - return Err(format!("upstream checksum mismatch for {g}:{a}:{v}{tail}")); + return Err(format!("upstream checksum mismatch for {what}")); } Ok(UpstreamCheck::Verified) } +/// The file `leaf` of `g:a:v` as the registry serves it, taken only when +/// its bytes match the checksum the registry publishes beside it. `Err` +/// says which of the two was missing. +pub(crate) async fn verified_registry_file( + g: &str, + a: &str, + v: &str, + leaf: &str, +) -> Result, String> { + let url = format!( + "{}/{}/{leaf}", + layout::registry_base(), + layout::version_dir(g, a, v) + ); + let upstream = fetch_registry_bytes(&url, super::registry_fetch::MAX_DOWNLOAD_BYTES).await; + let bytes = upstream.map_err(|e| format!("the registry did not serve it ({e})"))?; + match check_published_checksum(&bytes, &url, &format!("{g}:{a}:{v} ({leaf})")).await { + Ok(UpstreamCheck::Verified) => Ok(bytes), + Ok(UpstreamCheck::Unpublished(why)) => { + Err(format!("the registry publishes no checksum for it ({why})")) + } + Err(why) => Err(format!( + "the download does not match the registry's checksum ({why})" + )), + } +} + /// One upstream file of `gav` (`classifier`, `ext`): a local copy (see /// [`LocalSources::find`]), else a registry download when the service is /// online; online, the bytes are checked against the registry's checksum @@ -4060,6 +4144,280 @@ mod tests { assert!(detail.contains("patch service request failed"), "{detail}"); } + /// A jar over the limits of the reader jars used to share with Python + /// wheels (10,000 entries, 64 MiB inflated) vendors, verifies (what + /// `vex` and `vendor --check` ask), passes an online re-run's comparison + /// with upstream, and is repaired. + #[tokio::test] + #[serial_test::serial] + async fn a_jar_over_the_wheel_reader_limits_vendors_verifies_and_repairs() { + use crate::patch::jar_members::testing::big_jar; + use crate::vendor::{check_vendored_artifact, ArtifactHealth}; + + let (dir, blobs, installed, record) = reactor_fixture(true).await; + let root = dir.path(); + let upstream = big_jar(10_001, 65 * 1024 * 1024, &[(JAR_FILE, PRISTINE)]); + assert!(crate::vendor::verify::read_zip_bytes_to_map(&upstream).is_err()); + tokio::fs::write(installed.join("commons-text-1.10.0.jar"), &upstream) + .await + .unwrap(); + let sources = PatchSources::blobs_only(&blobs); + let service = crate::vendor::test_support::service_fixture::Fixture::new( + PURL, + installed.as_path().into(), + &record, + &sources, + ) + .await; + + let (result, entry, _) = + unwrap_done(run_jvm(root, &blobs, &installed, &record, Some(&service.cfg)).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("ledger entry"); + crate::vendor::test_support::persist(root, PURL, entry.clone()).await; + let jar = root.join(&entry.artifact.path); + let committed = std::fs::read(&jar).unwrap(); + assert_eq!( + crate::patch::jar_members::Digests::of_bytes(&committed) + .unwrap() + .len(), + 10_002 + ); + + assert_eq!( + crate::vendor::verify::verify_vendored_patch_record(root, &entry, &record).await, + Ok(()) + ); + assert_eq!( + check_vendored_artifact(root, &entry, &record).await, + ArtifactHealth::Healthy + ); + + // Online, the committed jar is held to upstream outside the patch. + let (again, _, _) = + unwrap_done(run_jvm(root, &blobs, &installed, &record, Some(&service.cfg)).await); + assert!(again.success, "{:?}", again.error); + + let snapshot = crate::vendor::test_support::tree_snapshot(root); + tokio::fs::remove_dir_all(jar.parent().unwrap()) + .await + .unwrap(); + crate::vendor::redownload::restore(root, &entry, &record, &service.cfg) + .await + .unwrap(); + assert_eq!(crate::vendor::test_support::tree_snapshot(root), snapshot); + assert_eq!( + check_vendored_artifact(root, &entry, &record).await, + ArtifactHealth::Healthy + ); + } + + /// A committed jar whose patched member is past the jar limits is + /// reported as too large, not as unreadable, and is repair's to put + /// back: the jar the ledger records was within them. + #[tokio::test] + #[serial_test::serial] + async fn a_committed_jar_past_the_jar_limits_is_too_large() { + use crate::vendor::{check_vendored_artifact, ArtifactHealth}; + + let (dir, blobs, installed, record) = reactor_fixture(true).await; + let root = dir.path(); + let (result, entry, _) = + unwrap_done(run_jvm(root, &blobs, &installed, &record, None).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("ledger entry"); + // The member the check must inflate is 65 MiB of zeros, deflated to + // a few kilobytes: over what a jar that small may inflate to. + let mut bomb = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + bomb.start_file(JAR_FILE, opts).unwrap(); + std::io::copy(&mut std::io::repeat(0).take(65 * 1024 * 1024), &mut bomb).unwrap(); + std::fs::write( + root.join(&entry.artifact.path), + bomb.finish().unwrap().into_inner(), + ) + .unwrap(); + assert_eq!( + crate::vendor::verify::verify_vendored_patch_record(root, &entry, &record).await, + Err("vendor_artifact_too_large".to_string()) + ); + assert_eq!( + check_vendored_artifact(root, &entry, &record).await, + ArtifactHealth::Corrupt { + reason: "vendor_artifact_too_large".to_string() + } + ); + // The recorded jar is within the limits: repair puts it back. + crate::vendor::test_support::persist(root, PURL, entry.clone()).await; + let sources = PatchSources::blobs_only(&blobs); + let service = crate::vendor::test_support::service_fixture::Fixture::new( + PURL, + installed.as_path().into(), + &record, + &sources, + ) + .await; + crate::vendor::redownload::restore(root, &entry, &record, &service.cfg) + .await + .unwrap(); + assert_eq!( + check_vendored_artifact(root, &entry, &record).await, + ArtifactHealth::Healthy + ); + } + + /// The registry's files for the fixture's upstream jar and pom, served + /// from `server` with the `.sha1` Maven Central publishes beside them. + async fn mount_upstream(server: &wiremock::MockServer, jar: &[u8]) -> EnvGuard { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, ResponseTemplate}; + let base = "/org/apache/commons/commons-text/1.10.0/commons-text-1.10.0"; + for (ext, bytes) in [("jar", jar), ("pom", UPSTREAM_POM)] { + Mock::given(method("GET")) + .and(path(format!("{base}.{ext}"))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes.to_vec())) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path(format!("{base}.{ext}.sha1"))) + .respond_with(ResponseTemplate::new(200).set_body_string(sha1_hex(bytes))) + .mount(server) + .await; + } + EnvGuard::set("SOCKET_MAVEN_REGISTRY", server.uri()) + } + + /// A first vendoring holds the service's jar to upstream outside the + /// patched members, as agent mode does, before anything is written: a + /// jar built from another base, one with a class added (whatever unix + /// mode its entry carries: the JVM loads it all the same) and one with a + /// class dropped are refused, and the project is left as it was. + #[tokio::test] + #[serial_test::serial] + async fn a_first_vendoring_refuses_a_service_jar_that_is_not_upstream_outside_the_patch() { + use crate::patch::jar_members::testing::jar_with_modes; + const MANIFEST: (&str, &[u8], Option) = + ("META-INF/MANIFEST.MF", b"Manifest-Version: 1.0\n", None); + const NOTICE: (&str, &[u8], Option) = (JAR_FILE, PATCHED, None); + const CLASS: &str = "org/apache/commons/text/StringSubstitutor.class"; + const CODE: (&str, &[u8], Option) = (CLASS, b"\xca\xfe\xba\xbe-fake-class", None); + const ADDED: &str = "org/apache/commons/text/Added.class"; + + let cases: Vec<(Vec, String)> = vec![ + ( + jar_with_modes(&[MANIFEST, NOTICE, (CLASS, b"another release's class", None)]), + format!("1 changed (`{CLASS}`)"), + ), + ( + jar_with_modes(&[MANIFEST, NOTICE, CODE, (ADDED, b"\xca\xfe\xba\xbe", None)]), + format!("1 added (`{ADDED}`)"), + ), + ( + // A symlink-mode entry is not a regular file to a zip + // reader, and is a class to the JVM. + jar_with_modes(&[MANIFEST, NOTICE, CODE, (ADDED, b"target", Some(0o120777))]), + format!("1 added (`{ADDED}`)"), + ), + ( + jar_with_modes(&[MANIFEST, NOTICE]), + format!("1 missing (`{CLASS}`)"), + ), + ]; + for (service_jar, difference) in cases { + let (dir, blobs, installed, record) = reactor_fixture(true).await; + let root = dir.path(); + assert!( + zip_bytes_match_after_hashes(&service_jar, &record.files), + "{difference}: the jar carries the patch" + ); + let server = mount_granted_jar(&service_jar).await; + let _registry = mount_upstream(&server, &make_jar(PRISTINE)).await; + let cfg = service_cfg( + Some(&server.uri()), + crate::vendor::VendorSource::Service, + false, + ); + let before = crate::vendor::test_support::tree_snapshot(root); + let (code, detail) = + unwrap_refused(run_jvm(root, &blobs, &installed, &record, Some(&cfg)).await); + assert_eq!(code, "vendor_prebuilt_integrity_mismatch", "{difference}"); + assert_eq!( + detail, + format!( + "the patch service's jar differs from the verified upstream jar outside \ + the patched members: {difference}" + ) + ); + assert_eq!( + crate::vendor::test_support::tree_snapshot(root), + before, + "{difference}: nothing is written" + ); + assert!(!root.join(".socket").exists(), "{difference}"); + } + + // The honest jar vendors. Directory entries and signature files are + // the two things that may differ: the service's builds drop both. + for upstream in [ + make_jar(PRISTINE), + jar_with_modes(&[ + ("META-INF/", b"", None), + MANIFEST, + ("META-INF/APACHE.SF", b"signature", None), + ("META-INF/APACHE.RSA", b"signature", None), + (JAR_FILE, PRISTINE, None), + ("org/apache/commons/text/", b"", None), + CODE, + ]), + ] { + let (dir, blobs, installed, record) = reactor_fixture(true).await; + let root = dir.path(); + tokio::fs::write(installed.join("commons-text-1.10.0.jar"), &upstream) + .await + .unwrap(); + let server = mount_granted_jar(&make_jar(PATCHED)).await; + let _registry = mount_upstream(&server, &upstream).await; + let cfg = service_cfg( + Some(&server.uri()), + crate::vendor::VendorSource::Service, + false, + ); + let (result, entry, _) = + unwrap_done(run_jvm(root, &blobs, &installed, &record, Some(&cfg)).await); + assert!(result.success && entry.is_some(), "{:?}", result.error); + } + } + + /// The jar agent mode patched in `~/.m2` is not upstream's: the first + /// vendoring compares with the registry's own jar instead of refusing. + #[tokio::test] + #[serial_test::serial] + async fn a_first_vendoring_over_an_agent_patched_local_jar_compares_with_the_registry() { + let (dir, blobs, installed, record) = reactor_fixture(true).await; + let root = dir.path(); + let patched = make_jar(PATCHED); + tokio::fs::write(installed.join("commons-text-1.10.0.jar"), &patched) + .await + .unwrap(); + tokio::fs::write( + installed.join("commons-text-1.10.0.jar.sha1"), + sha1_hex(&patched), + ) + .await + .unwrap(); + let server = mount_granted_jar(&patched).await; + let _registry = mount_upstream(&server, &make_jar(PRISTINE)).await; + let cfg = service_cfg( + Some(&server.uri()), + crate::vendor::VendorSource::Service, + false, + ); + let (result, entry, _) = + unwrap_done(run_jvm(root, &blobs, &installed, &record, Some(&cfg)).await); + assert!(result.success && entry.is_some(), "{:?}", result.error); + } + /// commons-text as log4j-core is published: a sibling's version comes /// from the parent's management, written `${project.version}`. const CHILD_OF_PARENT_POM: &str = "4.0.0\ diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index e6bc9195b..6b640ed5b 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -158,19 +158,31 @@ pub async fn restore( { return Err("the downloaded artifact does not match the recorded size".into()); } - let members = if entry.ecosystem == "pypi" { - super::pypi_distribution::read_members(&archive.bytes, &entry.artifact.path)? - } else if entry.artifact.path.ends_with(".tgz") || entry.artifact.path.ends_with(".tar.gz") - { - crate::patch::package::read_archive_bytes_to_map_strict(&archive.bytes) - .map_err(|e| e.to_string())? - } else { - super::verify::read_zip_bytes_to_map_strict(&archive.bytes)? - }; - if entry.ecosystem == "pypi" { - super::pypi_distribution::verify_members(&members, &entry.artifact.path, record)?; + if entry.artifact.path.ends_with(".jar") { + // A jar is read by name, case and all, by the JVM: the + // installer-shaped strictness of the wheel reader (ASCII names, + // no case-colliding pair) refuses obfuscated jars that hold + // both `a.class` and `A.class`, and its size caps refuse large + // ones. The record's members are hashed within the jar limits. + super::verify::verify_jar_bytes_members(&archive.bytes, &record.files).map_err( + |(tag, why)| format!("{tag}: the downloaded jar cannot be verified: {why}"), + )?; } else { - super::verify::verify_member_map(&members, record)?; + let members = if entry.ecosystem == "pypi" { + super::pypi_distribution::read_members(&archive.bytes, &entry.artifact.path)? + } else if entry.artifact.path.ends_with(".tgz") + || entry.artifact.path.ends_with(".tar.gz") + { + crate::patch::package::read_archive_bytes_to_map_strict(&archive.bytes) + .map_err(|e| e.to_string())? + } else { + super::verify::read_zip_bytes_to_map_strict(&archive.bytes)? + }; + if entry.ecosystem == "pypi" { + super::pypi_distribution::verify_members(&members, &entry.artifact.path, record)?; + } else { + super::verify::verify_member_map(&members, record)?; + } } tokio::fs::create_dir_all(uuid_dir) .await diff --git a/crates/socket-patch-core/src/vendor/test_support/service_fixture.rs b/crates/socket-patch-core/src/vendor/test_support/service_fixture.rs index 47ac3d38a..6953f8f03 100644 --- a/crates/socket-patch-core/src/vendor/test_support/service_fixture.rs +++ b/crates/socket-patch-core/src/vendor/test_support/service_fixture.rs @@ -112,6 +112,24 @@ impl Fixture { pub type Secondary = Vec<(&'static str, String, Vec)>; +/// Every file member of a jar, whatever its size: a fixture jar may be past +/// the wheel-sized caps of `read_zip_bytes_to_map`. +fn jar_members(jar: &[u8]) -> Result>, String> { + use std::io::Read as _; + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(jar)).map_err(|e| e.to_string())?; + let mut members = BTreeMap::new(); + for i in 0..zip.len() { + let mut entry = zip.by_index(i).map_err(|e| e.to_string())?; + if entry.is_dir() { + continue; + } + let mut bytes = Vec::new(); + entry.read_to_end(&mut bytes).map_err(|e| e.to_string())?; + members.insert(entry.name().to_string(), bytes); + } + Ok(members) +} + pub async fn archive( purl: &str, dir: &Path, @@ -127,7 +145,7 @@ pub async fn archive( crate::utils::fs::read_regular_to_bytes(&dir.join(format!("{artifact}-{version}.jar"))) .await .map_err(|e| e.to_string())?; - members.extend(crate::vendor::verify::read_zip_bytes_to_map(&bytes)?); + members.extend(jar_members(&bytes)?); } else if let Some((name, version)) = parse_nuget_purl(purl) { let bytes = crate::utils::fs::read_regular_to_bytes(&dir.join(format!( "{}.{}.nupkg", diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 038b4d8da..ebda8b60a 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -5,13 +5,17 @@ //! manifest claims the patch modified must hash (git-blob sha256) to its //! `afterHash` inside that artifact — the same standard `vex::verify` applies //! to installed trees. Dir-shaped ecosystems are hashed in place; npm -//! tarballs and zip artifacts (`.whl`/`.nupkg`/`.jar`) are decoded in memory +//! tarballs and zip artifacts (`.whl`/`.nupkg`) are decoded in memory //! (bounded — the artifacts are committed and tamper-able, so a crafted -//! archive must not OOM an audit). +//! archive must not OOM an audit). A `.jar` has its record members hashed +//! as they are inflated, within the jar limits of +//! [`crate::patch::jar_members`]: released jars are larger than the +//! wheel-sized caps of the in-memory reader allow. //! //! Fail-closed order (each failure is a stable snake_case routing tag): //! `no_files` → `vendor_path_unsafe` → `vendor_uuid_mismatch` → //! `vendor_artifact_missing` → `vendor_artifact_unreadable` / +//! `vendor_artifact_too_large` / //! `file_not_found` / `vendor_hash_mismatch` / `vendor_inventory_mismatch` / //! `vendor_manifest_unverifiable` //! (dir-shaped artifacts with a recorded [`file_inventory`] additionally @@ -126,9 +130,15 @@ pub async fn verify_vendored_patch_record( return super::pypi_distribution::verify_members(&members, &entry.artifact.path, record); } let path_str = artifact.to_string_lossy(); + if path_str.ends_with(".jar") { + let files = record.files.clone(); + tokio::task::spawn_blocking(move || verify_jar_file_members(&artifact, &files)) + .await + .map_err(|_| "vendor_artifact_unreadable".to_string())??; + return super::bun_workspace::verify(project_root, entry).await; + } let is_tarball = path_str.ends_with(".tgz") || path_str.ends_with(".tar.gz"); - let is_zip = - path_str.ends_with(".whl") || path_str.ends_with(".nupkg") || path_str.ends_with(".jar"); + let is_zip = path_str.ends_with(".whl") || path_str.ends_with(".nupkg"); if !is_tarball && !is_zip { let cargo_uuid = (entry.ecosystem == "cargo").then_some(entry.uuid.as_str()); verify_dir_members(&artifact, record, cargo_uuid).await?; @@ -441,6 +451,76 @@ async fn untagged_manifest_matches(dir: &Path, uuid: &str, after_hash: &str) -> .is_some_and(|b| compute_git_sha256_from_bytes(&b).eq_ignore_ascii_case(after_hash)) } +/// A jar past the limits of [`crate::patch::jar_members`]: its own tag, so +/// the omission says the jar is too large, not that it cannot be read. +pub(crate) const ARTIFACT_TOO_LARGE: &str = "vendor_artifact_too_large"; + +fn jar_error_tag(e: crate::patch::jar_members::JarError) -> String { + if e.is_too_large() { + ARTIFACT_TOO_LARGE.to_string() + } else { + "vendor_artifact_unreadable".to_string() + } +} + +/// Every record file at its `afterHash` in the committed jar at `jar`: +/// only those members are inflated, each through the hasher. +fn verify_jar_file_members( + jar: &Path, + files: &HashMap, +) -> Result<(), String> { + // The shared guarded opener, as for a wheel: a FIFO planted at the + // artifact path fails the audit instead of wedging it. + let (file, metadata) = crate::utils::fs::open_regular_file_sync(jar) + .map_err(|_| "vendor_artifact_unreadable".to_string())?; + let jar = crate::patch::jar_members::Jar::open(std::io::BufReader::new(file), metadata.len()) + .map_err(jar_error_tag)?; + verify_jar_members(jar, files).map_err(|(tag, _)| tag) +} + +/// [`verify_jar_file_members`] over a jar already in memory. The error is +/// `(routing tag, what a limit or the archive said)`. +pub(crate) fn verify_jar_bytes_members( + jar: &[u8], + files: &HashMap, +) -> Result<(), (String, String)> { + let jar = crate::patch::jar_members::Jar::of_bytes(jar) + .map_err(|e| (jar_error_tag(e.clone()), e.to_string()))?; + verify_jar_members(jar, files) +} + +fn verify_jar_members( + mut jar: crate::patch::jar_members::Jar, + files: &HashMap, +) -> Result<(), (String, String)> { + for (file_name, info) in files { + // The two spellings `verify_member_map` looks a member up by. + let key = normalize_file_path(file_name); + let mut hash = None; + for name in [key, file_name.as_str()] { + hash = jar + .member_git_sha256(name) + .map_err(|e| (jar_error_tag(e.clone()), e.to_string()))?; + if hash.is_some() || key == file_name { + break; + } + } + let Some(hash) = hash else { + return Err(( + "file_not_found".to_string(), + format!("it has no member `{key}`"), + )); + }; + if !hash.eq_ignore_ascii_case(&info.after_hash) { + return Err(( + "vendor_hash_mismatch".to_string(), + format!("its member `{key}` is not the patched file"), + )); + } + } + Ok(()) +} + fn read_wheel_to_map(whl: &Path) -> Result>, String> { // The shared guarded opener: non-blocking open + regular-file check on // the handle, so a FIFO planted at the artifact path fails the audit @@ -454,7 +534,10 @@ fn read_wheel_to_map(whl: &Path) -> Result>, String> { /// [`read_wheel_to_map`] over in-memory zip bytes — the same entry and /// decompressed-size caps — for callers that hash and decode the SAME -/// buffer (a committed wheel read exactly once). +/// buffer (a committed wheel read exactly once). Jars have their own +/// reader ([`crate::patch::jar_members`]), which leaves this one to the +/// fixtures and the tests. +#[cfg(any(test, feature = "test-fixtures"))] pub(crate) fn read_zip_bytes_to_map(bytes: &[u8]) -> Result>, String> { read_zip_to_map(std::io::Cursor::new(bytes), false) } @@ -707,7 +790,8 @@ pub enum ArtifactHealth { Missing, /// Present but failing verification: rebuildable. `reason` is the /// stable routing tag (`vendor_hash_mismatch`, `file_not_found`, - /// `vendor_artifact_unreadable`, `vendor_sha256_mismatch`, + /// `vendor_artifact_unreadable`, `vendor_artifact_too_large`, + /// `vendor_sha256_mismatch`, /// `vendor_inventory_mismatch`, `vendor_workspace_artifact_missing`, /// `vendor_workspace_artifact_corrupt`). Corrupt { reason: String }, @@ -773,6 +857,7 @@ pub async fn check_vendored_artifact( "vendor_hash_mismatch" | "file_not_found" | "vendor_artifact_unreadable" + | ARTIFACT_TOO_LARGE | "vendor_artifact_non_canonical" | "vendor_inventory_mismatch" | "vendor_workspace_artifact_missing" diff --git a/docs/design/maven-vendoring.md b/docs/design/maven-vendoring.md index 211026634..26998e815 100644 --- a/docs/design/maven-vendoring.md +++ b/docs/design/maven-vendoring.md @@ -335,7 +335,7 @@ tree is refused nowhere and degraded nowhere. ## Artifact identity and integrity -Service jars pass transfer-integrity and patched-member checks. The server constructs jars and strips invalidated signatures; the CLI never rebuilds jar archives. Online vendoring authenticates upstream POM and Gradle module metadata against registry sidecars. A POM or module that a local cache holds and the registry gives no checksum for is the file the build resolved: it is used, and the entry is recorded unverified (`vendor_jvm_upstream_unverified`), as an offline one is. Bytes that differ from a published checksum are refused. Metadata fetches use a separate HTTP client and do not send Socket API credentials. `SOCKET_MAVEN_REGISTRY` supports a private mirror. +Service jars pass transfer-integrity and patched-member checks. The server constructs jars and strips invalidated signatures; the CLI never rebuilds jar archives. Online, before anything is written, the jar (the service's on a first vendoring, the committed one on a re-run) is also compared with the registry-verified upstream jar: every entry the JVM would load, whatever unix mode it carries, must hold the same content outside the record's members and signature files, or the run is refused with `vendor_prebuilt_integrity_mismatch`. A cached upstream jar the registry's checksum does not vouch for (one agent mode patched in `~/.m2`) is not the baseline; the registry's own download is. Jars are read member by member within fixed limits (200,000 entries; 1 GiB and 100 times the jar's size inflated per pass); one past them is `vendor_artifact_too_large`. Online vendoring authenticates upstream POM and Gradle module metadata against registry sidecars. A POM or module that a local cache holds and the registry gives no checksum for is the file the build resolved: it is used, and the entry is recorded unverified (`vendor_jvm_upstream_unverified`), as an offline one is. Bytes that differ from a published checksum are refused. Metadata fetches use a separate HTTP client and do not send Socket API credentials. `SOCKET_MAVEN_REGISTRY` supports a private mirror. Maven v5 does not enable Resolver trusted-checksum processors at build time. Those processors crash some release reactors and system-scope dependencies, diff --git a/docs/ecosystems.md b/docs/ecosystems.md index c8f89d538..5e4aba452 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1093,11 +1093,20 @@ then `.gradle` in the account's home directory. On Unix that is the passwd entry `$HOME`; when they differ, scan notes `gradle_user_home_differs`. `~/.m2` here means the Maven local repository, found the way Maven finds it: -`MAVEN_REPO_LOCAL`, then `-Dmaven.repo.local` in `MAVEN_ARGS` or `MAVEN_OPTS`, then +`MAVEN_REPO_LOCAL`, then `-Dmaven.repo.local` in `MAVEN_ARGS` (the command line), in +the project's `.mvn/maven.config`, or in `MAVEN_OPTS`, in that order, then `` in `~/.m2/settings.xml`, then in the install's `conf/settings.xml` (`MAVEN_HOME` or `M2_HOME`), then `.m2/repository` in `user.home`. `M2_HOME` itself never names a local repository. On Windows `user.home` is `USERPROFILE`, not `HOME`. +The `.mvn/maven.config` read is the one Maven's launcher finds from the project +directory: in the nearest directory at or above it that holds a `.mvn` directory. A +line is one argument (`#` starts a comment), the last `-Dmaven.repo.local=` wins, +`${session.rootDirectory}`, `${session.topDirectory}`, `${user.home}` and +`${env.NAME}` are filled in, and a relative path is taken from the project directory, +where Maven would run. A `--global` run reads no project's config. Maven before 3.9 +does not read `MAVEN_ARGS`; socket-patch reads it whatever Maven is installed. + A Gradle-only build reads `~/.m2` only through `mavenLocal()`. Scan looks for it in every settings, build, `buildSrc`, included-build, applied and init script, including the wrapper distribution's `init.d`. Without it, `~/.m2` is not scanned, and modules @@ -1111,8 +1120,19 @@ cannot be read literally, `~/.m2` stays in the scan and scan notes `apply` patches every copy the build consumes. Gradle keeps one hash directory per download of a version, and each one holding the patched files is patched. Records keyed by members inside a jar swap in the patch service's build of the whole jar, so -they need network access (`jvm_agent_service_required` offline). The original is -backed up under `.socket/jvm-originals/` and `rollback` restores from it. `rollback` +they need network access (`jvm_agent_service_required` offline). Before the swap the +service's jar is compared with the installed one member by member: everything the +JVM would load outside the patched members and signature files must be identical, or +that copy is left alone (`jvm_agent_service_jar_mismatch`, naming the members). Jars +of up to 200,000 entries and 1 GiB inflated are handled; one past that is +`jvm_jar_too_large`. The original is +backed up under `.socket/jvm-originals/` and `rollback` restores from it. A `~/.m2` +jar that another project (or an earlier workspace over a cached `~/.m2`) patched has +no backup in this project: online, `rollback` downloads the original from the +registry and uses it only when it matches the registry's checksum and is the jar the +copy was patched from; otherwise it fails with `jvm_jar_backup_missing` and says how +to recover (roll back from the project that applied the patch, or delete the version +directory so the build downloads the jar again). `rollback` and `remove` restore every patched writable copy, including a `~/.m2` copy the build no longer reads (an earlier apply patched it while `mavenLocal()` was declared). Such a copy never fails the run: one another build re-patched or rebuilt, or whose From c500e5a2fed7bdb23d88611b4498c495646cad0d Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 13:42:13 -0500 Subject: [PATCH 2/5] Address review of the jar limits and checks Read `.mvn/maven.config` only for a Maven build, and as its Maven reads it. A Gradle or Scala-tool build's mavenLocal() never reads the file, so such a project keeps the environment's repository. Maven before 3.9 splits the file on whitespace and interpolates nothing; 3.9 and later take a line as one argument. The Maven Wrapper says which applies; without one the reading whose directory exists is used, and when both exist no repository is guessed at (maven_local_repository_undetermined). An empty value and an undefined placeholder resolve as Maven resolves them, instead of falling through to the settings. A first vendoring no longer fails when the registry cannot be reached while the patch service can. The baseline is the registry-verified jar, else the local repository's jar, else none; the last two are reported (vendor_jvm_upstream_unverified). A mismatch is still a refusal. A rollback reads the copy before it looks for a backup or downloads anything: a `~/.m2` copy past the jar limits fails as that, not as a missing backup, and a Gradle copy's backup is found by its hash directory without reading the copy. The copy is hashed once. The central directory is bounded by what the archive's end records declare, before the zip reader parses it: 200,000 entries, 64 MiB. Also: the Gradle classifier check fails closed on a jar it cannot read; `vendor --check` names the limit a jar is past; the digest passes run on the blocking pool and identical copies are read once; a copy's refusal code travels beside its result instead of being parsed out of the text. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 43 +- crates/socket-patch-cli/src/commands/apply.rs | 32 +- .../socket-patch-cli/src/commands/scan/mod.rs | 9 + .../tests/maven_sidecar_cli.rs | 39 ++ .../src/crawlers/maven_crawler.rs | 233 +++++++--- .../maven_crawler/local_repo_tests.rs | 193 +++++++- .../src/patch/jar_members.rs | 140 +++++- crates/socket-patch-core/src/patch/jvm_jar.rs | 419 +++++++++++++----- .../src/vendor/jvm/gradle.rs | 73 ++- .../src/vendor/maven_repo.rs | 164 +++++-- crates/socket-patch-core/src/vendor/verify.rs | 23 + docs/design/maven-vendoring.md | 2 +- docs/ecosystems.md | 29 +- 13 files changed, 1122 insertions(+), 277 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8c46a6bcf..84eb9cb30 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2832,15 +2832,25 @@ the JVM would load must hold the same content in both, whatever unix mode it car the record's members and signature files (`META-INF/*.SF`, `.RSA`, `.DSA`, `.EC`) are exempt and directory entries may differ. A jar that adds, drops or changes anything else is refused with `vendor_prebuilt_integrity_mismatch`, the detail naming up to -three such members, and a first vendoring commits and wires nothing. When no upstream -jar can be verified the refusal is `vendor_jvm_upstream_unavailable`. +three such members, and a first vendoring commits and wires nothing. + +A registry that cannot be reached while the patch service can does not stop a first +vendoring. The baseline is then, in order: the registry-verified jar; else the jar in +the build's local repository, as agent mode trusts the installed jar; else none, and +the service's jar is vendored as served. The last two are reported with +`vendor_jvm_upstream_unverified` (the detail says which, and that a later run makes +the comparison) and the entry is recorded as not registry-verified. A mismatch +against whichever baseline was used is still the refusal above. An online re-run over +a committed tree needs the registry-verified jar, as before +(`vendor_jvm_upstream_unavailable` without one). 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 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, which +archive's own entry count, never on the sizes an archive declares: 200,000 entries +and 64 MiB of central directory (read from the archive's end records 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 @@ -3168,6 +3178,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` @@ -3199,7 +3210,11 @@ 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. Such an +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 @@ -3216,8 +3231,10 @@ to three added, missing or changed members, and is left as it is; the other copi 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 per pass over one jar 1 GiB inflated and at most 100 times the jar's own size (a +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 archive's end records before the +directory is parsed, so a directory of millions of records is refused unread), 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 @@ -3245,7 +3262,7 @@ starts with the code): | `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; 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. The message names the limit that was passed. | +| `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 | 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. | @@ -3388,9 +3405,9 @@ 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_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. Also reported by a first vendoring that could get no registry-verified upstream jar: the members the patch does not touch were compared with the local repository's jar, or, with none, not compared at all. | | `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 (`:`). | The Maven half of a root (single-module, reactor or mixed) also reports diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index b7386ed31..dc2f591f8 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 @@ -3699,18 +3715,18 @@ 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. - let coded = result.error.as_deref().and_then(|error| { - let code = jvm_jar::copy_failure_code(error)?; - Some((code, error[code.len() + 2..].to_string())) - }); - if let Some((code, detail)) = coded { - out.warn(code, detail); + 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 01eb328a5..43d53274e 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 { @@ -1459,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/tests/maven_sidecar_cli.rs b/crates/socket-patch-cli/tests/maven_sidecar_cli.rs index 25d74a533..36dc1d6d0 100644 --- a/crates/socket-patch-cli/tests/maven_sidecar_cli.rs +++ b/crates/socket-patch-cli/tests/maven_sidecar_cli.rs @@ -337,6 +337,45 @@ fn maven_config_local_repository_is_the_one_patched() { 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 _; diff --git a/crates/socket-patch-core/src/crawlers/maven_crawler.rs b/crates/socket-patch-core/src/crawlers/maven_crawler.rs index 3984e3235..7a05378e4 100644 --- a/crates/socket-patch-core/src/crawlers/maven_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/maven_crawler.rs @@ -539,6 +539,11 @@ 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, } @@ -549,6 +554,7 @@ impl JvmEnv { pub fn from_process() -> Self { Self { m2_repo: MavenCrawler::m2_repo_path(), + m2_undetermined: None, gradle: gradle_cache::home_from_process_env(), } } @@ -558,13 +564,15 @@ impl JvmEnv { /// 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_repo_path_in( - &gradle_cache::ProcessEnv, - Os::current(), - None, - Some(project), - ), + m2_repo, + m2_undetermined, gradle: gradle_cache::home_from_process_env(), } } @@ -592,8 +600,10 @@ impl JvmEnv { 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_in(env, os, home_dir, project), + m2_repo, + m2_undetermined, gradle: GradleHome::resolve(env, os, home_dir), } } @@ -665,19 +675,30 @@ pub fn m2_repo_path_with(env: &dyn Env, os: Os, home_dir: Option<&Path>) -> Opti /// `~/.m2` inside the scanned project as the user's local repository (B66). /// 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`. +/// 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. @@ -722,15 +743,19 @@ pub fn m2_repo_path_in( }, }; 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.and_then(|p| maven_config_repo_local(p, &lookup)) { - Some(value) => value, - None => rooted(argument("MAVEN_OPTS")), + 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); + return (Some(repo), None); } let maven_home = set("MAVEN_HOME").or_else(|| set("M2_HOME")); let settings_files = [ @@ -741,63 +766,90 @@ pub fn m2_repo_path_in( ]; for path in settings_files.into_iter().flatten() { if let Some(repo) = settings_local_repository(&path, &lookup) { - return Some(repo); + return (Some(repo), None); } } - Some(user_home?.join(".m2").join("repository")) + (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; -/// The local repository a `-Dmaven.repo.local=…` in the `.mvn/maven.config` -/// of the build Maven would run in `project` names. `None` when no config -/// sets the property; `Some(None)` when one does with a value that is not -/// used here: an empty one (Maven then takes the directory it runs in for -/// its repository) or a placeholder nothing here defines. The config still -/// decides, as it does in Maven: no later source is consulted. +/// 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). /// -/// 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. -/// Each line is one argument (Maven 3.9 and later; `#` starts a comment -/// line); a line that is not the property itself is also split on -/// whitespace, which is how earlier Mavens read the whole file. The last -/// occurrence wins. Maven interpolates the arguments (3.9.2 and later): -/// `${session.rootDirectory}` and `${maven.multiModuleProjectDirectory}` -/// are that directory, `${session.topDirectory}` and `${user.dir}` are -/// `project`, and anything else is asked of `lookup` (`${user.home}`, -/// `${env.NAME}`, a `-D` of the environment). A relative path is taken -/// from `project`, where Maven would run. -fn maven_config_repo_local( - project: &Path, - lookup: &dyn Fn(&str) -> Option, -) -> Option> { +/// 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. +/// From 3.9.2 on it fills in `${session.rootDirectory}` and +/// `${maven.multiModuleProjectDirectory}` (that directory), +/// `${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 Wrapper's version says which reading applies. Without one, +/// 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="; - // `.` has no ancestors to search. - let project = std::path::absolute(project).ok()?; - let root = project.ancestors().find(|dir| dir.join(".mvn").is_dir())?; - let config = root.join(".mvn").join("maven.config"); - // Bounded, and FIFO-safe: the file is in the project's own tree. - if std::fs::metadata(&config).ok()?.len() > MAX_MAVEN_CONFIG_BYTES { - return None; + 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 text = crate::utils::fs::read_regular_to_string_sync(&config).ok()?; - let value = text + 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); + let before_3_9 = text + .split_whitespace() + .filter_map(|arg| arg.strip_prefix(FLAG)) + .next_back() + .map(at); + let per_line = text .lines() - .map(str::trim) + .map(str::trim_end) .filter(|line| !line.is_empty() && !line.starts_with('#')) - .filter_map(|line| match line.strip_prefix(FLAG) { - Some(value) => Some(value), - None => line - .split_whitespace() - .filter_map(|arg| arg.strip_prefix(FLAG)) - .next_back(), - }) - .next_back()? - .trim(); - if value.is_empty() { - return Some(None); - } + .filter_map(|line| line.strip_prefix(FLAG)) + .next_back(); let lookup = |name: &str| match name { "session.rootDirectory" | "maven.multiModuleProjectDirectory" => { Some(root.display().to_string()) @@ -805,7 +857,69 @@ fn maven_config_repo_local( "session.topDirectory" | "user.dir" => Some(project.display().to_string()), _ => lookup(name), }; - Some(interpolate(value, &lookup).map(|value| project.join(value))) + let from_3_9 = |interpolates: bool| { + per_line.map(|value| match interpolates { + true => at(&interpolate_defined(value, &lookup)), + false => at(value), + }) + }; + let version = read("wrapper/maven-wrapper.properties") + .and_then(|props| crate::formats::maven::trusted_checksums::wrapper_maven_version(&props)) + .map(|version| { + let mut parts = version + .split(['.', '-']) + .map(|part| part.parse::().unwrap_or(0)); + [0; 3].map(|_| parts.next().unwrap_or(0)) + }); + let found = |repo: Option| repo.map_or(ConfigRepo::Unset, ConfigRepo::Path); + match version { + 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..]; + } + // 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 @@ -2921,6 +3035,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 cf622aeb6..b3713f891 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 @@ -314,6 +314,25 @@ fn maven_args_user_home_does_not_move_the_m2_directory() { ); } +/// 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 @@ -327,6 +346,7 @@ fn maven_config_local_repository_is_honoured_in_mavens_order() { 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()), @@ -378,6 +398,46 @@ fn maven_config_local_repository_is_honoured_in_mavens_order() { ); } +/// 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 @@ -387,7 +447,8 @@ 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"); - std::fs::create_dir_all(&module).unwrap(); + maven_build(root.path()); + maven_build(&module); let config = root.path().join(".mvn").join("maven.config"); let e = env(&[("HOME", home.path())]); @@ -399,17 +460,18 @@ fn maven_config_is_found_above_a_module_and_interpolated() { 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\n"); + 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")) ); - // Maven before 3.9 split the whole file on whitespace; the last - // occurrence wins either way. write( &config, - "-B -Dmaven.repo.local=first -Dmaven.repo.local=.repo -q\n", + "-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"))); @@ -422,14 +484,110 @@ fn maven_config_is_found_above_a_module_and_interpolated() { ); } +/// 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}"); + } + + // 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 to a value not used here (empty, or with a -/// placeholder nothing defines) still decides, as it does in Maven. +/// 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 an_unusable_maven_config_changes_nothing() { +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")); @@ -454,13 +612,14 @@ fn an_unusable_maven_config_changes_nothing() { assert_eq!(m2_repo_in(&e, project.path()), opts, "a directory"); std::fs::remove_dir(&config).unwrap(); - // Set, but not used here: Maven takes the config's value, so the - // repository MAVEN_OPTS names (which Maven does not reach) is not it. - for text in [ - "-Dmaven.repo.local=${some.build.property}/m2\n", - "-Dmaven.repo.local=\n", - ] { - write(&config, text); - assert_eq!(m2_repo_in(&e, project.path()), default, "{text:?}"); - } + 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/patch/jar_members.rs b/crates/socket-patch-core/src/patch/jar_members.rs index e46bc0fdb..612179554 100644 --- a/crates/socket-patch-core/src/patch/jar_members.rs +++ b/crates/socket-patch-core/src/patch/jar_members.rs @@ -31,11 +31,16 @@ //! # Limits //! //! The sizes an archive declares for its entries are the author's claim, so -//! none of the limits trusts them: the count is the central directory's own, -//! and the byte limits are on what is actually inflated. +//! 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 records +//! before the zip reader parses the directory, since the reader allocates +//! for whatever those records declare: a directory of millions of tiny +//! records is refused unread. //! //! * [`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. @@ -49,7 +54,7 @@ //! limit and by how much. use std::collections::BTreeMap; -use std::io::{Read, Seek}; +use std::io::{Read, Seek, SeekFrom}; use sha2::{Digest, Sha256}; @@ -57,6 +62,8 @@ 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`]. @@ -114,7 +121,8 @@ impl<'a> Jar> { impl Jar { /// A pass over the archive `reader` holds, `archive_len` bytes long. - pub(crate) fn open(reader: R, archive_len: u64) -> Result { + pub(crate) fn open(mut reader: R, archive_len: u64) -> Result { + check_declared_directory(&mut reader, archive_len)?; let zip = zip::ZipArchive::new(reader) .map_err(|e| JarError::Unreadable(format!("not a readable zip archive ({e})")))?; if zip.len() > MAX_ENTRIES { @@ -213,6 +221,78 @@ impl Jar { } } +/// Hold what an archive's end records declare of its central directory to +/// [`MAX_ENTRIES`] and [`MAX_CENTRAL_DIRECTORY_BYTES`], before the zip reader +/// parses (and allocates for) it. The reader may settle on any record that +/// looks like the end of the directory, so every `PK\x05\x06` in the last +/// 64 KiB is checked, with the zip64 record its locator points at and any +/// zip64 record in that tail. +fn check_declared_directory(reader: &mut R, len: u64) -> Result<(), JarError> { + const END: &[u8] = b"PK\x05\x06"; + const END64: &[u8] = b"PK\x06\x06"; + const LOCATOR: &[u8] = b"PK\x06\x07"; + let unread = |e: std::io::Error| JarError::Unreadable(format!("its end cannot be read ({e})")); + let le = |bytes: &[u8]| { + bytes + .iter() + .rev() + .fold(0u64, |n, b| (n << 8) | u64::from(*b)) + }; + let within = |entries: u64, directory: u64| { + // A record declaring more than the archive can hold (a central + // record is 46 bytes at least) is not its end record: bytes that + // happen to spell the signature, which the reader passes over too. + if directory > len || entries > len / 46 { + return Ok(()); + } + if entries > MAX_ENTRIES as u64 { + return Err(JarError::TooLarge(format!( + "it holds {entries} entries, over the limit of {MAX_ENTRIES}" + ))); + } + if directory > MAX_CENTRAL_DIRECTORY_BYTES { + return Err(JarError::TooLarge(format!( + "its central directory takes {} MiB, over the limit of {} MiB", + mib(directory), + mib(MAX_CENTRAL_DIRECTORY_BYTES) + ))); + } + Ok(()) + }; + // An end record, its comment (at most 64 KiB) and a zip64 locator and + // record before it. + let tail_len = len.min(22 + 65_535 + 20 + 56); + reader + .seek(SeekFrom::Start(len - tail_len)) + .map_err(unread)?; + let mut tail = vec![0u8; tail_len as usize]; + reader.read_exact(&mut tail).map_err(unread)?; + for at in 0..tail.len() { + let rest = &tail[at..]; + if rest.len() >= 56 && rest.starts_with(END64) { + within(le(&rest[32..40]), le(&rest[40..48]))?; + } + if rest.len() < 22 || !rest.starts_with(END) { + continue; + } + within(le(&rest[10..12]), le(&rest[12..16]))?; + if at < 20 || !tail[at - 20..].starts_with(LOCATOR) { + continue; + } + let offset = le(&tail[at - 12..at - 4]); + if offset.checked_add(56).is_some_and(|end| end <= len) { + let mut record = [0u8; 56]; + reader.seek(SeekFrom::Start(offset)).map_err(unread)?; + reader.read_exact(&mut record).map_err(unread)?; + if record.starts_with(END64) { + within(le(&record[32..40]), le(&record[40..48]))?; + } + } + } + reader.seek(SeekFrom::Start(0)).map_err(unread)?; + Ok(()) +} + /// The content digests of a jar's members ([`Jar::content_digests`]). #[derive(Debug, Clone, PartialEq, Eq, Default)] pub(crate) struct Digests(BTreeMap, [u8; 32]>); @@ -418,6 +498,58 @@ mod tests { ); } + /// The limits on the central directory are held to what the end records + /// declare, before the zip reader parses (and allocates for) it: these + /// archives have no directory to parse at all, so the refusal can only + /// have come from the records. + #[test] + fn the_central_directory_is_bounded_before_it_is_parsed() { + let end = |entries: u16, directory: u32| { + let mut record = b"PK\x05\x06\0\0\0\0".to_vec(); + record.extend_from_slice(&entries.to_le_bytes()); + record.extend_from_slice(&entries.to_le_bytes()); + record.extend_from_slice(&directory.to_le_bytes()); + record.extend_from_slice(&[0; 6]); + record + }; + // Millions of 46-byte records fit a download: 200,001 of them here, + // declared by a zip64 record and the locator that points at it. + let entries = MAX_ENTRIES as u64 + 1; + let mut many = vec![0u8; entries as usize * 46]; + let at = many.len() as u64; + many.extend_from_slice(b"PK\x06\x06"); + many.extend_from_slice(&[0; 20]); + many.extend_from_slice(&entries.to_le_bytes()); + many.extend_from_slice(&entries.to_le_bytes()); + many.extend_from_slice(&(entries * 46).to_le_bytes()); + many.extend_from_slice(&[0; 8]); + many.extend_from_slice(b"PK\x06\x07\0\0\0\0"); + many.extend_from_slice(&at.to_le_bytes()); + many.extend_from_slice(&1u32.to_le_bytes()); + many.extend_from_slice(&end(u16::MAX, u32::MAX)); + let err = Jar::of_bytes(&many).err().expect("refused"); + assert_eq!( + err.to_string(), + format!("it holds {entries} entries, over the limit of {MAX_ENTRIES}") + ); + assert!(err.is_too_large()); + + // A directory of a few entries with 65 MiB of names and comments. + let mut wide = vec![0u8; 65 * 1024 * 1024]; + wide.extend_from_slice(&end(3, 65 * 1024 * 1024)); + let err = Jar::of_bytes(&wide).err().expect("refused"); + assert_eq!( + err.to_string(), + "its central directory takes 65 MiB, over the limit of 64 MiB" + ); + + // Bytes that spell an end record but declare more than the archive + // holds are not one: the real record decides. + let lookalike = end(u16::MAX, u32::MAX); + let real = jar(&[("a/B.class", &lookalike)]); + assert_eq!(Digests::of_bytes(&real).unwrap().len(), 1); + } + /// What is inflated is bounded, whatever the entry declares: a deflated /// run of zeros is a few kilobytes of archive. #[test] diff --git a/crates/socket-patch-core/src/patch/jvm_jar.rs b/crates/socket-patch-core/src/patch/jvm_jar.rs index dcc961ba3..8c72e29aa 100644 --- a/crates/socket-patch-core/src/patch/jvm_jar.rs +++ b/crates/socket-patch-core/src/patch/jvm_jar.rs @@ -54,16 +54,32 @@ pub const JAR_TOO_LARGE: &str = "jvm_jar_too_large"; /// copy fails). pub const SERVICE_JAR_MISMATCH: &str = "jvm_agent_service_jar_mismatch"; -/// The reason code a copy's own failure starts with, when it is one a run -/// reports as a warning too ([`JAR_TOO_LARGE`], [`SERVICE_JAR_MISMATCH`]). -pub fn copy_failure_code(error: &str) -> Option<&'static str> { - [JAR_TOO_LARGE, SERVICE_JAR_MISMATCH] - .into_iter() - .find(|code| { - error - .strip_prefix(code) - .is_some_and(|rest| rest.starts_with(": ")) - }) +/// One copy's result of a swap. `refusal` is set when the copy was left +/// alone for a reason a run reports as a warning too ([`JAR_TOO_LARGE`], +/// [`SERVICE_JAR_MISMATCH`]); `result.error` is that refusal, formatted. +#[derive(Debug, Clone)] +pub struct SwappedCopy { + pub result: ApplyResult, + pub refusal: Option, +} + +impl std::ops::Deref for SwappedCopy { + type Target = ApplyResult; + fn deref(&self) -> &ApplyResult { + &self.result + } +} + +/// `work` on the blocking pool: a digest pass inflates a jar up to the jar +/// limits, which is no work for an async worker. +async fn blocking(work: impl FnOnce() -> T + Send + 'static) -> T { + match tokio::task::spawn_blocking(work).await { + Ok(value) => value, + Err(e) => match e.try_into_panic() { + Ok(panic) => std::panic::resume_unwind(panic), + Err(e) => panic!("the blocking pool is gone: {e}"), + }, + } } /// The two shapes of a Maven patch record (see the module docs). @@ -452,6 +468,25 @@ pub async fn apply_jar_swap( swap: &JarSwap<'_>, copies: &[PathBuf], service: Option<&VendorServiceConfig>, +) -> Result, SwapRefusal> { + let mut refusals = HashMap::new(); + let results = swap_copies(swap, copies, service, &mut refusals).await?; + Ok(results + .into_iter() + .enumerate() + .map(|(i, result)| SwappedCopy { + result, + refusal: refusals.remove(&i), + }) + .collect()) +} + +/// [`apply_jar_swap`]; a copy's coded refusal goes to `refusals` by index. +async fn swap_copies( + swap: &JarSwap<'_>, + copies: &[PathBuf], + service: Option<&VendorServiceConfig>, + refusals: &mut HashMap, ) -> Result, SwapRefusal> { let mut results = Vec::new(); let mut pending: Vec<(usize, Vec)> = Vec::new(); @@ -509,59 +544,96 @@ pub async fn apply_jar_swap( } let jar = service_jar(service, swap.uuid).await?; - // Every member's content, read within the jar limits before anything - // else inflates the download. - let service_members = Digests::of_bytes(&jar).map_err(|e| match e { - JarError::TooLarge(why) => SwapRefusal::new( - JAR_TOO_LARGE, - format!( - "the patch service's build of {} cannot be checked against the installed jar: \ - {why}. Nothing was written. `--mode hosted` does not read the jar.", - swap.jar_leaf - ), - ), - JarError::Unreadable(why) => SwapRefusal::new( - SERVICE_JAR_MISMATCH, - format!("the patch service's jar cannot be read: {why}"), - ), - })?; - // After the bounded pass: this one inflates only what that one did. - if !crate::vendor::common::zip_bytes_match_after_hashes(&jar, swap.files) { - return Err(SwapRefusal::new( - SERVICE_JAR_MISMATCH, - "the patch service's jar does not carry the record's patched members", - )); - } + // One pass off the async workers: every member's content of the + // service's jar, read within the jar limits before anything else + // inflates the download, then of each original. Identical originals + // (one jar in several caches) are read once, keyed by their sha256. + let files = swap.files.clone(); + let (jar, originals, service_members, copy_members) = blocking(move || { + use sha2::Digest as _; + let service = Digests::of_bytes(&jar).map(|members| { + // After the bounded pass: this inflates only what that one did. + crate::vendor::common::zip_bytes_match_after_hashes(&jar, &files).then_some(members) + }); + let mut read: HashMap<[u8; 32], Result> = HashMap::new(); + let copies: Vec> = match &service { + Ok(Some(_)) => pending + .iter() + .map(|(_, original)| { + read.entry(sha2::Sha256::digest(original).into()) + .or_insert_with(|| Digests::of_bytes(original)) + .clone() + }) + .collect(), + _ => Vec::new(), + }; + (jar, pending, service, copies) + }) + .await; + let service_members = match service_members { + Ok(Some(members)) => members, + Ok(None) => { + return Err(SwapRefusal::new( + SERVICE_JAR_MISMATCH, + "the patch service's jar does not carry the record's patched members", + )) + } + Err(JarError::TooLarge(why)) => { + return Err(SwapRefusal::new( + JAR_TOO_LARGE, + format!( + "the patch service's build of {} cannot be checked against the installed \ + jar: {why}. Nothing was written. `--mode hosted` does not read the jar.", + swap.jar_leaf + ), + )) + } + Err(JarError::Unreadable(why)) => { + return Err(SwapRefusal::new( + SERVICE_JAR_MISMATCH, + format!("the patch service's jar cannot be read: {why}"), + )) + } + }; // Per copy: everything the patch does not touch must be upstream's. let patched = patched_names(swap.files); - pending.retain(|(i, original)| { - let path = Path::new(&results[*i].package_path).join(swap.jar_leaf); - let failure = match Digests::of_bytes(original) { + let mut pending = Vec::new(); + for ((i, original), members) in originals.into_iter().zip(copy_members) { + let path = Path::new(&results[i].package_path).join(swap.jar_leaf); + let refusal = match members { Ok(members) => { let difference = unpatched_difference(&members, &service_members, &patched); if difference.is_empty() { - return true; + pending.push((i, original)); + continue; } - format!( - "{SERVICE_JAR_MISMATCH}: the patch service's jar differs from {} outside the \ - patched members: {}. The two are not the same jar apart from the patch, so \ - that copy was left as it is.", - path.display(), - difference.describe() + SwapRefusal::new( + SERVICE_JAR_MISMATCH, + format!( + "the patch service's jar differs from {} outside the patched members: \ + {}. The two are not the same jar apart from the patch, so that copy \ + was left as it is.", + path.display(), + difference.describe() + ), ) } - Err(JarError::TooLarge(why)) => format!( - "{JAR_TOO_LARGE}: {} cannot be checked against the patch service's jar: {why}. \ - It was left as it is. `--mode hosted` does not read the jar.", - path.display() + Err(JarError::TooLarge(why)) => SwapRefusal::new( + JAR_TOO_LARGE, + format!( + "{} cannot be checked against the patch service's jar: {why}. It was left \ + as it is. `--mode hosted` does not read the jar.", + path.display() + ), ), Err(JarError::Unreadable(why)) => { - format!("Cannot apply patch: {} - {why}", path.display()) + results[i].error = Some(format!("Cannot apply patch: {} - {why}", path.display())); + continue; } }; - results[*i].error = Some(failure); - false - }); + results[i].error = Some(format!("{}: {}", refusal.code, refusal.message)); + refusals.insert(i, refusal); + } if swap.dry_run { for (i, _) in &pending { results[*i].success = true; @@ -675,16 +747,9 @@ pub struct JarRestore<'a> { pub offline: bool, } -/// The backup under [`ORIGINALS_DIR`] that is the original of `current` (a -/// patched copy): its record members at their `beforeHash`, every other -/// member equal to `current`'s, and — for a Gradle hash dir — hashing to the -/// directory's name. Backups are tried in name order. -async fn find_backup(restore: &JarRestore<'_>, dir: &Path, current: &[u8]) -> Option> { - let current = Digests::of_bytes(current).ok()?; - let gradle_hash = maven_sidecars::is_gradle_hash_dir(dir) - .then(|| dir.file_name()?.to_str().map(str::to_string)) - .flatten(); - let mut names: Vec = std::fs::read_dir(restore.socket_dir.join(ORIGINALS_DIR)) +/// The backups under [`ORIGINALS_DIR`], in name order. +fn backups(socket_dir: &Path) -> Vec { + let mut names: Vec = std::fs::read_dir(socket_dir.join(ORIGINALS_DIR)) .into_iter() .flatten() .flatten() @@ -692,20 +757,67 @@ async fn find_backup(restore: &JarRestore<'_>, dir: &Path, current: &[u8]) -> Op .filter(|p| p.extension().is_some_and(|e| e == "jar")) .collect(); names.sort(); - for path in names { - let Ok(bytes) = crate::utils::fs::read_regular_to_bytes(&path).await else { - continue; - }; - if let Some(hash) = &gradle_hash { - if !gradle_cache::hash_eq(hash, &sha1_hex(&bytes)) { - continue; - } - } - if is_original_of(&bytes, ¤t, restore.files) { - return Some(bytes); - } + names +} + +/// The backup of a Gradle copy: the one that hashes to the copy's hash +/// directory, which names the jar Gradle downloaded there, and holds the +/// record's members at their `beforeHash`. The patched copy is not read: +/// the directory says what its original is. +fn gradle_backup( + socket_dir: &Path, + dir: &Path, + files: &HashMap, +) -> Option> { + let hash = dir.file_name()?.to_str()?; + backups(socket_dir).into_iter().find_map(|path| { + let bytes = crate::utils::fs::read_regular_to_bytes_sync(&path).ok()?; + (gradle_cache::hash_eq(hash, &sha1_hex(&bytes)) && members_at_before(&bytes, files)) + .then_some(bytes) + }) +} + +/// What a `~/.m2` copy's original can be told from. +enum M2Original { + /// The backup that is its original. + Backup(Vec), + /// No backup is; the copy's members, for judging an upstream jar. + NoBackup(Digests), + /// The copy cannot be compared with anything: why. + Unread(JarError), +} + +/// The backup of a `~/.m2` copy `current`, which nothing names: the one +/// that is its original ([`is_original_of`]). The copy is read first, and +/// once: one that cannot be compared has no original to look for. +fn m2_backup( + socket_dir: &Path, + current: &[u8], + files: &HashMap, +) -> M2Original { + let members = match Digests::of_bytes(current) { + Ok(members) => members, + Err(e) => return M2Original::Unread(e), + }; + let found = backups(socket_dir).into_iter().find_map(|path| { + let bytes = crate::utils::fs::read_regular_to_bytes_sync(&path).ok()?; + is_original_of(&bytes, &members, files).then_some(bytes) + }); + match found { + Some(bytes) => M2Original::Backup(bytes), + None => M2Original::NoBackup(members), } - None +} + +/// Whether `candidate` holds each record member at its `beforeHash` (a +/// member the patch adds, with an empty `beforeHash`, absent). +fn members_at_before(candidate: &[u8], files: &HashMap) -> bool { + verify_member_bytes(candidate, files).iter().all(|v| { + v.status == VerifyStatus::Ready + && files + .get(&v.file) + .is_some_and(|i| v.current_hash.as_deref().unwrap_or("") == i.before_hash) + }) } /// Whether the jar `candidate` is the original of a patched copy whose @@ -717,14 +829,10 @@ fn is_original_of( patched_copy: &Digests, files: &HashMap, ) -> bool { - verify_member_bytes(candidate, files).iter().all(|v| { - v.status == VerifyStatus::Ready - && files - .get(&v.file) - .is_some_and(|i| v.current_hash.as_deref().unwrap_or("") == i.before_hash) - }) && Digests::of_bytes(candidate).is_ok_and(|members| { - unpatched_difference(&members, patched_copy, &patched_names(files)).is_empty() - }) + members_at_before(candidate, files) + && Digests::of_bytes(candidate).is_ok_and(|members| { + unpatched_difference(&members, patched_copy, &patched_names(files)).is_empty() + }) } /// The upstream jar of a Gradle copy, accepted only when it hashes to the @@ -754,7 +862,10 @@ async fn upstream_for_gradle_copy(purl: &str, jar_leaf: &str, dir: &Path) -> Opt /// members at their `beforeHash`, every other member the copy's own). The /// `.sha1` Maven wrote beside the jar cannot vouch for it: the swap rewrote /// that file for the patched jar. `Err` says what was missing. -async fn upstream_for_m2_copy(restore: &JarRestore<'_>, current: &[u8]) -> Result, String> { +async fn upstream_for_m2_copy( + restore: &JarRestore<'_>, + current: Digests, +) -> Result, String> { let (group, artifact, version) = parse_maven_purl(restore.purl).ok_or("its purl names no Maven coordinates")?; let bytes = crate::vendor::maven_repo::verified_registry_file( @@ -764,8 +875,13 @@ async fn upstream_for_m2_copy(restore: &JarRestore<'_>, current: &[u8]) -> Resul restore.jar_leaf, ) .await?; - let current = Digests::of_bytes(current).map_err(|e| format!("the copy {e}"))?; - if !is_original_of(&bytes, ¤t, restore.files) { + let files = restore.files.clone(); + let (bytes, original) = blocking(move || { + let original = is_original_of(&bytes, ¤t, &files); + (bytes, original) + }) + .await; + if !original { return Err(format!( "the registry's {} is not the jar this copy was patched from", restore.jar_leaf @@ -862,14 +978,53 @@ pub async fn rollback_jar_swap( continue; } let gradle = maven_sidecars::is_gradle_hash_dir(dir); + const OFFLINE: &str = "--offline prevents downloading it again"; + let (socket_dir, files) = (restore.socket_dir.to_path_buf(), restore.files.clone()); // Why upstream could not stand in for a missing backup. - let original = match find_backup(restore, dir, ¤t).await { - Some(bytes) => Ok(bytes), - None if restore.offline => Err("--offline prevents downloading it again".to_string()), - None if gradle => upstream_for_gradle_copy(restore.purl, restore.jar_leaf, dir) - .await - .ok_or_else(|| "no upstream download matches its hash directory".to_string()), - None => upstream_for_m2_copy(restore, ¤t).await, + let (current, original) = if gradle { + let hash_dir = dir.clone(); + let found = blocking(move || gradle_backup(&socket_dir, &hash_dir, &files)).await; + let original = match found { + Some(bytes) => Ok(bytes), + None if restore.offline => Err(OFFLINE.to_string()), + None => upstream_for_gradle_copy(restore.purl, restore.jar_leaf, dir) + .await + .ok_or_else(|| "no upstream download matches its hash directory".to_string()), + }; + (current, original) + } else { + // The copy is read before anything is looked for or downloaded: + // one that cannot be compared has its own failure, not a + // missing backup's. + let (current, found) = blocking(move || { + let found = m2_backup(&socket_dir, ¤t, &files); + (current, found) + }) + .await; + let original = match found { + M2Original::Backup(bytes) => Ok(bytes), + M2Original::NoBackup(_) if restore.offline => Err(OFFLINE.to_string()), + M2Original::NoBackup(members) => upstream_for_m2_copy(restore, members).await, + M2Original::Unread(e) => { + let delete = format!( + "It was left as it is; delete {} so the build downloads the jar again.", + dir.display() + ); + result.error = Some(match e { + JarError::TooLarge(why) => format!( + "{JAR_TOO_LARGE}: {} holds this patch's members, but cannot be \ + compared with a backup or with upstream: {why}. {delete}", + path.display() + ), + JarError::Unreadable(why) => { + format!("Cannot roll back: {} - {why}. {delete}", path.display()) + } + }); + out.push(result); + continue; + } + }; + (current, original) }; let original = match original { Ok(bytes) => bytes, @@ -1348,7 +1503,7 @@ mod tests { let error = out[0].error.as_deref().unwrap(); // The copy's failure carries the contract's code and // says which members differ. - assert_eq!(copy_failure_code(error), Some(SERVICE_JAR_MISMATCH)); + assert_eq!(out[0].refusal.as_ref().unwrap().code, SERVICE_JAR_MISMATCH); assert!( error.starts_with( "jvm_agent_service_jar_mismatch: the patch service's jar differs from " @@ -1504,7 +1659,7 @@ mod tests { let out = out.unwrap(); let error = out[0].error.as_deref().unwrap(); assert!(!out[0].success); - assert_eq!(copy_failure_code(error), Some(JAR_TOO_LARGE)); + assert_eq!(out[0].refusal.as_ref().unwrap().code, JAR_TOO_LARGE); assert!( error.contains("lib-1.0.jar cannot be checked against the patch service's jar") && error.contains(limit), @@ -1516,27 +1671,6 @@ mod tests { } } - /// The reason codes a copy's failure may start with, and nothing else. - #[test] - fn copy_failure_code_reads_only_a_leading_code() { - assert_eq!( - copy_failure_code("jvm_jar_too_large: x.jar: it holds 5 entries"), - Some(JAR_TOO_LARGE) - ); - assert_eq!( - copy_failure_code("jvm_agent_service_jar_mismatch: the patch service's jar differs"), - Some(SERVICE_JAR_MISMATCH) - ); - for other in [ - "Cannot apply patch: x - jvm_jar_too_large: y", - "jvm_jar_too_large", - "jvm_jar_too_larger: x", - "", - ] { - assert_eq!(copy_failure_code(other), None, "{other}"); - } - } - /// A registry serving `jar` at lib-1.0.jar with the `.sha1` of `summed` /// (`None`: it publishes no checksum). async fn registry(jar: &[u8], summed: Option<&[u8]>) -> wiremock::MockServer { @@ -1649,6 +1783,61 @@ mod tests { } } + /// A rollback reads the copy before it looks for anything. A `~/.m2` + /// copy past the jar limits has that failure, not a missing backup's, + /// and nothing is downloaded for it. A Gradle copy's hash directory + /// names its original, so its backup is found without reading the copy. + #[tokio::test] + #[serial_test::serial] + async fn a_rollback_checks_the_copy_before_it_blames_a_missing_backup() { + use std::io::Read as _; + // The patched member, and 65 MiB of zeros deflated to kilobytes. + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + zw.start_file("META-INF/NOTICE.txt", opts).unwrap(); + zw.write_all(b"patched").unwrap(); + zw.start_file("a/zeros.bin", opts).unwrap(); + std::io::copy(&mut std::io::repeat(0).take(65 * 1024 * 1024), &mut zw).unwrap(); + let oversized = zw.finish().unwrap().into_inner(); + let original = pristine_jar(); + let files = record(); + let server = wiremock::MockServer::start().await; + let _registry = EnvGuard::set("SOCKET_MAVEN_REGISTRY", server.uri()); + + let d = tempfile::tempdir().unwrap(); + let socket = d.path().join(".socket"); + write_backup(&socket, &original).await.unwrap(); + let m2 = d.path().join("m2/com/example/lib/1.0"); + std::fs::create_dir_all(&m2).unwrap(); + std::fs::write(m2.join("lib-1.0.jar"), &oversized).unwrap(); + let back = rollback_jar_swap(&restore(&files, &socket, false), &[m2.clone()]).await; + let error = back[0].error.as_deref().unwrap(); + assert!(!back[0].success); + assert!( + error.starts_with("jvm_jar_too_large: ") + && error.contains("cannot be compared with a backup or with upstream: it inflates") + && error.contains(&format!("delete {} so the build", m2.display())) + && !error.contains("has no backup"), + "{error}" + ); + assert!(std::fs::read(m2.join("lib-1.0.jar")).unwrap() == oversized); + assert!( + server.received_requests().await.unwrap().is_empty(), + "nothing is downloaded for a copy that cannot be compared" + ); + + let hash_dir = d + .path() + .join(".gradle/caches/modules-2/files-2.1/com.example/lib/1.0") + .join(sha1_hex(&original)); + std::fs::create_dir_all(&hash_dir).unwrap(); + std::fs::write(hash_dir.join("lib-1.0.jar"), &oversized).unwrap(); + let back = rollback_jar_swap(&restore(&files, &socket, true), &[hash_dir.clone()]).await; + assert!(back[0].success, "{:?}", back[0].error); + assert!(std::fs::read(hash_dir.join("lib-1.0.jar")).unwrap() == original); + } + /// A copy that holds another revision of the patch (applied from another /// project) is neither side of this record: the apply fails that copy /// and says what the bytes may be and how to get back to the original. diff --git a/crates/socket-patch-core/src/vendor/jvm/gradle.rs b/crates/socket-patch-core/src/vendor/jvm/gradle.rs index 56f1f65d4..83d702082 100644 --- a/crates/socket-patch-core/src/vendor/jvm/gradle.rs +++ b/crates/socket-patch-core/src/vendor/jvm/gradle.rs @@ -187,23 +187,27 @@ pub fn committed_patched(read: ReadFn<'_>, c: &Coords<'_>) -> Vec { /// The first patched member (sorted) that the classifier artifact `bytes` /// holds with other content than the patched `jar`: a build consuming that -/// classifier stays unpatched (#533). -fn unpatched_copy(bytes: &[u8], jar: &[u8], patched: &[String]) -> Option { - // Only the patched members are inflated, within the jar limits: the - // wheel-sized reader this went through gave up on a large jar, which - // then passed unchecked. +/// classifier stays unpatched (#533). `Err` when either jar cannot be read +/// to tell: an artifact that is not checked is not taken for patched. +fn unpatched_copy(bytes: &[u8], jar: &[u8], patched: &[String]) -> Result, String> { + // Only the patched members are inflated, within the jar limits. use crate::patch::jar_members::Jar; - let mut copy = Jar::of_bytes(bytes).ok()?; - let mut patched_jar = Jar::of_bytes(jar).ok()?; + let mut copy = Jar::of_bytes(bytes).map_err(|e| e.to_string())?; + let mut patched_jar = Jar::of_bytes(jar).map_err(|e| format!("the patched jar: {e}"))?; let mut names: Vec<&String> = patched.iter().collect(); names.sort(); - names - .into_iter() - .find(|name| match copy.member_git_sha256(name) { - Ok(Some(held)) => patched_jar.member_git_sha256(name).ok().flatten() != Some(held), - _ => false, - }) - .cloned() + for name in names { + let Some(held) = copy.member_git_sha256(name).map_err(|e| e.to_string())? else { + continue; + }; + let patched = patched_jar + .member_git_sha256(name) + .map_err(|e| format!("the patched jar: {e}"))?; + if patched != Some(held) { + return Ok(Some(name.clone())); + } + } + Ok(None) } /// `(classifier, extension)` of a tree file name `--.`. @@ -482,16 +486,20 @@ fn plan_as( } for x in patch.extra_artifacts { files.push((x.file_name(a, v), &x.bytes)); - if let Some(member) = unpatched_copy(&x.bytes, patch.jar, patch.patched_members) { - warnings.push(degraded( - "classifier_unpatched_copy", - format!( - "{} carries an unpatched copy of {member}; a build consuming that \ - classifier stays unpatched", - x.file_name(a, v) - ), - )); - } + let detail = match unpatched_copy(&x.bytes, patch.jar, patch.patched_members) { + Ok(None) => continue, + Ok(Some(member)) => format!( + "{} carries an unpatched copy of {member}; a build consuming that classifier \ + stays unpatched", + x.file_name(a, v) + ), + Err(why) => format!( + "{} could not be checked for unpatched copies of the patched members ({why}); \ + a build consuming that classifier may stay unpatched", + x.file_name(a, v) + ), + }; + warnings.push(degraded("classifier_unpatched_copy", detail)); } files.sort_by(|x, y| x.0.cmp(&y.0)); files.dedup_by(|x, y| x.0 == y.0); @@ -5298,6 +5306,23 @@ mod tests { &p.coords(), ) }; + // A classifier jar that cannot be read is not taken for patched. + let unreadable = [extra("all", b"not a zip archive")]; + let p = JvmPatch { + jar: &jar, + extra_artifacts: &unreadable, + patched_members: &patched, + ..patch() + }; + let plan = run(&files, &p).unwrap(); + assert!( + plan.warnings.iter().any(|w| w.code == DEGRADED + && w.detail.starts_with("reason: classifier_unpatched_copy: ") + && w.detail + .contains("could not be checked for unpatched copies")), + "{:?}", + plan.warnings + ); for (all, unpatched) in [ (zip_of(&[(VULN, b"VULNERABLE"), ("A.class", b"A")]), true), (zip_of(&[(VULN, b"PATCHED")]), false), diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index 20bff82a9..fea79c99c 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -1022,7 +1022,7 @@ async fn vendor_maven_jvm( let mut warnings: Vec = gate_pass.warnings; let committed = jvm_committed_patch(shape, purl, project_root, record).await; let was_committed = committed.is_some(); - let (jar_bytes, mut pom_bytes, mut module_bytes, mut extras, mut result) = match committed { + let (mut jar_bytes, mut pom_bytes, mut module_bytes, mut extras, mut result) = match committed { Some(((jar, pom, module), extras)) => ( jar, pom, @@ -1060,29 +1060,75 @@ async fn vendor_maven_jvm( let online = service.is_some_and(|s| !s.offline); // Everything the patch does not touch must be upstream's, checked - // against the registry-verified upstream jar before anything is - // written: on a first vendoring (always online: the jar comes from the - // service) as on an online re-run over a committed tree. A service jar - // built from another base, or one that adds or drops a class, is never - // committed and wired. + // before anything is written: on a first vendoring (always online: the + // jar comes from the service) as on an online re-run over a committed + // tree. A service jar built from another base, or one that adds or + // drops a class, is never committed and wired. + // + // The baseline is the registry-verified upstream jar: a cached copy the + // registry's checksum vouches for, else the registry's own download + // held to it (the jar agent mode patched in `~/.m2` is no baseline). + // A re-run needs that one, as it always did. A first vendoring must not + // fail because the registry cannot be reached while the patch service + // can: it falls back to the jar in the build's local repository (the + // trust agent mode places in the installed jar), and with no jar at all + // vendors as served, saying the comparison was not made. if online { - let upstream = match acquire_jvm_artifact(&local, &gav, None, "jar", service).await { - Ok(bytes) => bytes, - // A cached copy the registry's checksum does not vouch for (the - // jar agent mode patched in `~/.m2`, say) is no baseline: the - // registry's own jar is, held to the same checksum. - Err(_) => { - match acquire_jvm_artifact(&LocalSources::none(), &gav, None, "jar", service).await - { - Ok(bytes) => bytes, - Err(e) => return refused("vendor_jvm_upstream_unavailable", e), - } + let verified = match acquire_jvm_artifact(&local, &gav, None, "jar", service).await { + Ok(bytes) => Ok(bytes), + Err(_) => acquire_jvm_artifact(&LocalSources::none(), &gav, None, "jar", service).await, + }; + let baseline = match verified { + Ok(bytes) => Some(bytes), + Err(e) if was_committed => return refused("vendor_jvm_upstream_unavailable", e), + Err(why) => { + let cached = local.find(&gav, None, "jar", false).await.ok().flatten(); + local + .unverified + .store(true, std::sync::atomic::Ordering::Relaxed); + let jar = layout::file_name(&artifact_id, &version, None, "jar"); + warnings.push(VendorWarning::new( + "vendor_jvm_upstream_unverified", + match cached { + Some(_) => format!( + "no registry-verified copy of {jar} could be had ({why}), so the \ + members the patch does not touch were compared with the jar in the \ + local repository instead" + ), + None => format!( + "no upstream copy of {jar} could be had ({why}), so the members the \ + patch does not touch were not compared with upstream; the patch \ + service's jar was vendored as served. Run `socket-patch vendor` \ + again when the registry can be reached to make the comparison" + ), + }, + )); + cached } }; - if let Err((code, detail)) = - verify_unpatched_jar_members(&upstream, &jar_bytes, record, was_committed) - { - return refused(code, detail); + if let Some(upstream) = baseline { + let names: Vec = record + .files + .keys() + .map(|k| crate::patch::apply::normalize_file_path(k).to_string()) + .collect(); + // Off the async workers: a pass inflates up to the jar limits. + let compared = tokio::task::spawn_blocking(move || { + let verdict = + verify_unpatched_jar_members(&upstream, &jar_bytes, &names, was_committed); + (jar_bytes, verdict) + }) + .await; + let Ok((bytes, verdict)) = compared else { + return refused( + "vendor_prebuilt_integrity_mismatch", + "the comparison with the upstream jar did not finish".to_string(), + ); + }; + jar_bytes = bytes; + if let Err((code, detail)) = verdict { + return refused(code, detail); + } } } if online && was_committed { @@ -1481,14 +1527,14 @@ async fn acquire_classifier( } /// The patched jar (the service's on a first vendoring, the committed one -/// on a re-run) must be the verified upstream jar outside the record's -/// members and signature files: every other member a JVM would load, the +/// on a re-run) must be the upstream jar outside the record's members +/// (`patched_members`, as a jar spells them) and signature files: every other member a JVM would load, the /// same in both ([`crate::patch::jar_members`], whose limits also bound /// the read). `Err` is the refusal's `(code, detail)`. fn verify_unpatched_jar_members( upstream: &[u8], patched: &[u8], - record: &PatchRecord, + patched_members: &[String], committed: bool, ) -> Result<(), (&'static str, String)> { use crate::patch::jar_members::{unpatched_difference, Digests, JarError}; @@ -1511,11 +1557,7 @@ fn verify_unpatched_jar_members( }; let original = read(upstream, "the upstream jar")?; let candidate = read(patched, whose)?; - let names: Vec<&str> = record - .files - .keys() - .map(|k| crate::patch::apply::normalize_file_path(k)) - .collect(); + let names: Vec<&str> = patched_members.iter().map(String::as_str).collect(); let difference = unpatched_difference(&original, &candidate, &names); if !difference.is_empty() { return Err(( @@ -4389,6 +4431,70 @@ mod tests { } } + /// A registry that cannot be reached while the patch service can must + /// not stop a first vendoring. The jar in the build's local repository + /// is then the baseline, a mismatch against it is still a refusal, and + /// with no jar at all the service's jar is vendored as served. Each + /// says so, and the entry is recorded as not registry-verified. + #[tokio::test] + #[serial_test::serial] + async fn a_first_vendoring_without_the_registry_falls_back_and_says_so() { + use crate::patch::jar_members::testing::jar_with_modes; + let tampered = jar_with_modes(&[ + ("META-INF/MANIFEST.MF", b"Manifest-Version: 1.0\n", None), + (JAR_FILE, PATCHED, None), + ( + "org/apache/commons/text/StringSubstitutor.class", + b"another release's class", + None, + ), + ]); + // (the service's jar, a jar in the local repository, the outcome) + for (served, local_jar, refusal) in [ + (make_jar(PATCHED), true, None), + (tampered.clone(), true, Some("1 changed")), + (make_jar(PATCHED), false, None), + (tampered, false, None), + ] { + let (dir, blobs, installed, record) = reactor_fixture(local_jar).await; + let root = dir.path(); + // The service answers; the registry routes are all 404. + let server = mount_granted_jar(&served).await; + let _registry = EnvGuard::set("SOCKET_MAVEN_REGISTRY", server.uri()); + let cfg = service_cfg( + Some(&server.uri()), + crate::vendor::VendorSource::Service, + false, + ); + let outcome = run_jvm(root, &blobs, &installed, &record, Some(&cfg)).await; + if let Some(difference) = refusal { + let (code, detail) = unwrap_refused(outcome); + assert_eq!(code, "vendor_prebuilt_integrity_mismatch"); + assert!(detail.contains(difference), "{detail}"); + assert!(!root.join(".socket").exists()); + continue; + } + let (result, entry, warnings) = unwrap_done(outcome); + assert!(result.success, "local_jar={local_jar}: {:?}", result.error); + assert_eq!(upstream_status(&entry.expect("entry")), "local_unverified"); + let said: Vec<&str> = warnings + .iter() + .filter(|w| w.code == "vendor_jvm_upstream_unverified") + .map(|w| w.detail.as_str()) + .collect(); + assert_eq!(said.len(), 1, "{warnings:?}"); + assert!( + said[0].contains(if local_jar { + "were compared with the jar in the local repository instead" + } else { + "were not compared with upstream; the patch service's jar was vendored as served" + }), + "{}", + said[0] + ); + } + } + /// The jar agent mode patched in `~/.m2` is not upstream's: the first /// vendoring compares with the registry's own jar instead of refusing. #[tokio::test] diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index ebda8b60a..92bb48c12 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -940,6 +940,29 @@ pub async fn describe_artifact_failure( }; format!("Bun workspace copy {mirror} {cause} ({reason}){canonical}; {repair}") } + ArtifactHealth::Corrupt { reason } if reason == ARTIFACT_TOO_LARGE => { + // Which limit: the archive's own (entries, central directory), + // else a patched member's inflated size. + let jar = project_root.join(path); + let limit = tokio::task::spawn_blocking(move || { + let (file, metadata) = crate::utils::fs::open_regular_file_sync(&jar).ok()?; + let reader = std::io::BufReader::new(file); + match crate::patch::jar_members::Jar::open(reader, metadata.len()) { + Err(e) if e.is_too_large() => Some(e.to_string()), + _ => None, + } + }) + .await + .ok() + .flatten() + .unwrap_or_else(|| { + "a patched member inflates past what a jar of its size may".to_string() + }); + format!( + "committed artifact {path} is past the limits jars are read within: {limit} \ + ({reason}); {repair}" + ) + } ArtifactHealth::Corrupt { reason } => { let cause = match reason.as_str() { "vendor_sha256_mismatch" => "does not match the sha256 in the vendor ledger", diff --git a/docs/design/maven-vendoring.md b/docs/design/maven-vendoring.md index 26998e815..2a4de8ae4 100644 --- a/docs/design/maven-vendoring.md +++ b/docs/design/maven-vendoring.md @@ -335,7 +335,7 @@ tree is refused nowhere and degraded nowhere. ## Artifact identity and integrity -Service jars pass transfer-integrity and patched-member checks. The server constructs jars and strips invalidated signatures; the CLI never rebuilds jar archives. Online, before anything is written, the jar (the service's on a first vendoring, the committed one on a re-run) is also compared with the registry-verified upstream jar: every entry the JVM would load, whatever unix mode it carries, must hold the same content outside the record's members and signature files, or the run is refused with `vendor_prebuilt_integrity_mismatch`. A cached upstream jar the registry's checksum does not vouch for (one agent mode patched in `~/.m2`) is not the baseline; the registry's own download is. Jars are read member by member within fixed limits (200,000 entries; 1 GiB and 100 times the jar's size inflated per pass); one past them is `vendor_artifact_too_large`. Online vendoring authenticates upstream POM and Gradle module metadata against registry sidecars. A POM or module that a local cache holds and the registry gives no checksum for is the file the build resolved: it is used, and the entry is recorded unverified (`vendor_jvm_upstream_unverified`), as an offline one is. Bytes that differ from a published checksum are refused. Metadata fetches use a separate HTTP client and do not send Socket API credentials. `SOCKET_MAVEN_REGISTRY` supports a private mirror. +Service jars pass transfer-integrity and patched-member checks. The server constructs jars and strips invalidated signatures; the CLI never rebuilds jar archives. Online, before anything is written, the jar (the service's on a first vendoring, the committed one on a re-run) is also compared with the registry-verified upstream jar: every entry the JVM would load, whatever unix mode it carries, must hold the same content outside the record's members and signature files, or the run is refused with `vendor_prebuilt_integrity_mismatch`. A cached upstream jar the registry's checksum does not vouch for (one agent mode patched in `~/.m2`) is not the baseline; the registry's own download is. When the registry cannot be reached, a first vendoring falls back to the local repository's jar, then to no comparison at all, and reports which with `vendor_jvm_upstream_unverified`. Jars are read member by member within fixed limits (200,000 entries; 1 GiB and 100 times the jar's size inflated per pass); one past them is `vendor_artifact_too_large`. Online vendoring authenticates upstream POM and Gradle module metadata against registry sidecars. A POM or module that a local cache holds and the registry gives no checksum for is the file the build resolved: it is used, and the entry is recorded unverified (`vendor_jvm_upstream_unverified`), as an offline one is. Bytes that differ from a published checksum are refused. Metadata fetches use a separate HTTP client and do not send Socket API credentials. `SOCKET_MAVEN_REGISTRY` supports a private mirror. Maven v5 does not enable Resolver trusted-checksum processors at build time. Those processors crash some release reactors and system-scope dependencies, diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 5e4aba452..efd3e4cf2 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1099,13 +1099,28 @@ the project's `.mvn/maven.config`, or in `MAVEN_OPTS`, in that order, then (`MAVEN_HOME` or `M2_HOME`), then `.m2/repository` in `user.home`. `M2_HOME` itself never names a local repository. On Windows `user.home` is `USERPROFILE`, not `HOME`. -The `.mvn/maven.config` read is the one Maven's launcher finds from the project -directory: in the nearest directory at or above it that holds a `.mvn` directory. A -line is one argument (`#` starts a comment), the last `-Dmaven.repo.local=` wins, -`${session.rootDirectory}`, `${session.topDirectory}`, `${user.home}` and -`${env.NAME}` are filled in, and a relative path is taken from the project directory, -where Maven would run. A `--global` run reads no project's config. Maven before 3.9 -does not read `MAVEN_ARGS`; socket-patch reads it whatever Maven is installed. +`.mvn/maven.config` is read only for a Maven build, where Maven itself reads it: a +project with a `pom.xml` and no Gradle or Scala-tool build beside it. A Gradle +build's `mavenLocal()` never reads the file, so a Gradle project below a directory +that holds one keeps the environment's repository. The file is the one Maven's +launcher finds from the project directory: in the nearest directory at or above it +that holds a `.mvn` directory. It is read the way the project's Maven reads it: + +- Maven before 3.9 splits the whole file on whitespace and fills in nothing. +- Maven 3.9 and later takes each line as one argument (`#` starts a comment), so a + value runs to the end of its line, and from 3.9.2 fills in + `${session.rootDirectory}`, `${session.topDirectory}`, `${user.home}` and + `${env.NAME}`. + +For both, the last `-Dmaven.repo.local=` wins, a placeholder nothing defines stays in +the path as written, and a relative path (an empty one included) is taken from the +project directory, where Maven runs. The Maven Wrapper's version says which reading +applies. Without a wrapper, when the two readings differ, the one whose directory +exists is used. When both exist no repository is guessed at: nothing in `~/.m2` is +scanned or patched and the run warns `maven_local_repository_undetermined`; set +`MAVEN_REPO_LOCAL` to choose. A `--global` run reads no project's config. Maven +before 3.9 does not read `MAVEN_ARGS`; socket-patch reads it whatever Maven is +installed. A Gradle-only build reads `~/.m2` only through `mavenLocal()`. Scan looks for it in every settings, build, `buildSrc`, included-build, applied and init script, including From 624838d44a503baeec5aee871925e4d1d5c91f65 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 17:01:43 -0500 Subject: [PATCH 3/5] Read a copy within the jar limits from its first parse apply_jar_swap and rollback_jar_swap verified a copy's patched members through the zip reader directly, before the bounded reader saw the jar: the central directory was parsed, and allocated for, whatever the end records declared, and a member was inflated with no budget. A copy past the limits, or one with a hostile end record, could exhaust memory there instead of failing as jvm_jar_too_large, and a ~/.m2 rollback could go on to the registry afterwards. The member check now goes through the bounded reader, so the limits on the entry count and the central directory are held to the end records before anything parses the directory, and members are inflated within the pass's budget. A copy past a limit is refused there: jvm_jar_too_large on apply, with the run warning, and on rollback, before any backup is read or anything is downloaded. The unbounded member hasher has no caller left and is removed. Co-Authored-By: Claude Fable 5.2 --- .../socket-patch-core/src/hash/git_sha256.rs | 45 ----- .../src/patch/jar_members.rs | 32 ++++ crates/socket-patch-core/src/patch/jvm_jar.rs | 160 +++++++++++++++++- 3 files changed, 183 insertions(+), 54 deletions(-) diff --git a/crates/socket-patch-core/src/hash/git_sha256.rs b/crates/socket-patch-core/src/hash/git_sha256.rs index 515a4a34b..16e5e583c 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 index 612179554..1eca307e3 100644 --- a/crates/socket-patch-core/src/patch/jar_members.rs +++ b/crates/socket-patch-core/src/patch/jar_members.rs @@ -452,6 +452,38 @@ mod tests { const OLD_ENTRIES: usize = 10_000; const OLD_BYTES: u64 = 64 * 1024 * 1024; + /// A member's git hash is the buffered hash of its bytes, stored, + /// deflated or empty; an absent member is `None`. + #[test] + fn a_member_hashes_as_its_bytes() { + 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 bytes = out.finish().unwrap().into_inner(); + let mut jar = Jar::of_bytes(&bytes).unwrap(); + for (name, content, _) in &members { + assert_eq!( + jar.member_git_sha256(name).unwrap().unwrap(), + compute_git_sha256_from_bytes(content), + "{name}" + ); + } + assert_eq!(jar.member_git_sha256("missing.txt").unwrap(), None); + } + #[test] fn a_jar_over_the_wheel_limits_is_read_member_by_member() { let bytes = big_jar( diff --git a/crates/socket-patch-core/src/patch/jvm_jar.rs b/crates/socket-patch-core/src/patch/jvm_jar.rs index 8c72e29aa..be1a0ad28 100644 --- a/crates/socket-patch-core/src/patch/jvm_jar.rs +++ b/crates/socket-patch-core/src/patch/jvm_jar.rs @@ -30,13 +30,13 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; use crate::crawlers::gradle_cache; -use crate::hash::git_sha256::{compute_git_sha256_from_bytes, zip_member_git_sha256}; +use crate::hash::git_sha256::compute_git_sha256_from_bytes; use crate::manifest::schema::PatchFileInfo; use crate::patch::apply::{ apply_file_patch_at, files_in_order, normalize_file_path, ApplyResult, VerifyResult, VerifyStatus, }; -use crate::patch::jar_members::{unpatched_difference, Digests, JarError}; +use crate::patch::jar_members::{unpatched_difference, Digests, Jar, JarError}; use crate::patch::rollback::{RollbackResult, VerifyRollbackResult, VerifyRollbackStatus}; use crate::patch::sidecars::{self, maven as maven_sidecars}; use crate::utils::purl::{parse_maven_purl, purl_qualifier}; @@ -132,19 +132,59 @@ pub fn classify(purl: &str, files: &HashMap) -> RecordSha /// key order: a member at its `afterHash` is `AlreadyPatched`, at its /// `beforeHash` `Ready`, anything else `HashMismatch`; an absent member is /// `NotFound` (or `Ready` when the patch adds it). An unreadable jar makes -/// every member `NotFound`. +/// every member `NotFound`, and so does one past the jar limits (a caller +/// that tells the two apart asks [`member_statuses`]). pub fn verify_member_bytes( jar: &[u8], files: &HashMap, ) -> Vec { - let mut archive = zip::ZipArchive::new(std::io::Cursor::new(jar)).ok(); + member_statuses(jar, files).unwrap_or_else(|_| statuses(files, |_| None)) +} + +/// [`verify_member_bytes`], read within the jar limits +/// ([`super::jar_members`]) from the first byte: the limits on the +/// archive's entry count and central directory are held to its end records +/// before anything parses the directory, and a member is inflated only +/// within the pass's budget. `Err` is a jar past a limit; nothing of it was +/// parsed or inflated beyond that limit. +fn member_statuses( + jar: &[u8], + files: &HashMap, +) -> Result, JarError> { + let mut archive = match Jar::of_bytes(jar) { + Ok(archive) => Some(archive), + Err(e) if e.is_too_large() => return Err(e), + Err(_) => None, + }; + let mut too_large = None; + let results = statuses(files, |member| { + match archive.as_mut()?.member_git_sha256(member) { + Ok(hash) => hash, + Err(e) => { + if e.is_too_large() { + too_large.get_or_insert(e); + } + None + } + } + }); + match too_large { + Some(e) => Err(e), + None => Ok(results), + } +} + +/// The verify result of each record member, given its current git-blob +/// hash in the jar (`None` when the jar does not hold it). +fn statuses( + files: &HashMap, + mut hash_of: impl FnMut(&str) -> Option, +) -> Vec { files_in_order(files) .into_iter() .map(|(key, info)| { let member = normalize_file_path(key); - let hash = archive - .as_mut() - .and_then(|a| zip_member_git_sha256(a, member)?.ok()); + let hash = hash_of(member); let (status, current) = match hash { None if info.before_hash.is_empty() => (VerifyStatus::Ready, None), None => (VerifyStatus::NotFound, None), @@ -504,7 +544,25 @@ async fn swap_copies( continue; } }; - result.files_verified = verify_member_bytes(&original, swap.files); + // The bounded reader is the first thing to parse the copy: one past + // the jar limits is refused here, before anything allocates for it. + result.files_verified = match member_statuses(&original, swap.files) { + Ok(verified) => verified, + Err(e) => { + let refusal = SwapRefusal::new( + JAR_TOO_LARGE, + format!( + "{} cannot be read within the jar limits: {e}. It was left as it is. \ + `--mode hosted` does not read the jar.", + dir.join(swap.jar_leaf).display() + ), + ); + result.error = Some(format!("{}: {}", refusal.code, refusal.message)); + refusals.insert(results.len(), refusal); + results.push(result); + continue; + } + }; match aggregate(&result.files_verified) { VerifyStatus::AlreadyPatched => result.success = true, VerifyStatus::Ready => pending.push((results.len(), original)), @@ -955,7 +1013,22 @@ pub async fn rollback_jar_swap( continue; } }; - let verified = verify_member_bytes(¤t, restore.files); + // The bounded reader is the first thing to parse the copy: one past + // the jar limits fails here, before any backup is read or anything + // is downloaded. + let verified = match member_statuses(¤t, restore.files) { + Ok(verified) => verified, + Err(e) => { + result.error = Some(format!( + "{JAR_TOO_LARGE}: {} cannot be read within the jar limits: {e}. It was \ + left as it is; delete {} so the build downloads the jar again.", + path.display(), + dir.display() + )); + out.push(result); + continue; + } + }; result.files_verified = rollback_verify(&verified); let all = |s: VerifyStatus| verified.iter().all(|v| v.status == s); if all(VerifyStatus::Ready) { @@ -1838,6 +1911,75 @@ mod tests { assert!(std::fs::read(hash_dir.join("lib-1.0.jar")).unwrap() == original); } + /// The bounded reader is the first thing that parses a copy, on apply + /// and on rollback. This archive's end records declare 200,001 entries + /// and it holds no central directory at all: only a reader that holds + /// the records to the limit before parsing can call it too large. The + /// apply needs no service for it, and the rollback reads no backup and + /// downloads nothing. + #[tokio::test] + #[serial_test::serial] + async fn a_copy_past_the_limits_is_refused_before_it_is_parsed() { + let entries = 200_001u64; + let mut hostile = vec![0u8; entries as usize * 46]; + let at = hostile.len() as u64; + hostile.extend_from_slice(b"PK\x06\x06"); + hostile.extend_from_slice(&[0; 20]); + hostile.extend_from_slice(&entries.to_le_bytes()); + hostile.extend_from_slice(&entries.to_le_bytes()); + hostile.extend_from_slice(&(entries * 46).to_le_bytes()); + hostile.extend_from_slice(&[0; 8]); + hostile.extend_from_slice(b"PK\x06\x07\0\0\0\0"); + hostile.extend_from_slice(&at.to_le_bytes()); + hostile.extend_from_slice(&1u32.to_le_bytes()); + hostile.extend_from_slice(b"PK\x05\x06\0\0\0\0"); + hostile.extend_from_slice(&[0xff; 12]); + hostile.extend_from_slice(&[0; 2]); + let limit = "it holds 200001 entries, over the limit of 200000"; + let files = record(); + assert_eq!( + member_statuses(&hostile, &files).unwrap_err().to_string(), + limit + ); + // The callers that only ask for statuses see nothing verified. + assert_eq!( + aggregate(&verify_member_bytes(&hostile, &files)), + VerifyStatus::NotFound + ); + + let server = wiremock::MockServer::start().await; + let _registry = EnvGuard::set("SOCKET_MAVEN_REGISTRY", server.uri()); + let d = tempfile::tempdir().unwrap(); + let socket = d.path().join(".socket"); + write_backup(&socket, &pristine_jar()).await.unwrap(); + let copy = d.path().join("m2/com/example/lib/1.0"); + std::fs::create_dir_all(©).unwrap(); + std::fs::write(copy.join("lib-1.0.jar"), &hostile).unwrap(); + + let out = apply_jar_swap(&swap(&files, &socket, false), &[copy.clone()], None) + .await + .unwrap(); + let refusal = out[0].refusal.as_ref().expect("a coded refusal"); + assert_eq!(refusal.code, JAR_TOO_LARGE); + assert!(refusal.message.contains(limit), "{}", refusal.message); + assert!(!out[0].success); + + let back = rollback_jar_swap(&restore(&files, &socket, false), &[copy.clone()]).await; + let error = back[0].error.as_deref().unwrap(); + assert!( + !back[0].success + && error.starts_with("jvm_jar_too_large: ") + && error.contains(limit) + && !error.contains("has no backup"), + "{error}" + ); + assert!(std::fs::read(copy.join("lib-1.0.jar")).unwrap() == hostile); + assert!( + server.received_requests().await.unwrap().is_empty(), + "nothing is downloaded for a copy past the limits" + ); + } + /// A copy that holds another revision of the patch (applied from another /// project) is neither side of this record: the apply fails that copy /// and says what the bytes may be and how to get back to the original. From a4079dff70baae7e8180d87d8f54a8f488824426 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 23:44:50 -0500 Subject: [PATCH 4/5] Check the end record the zip reader takes, wherever it sits The check before the parse read the last 64 KiB of the file and the 56 bytes at the zip64 locator's offset. The zip reader does not take the end record from there: it looks for one backwards through the whole file, finds a zip64 record forwards from where the locator points, and falls back to an earlier end record when a directory does not parse. With bytes appended after the end record, an archive of 200,001 entries passed the check and was parsed whole before the count refused it. The check now walks as the reader does. It finds the last end record the reader can take and holds it to the limits. The reader is then shown zeros below that record's central directory while it opens the archive, so the only records it can fall back to are in the directory itself, and each of those is held to the limits as well. A record the reader would pass over is passed over; after 64 of them the archive is given up, since each costs a search of the file. An end record in a member's data, as a jar stored inside a fat jar has, is below the outer directory: the reader cannot take it, so it is not looked at, whatever it declares. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 11 +- .../src/patch/jar_members.rs | 442 ++++++++++++++---- crates/socket-patch-core/src/patch/jvm_jar.rs | 18 +- 3 files changed, 360 insertions(+), 111 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 84eb9cb30..59f439d8e 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2846,8 +2846,8 @@ a committed tree needs the registry-verified jar, 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 archive's end records before the -directory is parsed), and per pass over one jar 1 GiB inflated and at most 100 times +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 @@ -3232,8 +3232,11 @@ 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 archive's end records before the -directory is parsed, so a directory of millions of records is refused unread), and +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 diff --git a/crates/socket-patch-core/src/patch/jar_members.rs b/crates/socket-patch-core/src/patch/jar_members.rs index 1eca307e3..73993b39c 100644 --- a/crates/socket-patch-core/src/patch/jar_members.rs +++ b/crates/socket-patch-core/src/patch/jar_members.rs @@ -32,11 +32,24 @@ //! //! 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 records +//! 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 those records declare: a directory of millions of tiny +//! 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 @@ -55,6 +68,8 @@ use std::collections::BTreeMap; use std::io::{Read, Seek, SeekFrom}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; use sha2::{Digest, Sha256}; @@ -106,7 +121,7 @@ fn inflate_budget(archive_len: u64) -> u64 { /// One pass over a jar: the open archive and what is left of its inflate /// budget. pub(crate) struct Jar { - zip: zip::ZipArchive, + zip: zip::ZipArchive>, archive_len: u64, budget: u64, left: u64, @@ -122,9 +137,15 @@ impl<'a> Jar> { impl Jar { /// A pass over the archive `reader` holds, `archive_len` bytes long. pub(crate) fn open(mut reader: R, archive_len: u64) -> Result { - check_declared_directory(&mut reader, archive_len)?; - let zip = zip::ZipArchive::new(reader) + 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}", @@ -221,30 +242,132 @@ impl Jar { } } -/// Hold what an archive's end records declare of its central directory to -/// [`MAX_ENTRIES`] and [`MAX_CENTRAL_DIRECTORY_BYTES`], before the zip reader -/// parses (and allocates for) it. The reader may settle on any record that -/// looks like the end of the directory, so every `PK\x05\x06` in the last -/// 64 KiB is checked, with the zip64 record its locator points at and any -/// zip64 record in that tail. -fn check_declared_directory(reader: &mut R, len: u64) -> Result<(), JarError> { - const END: &[u8] = b"PK\x05\x06"; - const END64: &[u8] = b"PK\x06\x06"; - const LOCATOR: &[u8] = b"PK\x06\x07"; +/// A reader that shows zeros below `floor`, for as long as `floor` is set: +/// what the zip reader is given while it opens an archive, so that it +/// cannot take an end record [`admit`] did not look at. +pub(crate) struct Veiled { + inner: R, + floor: Arc, +} + +impl Read for Veiled { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let floor = self.floor.load(Ordering::Relaxed); + if floor == 0 { + return self.inner.read(buf); + } + let at = self.inner.stream_position()?; + if at >= floor { + return self.inner.read(buf); + } + let hidden = (floor - at).min(buf.len() as u64) as usize; + buf[..hidden].fill(0); + self.inner.seek(SeekFrom::Current(hidden as i64))?; + Ok(hidden) + } +} + +impl Seek for Veiled { + fn seek(&mut self, to: SeekFrom) -> std::io::Result { + self.inner.seek(to) + } +} + +/// End records [`admit`] passes over before it gives the archive up. +const MAX_RECORDS_PASSED_OVER: usize = 64; + +const END: &[u8; 4] = b"PK\x05\x06"; +const END64: &[u8; 4] = b"PK\x06\x06"; +const LOCATOR: &[u8; 4] = b"PK\x06\x07"; +const CENTRAL: &[u8; 4] = b"PK\x01\x02"; + +fn le(bytes: &[u8]) -> u64 { + bytes + .iter() + .rev() + .fold(0u64, |n, b| (n << 8) | u64::from(*b)) +} + +/// `bytes` at `at`, when the archive holds them. +fn read_at( + reader: &mut R, + at: u64, + len: u64, +) -> std::io::Result> { + if at.checked_add(N as u64).is_none_or(|end| end > len) { + return Ok(None); + } + let mut bytes = [0u8; N]; + reader.seek(SeekFrom::Start(at))?; + reader.read_exact(&mut bytes)?; + Ok(Some(bytes)) +} + +/// The offsets of `magic` in `[from, to)`, a window at a time: the last +/// first when `backwards`. `visit` returns `true` to stop. +fn scan( + reader: &mut R, + magic: &[u8; 4], + (from, to): (u64, u64), + backwards: bool, + mut visit: impl FnMut(&mut R, u64) -> Result, +) -> Result<(), JarError> { + const WINDOW: u64 = 64 * 1024; + let unread = |e: std::io::Error| JarError::Unreadable(format!("it cannot be read ({e})")); + let (mut low, mut high) = (from, to); + while high.saturating_sub(low) >= 4 { + // Windows overlap by three bytes, so a magic across an edge is seen. + let (start, end) = match backwards { + true => (high.saturating_sub(WINDOW).max(low), high), + false => (low, low.saturating_add(WINDOW).min(high)), + }; + let mut window = vec![0u8; (end - start) as usize]; + reader.seek(SeekFrom::Start(start)).map_err(unread)?; + reader.read_exact(&mut window).map_err(unread)?; + let mut hits: Vec = window + .windows(4) + .enumerate() + .filter(|(_, bytes)| bytes == magic) + .map(|(i, _)| start + i as u64) + .collect(); + if backwards { + hits.reverse(); + } + for hit in hits { + if visit(reader, hit)? { + return Ok(()); + } + } + match backwards { + true if start == low => break, + true => high = start + 3, + false if end == high => break, + false => low = end - 3, + } + } + Ok(()) +} + +/// Decide, before the zip reader parses anything, which end record it can +/// take from the archive `reader` holds, and hold what that record declares +/// to [`MAX_ENTRIES`] and [`MAX_CENTRAL_DIRECTORY_BYTES`]. Returns the +/// offset of that record's central directory: the reader is shown zeros +/// below it while it opens the archive ([`Veiled`]), so the only end +/// records it can fall back to are in the directory itself, and those are +/// held to the limits here as well. +/// +/// The walk is the reader's own (`zip` 8.6, `find_central_directory`): end +/// records from the end of the file backwards, whatever follows them; a +/// zip32 record is taken when a central header is found forwards from the +/// offset it declares; a record that may be zip64 and has a locator before +/// it is taken with the first zip64 record, forwards from where the locator +/// points, that ends where the locator begins. A record the reader would +/// pass over is passed over here, up to [`MAX_RECORDS_PASSED_OVER`] of +/// them. An archive with no record it could take is handed over unveiled: +/// every end record in it was looked at. +fn admit(reader: &mut R, len: u64) -> Result { let unread = |e: std::io::Error| JarError::Unreadable(format!("its end cannot be read ({e})")); - let le = |bytes: &[u8]| { - bytes - .iter() - .rev() - .fold(0u64, |n, b| (n << 8) | u64::from(*b)) - }; let within = |entries: u64, directory: u64| { - // A record declaring more than the archive can hold (a central - // record is 46 bytes at least) is not its end record: bytes that - // happen to spell the signature, which the reader passes over too. - if directory > len || entries > len / 46 { - return Ok(()); - } if entries > MAX_ENTRIES as u64 { return Err(JarError::TooLarge(format!( "it holds {entries} entries, over the limit of {MAX_ENTRIES}" @@ -259,38 +382,92 @@ fn check_declared_directory(reader: &mut R, len: u64) -> Result< } Ok(()) }; - // An end record, its comment (at most 64 KiB) and a zip64 locator and - // record before it. - let tail_len = len.min(22 + 65_535 + 20 + 56); - reader - .seek(SeekFrom::Start(len - tail_len)) - .map_err(unread)?; - let mut tail = vec![0u8; tail_len as usize]; - reader.read_exact(&mut tail).map_err(unread)?; - for at in 0..tail.len() { - let rest = &tail[at..]; - if rest.len() >= 56 && rest.starts_with(END64) { - within(le(&rest[32..40]), le(&rest[40..48]))?; + // Nothing below `floor` is looked at once a record has been taken. + let mut floor: Option = None; + let mut passed_over = 0; + scan(reader, END, (0, len), true, |reader, at| { + let bottom = floor.unwrap_or(0); + if at < bottom { + return Ok(true); } - if rest.len() < 22 || !rest.starts_with(END) { - continue; + // The record and its comment must fit the file. + let Some(end) = read_at::<_, 22>(reader, at, len).map_err(unread)? else { + return Ok(false); + }; + if at + 22 + le(&end[20..22]) > len { + return Ok(false); } - within(le(&rest[10..12]), le(&rest[12..16]))?; - if at < 20 || !tail[at - 20..].starts_with(LOCATOR) { - continue; + let (on_disk, total) = (le(&end[8..10]), le(&end[10..12])); + let (size, offset) = (le(&end[12..16]), le(&end[16..20])); + let may_be_zip64 = total == 0xffff || size == 0xffff_ffff || offset == 0xffff_ffff; + let locator = match at.checked_sub(20) { + Some(before) if may_be_zip64 && before >= bottom => { + read_at::<_, 20>(reader, before, len) + .map_err(unread)? + .filter(|bytes| bytes.starts_with(LOCATOR)) + .map(|bytes| (before, le(&bytes[8..16]))) + } + _ => None, + }; + let mut directory = None; + match locator { + // zip64: the first record, forwards from where the locator + // points, that ends where the locator begins. + Some((locator_at, declared)) if declared < locator_at => { + let range = (declared.max(bottom), locator_at); + scan(reader, END64, range, false, |reader, x| { + let Some(record) = read_at::<_, 56>(reader, x, len).map_err(unread)? else { + return Ok(false); + }; + if le(&record[4..12]).checked_add(12) != Some(locator_at - x) { + return Ok(false); + } + within(le(&record[32..40]), le(&record[40..48]))?; + // Prepended bytes move the directory with the record. + directory = le(&record[48..56]).checked_add(x - declared); + Ok(true) + })?; + } + Some(_) => {} + // An empty archive: nothing of a directory is read. + None if total == 0 => directory = Some(at), + // zip32: the first central header forwards from the offset. + None if offset < at => { + scan( + reader, + CENTRAL, + (offset.max(bottom), at), + false, + |_, header| { + directory = Some(header); + Ok(true) + }, + )?; + if directory.is_some() { + within(on_disk.max(total), size)?; + } + } + None => {} } - let offset = le(&tail[at - 12..at - 4]); - if offset.checked_add(56).is_some_and(|end| end <= len) { - let mut record = [0u8; 56]; - reader.seek(SeekFrom::Start(offset)).map_err(unread)?; - reader.read_exact(&mut record).map_err(unread)?; - if record.starts_with(END64) { - within(le(&record[32..40]), le(&record[40..48]))?; + match directory { + Some(start) if floor.is_none() => floor = Some(start.min(at)), + Some(_) => {} + // Each record passed over costs a search of the file, here and + // in the reader: an archive strewn with them is not a jar. + None => { + passed_over += 1; + if passed_over > MAX_RECORDS_PASSED_OVER { + return Err(JarError::Unreadable(format!( + "it holds more than {MAX_RECORDS_PASSED_OVER} end records that lead to \ + no central directory" + ))); + } } } - } + Ok(false) + })?; reader.seek(SeekFrom::Start(0)).map_err(unread)?; - Ok(()) + Ok(floor.unwrap_or(0)) } /// The content digests of a jar's members ([`Jar::content_digests`]). @@ -413,6 +590,31 @@ pub(crate) mod testing { out.finish().unwrap().into_inner() } + /// An archive whose end records declare `entries` 46-byte central + /// records where a directory would be, and hold none: a zip64 record + /// that ends where its locator begins, the locator (pointing `early` + /// bytes before the record) and a zip32 record that defers to them. + /// The zip reader takes these records, and would allocate for the + /// directory they declare. + pub(crate) fn declares_entries(entries: u64, early: u64) -> Vec { + let mut archive = vec![0u8; entries as usize * 46]; + let at = archive.len() as u64; + archive.extend_from_slice(b"PK\x06\x06"); + archive.extend_from_slice(&44u64.to_le_bytes()); + archive.extend_from_slice(&[0; 12]); + archive.extend_from_slice(&entries.to_le_bytes()); + archive.extend_from_slice(&entries.to_le_bytes()); + archive.extend_from_slice(&(entries * 46).to_le_bytes()); + archive.extend_from_slice(&[0; 8]); + archive.extend_from_slice(b"PK\x06\x07\0\0\0\0"); + archive.extend_from_slice(&(at - early).to_le_bytes()); + archive.extend_from_slice(&1u32.to_le_bytes()); + archive.extend_from_slice(b"PK\x05\x06\0\0\0\0"); + archive.extend_from_slice(&[0xff; 12]); + archive.extend_from_slice(&[0; 2]); + archive + } + /// [`jar_with_modes`] of plain files. pub(crate) fn jar(members: &[(&str, &[u8])]) -> Vec { let members: Vec<(&str, &[u8], Option)> = @@ -530,58 +732,114 @@ mod tests { ); } - /// The limits on the central directory are held to what the end records - /// declare, before the zip reader parses (and allocates for) it: these - /// archives have no directory to parse at all, so the refusal can only - /// have come from the records. + /// The limits on the central directory are held to what the end record + /// declares, before the zip reader parses (and allocates for) it, + /// wherever in the file that record sits. These archives have no + /// directory to parse at all, so the refusal can only have come from + /// the record; and the reader would take each of them, since the + /// records are consistent. #[test] fn the_central_directory_is_bounded_before_it_is_parsed() { - let end = |entries: u16, directory: u32| { - let mut record = b"PK\x05\x06\0\0\0\0".to_vec(); - record.extend_from_slice(&entries.to_le_bytes()); - record.extend_from_slice(&entries.to_le_bytes()); - record.extend_from_slice(&directory.to_le_bytes()); - record.extend_from_slice(&[0; 6]); - record - }; - // Millions of 46-byte records fit a download: 200,001 of them here, - // declared by a zip64 record and the locator that points at it. let entries = MAX_ENTRIES as u64 + 1; - let mut many = vec![0u8; entries as usize * 46]; - let at = many.len() as u64; - many.extend_from_slice(b"PK\x06\x06"); - many.extend_from_slice(&[0; 20]); - many.extend_from_slice(&entries.to_le_bytes()); - many.extend_from_slice(&entries.to_le_bytes()); - many.extend_from_slice(&(entries * 46).to_le_bytes()); - many.extend_from_slice(&[0; 8]); - many.extend_from_slice(b"PK\x06\x07\0\0\0\0"); - many.extend_from_slice(&at.to_le_bytes()); - many.extend_from_slice(&1u32.to_le_bytes()); - many.extend_from_slice(&end(u16::MAX, u32::MAX)); - let err = Jar::of_bytes(&many).err().expect("refused"); - assert_eq!( - err.to_string(), - format!("it holds {entries} entries, over the limit of {MAX_ENTRIES}") - ); - assert!(err.is_too_large()); + let limit = format!("it holds {entries} entries, over the limit of {MAX_ENTRIES}"); + let refused = |archive: &[u8]| Jar::of_bytes(archive).err().expect("refused").to_string(); + // Millions of 46-byte records fit a download: 200,001 of them here. + assert_eq!(refused(&testing::declares_entries(entries, 0)), limit); + // The reader finds an end record however much follows it. + let mut trailed = testing::declares_entries(entries, 0); + trailed.extend_from_slice(&[0u8; 70_000]); + assert_eq!(refused(&trailed), limit); + let mut trailed = testing::declares_entries(entries, 0); + trailed.extend_from_slice(&vec![0x20u8; 3 * 1024 * 1024]); + assert_eq!(refused(&trailed), limit); + // It finds the zip64 record forwards from where the locator points. + let mut early = testing::declares_entries(entries, 100); + assert_eq!(refused(&early), limit); + early.extend_from_slice(&[0u8; 70_000]); + assert_eq!(refused(&early), limit); // A directory of a few entries with 65 MiB of names and comments. let mut wide = vec![0u8; 65 * 1024 * 1024]; - wide.extend_from_slice(&end(3, 65 * 1024 * 1024)); - let err = Jar::of_bytes(&wide).err().expect("refused"); + wide[..4].copy_from_slice(b"PK\x01\x02"); + wide.extend_from_slice(b"PK\x05\x06\0\0\0\0\x03\0\x03\0"); + wide.extend_from_slice(&(65u32 * 1024 * 1024).to_le_bytes()); + wide.extend_from_slice(&[0; 6]); assert_eq!( - err.to_string(), + refused(&wide), "its central directory takes 65 MiB, over the limit of 64 MiB" ); - // Bytes that spell an end record but declare more than the archive - // holds are not one: the real record decides. - let lookalike = end(u16::MAX, u32::MAX); - let real = jar(&[("a/B.class", &lookalike)]); + // End records that lead nowhere are passed over, as the reader + // passes over them; an archive strewn with them is given up. + // (Each declares one entry at offset 0, where no central header is.) + let nowhere = b"PK\x05\x06\0\0\0\0\x01\0\x01\0\0\0\0\0\0\0\0\0\0\0"; + assert_eq!( + refused(&nowhere.repeat(MAX_RECORDS_PASSED_OVER + 1)), + "it holds more than 64 end records that lead to no central directory" + ); + assert!(refused(&nowhere.repeat(2)).starts_with("not a readable zip archive")); + + // Bytes that spell an end record in a member's data are not one. + let lookalike = testing::declares_entries(entries, 0); + let real = jar(&[("a/B.class", &lookalike[lookalike.len() - 98..])]); assert_eq!(Digests::of_bytes(&real).unwrap().len(), 1); } + /// The same for a real archive of 200,001 entries, which the reader + /// would parse whole: with bytes after it, the check before the parse + /// still refuses it (the count after the parse would too, having paid + /// for the parse). + #[test] + fn an_archive_past_the_limit_is_refused_unparsed_with_bytes_after_it() { + let members: Vec<(String, &[u8])> = (0..=MAX_ENTRIES) + .map(|i| (format!("c/{i}"), b"".as_slice())) + .collect(); + let members: Vec<(&str, &[u8])> = members.iter().map(|(n, b)| (n.as_str(), *b)).collect(); + let mut archive = jar(&members); + let limit = format!( + "it holds {} entries, over the limit of {MAX_ENTRIES}", + MAX_ENTRIES + 1 + ); + let admitted = |archive: &[u8]| { + admit(&mut std::io::Cursor::new(archive), archive.len() as u64) + .map_err(|e| e.to_string()) + }; + assert_eq!(admitted(&archive), Err(limit.clone())); + archive.extend_from_slice(&[0u8; 70_000]); + assert_eq!(admitted(&archive), Err(limit)); + } + + /// A fat jar holds other jars as stored members, end records and all. + /// The reader cannot take a record below the outer directory, so a + /// nested jar is not looked at, whatever its own end record declares: + /// the outer directory is what counts, and the members read as ever. + #[test] + fn a_fat_jar_with_a_stored_nested_jar_is_accepted() { + let small = jar(&[("inner/A.class", b"inner")]); + let huge = testing::declares_entries(MAX_ENTRIES as u64 + 1, 0); + for nested in [&small, &huge] { + assert!(nested.windows(4).any(|bytes| bytes == END)); + let fat = jar(&[ + ("BOOT-INF/classes/App.class", b"app"), + ("BOOT-INF/lib/first.jar", &small), + ("BOOT-INF/lib/nested.jar", nested), + ]); + let digests = Digests::of_bytes(&fat).unwrap(); + assert_eq!(digests.len(), 3); + let mut outer = Jar::of_bytes(&fat).unwrap(); + assert_eq!( + outer.member_git_sha256("BOOT-INF/lib/nested.jar").unwrap(), + Some(compute_git_sha256_from_bytes(nested)) + ); + // With bytes after the outer end record as well. + let mut trailed = fat.clone(); + trailed.extend_from_slice(&[0u8; 70_000]); + assert_eq!(Digests::of_bytes(&trailed).unwrap(), digests); + } + // On its own the nested archive is past the limit. + assert!(Jar::of_bytes(&huge).is_err_and(|e| e.is_too_large())); + } + /// What is inflated is bounded, whatever the entry declares: a deflated /// run of zeros is a few kilobytes of archive. #[test] diff --git a/crates/socket-patch-core/src/patch/jvm_jar.rs b/crates/socket-patch-core/src/patch/jvm_jar.rs index be1a0ad28..a01dcb933 100644 --- a/crates/socket-patch-core/src/patch/jvm_jar.rs +++ b/crates/socket-patch-core/src/patch/jvm_jar.rs @@ -1920,21 +1920,9 @@ mod tests { #[tokio::test] #[serial_test::serial] async fn a_copy_past_the_limits_is_refused_before_it_is_parsed() { - let entries = 200_001u64; - let mut hostile = vec![0u8; entries as usize * 46]; - let at = hostile.len() as u64; - hostile.extend_from_slice(b"PK\x06\x06"); - hostile.extend_from_slice(&[0; 20]); - hostile.extend_from_slice(&entries.to_le_bytes()); - hostile.extend_from_slice(&entries.to_le_bytes()); - hostile.extend_from_slice(&(entries * 46).to_le_bytes()); - hostile.extend_from_slice(&[0; 8]); - hostile.extend_from_slice(b"PK\x06\x07\0\0\0\0"); - hostile.extend_from_slice(&at.to_le_bytes()); - hostile.extend_from_slice(&1u32.to_le_bytes()); - hostile.extend_from_slice(b"PK\x05\x06\0\0\0\0"); - hostile.extend_from_slice(&[0xff; 12]); - hostile.extend_from_slice(&[0; 2]); + // With bytes after its end records: the reader finds them all the same. + let mut hostile = crate::patch::jar_members::testing::declares_entries(200_001, 0); + hostile.extend_from_slice(&[0u8; 70_000]); let limit = "it holds 200001 entries, over the limit of 200000"; let files = record(); assert_eq!( From 855ad759da05beddf6ced175e8e8a6ed4b92f64a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 19 Nov 2026 10:11:58 -0500 Subject: [PATCH 5/5] Vendor a jar without asking the upstream registry for it Vendoring a Maven or Gradle patch downloaded the original jar from the registry to compare the patch service's jar with, and refused or warned when it could not. It does not need the registry for that: the service's jar is checked as it was served (transfer integrity, the record's members at their afterHash) and committed. One comparison stays, since it costs no network and protects the build. When the original jar is already in the build's local repository, the members the patch does not touch must be that jar's, as agent mode requires before a swap. A difference means the project builds with a jar that is not the one the patch was made from, and the refusal says so. With no local copy nothing is compared and nothing is said. An online re-run over a committed tree makes the same local comparison and no longer needs the registry for the jar. Upstream metadata (pom, parents, module metadata, classifier jars) is read as before. Document that a project's .mvn/maven.config chooses where apply, rollback and remove write, what they do there, and that MAVEN_REPO_LOCAL takes the choice back. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 53 ++- .../src/vendor/maven_repo.rs | 388 +++++++----------- docs/design/maven-vendoring.md | 2 +- docs/ecosystems.md | 9 + 4 files changed, 183 insertions(+), 269 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 59f439d8e..101d3200e 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2824,25 +2824,26 @@ 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. -A vendored jar must be upstream's jar outside the patch. Online, the jar (the patch -service's on a first vendoring, the committed one on a re-run) is compared with the -upstream jar before anything is written: a cached copy the registry's checksum -vouches for, else the registry's own download held to the same checksum. Every entry -the JVM would load must hold the same content in both, whatever unix mode it carries; -the record's members and signature files (`META-INF/*.SF`, `.RSA`, `.DSA`, `.EC`) are -exempt and directory entries may differ. A jar that adds, drops or changes anything -else is refused with `vendor_prebuilt_integrity_mismatch`, the detail naming up to -three such members, and a first vendoring commits and wires nothing. - -A registry that cannot be reached while the patch service can does not stop a first -vendoring. The baseline is then, in order: the registry-verified jar; else the jar in -the build's local repository, as agent mode trusts the installed jar; else none, and -the service's jar is vendored as served. The last two are reported with -`vendor_jvm_upstream_unverified` (the detail says which, and that a later run makes -the comparison) and the entry is recorded as not registry-verified. A mismatch -against whichever baseline was used is still the refusal above. An online re-run over -a committed tree needs the registry-verified jar, as before -(`vendor_jvm_upstream_unavailable` without one). +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 @@ -3221,6 +3222,18 @@ or `mvn install` rebuilt it), lacks a file, or is a swapped jar whose original t 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 @@ -3410,7 +3423,7 @@ with `reason: : `: | `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, 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. Also reported by a first vendoring that could get no registry-verified upstream jar: the members the patch does not touch were compared with the local repository's jar, or, with none, not compared at all. | +| `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 (`:`). | The Maven half of a root (single-module, reactor or mixed) also reports diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index fea79c99c..a2634ed83 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -1059,70 +1059,42 @@ async fn vendor_maven_jvm( }; let online = service.is_some_and(|s| !s.offline); - // Everything the patch does not touch must be upstream's, checked - // before anything is written: on a first vendoring (always online: the - // jar comes from the service) as on an online re-run over a committed - // tree. A service jar built from another base, or one that adds or - // drops a class, is never committed and wired. + // The jar is the patch service's, checked as it was served (transfer + // integrity, the record's members at their `afterHash`), or the + // committed one. No copy of the original is fetched to hold it to: + // vendoring needs the patch service and this machine, not the registry. // - // The baseline is the registry-verified upstream jar: a cached copy the - // registry's checksum vouches for, else the registry's own download - // held to it (the jar agent mode patched in `~/.m2` is no baseline). - // A re-run needs that one, as it always did. A first vendoring must not - // fail because the registry cannot be reached while the patch service - // can: it falls back to the jar in the build's local repository (the - // trust agent mode places in the installed jar), and with no jar at all - // vendors as served, saying the comparison was not made. - if online { - let verified = match acquire_jvm_artifact(&local, &gav, None, "jar", service).await { - Ok(bytes) => Ok(bytes), - Err(_) => acquire_jvm_artifact(&LocalSources::none(), &gav, None, "jar", service).await, - }; - let baseline = match verified { - Ok(bytes) => Some(bytes), - Err(e) if was_committed => return refused("vendor_jvm_upstream_unavailable", e), - Err(why) => { - let cached = local.find(&gav, None, "jar", false).await.ok().flatten(); - local - .unverified - .store(true, std::sync::atomic::Ordering::Relaxed); - let jar = layout::file_name(&artifact_id, &version, None, "jar"); - warnings.push(VendorWarning::new( - "vendor_jvm_upstream_unverified", - match cached { - Some(_) => format!( - "no registry-verified copy of {jar} could be had ({why}), so the \ - members the patch does not touch were compared with the jar in the \ - local repository instead" - ), - None => format!( - "no upstream copy of {jar} could be had ({why}), so the members the \ - patch does not touch were not compared with upstream; the patch \ - service's jar was vendored as served. Run `socket-patch vendor` \ - again when the registry can be reached to make the comparison" - ), - }, - )); - cached - } - }; - if let Some(upstream) = baseline { + // One comparison costs no network and protects the build. When the + // original jar is already in the build's local repository, the members + // the patch does not touch must be that jar's, as agent mode requires + // before a swap. 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), and the service's jar would change more than + // the patch. With no local copy there is nothing to compare, and + // nothing to say. (An offline re-run compares nothing, as before.) + if !was_committed || online { + if let Ok(Some(resolved)) = local.find(&gav, None, "jar", false).await { let names: Vec = record .files .keys() .map(|k| crate::patch::apply::normalize_file_path(k).to_string()) .collect(); + let leaf = layout::file_name(&artifact_id, &version, None, "jar"); // Off the async workers: a pass inflates up to the jar limits. let compared = tokio::task::spawn_blocking(move || { - let verdict = - verify_unpatched_jar_members(&upstream, &jar_bytes, &names, was_committed); + let verdict = verify_unpatched_jar_members( + (&leaf, &resolved), + &jar_bytes, + &names, + was_committed, + ); (jar_bytes, verdict) }) .await; let Ok((bytes, verdict)) = compared else { return refused( "vendor_prebuilt_integrity_mismatch", - "the comparison with the upstream jar did not finish".to_string(), + "the comparison with the local repository's jar did not finish".to_string(), ); }; jar_bytes = bytes; @@ -1527,12 +1499,15 @@ async fn acquire_classifier( } /// The patched jar (the service's on a first vendoring, the committed one -/// on a re-run) must be the upstream jar outside the record's members -/// (`patched_members`, as a jar spells them) and signature files: every other member a JVM would load, the -/// same in both ([`crate::patch::jar_members`], whose limits also bound -/// the read). `Err` is the refusal's `(code, detail)`. +/// on a re-run) against `resolved`, the jar `(leaf, bytes)` the build +/// resolves from its local repository: outside the record's members +/// (`patched_members`, as a jar spells them) and signature files, every +/// member a JVM would load must be the same in both +/// ([`crate::patch::jar_members`], whose limits also bound the read). A +/// local jar that cannot be read gives nothing to compare with. `Err` is +/// the refusal's `(code, detail)`. fn verify_unpatched_jar_members( - upstream: &[u8], + resolved: (&str, &[u8]), patched: &[u8], patched_members: &[String], committed: bool, @@ -1543,27 +1518,30 @@ fn verify_unpatched_jar_members( } else { "the patch service's jar" }; - let read = |jar: &[u8], whose: &str| { - Digests::of_bytes(jar).map_err(|e| match e { - JarError::TooLarge(why) => ( - super::verify::ARTIFACT_TOO_LARGE, - format!("{whose} cannot be checked: {why}"), - ), - JarError::Unreadable(why) => ( - "vendor_prebuilt_integrity_mismatch", - format!("{whose} cannot be read: {why}"), - ), - }) + let candidate = Digests::of_bytes(patched).map_err(|e| match e { + JarError::TooLarge(why) => ( + super::verify::ARTIFACT_TOO_LARGE, + format!("{whose} cannot be checked: {why}"), + ), + JarError::Unreadable(why) => ( + "vendor_prebuilt_integrity_mismatch", + format!("{whose} cannot be read: {why}"), + ), + })?; + let Ok(original) = Digests::of_bytes(resolved.1) else { + return Ok(()); }; - let original = read(upstream, "the upstream jar")?; - let candidate = read(patched, whose)?; let names: Vec<&str> = patched_members.iter().map(String::as_str).collect(); let difference = unpatched_difference(&original, &candidate, &names); if !difference.is_empty() { return Err(( "vendor_prebuilt_integrity_mismatch", format!( - "{whose} differs from the verified upstream jar outside the patched members: {}", + "{whose} differs from {}, the jar this build resolves from its local \ + repository, outside the patched members: {}. The build uses a jar that is not \ + the one the patch was made from, so the vendored jar would change more than \ + the patch", + resolved.0, difference.describe() ), )); @@ -4309,35 +4287,17 @@ mod tests { ); } - /// The registry's files for the fixture's upstream jar and pom, served - /// from `server` with the `.sha1` Maven Central publishes beside them. - async fn mount_upstream(server: &wiremock::MockServer, jar: &[u8]) -> EnvGuard { - use wiremock::matchers::{method, path}; - use wiremock::{Mock, ResponseTemplate}; - let base = "/org/apache/commons/commons-text/1.10.0/commons-text-1.10.0"; - for (ext, bytes) in [("jar", jar), ("pom", UPSTREAM_POM)] { - Mock::given(method("GET")) - .and(path(format!("{base}.{ext}"))) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes.to_vec())) - .mount(server) - .await; - Mock::given(method("GET")) - .and(path(format!("{base}.{ext}.sha1"))) - .respond_with(ResponseTemplate::new(200).set_body_string(sha1_hex(bytes))) - .mount(server) - .await; - } - EnvGuard::set("SOCKET_MAVEN_REGISTRY", server.uri()) - } - - /// A first vendoring holds the service's jar to upstream outside the - /// patched members, as agent mode does, before anything is written: a - /// jar built from another base, one with a class added (whatever unix - /// mode its entry carries: the JVM loads it all the same) and one with a - /// class dropped are refused, and the project is left as it was. + /// Vendoring needs the patch service and this machine, not the + /// registry: no upstream jar is fetched to compare with, and none is + /// missed. The one comparison is with the jar the build already + /// resolves from its local repository. With none there, the service's + /// jar is committed, whatever it holds beside the patch, and nothing is + /// said. With one that matches outside the patch (the original, or the + /// jar agent mode patched there) it is committed. With one that + /// differs it is refused, naming the members, and nothing is written. #[tokio::test] #[serial_test::serial] - async fn a_first_vendoring_refuses_a_service_jar_that_is_not_upstream_outside_the_patch() { + async fn a_first_vendoring_compares_with_the_local_jar_and_asks_the_registry_for_none() { use crate::patch::jar_members::testing::jar_with_modes; const MANIFEST: (&str, &[u8], Option) = ("META-INF/MANIFEST.MF", b"Manifest-Version: 1.0\n", None); @@ -4345,120 +4305,61 @@ mod tests { const CLASS: &str = "org/apache/commons/text/StringSubstitutor.class"; const CODE: (&str, &[u8], Option) = (CLASS, b"\xca\xfe\xba\xbe-fake-class", None); const ADDED: &str = "org/apache/commons/text/Added.class"; - - let cases: Vec<(Vec, String)> = vec![ + let honest = make_jar(PATCHED); + let another_base = + jar_with_modes(&[MANIFEST, NOTICE, (CLASS, b"another release's class", None)]); + let with_signatures = jar_with_modes(&[ + ("META-INF/", b"", None), + MANIFEST, + ("META-INF/APACHE.SF", b"signature", None), + ("META-INF/APACHE.RSA", b"signature", None), + (JAR_FILE, PRISTINE, None), + ("org/apache/commons/text/", b"", None), + CODE, + ]); + // (the service's jar, the jar in the local repository, the refusal) + let cases: Vec<(Vec, Option>, Option)> = vec![ + (honest.clone(), None, None), + (another_base.clone(), None, None), + (honest.clone(), Some(make_jar(PRISTINE)), None), + // Directory entries and signature files may differ. + (honest.clone(), Some(with_signatures), None), + // The jar agent mode patched there, with the `.sha1` it wrote. + (honest.clone(), Some(honest.clone()), None), ( - jar_with_modes(&[MANIFEST, NOTICE, (CLASS, b"another release's class", None)]), - format!("1 changed (`{CLASS}`)"), + another_base, + Some(make_jar(PRISTINE)), + Some(format!("1 changed (`{CLASS}`)")), ), ( jar_with_modes(&[MANIFEST, NOTICE, CODE, (ADDED, b"\xca\xfe\xba\xbe", None)]), - format!("1 added (`{ADDED}`)"), + Some(make_jar(PRISTINE)), + Some(format!("1 added (`{ADDED}`)")), ), ( // A symlink-mode entry is not a regular file to a zip // reader, and is a class to the JVM. jar_with_modes(&[MANIFEST, NOTICE, CODE, (ADDED, b"target", Some(0o120777))]), - format!("1 added (`{ADDED}`)"), + Some(make_jar(PRISTINE)), + Some(format!("1 added (`{ADDED}`)")), ), ( jar_with_modes(&[MANIFEST, NOTICE]), - format!("1 missing (`{CLASS}`)"), + Some(make_jar(PRISTINE)), + Some(format!("1 missing (`{CLASS}`)")), ), ]; - for (service_jar, difference) in cases { - let (dir, blobs, installed, record) = reactor_fixture(true).await; - let root = dir.path(); - assert!( - zip_bytes_match_after_hashes(&service_jar, &record.files), - "{difference}: the jar carries the patch" - ); - let server = mount_granted_jar(&service_jar).await; - let _registry = mount_upstream(&server, &make_jar(PRISTINE)).await; - let cfg = service_cfg( - Some(&server.uri()), - crate::vendor::VendorSource::Service, - false, - ); - let before = crate::vendor::test_support::tree_snapshot(root); - let (code, detail) = - unwrap_refused(run_jvm(root, &blobs, &installed, &record, Some(&cfg)).await); - assert_eq!(code, "vendor_prebuilt_integrity_mismatch", "{difference}"); - assert_eq!( - detail, - format!( - "the patch service's jar differs from the verified upstream jar outside \ - the patched members: {difference}" - ) - ); - assert_eq!( - crate::vendor::test_support::tree_snapshot(root), - before, - "{difference}: nothing is written" - ); - assert!(!root.join(".socket").exists(), "{difference}"); - } - - // The honest jar vendors. Directory entries and signature files are - // the two things that may differ: the service's builds drop both. - for upstream in [ - make_jar(PRISTINE), - jar_with_modes(&[ - ("META-INF/", b"", None), - MANIFEST, - ("META-INF/APACHE.SF", b"signature", None), - ("META-INF/APACHE.RSA", b"signature", None), - (JAR_FILE, PRISTINE, None), - ("org/apache/commons/text/", b"", None), - CODE, - ]), - ] { - let (dir, blobs, installed, record) = reactor_fixture(true).await; - let root = dir.path(); - tokio::fs::write(installed.join("commons-text-1.10.0.jar"), &upstream) - .await - .unwrap(); - let server = mount_granted_jar(&make_jar(PATCHED)).await; - let _registry = mount_upstream(&server, &upstream).await; - let cfg = service_cfg( - Some(&server.uri()), - crate::vendor::VendorSource::Service, - false, - ); - let (result, entry, _) = - unwrap_done(run_jvm(root, &blobs, &installed, &record, Some(&cfg)).await); - assert!(result.success && entry.is_some(), "{:?}", result.error); - } - } - - /// A registry that cannot be reached while the patch service can must - /// not stop a first vendoring. The jar in the build's local repository - /// is then the baseline, a mismatch against it is still a refusal, and - /// with no jar at all the service's jar is vendored as served. Each - /// says so, and the entry is recorded as not registry-verified. - #[tokio::test] - #[serial_test::serial] - async fn a_first_vendoring_without_the_registry_falls_back_and_says_so() { - use crate::patch::jar_members::testing::jar_with_modes; - let tampered = jar_with_modes(&[ - ("META-INF/MANIFEST.MF", b"Manifest-Version: 1.0\n", None), - (JAR_FILE, PATCHED, None), - ( - "org/apache/commons/text/StringSubstitutor.class", - b"another release's class", - None, - ), - ]); - // (the service's jar, a jar in the local repository, the outcome) - for (served, local_jar, refusal) in [ - (make_jar(PATCHED), true, None), - (tampered.clone(), true, Some("1 changed")), - (make_jar(PATCHED), false, None), - (tampered, false, None), - ] { - let (dir, blobs, installed, record) = reactor_fixture(local_jar).await; + for (served, local_jar, refusal) in cases { + let (dir, blobs, installed, record) = reactor_fixture(false).await; let root = dir.path(); - // The service answers; the registry routes are all 404. + if let Some(local_jar) = &local_jar { + let jar = installed.join("commons-text-1.10.0.jar"); + tokio::fs::write(&jar, local_jar).await.unwrap(); + tokio::fs::write(jar.with_extension("jar.sha1"), sha1_hex(local_jar)) + .await + .unwrap(); + } + // The service answers; every registry route is a 404. let server = mount_granted_jar(&served).await; let _registry = EnvGuard::set("SOCKET_MAVEN_REGISTRY", server.uri()); let cfg = service_cfg( @@ -4466,64 +4367,55 @@ mod tests { crate::vendor::VendorSource::Service, false, ); + let before = crate::vendor::test_support::tree_snapshot(root); let outcome = run_jvm(root, &blobs, &installed, &record, Some(&cfg)).await; - if let Some(difference) = refusal { - let (code, detail) = unwrap_refused(outcome); - assert_eq!(code, "vendor_prebuilt_integrity_mismatch"); - assert!(detail.contains(difference), "{detail}"); - assert!(!root.join(".socket").exists()); - continue; - } - let (result, entry, warnings) = unwrap_done(outcome); - assert!(result.success, "local_jar={local_jar}: {:?}", result.error); - assert_eq!(upstream_status(&entry.expect("entry")), "local_unverified"); - let said: Vec<&str> = warnings + let asked_for_a_jar = server + .received_requests() + .await + .unwrap() .iter() - .filter(|w| w.code == "vendor_jvm_upstream_unverified") - .map(|w| w.detail.as_str()) - .collect(); - assert_eq!(said.len(), 1, "{warnings:?}"); - assert!( - said[0].contains(if local_jar { - "were compared with the jar in the local repository instead" - } else { - "were not compared with upstream; the patch service's jar was vendored as served" - }), - "{}", - said[0] - ); + .any(|r| r.url.path().starts_with("/org/") && r.url.path().contains(".jar")); + assert!(!asked_for_a_jar, "no jar is asked of the registry"); + match refusal { + Some(difference) => { + let (code, detail) = unwrap_refused(outcome); + assert_eq!(code, "vendor_prebuilt_integrity_mismatch", "{difference}"); + assert_eq!( + detail, + format!( + "the patch service's jar differs from commons-text-1.10.0.jar, the \ + jar this build resolves from its local repository, outside the \ + patched members: {difference}. The build uses a jar that is not \ + the one the patch was made from, so the vendored jar would change \ + more than the patch" + ) + ); + assert_eq!( + crate::vendor::test_support::tree_snapshot(root), + before, + "{difference}: nothing is written" + ); + assert!(!root.join(".socket").exists(), "{difference}"); + } + None => { + let (result, entry, warnings) = unwrap_done(outcome); + assert!(result.success && entry.is_some(), "{:?}", result.error); + assert!( + !warnings + .iter() + .any(|w| w.code == "vendor_jvm_upstream_unverified"), + "nothing is said of a comparison that was not made: {warnings:?}" + ); + // A re-run over the committed tree needs no jar either. + crate::vendor::test_support::persist(root, PURL, entry.unwrap()).await; + let (again, _, _) = + unwrap_done(run_jvm(root, &blobs, &installed, &record, Some(&cfg)).await); + assert!(again.success, "{:?}", again.error); + } + } } } - /// The jar agent mode patched in `~/.m2` is not upstream's: the first - /// vendoring compares with the registry's own jar instead of refusing. - #[tokio::test] - #[serial_test::serial] - async fn a_first_vendoring_over_an_agent_patched_local_jar_compares_with_the_registry() { - let (dir, blobs, installed, record) = reactor_fixture(true).await; - let root = dir.path(); - let patched = make_jar(PATCHED); - tokio::fs::write(installed.join("commons-text-1.10.0.jar"), &patched) - .await - .unwrap(); - tokio::fs::write( - installed.join("commons-text-1.10.0.jar.sha1"), - sha1_hex(&patched), - ) - .await - .unwrap(); - let server = mount_granted_jar(&patched).await; - let _registry = mount_upstream(&server, &make_jar(PRISTINE)).await; - let cfg = service_cfg( - Some(&server.uri()), - crate::vendor::VendorSource::Service, - false, - ); - let (result, entry, _) = - unwrap_done(run_jvm(root, &blobs, &installed, &record, Some(&cfg)).await); - assert!(result.success && entry.is_some(), "{:?}", result.error); - } - /// commons-text as log4j-core is published: a sibling's version comes /// from the parent's management, written `${project.version}`. const CHILD_OF_PARENT_POM: &str = "4.0.0\ diff --git a/docs/design/maven-vendoring.md b/docs/design/maven-vendoring.md index 2a4de8ae4..ab7c58fbc 100644 --- a/docs/design/maven-vendoring.md +++ b/docs/design/maven-vendoring.md @@ -335,7 +335,7 @@ tree is refused nowhere and degraded nowhere. ## Artifact identity and integrity -Service jars pass transfer-integrity and patched-member checks. The server constructs jars and strips invalidated signatures; the CLI never rebuilds jar archives. Online, before anything is written, the jar (the service's on a first vendoring, the committed one on a re-run) is also compared with the registry-verified upstream jar: every entry the JVM would load, whatever unix mode it carries, must hold the same content outside the record's members and signature files, or the run is refused with `vendor_prebuilt_integrity_mismatch`. A cached upstream jar the registry's checksum does not vouch for (one agent mode patched in `~/.m2`) is not the baseline; the registry's own download is. When the registry cannot be reached, a first vendoring falls back to the local repository's jar, then to no comparison at all, and reports which with `vendor_jvm_upstream_unverified`. Jars are read member by member within fixed limits (200,000 entries; 1 GiB and 100 times the jar's size inflated per pass); one past them is `vendor_artifact_too_large`. Online vendoring authenticates upstream POM and Gradle module metadata against registry sidecars. A POM or module that a local cache holds and the registry gives no checksum for is the file the build resolved: it is used, and the entry is recorded unverified (`vendor_jvm_upstream_unverified`), as an offline one is. Bytes that differ from a published checksum are refused. Metadata fetches use a separate HTTP client and do not send Socket API credentials. `SOCKET_MAVEN_REGISTRY` supports a private mirror. +Service jars pass transfer-integrity and patched-member checks. The server constructs jars and strips invalidated signatures; the CLI never rebuilds jar archives. No copy of the original jar is downloaded to compare the service's jar with: vendoring needs the patch service and the local machine, not the registry. When the original jar is already in the build's local repository, every entry the JVM would load, whatever unix mode it carries, must hold the same content in both outside the record's members and signature files, or the run is refused with `vendor_prebuilt_integrity_mismatch`: the project builds with a jar that is not the one the patch was made from. With no local copy nothing is compared. Jars are read member by member within fixed limits (200,000 entries; 1 GiB and 100 times the jar's size inflated per pass); one past them is `vendor_artifact_too_large`. Online vendoring authenticates upstream POM and Gradle module metadata against registry sidecars. A POM or module that a local cache holds and the registry gives no checksum for is the file the build resolved: it is used, and the entry is recorded unverified (`vendor_jvm_upstream_unverified`), as an offline one is. Bytes that differ from a published checksum are refused. Metadata fetches use a separate HTTP client and do not send Socket API credentials. `SOCKET_MAVEN_REGISTRY` supports a private mirror. Maven v5 does not enable Resolver trusted-checksum processors at build time. Those processors crash some release reactors and system-scope dependencies, diff --git a/docs/ecosystems.md b/docs/ecosystems.md index efd3e4cf2..badf40781 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1122,6 +1122,15 @@ scanned or patched and the run warns `maven_local_repository_undetermined`; set before 3.9 does not read `MAVEN_ARGS`; socket-patch reads it whatever Maven is installed. +This means a project's `.mvn/maven.config` chooses where agent mode writes. It can +point `apply`, `rollback` and `remove` at any directory laid out as a Maven +repository, including one outside the project and outside your home directory, exactly +as it points Maven there when the project is built. In that directory socket-patch +does what it does in `~/.m2`: it replaces a jar that matches the known original of a +patch with the patch service's build of it, rewrites the checksum files beside it +(`.sha1`, `.md5`), and restores both on rollback. Set `MAVEN_REPO_LOCAL` to name the +repository yourself, whatever the project's config says. + A Gradle-only build reads `~/.m2` only through `mavenLocal()`. Scan looks for it in every settings, build, `buildSrc`, included-build, applied and init script, including the wrapper distribution's `init.d`. Without it, `~/.m2` is not scanned, and modules