diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 147fed6cc7..6e5b4e5ae7 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -285,7 +285,7 @@ Beyond the globals above, each subcommand defines a small set of local arguments | Subcommand | Local arg | Env var | Purpose | |---|---|---|---| | `apply` | `--force` / `-f` | — | Bypass beforeHash check. A file of the patch that is missing on disk is skipped instead of failing the package, and named in a `patch_files_skipped` warning | -| `apply` | `--check` | — | Read-only audit that every in-scope (`--ecosystems`) manifest patch is in place, for CI / GitHub-App auditing (v5.0: previously Go-only, which passed on any unpatched non-Go tree). Local Go patches: the committed `.socket/go-patches/` copies and `go.mod` `replace` directives match the manifest (`go_redirect_drift`). Every other patch: each installed copy hashes to the record's `afterHash` — the `vex` verifier over the `vex` copy lookup; the copies are narrowed by `apply`'s own rules: a release variant (a qualified purl such as `?artifact_id=` / `?platform=`) is judged only on the copies holding its distribution, matched against every variant of its base as `apply` matches them, and an installed copy that holds none of them is drift of the base purl (`no_matching_variant`, the copy `apply` fails with "no matching variant found"; a Gradle / Ivy cache dir is exempt, as in `apply`); for gem, once a bundle-store copy exists the `gem env` fallback-home copies are not judged (`apply` treats them as best-effort). Drift is a `failed` event per patch with `errorCode` `not_applied` (still unpatched), `hash_mismatch` (neither the original nor the patched bytes), `file_not_found` or `no_matching_variant`, status `partialFailure`, exit 1, and the human `Error: Patches are OUT OF SYNC:` report (printed even under `--silent`), which ends with the remedy ``Run `socket-patch apply ` to regenerate them.`` (left out when every drift is a `no_matching_variant` one, which `apply` does not change; a gem's drift line names `bundle pristine `): `` repeats the check's own `--cwd`, `--manifest-path`, `-g` / `--global-prefix` and `--ecosystems` (each shell-quoted when needed), so running it verbatim heals the tree that was checked (v5.0, #1219). In sync is exit 0: `Patches are in sync (N checked).` and, under `--json`, a `skipped` event per verified patch (`errorCode: already_patched`). A record of an ecosystem this CLI does not support is not checked and the line says so instead (`unsupported_ecosystem`); a key that is not a purl is drift (`invalid_purl`). A patch with no installed copy is skipped as `apply` skips it (`package_not_installed`; the human line adds `M not installed, skipped`). A copy `apply` skips as not supported yet (a compiled conda build of a Python package that does not hold the patch) is not drift either: a `Warning:` line per copy, a `skipped` event per record and copy (`errorCode: conda_build_not_pypi_release`), and `K not supported, skipped` on the human line for the records with no other copy (see "Agent-mode apply to a conda build"). Vendor-owned patches are excluded (`vendor --check` audits them). Lock-free, fetch-free, offline-safe; it never writes. An unreadable manifest is drift (`manifest_unreadable`, exit 1) | +| `apply` | `--check` | — | Read-only audit that every in-scope (`--ecosystems`) manifest patch is in place, for CI / GitHub-App auditing (v5.0: previously Go-only, which passed on any unpatched non-Go tree). Local Go patches: the committed `.socket/go-patches/` copies and `go.mod` `replace` directives match the manifest (`go_redirect_drift`). Every other patch: each installed copy hashes to the record's `afterHash` — the `vex` verifier over the `vex` copy lookup; the copies are narrowed by `apply`'s own rules: a release variant (a qualified purl such as `?artifact_id=` / `?platform=`) is judged only on the copies holding its distribution, matched against every variant of its base as `apply` matches them, and an installed copy that holds none of them is drift of the base purl (`no_matching_variant`, the copy `apply` fails with "no matching variant found"; a Gradle / Ivy cache dir is exempt, as in `apply`); for gem, once a bundle-store copy exists the `gem env` fallback-home copies are not judged (`apply` treats them as best-effort). Drift is a `failed` event per patch with `errorCode` `not_applied` (still unpatched), `hash_mismatch` (neither the original nor the patched bytes), `file_not_found`, `no_matching_variant` or `multi_release_unpatched_copy` (Maven: every file of the patch is in place, and a multi-release jar holds a patched class again under `META-INF/versions//` without the patch; the drift line names the jar, the class and the copy, see [Other copies of a patched class](#other-copies-of-a-patched-class)), status `partialFailure`, exit 1, and the human `Error: Patches are OUT OF SYNC:` report (printed even under `--silent`), which ends with the remedy ``Run `socket-patch apply ` to regenerate them.`` (left out when every drift is a `no_matching_variant` or `multi_release_unpatched_copy` one, which `apply` does not change; a gem's drift line names `bundle pristine `): `` repeats the check's own `--cwd`, `--manifest-path`, `-g` / `--global-prefix` and `--ecosystems` (each shell-quoted when needed), so running it verbatim heals the tree that was checked (v5.0, #1219). In sync is exit 0: `Patches are in sync (N checked).` and, under `--json`, a `skipped` event per verified patch (`errorCode: already_patched`). A record of an ecosystem this CLI does not support is not checked and the line says so instead (`unsupported_ecosystem`); a key that is not a purl is drift (`invalid_purl`). A patch with no installed copy is skipped as `apply` skips it (`package_not_installed`; the human line adds `M not installed, skipped`). A copy `apply` skips as not supported yet (a compiled conda build of a Python package that does not hold the patch) is not drift either: a `Warning:` line per copy, a `skipped` event per record and copy (`errorCode: conda_build_not_pypi_release`), and `K not supported, skipped` on the human line for the records with no other copy (see "Agent-mode apply to a conda build"). Vendor-owned patches are excluded (`vendor --check` audits them). Lock-free, fetch-free, offline-safe; it never writes. An unreadable manifest is drift (`manifest_unreadable`, exit 1) | | `vendor` | `--force` / `-f` | — | Bypass the installed-variant probe for multi-release ecosystems. That is its only effect: vendoring commits the patch server's verified artifact and never reads the installed files' content, so a missing or mismatched installed file vendors the same with or without `--force` (no warning) | | `vendor` | `--revert` | `SOCKET_VENDOR_REVERT` | Undo vendoring: restore recorded original lockfile fragments + remove `.socket/vendor/` artifacts. Works without a manifest. A package vendored over a hosted pin returns to its upstream registry entry, never to hosted (see "Takeover reconciliation") | | `vendor` | `--check` | — | Offline, read-only artifact and wiring audit; exits 1 on drift. Conflicts with `--revert`. | @@ -2459,6 +2459,7 @@ command's integration tests check its output. | `package_not_installed` | `skipped` | apply: manifest entry has no matching installed package (an installed gem or PyPI copy that holds a patched file with content no record of its release was made for is `no_matching_variant` instead). When the project's lockfiles resolve the purl (a platform-gated optional dependency, a devDependency under `--omit=dev`), the detail says it is lockfile-only and the entry never fails the run, even when no other patch matched; only an all-miss run with an unmatched purl that no lock resolves exits 1 (`partialFailure`). **Cargo is never lockfile-only (v5.0, #616)**: `cargo fetch` unpacks every `Cargo.lock` entry (target-gated ones included), so a locked crate missing from `$CARGO_HOME/registry/src` was simply not fetched yet (a cold CI cache, a pruned `registry/src`) and the next `cargo build` would compile it unpatched; it counts as an unresolved purl (an all-miss run exits 1, as in 4.x) and its detail, the human error and the human warning say to run `cargo fetch` first. A crate `Cargo.lock` takes from a path, git, `[patch]` or `[replace]` source is never looked up in the registry cache (#506): cargo does not build that copy, so the same detail also names that case. | | `apply_failed` | `failed` | apply: hash mismatch, write error, archive read error. Also a manifest key that is not a purl (see `invalid_purl`). The copy is left as it was: every file is staged (its blob read and hash-checked, with the file's final mode and owner) before the first is renamed into place, and a rename that fails puts the files already replaced back. The `error` names the file (`Cannot apply patch: - `); a blob that does not hold its hash's bytes is named with the remedy (`blob is corrupt … Run \`socket-patch repair\``). Only when putting a file back fails too does the `error` end with the files left changed; the original of such a file is kept beside it as `.socket-kept--`, a name no later run removes. A run killed between two renames can still leave some files patched; the next `apply` finishes it. A killed run also leaves `.socket-stage--` / `.socket-orig--` files beside the patch's files (staged content and the second names of the files being replaced, never the package's own content); an `apply` or `rollback` of that package removes them once they are ten minutes old. | | `native_extension_not_rebuilt` | `failed` | apply (gem), and the apply that `get` / `scan --mode agent` run: the patch is incomplete. Its files were written into the installed copy and are left there (unlike `apply_failed`, where the copy is as it was), and the compiled code the copy runs is not the patch's: the build compiled nothing of it, or, on the JRuby build of a gem, the patch changes sources of the gem's jars and does not bring the jars. `error` says what was written and what is not in effect; `files` lists what this run wrote. The run exits 1 (`partialFailure`), the patch stays recorded, `apply --check` is out of sync and `vex` does not attest it; `rollback` restores the files. The same code is a `warnings[]` entry of the run, and the `apply --check` / `vex` tag of such a copy. See "A build that builds nothing of the patch". | +| `multi_release_unpatched_copy` | `failed` (apply, `apply --check`); `skipped` (vex); run-level `warnings[]` | Maven, a record keyed by jar members: every member the patch lists is in place, and its jar, a multi-release jar, holds one of them again under `META-INF/versions//` without the patch, which a Java runtime of release `` or later loads instead of the patched member. apply, and the apply that `get` / `scan --mode agent` run: the patch is incomplete, as with `native_extension_not_rebuilt`. The jar was swapped and is left swapped (the base member is patched), the copy's event is `failed` under this code, the run exits 1 (`partialFailure`), the patch stays recorded and `rollback` restores the jar. `apply --check`: drift under this code. vex: the package is omitted under this code wherever `vex` reads the jar, which for a hosted pin is only where a local cache holds the suffixed jar (the section says when it is not read). In each, a `warnings[]` entry (for `apply --check`, the drift's `reason`) names the jar, the member and the versioned paths. The same code covers a jar that could not be checked for such a copy (the text then says "could not be checked"): one that is not checked is not taken for patched. Vendored mode vendors the jar and reports the same as a `vendor_jvm_degraded` warning with `reason: multi_release_unpatched_copy`, exit 0. No command clears it by being run again: it takes a patch that lists the versioned copy. See [Other copies of a patched class](#other-copies-of-a-patched-class). | | `conda_build_not_pypi_release` | `skipped` (exit status unchanged; human: `Warning: …`), or the start of a `failed` error | apply, `apply --check`, and the apply that `get` / `scan --mode agent` run (PyPI): `skipped` when the installed copy is a compiled conda build, which is not supported yet: nothing is written and the run does not fail. The start of a `failed` event's error when a conda build without compiled code cannot take the record (a platform wheel's record, or nothing shows the copy is the pure-Python release). Also a top-level `warnings[]` code of `scan --mode agent` / `get` for a patch left out. See "Agent-mode apply to a conda build". | | `unsupported_ecosystem` | `skipped` + run-level `warnings[]`; remove: top-level error | apply (incl. `--check`), rollback, and the nested apply of `get` / `scan --mode agent` (additive): a manifest record whose purl type this CLI has no crawler for — an ecosystem a newer socket-patch recorded, or a known type in another case (`pkg:NPM/…`; the detail then names the lowercase spelling). The record is left alone, named in one `skipped` event each and in one warning (human: one `Warning:` line on stderr), and never changes the exit: a newer CLI's ecosystem in a committed manifest must not fail an older CLI's run (`scan --prune` exempts such records for the same reason). `apply --check` does not count it as checked: its result line reads `N checked patches are in sync; K patches not checked (unsupported ecosystem).` (or `No patches checked: …`) instead of `Patches are in sync`. `rollback` leaves it out of the confirmation prompt and keeps its record. `remove` refuses it before any mutation (exit 1, top-level `error.code`) unless `--skip-rollback` is given: it could not restore what the record patched. Not reported under `--ecosystems`, which scopes the run to ecosystems this CLI knows. | | `invalid_purl` | apply `--check` / rollback: `failed`; remove: top-level error | A manifest key that is not a `pkg:/` purl at all (a hand-edited manifest): no version of the CLI can match it to a package. `apply` fails it by name as `apply_failed` (exit 1; every other patch still applies), `apply --check` reports it as drift, `rollback` as a failed entry whose record is kept (exit 1), and `remove` refuses it unless `--skip-rollback` is given. Correct the key or remove the entry. | @@ -4025,6 +4026,7 @@ starts with the code): | `gradle_copy_unexpected_bytes` | refused, exit 1 | A hash directory's file is the pristine download (its sha1 names the directory) but neither side of the record, or a hash directory holds a variant's files whose bytes no variant was made for. That copy is left unpatched and the run fails (changed in v5.0: it used to only warn), since the build still loads it. | | `gradle_transform_copy_stale` | that copy fails | After the write, Gradle still holds a copy derived from the pristine jar (`caches/transforms-*`, `caches/jars-*`, instrumented jars). Run `gradle --stop`, delete those directories, apply again. | | `gradle_transform_copy_unverified` | warning | A same-named derived copy is neither the pristine nor the patched jar and is older than the patch, or the derived-cache walk was cut short. | +| `multi_release_unpatched_copy` | that copy's patch is incomplete, exit 1 | A member-keyed record's jar holds the record's members patched, and, being a multi-release jar, holds one of them again under `META-INF/versions//` without the patch: a Java runtime of release `` or later loads that copy (see [Other copies of a patched class](#other-copies-of-a-patched-class)). The jar is swapped and stays swapped, in `~/.m2` and in the Gradle cache alike, with its backup; `rollback` restores it. The copy's event is `failed` with this `errorCode` (not `apply_failed`), its `error` names the jar, the class and the versioned paths, and it lists the files the run wrote; the human line is `Error: Patch of is incomplete: …` and the summary counts the package as `not in effect`. A run that finds the jar already patched reports the same, and so does `--dry-run` (`would not take effect`). Also reported when the jar holds such a copy and its manifest cannot be read to tell whether a runtime loads it. Applying again does not clear it: it takes a patch that lists the versioned copy. | | `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. | @@ -4172,7 +4174,7 @@ with `reason: : `: |---|---|---| | `vendor_jvm_shape_unsupported` | refusal, nothing written | `gradle_below_6_8`, `android_or_kmp` (also `available-at` module redirects), `gradle_exclusive_content_conflict` (a user rule claiming the module, in any script), `gradle_range_excludes_vendored` (no declared selector admits the vendored version), `gradle_classifier_computed` (a declaration of the module names its classifier through a variable, such as `${osdetector.classifier}`: the vendored repository would claim that jar without holding it), `gradle_verification_unparseable`, `gradle_index_unreadable`, `build_file_unreadable` (including a non-UTF-8 settings file), `build_file_outside_root`, `not_build_root` (run from a directory an ancestor settings file includes or may include, from a project with no settings file of its own below one, or below an ancestor settings file that is not UTF-8; `repair` refuses there too), `no_build_file` (no `pom.xml`, Gradle, sbt or scala-cli build at the root), `legacy_maven_root` (the root's ledger still holds a pre-v5 single-POM `maven_pom_repository` entry; the whole root is refused until `vendor --revert`, then vendor again) | | `vendor_jvm_upstream_unavailable` | refusal | `classifier_unavailable` (a declared classifier jar no cache or registry has), `module_unavailable` (the pom declares Gradle module metadata that cannot be sourced), `pom_unavailable`, `verification_metadata_unavailable`; for a suffixed Maven / sbt pom also `suffix_unavailable` (the upstream pom computes its own version), `parent_unavailable` (a first vendoring whose upstream parent poms are in no local cache and cannot be fetched, so the suffixed pom cannot be checked) and `inherited_version_unresolvable` (a parent pom names `${project.version}` where the suffixed pom cannot declare the base version instead: in a profile, a management key or a repository URL) | -| `vendor_jvm_degraded` | applied, VEX withheld | `gradle_unscanned_build_logic`, `unwired_build_logic` (a nonliteral included build), `settings_plugins_unwired`, `classifier_unpatched_copy` (a classifier jar carries an unpatched copy of a patched member, 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_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), `multi_release_unpatched_copy` (every vendored JVM layout, Maven reactor, Gradle, sbt, scala-cli and the jar committed for a Bazel hub alike: the vendored jar is a multi-release jar that holds a patched member again under `META-INF/versions//` without the patch, or holds such a copy and cannot be read to tell whether a runtime loads it, or cannot be opened as a jar to be checked; reported on the first vendoring and on every in-sync run; `vendor --check` passes, since the artifact holds every file of the patch; see [Other copies of a patched class](#other-copies-of-a-patched-class)), `verification_parent_chain_unhandled`, `gradle_lock_overrides_vendored` (a dependency lock of the build, buildscript and settings classpath locks included, pins the module at a version no vendored row serves), `gradle_settings_lock_unrouted` (a `settings-gradle.lockfile` locks the module but that build's settings script does not hold the in-block repository entry for it), `gradle_lock_unreadable` (a lock file, or a followed custom `lockFile`, is missing, unreadable, outside the checkout or not UTF-8), `gradle_custom_lock_file` (a `lockFile` location that cannot be followed statically: anything but a literal `file(…)` in a project's own build script), `gradle_wiring_uncommitted` (VEX liveness only, never reported by `vendor`: the committed settings files, index, derived `maven-metadata.xml`, script or verification file lack wiring a re-plan would write, such as a removed apply line or in-block entry; the git hygiene files do not count), `conflicting_managed_version` / `management_unresolved` (Maven reactor: an imported BOM or an out-of-checkout parent manages the artifact at another version, or its POM is unavailable; that local root is not pinned), `selection_undetermined` (Maven reactor: what one or more modules resolve cannot be read, so no pin is written where that is so and one already there is left as it is; one event however many modules, naming the first and counting the rest), `pin_would_move_module` (Maven reactor: a parent pom resolves the base version itself above a module that resolves another version, so the parent takes no pin. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven)) | | `vendor_jvm_note` | applied, informational | `range_declared` (a range, prefix or rich selector lists versions from the derived `maven-metadata.xml`), `ide_sources_unavailable` | | `vendor_jvm_upstream_unverified` | warning | Upstream metadata was taken offline, or from a local cache while the registry published no checksum for it (a parent pom from a corporate repository), and not authenticated against registry checksums. | | `vendor_jvm_unattested` | warning (`vendor --check`) | A Maven reactor entry is intact and wired, but a declaration may still build the base release (an executable classifier or type copy, a version a property, profile or unpinned local root may move), so `vex` does not attest it. The entry stays `verified`; the detail names the purl and the declarations (`:`). | @@ -4216,6 +4218,7 @@ match it, withholds the statement: | `vex_gradle_unpatched_copy` | run warning | A copy a build may load does not carry the patch; no statement until every copy does. | | `gradle_unpatched_copy` | `failed[].reason` | The purl the warning above (or `vex_gradle_derived_cache_check_failed`) withheld. | | `vex_gradle_derived_cache_check_failed` | run warning | The derived-cache check of an attested Gradle copy did not finish (it crashed), so a copy derived from the unpatched jar cannot be ruled out; no statement for that purl. | +| `multi_release_unpatched_copy` | run warning and `failed[].reason` | Every member the record lists is patched in every jar the build consumes, and one of those jars, a multi-release jar, holds a patched member again under `META-INF/versions//` without the patch (or holds such a copy and its manifest cannot be read): a Java runtime of release `` or later runs the unpatched code, so no statement is emitted. The warning names the jar, the member and the versioned paths, one per jar. Judged where `vex` reads the jar: the installed jar of an agent-mode patch and the suffixed jar of a hosted pin when the copies are verified, and the committed jar of a vendored entry as a gate of its own, so `--no-verify` does not attest a vendored one. Not judged, and attested from the pin as before: a hosted pin whose suffixed jar is in no cache `vex` reads (the Maven local repository, the Gradle caches, a hosted sbt build's download directory), which is every hosted pin until a build downloads the jar; and the pins that the `--vex` of a `scan --mode hosted` run itself wrote or confirmed, whatever a cache holds. `--no-verify` reads no installed or hosted jar. A vendored jar that cannot be opened to be checked at all is not attested either: verification refuses it under its own reason (`vendor_artifact_unreadable`, `vendor_artifact_too_large`), and a run that does not verify omits it under this code. Not listed among the copies of `vex_gradle_unpatched_copy`: `apply` cannot patch it. See [Other copies of a patched class](#other-copies-of-a-patched-class). | | `vex_gradle_lock_above_base` | run warning and `failed[].reason` | A hosted pin is wired, but a lock file records a release above its base, which that build resolves instead of the patch; no statement until it is re-locked or the patch is rolled back. | | `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | **Experimental** (Bazel workspaces). In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`, rules_rust `crate.from_cargo`, rules_csharp `nuget.from_lock`, rules_jvm_external `maven.install`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, the lock of a pnpm workspace above it that names that directory among its importers, or a `packages.lock.json` below it), or it is a patch of a Maven artifact in any mode (in an installed jar, in a pin of a `pom.xml` or a Gradle file, in a copy vendored for such a build) while a pinned hub fetches the plain jar of that artifact at that version and the block that hosted and vendored mode keep in the root `MODULE.bazel` holds no entry of that patch for it, or holds one that does not reach the hub because the hub's `use_extension` is isolated (`isolate = True`: no `override_repo` of the block reaches such a usage, and the hub keeps the jar of its lock) (no file of a project decides what a hub fetches: the same from every project of the workspace, and the same after a hosted or vendored command that wrote no entry for the hub; a jar that the hub takes from the Maven local repository under `m2local` counts as fetched, and the lock's sha256 is not compared with the patch), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock, with the attribute the call has to carry for a crate, `cargo_config`, and for a NuGet package, `nuget_config`, and for a crate `scan --mode vendored` as well; for a Maven jar `get pkg:maven//@ --mode hosted` at the Bazel root, or with `--mode vendored`, the package by its coordinates alone, without the qualifiers of its purl; where hosted and vendored mode write no entry for the hub, in the place of the command ``Hosted and vendored mode write no entry for this hub (``): .`` with the `maven_bazel_*` code and the reason of the warning that the command gives (those of vendored mode: an option about downloads does not count); before either, when the block holds the entry of another patch for the jar, ``MODULE.bazel holds the entry of patch for this jar, and where the block is in effect the Bazel build takes that patch's jar.``, and when it holds the entry of the patch itself, which does not reach an isolated hub, ``The entry that MODULE.bazel holds for this patch does not reach this hub.``; for a vendored PyPI copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``; a Maven statement, which is one for every mode, says ``the patch is only in what Maven or Gradle builds from`` where the others say ``the patch is only in the installed copy``, and ends ``If what you ship is what Maven or Gradle builds and not what Bazel builds, pass …``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, under which the Bazel workspace is not read for the document (see "The installed tree" under "VEX provenance markers": what the host command itself does and says in a Bazel workspace stays), for a hosted pin of another ecosystem than Maven, for a vendored gem (rules_ruby builds one that is committed as its archive, `vendor_gem_bazel_file_source`, and one vendored by its path only when the call lists every file of the copy among its `srcs`, which is not read), for a vendored crate (rules_rust builds it), for a vendored NuGet package (rules_csharp builds it through the block that vendored mode keeps in `MODULE.bazel`, which `vex` does not read: the statement is the same where that block is missing and the build fails), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it unless it is a `packages.lock.json`, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**`, a `pip.parse` with `uv_lock` or a `crate.from_cargo` with a cargo-bazel lock, `lockfile` (it may take its packages from a file that is not read), for a crate the lock does not take from a registry, for a NuGet package when the `nuget_config` of any `nuget.from_lock` call names the patch, is not a plain string label of the main repository or cannot be read, or when such a call passes `*` or `**` (rules_csharp makes one hub of all the calls, so the pin of another project may be what it builds), for a Maven jar when the block holds the entry of its patch and no hub that fetches the jar is on an isolated `use_extension` (a usage that cannot be read may be a shared one: the entry stands), or was changed by hand and still calls `override_repo`, when a `maven.override` names the artifact, when the hub that would fetch it or its lock cannot be read (what is not known of another hub, such as a second hub without `lock_file` or a `maven_install` of a `WORKSPACE` file, changes nothing), or when the checkout does not say that Bazel reads `MODULE.bazel` as it stands (`.bazeliskrc` or `.bazelversion` names a Bazel before 7.0, or neither names a release while a `WORKSPACE` file defines a repository; an rc file of the checkout names `enable_bzlmod` other than switched on while the checkout names no Bazel 9 or later, or `--ignore_dev_dependency` without switching it off, on whatever line, or cannot be read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, which for a Maven jar counts only while the checkout names no Bazel release, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | | `vex_pnpm_bundled_copy` | run warning and `failed[].reason` | An npm pin is wired, but its pnpm lock names a package whose `bundledDependencies` may ship an unpatched copy of it (the lock does not record that copy's version); no statement while that package bundles it. `vendor --check` and `scan` still treat the wiring as live. | @@ -4257,3 +4260,97 @@ Coursier reads the module from the next repository, unpatched jar included) and `vendor_scala_cli_repository_shadowed`: an input declares a repository or a direct `url=` for the patched group, or Bloop evidence newer than every input and the wiring resolved the GAV outside the tree). + +### Other copies of a patched class + +A member-keyed record lists the jar members it changes. A JVM can load the same class +from elsewhere; one such place is checked, wherever a command reads the jar, and two +are not. Hosted mode reads no jar when it writes a pin, so there the check waits for +`vex` over a jar a build has downloaded; the table below says where each mode looks. + +**Multi-release jars (checked).** A jar whose manifest makes it a multi-release jar +may hold a member again per Java release under `META-INF/versions//`, and a runtime +of release `` or later loads that copy **instead of** the base entry. A versioned +entry that overrides a member the record changes must be one the record lists (it is +then held to its own `afterHash` like any member) or must hold the patched bytes of a +member it overrides. Any other is an unpatched copy that some runtime loads, reported +as `multi_release_unpatched_copy` with the jar, the member and the versioned paths +(up to three per member; further members are counted). A versioned copy of a member +the record does not change is not looked at. + +What a runtime loads is decided as the JDK decides it (`java.util.jar.JarFile`, +`java.util.zip.ZipFile`; read in OpenJDK 11, 17, 21 and the current sources, and run on +OpenJDK 11, 17, 21 and 26): + +- The jar is a multi-release jar only when the main section of its manifest holds + `Multi-Release` with the value `true`: name and value in any letter case, the value + with nothing after it, on one line that ends in a line terminator. `false`, any + other value, an attribute in a per-entry section, a value wrapped onto a + continuation line, a missing attribute or a missing manifest: the entries under + `META-INF/versions/` are never read, and nothing is reported. The manifest is the + entry named `META-INF/MANIFEST.MF` in any letter case, the last such entry of the + central directory. +- A versioned entry is `META-INF/versions//` in exactly that spelling, with + `` a decimal number without a leading zero. `meta-inf/versions/9/…`, + `META-INF/versions/09/…` and `META-INF/versions/x/…` are never loaded. +- `` counts from 8. The JAR specification says 9, and OpenJDK 11 ignores + `META-INF/versions/8/`; OpenJDK 17, 21 and 26 load it. 7 and below are ignored by + all of them. Every higher `` counts: a copy under a higher `` overrides one + under a lower `` as it overrides the base, so a record that changes only + `META-INF/versions/9/a/B.class` is also held to a `META-INF/versions/17/a/B.class`. +- A `` under `META-INF/` is never looked up as a versioned entry, so a record + that changes only such members (`META-INF/NOTICE.txt`) is never reported. + +A runtime started with `-Djdk.util.jar.enableMultiRelease=force` reads versioned +entries without the manifest attribute. No file of the jar or of the project records +that, and it is not considered. + +The check reads entry names from the central directory alone (no entry is read to +list them). The manifest is inflated only when the jar holds a versioned entry that +could be such a copy, and then only those entries are hashed, within the jar limits +above. When such a copy exists and the manifest's main section cannot be read as +`Name: value` lines, or the manifest or the copy cannot be inflated, or the directory +lists one of them and its own header does not parse, the copy is reported as one that +may be loaded ("could not be checked … which a Java runtime may load instead of the +patched one"): a jar that is not checked is not taken for patched. + +The same holds for a jar that cannot be checked at all, because it does not open as a +jar within the jar limits or because the check did not finish (it runs on the +blocking pool, and one that dies is reported, never taken for a clean answer): every +command reports it under `multi_release_unpatched_copy` ("could not be checked for +unpatched copies of the patched members under META-INF/versions"). `apply` reports the +copy's patch as incomplete, `vendor` warns `vendor_jvm_degraded`, and `vex` writes no +statement. One case keeps its older name: a vendored jar that `vex` cannot open is +refused by verification as `vendor_artifact_unreadable` or +`vendor_artifact_too_large`, and that reason is the one reported; only a run that does +not verify (`--no-verify`) omits it under `multi_release_unpatched_copy`. A vendored +jar that is missing, or whose tree lacks another of its files, is the same case. +Where the layout's wiring check reads the tree (Gradle), the entry is `vendor_unwired` +with or without verification, as before. Otherwise verification reports +`vendor_artifact_missing`, and `--no-verify` omits the entry under +`multi_release_unpatched_copy`, where it used to write the statement. + +| Mode | Where | What happens | +|---|---|---| +| agent | `apply` (and `scan` / `get` in agent mode), per consumed jar, after the swap or for a jar found patched; `--dry-run` too | That copy's patch is incomplete: a `failed` event with `errorCode` `multi_release_unpatched_copy`, a run warning with the same code, exit 1. The jar stays patched. | +| agent | `apply --check` | Drift, `errorCode` `multi_release_unpatched_copy`, exit 1; no "run `apply`" remedy. | +| vendored | `vendor` (and `scan` / `get` in vendored mode), first run and in-sync runs | The jar is vendored; warning `vendor_jvm_degraded`, `reason: multi_release_unpatched_copy: …`; exit 0. `vendor --check` and `repair` treat the artifact as healthy. | +| hosted | `scan --mode hosted`, `get --mode hosted`, and the `--vex` of a hosted `scan` | Nothing: hosted mode neither downloads nor reads the jar, and a hosted scan's own `--vex` attests the pins that run wrote or confirmed from the pin, whatever a local cache holds. | +| agent, vendored | `vex`, embedded `--vex` | No statement; `failed[].reason` and a run warning `multi_release_unpatched_copy`. The jar read is the installed one (agent) or the committed one (vendored). For a vendored entry also under `--no-verify`, a jar that cannot be opened to be checked included; `--no-verify` reads no installed jar. | +| hosted | `vex` (standalone, or the `--vex` of a command that is not the hosted run itself) | The same, but only when a local cache holds the pin's suffixed jar: the Maven local repository, a Gradle cache (the read-only one included) or a hosted sbt build's download directory. With the jar in none of them the pin is attested from the wiring alone, as a hosted pin is before the project's first build, and the jar is not read. `--no-verify` reads no jar. | + +Nothing is undone or refused in any mode: the base member is patched, which is what a +Java 8 runtime loads, and withholding the patch would leave the other runtimes no +better off. A record that replaces the jar file whole (a leaf record, +`package/-.jar`) lists no members, so nothing is looked for in its jar. + +**Nested jars (not detected).** A Spring Boot executable jar holds its dependencies +under `BOOT-INF/lib/`, and a war under `WEB-INF/lib/`. No command reads inside such an +archive, reports that it holds an unpatched copy of a patched artifact, or patches it. +An archive the build assembles after the patch takes the patched jar the build +resolves; one assembled before it, or downloaded, keeps the jar it was built with. + +**Shaded, relocated or repackaged copies (not detected).** A jar that copies another +artifact's classes into itself (an uber jar, a shaded dependency, with or without +renamed packages) is another artifact under other coordinates. A patch for the +original artifact neither reaches that copy nor reports it. diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 91bc47e414..003af3d065 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -618,6 +618,13 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { if reason == NO_MATCHING_VARIANT { detail.push_str(&no_variant_check_remedy(&args.common, &failed.purl)); } + if reason == MULTI_RELEASE_UNPATCHED_COPY { + // Which jar, which class, which copy. + let jars = outcome.multi_release_copies.iter(); + let jars = jars.filter(|(purl, _)| *purl == failed.purl); + let jars: Vec<&str> = jars.map(|(_, what)| what.as_str()).collect(); + detail.push_str(&format!(" ({})", jars.join("; "))); + } drifts.push((failed.purl, reason.to_string(), detail)); } } @@ -694,9 +701,12 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { } // A go consumer-sync drift names its own go command; apply // cannot regenerate vendor/ or go.sum. Nor does it change a - // copy no release variant matches: that drift says so itself. + // copy no release variant matches, or a versioned copy of a + // multi-release jar its patch does not list: those drifts say + // so themselves. if drifts.iter().any(|(_, code, _)| { code != NO_MATCHING_VARIANT + && code != MULTI_RELEASE_UNPATCHED_COPY && code != socket_patch_core::vendor::go_consumer_sync::VENDOR_MODULES_TXT_CODE && code != socket_patch_core::vendor::go_consumer_sync::REQUIREMENTS_CODE && code != socket_patch_core::vendor::go_consumer_sync::NATIVE_VENDOR_CODE @@ -1000,10 +1010,21 @@ fn describe_check_failure(reason: &str) -> &'static str { "an installed copy matches none of the manifest's release variants \ (no matching variant found)" } + MULTI_RELEASE_UNPATCHED_COPY => { + "the patch's files are in place, but a jar holds a patched class again for newer \ + Java releases without the patch (`apply` cannot change that copy, the patch has \ + to list it), or could not be checked for such a copy" + } _ => "an installed copy does not verify", } } +/// `errorCode` of a Maven patch whose members are all in place while its +/// jar, a multi-release one, holds one of them again under +/// `META-INF/versions//` without the patch: `apply` fails that copy +/// with it, and `apply --check` reports it as drift. +const MULTI_RELEASE_UNPATCHED_COPY: &str = socket_patch_core::vex::MULTI_RELEASE_UNPATCHED_COPY; + /// What follows the `no_matching_variant` drift of `base_purl` in the /// `apply --check` report: `apply` leaves such a copy as it is, so the /// report's closing `apply` remedy is not for it. A gem names the command @@ -1700,7 +1721,7 @@ fn collect_apply_failures( let mut failures: Vec = Vec::new(); for r in results { let (code, error, cause) = match caveats.incomplete_of(r) { - Some(copy) => (gem_ext::NOT_REBUILT_REASON, copy.detail.clone(), None), + Some(copy) => (copy.code, copy.detail.clone(), None), None if !r.success => ( if caveats.is_no_variant(r) { NO_MATCHING_VARIANT @@ -3113,18 +3134,23 @@ impl LeftCopy { } } -/// One gem copy whose patch is incomplete -/// ([`gem_ext::GemCaveat::Incomplete`]): the files of the patch are -/// written there and stay written, and the compiled code the copy runs is -/// not the patch's. Its [`ApplyResult`] is among the run's results, as the -/// successful write it is (so its sidecar advisory and per-file warnings -/// are reported like any write's); this entry is what makes the run fail -/// and the copy read as not patched. +/// One copy whose patch is incomplete: the files of the patch are written +/// there and stay written, and what the copy runs is not all the patch's. +/// A gem copy whose compiled code was not rebuilt from the patched sources +/// ([`gem_ext::GemCaveat::Incomplete`]), or a multi-release jar that holds +/// a patched class again under `META-INF/versions//` without the patch +/// ([`check_versioned_copies`]). Its [`ApplyResult`] is among the run's +/// results, as the successful write it is (so its sidecar advisory and +/// per-file warnings are reported like any write's); this entry is what +/// makes the run fail and the copy read as not patched. struct IncompleteCopy { /// The manifest key of the patch. purl: String, /// The result's `package_path`: which copy. path: String, + /// The `errorCode` of the copy's event, and the code of its run + /// warning: what is not in effect. + code: &'static str, /// What was written and what is not in effect, in words. detail: String, } @@ -3133,7 +3159,7 @@ impl IncompleteCopy { /// The copy's event: `failed`, with the files this run wrote. fn event(&self, result: &ApplyResult) -> PatchEvent { PatchEvent::new(PatchAction::Failed, self.purl.clone()) - .with_error(gem_ext::NOT_REBUILT_REASON, self.detail.as_str()) + .with_error(self.code, self.detail.as_str()) .with_files(patched_files(result)) } @@ -3173,11 +3199,12 @@ struct GemCaveats { /// Copies with nothing of the patch in their build: skipped, and /// patched as far as they can be. They have no result. not_in_build: Vec, - /// Copies whose patch is incomplete. They fail the run. + /// Copies whose patch is incomplete: a gem's, or a multi-release jar's + /// ([`IncompleteCopy`]). They fail the run. incomplete: Vec, /// Copies skipped because patching them is not supported yet: a - /// compiled conda build of a Python package (the one entry here that - /// is not a gem's). They have no result and do not fail the run. + /// compiled conda build of a Python package. They have no result and + /// do not fail the run. unsupported: Vec, /// Installed copies whose files match no record of their release /// (gem or PyPI). Each has a failed result, keyed by the base purl. @@ -3224,11 +3251,9 @@ impl GemCaveats { /// Whether `warning` is the coded copy of an incomplete patch's /// `Error:` line, which the human path already printed. fn restated_by(&self, warning: &RunWarning) -> bool { - warning.code == gem_ext::NOT_REBUILT_REASON - && self - .incomplete - .iter() - .any(|copy| copy.warning_detail() == warning.detail) + self.incomplete + .iter() + .any(|copy| copy.code == warning.code && copy.warning_detail() == warning.detail) } } @@ -3622,6 +3647,7 @@ async fn apply_patches_inner( }; let out = Box::pin(apply_maven_base(&maven)).await; has_errors |= out.failed; + caveats.incomplete.extend(out.incomplete); unreported.extend(out.unreported); matched_manifest_purls.extend(out.matched); run_warnings.extend(out.warnings); @@ -3890,6 +3916,7 @@ async fn apply_patches_inner( caveats.incomplete.push(IncompleteCopy { purl: variant_purl.clone(), path: outcome.result.package_path.clone(), + code: gem_ext::NOT_REBUILT_REASON, detail, }); warn_mismatch_overwrites(&outcome.result, &args.common); @@ -4368,6 +4395,10 @@ struct MavenApplied { applied: bool, /// See [`ApplyOutcome::unreported`]. unreported: Vec<(String, ApplyFailureCause)>, + /// Copies whose jar holds the patch's members and still runs old code + /// on some Java runtimes ([`check_versioned_copies`]). They fail the + /// run; their results stay the writes they are. + incomplete: Vec, } impl MavenApplied { @@ -4624,6 +4655,8 @@ async fn apply_maven_base(m: &MavenBase<'_>) -> MavenApplied { } = copy; check_derived_copies(&mut out, &mut result, &jar_leaf, args, m.derived) .await; + check_versioned_copies(&mut out, &result, &jar_leaf, &patch.files, args) + .await; // A copy's own coded refusal is a run warning too, // as a whole-swap one is. if let Some(refusal) = refusal { @@ -4876,6 +4909,72 @@ async fn check_derived_copies( } } +/// After a copy's jar `jar_leaf` holds the members of the record `files` +/// patched (swapped in by this run, or found so): a multi-release jar may +/// hold one of them again under `META-INF/versions//`, and a Java +/// runtime of that release or later loads that copy instead +/// (`socket_patch_core::patch::multi_release`). The swap requires every +/// entry the record does not list to be the installed jar's own, so such a +/// copy is upstream's, unpatched, unless the record lists it. +/// +/// The copy's patch is then incomplete ([`IncompleteCopy`], +/// `multi_release_unpatched_copy`), as a gem's is whose compiled code is +/// not the patch's: the run fails, because a patch that is only partly in +/// effect is not a success, and nothing is undone. The patched jar stays +/// where it is, with its backup, and `rollback` restores it as usual; a +/// runtime that reads the base entry (Java 8) runs the patched class. A +/// jar that cannot be checked is reported the same way. +/// +/// A dry run is told the same, as it is told of a gem patch that would not +/// take effect: the swap leaves every entry the record does not list as +/// it is, so the jar on disk already holds the copy in question. +async fn check_versioned_copies( + out: &mut MavenApplied, + result: &ApplyResult, + jar_leaf: &str, + files: &HashMap, + args: &ApplyArgs, +) { + use socket_patch_core::patch::multi_release::{check_file_off_thread, UNPATCHED_COPY}; + if !result.success { + return; + } + let jar = PathBuf::from(&result.package_path).join(jar_leaf); + let shown = jar.display().to_string(); + // A check that does not finish comes back as a jar that could not be + // checked, never as a clean one: `apply --check` and `vex` ask the same + // helper and get the same answer. + let Some(found) = check_file_off_thread(jar, files.clone()).await else { + return; + }; + let kept = match args.common.dry_run { + true => "Applying patches the class itself and leaves the rest of the jar as it is", + false => "The patched class is in place and was left there", + }; + // A copy that is there needs a patch that lists it. A jar that could + // not be checked may hold none: all that is known is that it was not + // checked. + let next = match found.established() { + true => { + "The patch has to change that copy too, so applying it again does not help: it \ + takes a patch that lists the versioned copy" + } + false => "A jar that could not be checked is not reported as patched", + }; + let copy = IncompleteCopy { + purl: result.package_key.clone(), + path: result.package_path.clone(), + code: UNPATCHED_COPY, + detail: format!("{}. {kept}. {next}.", found.describe(&shown)), + }; + if args.prints_errors() { + eprintln!("{}", format_patch_incomplete(©.purl, ©.detail)); + } + out.warn(UNPATCHED_COPY, copy.warning_detail()); + out.incomplete.push(copy); + out.failed = true; +} + /// The `package_not_installed` detail of a lockfile-resolved purl. const LOCKFILE_ONLY_DETAIL: &str = "Resolved by the project lockfile but not installed on this host (lockfile-only)"; @@ -5910,6 +6009,7 @@ mod tests { incomplete: vec![IncompleteCopy { purl: GEM_PURL.to_string(), path: result.package_path.clone(), + code: gem_ext::NOT_REBUILT_REASON, detail: "the patch's files were written, but not built".to_string(), }], ..GemCaveats::default() diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 031ab34aaf..41908a76b2 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -1141,6 +1141,29 @@ async fn generate_vex( outcome }; + // A vendored jar that could not be checked for unpatched versioned + // copies at all (`Plan::unchecked_jars`) is not attested: a jar that is + // not checked is not taken for patched. Verification refuses a jar it + // cannot open, and its own reason is the one reported. What still + // comes out applied is omitted here: every such purl of a run that + // does not verify, and one whose check died over a jar that verifies. + for (purl, what) in &plan.unchecked_jars { + const CODE: &str = socket_patch_core::vex::MULTI_RELEASE_UNPATCHED_COPY; + let Some(at) = outcome.applied.iter().position(|applied| applied == purl) else { + continue; + }; + outcome.applied.remove(at); + outcome.vendored.retain(|vendored| vendored != purl); + outcome + .vendored_out_of_sync + .retain(|drifted| drifted != purl); + outcome.failed.push(FailedPatch { + purl: purl.clone(), + reason: CODE.to_string(), + }); + note_warning(warnings, common, CODE, format!("{purl}: {what}.")); + } + // In-run `scan --mode hosted --vex`: the bytes of deps THAT RUN confirmed // redirected live on the patch server until the next install, so their // verification against the local tree would spuriously fail @@ -1433,6 +1456,26 @@ async fn generate_vex( // verification failure. outcome.failed.extend(plan.gated.iter().cloned()); + // A multi-release jar that holds a patched class again per Java + // release, without the patch (#2199): the skip carries the code, this + // says which jar and which copy. Only for a purl still omitted for it. + // (A vendored jar's is a note of the plan.) + // + // A hosted pin is judged only where this run read its jar, which is + // the gap every installed evidence of a hosted pin has: a pin whose + // suffixed jar no local cache holds is attested from the pin (the + // lockfile basis above), and so is a pin this very run wrote or + // confirmed (`assume_applied`), whatever a cache holds. Neither reads + // the jar, so neither sees such a copy; nothing downloads it to look. + // The contract and `docs/ecosystems.md` say so. + for (purl, what) in std::mem::take(&mut outcome.multi_release_copies) { + const CODE: &str = socket_patch_core::vex::MULTI_RELEASE_UNPATCHED_COPY; + let omitted = |f: &FailedPatch| f.purl == purl && f.reason == CODE; + if outcome.failed.iter().any(omitted) { + note_warning(warnings, common, CODE, format!("{purl}: {what}.")); + } + } + // Vendored disclosure: the committed artifact verified (the attestation // stands — the plan only takes the vendored basis for an artifact a // discovered lockfile / config reference, or the JVM wiring check, shows @@ -2891,6 +2934,11 @@ fn omission_phrase(reason: &str) -> &'static str { "another package bundles its own copy, which no Socket wiring reaches (the \ warning above names it)" } + socket_patch_core::vex::MULTI_RELEASE_UNPATCHED_COPY => { + "its jar holds a patched class again for newer Java releases \ + (META-INF/versions) without the patch, which those runtimes load, or could not \ + be checked for such a copy (the warning above says which)" + } _ => "the patch could not be verified", } } @@ -3636,6 +3684,7 @@ mod tests { GO_WORKSPACE_OVERRIDE, GO_VERSION_NOT_SELECTED, GO_INSTALLED_TOOL_STALE, + socket_patch_core::vex::MULTI_RELEASE_UNPATCHED_COPY, ] { assert_ne!( omission_phrase(tag), @@ -4073,6 +4122,7 @@ mod mirror_refusal_tests { hosted, gated: Vec::new(), notes: Vec::new(), + unchecked_jars: Default::default(), }; let mut params = VexEmbedArgs { vex: Some(tmp.path().join(format!("{refused}-{no_verify}.json"))), @@ -4195,6 +4245,7 @@ mod mirror_refusal_tests { hosted, gated: Vec::new(), notes: Vec::new(), + unchecked_jars: Default::default(), }; let mut params = VexEmbedArgs { vex: Some(tmp.path().join(format!("{index}.json"))), @@ -4374,6 +4425,7 @@ mod unjudged_tests { hosted, gated: Vec::new(), notes: Vec::new(), + unchecked_jars: Default::default(), }; let mut params = VexEmbedArgs { vex: Some(tmp.path().join(format!("{no_verify}.json"))), @@ -4501,6 +4553,7 @@ mod bazel_tests { hosted: BTreeMap::from([(purls[2].to_string(), wiring)]), gated: Vec::new(), notes: Vec::new(), + unchecked_jars: Default::default(), }; for (global, no_bazel) in [(false, false), (true, false), (false, true)] { let common = GlobalArgs { diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index f650a8199f..024c88d66e 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -189,6 +189,15 @@ pub(crate) struct Plan { /// fetch failures): `vex` emits each as a `warnings[]` entry, so the /// `--json` envelope carries the detail its skip codes cannot. pub notes: Vec, + /// Vendored view purls whose committed jar could not be checked for + /// unpatched versioned copies at all (it does not open as a jar, or the + /// check did not finish), with the clause that says so. A jar that is + /// not checked is not attested, but the purl is not gated here: + /// verification refuses a jar it cannot open under its own reason + /// (`vendor_artifact_unreadable`, `vendor_artifact_too_large`), and + /// that reason stands. `vex` omits whichever of these still comes out + /// applied, which is every one of them in a run that does not verify. + pub unchecked_jars: BTreeMap, } /// One [`Plan`] advisory: a stable `warnings[]` code and its detail. @@ -882,6 +891,7 @@ pub(crate) async fn plan( hosted: BTreeMap::new(), gated, notes, + unchecked_jars: BTreeMap::new(), }; // Keys two candidates resolved to (see the collision branch below). let mut collided: HashSet = HashSet::new(); @@ -908,6 +918,7 @@ pub(crate) async fn plan( plan.redirected.retain(|k| *k != cand.key); plan.lockfile_basis.remove(&cand.key); plan.hosted.remove(&cand.key); + plan.unchecked_jars.remove(&cand.key); } collided.insert(cand.key.clone()); plan.gated.push(failed(&cand.key, RECORD_MISMATCH)); @@ -916,6 +927,35 @@ pub(crate) async fn plan( match basis { Basis::Installed => {} Basis::Vendored(entry) => { + // The committed jar may hold a class the patch changes again + // per Java release, without the patch (#2199): a runtime of + // that release loads that copy, whatever the wiring says. A + // gate like the liveness ones, for every JVM layout alike: + // `--no-verify` does not bypass it. + use socket_patch_core::vendor::{vendored_jar_versioned_copies, VendoredJarCopies}; + match vendored_jar_versioned_copies(root, &entry, &record).await { + Some(VendoredJarCopies::Found(what)) => { + const CODE: &str = socket_patch_core::vex::MULTI_RELEASE_UNPATCHED_COPY; + plan.gated.push(failed(&cand.key, CODE)); + plan.notes.push(PlanNote { + code: CODE, + detail: format!("{}: {what}.", cand.key), + }); + // The key is taken, though it never reaches the view: + // a later candidate that resolves to it collides with + // this one (above) instead of attesting beside its + // skip. + collided.insert(cand.key.clone()); + continue; + } + // Not checked, so not to be attested; but verification + // refuses such a jar in its own words, so the purl goes + // on and `vex` settles it (see `Plan::unchecked_jars`). + Some(VendoredJarCopies::Unchecked(what)) => { + plan.unchecked_jars.insert(cand.key.clone(), what); + } + None => {} + } let found = cand.discovered.iter(); let found = found.filter(|r| r.mode == WiringMode::Vendored); let pins = found.map(|r| r.source_file.to_string_lossy().replace('\\', "/")); @@ -1841,6 +1881,100 @@ mod tests { assert!(plan.view.patches.is_empty()); } + /// A vendored jar gated for an unpatched versioned copy still counts + /// as a candidate of its purl: a second candidate that resolves to the + /// same key (a lockfile-only one, renamed to the key its record is + /// filed under) collides with it and is omitted too, as it would be + /// had the first one reached the view. The purl never carries a + /// statement beside its skip. + /// + /// Two candidates meet on one key only where two spellings of one + /// release are not one string: discovery canonicalizes a reference's + /// purl, so two patches wired to one Maven release are a wiring + /// conflict long before this, and only NuGet's and Composer's version + /// spellings (`13.0.3` and `13.0.3.0`) get past it. The gate reads any + /// vendored artifact that is a jar, so the fixture is a NuGet purl + /// whose artifact is one: not a package anything vendors, and the one + /// way to put the two together. + #[tokio::test] + async fn a_gated_vendored_jar_still_collides_with_a_second_candidate() { + use socket_patch_core::vex::MULTI_RELEASE_UNPATCHED_COPY; + use std::io::Write as _; + const KEY: &str = "pkg:nuget/lib@13.0.3"; + let tmp = tempfile::tempdir().unwrap(); + // The vendored jar: the patched class, and an unlisted, unpatched + // copy of it for Java 9, in a multi-release jar. + let artifact = format!(".socket/vendor/nuget/{U1}/lib-13.0.3.jar"); + let after = b"class B, fixed"; + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in [ + ( + "META-INF/MANIFEST.MF", + &b"Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\n"[..], + ), + ("a/B.class", &after[..]), + ("META-INF/versions/9/a/B.class", &b"class B, vulnerable"[..]), + ] { + zw.start_file(name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zw.write_all(bytes).unwrap(); + } + let jar = tmp.path().join(&artifact); + std::fs::create_dir_all(jar.parent().unwrap()).unwrap(); + std::fs::write(&jar, zw.finish().unwrap().into_inner()).unwrap(); + + // The manifest records U1 under the key; the hosted ledger files + // U2 under the same key. + let mut vendored = record(U1); + vendored.files = [( + "a/B.class".to_string(), + PatchFileInfo { + before_hash: String::new(), + after_hash: socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes( + after, + ), + }, + )] + .into_iter() + .collect(); + let mut manifest = PatchManifest::new(); + manifest.patches.insert(KEY.into(), vendored); + let mut redirect = RedirectState::new(); + redirect.records.insert(KEY.into(), record(U2)); + // One file wires U1 to the vendored jar. A lock wires U2 to the + // other spelling of the release: a candidate of its own, whose + // record is the ledger's, filed under the key. + let vref = vendor_ref(&artifact).unwrap(); + let sources = Sources { + manifest, + vendor: VendorState::new(), + redirect: Some(redirect), + discovery: discovery(vec![ + PatchedRef::vendored(KEY.into(), &vref, "nuget.config", None), + hosted_ref("pkg:nuget/lib@13.0.3.0", U2, true), + ]), + hosted_uuids: Vec::new(), + }; + let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; + assert!( + plan.gated + .contains(&failed(KEY, MULTI_RELEASE_UNPATCHED_COPY)), + "{:?}", + plan.gated + ); + assert!( + plan.view.patches.is_empty(), + "a statement beside the skip: {:?}", + plan.view.patches.keys().collect::>() + ); + assert!(plan.redirected.is_empty() && plan.hosted.is_empty()); + assert!( + plan.gated.contains(&failed(KEY, RECORD_MISMATCH)), + "{:?}", + plan.gated + ); + } + /// Two lockfiles wiring one package to different patches: every /// candidate for it is gated `wiring_conflict` exactly once, none /// reaches the view (no statement next to a skip), and other packages diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/maven.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/maven.rs index c762a6f1e5..a5ff2b272c 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/maven.rs @@ -1615,6 +1615,116 @@ fn maven_scan_hosted_wiring_reattests_without_manifest_or_ledger() { }); } +/// When a hosted pin's jar is judged for unpatched versioned copies of a +/// patched class (a multi-release jar, `multi_release_unpatched_copy`), and +/// when it is not. Hosted mode never downloads the jar, so `vex` can only +/// read one that a build left in a local cache: +/// +/// * no suffixed jar cached (a checkout that has not built yet): attested +/// from the pin, the jar unread; +/// * the suffixed jar cached, with such a copy: omitted, and the warning +/// names the jar and the copy; +/// * the same jar under `--no-verify`, which reads no installed jar: +/// attested; +/// * the same jar without `Multi-Release: true`: attested, no runtime reads +/// the copy; +/// * the `--vex` of a `scan --mode hosted` run over the project, with that +/// jar cached: attested. The run attests the pins it confirmed from the +/// pin, whatever a cache holds. +#[test] +fn maven_hosted_versioned_copy_is_judged_only_where_vex_reads_the_jar() { + const CLASS: &str = "org/slf4j/Logger.class"; + const CLASS_FOR_9: &str = "META-INF/versions/9/org/slf4j/Logger.class"; + const OLD: &[u8] = b"class Logger, vulnerable"; + const NEW: &[u8] = b"class Logger, fixed"; + const MULTI_RELEASE: &[u8] = b"Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\n"; + let served = |manifest: &[u8]| { + zip_bytes(&[ + ("META-INF/MANIFEST.MF", manifest), + (CLASS, NEW), + (CLASS_FOR_9, OLD), + ]) + }; + let class_view = || view(MVN_HOSTED_UUID, MVN_PURL, &[(CLASS, OLD, NEW)]); + + let fx = Fx::new(); + copy_golden(&fx, "maven/pom/basic/expected"); + let api = Api::serve(vec![(MVN_HOSTED_UUID, class_view())]); + let args = ["--proxy-url", &api.uri()]; + let sfx_dir = fx.m2().join(format!("org/slf4j/slf4j-api/{MVN_SUFFIXED}")); + let sfx_jar = sfx_dir.join(format!("slf4j-api-{MVN_SUFFIXED}.jar")); + + // Not downloaded: the pin is all there is. + let (code, env) = fx.vex(&args); + assert_attested(&fx, code, &env, MVN_HOSTED_UUID, MVN_PURL, "redirected"); + + // Downloaded: the jar is read, and the copy for Java 9 is not the + // patch's. + put( + &sfx_dir, + &format!("slf4j-api-{MVN_SUFFIXED}.pom"), + b"", + ); + std::fs::write(&sfx_jar, served(MULTI_RELEASE)).unwrap(); + let (code, env) = fx.vex(&args); + assert_omitted( + code, + &env, + MVN_PURL, + "multi_release_unpatched_copy", + "cached suffixed jar with an unpatched versioned copy", + ); + let warned = env["warnings"].to_string(); + assert!( + warned.contains(&format!( + "slf4j-api-{MVN_SUFFIXED}.jar carries an unpatched copy of {CLASS} at {CLASS_FOR_9}" + )), + "{env}" + ); + + // `--no-verify` reads no installed jar. + let (code, env) = fx.vex(&["--proxy-url", &api.uri(), "--no-verify"]); + assert_attested(&fx, code, &env, MVN_HOSTED_UUID, MVN_PURL, "redirected"); + + // Not a multi-release jar: the copy is inert. + std::fs::write(&sfx_jar, served(b"Manifest-Version: 1.0\r\n\r\n")).unwrap(); + let (code, env) = fx.vex(&args); + assert_attested(&fx, code, &env, MVN_HOSTED_UUID, MVN_PURL, "redirected"); + + // The `--vex` of a hosted scan attests the pin it confirms, with the + // flagged jar in the cache. + let golden = "maven/pom/basic"; + let fx = Fx::new(); + copy_golden(&fx, &format!("{golden}/input")); + let base = fx.m2().join("org/slf4j/slf4j-api/1.7.36"); + put(&base, "slf4j-api-1.7.36.pom", b"org.slf4jslf4j-api1.7.36"); + put(&base, MVN_JAR_KEY, MVN_PRISTINE); + let sfx_dir = fx.m2().join(format!("org/slf4j/slf4j-api/{MVN_SUFFIXED}")); + put( + &sfx_dir, + &format!("slf4j-api-{MVN_SUFFIXED}.pom"), + b"", + ); + put( + &sfx_dir, + &format!("slf4j-api-{MVN_SUFFIXED}.jar"), + &served(MULTI_RELEASE), + ); + let api = serve_hosted_api(golden, MVN_PURL, MVN_HOSTED_UUID, class_view()); + let (code, env, stderr) = scan_hosted_vex(&fx, &api); + assert_eq!(code, Some(0), "scan --mode hosted --vex: {env}\n{stderr}"); + assert_doc_attests(&fx.embedded_doc(), MVN_HOSTED_UUID, MVN_PURL, "redirected"); + // The standalone run over the same checkout reads the jar. + let (code, env) = fx.vex(&["--proxy-url", &api.uri()]); + assert_omitted( + code, + &env, + MVN_PURL, + "multi_release_unpatched_copy", + "standalone vex after the hosted scan", + ); +} + /// DOCUMENTED LIMITATION (design scope): an AGENT-mode patch (`apply` /// rewrites the installed jar in place) has no lockfile wiring — only the /// manifest records it. `apply --vex` attests it; with the manifest gone diff --git a/crates/socket-patch-cli/tests/gradle_agent_cli.rs b/crates/socket-patch-cli/tests/gradle_agent_cli.rs index 8204b71e77..2528b87f48 100644 --- a/crates/socket-patch-cli/tests/gradle_agent_cli.rs +++ b/crates/socket-patch-cli/tests/gradle_agent_cli.rs @@ -1304,6 +1304,151 @@ fn member_record_apply_repair_rollback_is_byte_exact() { ); } +// ── multi-release jars ────────────────────────────────────────────────── + +const CLASS: &str = "com/example/Victim.class"; +const CLASS_FOR_9: &str = "META-INF/versions/9/com/example/Victim.class"; +const OLD_CLASS: &[u8] = b"class Victim, vulnerable\n"; +const NEW_CLASS: &[u8] = b"class Victim, fixed\n"; +const OLD_FOR_9: &[u8] = b"class Victim for Java 9, vulnerable\n"; +const NEW_FOR_9: &[u8] = b"class Victim for Java 9, fixed\n"; +const MULTI_RELEASE: &[u8] = b"Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\n"; + +/// A jar that holds [`CLASS`] and a copy of it for Java 9 under +/// `META-INF/versions/9/`, with `manifest` as its manifest. +fn versioned_jar(manifest: &[u8], class: &[u8], for_9: &[u8]) -> Vec { + jar(&[ + ("META-INF/MANIFEST.MF", manifest), + (CLASS, class), + (CLASS_FOR_9, for_9), + ]) +} + +/// A patch that changes a class of a multi-release jar and not the copy of +/// that class under `META-INF/versions/9/`. The swap goes through and +/// stays (the base class is patched in `~/.m2` and in the Gradle cache), +/// and the run fails with `multi_release_unpatched_copy`, naming the jar, +/// the class and the copy: a Java 9 or later runtime still loads the old +/// code. A second run, which finds the jars already patched, says the +/// same, and so does `apply --check`. `vex` does not attest the package and +/// does not list the jar as one `apply` could patch. A dry run reports it +/// too. Rollback restores every copy byte for byte. +#[test] +fn multi_release_unpatched_copy_fails_apply_and_vex_withholds() { + const SAID: &str = "victim-1.0.jar carries an unpatched copy of com/example/Victim.class at \ + META-INF/versions/9/com/example/Victim.class"; + let pristine = versioned_jar(MULTI_RELEASE, OLD_CLASS, OLD_FOR_9); + let served = versioned_jar(MULTI_RELEASE, NEW_CLASS, OLD_FOR_9); + let f = fx(" mavenLocal()\n mavenCentral()\n"); + let m2 = f.m2(&[(JAR, &pristine), (POM, PRISTINE_POM)]); + let version = f.gradle(&[(JAR, &pristine), (POM, PRISTINE_POM)]); + f.manifest(&[(PURL, &[(CLASS, OLD_CLASS, NEW_CLASS)])]); + let before = f.snapshot(); + let (_rt, server) = service(&served); + + // A dry run says the patch would not take effect, and writes nothing. + f.run(&["apply", "--dry-run", "--vendor-url", &server.uri()]) + .failed() + .has("multi_release_unpatched_copy"); + assert_eq!(std::fs::read(m2.join(JAR)).unwrap(), pristine); + assert_eq!(hash_copies(&version, JAR)[0].1, pristine); + + for run in ["first", "already patched"] { + let out = f.run(&["apply", "--vendor-url", &server.uri()]); + out.failed().has("multi_release_unpatched_copy"); + let text = out.json.to_string(); + assert!(text.contains(SAID), "{run}: {text}"); + let failed: Vec<&serde_json::Value> = out.json["events"] + .as_array() + .unwrap() + .iter() + .filter(|e| e["action"] == "failed") + .collect(); + // One per copy, `~/.m2` and the Gradle hash directory, each under + // the code and none as a plain `apply_failed`. + assert_eq!(failed.len(), 2, "{run}: {text}"); + for event in failed { + assert_eq!( + event["errorCode"], "multi_release_unpatched_copy", + "{run}: {event}" + ); + } + assert_eq!(out.json["summary"]["applied"], 0, "{run}: {text}"); + // The patched class stays where the swap put it. + assert_eq!(std::fs::read(m2.join(JAR)).unwrap(), served, "{run}"); + assert_eq!(hash_copies(&version, JAR)[0].1, served, "{run}"); + } + + let check = f.run(&["apply", "--check", "--offline"]); + check.failed(); + assert_eq!( + check.json["events"][0]["errorCode"], "multi_release_unpatched_copy", + "{}", + check.json + ); + assert!(check.json.to_string().contains(SAID), "{}", check.json); + + let (out, statements) = f.vex(&[]); + assert_eq!(statements, 0, "{}", out.json); + out.has("multi_release_unpatched_copy"); + assert!(out.json.to_string().contains(SAID), "{}", out.json); + assert!( + !out.warning_codes() + .iter() + .any(|c| c == "vex_gradle_unpatched_copy"), + "{}", + out.json + ); + + f.run(&["rollback", "--offline"]).ok(); + let after: BTreeMap = f + .snapshot() + .into_iter() + .filter(|(k, _)| !k.contains(".socket/jvm-originals")) + .collect(); + assert_eq!( + after, before, + "rollback must restore every copy byte for byte" + ); +} + +/// The same patch applies cleanly, and is attested, when the patch changes +/// the copy for Java 9 as well, and when the jar's manifest does not make +/// it a multi-release jar (no runtime reads `META-INF/versions/` then). +#[test] +fn multi_release_copy_that_is_patched_or_inert_applies_and_attests() { + const PLAIN: &[u8] = b"Manifest-Version: 1.0\r\n\r\n"; + let both: &[(&str, &[u8], &[u8])] = &[ + (CLASS, OLD_CLASS, NEW_CLASS), + (CLASS_FOR_9, OLD_FOR_9, NEW_FOR_9), + ]; + let base_only: &[(&str, &[u8], &[u8])] = &[(CLASS, OLD_CLASS, NEW_CLASS)]; + for (what, manifest, record, for_9) in [ + ("the patch lists the copy", MULTI_RELEASE, both, NEW_FOR_9), + ("not a multi-release jar", PLAIN, base_only, OLD_FOR_9), + ] { + let f = fx(CENTRAL); + let version = f.gradle(&[(JAR, &versioned_jar(manifest, OLD_CLASS, OLD_FOR_9))]); + f.manifest(&[(PURL, record)]); + let served = versioned_jar(manifest, NEW_CLASS, for_9); + let (_rt, server) = service(&served); + let out = f.run(&["apply", "--vendor-url", &server.uri()]); + out.ok(); + assert!( + !out.json + .to_string() + .contains("multi_release_unpatched_copy"), + "{what}: {}", + out.json + ); + assert_eq!(hash_copies(&version, JAR)[0].1, served, "{what}"); + f.run(&["apply", "--check", "--offline"]).ok(); + let (out, statements) = f.vex(&[]); + out.ok(); + assert!(statements > 0, "{what}: {}", out.json); + } +} + // ── global prefix ─────────────────────────────────────────────────────── /// `--global-prefix` naming the Gradle user home (`.gradle`) or its diff --git a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs index 1cd6b794eb..784bedba2e 100644 --- a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs +++ b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs @@ -1316,6 +1316,262 @@ fn gradle_vendor_533_unpatched_classifier_copy_withholds_vex() { assert!(!vex.exists(), "{env}"); } +const CLASS: &str = "org/example/Foo.class"; +const CLASS_FOR_9: &str = "META-INF/versions/9/org/example/Foo.class"; +const MULTI_RELEASE: &[u8] = b"Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\n"; + +/// Make `foo`'s patch one of a class: the upstream jar in the local +/// repository holds [`CLASS`] and a copy of it for Java 9 under +/// `META-INF/versions/9/`, with `manifest` as its manifest, and the record +/// changes [`CLASS`] (and the copy for Java 9 as well when `listed`). +fn class_patch(root: &Path, manifest: &[u8], listed: bool) { + const OLD: &[u8] = b"class Foo, vulnerable\n"; + const OLD_FOR_9: &[u8] = b"class Foo for Java 9, vulnerable\n"; + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default(); + for (name, bytes) in [ + ("META-INF/MANIFEST.MF", manifest), + (CLASS, OLD), + (CLASS_FOR_9, OLD_FOR_9), + ] { + zw.start_file(name, opts).unwrap(); + zw.write_all(bytes).unwrap(); + } + write( + root, + "m2/org/example/foo/1.0/foo-1.0.jar", + &zw.finish().unwrap().into_inner(), + ); + let mut files = serde_json::Map::new(); + let patched = [(CLASS, OLD), (CLASS_FOR_9, OLD_FOR_9)]; + for (name, before) in patched.into_iter().take(if listed { 2 } else { 1 }) { + let after = [before, b"FIXED\n"].concat(); + write( + root, + &format!("proj/.socket/blobs/{}", git_sha256(&after)), + &after, + ); + files.insert( + name.to_string(), + serde_json::json!({ + "beforeHash": git_sha256(before), + "afterHash": git_sha256(&after), + }), + ); + } + let path = root.join("proj/.socket/manifest.json"); + let mut manifest: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + manifest["patches"][purl("foo")]["files"] = files.into(); + std::fs::write(path, serde_json::to_string_pretty(&manifest).unwrap()).unwrap(); +} + +/// A patch that changes a class of a multi-release jar and not the copy of +/// that class under `META-INF/versions/9/`: a Java 9 or later runtime loads +/// the copy, so the build stays unpatched there. In a Maven reactor and in +/// a Gradle build alike the jar is vendored all the same, with a degraded +/// warning that names the jar, the class and the copy, on the first run +/// and on an in-sync one; `vendor --check` passes and `repair` rebuilds +/// nothing, since the artifact holds every file of the patch; and `vex` +/// does not attest the package, with or without `--no-verify`. A revert +/// restores every byte. +#[test] +fn multi_release_unpatched_copy_degrades_vendor_and_withholds_vex() { + const SAID: &str = "reason: multi_release_unpatched_copy: foo-1.0.jar carries an unpatched \ + copy of org/example/Foo.class at \ + META-INF/versions/9/org/example/Foo.class"; + for shape in [Shape::Reactor, Shape::Gradle] { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fixture(root, shape, &[("foo", FOO_UUID)]); + class_patch(root, MULTI_RELEASE, false); + let pristine = snapshot(root); + for run in ["first", "in sync"] { + let env = ok(root, &["vendor"]); + assert!(env.to_string().contains(SAID), "{run}: {env}"); + } + ok(root, &["vendor", "--check"]); + // Nor is it an artifact for `repair` to rebuild. + let vendored = snapshot(root); + let env = ok(root, &["repair"]); + assert_eq!(env["summary"]["rebuilt"], 0, "{env}"); + assert_eq!(snapshot(root), vendored); + let vex = root.join("vex.json"); + for no_verify in [false, true] { + let mut args = vec![ + "vex", + "-O", + vex.to_str().unwrap(), + "--product", + "pkg:generic/x@1", + ]; + args.extend(no_verify.then_some("--no-verify")); + let (_, env) = socket(root, &args); + assert_eq!( + events(&env), + [( + purl("foo"), + "skipped".to_string(), + "multi_release_unpatched_copy".to_string() + )], + "no_verify={no_verify}: {env}" + ); + assert!( + env.to_string().contains( + "carries an unpatched copy of org/example/Foo.class at \ + META-INF/versions/9/org/example/Foo.class" + ), + "{env}" + ); + assert!(!vex.exists(), "{env}"); + } + ok(root, &["vendor", "--revert"]); + assert_eq!(snapshot(root), pristine); + } +} + +/// A vendored jar that cannot be opened, or is not there, cannot be +/// checked for versioned copies, and a jar that is not checked is not +/// attested. With verification, `vex` refuses it under verification's own +/// reason, as before. Under `--no-verify`, which skips that verification, +/// `vex` used to write `not_affected` for it; now it omits the package as +/// one whose jar could not be checked. +#[test] +fn a_vendored_jar_that_cannot_be_opened_is_not_attested_under_no_verify() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fixture(root, Shape::Reactor, &[("foo", FOO_UUID)]); + class_patch(root, MULTI_RELEASE, true); + ok(root, &["vendor"]); + let tree_jar = root.join( + "proj/.socket/vendor/maven2/org/example/foo/1.0-socket.1d3c1fd2/foo-1.0-socket.1d3c1fd2.jar", + ); + let vex = root.join("vex.json"); + let run = |no_verify: bool| { + let mut args = vec![ + "vex", + "-O", + vex.to_str().unwrap(), + "--product", + "pkg:generic/x@1", + ]; + args.extend(no_verify.then_some("--no-verify")); + socket(root, &args).1 + }; + // Control: the jar as vendored is attested either way. + for no_verify in [false, true] { + let env = run(no_verify); + assert_eq!( + events(&env)[0].1, + "verified", + "no_verify={no_verify}: {env}" + ); + std::fs::remove_file(&vex).unwrap(); + } + + std::fs::write(&tree_jar, b"not a jar").unwrap(); + let env = run(false); + assert_eq!( + events(&env), + [( + purl("foo"), + "skipped".to_string(), + "vendor_artifact_unreadable".to_string() + )], + "{env}" + ); + assert!(!vex.exists(), "{env}"); + let env = run(true); + assert_eq!( + events(&env), + [( + purl("foo"), + "skipped".to_string(), + "multi_release_unpatched_copy".to_string() + )], + "{env}" + ); + const UNCHECKED: &str = "foo-1.0-socket.1d3c1fd2.jar could not be checked for unpatched \ + copies of the patched members under META-INF/versions"; + const NO_STATEMENT: &str = "no statement is emitted for a jar that could not be checked."; + let said = env.to_string(); + assert!( + said.contains(UNCHECKED) && said.contains(NO_STATEMENT), + "{env}" + ); + assert!(!vex.exists(), "{env}"); + + // The jar gone altogether: the same two answers. + std::fs::remove_file(&tree_jar).unwrap(); + let env = run(false); + assert_eq!( + events(&env), + [( + purl("foo"), + "skipped".to_string(), + "vendor_artifact_missing".to_string() + )], + "{env}" + ); + let env = run(true); + assert_eq!( + events(&env), + [( + purl("foo"), + "skipped".to_string(), + "multi_release_unpatched_copy".to_string() + )], + "{env}" + ); + let said = env.to_string(); + assert!( + said.contains(UNCHECKED) && said.contains(NO_STATEMENT), + "{env}" + ); + assert!(!vex.exists(), "{env}"); +} + +/// The same jar is vendored with nothing to say, and attested, when no +/// runtime loads the copy for Java 9 (the manifest does not make the jar a +/// multi-release one) or when the patch changes that copy too. +#[test] +fn multi_release_copy_that_is_inert_or_patched_attests() { + for (what, manifest, listed) in [ + ( + "not a multi-release jar", + &b"Manifest-Version: 1.0\r\n\r\n"[..], + false, + ), + ("the patch lists the copy", MULTI_RELEASE, true), + ] { + for shape in [Shape::Reactor, Shape::Gradle] { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fixture(root, shape, &[("foo", FOO_UUID)]); + class_patch(root, manifest, listed); + let env = ok(root, &["vendor"]); + assert!( + !env.to_string().contains("multi_release_unpatched_copy"), + "{what}: {env}" + ); + 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", "{what}"); + } + } +} + /// #513 / #459: a reactor `${prop}` version that can't be pinned with /// certainty (undefined in the checkout, or raised by a profile) is left /// as is with a warning, and `vex` does not attest the package the build diff --git a/crates/socket-patch-core/src/patch/jar_manifest.rs b/crates/socket-patch-core/src/patch/jar_manifest.rs index 77159d6450..b67cce3744 100644 --- a/crates/socket-patch-core/src/patch/jar_manifest.rs +++ b/crates/socket-patch-core/src/patch/jar_manifest.rs @@ -192,6 +192,51 @@ fn terminated(manifest: &[u8]) -> &[u8] { } } +/// Whether `manifest` makes its jar a multi-release jar, decided as the JDK +/// decides it (`java.util.jar.JarFile.checkForSpecialAttributes`, read in +/// OpenJDK 11, 17, 21 and the current sources, and run on OpenJDK 11, 17, +/// 21 and 26): +/// +/// * the bytes `Multi-Release: true` must stand somewhere in the file, in +/// any letter case, on one line (the JDK searches for them before it +/// parses anything, so a value wrapped onto a continuation line never +/// counts); +/// * and the main section must hold a `Multi-Release` attribute, its name +/// in any case, whose value is `true` in any case +/// (`Boolean.parseBoolean`) and nothing more: `true ` with a trailing +/// space is not. Of two such attributes the last one counts. One in a +/// per-entry section does not. +/// +/// A last line with no terminator is one the JDK never reads. Only the +/// main section is parsed, so nothing a per-entry section holds can make +/// this fail. `Err` says why the main section could not be read as +/// `Name: value` lines. +pub(crate) fn is_multi_release(manifest: &[u8]) -> Result { + const ANNOUNCED: &[u8] = b"multi-release: true"; + if !manifest + .windows(ANNOUNCED.len()) + .any(|window| window.eq_ignore_ascii_case(ANNOUNCED)) + { + return Ok(false); + } + // The main section: every line before the first blank one. + let manifest = terminated(manifest); + let mut end = 0; + while end < manifest.len() { + let (line, next) = line_end(manifest, end); + if line == end { + break; + } + end = next; + } + let main = attributes(&manifest[..end])?; + Ok(main + .iter() + .rev() + .find(|attribute| attribute.name.eq_ignore_ascii_case(b"Multi-Release")) + .is_some_and(|attribute| attribute.value.eq_ignore_ascii_case(b"true"))) +} + /// The digest attributes of `is` that must be the member's own, when `is` /// is `was` as signing again leaves a section: every line of `was` kept in /// order, digest attributes added, and, for a member the record `changes`, diff --git a/crates/socket-patch-core/src/patch/jar_members.rs b/crates/socket-patch-core/src/patch/jar_members.rs index 09c2090379..6b2b970fc2 100644 --- a/crates/socket-patch-core/src/patch/jar_members.rs +++ b/crates/socket-patch-core/src/patch/jar_members.rs @@ -174,6 +174,12 @@ impl Jar { if name.ends_with('/') { return None; } + self.name_index().get(name.as_bytes()).copied() + } + + /// Entry indices by raw name, read from the central directory on first + /// use. + fn name_index(&mut self) -> &std::collections::HashMap, usize> { if self.names.is_none() { let mut names = std::collections::HashMap::new(); for index in 0..self.zip.len() { @@ -183,7 +189,48 @@ impl Jar { } self.names = Some(names); } - self.names.as_ref()?.get(name.as_bytes()).copied() + self.names.as_ref().expect("built above") + } + + /// Hand `each` the raw name of every member, with its place among the + /// names the central directory lists (two entries of one name count + /// once), in that order. + /// + /// The names come from the central directory alone. No local header is + /// read and nothing is inflated, so an entry whose own header does not + /// parse is listed like any other, and a jar of many thousand entries + /// costs no seek per entry. (The lookups by name above go through + /// [`Self::name_index`], which does read each entry's header once and + /// leaves out an entry it cannot read.) + /// + /// The zip reader keys its entries by the raw bytes of their names and + /// hands a name out decoded. Where the decoded name spells those bytes + /// (an ASCII name, or one flagged UTF-8: nearly every name of every + /// jar) the reader's lookup by it lands on the same entry, which shows + /// the bytes without reading anything. Only a name in another encoding + /// is taken from its entry, and such an entry that cannot be read is the + /// `Err`: a name that is not known is not passed over. + pub(crate) fn member_names( + &mut self, + mut each: impl FnMut(&[u8], usize), + ) -> Result<(), JarError> { + for index in 0..self.zip.len() { + let decoded = self.zip.name_for_index(index); + if let Some(name) = decoded.filter(|name| self.zip.index_for_name(name) == Some(index)) + { + if !name.ends_with('/') { + each(name.as_bytes(), index); + } + continue; + } + let entry = self.zip.by_index_raw(index).map_err(|e| { + JarError::Unreadable(format!("the name of entry {index} cannot be read ({e})")) + })?; + if entry.name_raw().last() != Some(&b'/') { + each(entry.name_raw(), index); + } + } + Ok(()) } fn over_budget(&self) -> JarError { @@ -921,6 +968,18 @@ pub(crate) mod testing { archive } + /// Overwrite the signature of the local header of `name` in `jar`: the + /// central directory still lists the entry, and nothing can read it. + pub(crate) fn break_local_header(jar: &mut [u8], name: &str) { + let at = zip::ZipArchive::new(std::io::Cursor::new(&*jar)) + .unwrap() + .by_name(name) + .unwrap() + .header_start() as usize; + assert_eq!(&jar[at..at + 4], b"PK\x03\x04"); + jar[at..at + 4].copy_from_slice(b"XXXX"); + } + /// [`jar_with_modes`] of plain files. pub(crate) fn jar(members: &[(&str, &[u8])]) -> Vec { let members: Vec<(&str, &[u8], Option)> = @@ -987,6 +1046,41 @@ mod tests { assert_eq!(jar.member_git_sha256("org/x/absent.class").unwrap(), None); } + /// The member names are the central directory's, raw: an entry whose + /// own header does not parse is listed like any other (the lookup by + /// name, which reads that header, does not find it), a UTF-8 name + /// written without the UTF-8 flag comes back as its bytes, and a + /// directory entry is no member. + #[test] + fn member_names_are_the_central_directorys() { + const NAME: &str = "org/x/\u{dc}n\u{ef}.class"; + let mut bytes = testing::without_utf8_flag(jar(&[ + ("a/B.class", b"b"), + ("dir/", b""), + (NAME, b"code"), + ("META-INF/versions/9/a/B.class", b"nine"), + ])); + testing::break_local_header(&mut bytes, "META-INF/versions/9/a/B.class"); + let mut jar = Jar::of_bytes(&bytes).unwrap(); + let mut names = Vec::new(); + jar.member_names(|name, index| names.push((name.to_vec(), index))) + .unwrap(); + assert_eq!( + names, + [ + (b"a/B.class".to_vec(), 0), + (NAME.as_bytes().to_vec(), 2), + (b"META-INF/versions/9/a/B.class".to_vec(), 3), + ] + ); + assert_eq!( + jar.member_git_sha256("META-INF/versions/9/a/B.class") + .unwrap(), + None + ); + assert!(jar.member_git_sha256("a/B.class").unwrap().is_some()); + } + /// A member's git hash is the buffered hash of its bytes, stored, /// deflated or empty; an absent member is `None`. #[test] diff --git a/crates/socket-patch-core/src/patch/mod.rs b/crates/socket-patch-core/src/patch/mod.rs index c653345e85..26844b4021 100644 --- a/crates/socket-patch-core/src/patch/mod.rs +++ b/crates/socket-patch-core/src/patch/mod.rs @@ -10,6 +10,7 @@ pub(crate) mod gem_source; pub(crate) mod jar_manifest; pub(crate) mod jar_members; pub mod jvm_jar; +pub mod multi_release; pub(crate) mod npm_bin; pub mod package; pub(crate) mod path_safety; diff --git a/crates/socket-patch-core/src/patch/multi_release.rs b/crates/socket-patch-core/src/patch/multi_release.rs new file mode 100644 index 0000000000..7cc2499aa7 --- /dev/null +++ b/crates/socket-patch-core/src/patch/multi_release.rs @@ -0,0 +1,854 @@ +//! Copies of a patched member that a multi-release jar holds under +//! `META-INF/versions//` and that the patch does not change. +//! +//! A patch record lists the members it changes (`a/B.class`). A +//! multi-release jar may hold the same class again per Java release +//! (`META-INF/versions/9/a/B.class`), and a runtime of that release or later +//! loads that copy **instead of** the base entry. When the record does not +//! list the versioned copy and its bytes are not the patched ones, the +//! patched class is in the jar and the code that runs is still the old one. +//! [`check_jar`] finds those copies; the patch service is expected to list +//! them, and this is the check that it did. +//! +//! # What a JVM loads +//! +//! The rules are those of `java.util.jar.JarFile` (`isMultiRelease`, +//! `getVersionedEntry`) and `java.util.zip.ZipFile.Source` +//! (`getMetaVersion`), read in the OpenJDK 11, 17 and 21 sources and the +//! current ones, and run against OpenJDK 11, 17, 21 and 26: +//! +//! * Versioned entries count only in a jar whose manifest says so +//! ([`jar_manifest::is_multi_release`]): a main attribute +//! `Multi-Release` with the value `true`, both in any letter case. +//! Without it, or with any other value, or with no manifest, the entries +//! under `META-INF/versions/` are never read. The manifest is the entry +//! named `META-INF/MANIFEST.MF` in any letter case, the last one in the +//! central directory when there are several. +//! * A versioned entry is looked up under exactly +//! `META-INF/versions//`: that spelling, `` a decimal number +//! with no leading zero. `meta-inf/versions/9/…`, `versions/09/…` and +//! `versions/x/…` are never loaded. +//! * A Java N runtime loads `` from the highest `` that is at most +//! N and holds it, and from the base entry when none does. So every +//! versioned copy is what some runtime loads, and a copy under a higher +//! `` overrides one under a lower `` as it overrides the base. +//! * `` starts at [`FIRST_VERSIONED`], 8, not at 9. The JAR +//! specification and the `JarFile` documentation say `8 < n`, and OpenJDK +//! 11 ignores `META-INF/versions/8/`. OpenJDK 17, 21 and 26 load it: their +//! lookup stops only below the base version, which is 8. A copy there is +//! one a current runtime runs. Directories 7 and below are ignored by all +//! of them. +//! * A `` that starts with `META-INF/` is never looked up as a +//! versioned entry: `META-INF/versions/9/META-INF/x` does not override +//! `META-INF/x`. +//! +//! (`-Djdk.util.jar.enableMultiRelease=force` makes a runtime read +//! versioned entries without the manifest attribute. That is a setting of +//! one JVM invocation, which no file of the jar or of a project records; +//! it is not considered here.) +//! +//! # What counts as unpatched +//! +//! A versioned entry that overrides a member the record changes is fine +//! when the record lists that exact path (the member check holds it to its +//! own `afterHash`), or when its bytes are the patched ones of a member it +//! overrides. Anything else is an unpatched copy a runtime loads. A +//! versioned copy of a member the record does not change is not looked at. +//! +//! # Cost +//! +//! The names come from the central directory alone: no entry is read to +//! list them. The manifest is inflated only when the jar holds a versioned +//! entry that could be such a copy, and then only those entries are hashed, +//! within the limits of [`super::jar_members`]. (Reading a member by name +//! makes the reader look at each entry's own header once; a jar with no +//! such copy never gets there.) +//! +//! An entry the directory lists and nothing can read (its own header does +//! not parse) is not passed over: when it is a versioned copy of a patched +//! member, or the manifest of a jar that holds one, the copy is reported +//! as one that could not be checked. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::io::{Read, Seek}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use super::jar_manifest::{self, MANIFEST}; +use super::jar_members::Jar; +use crate::manifest::schema::PatchFileInfo; +use crate::patch::apply::normalize_file_path; + +/// A multi-release jar holds a copy of a patched member, under +/// `META-INF/versions//`, that the patch does not change (or the jar +/// could not be read to rule that out). The patched member is in place; a +/// runtime that loads the versioned copy runs the unpatched code. +pub const UNPATCHED_COPY: &str = "multi_release_unpatched_copy"; + +/// The lowest `` of `META-INF/versions//` that some JVM loads (see +/// the module docs: OpenJDK 17 and later load 8). +const FIRST_VERSIONED: u32 = 8; + +const VERSIONS: &str = "META-INF/versions/"; +const META_INF: &str = "META-INF/"; + +/// How many versioned paths [`Finding::describe`] spells out per member. +const SHOWN: usize = 3; + +/// One patched member and the versioned entries that override it without +/// carrying the patch. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VersionedCopies { + /// The member as the record names it. + pub member: String, + /// `META-INF/versions//…`, lowest `` first. + pub paths: Vec, +} + +/// What [`check_jar`] found in a jar that is not clean. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Finding { + /// By member name. Empty only when the jar itself could not be opened. + pub copies: Vec, + /// Set when the copies could not be judged: the manifest that says + /// whether a runtime reads them, or a copy itself, could not be read. + /// They may be unpatched copies a runtime loads; a jar that is not + /// checked is not taken for patched. + pub unchecked: Option, +} + +impl Finding { + /// Whether an unpatched copy is established: the jar was read, a + /// runtime reads its versioned entries, and one of them is not the + /// patch's. Otherwise the jar, or a copy in it, could not be checked: + /// there may be no such copy, and nothing shows it. + pub fn established(&self) -> bool { + self.unchecked.is_none() + } + + /// Why `vex` writes no statement for the jar, as a clause to follow + /// [`Self::describe`]: what would clear it differs between a copy that + /// is there and a jar that could not be checked. + pub fn no_statement(&self) -> &'static str { + match self.established() { + true => "no statement is emitted until the patch changes that copy as well", + false => "no statement is emitted for a jar that could not be checked", + } + } + + /// The finding as a clause about the jar `jar` (a file name or a path), + /// with no closing stop. + pub fn describe(&self, jar: &str) -> String { + let Some(first) = self.copies.first() else { + let why = self.unchecked.as_deref().unwrap_or("it cannot be read"); + return format!( + "{jar} could not be checked for unpatched copies of the patched members under \ + META-INF/versions ({why}); a Java runtime may load such a copy instead of the \ + patched member" + ); + }; + let mut paths: Vec<&str> = first.paths.iter().take(SHOWN).map(String::as_str).collect(); + if first.paths.len() > SHOWN { + paths.push("…"); + } + let paths = paths.join(", "); + let more = match self.copies.len() - 1 { + 0 => String::new(), + 1 => " (and of 1 more patched member)".to_string(), + n => format!(" (and of {n} more patched members)"), + }; + let member = &first.member; + match &self.unchecked { + None => format!( + "{jar} carries an unpatched copy of {member} at {paths}{more}; it is a \ + multi-release jar, so a Java runtime of that release or later loads that \ + copy, not the patched one" + ), + Some(why) => format!( + "{jar} could not be checked for unpatched copies of the patched members under \ + META-INF/versions ({why}); it holds {member} again at {paths}{more}, which a \ + Java runtime may load instead of the patched one" + ), + } + } +} + +/// `(n, name)` when `entry` is `META-INF/versions//` as a JVM +/// looks a versioned entry up (see the module docs). +fn versioned(entry: &str) -> Option<(u32, &str)> { + let (digits, name) = entry.strip_prefix(VERSIONS)?.split_once('/')?; + if digits.starts_with('0') || !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + // The JDK keeps the number in an `int`. + let n = u32::try_from(digits.parse::().ok()?).ok()?; + (n >= FIRST_VERSIONED + && !name.is_empty() + && !name.ends_with('/') + && !name.starts_with(META_INF)) + .then_some((n, name)) +} + +/// A member the record changes, as the entry a runtime resolves its class +/// or resource name to. +struct Patched<'a> { + /// The member as the record names it (normalized). + member: &'a str, + /// The `` of a versioned member; 0 for a base entry, which every + /// versioned copy overrides. + release: u32, + after_hash: &'a str, +} + +/// The versioned copies of the members `files` changes that the jar `jar` +/// holds without the patch; `None` when it holds none a runtime loads. +/// +/// `files` is a member-keyed record (see [`super::jvm_jar::classify`]). The +/// jar is one whose listed members already verify: this looks only at +/// entries the record does not list. +pub(crate) fn check_jar( + jar: &mut Jar, + files: &HashMap, +) -> Option { + let listed: HashSet<&str> = files.keys().map(|key| normalize_file_path(key)).collect(); + // The patched entries by the name a runtime asks for. + let mut patched: HashMap<&str, Vec>> = HashMap::new(); + for (key, info) in files { + let member = normalize_file_path(key); + let (release, name) = versioned(member).unwrap_or((0, member)); + // Never looked up as a versioned entry. + if name.starts_with(META_INF) { + continue; + } + patched.entry(name).or_default().push(Patched { + member, + release, + after_hash: &info.after_hash, + }); + } + if patched.is_empty() { + return None; + } + + // Names only: the versioned entries that override a patched member and + // are not the record's own, and the manifest a JVM would read. + struct Candidate<'a> { + path: String, + release: u32, + overrides: Vec<&'a Patched<'a>>, + } + let mut candidates: Vec> = Vec::new(); + let mut manifest: Option<(usize, String)> = None; + let names = jar.member_names(|raw, index| { + // A record names its members in UTF-8, and so does the manifest. + let Ok(entry) = std::str::from_utf8(raw) else { + return; + }; + if entry.eq_ignore_ascii_case(MANIFEST) + && manifest.as_ref().is_none_or(|(at, _)| index > *at) + { + manifest = Some((index, entry.to_string())); + } + let Some((release, name)) = versioned(entry) else { + return; + }; + if listed.contains(entry) { + return; + } + let overrides: Vec<&Patched<'_>> = patched + .get(name) + .into_iter() + .flatten() + .filter(|p| p.release < release) + .collect(); + if !overrides.is_empty() { + candidates.push(Candidate { + path: entry.to_string(), + release, + overrides, + }); + } + }); + // A name that could not be read may be such a copy's. + if let Err(e) = names { + return unopened(e); + } + if candidates.is_empty() { + return None; + } + + // Whether a runtime reads versioned entries of this jar at all. The + // directory lists the manifest: one that cannot be read is not taken + // for one that says nothing. + let multi_release = match &manifest { + None => Ok(false), + Some((_, name)) => match jar.member_bytes(name) { + Ok(Some(bytes)) => jar_manifest::is_multi_release(&bytes) + .map_err(|why| format!("its manifest cannot be read: {why}")), + Ok(None) => Err("its manifest cannot be read: its entry does not parse".to_string()), + Err(e) => Err(format!("its manifest cannot be read: {e}")), + }, + }; + let mut unchecked = match multi_release { + Ok(false) => return None, + Ok(true) => None, + Err(why) => Some(why), + }; + + // A copy whose bytes are the patched ones of a member it overrides + // carries the patch. + candidates.sort_by(|a, b| (a.release, &a.path).cmp(&(b.release, &b.path))); + let mut copies: BTreeMap<&str, Vec> = BTreeMap::new(); + for candidate in candidates { + match jar.member_git_sha256(&candidate.path) { + Ok(Some(hash)) + if candidate + .overrides + .iter() + .any(|p| p.after_hash.eq_ignore_ascii_case(&hash)) => + { + continue + } + Ok(Some(_)) => {} + // The directory lists it and the reader cannot find it: its + // own header does not parse. + Ok(None) => { + let path = &candidate.path; + unchecked.get_or_insert(format!("{path} cannot be read: its entry does not parse")); + } + Err(e) => { + unchecked.get_or_insert(format!("{} cannot be read: {e}", candidate.path)); + } + } + // Named by the lowest entry it overrides: the base member when the + // record changes it. + let member = candidate + .overrides + .iter() + .min_by_key(|p| p.release) + .map(|p| p.member) + .expect("a candidate overrides a patched member"); + copies.entry(member).or_default().push(candidate.path); + } + if copies.is_empty() { + return None; + } + Some(Finding { + copies: copies + .into_iter() + .map(|(member, paths)| VersionedCopies { + member: member.to_string(), + paths, + }) + .collect(), + unchecked, + }) +} + +/// A jar that could not be opened to be checked. +fn unopened(why: impl std::fmt::Display) -> Option { + Some(Finding { + copies: Vec::new(), + unchecked: Some(format!("it cannot be read: {why}")), + }) +} + +/// [`check_jar`] over the jar bytes `jar`. Blocking: an async caller asks +/// [`check_bytes_off_thread`]. +pub fn check_bytes(jar: &[u8], files: &HashMap) -> Option { + match Jar::of_bytes(jar) { + Ok(mut jar) => check_jar(&mut jar, files), + Err(e) => unopened(e), + } +} + +/// `check` on the blocking pool: it parses a jar's directory and inflates +/// its manifest and the copies in question, which is no work for an async +/// worker. +/// +/// A check that does not finish (its task panicked, or the runtime dropped +/// it) is a finding: nothing it would have found is known, and a jar that +/// is not checked is not taken for patched. Every caller gets the same +/// answer for it, whichever command asks. +async fn off_thread(check: impl FnOnce() -> Option + Send + 'static) -> Option { + match tokio::task::spawn_blocking(check).await { + Ok(found) => found, + Err(e) => Some(Finding { + copies: Vec::new(), + unchecked: Some(format!("the check did not finish ({e})")), + }), + } +} + +/// [`check_file`] off the async workers. +pub async fn check_file_off_thread( + path: PathBuf, + files: HashMap, +) -> Option { + off_thread(move || check_file(&path, &files)).await +} + +/// [`check_bytes`] off the async workers, over bytes the caller keeps. +pub async fn check_bytes_off_thread( + jar: Arc>, + files: HashMap, +) -> Option { + off_thread(move || check_bytes(&jar, &files)).await +} + +/// [`check_jar`] over the jar file at `path`, read in place (the jar is +/// not held in memory). Blocking: an async caller asks +/// [`check_file_off_thread`]. +pub fn check_file(path: &Path, files: &HashMap) -> Option { + // The guarded opener: a FIFO at the path fails instead of blocking. + let (file, metadata) = match crate::utils::fs::open_regular_file_sync(path) { + Ok(opened) => opened, + Err(e) => return unopened(e), + }; + match Jar::open(std::io::BufReader::new(file), metadata.len()) { + Ok(mut jar) => check_jar(&mut jar, files), + Err(e) => unopened(e), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::hash::git_sha256::compute_git_sha256_from_bytes; + use crate::patch::jar_members::testing::jar; + + const CLASS: &str = "a/B.class"; + const V9: &str = "META-INF/versions/9/a/B.class"; + const PATCHED: &[u8] = b"class B, fixed"; + const OLD: &[u8] = b"class B, vulnerable"; + const MULTI_RELEASE: &[u8] = b"Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\n"; + const PLAIN: &[u8] = b"Manifest-Version: 1.0\r\n\r\n"; + + fn info(before: &[u8], after: &[u8]) -> PatchFileInfo { + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(before), + after_hash: compute_git_sha256_from_bytes(after), + } + } + + /// The record that changes [`CLASS`] to [`PATCHED`]. + fn record() -> HashMap { + HashMap::from([(CLASS.to_string(), info(OLD, PATCHED))]) + } + + /// A patched jar: `manifest`, the patched [`CLASS`] and `extra`. + fn patched(manifest: &[u8], extra: &[(&str, &[u8])]) -> Vec { + let mut members: Vec<(&str, &[u8])> = vec![(MANIFEST, manifest), (CLASS, PATCHED)]; + members.extend_from_slice(extra); + jar(&members) + } + + fn found(jar: &[u8], files: &HashMap) -> Vec<(String, Vec)> { + let finding = check_bytes(jar, files).expect("a finding"); + assert_eq!(finding.unchecked, None); + finding + .copies + .into_iter() + .map(|c| (c.member, c.paths)) + .collect() + } + + /// The case of the issue: a multi-release jar whose patched class has + /// an unlisted, unpatched copy under `META-INF/versions/9/`. + #[test] + fn an_unpatched_versioned_copy_of_a_patched_class_is_found() { + let bytes = patched(MULTI_RELEASE, &[(V9, OLD), ("a/C.class", b"c")]); + assert_eq!( + found(&bytes, &record()), + [(CLASS.to_string(), vec![V9.to_string()])] + ); + let finding = check_bytes(&bytes, &record()).unwrap(); + assert!(finding.established()); + assert_eq!( + finding.no_statement(), + "no statement is emitted until the patch changes that copy as well" + ); + let text = finding.describe("b-1.0.jar"); + assert_eq!( + text, + "b-1.0.jar carries an unpatched copy of a/B.class at META-INF/versions/9/a/B.class; \ + it is a multi-release jar, so a Java runtime of that release or later loads that \ + copy, not the patched one" + ); + // Read in place, a file gives the same answer. + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("b-1.0.jar"); + std::fs::write(&path, &bytes).unwrap(); + assert_eq!(check_file(&path, &record()), check_bytes(&bytes, &record())); + // A record key may carry the `package/` prefix. + let prefixed = HashMap::from([(format!("package/{CLASS}"), info(OLD, PATCHED))]); + assert_eq!( + found(&bytes, &prefixed), + [(CLASS.to_string(), vec![V9.to_string()])] + ); + } + + /// A versioned copy the record lists, or whose bytes are the patched + /// member's, carries the patch. + #[test] + fn a_listed_or_identical_versioned_copy_is_clean() { + let listed = HashMap::from([ + (CLASS.to_string(), info(OLD, PATCHED)), + (V9.to_string(), info(b"nine, old", b"nine, fixed")), + ]); + let bytes = patched(MULTI_RELEASE, &[(V9, b"nine, fixed")]); + assert_eq!(check_bytes(&bytes, &listed), None); + let same = patched(MULTI_RELEASE, &[(V9, PATCHED)]); + assert_eq!(check_bytes(&same, &record()), None); + } + + /// Without `Multi-Release: true` in the main section no runtime reads + /// the versioned entries, whatever they hold. + #[test] + fn versioned_entries_are_inert_without_the_manifest_attribute() { + let in_a_section: &[u8] = + b"Manifest-Version: 1.0\r\n\r\nName: a/B.class\r\nMulti-Release: true\r\n\r\n"; + for manifest in [ + PLAIN, + b"Manifest-Version: 1.0\r\nMulti-Release: false\r\n\r\n", + // The value is `true` and nothing more. + b"Manifest-Version: 1.0\r\nMulti-Release: true \r\n\r\n", + b"Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\n", + b"Manifest-Version: 1.0\r\nMulti-Release: yes\r\n\r\n", + // Wrapped onto a continuation line: the JDK never finds it. + b"Manifest-Version: 1.0\r\nMulti-Release: tr\r\n ue\r\n\r\n", + // A last line with no terminator is never read. + b"Manifest-Version: 1.0\nMulti-Release: true", + // Not a main attribute. + in_a_section, + // The last of two counts. + b"Multi-Release: true\r\nMulti-Release: false\r\n\r\n", + ] { + let bytes = patched(manifest, &[(V9, OLD)]); + assert_eq!( + check_bytes(&bytes, &record()), + None, + "{}", + String::from_utf8_lossy(manifest) + ); + } + // No manifest at all. + let bare = jar(&[(CLASS, PATCHED), (V9, OLD)]); + assert_eq!(check_bytes(&bare, &record()), None); + } + + /// The attribute's name and value are read in any letter case, with any + /// of the three line endings, and so is the manifest's own name. + #[test] + fn the_manifest_attribute_is_read_as_the_jdk_reads_it() { + for manifest in [ + MULTI_RELEASE, + b"Manifest-Version: 1.0\r\nMulti-Release: TRUE\r\n\r\n", + b"Manifest-Version: 1.0\r\nmulti-release: True\r\n\r\n", + b"Manifest-Version: 1.0\nMulti-Release: true\n", + b"Manifest-Version: 1.0\rMulti-Release: true\r", + b"Multi-Release: false\r\nMulti-Release: true\r\n\r\n", + ] { + let bytes = patched(manifest, &[(V9, OLD)]); + assert_eq!( + found(&bytes, &record()), + [(CLASS.to_string(), vec![V9.to_string()])], + "{}", + String::from_utf8_lossy(manifest) + ); + } + let lower = jar(&[ + ("meta-inf/manifest.mf", MULTI_RELEASE), + (CLASS, PATCHED), + (V9, OLD), + ]); + assert_eq!(found(&lower, &record()).len(), 1); + // Of two manifests the JDK reads the last one in the directory. + let two = |first: &[u8], second: &[u8]| { + jar(&[ + (MANIFEST, first), + ("META-INF/Manifest.mf", second), + (CLASS, PATCHED), + (V9, OLD), + ]) + }; + assert_eq!(check_bytes(&two(MULTI_RELEASE, PLAIN), &record()), None); + assert_eq!(found(&two(PLAIN, MULTI_RELEASE), &record()).len(), 1); + } + + /// Only `META-INF/versions//` with a plain decimal `` of 8 or more + /// is a directory a runtime reads. 8 is one: OpenJDK 17 and later load + /// it, whatever the specification says. + #[test] + fn only_directories_a_runtime_reads_count() { + for inert in [ + "META-INF/versions/7/a/B.class", + "META-INF/versions/1/a/B.class", + "META-INF/versions/0/a/B.class", + "META-INF/versions/09/a/B.class", + "META-INF/versions/x/a/B.class", + "META-INF/versions/9x/a/B.class", + "META-INF/versions/-9/a/B.class", + "META-INF/versions/99999999999/a/B.class", + "META-INF/versions//a/B.class", + "META-INF/versions/a/B.class", + "meta-inf/versions/9/a/B.class", + "META-INF/Versions/9/a/B.class", + "versions/9/a/B.class", + "META-INF/versions/9/x/a/B.class", + ] { + let bytes = patched(MULTI_RELEASE, &[(inert, OLD)]); + assert_eq!(check_bytes(&bytes, &record()), None, "{inert}"); + } + for loaded in [ + "META-INF/versions/8/a/B.class", + "META-INF/versions/9/a/B.class", + "META-INF/versions/17/a/B.class", + "META-INF/versions/2147483647/a/B.class", + ] { + let bytes = patched(MULTI_RELEASE, &[(loaded, OLD)]); + assert_eq!( + found(&bytes, &record()), + [(CLASS.to_string(), vec![loaded.to_string()])], + "{loaded}" + ); + } + } + + /// A versioned copy of a class the record does not change is none of + /// the patch's business, and a name under `META-INF/` is never looked + /// up as a versioned entry. + #[test] + fn copies_of_other_members_are_not_looked_at() { + let bytes = patched( + MULTI_RELEASE, + &[ + ("a/C.class", b"c"), + ("META-INF/versions/9/a/C.class", b"c for 9"), + ("META-INF/versions/9/a/B$1.class", b"inner"), + ("META-INF/versions/9/b/a/B.class", b"other package"), + ], + ); + assert_eq!(check_bytes(&bytes, &record()), None); + const NOTICE: &str = "META-INF/NOTICE.txt"; + let notice = HashMap::from([(NOTICE.to_string(), info(b"old", b"new"))]); + let bytes = jar(&[ + (MANIFEST, MULTI_RELEASE), + (NOTICE, b"new"), + ("META-INF/versions/9/META-INF/NOTICE.txt", b"old"), + ]); + assert_eq!(check_bytes(&bytes, ¬ice), None); + } + + /// Every unpatched copy is named, lowest release first, and a copy + /// under a higher release overrides a patched versioned member as it + /// overrides the base. + #[test] + fn every_overriding_copy_is_named() { + const V11: &str = "META-INF/versions/11/a/B.class"; + const V17: &str = "META-INF/versions/17/a/B.class"; + let bytes = patched(MULTI_RELEASE, &[(V17, OLD), (V9, OLD), (V11, PATCHED)]); + assert_eq!( + found(&bytes, &record()), + [(CLASS.to_string(), vec![V9.to_string(), V17.to_string()])] + ); + // The record changes the copy for 11 only: 17 overrides it, 9 and + // the base do not. + let only_11 = HashMap::from([(V11.to_string(), info(OLD, PATCHED))]); + let bytes = jar(&[ + (MANIFEST, MULTI_RELEASE), + (CLASS, OLD), + (V9, OLD), + (V11, PATCHED), + (V17, OLD), + ]); + assert_eq!( + found(&bytes, &only_11), + [(V11.to_string(), vec![V17.to_string()])] + ); + // Equal to the patched copy for 11, the one for 17 carries the patch. + let bytes = jar(&[(MANIFEST, MULTI_RELEASE), (V11, PATCHED), (V17, PATCHED)]); + assert_eq!(check_bytes(&bytes, &only_11), None); + // Several members, and more paths than are spelled out. + let two = HashMap::from([ + (CLASS.to_string(), info(OLD, PATCHED)), + ("a/D.class".to_string(), info(b"d old", b"d new")), + ]); + let bytes = jar(&[ + (MANIFEST, MULTI_RELEASE), + (CLASS, PATCHED), + ("a/D.class", b"d new"), + (V9, OLD), + ("META-INF/versions/10/a/B.class", OLD), + (V11, OLD), + (V17, OLD), + ("META-INF/versions/9/a/D.class", b"d old"), + ]); + let finding = check_bytes(&bytes, &two).unwrap(); + assert_eq!(finding.copies.len(), 2); + assert_eq!(finding.copies[0].paths.len(), 4); + assert!( + finding.describe("x.jar").contains( + "an unpatched copy of a/B.class at META-INF/versions/9/a/B.class, \ + META-INF/versions/10/a/B.class, META-INF/versions/11/a/B.class, … (and of 1 \ + more patched member);" + ), + "{}", + finding.describe("x.jar") + ); + } + + /// A manifest that cannot be read as one leaves the copies unjudged: + /// they are reported as possibly unpatched, never taken for inert. With + /// no versioned copy to judge, the manifest is not read at all. + #[test] + fn an_unreadable_manifest_is_reported_only_when_a_copy_depends_on_it() { + let broken: &[u8] = b"Manifest-Version: 1.0\r\nnot a header\r\nMulti-Release: true\r\n\r\n"; + let bytes = patched(broken, &[(V9, OLD)]); + let finding = check_bytes(&bytes, &record()).unwrap(); + assert_eq!( + finding.copies, + [VersionedCopies { + member: CLASS.to_string(), + paths: vec![V9.to_string()], + }] + ); + let why = finding.unchecked.clone().unwrap(); + assert!(why.starts_with("its manifest cannot be read: "), "{why}"); + let text = finding.describe("b-1.0.jar"); + assert!( + text.starts_with( + "b-1.0.jar could not be checked for unpatched copies of the patched members \ + under META-INF/versions (its manifest cannot be read: " + ) && text.ends_with( + "it holds a/B.class again at META-INF/versions/9/a/B.class, which a Java \ + runtime may load instead of the patched one" + ), + "{text}" + ); + // The same manifest with nothing to judge, or with a copy that + // carries the patch: clean. + assert_eq!(check_bytes(&patched(broken, &[]), &record()), None); + assert_eq!( + check_bytes(&patched(broken, &[(V9, PATCHED)]), &record()), + None + ); + // A per-entry section the reader would refuse changes nothing. + let odd_section: &[u8] = + b"Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\nno name here\r\n\r\n"; + assert_eq!( + found(&patched(odd_section, &[(V9, OLD)]), &record()).len(), + 1 + ); + } + + /// The central directory lists a versioned copy whose own header does + /// not parse, so nothing can say what it holds: it is reported as a + /// copy that could not be checked, never passed over. The same for a + /// manifest that is listed and cannot be read. + #[test] + fn an_entry_the_directory_lists_and_nothing_can_read_is_not_clean() { + use crate::patch::jar_members::testing::break_local_header; + let mut bytes = patched(MULTI_RELEASE, &[(V9, OLD)]); + break_local_header(&mut bytes, V9); + let finding = check_bytes(&bytes, &record()).expect("a finding"); + assert_eq!( + finding.copies, + [VersionedCopies { + member: CLASS.to_string(), + paths: vec![V9.to_string()], + }] + ); + let why = finding.unchecked.expect("not judged"); + assert!(why.starts_with(&format!("{V9} cannot be read")), "{why}"); + + let mut bytes = patched(MULTI_RELEASE, &[(V9, OLD)]); + break_local_header(&mut bytes, MANIFEST); + let finding = check_bytes(&bytes, &record()).expect("a finding"); + assert_eq!(finding.copies.len(), 1); + let why = finding.unchecked.expect("not judged"); + assert!(why.starts_with("its manifest cannot be read"), "{why}"); + + // An unreadable entry that is no copy of a patched member, in a jar + // with no such copy, is none of this check's business. + let mut bytes = patched(MULTI_RELEASE, &[("a/C.class", b"c")]); + break_local_header(&mut bytes, "a/C.class"); + assert_eq!(check_bytes(&bytes, &record()), None); + } + + /// Bytes that are no jar are not taken for a clean one. + #[test] + fn a_jar_that_cannot_be_opened_is_not_clean() { + let finding = check_bytes(b"not a zip archive", &record()).unwrap(); + assert!(finding.copies.is_empty()); + assert!(finding.unchecked.is_some()); + assert!(finding + .describe("b-1.0.jar") + .starts_with("b-1.0.jar could not be checked for unpatched copies")); + let dir = tempfile::tempdir().unwrap(); + let missing = check_file(&dir.path().join("absent.jar"), &record()).unwrap(); + assert!(missing.copies.is_empty() && missing.unchecked.is_some()); + } + + /// A check that dies has found nothing, and that is not "nothing to + /// find": it comes back as a jar that could not be checked, to `apply` + /// as to `apply --check` and `vex`. One that finishes is passed on as + /// it is. + #[tokio::test] + async fn a_check_that_does_not_finish_is_not_clean() { + let died = off_thread(|| panic!("the zip reader gave up")) + .await + .expect("a finding"); + assert!(died.copies.is_empty() && !died.established()); + assert_eq!( + died.no_statement(), + "no statement is emitted for a jar that could not be checked" + ); + let why = died.unchecked.clone().expect("not judged"); + assert!(why.starts_with("the check did not finish ("), "{why}"); + assert!( + died.describe("b-1.0.jar").starts_with( + "b-1.0.jar could not be checked for unpatched copies of the patched members \ + under META-INF/versions (the check did not finish (" + ), + "{}", + died.describe("b-1.0.jar") + ); + assert_eq!(off_thread(|| None).await, None); + + // Over a file and over bytes, off the async workers. + let bytes = patched(MULTI_RELEASE, &[(V9, OLD)]); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("b-1.0.jar"); + std::fs::write(&path, &bytes).unwrap(); + let expected = check_bytes(&bytes, &record()); + assert!(expected.is_some()); + assert_eq!(check_file_off_thread(path, record()).await, expected); + let shared = Arc::new(bytes); + assert_eq!( + check_bytes_off_thread(Arc::clone(&shared), record()).await, + expected + ); + assert_eq!(Arc::strong_count(&shared), 1); + } + + #[test] + fn the_versioned_entry_grammar() { + assert_eq!( + versioned("META-INF/versions/9/a/B.class"), + Some((9, "a/B.class")) + ); + assert_eq!(versioned("META-INF/versions/21/x"), Some((21, "x"))); + for not in [ + "a/B.class", + "META-INF/versions/9/", + "META-INF/versions/9", + "META-INF/versions/9/dir/", + "META-INF/versions/9/META-INF/x", + "META-INF/versions/+9/x", + "META-INF/versions/ 9/x", + ] { + assert_eq!(versioned(not), None, "{not}"); + } + } +} diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index da7a93d28c..ea27ada87d 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -488,6 +488,15 @@ async fn vendor_hub( Err(outcome) => return *outcome, }, }; + // A dry run that has no committed jar holds no bytes to look at. + let jar = if jar.is_empty() { + jar + } else { + let leaf = jar_path.file_name().unwrap_or_default().to_string_lossy(); + let (jar, warning) = multi_release_warning(&leaf, jar, &record.files).await; + warnings.extend(warning); + jar + }; let result = already_patched_result(purl, &jar_path, &record.files); let entry = VendorEntry { flavor: Some(HUB_FLAVOR.to_string()), @@ -505,6 +514,43 @@ async fn vendor_hub( } } +/// The `vendor_jvm_degraded` warning for a patched jar `jar` (named `leaf`) +/// that holds a member of the record `files` again under +/// `META-INF/versions//` without the patch +/// ([`crate::patch::multi_release`]): a Java runtime of that release or +/// later loads that copy, so the build stays unpatched there. The jar is +/// vendored all the same (the base member is patched, and withholding it +/// would leave the build with nothing of the patch); the warning says what +/// is missing, and `vex` does not attest the package. A jar that cannot be +/// checked is reported the same way, as a classifier jar is. +/// +/// The jar is parsed on the blocking pool and handed back with the warning. +async fn multi_release_warning( + leaf: &str, + jar: Vec, + files: &std::collections::HashMap, +) -> (Vec, Option) { + use crate::patch::multi_release::check_bytes_off_thread; + let shared = std::sync::Arc::new(jar); + let found = check_bytes_off_thread(std::sync::Arc::clone(&shared), files.clone()).await; + // The check is over, and with it its hold on the bytes. + let jar = std::sync::Arc::try_unwrap(shared).unwrap_or_else(|shared| (*shared).clone()); + let warning = found.map(|found| { + let next = match found.established() { + true => "The patch has to change that copy too; vendoring again does not", + false => "A jar that could not be checked is not taken for patched", + }; + VendorWarning::new( + super::jvm::gradle::DEGRADED, + format!( + "reason: multi_release_unpatched_copy: {}. {next}", + found.describe(leaf) + ), + ) + }); + (jar, warning) +} + /// The ledger entry for a vendored jar: `wiring` is the pom.xml record on a /// full vendor, empty on an artifact-only rebuild (see the hot path). fn maven_entry( @@ -1734,6 +1780,12 @@ async fn vendor_maven_jvm( } } } + // A class the patch changes may be in the jar again per Java release, + // unpatched (#2199). Whatever the build's shape, the jar is the same. + let leaf = layout::file_name(&artifact_id, &version, None, "jar"); + let (bytes, warning) = multi_release_warning(&leaf, jar_bytes, &record.files).await; + jar_bytes = bytes; + warnings.extend(warning); if online && was_committed { pom_bytes = match acquire_jvm_artifact(&local, &gav, None, "pom", service).await { Ok(bytes) => bytes, @@ -5693,6 +5745,64 @@ mod tests { assert_eq!(detect_shape(root), super::super::jvm::Shape::MavenReactor); } + /// #2199: a patched jar that holds a patched class again under + /// `META-INF/versions//`, unpatched, is a degraded vendoring under + /// its own reason; one that cannot be read to tell is too; a jar with + /// no such copy says nothing. + #[tokio::test] + async fn a_multi_release_copy_of_a_patched_class_is_a_degraded_warning() { + use crate::hash::git_sha256::compute_git_sha256_from_bytes as git; + use crate::patch::jar_members::testing::jar; + const MANIFEST: &[u8] = b"Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\n"; + let files = HashMap::from([( + "a/B.class".to_string(), + crate::manifest::schema::PatchFileInfo { + before_hash: git(b"old"), + after_hash: git(b"fixed"), + }, + )]); + let flagged = jar(&[ + ("META-INF/MANIFEST.MF", MANIFEST), + ("a/B.class", b"fixed"), + ("META-INF/versions/9/a/B.class", b"old"), + ]); + let (kept, warning) = multi_release_warning("lib-1.0.jar", flagged.clone(), &files).await; + assert_eq!(kept, flagged, "the jar comes back as it went in"); + let warning = warning.unwrap(); + assert_eq!(warning.code, super::super::jvm::gradle::DEGRADED); + assert_eq!( + warning.detail, + "reason: multi_release_unpatched_copy: lib-1.0.jar carries an unpatched copy of \ + a/B.class at META-INF/versions/9/a/B.class; it is a multi-release jar, so a Java \ + runtime of that release or later loads that copy, not the patched one. The patch \ + has to change that copy too; vendoring again does not" + ); + // The reason is the one code every mode reports. + assert!(warning.detail.starts_with(&format!( + "reason: {}: ", + crate::patch::multi_release::UNPATCHED_COPY + ))); + let (_, unread) = multi_release_warning("lib-1.0.jar", b"not a jar".to_vec(), &files).await; + let unread = unread.unwrap(); + assert!( + unread.detail.starts_with( + "reason: multi_release_unpatched_copy: lib-1.0.jar could not be checked for \ + unpatched copies of the patched members under META-INF/versions (" + ) && unread + .detail + .ends_with(". A jar that could not be checked is not taken for patched"), + "{}", + unread.detail + ); + let clean = jar(&[ + ("META-INF/MANIFEST.MF", MANIFEST), + ("a/B.class", b"fixed"), + ("META-INF/versions/9/a/C.class", b"other"), + ]); + let (_, none) = multi_release_warning("lib-1.0.jar", clean, &files).await; + assert!(none.is_none()); + } + // ── #973: single-module poms through the planner ── /// A pre-v5 single-pom vendoring of `record` over the project pom, as diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 0f7a5ebf33..34fda8d7ec 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -140,7 +140,8 @@ pub use state::{ }; pub use verify::{ artifact_is_file_shaped, check_vendored_artifact, compute_dir_inventory, - compute_package_dir_inventory, describe_artifact_failure, file_sha256_hex, ArtifactHealth, + compute_package_dir_inventory, describe_artifact_failure, file_sha256_hex, + vendored_jar_versioned_copies, ArtifactHealth, VendoredJarCopies, }; // The hosted→vendored takeover refuses a berry project the backend would // refuse BEFORE it reverts the hosted redirect. diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 0e9785611f..04e106ae64 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -88,6 +88,66 @@ pub(crate) fn checked_artifact_path( Ok(project_root.join(norm)) } +/// What [`vendored_jar_versioned_copies`] says of a vendored jar that is not +/// known to be clean. Each carries the clause that names the jar. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum VendoredJarCopies { + /// The jar holds a versioned copy of a patched member without the + /// patch, or one that could not be judged. + Found(String), + /// The jar could not be checked at all: it is missing, it does not + /// open as a jar within the jar limits, or the check did not finish. + /// `vendor` reports a jar it cannot open as degraded. A jar that is not + /// checked is not attested; [`verify_vendored_patch_record`] refuses + /// one that is missing or that it cannot open under its own tag, which + /// stands when it runs. + Unchecked(String), +} + +/// What the vendored jar of `entry` still holds, under +/// `META-INF/versions//`, of the members `record` changes, without the +/// patch ([`crate::patch::multi_release`]): the clause `vex` withholds the +/// statement with, and why. `None` for a clean jar, for an artifact that is +/// no jar, and for an entry whose artifact path is not one of its own +/// (which [`verify_vendored_patch_record`] refuses under its own tag). +/// +/// Kept apart from that function on purpose. It answers "does the artifact +/// hold the patch's files", which `vendor --check` and `repair` read as the +/// artifact's health; a jar with such a copy holds every file of the patch +/// and is not corrupt. The jar is read on the blocking pool. +pub async fn vendored_jar_versioned_copies( + project_root: &Path, + entry: &VendorEntry, + record: &PatchRecord, +) -> Option { + use crate::patch::multi_release::{check_file_off_thread, Finding}; + let clause = |found: &Finding| { + let what = found.describe(&entry.artifact.path); + format!("{what}; {}", found.no_statement()) + }; + let artifact = match checked_artifact_path(project_root, entry, record) { + Ok(artifact) => artifact, + // A JVM tree that lacks one of its files, the jar among them, has + // no path to hand out: its jar was not checked either. + Err(tag) if tag == "vendor_artifact_missing" && entry.artifact.path.ends_with(".jar") => { + let unchecked = Finding { + copies: Vec::new(), + unchecked: Some("a file of its vendored tree is missing".to_string()), + }; + return Some(VendoredJarCopies::Unchecked(clause(&unchecked))); + } + Err(_) => return None, + }; + if artifact.extension().is_none_or(|ext| ext != "jar") { + return None; + } + let found = check_file_off_thread(artifact, record.files.clone()).await?; + Some(match found.copies.is_empty() { + true => VendoredJarCopies::Unchecked(clause(&found)), + false => VendoredJarCopies::Found(clause(&found)), + }) +} + /// `Ok(())` iff every `record.files` entry hashes to its `afterHash` inside /// the vendored artifact named by `entry`. The error is a stable routing tag /// (see module docs) compatible with `vex::verify::FailedPatch.reason`. @@ -2170,6 +2230,99 @@ mod tests { ); } + /// What the `vex` gate hears of a vendored jar: a versioned copy of a + /// patched member without the patch; a jar that could not be checked at + /// all, which `vendor` reports as degraded and `vex` must not attest; + /// and nothing for a clean jar, a missing one (the wiring checks' and + /// verification's) and an artifact that is no jar. + #[tokio::test] + async fn the_vendored_jar_gate_tells_a_copy_from_a_jar_it_could_not_check() { + use crate::patch::jar_members::testing::jar; + const MANIFEST: &[u8] = b"Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\n"; + const CLASS: &str = "a/B.class"; + const V9: &str = "META-INF/versions/9/a/B.class"; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let rel = format!(".socket/vendor/maven/{UUID}/lib-1.0.jar"); + let path = root.join(&rel); + tokio::fs::create_dir_all(path.parent().unwrap()) + .await + .unwrap(); + let rec = record(UUID, CLASS); + let ent = entry("maven", UUID, &rel); + + // A missing jar was not checked. Verification has its own word + // for it, and a run that does not verify must not attest it. + let Some(VendoredJarCopies::Unchecked(what)) = + vendored_jar_versioned_copies(root, &ent, &rec).await + else { + panic!("not checked"); + }; + assert!( + what.starts_with(&format!("{rel} could not be checked for unpatched copies")) + && what.ends_with("; no statement is emitted for a jar that could not be checked"), + "{what}" + ); + assert_eq!( + verify_vendored_patch_record(root, &ent, &rec) + .await + .unwrap_err(), + "vendor_artifact_missing" + ); + std::fs::write( + &path, + jar(&[("META-INF/MANIFEST.MF", MANIFEST), (CLASS, PATCHED)]), + ) + .unwrap(); + assert_eq!(vendored_jar_versioned_copies(root, &ent, &rec).await, None); + + let flagged = jar(&[ + ("META-INF/MANIFEST.MF", MANIFEST), + (CLASS, PATCHED), + (V9, b"old"), + ]); + std::fs::write(&path, flagged).unwrap(); + let Some(VendoredJarCopies::Found(what)) = + vendored_jar_versioned_copies(root, &ent, &rec).await + else { + panic!("a copy"); + }; + assert!( + what.starts_with(&format!( + "{rel} carries an unpatched copy of {CLASS} at {V9};" + )) && what + .ends_with("; no statement is emitted until the patch changes that copy as well"), + "{what}" + ); + // The artifact holds every file of the patch: it verifies. + assert!(verify_vendored_patch_record(root, &ent, &rec).await.is_ok()); + + std::fs::write(&path, b"not a jar").unwrap(); + let Some(VendoredJarCopies::Unchecked(what)) = + vendored_jar_versioned_copies(root, &ent, &rec).await + else { + panic!("not checked"); + }; + assert!( + what.starts_with(&format!("{rel} could not be checked for unpatched copies")), + "{what}" + ); + // Verification has its own word for that jar. + assert_eq!( + verify_vendored_patch_record(root, &ent, &rec) + .await + .unwrap_err(), + "vendor_artifact_unreadable" + ); + + // Not a jar: none of this check's business. + let other = format!(".socket/vendor/nuget/{UUID}/lib.1.0.nupkg"); + std::fs::create_dir_all(root.join(&other).parent().unwrap()).unwrap(); + std::fs::write(root.join(&other), b"not a jar").unwrap(); + let ent = entry("nuget", UUID, &other); + assert_eq!(vendored_jar_versioned_copies(root, &ent, &rec).await, None); + } + #[tokio::test] async fn nupkg_and_jar_members_verified_as_zip() { // `.nupkg` (NuGet) and `.jar` (Maven) are single committed zip files diff --git a/crates/socket-patch-core/src/vex/mod.rs b/crates/socket-patch-core/src/vex/mod.rs index bac74b7535..6e8488df06 100644 --- a/crates/socket-patch-core/src/vex/mod.rs +++ b/crates/socket-patch-core/src/vex/mod.rs @@ -41,7 +41,7 @@ pub use schema::{ }; pub use verify::{ applied_patches, applied_patches_with_copies, applied_patches_with_vendor, FailedPatch, - HostedCopies, VendorContext, VerifyOutcome, + HostedCopies, VendorContext, VerifyOutcome, MULTI_RELEASE_UNPATCHED_COPY, }; #[cfg(test)] diff --git a/crates/socket-patch-core/src/vex/verify.rs b/crates/socket-patch-core/src/vex/verify.rs index 3bad1c47a2..1f211f5a59 100644 --- a/crates/socket-patch-core/src/vex/verify.rs +++ b/crates/socket-patch-core/src/vex/verify.rs @@ -64,6 +64,14 @@ pub struct VerifyOutcome { /// purl that does not verify — the copy a build may still load /// unpatched. Callers name them (`vex_gradle_unpatched_copy`). pub unpatched_copies: Vec<(String, PathBuf)>, + /// Maven: `(purl, what)` for each installed jar of a failed purl whose + /// record members all verify while the jar, a multi-release one, holds + /// one of them again under `META-INF/versions//` without the patch, + /// or could not be checked for one ([`MULTI_RELEASE_UNPATCHED_COPY`], + /// the purl's reason). `what` names the jar, the member and the + /// versioned paths, and says why no statement is emitted. These are not + /// in `unpatched_copies`: running `apply` again does not change them. + pub multi_release_copies: Vec<(String, String)>, /// The subset of `applied` that is attested with nothing applied: in /// every installed copy, no file of the patch is part of the build /// installed there (the JRuby build of a gem, for a patch to its C @@ -244,6 +252,39 @@ pub async fn applied_patches_with_copies( } else { Err("package_not_found".to_string()) }; + // Every listed member of every consumed jar is patched. A + // multi-release jar may hold one of them again per Java release, + // and a runtime of that release loads that copy instead (#2199): the + // record has to list it, or it has to be the patched bytes. Judged + // here, after and apart from the member check, so that the check + // itself keeps meaning "the record's files are in place" for + // everything else that asks it (rollback, variant selection, the + // vendored drift probe). A vendored entry's jar is gated before + // verification, by the caller that builds the [`VendorContext`]. + let result = match result { + Ok(()) + if vendor_entry.is_none() + && Ecosystem::from_purl(purl) == Some(Ecosystem::Maven) => + { + let hosted = vendor.and_then(|ctx| ctx.hosted.get(purl)); + let (dirs, rename) = match hosted { + Some(copies) => (copies.paths.as_slice(), copies.rename.as_ref()), + None => ( + package_copies.get(purl).map_or(&[][..], Vec::as_slice), + None, + ), + }; + let found = multi_release_copies(purl, record, dirs, rename).await; + if found.is_empty() { + Ok(()) + } else { + out.multi_release_copies + .extend(found.into_iter().map(|what| (purl.clone(), what))); + Err(MULTI_RELEASE_UNPATCHED_COPY.to_string()) + } + } + other => other, + }; match result { Ok(()) => { @@ -406,6 +447,59 @@ async fn verify_member_copies( Ok(()) } +/// The omission tag of a Maven purl whose record members all verify while a +/// jar that holds them, a multi-release one, also holds one of them under +/// `META-INF/versions//` without the patch +/// ([`crate::patch::multi_release`]): a Java runtime of that release or +/// later loads that copy, so the patch is not what runs there. +pub const MULTI_RELEASE_UNPATCHED_COPY: &str = crate::patch::multi_release::UNPATCHED_COPY; + +/// One clause per jar of `purl` under `dirs` (version directories, as +/// [`verify_member_copies`] takes them) that holds an unpatched versioned +/// copy of a member `record` changes, or that could not be checked for one. +/// `rename` is a hosted pin's file rename ([`HostedCopies::rename`]). +/// +/// Only a member-keyed record names members to look for. A record that +/// replaces the jar file whole says nothing of which classes changed, and +/// its jar is the patch service's build from the first byte to the last. +async fn multi_release_copies( + purl: &str, + record: &PatchRecord, + dirs: &[PathBuf], + rename: Option<&(String, String)>, +) -> Vec { + use crate::patch::jvm_jar::{self, RecordShape}; + let RecordShape::Members { jar_leaf } = jvm_jar::classify(purl, &record.files) else { + return Vec::new(); + }; + let jar_leaf = match rename { + Some((from, to)) => rename_leaf(&jar_leaf, from, to), + None => jar_leaf, + }; + let jars: Vec = dirs + .iter() + .flat_map(|dir| jvm_jar::jar_copies(dir, &jar_leaf)) + .map(|dir| dir.join(&jar_leaf)) + .collect(); + if jars.is_empty() { + return Vec::new(); + } + // Off the async workers: a jar's directory is parsed, and its manifest + // and the copies in question are inflated. A check that does not finish + // is a jar that was not checked, as it is to `apply`. + let mut found = Vec::new(); + for jar in jars { + let shown = jar.display().to_string(); + let checked = + crate::patch::multi_release::check_file_off_thread(jar, record.files.clone()).await; + found + .extend(checked.map(|finding| { + format!("{}; {}", finding.describe(&shown), finding.no_statement()) + })); + } + found +} + /// What one pass over an installed copy's record files proves: the /// [`verify_patch_record`] verdict plus the stale-install probes' POSITIVE /// staleness evidence. @@ -3047,6 +3141,151 @@ mod tests { ); } + const MULTI_RELEASE_MANIFEST: &[u8] = b"Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\n"; + + /// #2199, agent mode: a multi-release jar whose patched class has an + /// unlisted, unpatched copy under `META-INF/versions/9/` is not + /// attested, under its own reason and with the jar and the copy named. + /// The member check itself still passes (rollback, variant selection + /// and the vendored drift probe ask it "are the record's files in + /// place"), and the jar is not listed as a copy `apply` could patch. A + /// copy the record lists, or one equal to the patched class, attests; + /// so does the same jar without the manifest attribute. + #[tokio::test] + async fn maven_multi_release_unpatched_copy_withholds() { + const CLASS: &str = "a/B.class"; + const V9: &str = "META-INF/versions/9/a/B.class"; + let purl = "pkg:maven/com.example/lib@1.0"; + let record = maven_record(&[(CLASS, b"old", b"fixed")]); + let judge = |jar: Vec, record: PatchRecord| async move { + let tmp = tempfile::tempdir().unwrap(); + let m2 = tmp.path().join("m2/com/example/lib/1.0"); + std::fs::create_dir_all(&m2).unwrap(); + std::fs::write(m2.join("lib-1.0.jar"), jar).unwrap(); + assert_eq!(verify_patch_record_for(purl, &m2, &record).await, Ok(())); + let mut manifest = PatchManifest::new(); + manifest.patches.insert(purl.to_string(), record); + let copies = HashMap::from([(purl.to_string(), vec![m2.clone()])]); + let out = applied_patches_with_copies(&manifest, &copies, None).await; + (out, m2.join("lib-1.0.jar")) + }; + + let flagged = stored_jar(&[ + ("META-INF/MANIFEST.MF", MULTI_RELEASE_MANIFEST), + (CLASS, b"fixed"), + (V9, b"old"), + ]); + let (out, jar) = judge(flagged, record.clone()).await; + assert!(out.applied.is_empty(), "{out:?}"); + assert_eq!( + out.failed, + [FailedPatch { + purl: purl.to_string(), + reason: MULTI_RELEASE_UNPATCHED_COPY.to_string(), + }] + ); + assert_eq!(MULTI_RELEASE_UNPATCHED_COPY, "multi_release_unpatched_copy"); + assert!(out.unpatched_copies.is_empty(), "{out:?}"); + assert_eq!(out.multi_release_copies.len(), 1, "{out:?}"); + let (named, what) = &out.multi_release_copies[0]; + assert_eq!(named, purl); + assert!( + what.starts_with(&format!( + "{} carries an unpatched copy of a/B.class at META-INF/versions/9/a/B.class;", + jar.display() + )), + "{what}" + ); + + for (what, jar, record) in [ + ( + "the copy is the patched class", + stored_jar(&[ + ("META-INF/MANIFEST.MF", MULTI_RELEASE_MANIFEST), + (CLASS, b"fixed"), + (V9, b"fixed"), + ]), + record.clone(), + ), + ( + "the record lists the copy", + stored_jar(&[ + ("META-INF/MANIFEST.MF", MULTI_RELEASE_MANIFEST), + (CLASS, b"fixed"), + (V9, b"fixed for 9"), + ]), + maven_record(&[ + (CLASS, b"old", b"fixed"), + (V9, b"old for 9", b"fixed for 9"), + ]), + ), + ( + "not a multi-release jar", + stored_jar(&[ + ("META-INF/MANIFEST.MF", b"Manifest-Version: 1.0\r\n\r\n"), + (CLASS, b"fixed"), + (V9, b"old"), + ]), + record.clone(), + ), + ] { + let (out, _) = judge(jar, record).await; + assert_eq!(out.applied, [purl.to_string()], "{what}: {out:?}"); + assert!(out.multi_release_copies.is_empty(), "{what}: {out:?}"); + } + + // A record that replaces the jar file whole names no member: its + // jar is the patch service's from the first byte to the last, and + // nothing is looked for in it. + let whole = stored_jar(&[ + ("META-INF/MANIFEST.MF", MULTI_RELEASE_MANIFEST), + (CLASS, b"fixed"), + (V9, b"old"), + ]); + let leaf = maven_record(&[("package/lib-1.0.jar", b"upstream jar", &whole)]); + let (out, _) = judge(whole.clone(), leaf).await; + assert_eq!(out.applied, [purl.to_string()], "{out:?}"); + } + + /// #2199, hosted mode: the jar Maven or Gradle downloaded under the + /// suffixed version is held to the same rule, under its suffixed name. + #[tokio::test] + async fn hosted_multi_release_unpatched_copy_withholds() { + let tmp = tempfile::tempdir().unwrap(); + let purl = "pkg:maven/com.example/lib@1.0"; + let record = maven_record(&[("a/B.class", b"old", b"fixed")]); + let served = stored_jar(&[ + ("META-INF/MANIFEST.MF", MULTI_RELEASE_MANIFEST), + ("a/B.class", b"fixed"), + ("META-INF/versions/11/a/B.class", b"old"), + ]); + let version = tmp + .path() + .join(".gradle/caches/modules-2/files-2.1/com.example/lib/1.0-socket.0123abcd"); + let dir = version.join(sha1_hex(&served)); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("lib-1.0-socket.0123abcd.jar"), &served).unwrap(); + let hosted = HostedCopies { + paths: vec![version.clone()], + rename: Some(("lib-1.0".to_string(), "lib-1.0-socket.0123abcd".to_string())), + }; + assert_eq!(verify_hosted_copies(purl, &hosted, &record).await, Ok(())); + let mut manifest = PatchManifest::new(); + manifest.patches.insert(purl.to_string(), record); + let vendor = VendorContext { + hosted: HashMap::from([(purl.to_string(), hosted)]), + ..VendorContext::default() + }; + let out = applied_patches_with_copies(&manifest, &HashMap::new(), Some(&vendor)).await; + assert!(out.applied.is_empty(), "{out:?}"); + assert_eq!(out.failed[0].reason, MULTI_RELEASE_UNPATCHED_COPY); + let (_, what) = &out.multi_release_copies[0]; + assert!( + what.contains("lib-1.0-socket.0123abcd.jar carries an unpatched copy of a/B.class at META-INF/versions/11/a/B.class"), + "{what}" + ); + } + /// Where a (safe) record key lands under the package dir; unsafe keys /// land somewhere harmless inside the tempdir. fn normalize_file_path_for_test(name: &str) -> String { diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 843aa0cc33..721b9dc27c 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1654,6 +1654,67 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: and a tripwire fails the build if the base version still resolves. See [Gradle](#gradle) for the rules and refusals; `redirect_gradle_manual_snippet` now appears only beside a refusal. +* **Other copies of a patched class (Maven).** A patch replaces a class in one jar. The + JVM can load the same class from other places, and only one of them is checked: + * **Multi-release jars: checked.** A jar whose manifest says `Multi-Release: true` + may hold a class once more per Java release, under `META-INF/versions//`, and a + Java runtime of release `` or later loads that copy instead of the base one + (`log4j-api` and `h2` ship such jars). When a patch changes `a/B.class` and the jar + also holds `META-INF/versions/9/a/B.class`, that copy must be one the patch lists, + or hold the patched bytes. Otherwise the patched class is in the jar while Java 9 + and later still run the old code, and socket-patch says so wherever a command + reads the jar, under one code, `multi_release_unpatched_copy`, naming the jar, the + class and the copy: + * agent mode: the jar is patched and stays patched, and `apply` reports the patch + as incomplete and exits 1 (`apply --check` reports the same as drift); + * vendored mode: the jar is vendored, with a `vendor_jvm_degraded` warning + (`reason: multi_release_unpatched_copy`), exit 0; + * hosted mode: nothing is said when the pin is written, because hosted mode + never downloads or reads the jar; + * `vex` writes no statement for the package wherever it reads such a jar, since + a statement would say the vulnerable code cannot run. It reads the installed + jar of an agent-mode patch and the committed jar of a vendored one (that one + under `--no-verify` too). For a hosted pin it reads the jar only where a build + has left it: the suffixed version in the Maven local repository, in a Gradle + cache or in a hosted sbt build's download directory. + + That leaves hosted mode with a gap, and it is the one hosted mode already has + for every other kind of evidence: a hosted pin whose jar no local cache holds + is attested from the pin alone. So `vex` on a checkout that has not built yet + writes `not_affected` for a patch whose jar has such a copy, and so does the + `--vex` of the `scan --mode hosted` run that writes or confirms the pin, even + when a cache holds the jar: that run attests what it just pinned without + reading anything. Run `vex` on a machine that has built the project to have + the jar judged. `--no-verify` reads no installed or downloaded jar in any + mode. + + Nothing is undone or refused: the base class is patched, which is what a Java 8 + runtime loads. Running the command again does not clear it. It takes a patch that + lists the versioned copy, and the patch service is expected to publish patches + that do; this check is how the CLI notices one that does not. The rules are the + JDK's: the copies count only with `Multi-Release: true` in the main section of + the manifest (any letter case; any other value, or no such attribute, and the + entries under `META-INF/versions/` are never read), only under exactly + `META-INF/versions//` with a plain decimal ``, and never for a name under + `META-INF/`. `` counts from 8: the specification starts at 9, but JDK 17 and + later also load a copy under `META-INF/versions/8/`. A manifest that cannot be + read, in a jar that holds such a copy, is reported the same way (the copy may be + live). A record that replaces the jar file whole lists no classes, so nothing is + looked for in its jar. + * **Jars nested in an application archive: not detected.** A Spring Boot executable + jar keeps its dependencies under `BOOT-INF/lib/`, and a war under `WEB-INF/lib/`. + socket-patch patches the dependency your build resolves (in the local repository, + the Gradle cache or the vendored tree), so an archive built after the patch + holds the patched jar. An archive built before it, or one you only download, + still holds the old jar, and nothing here reads inside such archives or reports + them. Rebuild the application after patching. + * **Shaded, relocated or repackaged copies: not detected.** An uber jar or a + library that shades another one holds a copy of its classes, often under a + renamed package (`com.example.shaded.org.apache…`). That copy belongs to another + artifact with other coordinates, and a patch for the original does not reach it, + nor is it reported. When the shading happens in your own build (the Maven Shade + or Gradle Shadow plugin), the plugin takes the jar the build resolves, so a build + that runs after the patch shades the patched jar. * **NuGet locked mode (hosted + vendored).** With a `packages.lock.json` and `dotnet restore --locked-mode`, the rewritten `contentHash` pins the patched `.nupkg` — a tampered or wrong package fails restore with `NU1403`. Without a lockfile there is no @@ -2082,6 +2143,13 @@ Guards: to come from the unpatched jar fails that copy (`gradle_transform_copy_stale`); one that cannot be matched is reported (`gradle_transform_copy_unverified`). Run `gradle --stop`, delete the named directories, and apply again. +- **Multi-release jars.** A patched class that the jar also holds under + `META-INF/versions//`, without the patch, is what Java `` and later load. The + jar is patched and left patched, and the patch is reported as incomplete + (`multi_release_unpatched_copy`, exit 1), in `~/.m2` as in the Gradle cache. Applying + again does not change it; it takes a patch that lists the versioned copy. See + **Other copies of a patched class** under + [Maven & NuGet caveats](#maven--nuget-caveats). - On Windows a jar held open by a daemon is reported as `gradle_jar_locked_by_daemon`. Run `gradle --stop` and retry. @@ -2165,7 +2233,10 @@ Classifier jars a build declares are vendored too, and a derived `maven-metadata keeps ranges on the vendored version. Existing pgp-only verification entries, and the classifier jars the tree serves, get a checksum. Refusals use `vendor_jvm_shape_unsupported` / `vendor_jvm_upstream_unavailable`, and partial wiring uses `vendor_jvm_degraded` -(VEX withheld). Each detail starts with `reason: :`. The tree root owns a +(VEX withheld). Each detail starts with `reason: :`. One such reason is not +about wiring: `multi_release_unpatched_copy`, for a vendored jar that holds a patched +class again under `META-INF/versions//` without the patch (in a Maven, sbt or +scala-cli build as well). The tree root owns a `.gitignore` (`!*`) so a `*.jar` rule (GitHub's stock Java.gitignore) cannot drop the vendored jars from the commit; a rule that ignores `.socket/` itself is refused (`vendor_artifact_gitignored`) before anything is written. @@ -2183,7 +2254,15 @@ to come from the unpatched jar, or an older one that does not match the patched withholds the statement (`vex_gradle_unpatched_copy`). A derived-cache walk cut short on a very large cache warns `vex_gradle_derived_cache_unchecked` and does not withhold; a derived-cache check that does not finish at all withholds the statement -(`vex_gradle_derived_cache_check_failed`). +(`vex_gradle_derived_cache_check_failed`). A multi-release jar that holds a patched +class again under `META-INF/versions//`, without the patch, withholds it too +(`multi_release_unpatched_copy`) wherever `vex` reads the jar: the installed jar in +agent mode, the committed jar of a vendored tree, and the suffixed jar of a hosted +pin once a build has downloaded it into a cache `vex` reads. A hosted pin whose jar +is in no such cache, and the pins that the `--vex` of a `scan --mode hosted` run +wrote or confirmed, are attested from the pin without the jar being read (see +**Other copies of a patched class** under +[Maven & NuGet caveats](#maven--nuget-caveats)). ## Scala build tools: sbt, Mill, scala-cli