diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index 17659d19c..8bf471348 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -24,15 +24,24 @@ name: nokogiri patch compatibility # system-libraries `--use-system-libraries`: the extension is rebuilt # with the recorded build arguments, and a patch to the # vendored libxml2, which such a build does not compile, is -# written and not attested: its build reads nothing of the -# patch, and `apply` says so. +# written and incomplete: its build reads nothing of the +# patch, so `apply` exits 1 and says so, and nothing +# attests it. # The `legacy setting` leg is a precompiled install # in a project that still carries that Bundler setting from # the years before precompiled gems: its rebuild must keep # the libxml2 the gem ships, not link the system's. # unavailable a precompiled install on a machine with no compiler: the # patch must fail, name what is missing and change nothing. -# java JRuby loads no C extension: a C record is refused. +# java JRuby installs the `java` platform gem, which runs jars: +# no C extension, no libxml2, nothing to build. It takes of +# a record what is part of that build. The Ruby record is +# applied; the C record's file is written, since the gem +# ships the C sources too, and the patch is in sync and +# attested with the same jars loaded; the libxml2 record +# has no file in that gem, so `apply` exits 0, writes +# nothing and says so, and the install is attested. 9.4 is +# the Ruby 3.1 line, 10.1 the newest (Ruby 4.0). # # The `native` legs run on the runner with setup-ruby. The `container` legs # run the same script inside an official Ruby image, where the gems land in @@ -143,8 +152,10 @@ jobs: - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, system-libxml2: true, args: '--bundle-setting BUNDLE_BUILD__NOKOGIRI=--use-system-libraries', note: legacy setting} # No compiler on PATH: nothing may change. - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, build: unavailable, args: '--hide-toolchain', note: no toolchain} - # JRuby: the Ruby-only record applies, a C record is refused. - - {os: ubuntu-latest, ruby: 'jruby-9.4', nokogiri: '1.18.10', install: java, build: refused} + # JRuby: the `java` gem takes the files of a record that are part + # of it, and nothing is built. + - {os: ubuntu-latest, ruby: 'jruby-9.4', nokogiri: '1.18.10', install: java} + - {os: ubuntu-latest, ruby: 'jruby-10.1', nokogiri: '1.18.10', install: java} # The other platform gems. - {os: ubuntu-24.04-arm, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build} - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build} @@ -197,18 +208,26 @@ jobs: run: | chmod +x static-cli/socket-patch echo "SOCKET_PATCH_BIN=static-cli/socket-patch" >> "$GITHUB_ENV" + - name: Setup Java 21 (JRuby legs) + # JRuby 10 runs on Java 21 or newer, and 9.4 on it as well. With + # this, the leg does not depend on which JDKs the runner image has. + if: startsWith(matrix.ruby, 'jruby') + uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + with: + distribution: temurin + java-version: '21' - name: Setup Ruby (attempt 1) # setup-ruby downloads the prebuilt Ruby from a github.com release # asset; a CDN blip there is not a result. Try once more. id: setup-ruby - uses: ruby/setup-ruby@319994f95fa847cf3fb3cd3dbe89f6dcde9f178f # v1.295.0 + uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0 continue-on-error: true with: ruby-version: ${{ matrix.ruby }} bundler: ${{ matrix.bundler || 'default' }} - name: Setup Ruby (attempt 2) if: steps.setup-ruby.outcome != 'success' - uses: ruby/setup-ruby@319994f95fa847cf3fb3cd3dbe89f6dcde9f178f # v1.295.0 + uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0 with: ruby-version: ${{ matrix.ruby }} bundler: ${{ matrix.bundler || 'default' }} diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8f2665cba..acdc11dd3 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -657,7 +657,7 @@ Contract details: ### VEX provenance markers (contract) -Every VEX statement's impact string records which patch-application mode persists the patch. The three marker strings are **stable contract surfaces** — scanners and policy engines match on them, so renaming or reformatting any of them is a MAJOR change: +Every VEX statement's impact string records which patch-application mode persists the patch (one kind of statement has no patch in place to name: see "Code not present" below). The three marker strings are **stable contract surfaces** — scanners and policy engines match on them, so renaming or reformatting any of them is a MAJOR change: | Impact statement | Mode | Verification evidence | |---|---|---| @@ -667,6 +667,8 @@ Every VEX statement's impact string records which patch-application mode persist `vendored` and `redirected` are disjoint in practice (the modes conflict); if a PURL somehow appears in both sets, `vendored` wins. +**Code not present (additive).** One verified agent-mode attestation carries none of the markers, because no patch is in place: a gem whose installed build holds no file of its patch (the JRuby build of a gem, for a patch to what only a C build reads; `apply` reports it as `not_in_platform_build`). Its impact-statement part reads `The code this vulnerability is in is not in the installed build of the package: no file of Socket patch is part of it`. A statement all of whose packages are of that kind has the justification `vulnerable_code_not_present`. Every other statement keeps `inline_mitigations_already_exist`, including one that covers such a package beside a patched one: its impact statement then carries one part per package, each saying what is true of that package. A package with any installed copy that took a file of the patch is a patched package, with the usual marker. Under `--no-verify` nothing is looked at on disk, so the package gets the unverified `Patched via …; not verified on disk` part like any other. + **Unverified statements (`--no-verify`).** `--no-verify` / `--vex-no-verify` (and an ambient `SOCKET_VEX_NO_VERIFY`) skip every on-disk hash check, so a statement emitted under it rests on the patch records and the wiring gates alone — for an agent-mode patch on nothing but the manifest, even when the installed files are unpatched or absent. Such a run is never silent. Each purl it attests ends its impact-statement part with `; not verified on disk`, appended AFTER the marker, so the three marker strings above stay intact as prefixes (`Patched via Socket patch (vendored); not verified on disk`), and the run raises the `vex_not_verified` warning (stderr in human mode, `warnings[]` / `vex.warnings` under `--json`) naming how many statements carry the suffix. The purls an in-run `scan --mode hosted --vex` confirmed are attested from that run's own evidence in either mode and never carry it. A default (verifying) run's document is unchanged: it never contains the suffix. **Identifier overrides.** `--product` / `--vex-product` and `--doc-id` / `--vex-doc-id` are emitted with surrounding whitespace trimmed (a blank value means unset). @@ -891,7 +893,9 @@ runs) and puts the build where Ruby loads it, using the Ruby that owns the insta `--cwd`. **Build inputs.** A gem is native when its installed gemspec declares `extensions`, or its -platform is not `ruby` (a precompiled gem). In a native gem: +platform is not `ruby` (a precompiled gem). The JRuby build of a gem (the `java` platform, with +no `extensions` declared) is the exception: it has no extension to rebuild, and takes a record by +the rule under "The JRuby build of a gem" below. In a native gem: - Always an input, wherever it sits: a `.c`, `.h`, `.cc`, `.cpp`, `.cxx`, `.hh`, `.hpp`, `.hxx`, `.m`, `.y`, `.rl`, `.java` or `.rs` file, an `extconf.rb`, a `CMakeLists.txt`, `Makefile`, @@ -987,15 +991,41 @@ of them did not build the patch. One read is enough, because a record also carri build opens. Neither did a build that left no compiled file: nothing in RubyGems' extension directory, and nothing Ruby loads in the gem's own tree. -In both cases the record's files are written into the installed copy and its compiled code is -left as it was installed: the package's event is `applied`, the run exits 0, and it carries a -`native_extension_not_rebuilt` warning that names the files and says why. The patch's Ruby files -are in effect, and a source the gem compiles later on its own (passenger builds its agent the -first time it starts without one) is the patched one. No build marker is written, so -`apply --check` reports the package as not in sync and `vex` never attests it. A later `apply` -runs the build again and says the same. The one exception is a record that changes a build input -the installed copy no longer holds: only a build from the source gem accounts for a file added -that way, so that package fails with `native_extensions_unsupported` and nothing is written. +In both cases the patch is **incomplete**. The record's files are written into the installed +copy and stay written, its compiled code is left as it was installed, and the run fails: + +- `apply` exits 1 (`partialFailure`). Nothing is put back: the patch's Ruby files are in effect, + and a source the gem compiles later on its own (passenger builds its agent the first time it + starts without one) is the patched one. +- The package's event is `failed` with `errorCode` `native_extension_not_rebuilt`, never + `applied`. Its `error` says that the patch's files were written, names the sources that are in + no compiled code and says why; its `files` lists what this run wrote (none on a later run that + finds them written). `warnings[]` carries the same code and text. +- On the human path the package gets one line on stderr, also under `--silent`: + `Error: Patch of is incomplete: the patch's files were written, but …`. The warning is + not printed beside it, the package is not listed under `Patched packages:`, and the summary + counts it as `N not in effect`, not as applied or already patched. +- No build marker is written, so `apply --check` reports the package as not in sync and `vex` + never attests it. A later `apply` runs the build again and ends the same way. +- The patch stays recorded in the manifest, so `rollback` restores the written files. The apply + that `get` and `scan --mode agent` run reports it as any failed package (a `failed` event with + this code, `Error: Some patches could not be applied.`, exit 1) and keeps the record too. +- A package is in effect only when no copy of it is incomplete. With several installed copies + each has its own event (`applied` for one that took the patch, `failed` for the incomplete + one), and the package is counted once, as `N not in effect`: it is not listed under `Patched + packages:`, not counted as applied or already patched, and not handed to `get` / + `scan --mode agent` as applied. +- A `gem env` fallback-home copy that is patched best-effort (see above) is the exception, as + for a failure there: its incomplete patch is that copy's `gem_fallback_home_skipped` event and + warning, and the run stands. An incomplete bundle-store copy does not count as the applied + copy that makes a fallback-home copy best-effort. + +A dry run cannot see either case, since only a build shows it: it reports the pending rebuild as +before. With `--no-gem-native-rebuild` nothing is incomplete: the caller compiles (below). + +The one exception is a record that changes a build input the installed copy no longer holds: +only a build from the source gem accounts for a file added that way, so that package fails with +`native_extensions_unsupported` and nothing is written. Off Linux, where a read leaves no trace in a file's access time (a `noatime` mount, Windows by default), which `apply` tests with a file of its own, nothing is concluded from the reads and @@ -1031,8 +1061,12 @@ also does not count against the ruby-platform record (`?platform=ruby`, or no qu release variant is matched to the installed copy, as a missing file otherwise does; a record qualified for another platform is matched as before. When the manifest holds a record whose `platform` qualifier names a platform gem copy's own platform (`x86_64-linux` and -`x86_64-linux-gnu` are one) and that record matches the copy, it alone is applied to the copy: -the ruby-platform record of the same version is not applied on top. +`x86_64-linux-gnu` are one) and that record matches the copy, it is the copy's only record. It +alone is applied to the copy: the ruby-platform record of the same version is not applied on +top. Every other reader follows `apply` in this: `apply --check`, `vex`, `rollback` and the +lookup of `get` / `scan` do not judge the ruby-platform record on that copy either. With no +other installed copy to match, that record is `package_not_installed` in `apply` and in +`apply --check` alike, and `vex` omits it as not installed. **Without a build from the source gem.** Whatever keeps a gem RubyGems built from being rebuilt from its source gem, before anything of the installed copy is written, leaves it the rebuild it @@ -1048,16 +1082,101 @@ refused instead. The one case with no fallback is another run building the same precompiled gem has no in-place rebuild: it is refused with `native_extensions_unsupported` (`native_extension_build_failed` for a failed build), and the message says what is needed (one run with network access to the registry, or the source gem in the home's `cache/`; for a gem the lock -resolves from another source, only the latter). The JRuby build of a gem (the `java` platform) -ships jars compiled from Java sources, which no source gem's build produces: a record that changes -its build inputs is always refused. +resolves from another source, only the latter). + +**The JRuby build of a gem.** JRuby installs a gem's `java` platform build +(`nokogiri-1.18.10-java`; also a `jruby` or `universal-java-*` platform), whose compiled code is +jars: there is no C extension, and nothing to rebuild. That is a JVM-platform gem whose gemspec +declares no `extensions`. One that does declare them (jruby-launcher compiles a native launcher +when it is installed) is a gem RubyGems built, and its records are rebuilt as described above, +like those of any such gem. + +The patch records are written for the `ruby` platform gem, and the `java` gem of the same release +is another archive. It ships the gem's Ruby files, often its C sources too (nothing on JRuby +compiles them), and none of what only a C build reads. `apply` gives such a copy the files of the +ruby-platform record (no `platform` qualifier, or `?platform=ruby`) that are part of its own +build, file by file, starts no Ruby, builds nothing and writes no marker or backup: + +- A file the record replaces (it has a `beforeHash`) that the copy holds is verified and written + like any patch file: content that is neither the `beforeHash` nor the `afterHash` content is + the usual mismatch. A C source the `java` gem ships is updated this way. +- An input of a C build that the copy does not hold is not part of that platform's gem. It is + skipped: not written, not required, and not counted as missing. Such an input is told by its + path alone: anything under `ext/`, `patches/` or `ports/`, or a file with one of the source or + build file names under "Build inputs" above. One the record adds is skipped the same way: a + new C source or a new patch to a packed library means nothing to a gem with no C build. +- Every other file of the record is part of every build of the gem. One the record adds is + created. One it replaces that the copy does not hold (a Ruby file under `lib/` that was + deleted from the copy) is the usual missing file: the patch fails with nothing written, + `apply --check` is out of sync and `vex` does not attest it. A missing file is never taken for + a patch with nothing to do there. + +With those files written the patch is applied: the event is `applied` and lists the files +written, `apply --check` is in sync, `vex` attests it, a second `apply` reports `already_patched`, +and `rollback` restores exactly the files `apply` wrote. Each of them reads the record by the same +rule, as does matching the ruby-platform record to the copy: a C build input the copy has no use +for never counts against it. So a copy that takes only a C source it ships, which nothing there +compiles, counts as patched, and a C build input that was deleted from the copy reads as one the +gem never shipped (nothing here knows the `java` gem's file list, and nothing on JRuby reads +such a file). A copy patched this way holds the same files as one installed from the patched +`java` platform gem that Socket's backend builds. + +A record qualified for a platform names the archive it was written for, and gets none of this: +the copy's own (`?platform=java`), or another one that was matched to the copy. Every file of it +is required, in `apply`, `apply --check`, `vex` and `rollback` alike: one the copy does not hold +is the usual missing file, and one it adds is created wherever it goes. + +When no file of the ruby-platform record is part of the copy's build (a record that only adds +`patches/libxml2/.patch`), the code the patch changes is not in that build. The run writes +nothing and exits 0; the patch's event is `skipped` with `not_in_platform_build`, and its reason +says that none of the patch's files are part of the JRuby build of the gem (on the human path: a +`Note:` line on stderr, and `N not applicable` in the summary). `apply --check` is in sync, and +whatever counts the patches a run left in place counts it as it counts `already_patched` (the +advisory lines of `scan --mode agent`). `vex` attests the package with the reason that is true +of it. Nothing was patched, so the statement does not say `Patched via …`: it is `not_affected` +with the justification `vulnerable_code_not_present`, and its impact statement reads `The code +this vulnerability is in is not in the installed build of the package: no file of Socket patch + is part of it` (see "VEX provenance markers"). `rollback` has nothing to restore there +and says that: the patch's event is `skipped` with `not_in_platform_build` and a reason that +nothing of the patch was applied to that build, not `no_files`. Its record is removed as usual. + +The one thing `apply` cannot do there is rebuild a jar. A record that changes a JVM build input +and brings no compiled code for it has its files written, as above, and is incomplete in the +sense of "A build that builds nothing of the patch": the files stay written, the run exits 1, +the event is `failed` with `native_extension_not_rebuilt` (the gem's jars were built from +sources the patch changes, and are as they were installed), and the warning of that code goes +with it. `apply --check` reports that package as not in sync and `vex` never attests it, on +this run or a later one. A JVM build input is, by file name alone, wherever the file sits and +whatever its case: a `.java`, `.kt` or `.scala` source, or a `pom.xml`, `build.xml`, +`build.gradle`, `build.gradle.kts` or `Mavenfile`. It counts whether the copy holds the file or +not, since a gem need not ship the sources of its jars. When the copy takes none of the record's +files, nothing is written and the patch is incomplete all the same: the `failed` event lists no +files, and the summary counts the package as `N not in effect`, never as not applicable. Files +alone show all of this, so `apply --dry-run` ends the same way without writing: exit 1, the +`failed` event, and an `error` that says what `apply` would write and what would not be in +effect. With `--no-gem-native-rebuild` the caller builds the jars: the files the copy takes are +written and the run exits 0 with the warning, as for an extension. A dry run with that flag +writes nothing, and its warning says what `apply` would do (`dry run: … apply would write them +without rebuilding the jars`), as it does for an extension. + +Two records are not held up by a JVM build input, because the compiled code they need is theirs: + +- A record that itself replaces or adds a `.jar` or `.class` file. Those are not build inputs: + the record puts the patched code where the JVM loads it, and a source it changes beside the + jar is the source that jar was built from. +- A record qualified for the copy's own platform (`?platform=java` on a `java` gem). It was + written against that gem's archive, and its files are the patch of that build. + +Either is verified and written like any patch, with no warning, and the copy is in sync and +attested. What runs, and when: whether a record needs a rebuild is decided from files alone. The installed gemspec is read as text for its `extensions`, `platform` and `require_paths`, never evaluated, so `apply --dry-run`, `apply --check` and `vex` start no Ruby and download nothing. A dry run reports -the pending rebuild as a `native_extension_rebuilt` warning ("apply would …") and refuses only what -it can see without one (no extension directory, no `ruby` to run, a JRuby gem, a source gem that is -needed, not cached, and out of reach offline or withheld by the lock). A real run starts Ruby only +the pending rebuild as a `native_extension_rebuilt` warning ("apply would …") and fails only what +it can see without one, the way the real run would (no extension directory, no `ruby` to run, a +source gem that is needed, not cached, and out of reach offline or withheld by the lock; on the +JRuby build of a gem, a record that changes sources of its jars). A real run starts Ruby only once every file of the record verified against the installed copy (it holds the record's `beforeHash` or `afterHash` content, or a mismatch the run was told to overwrite): first the host Ruby alone, asked where it builds extensions for that gem home and what it is, which loads @@ -1110,20 +1229,29 @@ as it is, with its `redirect_gem_stale_install` warning; see the "Gem stale-inst `--no-gem-native-rebuild` (env `SOCKET_NO_GEM_NATIVE_REBUILD`) is for a caller that compiles the extension itself (the patches evaluation harness): the patched sources are written as before #1996, with no Ruby run, no download and no backup or marker, and the run succeeds with a -`native_extension_not_rebuilt` warning. `vex` and `apply --check` then omit the patch until a +`native_extension_not_rebuilt` warning. Under `--dry-run` nothing is written, and that warning +says what `apply` would do (`dry run: … apply would write them without rebuilding the +extension`). `vex` and `apply --check` then omit the patch until a rebuild by `apply` records it. It covers every build input above, on a precompiled gem too (where -a file the copy does not hold is not written: the record fails on it as on any missing file). +a file the copy does not hold is not written: the record fails on it as on any missing file), and +the sources of a JRuby gem's jars. Under this flag a patch is never incomplete for want of a +build, with one exception: a JRuby gem that holds none of the files of a record that changes +sources of its jars has nothing for the caller to build from, and fails as without the flag. | Code | Run result | Meaning | |---|---|---| -| `native_extensions_unsupported` | refused, exit 1 | The record changes build inputs that cannot be rebuilt here: the copy is not a RubyGems install with a `specifications/` entry (a Bundler git checkout); the gem neither declares extensions nor is a platform gem; it is the JRuby (`java`) build; no Ruby that owns the install was found; a precompiled gem cannot be built from its source gem (the archive is neither in the home's `cache/` nor downloadable, is not the copy's own source, the record does not apply to it, a gem its build needs could not be staged, its build leaves a library in the gem's own tree, or the build has no counterpart among the gem's prebuilt binaries); a record changes an input a build removed and the source gem cannot be built. Nothing is written. Also: another run is rebuilding the same gem right now, or an interrupted rebuild could not be undone (the error says which). | +| `native_extensions_unsupported` | refused, exit 1 | The record changes build inputs that cannot be rebuilt here: the copy is not a RubyGems install with a `specifications/` entry (a Bundler git checkout); the gem neither declares extensions nor is a platform gem; no Ruby that owns the install was found; a precompiled gem cannot be built from its source gem (the archive is neither in the home's `cache/` nor downloadable, is not the copy's own source, the record does not apply to it, a gem its build needs could not be staged, its build leaves a library in the gem's own tree, or the build has no counterpart among the gem's prebuilt binaries); a record changes an input a build removed and the source gem cannot be built. Nothing is written. Also: another run is rebuilding the same gem right now, or an interrupted rebuild could not be undone (the error says which). | | `native_extension_build_failed` | refused, exit 1 | The extension did not build from the patched sources (no compiler or Ruby headers, a build error, an in-place build that exited cleanly and kept the library it found instead of compiling it again), or the finished build could not be moved into place. The installed copy is as it was before the run; the error carries the build output's tail (of the build from the source gem and of the in-place one, when both ran), at most 30 lines of each, without mkmf's list of configuration options or its pointer to the `mkmf.log` that was removed with the failed build. For a precompiled gem it says that the rebuild needs what `gem install -v --platform ruby` needs. | | `native_extension_rebuilt` | warning | The sources were already patched (by a release before #1996, with `--no-gem-native-rebuild`, or by `apply` under another Ruby version of a precompiled gem) and the extension was rebuilt from them. Under `--dry-run`: the rebuild a real `apply` would run; no Ruby is started and nothing is downloaded to check that it can. | -| `native_extension_not_rebuilt` | warning | The record's files were written and no build holds them. With `--no-gem-native-rebuild`: Ruby loads the old build until the caller compiles it. Without it: a build ran and built nothing of the patch (it read none of the files the patch changes, or left no compiled file), so the compiled code is as it was installed. `vex` and `apply --check` do not take the package for patched. | +| `native_extension_not_rebuilt` | incomplete: `failed` event and warning, exit 1 (with `--no-gem-native-rebuild`: warning only, exit 0) | The record's files were written and no build holds them. Without `--no-gem-native-rebuild` the patch is incomplete: a build ran and built nothing of the patch (it read none of the files the patch changes, or left no compiled file), so the compiled code is as it was installed; or, on the JRuby build of a gem, the ruby-platform record changes what the gem's jars were built from (a Java, Kotlin or Scala source, a Maven, Ant or Gradle build file) and brings no `.jar` or `.class` file of its own, and nothing here rebuilds a jar. The files stay written and the patch stays recorded; the run exits 1 with the package's `failed` event under this code and the warning. With `--no-gem-native-rebuild`: Ruby loads the old build until the caller compiles it, and the run exits 0 with the warning alone. Either way `vex` and `apply --check` do not take the package for patched. | +| `not_in_platform_build` | `skipped` event, exit 0 | No file of the ruby-platform record is part of the build installed there: the JRuby (`java`) build of a gem, for a record that only changes what a C build reads. Nothing is written. The code the patch changes is not in that build, so `apply --check` is in sync and `vex` attests the package as `not_affected` with the justification `vulnerable_code_not_present`. `rollback` of such a copy is a `skipped` event with this code too: nothing of the patch was applied there. | | `native_extension_restore_failed` | rollback: that copy fails | The sources were restored, but the original compiled extension could not be put back. Run `gem pristine --extensions` (a precompiled gem: `gem pristine `). | A refusal is printed once on the human path, as the package's `Error: Failed to patch` line. Under -`--json` it is the package's error and, under its code, a `warnings[]` entry. +`--json` it is the package's error and, under its code, a `warnings[]` entry. An incomplete patch +is printed once too, as `Error: Patch of is incomplete: …`; under `--json` it is the +package's `failed` event, whose `errorCode` is `native_extension_not_rebuilt` itself, and the +`warnings[]` entry of that code. `vex` and `apply --check` attest such a copy only while its marker matches the record's patched sources and every artifact it lists, a precompiled gem's replaced binary included; otherwise the @@ -1797,6 +1925,7 @@ v5.0 replaces v4's per-purl reverts and whole-ledger reverse replay (`revert_rem | Agent leg: a copy restored | `rolledBack` (`verified` on `--dry-run`); `files` = the restored (would-be restored) files, `details.path` = the installed copy. One event per copy | | Agent leg: already original | `skipped` `already_original` | | Agent leg: patch record lists no files | `skipped` `no_files` | +| Agent leg: no file of the record is part of the installed build (the JRuby build of a gem) | `skipped` `not_in_platform_build`, on `--dry-run` too; `details.path` = the installed copy | | Agent leg: copy failed | `failed`; `errorCode` from the first blocking file (`hash_mismatch`, `file_not_found`, `missing_blob`), else `rollback_failed`; `details.filesVerified[{file, status, message, currentHash, expectedHash, targetHash}]` with camelCase `status` (`ready`, `alreadyOriginal`, `hashMismatch`, `notFound`, `missingBlob`). A before-blob gate abort is one `missing_blob` failure per gated package | | In-scope entry not installed | `skipped` `package_not_installed` (never flips status or exit). Nothing was restored for it; when its record is dropped, the human warning adds that a copy the run did not find stays patched until the package is reinstalled | | Vendored leg: reverted / preserved (`--preserve-state`) | `rolledBack` (`verified` on `--dry-run`), `details.mode: "vendored"`; preserved adds `details.preserved: true` | @@ -2150,8 +2279,10 @@ command's integration tests check its output. | Tag | Action(s) | Context | |---------------------------|------------------|---------| | `already_patched` | `skipped` | apply: every file's hash already matches `afterHash`. | +| `not_in_platform_build` | `skipped` | apply (gem): the installed copy is the JRuby (`java`) build of the gem and no file of the patch is part of that build (a patch to the C extension or a library it packs). Nothing was written and nothing is left to do: the code the patch changes is not in that build, `apply --check` is in sync and `vex` attests the package (`vulnerable_code_not_present`), and a nested `scan --mode agent` counts the patch among those in place, as it counts `already_patched`. `reason` says so in plain words. rollback (gem): the same copy; nothing of the patch was applied to it, so nothing was restored. See "The JRuby build of a gem". | | `package_not_installed` | `skipped` | apply: manifest entry has no matching installed package. 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". | | `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. | | `no_local_source` | `skipped`/`failed` | Agent patch application cannot obtain the required local or downloaded patch source. Vendored mode consumes complete server artifacts and no longer stages patch blobs. | @@ -2477,7 +2608,7 @@ outcome for a selected record, rather than inferring a write from exit 0. | `repair` | `Downloaded` (or `Verified` on dry-run; `details: {count, downloadMode: "file"}` — `downloadMode` is always `"file"` since v5.0 removed the diff download path; `details.corrupt` when some of the blobs replaced corrupt cache entries) · `Rebuilt` (vendored artifacts; `Verified` previews on dry-run; every vendored-phase event carries `details.mode: "vendored"`) · `Skipped` (vendor_uuid_mismatch, cleanup_failed) · artifact-level `Removed` (or `Verified`) GC carrier (`details.count`, `details.checked`, `bytes`) · `Failed` events (`download_failed`; `--offline`: one `offline_missing_sources` / `blob_corrupt` per blob it could not restore) · top-level `gc` (absent under `--download-only`) | | `vex` | `Verified` (one per attested subcomponent) · `Skipped` (omissions) — only under `--json --output` | | `remove` | `Removed` (per purl; `Verified` on dry-run) · `RolledBack` (one per installed copy the in-place rollback restored; `summary.rolledBack`) · vendored/hosted-leg `Removed`/`Skipped` events with `details.mode` · artifact-level `Removed`/`Verified` GC carrier (`details: {count, checked}`, `bytes`; only when the sweep removed something — v5.0, MAJOR: replaces `details.blobsRemoved` / `archivesRemoved` / `rolledBack`) · top-level `gc` (absent under `--preserve-state`) · `cleanup_failed` warnings | -| `rollback` | `RolledBack` (agent copies; vendored / hosted unwinds with `details.mode`) · `Verified` (dry-run previews, manifest removals included) · `Skipped` (already_original / no_files / package_not_installed) · `Failed` (per copy or leg; artifact-level `hosted_write_failed` / `hosted_wiring_contested`) · `Removed` (manifest entries, `details.manifest: true`) · top-level `gc` (absent under `--preserve-state`) | +| `rollback` | `RolledBack` (agent copies; vendored / hosted unwinds with `details.mode`) · `Verified` (dry-run previews, manifest removals included) · `Skipped` (already_original / no_files / not_in_platform_build / package_not_installed) · `Failed` (per copy or leg; artifact-level `hosted_write_failed` / `hosted_wiring_contested`) · `Removed` (manifest entries, `details.manifest: true`) · top-level `gc` (absent under `--preserve-state`) | | `get`, `scan` | Agent mode: `Downloaded` / `Updated` (+`oldUuid`) / `Skipped` (`already_in_manifest`, `vendored`, `package_not_installed`, …) / `Failed` per patch, then `Applied` / `Skipped` / `Failed` for the nested apply · Hosted: `Applied` (pin written) / `Skipped` (`details.mode: "hosted"`) · Vendored: `Downloaded` / `Failed`, then the vendor engine's events (`details.mode: "vendored"`) · dry runs: `Verified` / `Skipped` · `scan --prune`: `Removed` (`details.manifest: true`, or a vendored revert) / `Skipped` + top-level `gc` · `get` search outcomes: `Skipped` (`paid_required`, `package_not_installed`, …) — see [`scan` and `get` JSON](#scan-and-get-json-v50-major) | | `--update` | `Downloaded` → `Updated` (success) · `Skipped` (already_latest) · `Verified` (dry-run check, reason update_check) — see the Self-update contract section for details fields and top-level error codes | diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 7e577cbcd..e33ee73e9 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -980,10 +980,8 @@ async fn own_platform_variant<'v>( if variants.len() < 2 { return None; } - let platform = gem_ext::copy_platform(pkg_path).await?; - let own = variants - .iter() - .find(|variant| gem_ext::names_platform(variant, &platform))?; + let own = gem_ext::own_platform_record(pkg_path, variants.iter().map(String::as_str)).await?; + let own = variants.iter().find(|variant| variant.as_str() == own)?; if force { return Some(own); } @@ -1022,8 +1020,8 @@ pub(crate) fn representative_file( /// /// Action mapping (in priority order): /// * `!result.success` → `Failed` -/// * `dry_run` and any file was Ready/Patched → `Verified` /// * all `files_verified` are AlreadyPatched → `Skipped` (already_patched) +/// * `dry_run` and any file was Ready/Patched → `Verified` /// * something was actually patched on disk → `Applied` /// /// `files` enumerates only the files that participated in the action — @@ -1071,7 +1069,18 @@ pub(crate) fn result_to_event(result: &ApplyResult, dry_run: bool) -> PatchEvent return PatchEvent::new(PatchAction::Verified, purl).with_files(files); } - let files = result + // Sidecar data is NOT attached here — it's surfaced at the + // envelope level under `Envelope.sidecars[]` by the run loop. + // Keeping events clean of sidecar info means each event describes + // only the apply action; sidecar reporting is a separate, + // JOIN-able list. + PatchEvent::new(PatchAction::Applied, purl).with_files(patched_files(result)) +} + +/// The files `result`'s run wrote, as an event lists them: each with the +/// source its patched bytes came from. +fn patched_files(result: &ApplyResult) -> Vec { + result .files_patched .iter() .map(|f| PatchEventFile { @@ -1083,13 +1092,7 @@ pub(crate) fn result_to_event(result: &ApplyResult, dry_run: bool) -> PatchEvent .copied() .map(AppliedVia::from_core), }) - .collect(); - // Sidecar data is NOT attached here — it's surfaced at the - // envelope level under `Envelope.sidecars[]` by the run loop. - // Keeping events clean of sidecar info means each event describes - // only the apply action; sidecar reporting is a separate, - // JOIN-able list. - PatchEvent::new(PatchAction::Applied, purl).with_files(files) + .collect() } /// True when the manifest records at least one npm patch — the only kind a @@ -1452,23 +1455,35 @@ impl ApplyRunReport { /// the in-scope manifest purls with no installed package that the /// project's lockfiles do not resolve either; beside a failed result those /// are only the "no matching installed package" warning, never a failure. +/// +/// A copy whose patch is incomplete (`caveats`) is a failure of its patch +/// too, under its own code: its files were written, and what it compiles +/// is not the patch's. fn collect_apply_failures( results: &[ApplyResult], + caveats: &GemCaveats, unmatched: &[String], lockfile_only: &HashSet, ) -> Vec { let mut failures: Vec = Vec::new(); - for r in results.iter().filter(|r| !r.success) { + for r in results { + let (code, error) = match caveats.incomplete_of(r) { + Some(copy) => (gem_ext::NOT_REBUILT_REASON, copy.detail.clone()), + None if !r.success => ( + "apply_failed", + r.error + .clone() + .unwrap_or_else(|| "unknown error".to_string()), + ), + None => continue, + }; if failures.iter().any(|f| f.purl == r.package_key) { continue; } failures.push(ApplyFailure { purl: r.package_key.clone(), - code: "apply_failed".to_string(), - error: r - .error - .clone() - .unwrap_or_else(|| "unknown error".to_string()), + code: code.to_string(), + error, }); } if !failures.is_empty() { @@ -1489,16 +1504,22 @@ fn collect_apply_failures( /// package; per-copy advisories remain standalone apply events. fn collect_apply_outcomes( results: &[ApplyResult], + caveats: &GemCaveats, unmatched: &[String], lockfile_only: &HashSet, mut skipped: Vec, dry_run: bool, ) -> (Vec, Vec) { let mut applied = Vec::new(); + skipped.extend(caveats.not_in_build.iter().map(LeftCopy::event)); for result in results { - let event = result_to_event(result, dry_run); + let event = caveats.event_of(result, dry_run); match event.action { - PatchAction::Applied | PatchAction::Verified => { + // Another copy of a package whose patch is incomplete somewhere + // does not make the package applied. + PatchAction::Applied | PatchAction::Verified + if !caveats.is_incomplete(&result.package_key) => + { applied.push(result.package_key.clone()); } PatchAction::Skipped => skipped.push(event), @@ -1519,7 +1540,7 @@ fn collect_apply_outcomes( let applied_keys: HashSet<&str> = applied.iter().map(String::as_str).collect(); let failed_keys: HashSet<&str> = results .iter() - .filter(|r| !r.success) + .filter(|r| !r.success || caveats.is_incomplete(&r.package_key)) .map(|r| r.package_key.as_str()) .collect(); skipped.retain(|event| { @@ -1707,6 +1728,7 @@ pub(crate) async fn run_locked( lockfile_only, run_warnings, fallback_skips, + caveats, targeted, show_summary, }) => { @@ -1801,14 +1823,28 @@ pub(crate) async fn run_locked( // whose native extension cannot be rebuilt): the // package's own `Error: Failed to patch` line carries // the same text, and a build failure's is many lines - // long (#2117). - if !is_stage_failure_code(&w.code) && !restates_a_failure(w, &results) { + // long (#2117). And of an incomplete patch, whose + // `Error:` line says the same. + if !is_stage_failure_code(&w.code) + && !restates_a_failure(w, &results) + && !caveats.restated_by(w) + { eprintln!("Warning: {}", w.detail); } } for skip in &fallback_skips { eprintln!("Warning: {}", skip.detail()); } + // A gem build that holds none of a patch's files (the JRuby + // build of a gem patched in its C code): nothing to do, said + // in plain words, each distinct one once. It is the copy's + // `skipped` event under `--json`. + let mut noted = HashSet::new(); + for left in &caveats.not_in_build { + if noted.insert((left.purl.as_str(), left.detail.as_str())) { + eprintln!("Note: {}: {}", normalize_purl(&left.purl), left.detail); + } + } // A package's sidecar advisory (the PyPI `RECORD`, a gem // `--redownload`, `go mod verify`, a signed NuGet package, // a Gradle cache copy) is `sidecars[]` under `--json`; a @@ -1856,7 +1892,7 @@ pub(crate) async fn run_locked( if !args.common.json && !args.common.silent { let cwd = std::fs::canonicalize(&args.common.cwd) .unwrap_or_else(|_| args.common.cwd.clone()); - let block = format_results_block(&results, args.common.dry_run, &cwd); + let block = format_results_block(&results, &caveats, args.common.dry_run, &cwd); let mut block = block.iter().peekable(); // A nested apply's caller already ended its stdout with a // blank line (its listing or table), so the block's leading @@ -1872,7 +1908,7 @@ pub(crate) async fn run_locked( print_verbose_verification(&results); } if show_summary { - let tally = tally_results(&results); + let tally = tally_results(&results, &caveats); println!(); if args.common.dry_run { for line in format_dry_run_summary(&tally, unmatched.len()) { @@ -1914,7 +1950,7 @@ pub(crate) async fn run_locked( env.record(skip.clone()); } for result in &results { - env.record(result_to_event(result, args.common.dry_run)); + env.record(caveats.event_of(result, args.common.dry_run)); // Mismatch overwrites ride as Skipped warning events // (same pattern as the vendor warnings): the package's // Applied event stands, the warning is per-file. @@ -1962,6 +1998,12 @@ pub(crate) async fn run_locked( .with_reason("package_not_installed", detail), ); } + // Gem copies left as they were on purpose: one Skipped event + // each, with the reason. Never an `applied` event with no + // files. + for left in &caveats.not_in_build { + env.record(left.event()); + } // Best-effort gem-env fallback-home copies left unpatched: // one non-fatal Skipped event each, with the copy's path // and reason. Never a Failed event — the bundle-store copy @@ -2078,6 +2120,7 @@ pub(crate) async fn run_locked( ); let (applied, skipped) = collect_apply_outcomes( &results, + &caveats, &unmatched, &lockfile_only, user_patch_skips, @@ -2096,7 +2139,7 @@ pub(crate) async fn run_locked( let failures = if success { Vec::new() } else { - collect_apply_failures(&results, &unmatched, &lockfile_only) + collect_apply_failures(&results, &caveats, &unmatched, &lockfile_only) }; let run_error = if let Some(Err(e)) = &vex_result { Some((e.code.to_string(), e.message.clone())) @@ -2253,6 +2296,10 @@ struct ApplyOutcome { /// (best-effort class): one non-fatal `Skipped` event each in the /// envelope, one gated stderr line each on the human path. fallback_skips: Vec, + /// The gem copies whose apply succeeded with a caveat + /// ([`gem_ext::GemCaveat`]): the ones with nothing of the patch in + /// their build, and the ones whose patch is incomplete. + caveats: GemCaveats, /// In-scope (`--ecosystems`-filtered) manifest patches: the human /// summary's denominator. targeted: usize, @@ -2324,24 +2371,53 @@ struct ApplyTally { /// Owned by `socket-patch vendor` (its committed artifact is the /// patch; apply does no work for it). vendored: usize, + /// No copy had anything to patch: every one is a build of the package + /// that holds none of the code the patch changes + /// ([`gem_ext::GemCaveat::NotInBuild`]). Nothing is left to do. + not_applicable: usize, + /// Some copy's patch is incomplete: its files are written (or the + /// copy holds none of them), and the compiled code it runs is not the + /// patch's ([`gem_ext::GemCaveat::Incomplete`]). The package is not + /// patched, and is counted neither as applied nor as already patched. + not_in_effect: usize, } -fn tally_results(results: &[ApplyResult]) -> ApplyTally { +fn tally_results(results: &[ApplyResult], caveats: &GemCaveats) -> ApplyTally { let mut by_purl: std::collections::BTreeMap<&str, Vec<&ApplyResult>> = std::collections::BTreeMap::new(); let mut vendored: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new(); + let mut not_in_effect: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new(); for r in results { if r.package_path == VENDOR_OWNED_MARKER { vendored.insert(r.package_key.as_str()); continue; } + // A package with an incomplete patch on any copy is not in + // effect, once: its results, the incomplete one that wrote files + // and any other copy's, count under that heading alone. + if caveats.is_incomplete(&r.package_key) { + not_in_effect.insert(r.package_key.as_str()); + continue; + } by_purl.entry(r.package_key.as_str()).or_default().push(r); } + // A copy with nothing of the patch in its build counts for its + // package only when no copy of the package says more. + let not_applicable: std::collections::BTreeSet<&str> = caveats + .not_in_build + .iter() + .map(|copy| copy.purl.as_str()) + .filter(|purl| { + !by_purl.contains_key(purl) && !vendored.contains(purl) && !not_in_effect.contains(purl) + }) + .collect(); let mut tally = ApplyTally { vendored: vendored .iter() .filter(|k| !by_purl.contains_key(*k)) .count(), + not_applicable: not_applicable.len(), + not_in_effect: not_in_effect.len(), ..ApplyTally::default() }; for copies in by_purl.values() { @@ -2382,6 +2458,12 @@ fn format_summary_line(tally: &ApplyTally, targeted: usize, not_found: usize) -> if tally.vendored > 0 { parts.push(format!("{} vendored", tally.vendored)); } + if tally.not_applicable > 0 { + parts.push(format!("{} not applicable", tally.not_applicable)); + } + if tally.not_in_effect > 0 { + parts.push(format!("{} not in effect", tally.not_in_effect)); + } if tally.failed > 0 { parts.push(format!("{} failed", tally.failed)); } @@ -2404,6 +2486,18 @@ fn format_dry_run_summary(tally: &ApplyTally, not_found: usize) -> Vec { plural(tally.already, "package", "packages") )); } + if tally.not_applicable > 0 { + lines.push(format!( + " {} not applicable", + plural(tally.not_applicable, "package", "packages") + )); + } + if tally.not_in_effect > 0 { + lines.push(format!( + " {} would not take effect", + plural(tally.not_in_effect, "package", "packages") + )); + } if tally.failed > 0 { lines.push(format!( " {} cannot be patched", @@ -2431,7 +2525,12 @@ fn format_patched_line(purl: &str, copy: Option<&str>, detail: &str) -> String { /// The wet run's `Patched packages:` block (empty when nothing would be /// listed — no header over an empty list). Dry runs report through /// [`format_dry_run_summary`] instead. -fn format_results_block(results: &[ApplyResult], dry_run: bool, cwd: &Path) -> Vec { +fn format_results_block( + results: &[ApplyResult], + caveats: &GemCaveats, + dry_run: bool, + cwd: &Path, +) -> Vec { if dry_run { return Vec::new(); } @@ -2440,10 +2539,12 @@ fn format_results_block(results: &[ApplyResult], dry_run: bool, cwd: &Path) -> V *copies.entry(r.package_key.as_str()).or_default() += 1; } let mut lines: Vec = Vec::new(); - for result in results - .iter() - .filter(|r| r.success && r.package_path != VENDOR_OWNED_MARKER) - { + // A package whose patch is incomplete on some copy is no patched + // package: its `Error:` line says what was written and what is not in + // effect. + for result in results.iter().filter(|r| { + r.success && r.package_path != VENDOR_OWNED_MARKER && !caveats.is_incomplete(&r.package_key) + }) { let detail = if !result.files_patched.is_empty() { // Summarize the per-file strategy used by this package: if // everything came from the same source, show just that tag; @@ -2523,6 +2624,106 @@ fn expected_hash_label(hash: &str) -> &str { } } +/// One gem copy `apply` left as it was because its build holds none of +/// the code the patch changes ([`gem_ext::GemCaveat::NotInBuild`]): the +/// JRuby build of a gem that takes no file of the patch. It is a `Skipped` +/// event of the patch, not an apply result. +struct LeftCopy { + /// The manifest key of the patch. + purl: String, + /// The reason, in words. + detail: String, +} + +impl LeftCopy { + fn event(&self) -> PatchEvent { + PatchEvent::new(PatchAction::Skipped, self.purl.clone()) + .with_reason(gem_ext::NOT_IN_BUILD_CODE, self.detail.as_str()) + } +} + +/// 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. +struct IncompleteCopy { + /// The manifest key of the patch. + purl: String, + /// The result's `package_path`: which copy. + path: String, + /// What was written and what is not in effect, in words. + detail: String, +} + +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_files(patched_files(result)) + } + + /// The run warning that says the same as this copy's `Error:` line. + fn warning_detail(&self) -> String { + format!("{}: {}", self.purl, self.detail) + } +} + +/// The gem copies of a run whose apply succeeded with a caveat +/// ([`gem_ext::GemCaveat`]). +#[derive(Default)] +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. + incomplete: Vec, +} + +impl GemCaveats { + /// The incomplete-patch entry of `result`'s copy, if it has one. + fn incomplete_of(&self, result: &ApplyResult) -> Option<&IncompleteCopy> { + self.incomplete + .iter() + .find(|copy| copy.purl == result.package_key && copy.path == result.package_path) + } + + /// Whether some copy of the package `purl` has an incomplete patch. + /// That package is not in effect, whatever its other copies say: it is + /// never counted or listed as applied. + fn is_incomplete(&self, purl: &str) -> bool { + self.incomplete.iter().any(|copy| copy.purl == purl) + } + + /// [`result_to_event`], or the `failed` event of an incomplete patch. + fn event_of(&self, result: &ApplyResult, dry_run: bool) -> PatchEvent { + match self.incomplete_of(result) { + Some(copy) => copy.event(result), + None => result_to_event(result, dry_run), + } + } + + /// 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) + } +} + +/// `Error: Patch of is incomplete: ` (stderr, even under +/// --silent): the files of the patch were written, and part of it is not +/// in effect. +fn format_patch_incomplete(purl: &str, what: &str) -> String { + format!("Error: Patch of {purl} is incomplete: {what}") +} + /// One gem-env fallback-home copy the fan-out skipped best-effort (a /// bundle-store copy applied; this shared-home copy mismatched or failed /// to write). Carries what the warning must name: the package, the copy's @@ -2590,6 +2791,7 @@ async fn apply_patches_inner( lockfile_only: HashSet::new(), run_warnings: vec![stage_failure_warning(args.common.offline)], fallback_skips: Vec::new(), + caveats: GemCaveats::default(), targeted: target_manifest_purls.len(), show_summary: false, }) @@ -2631,6 +2833,7 @@ async fn apply_patches_inner( lockfile_only: HashSet::new(), run_warnings: Vec::new(), fallback_skips: Vec::new(), + caveats: GemCaveats::default(), targeted: 0, show_summary: false, }); @@ -2704,6 +2907,7 @@ async fn apply_patches_inner( } } let mut fallback_skips: Vec = Vec::new(); + let mut caveats = GemCaveats::default(); let mut go_pristine_mods: HashMap = HashMap::new(); // Multi-copy aware: npm nests genuine duplicates of one `name@version` @@ -2786,6 +2990,7 @@ async fn apply_patches_inner( lockfile_only, run_warnings, fallback_skips, + caveats: GemCaveats::default(), targeted: target_manifest_purls.len(), show_summary: true, }); @@ -2950,6 +3155,10 @@ async fn apply_patches_inner( let mut any_store_copy_applied = false; let mut any_copy_applied = false; + // A copy's patch was incomplete. The package was dealt with (it + // is not gone over again under another of its manifest keys, + // which would run its build a second time), and not applied. + let mut any_copy_incomplete = false; for (pkg_path, is_store_copy) in store_copies .into_iter() .map(|p| (p, true)) @@ -3029,7 +3238,9 @@ async fn apply_patches_inner( // A native gem's copy does not hold every build // input of its source gem (a build removes them; a // precompiled gem never shipped them): those cannot - // tell distributions apart. + // tell distributions apart. Neither can a file the + // JRuby build of a gem has no use for: such a copy + // is matched by the files it takes of the record. let telling = gem_ext::discriminating_files(pkg_path, variant_purl, &patch.files) .await; @@ -3050,9 +3261,11 @@ async fn apply_patches_inner( // A gem patch to native-extension sources rebuilds the // extension (#1996). One it cannot build is refused // with nothing written; one whose build compiles - // nothing of it is written with a warning (#2144). + // nothing of it is written and is incomplete, which + // fails the run (#2144). The JRuby build of a gem takes + // the files that are part of it, and builds nothing. let result = if Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) { - let applied = gem_ext::apply_gem_package_patch( + let outcome = gem_ext::apply_gem_package_patch( args.common.read_scope(), variant_purl, pkg_path, @@ -3068,15 +3281,72 @@ async fn apply_patches_inner( }, ) .await; - // A best-effort fallback-home copy's refusal is - // its per-copy skip below, not a run warning. - if let Some((code, detail)) = applied - .warning - .filter(|_| applied.result.success || !best_effort) - { + // A best-effort fallback-home copy's refusal, or + // its incomplete patch, is its per-copy skip below, + // not a run warning. + let skipped_quietly = best_effort + && (!outcome.result.success + || matches!( + outcome.caveat, + Some(gem_ext::GemCaveat::Incomplete(_)) + )); + if let Some((code, detail)) = outcome.warning.filter(|_| !skipped_quietly) { run_warnings.push(RunWarning { code, detail }); } - applied.result + match outcome.caveat { + // A copy with nothing of the patch in its build + // (the JRuby build of a gem that takes no file + // of it) is the installed distribution, + // handled: its own skip, with the reason, and + // no result. + Some(gem_ext::GemCaveat::NotInBuild(detail)) => { + matched_manifest_purls.insert(variant_purl.clone()); + applied = true; + caveats.not_in_build.push(LeftCopy { + purl: variant_purl.clone(), + detail, + }); + continue; + } + // An incomplete patch on a BEST-EFFORT + // fallback-home copy is that copy's non-fatal + // skip, like a failure there: the bundle-store + // copy applied, so the run stands. + Some(gem_ext::GemCaveat::Incomplete(detail)) if best_effort => { + matched_manifest_purls.insert(variant_purl.clone()); + fallback_skips.push(FallbackHomeSkip { + purl: base_purl.clone(), + path: pkg_path.clone(), + why: detail, + }); + continue; + } + // An incomplete patch fails the run. Its files + // are written and stay written, so the result + // is recorded as the write it is, and the entry + // here makes it read as not patched. The copy + // never counts as one that applied: a + // fallback-home copy after it is not best + // effort, and the package is not in effect. + Some(gem_ext::GemCaveat::Incomplete(detail)) => { + has_errors = true; + any_copy_incomplete = true; + if args.prints_errors() { + eprintln!("{}", format_patch_incomplete(variant_purl, &detail)); + } + caveats.incomplete.push(IncompleteCopy { + purl: variant_purl.clone(), + path: outcome.result.package_path.clone(), + detail, + }); + warn_mismatch_overwrites(&outcome.result, &args.common); + matched_manifest_purls.insert(variant_purl.clone()); + results.push(outcome.result); + continue; + } + None => {} + } + outcome.result } else { apply_package_patch( args.common.read_scope(), @@ -3192,7 +3462,7 @@ async fn apply_patches_inner( } } - if any_copy_applied { + if any_copy_applied || any_copy_incomplete { applied_base_purls.insert(base_purl.clone()); } } else { @@ -3335,6 +3605,7 @@ async fn apply_patches_inner( lockfile_only, run_warnings, fallback_skips, + caveats, targeted: target_manifest_purls.len(), show_summary: true, }) @@ -4226,6 +4497,7 @@ mod tests { let missing = "pkg:npm/missing@1.0.0".to_string(); let (applied, skipped) = collect_apply_outcomes( &[unchanged_copy, changed_copy, vendored, already_patched], + &GemCaveats::default(), std::slice::from_ref(&missing), &HashSet::from([missing.clone()]), Vec::new(), @@ -4575,7 +4847,7 @@ mod tests { true, ), ]; - let t = tally_results(&results); + let t = tally_results(&results, &GemCaveats::default()); assert_eq!(t.applied, 1); assert_eq!(t.already, 0); assert_eq!(t.failed, 0); @@ -4592,7 +4864,7 @@ mod tests { let mut vendored = sample_applied(VerifyStatus::Ready); vendored.package_key = "pkg:npm/vend@1.0.0".into(); vendored.package_path = VENDOR_OWNED_MARKER.into(); - let t = tally_results(&[already, failed, vendored]); + let t = tally_results(&[already, failed, vendored], &GemCaveats::default()); assert_eq!( t, ApplyTally { @@ -4601,6 +4873,8 @@ mod tests { can_patch: 0, failed: 1, vendored: 1, + not_applicable: 0, + not_in_effect: 0, } ); assert_eq!( @@ -4608,7 +4882,297 @@ mod tests { "Summary: 0 of 3 targeted patches applied, 1 already patched, 1 vendored, 1 failed, \ 0 not found on disk" ); - assert_eq!(tally_results(&[]), ApplyTally::default()); + assert_eq!( + tally_results(&[], &GemCaveats::default()), + ApplyTally::default() + ); + } + + const GEM_PURL: &str = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + + /// A gem copy with nothing of the patch in its build (the JRuby build + /// of a gem that takes no file of it). + fn not_in_build() -> GemCaveats { + GemCaveats { + not_in_build: vec![LeftCopy { + purl: GEM_PURL.to_string(), + detail: "not part of it".to_string(), + }], + ..GemCaveats::default() + } + } + + /// The result of a gem copy whose patch is incomplete, and the caveat + /// that says so: the result itself is a successful write. + fn incomplete(written: bool) -> (ApplyResult, GemCaveats) { + let mut result = copy_at( + "/p/vendor/bundle/ruby/3.4.0/gems/nokogiri-1.18.10", + if written { + VerifyStatus::Ready + } else { + VerifyStatus::AlreadyPatched + }, + written, + ); + result.package_key = GEM_PURL.to_string(); + let caveats = GemCaveats { + incomplete: vec![IncompleteCopy { + purl: GEM_PURL.to_string(), + path: result.package_path.clone(), + detail: "the patch's files were written, but not built".to_string(), + }], + ..GemCaveats::default() + }; + (result, caveats) + } + + /// A copy with nothing of the patch in its build is a `skipped` event + /// with its reason: never an `applied` (or `verified`) event with no + /// files. + #[test] + fn a_copy_with_nothing_of_the_patch_is_a_skip_with_its_reason() { + let caveats = not_in_build(); + let v = serde_json::to_value(caveats.not_in_build[0].event()).unwrap(); + assert_eq!(v["action"], "skipped"); + assert_eq!(v["errorCode"], "not_in_platform_build"); + assert_eq!(v["reason"], "not part of it"); + assert_eq!(v["purl"], GEM_PURL); + // For a nested caller it is a skip of the patch as well. + let (applied, skipped) = + collect_apply_outcomes(&[], &caveats, &[], &HashSet::new(), Vec::new(), false); + assert!(applied.is_empty()); + assert_eq!(skipped.len(), 1); + assert_eq!( + skipped[0].error_code.as_deref(), + Some("not_in_platform_build") + ); + assert!(collect_apply_failures(&[], &caveats, &[], &HashSet::new()).is_empty()); + } + + /// An incomplete patch is a `failed` event under its own code, wet or + /// dry, that lists the files this run wrote: never a clean `applied`. + /// Any other result keeps the event it had. + #[test] + fn an_incomplete_patch_is_a_failed_event_that_lists_what_was_written() { + for dry_run in [false, true] { + let (result, caveats) = incomplete(true); + let v = serde_json::to_value(caveats.event_of(&result, dry_run)).unwrap(); + assert_eq!(v["action"], "failed", "dry_run={dry_run}"); + assert_eq!(v["errorCode"], "native_extension_not_rebuilt"); + assert_eq!(v["error"], "the patch's files were written, but not built"); + assert_eq!(v["purl"], GEM_PURL); + assert_eq!(v["files"][0]["path"], "package/index.js"); + assert_eq!(v["files"].as_array().map(Vec::len), Some(1)); + // The same result without the caveat is the write it is. + let plain = GemCaveats::default().event_of(&result, false); + assert_eq!(serde_json::to_value(plain).unwrap()["action"], "applied"); + // Another copy of the package is not this copy. + let mut other = result.clone(); + other.package_path = "/elsewhere/gems/nokogiri-1.18.10".to_string(); + let event = serde_json::to_value(caveats.event_of(&other, false)).unwrap(); + assert_eq!(event["action"], "applied"); + } + // A second run finds the files written: still incomplete, and it + // wrote nothing itself. + let (result, caveats) = incomplete(false); + let v = serde_json::to_value(caveats.event_of(&result, false)).unwrap(); + assert_eq!(v["action"], "failed"); + assert_eq!(v["errorCode"], "native_extension_not_rebuilt"); + assert!(v + .get("files") + .is_none_or(|f| f.as_array().is_some_and(Vec::is_empty))); + } + + /// For a nested caller (`get`, `scan --mode agent`) an incomplete + /// patch is a failure of the patch with its code and words, and never + /// one of the packages the apply patched. + #[test] + fn an_incomplete_patch_is_a_failure_of_the_nested_apply() { + let (result, caveats) = incomplete(true); + let results = [result]; + let failures = collect_apply_failures(&results, &caveats, &[], &HashSet::new()); + assert_eq!( + failures, + vec![ApplyFailure { + purl: GEM_PURL.to_string(), + code: "native_extension_not_rebuilt".to_string(), + error: "the patch's files were written, but not built".to_string(), + }] + ); + let (applied, skipped) = + collect_apply_outcomes(&results, &caveats, &[], &HashSet::new(), Vec::new(), false); + assert!(applied.is_empty(), "{applied:?}"); + assert!(skipped.is_empty()); + // Without the caveat the same result is a patched package. + let (applied, _) = collect_apply_outcomes( + &results, + &GemCaveats::default(), + &[], + &HashSet::new(), + Vec::new(), + false, + ); + assert_eq!(applied, [GEM_PURL]); + } + + /// The human path prints an incomplete patch once, as its `Error:` + /// line: the coded warning that says the same is for the envelope, and + /// the package is not listed among the patched ones. + #[test] + fn an_incomplete_patch_is_printed_once_and_not_listed_as_patched() { + let (result, caveats) = incomplete(true); + let detail = &caveats.incomplete[0].detail; + assert_eq!( + format_patch_incomplete(GEM_PURL, detail), + format!("Error: Patch of {GEM_PURL} is incomplete: {detail}") + ); + let restated = RunWarning::new( + "native_extension_not_rebuilt", + format!("{GEM_PURL}: {detail}"), + ); + assert!(caveats.restated_by(&restated)); + for other in [ + RunWarning::new("native_extension_not_rebuilt", "another package: x"), + RunWarning::new("native_extension_rebuilt", format!("{GEM_PURL}: {detail}")), + ] { + assert!(!caveats.restated_by(&other), "{}", other.detail); + } + assert!(!GemCaveats::default().restated_by(&restated)); + assert!(format_results_block( + std::slice::from_ref(&result), + &caveats, + false, + Path::new("/p") + ) + .is_empty()); + assert!( + !format_results_block(&[result], &GemCaveats::default(), false, Path::new("/p")) + .is_empty() + ); + } + + /// The summary accounts for both under their own headings: "not + /// applicable" when the code is not in the build (nothing left to do), + /// "not in effect" when the patch is incomplete. An incomplete patch + /// is never counted as applied or already patched, whatever its result + /// wrote. + #[test] + fn tally_tells_nothing_to_do_from_not_in_effect() { + let t = tally_results(&[], ¬_in_build()); + assert_eq!( + t, + ApplyTally { + not_applicable: 1, + ..ApplyTally::default() + } + ); + assert_eq!( + format_summary_line(&t, 1, 0), + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not applicable, \ + 0 not found on disk" + ); + assert_eq!( + format_dry_run_summary(&t, 0), + vec![ + "Patch verification complete:", + " 0 packages can be patched", + " 1 package not applicable", + ] + ); + + for written in [true, false] { + let (result, caveats) = incomplete(written); + let t = tally_results(std::slice::from_ref(&result), &caveats); + assert_eq!( + t, + ApplyTally { + not_in_effect: 1, + ..ApplyTally::default() + }, + "written={written}" + ); + assert_eq!( + format_summary_line(&t, 1, 0), + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not in effect, \ + 0 not found on disk" + ); + assert_eq!( + format_dry_run_summary(&t, 0), + vec![ + "Patch verification complete:", + " 0 packages can be patched", + " 1 package would not take effect", + ] + ); + // Without the caveat the same result counts as what it wrote. + let plain = tally_results(&[result], &GemCaveats::default()); + assert_eq!( + (plain.applied, plain.already), + (usize::from(written), usize::from(!written)) + ); + } + + // A copy with nothing of the patch beside an incomplete one: the + // package is not done. Beside a patched one: it is applied. + let (result, mut caveats) = incomplete(true); + caveats.not_in_build = not_in_build().not_in_build; + let t = tally_results(std::slice::from_ref(&result), &caveats); + assert_eq!((t.not_applicable, t.not_in_effect), (0, 1)); + let t = tally_results(&[result], ¬_in_build()); + assert_eq!((t.applied, t.not_applicable, t.not_in_effect), (1, 0, 0)); + } + + /// A package with an incomplete patch on one copy is not in effect, + /// once, whatever its other copies say: a copy that applied cleanly + /// does not make it applied in the summary, list it under the patched + /// packages, or hand it to a nested caller as applied. Each copy keeps + /// its own event. + #[test] + fn a_package_with_an_incomplete_copy_is_never_applied() { + let (incomplete_copy, caveats) = incomplete(true); + let mut fine = copy_at( + "/p/vendor/bundle/ruby/3.4.0/gems/nokogiri-1.18.10-arm64-darwin", + VerifyStatus::Ready, + true, + ); + fine.package_key = GEM_PURL.to_string(); + for results in [ + vec![fine.clone(), incomplete_copy.clone()], + vec![incomplete_copy.clone(), fine.clone()], + ] { + let t = tally_results(&results, &caveats); + assert_eq!( + t, + ApplyTally { + not_in_effect: 1, + ..ApplyTally::default() + } + ); + assert_eq!( + format_summary_line(&t, 1, 0), + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not in effect, \ + 0 not found on disk" + ); + assert!(format_results_block(&results, &caveats, false, Path::new("/p")).is_empty()); + let (applied, skipped) = + collect_apply_outcomes(&results, &caveats, &[], &HashSet::new(), Vec::new(), false); + assert!(applied.is_empty(), "{applied:?}"); + assert!(skipped.is_empty()); + let failures = collect_apply_failures(&results, &caveats, &[], &HashSet::new()); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].code, "native_extension_not_rebuilt"); + } + // The copies' own events stay what each copy is. + let event = |result: &ApplyResult| { + serde_json::to_value(caveats.event_of(result, false)).unwrap()["action"].clone() + }; + assert_eq!(event(&fine), "applied"); + assert_eq!(event(&incomplete_copy), "failed"); + // Another package is not touched by it. + let other = copy_at("/p/node_modules/nuxt", VerifyStatus::Ready, true); + let t = tally_results(&[other.clone(), incomplete_copy], &caveats); + assert_eq!((t.applied, t.not_in_effect), (1, 1)); + assert!(!format_results_block(&[other], &caveats, false, Path::new("/p")).is_empty()); } #[test] @@ -4619,6 +5183,8 @@ mod tests { failed: 1, applied: 0, vendored: 0, + not_applicable: 1, + not_in_effect: 2, }; assert_eq!( format_dry_run_summary(&t, 3), @@ -4626,6 +5192,8 @@ mod tests { "Patch verification complete:", " 1 package can be patched", " 2 packages already patched", + " 1 package not applicable", + " 2 packages would not take effect", " 1 package cannot be patched", " 3 packages not found on disk", ] @@ -4645,11 +5213,18 @@ mod tests { let mut failed = sample_applied(VerifyStatus::Ready); failed.success = false; failed.files_patched.clear(); - assert!(format_results_block(&[failed], false, Path::new("/p")).is_empty()); - assert!(format_results_block(&[], false, Path::new("/p")).is_empty()); + assert!( + format_results_block(&[failed], &GemCaveats::default(), false, Path::new("/p")) + .is_empty() + ); + assert!( + format_results_block(&[], &GemCaveats::default(), false, Path::new("/p")).is_empty() + ); // Dry runs report through the verification block instead. let ok = sample_applied(VerifyStatus::Ready); - assert!(format_results_block(&[ok], true, Path::new("/p")).is_empty()); + assert!( + format_results_block(&[ok], &GemCaveats::default(), true, Path::new("/p")).is_empty() + ); } #[test] @@ -4663,7 +5238,12 @@ mod tests { r }; assert_eq!( - format_results_block(&[ok, already], false, Path::new("/tmp")), + format_results_block( + &[ok, already], + &GemCaveats::default(), + false, + Path::new("/tmp") + ), vec![ "", "Patched packages:", @@ -4684,7 +5264,7 @@ mod tests { ), ]; assert_eq!( - format_results_block(&results, false, Path::new("/p")), + format_results_block(&results, &GemCaveats::default(), false, Path::new("/p")), vec![ "", "Patched packages:", @@ -4924,7 +5504,8 @@ mod tests { failed_result("pkg:npm/b@1.0.0", None), sample_applied(VerifyStatus::Ready), ]; - let failures = collect_apply_failures(&results, &[], &HashSet::new()); + let failures = + collect_apply_failures(&results, &GemCaveats::default(), &[], &HashSet::new()); assert_eq!( failures, vec![ @@ -4949,7 +5530,8 @@ mod tests { "pkg:npm/opt@1.0.0".to_string(), ]; let lockfile_only = HashSet::from(["pkg:npm/opt@1.0.0".to_string()]); - let failures = collect_apply_failures(&[], &unmatched, &lockfile_only); + let failures = + collect_apply_failures(&[], &GemCaveats::default(), &unmatched, &lockfile_only); assert_eq!( failures, vec![ApplyFailure { @@ -4961,7 +5543,8 @@ mod tests { ); // Beside a real failure, an uninstalled patch is only a warning. let results = vec![failed_result("pkg:npm/a@1.0.0", Some("boom"))]; - let failures = collect_apply_failures(&results, &unmatched, &lockfile_only); + let failures = + collect_apply_failures(&results, &GemCaveats::default(), &unmatched, &lockfile_only); assert_eq!(failures.len(), 1, "{failures:?}"); assert_eq!(failures[0].purl, "pkg:npm/a@1.0.0"); } diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index 2a6701060..3db169b95 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -3466,6 +3466,36 @@ mod tests { assert!(env.error.is_none()); } + /// An incomplete patch (its files written, its compiled part not in + /// effect) reaches the caller as a failure of the nested apply under + /// its own code: the recorded patch is `failed` with that code and the + /// apply's words, never `applied`, and the run is a partial failure. + #[test] + fn record_apply_outcome_reports_an_incomplete_patch_under_its_own_code() { + let mut env = Envelope::new(JsonCommand::Get); + let purl = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let report = report_with( + vec![failure( + purl, + "native_extension_not_rebuilt", + "the patch's files were written, but not built", + )], + &[], + ); + let recs = recorded(&[(purl, "un")]); + record_apply_outcome(&mut env, &recs, Some(&report), |_| None); + assert_eq!( + outcomes(&env), + vec![o("failed", purl, "un", "native_extension_not_rebuilt")] + ); + assert_eq!( + env.events[0].error.as_deref(), + Some("the patch's files were written, but not built") + ); + assert_eq!(env.status, Status::PartialFailure); + assert_eq!(env.summary.applied, 0); + } + #[test] fn record_apply_outcome_matches_percent_encoded_and_base_purl_keys() { let mut env = Envelope::new(JsonCommand::Get); diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 36f2e0d1a..25fb544e7 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -784,7 +784,24 @@ fn rollback_failure_code(result: &RollbackResult) -> &'static str { /// `already_original`, or `failed` with the blocking file's code. The /// installed copy rides in `details.path`; a failure adds /// `details.filesVerified` (per-file camelCase status + hashes). -fn agent_result_event(result: &RollbackResult, uuid: Option<&str>, dry_run: bool) -> PatchEvent { +/// +/// `record` is the result's manifest record. A gem record that lists +/// files, none of which was looked at on the copy, is `skipped` +/// `not_in_platform_build`, wet or dry: none of them is part of the build +/// installed there (the JRuby build of a gem, see +/// `gem_ext::rollback_files`), so `apply` wrote nothing of the patch and +/// there is nothing to restore. That is not a record with no files. +fn agent_result_event( + result: &RollbackResult, + record: Option<&PatchRecord>, + dry_run: bool, +) -> PatchEvent { + let uuid = record.map(|record| record.uuid.as_str()); + let nothing_of_it_here = result.success + && result.files_verified.is_empty() + && result.files_rolled_back.is_empty() + && record.is_some_and(|record| !record.files.is_empty()) + && Ecosystem::from_purl(&result.package_key) == Some(Ecosystem::Gem); let file = |path: &str| PatchEventFile { path: path.to_string(), verified: true, @@ -815,6 +832,12 @@ fn agent_result_event(result: &RollbackResult, uuid: Option<&str>, dry_run: bool "already_original", "every file already matches its original (beforeHash) content", ) + } else if nothing_of_it_here { + PatchEvent::new(PatchAction::Skipped, result.package_key.clone()).with_reason( + socket_patch_core::patch::gem_ext::NOT_IN_BUILD_CODE, + "none of the patch's files are part of the build of the gem installed here: \ + nothing of the patch was applied to it, so there is nothing to restore", + ) } else if dry_run { PatchEvent::new(PatchAction::Verified, result.package_key.clone()).with_files( result @@ -1239,7 +1262,7 @@ fn build_rollback_envelope(report: &RollbackReport<'_>) -> Envelope { for result in report.results { env.record(agent_result_event( result, - manifest_uuid(&result.package_key), + report.manifest.patches.get(&result.package_key), dry_run, )); if let Some(sidecar) = &result.sidecar { @@ -3668,7 +3691,7 @@ pub(crate) async fn rollback_patches_inner( // hold it (a precompiled gem never shipped it; a build // removed it) is removed, not restored. let gem_files = if is_gem { - Some(gem_ext::rollback_files(pkg_path, &patch.files).await) + Some(gem_ext::rollback_files(pkg_path, purl, &patch.files).await) } else { None }; diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index c960e329f..9af689aca 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -801,14 +801,19 @@ fn print_coverage( } /// The uuids of the patches an agent run left applied: the ones its nested -/// apply wrote, and the ones it found already in place. +/// apply wrote, the ones it found already in place, and the ones whose +/// code is not in the build installed here +/// ([`skip_leaves_patched`](crate::json_envelope::skip_leaves_patched)), +/// as `apply --check` and `vex` count them. fn patched_uuids(outcome: &Envelope) -> HashSet<&str> { outcome .events .iter() .filter(|event| match event.action { PatchAction::Applied => true, - PatchAction::Skipped => event.error_code.as_deref() == Some("already_patched"), + PatchAction::Skipped => { + crate::json_envelope::skip_leaves_patched(event.error_code.as_deref()) + } _ => false, }) .filter_map(|event| event.uuid.as_deref()) @@ -3922,6 +3927,56 @@ async fn scan_project( mod tests { use super::*; + /// The patches an agent run left in place, for the coverage lines: the + /// ones it wrote, the ones already there, and the ones whose code is + /// not in the build installed here, which `apply --check` and `vex` + /// count as patched too. An incomplete patch (its files written, its + /// compiled part not in effect), a failed one and one that is not + /// installed are not among them. + #[test] + fn patched_uuids_are_the_patches_the_run_left_in_place() { + let mut env = Envelope::new(JsonCommand::Scan); + let skip = |purl: &str, uuid: &str, code: &str| { + PatchEvent::new(PatchAction::Skipped, purl) + .with_uuid(uuid) + .with_reason(code, "why") + }; + env.record(PatchEvent::new(PatchAction::Applied, "pkg:gem/a@1").with_uuid("applied")); + env.record(skip("pkg:gem/b@1", "in-place", "already_patched")); + env.record(skip( + "pkg:gem/nokogiri@1.18.10?platform=ruby", + "not-in-build", + "not_in_platform_build", + )); + // An incomplete patch: its files are written and what the copy + // compiles is not the patch's. The apply reports it as failed + // under its own code, on the run that wrote the files and on + // every later one, and it is no patch left in place. + env.record( + PatchEvent::new(PatchAction::Failed, "pkg:gem/c@1") + .with_uuid("incomplete") + .with_error( + "native_extension_not_rebuilt", + "the patch's files were written, but not built", + ), + ); + // Neither is a skip that carries that code. + env.record(skip( + "pkg:gem/c2@1", + "not-rebuilt", + "native_extension_not_rebuilt", + )); + env.record(skip("pkg:gem/d@1", "absent", "package_not_installed")); + env.record( + PatchEvent::new(PatchAction::Failed, "pkg:gem/e@1") + .with_uuid("failed") + .with_error("apply_failed", "no"), + ); + let mut landed: Vec<&str> = patched_uuids(&env).into_iter().collect(); + landed.sort_unstable(); + assert_eq!(landed, ["applied", "in-place", "not-in-build"]); + } + #[test] fn pypi_equivalents_add_spellings_only_for_lockfile_only_pypi_pins() { let purls: Vec = [ diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index f5614ead8..d5926d63c 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -25,7 +25,7 @@ use socket_patch_core::manifest::schema::PatchManifest; use socket_patch_core::telemetry::{track_vex_failed, track_vex_generated, TelemetryAuth}; use socket_patch_core::vex::verify::{npm_manifest_after_hash, DEPENDENCY_NOT_INSTALLED}; use socket_patch_core::vex::{ - build_document_marking_unverified, detect_product, BuildOptions, Document, FailedPatch, + build_document_with, detect_product, Attested, BuildOptions, Document, FailedPatch, VendorContext, VerifyOutcome, NOT_VERIFIED_SUFFIX, }; @@ -1379,12 +1379,17 @@ async fn generate_vex( Vec::new() }; - let doc = match build_document_marking_unverified( + let doc = match build_document_with( manifest, - &outcome.applied, - &outcome.vendored, - redirected, - &unverified, + &Attested { + applied: &outcome.applied, + vendored: &outcome.vendored, + redirected, + unverified: &unverified, + // A package no installed build of which holds any file of + // its patch: not affected because the code is not there. + code_not_present: &outcome.code_not_present, + }, &opts, ) { Some(doc) => doc, diff --git a/crates/socket-patch-cli/src/hot_patch.rs b/crates/socket-patch-cli/src/hot_patch.rs index 8441a9311..f73da6bf1 100644 --- a/crates/socket-patch-cli/src/hot_patch.rs +++ b/crates/socket-patch-cli/src/hot_patch.rs @@ -365,7 +365,9 @@ fn summary_line( // not news either. let in_place = distinct( &mut events(reports, "skipped") - .filter(|event| text(event, "errorCode").as_deref() == Some("already_patched")) + .filter(|event| { + crate::json_envelope::skip_leaves_patched(text(event, "errorCode").as_deref()) + }) .filter(|event| !applied.contains(&text(event, "purl"))), ); let failed = distinct(&mut events(reports, "failed")); @@ -705,6 +707,30 @@ mod tests { ); } + /// A patch whose code is not in the build installed here is in place + /// as far as it can be, like one already applied. An incomplete patch + /// (its files written, its compiled part not in effect) is not: it is + /// a patch that was not applied, on the run that wrote the files and + /// on every later one. + #[test] + fn a_patch_with_nothing_to_change_here_counts_as_in_place() { + let project = json!({ "status": "partialFailure", "scannedPackages": 12, "events": [ + { "action": "skipped", "purl": "pkg:gem/nokogiri@1.18.10", + "errorCode": "not_in_platform_build" }, + { "action": "skipped", "purl": "pkg:gem/rack@3.1.0", "errorCode": "already_patched" }, + { "action": "failed", "purl": "pkg:gem/other@1.0.0", + "errorCode": "native_extension_not_rebuilt", + "error": "the patch's files were written, but not built" }, + { "action": "skipped", "purl": "pkg:gem/absent@1.0.0", + "errorCode": "package_not_installed" }, + ]}); + assert_eq!( + summary_line(&[(PROJECT, project)], false, LIMIT, "0.4s"), + "2 patches already in place; 1 patch not applied (pkg:gem/other@1.0.0: the patch's \ + files were written, but not built) [12 project packages checked, 0.4s]" + ); + } + #[test] fn the_line_says_why_nothing_was_patched() { let read_only = json!({ "status": "partialFailure", "scannedPackages": 106, "events": [ diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index 37c6ef4f6..874a90fea 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -699,6 +699,20 @@ impl RunWarning { } } +/// Whether a `skipped` apply event with this `errorCode` reports a package +/// that is patched as far as it can be on this install: every file already +/// holds the patch (`already_patched`), or the build installed there holds +/// none of the code the patch changes (`not_in_platform_build`). Whatever +/// counts the patches a run left in place reads it through this, so that +/// it agrees with `apply --check` and `vex`. A `native_extension_not_rebuilt` +/// skip is not one: that patch is not in effect. +pub(crate) fn skip_leaves_patched(error_code: Option<&str>) -> bool { + matches!( + error_code, + Some("already_patched") | Some(socket_patch_core::patch::gem_ext::NOT_IN_BUILD_CODE) + ) +} + #[cfg(test)] mod tests { use super::*; @@ -1323,4 +1337,26 @@ mod tests { assert_eq!(value["gc"], serde_json::to_value(report).unwrap()); assert_eq!(value["summary"]["bytesFreed"], 34); } + + /// Only a skip that leaves the package patched as far as it can be + /// counts as landed: one already patched, and one whose code is not + /// in the build installed here. A patch written without effect, a + /// package that is not installed and a vendored one are not. + #[test] + fn only_a_skip_with_nothing_left_to_do_leaves_the_package_patched() { + assert!(skip_leaves_patched(Some("already_patched"))); + assert!(skip_leaves_patched(Some( + socket_patch_core::patch::gem_ext::NOT_IN_BUILD_CODE + ))); + assert!(skip_leaves_patched(Some("not_in_platform_build"))); + for code in [ + Some(socket_patch_core::patch::gem_ext::NOT_REBUILT_REASON), + Some("package_not_installed"), + Some("vendored"), + Some("gem_fallback_home_skipped"), + None, + ] { + assert!(!skip_leaves_patched(code), "{code:?}"); + } + } } diff --git a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs index 1a21534dd..bcf025be1 100644 --- a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs +++ b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs @@ -226,6 +226,41 @@ fn not_rebuilt_warning(stdout: &str) -> String { .to_string() } +/// The event of a patch that is INCOMPLETE in an `apply --json` envelope, +/// after checking the shape the contract gives it: the run is a partial +/// failure, and the patch's event is `failed` with the +/// `native_extension_not_rebuilt` code (never a clean `applied`), beside +/// the warning of the same code and text. +fn incomplete_event(stdout: &str, purl: &str) -> serde_json::Value { + let env = parse_json_envelope(stdout); + assert_eq!(env["status"], "partialFailure", "{stdout}"); + let event = common::envelope::event_for(&env, purl).clone(); + assert_eq!(event["action"], "failed", "{stdout}"); + assert_eq!( + event["errorCode"], "native_extension_not_rebuilt", + "{stdout}" + ); + let error = event["error"].as_str().unwrap_or_default(); + assert_eq!( + not_rebuilt_warning(stdout), + format!("{purl}: {error}"), + "the warning says what the event says: {stdout}" + ); + event +} + +/// The paths an event lists in `files`, sorted. +fn event_files(event: &serde_json::Value) -> Vec { + let mut files: Vec = event["files"] + .as_array() + .into_iter() + .flatten() + .filter_map(|file| file["path"].as_str().map(str::to_string)) + .collect(); + files.sort(); + files +} + /// `tree` with the file `rel` holding `bytes`. fn tree_with(tree: &[(String, Vec)], rel: &str, bytes: &[u8]) -> Vec<(String, Vec)> { let mut out: Vec<_> = tree.iter().filter(|(r, _)| r != rel).cloned().collect(); @@ -1374,6 +1409,24 @@ fn opted_out_native_patch_writes_sources_without_a_build() { // The build Ruby loads is still the old one: no attestation. let (code, stdout, _) = run_without_ruby(&proj, &["apply", "--check", "--json"]); assert_ne!(code, 0, "{stdout}"); + + // A dry run writes nothing, and says what apply would do. + let (_tmp, proj, gem_dir) = fake_native_gem(true); + write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + let dry: Vec<&str> = opt_out.iter().copied().chain(["--dry-run"]).collect(); + let (code, stdout, stderr) = common::run_with_env(&proj, &dry, &env); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + let warning = not_rebuilt_warning(&stdout); + assert!( + warning.contains("dry run") + && warning.contains("apply would write them without rebuilding the extension") + && !warning.contains(", written "), + "{warning}" + ); + assert_eq!( + std::fs::read_to_string(gem_dir.join(C_KEY)).unwrap(), + c_source(1) + ); } } @@ -1514,6 +1567,164 @@ async fn the_opt_out_reaches_the_apply_that_scan_and_get_run() { } } +/// An incomplete patch through the apply that `scan --mode agent` and +/// `get --mode agent` run: they report it and exit 1 as for any package +/// whose apply failed, under the patch's own code, and the patch stays +/// recorded in the manifest with its files written, so `rollback` undoes +/// it. (The build here leaves no compiled file, as a gem whose extension +/// script downloads the binary it runs.) +#[cfg(unix)] +#[tokio::test] +async fn an_incomplete_patch_fails_scan_and_get_and_stays_recorded() { + let mock = wiremock::MockServer::start().await; + mount_native_patch_api(&mock).await; + let uri = mock.uri(); + let api = ["--api-url", &uri, "--api-token", "fake-token", "--org", ORG]; + let cases = [ + ("scan", &["scan", "--mode", "agent", "--yes", "--json"][..]), + ("scan, human output", &["scan", "--mode", "agent", "--yes"]), + ("get", &["get", PURL, "--mode", "agent", "--yes", "--json"]), + ( + "get, human output", + &["get", PURL, "--mode", "agent", "--yes"], + ), + ]; + for (case, command) in cases { + let (_tmp, proj, gem_dir, _home) = built_gem_with_its_archive(); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + ruby.build_nothing(); + let tree_before = walk_files(&proj.join("vendor")); + let args = [command, &api[..]].concat(); + let (code, stdout, stderr) = ruby.run(&proj, &args, &[]); + assert_eq!(code, 1, "{case}:\n{stdout}\n{stderr}"); + + // The patch's file is written and stays written; the compiled + // code is as it was installed, with no marker beside it. + assert_eq!( + std::fs::read_to_string(gem_dir.join(C_KEY)).unwrap(), + c_source(2), + "{case}: the patched source was not left written\n{stdout}\n{stderr}" + ); + assert_eq!( + std::fs::read(gem_dir.join("lib/sp_native/sp_native.so")).unwrap(), + b"\x7fELF original", + "{case}" + ); + assert!( + !gem_dir.join(".socket-patch-native-build.json").exists(), + "{case}" + ); + + if command.contains(&"--json") { + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "partialFailure", "{case}: {stdout}"); + let events: Vec<&serde_json::Value> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["purl"] == PURL) + .collect(); + let failed = events + .iter() + .find(|e| e["action"] == "failed") + .unwrap_or_else(|| panic!("{case}: no failed event:\n{stdout}")); + assert_eq!( + failed["errorCode"], "native_extension_not_rebuilt", + "{case}: {stdout}" + ); + let error = failed["error"].as_str().unwrap_or_default(); + assert!( + error.contains("the patch's files were written") + && error.contains("left no compiled file"), + "{case}: {error}" + ); + assert!( + !events.iter().any(|e| e["action"] == "applied"), + "{case}: the patch reads as applied:\n{stdout}" + ); + assert!( + common::envelope::warning_codes(&env) + .iter() + .any(|code| code == "native_extension_not_rebuilt"), + "{case}: {stdout}" + ); + } else { + let error_line = + format!("Error: Patch of {PURL} is incomplete: the patch's files were written"); + assert!(stderr.contains(&error_line), "{case}:\n{stderr}"); + assert!( + stderr.contains("Error: Some patches could not be applied."), + "{case}:\n{stderr}" + ); + } + + // The patch stays recorded, so the installed copy is still known + // as patched by it: out of sync, and there to roll back. + let manifest = std::fs::read_to_string(proj.join(".socket/manifest.json")) + .unwrap_or_else(|e| panic!("{case}: the manifest is gone: {e}")); + assert!( + manifest.contains(PURL) && manifest.contains(UUID), + "{case}: the patch was dropped from the manifest:\n{manifest}" + ); + + // A second run finds the file written and the patch still + // incomplete: it fails the same way, and nothing reads as applied + // or already in place. + let (code, stdout, stderr) = ruby.run(&proj, &args, &[]); + assert_eq!(code, 1, "{case}, second run:\n{stdout}\n{stderr}"); + if command.contains(&"--json") { + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "partialFailure", "{case}: {stdout}"); + let of_patch: Vec<(String, String)> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["purl"] == PURL) + .map(|e| { + let field = |key: &str| e[key].as_str().unwrap_or_default().to_string(); + (field("action"), field("errorCode")) + }) + .collect(); + assert!( + of_patch.contains(&( + "failed".to_string(), + "native_extension_not_rebuilt".to_string() + )), + "{case}, second run: {of_patch:?}" + ); + assert!( + !of_patch + .iter() + .any(|(action, code)| action == "applied" || code == "already_patched"), + "{case}, second run: {of_patch:?}" + ); + } else { + assert!( + stderr.contains(&format!("Error: Patch of {PURL} is incomplete:")), + "{case}, second run:\n{stderr}" + ); + } + let (check, check_out, _) = ruby.run(&proj, &["apply", "--check", "--json"], &[]); + assert_ne!(check, 0, "{case}: {check_out}"); + assert!( + check_out.contains("native_extension_not_rebuilt"), + "{case}: {check_out}" + ); + // `rollback` restores from the patch's before-blob, which it would + // fetch on demand: here it is put where the download puts it. + let before = c_source(1); + write_blob( + &proj.join(".socket"), + &git_sha256(before.as_bytes()), + before.as_bytes(), + ); + let (code, stdout, stderr) = ruby.run(&proj, &["rollback", "--json", "--offline"], &[]); + assert_eq!(code, 0, "{case}: rollback failed:\n{stdout}\n{stderr}"); + assert_tree(&proj.join("vendor"), &tree_before, case); + } +} + // ── rebuilds from the source gem ────────────────────────────────────── // // An installed gem does not hold everything its extension was built from: @@ -1579,6 +1790,28 @@ fn vex_attests(run: impl Fn(&[&str]) -> (i32, String, String)) -> bool { stdout.contains("\"not_affected\"") } +/// The `vex` document of the project (`None` when the command writes +/// none), for a test that reads a statement. +fn vex_document(run: impl Fn(&[&str]) -> (i32, String, String)) -> Option { + let (_, stdout, _) = run(&["vex", "--product", "pkg:generic/app@1"]); + serde_json::from_str(&stdout).ok() +} + +/// The `@id` of every subcomponent a `vex` document attests. +fn vex_subcomponents(document: &serde_json::Value) -> Vec { + let mut ids: Vec = document["statements"] + .as_array() + .into_iter() + .flatten() + .flat_map(|statement| statement["products"].as_array().into_iter().flatten()) + .flat_map(|product| product["subcomponents"].as_array().into_iter().flatten()) + .filter_map(|sub| sub["@id"].as_str().map(str::to_string)) + .collect(); + ids.sort(); + ids.dedup(); + ids +} + const PRE_FULL_NAME: &str = "sp_native-1.0.0-x86_64-linux"; const BASE_PATCH: &str = "base\n"; @@ -1857,13 +2090,15 @@ fn records_reads(dir: &Path) -> bool { /// written, "rebuilt" and attested on such an install, with nothing of it /// in what Ruby loads. The CLI knows no gem's switches: it marks the /// record's build inputs unread, and a build that read none of them is not -/// a build of the patch. The record's files are written, the compiled code -/// stays what it was, the run says so, and nothing attests the copy -/// (#2144). The same record is built by a build that applies the patch -/// file. +/// a build of the patch. The record's files are written and stay written, +/// the compiled code stays what it was, and the patch is incomplete: the +/// run fails (exit 1) and says what was written and what is not in +/// effect, and nothing attests the copy (#2144). `rollback` still takes +/// the file out. The same record is built by a build that applies the +/// patch file. #[cfg(unix)] #[test] -fn a_build_that_reads_nothing_of_the_patch_writes_it_and_attests_nothing() { +fn a_build_that_reads_nothing_of_the_patch_writes_it_and_fails_as_incomplete() { const PATCH_REL: &str = "patches/libsp/0100-CVE-test.patch"; let library_patch: [RecordFile<'_>; 1] = [(PATCH_REL, None, "fix\n")]; let (_tmp, proj, gem_dir, home) = built_gem_with_its_archive(); @@ -1882,21 +2117,23 @@ fn a_build_that_reads_nothing_of_the_patch_writes_it_and_attests_nothing() { ); let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); - assert_eq!(code, 0, "ruby ran {:?}\n{stdout}\n{stderr}", ruby.calls()); - assert_eq!(event_action(&stdout), "applied", "{stdout}"); - let warning = not_rebuilt_warning(&stdout); + assert_eq!(code, 1, "ruby ran {:?}\n{stdout}\n{stderr}", ruby.calls()); + let event = incomplete_event(&stdout, PURL); + let error = event["error"].as_str().unwrap_or_default(); for needle in [ "the patch's files were written", "without reading any of those files", PATCH_REL, "vex does not attest the patch", ] { - assert!(warning.contains(needle), "no {needle:?} in {warning:?}"); + assert!(error.contains(needle), "no {needle:?} in {error:?}"); } assert!( - !warning.contains(" "), - "the message has a gap in it: {warning}" + !error.contains(" "), + "the message has a gap in it: {error}" ); + // The event lists what this run wrote. + assert_eq!(event_files(&event), [PATCH_REL], "{stdout}"); assert_eq!( ruby.calls(), ["extensions_dir", "unpack", "missing_deps", "stage_build"], @@ -1912,22 +2149,42 @@ fn a_build_that_reads_nothing_of_the_patch_writes_it_and_attests_nothing() { "vex attested a patch that is compiled into nothing" ); - // Applying again says the same and changes nothing. + // Applying again says the same and changes nothing: the patch is as + // incomplete as it was, and this run wrote no file. let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); - assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + let event = incomplete_event(&stdout, PURL); assert!( - not_rebuilt_warning(&stdout).contains("without reading any of those files"), + event["error"] + .as_str() + .is_some_and(|e| e.contains("without reading any of those files")), "{stdout}" ); + assert_eq!(event_files(&event), Vec::::new(), "{stdout}"); + assert!(!stdout.contains("already_patched"), "{stdout}"); assert_tree(&proj.join("vendor"), &written, "after a second apply"); - // The human path says it too, as a warning beside the summary. + // The human path says it once, as the package's error (also under + // `--silent`), and the summary does not count the patch as applied. let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--offline"], &[]); - assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + let error_line = + format!("Error: Patch of {PURL} is incomplete: the patch's files were written"); + assert!(stderr.contains(&error_line), "{stdout}\n{stderr}"); + assert_eq!( + stderr.matches("vex does not attest the patch").count(), + 1, + "the error is not repeated as a warning:\n{stderr}" + ); assert!( - stderr.contains("Warning:") && stderr.contains("vex does not attest the patch"), - "{stdout}\n{stderr}" + stdout.contains("0 of 1 targeted patch applied") && stdout.contains("1 not in effect"), + "{stdout}" ); + assert!(!stdout.contains("Patched packages:"), "{stdout}"); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--offline", "--silent"], &[]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!(stderr.contains(&error_line), "{stdout}\n{stderr}"); + assert_tree(&proj.join("vendor"), &written, "after the human runs"); // Rollback takes the file out again. let (code, stdout, stderr) = ruby.run(&proj, &["rollback", "--json", "--offline"], &[]); @@ -1963,8 +2220,8 @@ fn a_build_that_reads_nothing_of_the_patch_writes_it_and_attests_nothing() { /// The rebuild of an installed tree (no source gem to stage) is held to the /// same: after a build that read nothing of the patch, the previous build -/// is put back, the record's files stay written, and nothing attests the -/// copy. +/// is put back, the record's files stay written, the run fails with the +/// patch incomplete, and nothing attests the copy. #[cfg(unix)] #[test] fn an_in_place_build_that_reads_nothing_of_the_patch_keeps_the_previous_build() { @@ -1993,14 +2250,16 @@ fn an_in_place_build_that_reads_nothing_of_the_patch_keeps_the_previous_build() ); let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); - assert_eq!(code, 0, "{stdout}\n{stderr}"); - assert_eq!(event_action(&stdout), "applied", "{stdout}"); - let warning = not_rebuilt_warning(&stdout); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + let event = incomplete_event(&stdout, PURL); + let error = event["error"].as_str().unwrap_or_default(); assert!( - warning.contains("without reading any of those files") - && warning.contains("vex does not attest the patch"), + error.contains("the patch's files were written") + && error.contains("without reading any of those files") + && error.contains("vex does not attest the patch"), "{stdout}" ); + assert_eq!(event_files(&event), [PATCH_REL], "{stdout}"); assert_eq!(ruby.calls(), ["extensions_dir", "build"]); assert_tree(&proj.join("vendor"), &written, "after the apply"); assert!(!vex_attests(|args| ruby.run(&proj, args, &[]))); @@ -2015,12 +2274,13 @@ fn an_in_place_build_that_reads_nothing_of_the_patch_keeps_the_previous_build() /// empty extension dir, and the binary somewhere Ruby does not load from. /// Moving that dir in passed for a build of the patch: the run said /// "applied" and `vex` attested it while the code the gem runs was -/// byte-for-byte unchanged (#2144). The record's files are written (the -/// gem's own Ruby is what compiles such a binary later), the run says the -/// compiled code is not the patch's, and nothing attests the copy. +/// byte-for-byte unchanged (#2144). The record's files are written and +/// stay written (the gem's own Ruby is what compiles such a binary later), +/// the run fails with the patch incomplete and says that the compiled code +/// is not the patch's, and nothing attests the copy. #[cfg(unix)] #[test] -fn a_build_that_leaves_no_compiled_file_writes_the_patch_and_attests_nothing() { +fn a_build_that_leaves_no_compiled_file_writes_the_patch_and_fails_as_incomplete() { let (_tmp, proj, gem_dir, home) = built_gem_with_its_archive(); let (before, after) = (c_source(1), c_source(2)); write_record( @@ -2039,21 +2299,22 @@ fn a_build_that_leaves_no_compiled_file_writes_the_patch_and_attests_nothing() { ); let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); - assert_eq!(code, 0, "ruby ran {:?}\n{stdout}\n{stderr}", ruby.calls()); - assert_eq!(event_action(&stdout), "applied", "{stdout}"); - let warning = not_rebuilt_warning(&stdout); + assert_eq!(code, 1, "ruby ran {:?}\n{stdout}\n{stderr}", ruby.calls()); + let event = incomplete_event(&stdout, PURL); + let error = event["error"].as_str().unwrap_or_default(); for needle in [ "the patch's files were written", C_KEY, "left no compiled file", "vex does not attest the patch", ] { - assert!(warning.contains(needle), "no {needle:?} in {warning:?}"); + assert!(error.contains(needle), "no {needle:?} in {error:?}"); } assert!( - !warning.contains(" "), - "the message has a gap in it: {warning}" + !error.contains(" "), + "the message has a gap in it: {error}" ); + assert_eq!(event_files(&event), [C_KEY], "{stdout}"); assert_eq!( ruby.calls(), ["extensions_dir", "unpack", "missing_deps", "stage_build"] @@ -2070,6 +2331,15 @@ fn a_build_that_leaves_no_compiled_file_writes_the_patch_and_attests_nothing() { "vex attested a patch whose build installed nothing" ); + // A second run finds the source written and the patch as incomplete + // as it was: it fails again, and never reads as already patched. + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + let event = incomplete_event(&stdout, PURL); + assert_eq!(event_files(&event), Vec::::new(), "{stdout}"); + assert!(!stdout.contains("already_patched"), "{stdout}"); + assert_tree(&proj.join("vendor"), &written, "after a second apply"); + let (code, stdout, stderr) = ruby.run(&proj, &["rollback", "--json", "--offline"], &[]); assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); assert_tree(&proj.join("vendor"), &tree_before, "after rollback"); @@ -2817,77 +3087,1132 @@ fn a_ruby_of_another_platform_does_not_rebuild_a_precompiled_copy() { assert_tree(&proj.join("vendor"), &tree_before, ""); } -/// The JRuby build of a gem ships jars compiled from Java sources: nothing -/// here rebuilds them, so a record that changes one is refused with -/// nothing written, and a copy that holds the patched source anyway is -/// never reported as patched. Its Ruby files are patched as any gem's. -#[test] -fn a_java_gem_is_refused_and_never_attested() { - const JAVA_KEY: &str = "ext/java/sp/SpNative.java"; - let (before, after) = ( - "class SpNative { int v = 1; }\n", - "class SpNative { int v = 2; }\n", - ); - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().to_path_buf(); - let home = proj.join("vendor/bundle/jruby/3.4.0"); - let gem_dir = home.join("gems/sp_native-1.0.0-java"); - std::fs::create_dir_all(gem_dir.join("ext/java/sp")).unwrap(); - std::fs::create_dir_all(gem_dir.join("lib/sp_native")).unwrap(); - std::fs::write(gem_dir.join(JAVA_KEY), before).unwrap(); - std::fs::write(gem_dir.join("lib/sp_native.rb"), LIB_RB).unwrap(); - std::fs::write(gem_dir.join("lib/sp_native/sp_native.jar"), b"PK jar").unwrap(); - std::fs::create_dir_all(home.join("specifications")).unwrap(); - std::fs::write( - home.join("specifications/sp_native-1.0.0-java.gemspec"), - "Gem::Specification.new do |s|\n s.name = \"sp_native\".freeze\n \ - s.version = \"1.0.0\".freeze\n s.platform = \"java\".freeze\n \ - s.require_paths = [\"lib\".freeze]\nend\n", - ) - .unwrap(); - std::fs::write( - proj.join("Gemfile"), - "source \"https://rubygems.org\"\ngem \"sp_native\"\n", - ) - .unwrap(); - let socket = proj.join(".socket"); - write_record(&socket, PURL, &[(JAVA_KEY, Some(before), after)]); - let tree_before = walk_files(&proj.join("vendor")); +// ── the JRuby build of a gem ────────────────────────────────────────── +// +// JRuby installs a gem's `java` platform build, whose compiled code is +// jars. The patch records are written for the `ruby` platform gem, and +// such a copy takes of one what is part of its own build: the files it +// holds, and the files the patch adds that are not inputs of a C build. +// Nothing is built and no Ruby is started. Only a record that changes what +// the jars were built from (their sources, not a jar replaced whole) is +// never attested. A record qualified for a platform is applied whole, and +// a `java` gem that declares extensions is rebuilt like any built gem. + +/// The record of the `ruby` platform gem, as the patch service keys it. +const RUBY_PLATFORM_PURL: &str = "pkg:gem/sp_native@1.0.0?platform=ruby"; +/// A record written for the `java` platform gem itself. +const JAVA_PLATFORM_PURL: &str = "pkg:gem/sp_native@1.0.0?platform=java"; +const JAVA_KEY: &str = "ext/java/sp/SpNative.java"; +const JAVA_SOURCE: &str = "class SpNative { int v = 1; }\n"; +const PATCHED_JAVA_SOURCE: &str = "class SpNative { int v = 2; }\n"; +const PATCHED_RB: &str = "require \"sp_native/sp_native\"\n# patched\n"; +/// A patch to a library the `ruby` platform gem packs and compiles. +const LIBRARY_PATCH_KEY: &str = "patches/libxml2/0100-fix.patch"; + +/// A project with a hand-laid JRuby copy of `sp_native`: its Ruby file, +/// the jar it runs, the Java source of that jar, and the C source of the +/// `ruby` platform gem, which the `java` gem ships too and nothing on +/// JRuby compiles. It has no `patches/` dir. +struct JavaGem { + _tmp: tempfile::TempDir, + proj: PathBuf, + gem_dir: PathBuf, + /// The only `ruby` on the `PATH` the CLI is run with: it records every + /// call, and none may be made for a JRuby gem. + #[cfg(unix)] + ruby: FakeRuby, + /// `vendor/` as it was laid down. + pristine: Vec<(String, Vec)>, +} - for args in [&["apply", "--json"][..], &["apply", "--json", "--dry-run"]] { - let (code, stdout, stderr) = run_without_ruby(&proj, args); - assert_eq!(code, 1, "{args:?}: {stdout}\n{stderr}"); - assert!( - stdout.contains("native_extensions_unsupported") && stdout.contains("JRuby"), - "{args:?}: {stdout}" +impl JavaGem { + fn new() -> JavaGem { + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().to_path_buf(); + let home = proj.join("vendor/bundle/jruby/3.1.0"); + let gem_dir = home.join("gems/sp_native-1.0.0-java"); + for (rel, bytes) in [ + (JAVA_KEY, JAVA_SOURCE.as_bytes()), + (C_KEY, c_source(1).as_bytes()), + ("lib/sp_native.rb", LIB_RB.as_bytes()), + ("lib/sp_native/sp_native.jar", b"PK jar"), + ] { + let path = gem_dir.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write( + home.join("specifications/sp_native-1.0.0-java.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"sp_native\".freeze\n \ + s.version = \"1.0.0\".freeze\n s.platform = \"java\".freeze\n \ + s.require_paths = [\"lib\".freeze]\nend\n", + ) + .unwrap(); + std::fs::write( + proj.join("Gemfile"), + "source \"https://rubygems.org\"\ngem \"sp_native\"\n", + ) + .unwrap(); + let pristine = walk_files(&proj.join("vendor")); + JavaGem { + _tmp: tmp, + proj, + gem_dir, + #[cfg(unix)] + ruby: FakeRuby::new(), + pristine, + } + } + + fn record(&self, purl: &str, entries: &[RecordFile<'_>]) { + write_record(&self.proj.join(".socket"), purl, entries); + } + + fn run(&self, args: &[&str]) -> (i32, String, String) { + #[cfg(unix)] + let out = self.ruby.run(&self.proj, args, &[]); + #[cfg(not(unix))] + let out = run_without_ruby(&self.proj, args); + out + } + + fn read(&self, rel: &str) -> String { + std::fs::read_to_string(self.gem_dir.join(rel)).unwrap() + } + + /// The gem file `file` as [`walk_files`] of `vendor/` names it. + fn vendor_rel(&self, file: &str) -> String { + let mut path = self + .gem_dir + .strip_prefix(self.proj.join("vendor")) + .unwrap() + .to_path_buf(); + path.extend(file.split('/')); + path.display().to_string() + } + + /// The event of the gem's record in a `--json` run: its action and + /// reason code. + fn event(&self, stdout: &str, purl: &str) -> (String, String) { + let env = parse_json_envelope(stdout); + let event = common::envelope::event_for(&env, purl); + let field = |key: &str| event[key].as_str().unwrap_or_default().to_string(); + (field("action"), field("errorCode")) + } + + fn attested(&self) -> bool { + vex_attests(|args| self.run(args)) + } + + /// `vendor/` holds exactly the files of `expected`, and nothing of a + /// build: no marker, no backup, no stage. + fn assert_vendor(&self, expected: &[(String, Vec)], what: &str) { + assert_tree(&self.proj.join("vendor"), expected, what); + } + + /// `rollback` succeeds and leaves the install byte for byte as it was + /// laid down. + fn assert_rolls_back(&self) { + let (code, stdout, stderr) = self.run(&["rollback", "--json"]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + self.assert_vendor(&self.pristine, "after rollback"); + } + + /// No Ruby was started by any run so far. + fn assert_no_ruby_ran(&self) { + #[cfg(unix)] + assert_eq!( + self.ruby.calls(), + Vec::::new(), + "a Ruby was started for a JRuby gem" ); - assert_tree(&proj.join("vendor"), &tree_before, &format!("{args:?}")); } +} - // The patched source over the old jar is not a patched gem. - std::fs::write(gem_dir.join(JAVA_KEY), after).unwrap(); - let (code, stdout, _) = run_without_ruby(&proj, &["apply", "--check", "--json"]); - assert_ne!(code, 0, "{stdout}"); - assert!(stdout.contains("native_extension_not_rebuilt"), "{stdout}"); - assert!( - !vex_attests(|args| run_without_ruby(&proj, args)), - "vex attested a jar that was not rebuilt" +/// A patch with a Ruby half and a C half, on a JRuby gem that ships both +/// files: both are written (the C source is dead code there), the copy is +/// in sync and attested with no build and no marker, and `rollback` puts +/// every byte back. +#[test] +fn a_java_gem_takes_the_ruby_and_c_files_it_ships() { + let gem = JavaGem::new(); + let (c_before, c_after) = (c_source(1), c_source(2)); + gem.record( + RUBY_PLATFORM_PURL, + &[ + ("lib/sp_native.rb", Some(LIB_RB), PATCHED_RB), + (C_KEY, Some(&c_before), &c_after), + ], + ); + let patched = tree_with( + &tree_with( + &gem.pristine, + &gem.vendor_rel("lib/sp_native.rb"), + PATCHED_RB.as_bytes(), + ), + &gem.vendor_rel("ext/sp_native/sp_native.c"), + c_after.as_bytes(), ); - let (code, stdout, _) = run_without_ruby(&proj, &["apply", "--json"]); - assert_eq!(code, 1, "{stdout}"); - assert!(stdout.contains("native_extensions_unsupported"), "{stdout}"); - // A Ruby file of the same gem needs no build. - let patched_rb = "require \"sp_native/sp_native\"\n# patched\n"; - write_record( - &socket, - PURL, - &[("lib/sp_native.rb", Some(LIB_RB), patched_rb)], + let (code, stdout, _) = gem.run(&["apply", "--check", "--json"]); + assert_ne!(code, 0, "an unapplied patch must not check clean: {stdout}"); + assert!(!gem.attested(), "vex attested an unapplied patch"); + + let (code, stdout, stderr) = gem.run(&["apply", "--json", "--dry-run"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!( + gem.event(&stdout, RUBY_PLATFORM_PURL).0, + "verified", + "{stdout}" ); - let (code, stdout, stderr) = run_without_ruby(&proj, &["apply", "--json"]); + gem.assert_vendor(&gem.pristine, "after a dry run"); + + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!( + gem.event(&stdout, RUBY_PLATFORM_PURL).0, + "applied", + "{stdout}" + ); + let env = parse_json_envelope(&stdout); + let native: Vec = common::envelope::warning_codes(&env) + .into_iter() + .filter(|code| code.starts_with("native_extension")) + .collect(); + assert_eq!(native, Vec::::new(), "{stdout}"); + gem.assert_vendor(&patched, "after apply"); + + let (code, stdout, stderr) = gem.run(&["apply", "--check"]); + assert_eq!( + code, 0, + "the patched copy checks clean:\n{stdout}\n{stderr}" + ); + assert!(gem.attested(), "vex did not attest the patched copy"); + + // Idempotent: nothing left to write. + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); assert_eq!(code, 0, "{stdout}\n{stderr}"); - assert_eq!(event_action(&stdout), "applied", "{stdout}"); - assert!(vex_attests(|args| run_without_ruby(&proj, args))); + assert_eq!( + gem.event(&stdout, RUBY_PLATFORM_PURL), + ("skipped".to_string(), "already_patched".to_string()), + "{stdout}" + ); + gem.assert_vendor(&patched, "after a second apply"); + + gem.assert_rolls_back(); + gem.assert_no_ruby_ran(); +} + +/// A file the patch replaces that the JRuby gem does not ship, and a file +/// it adds that only a C build reads, are not part of that platform's gem: +/// neither is written or missed, and the patch is applied with the rest. +#[test] +fn a_java_gem_skips_the_files_it_has_no_use_for() { + for purl in [PURL, RUBY_PLATFORM_PURL] { + let gem = JavaGem::new(); + gem.record( + purl, + &[ + ("lib/sp_native.rb", Some(LIB_RB), PATCHED_RB), + ( + "ext/sp_native/only_in_the_ruby_gem.c", + Some("int before;\n"), + "int after;\n", + ), + (LIBRARY_PATCH_KEY, None, "a patch to the packed library\n"), + ("ext/sp_native/new_source.c", None, "int added;\n"), + // A Ruby file the patch adds is created as on any gem. + ( + "lib/sp_native/helper.rb", + None, + "module SpNativeHelper; end\n", + ), + ], + ); + let patched = tree_with( + &tree_with( + &gem.pristine, + &gem.vendor_rel("lib/sp_native.rb"), + PATCHED_RB.as_bytes(), + ), + &gem.vendor_rel("lib/sp_native/helper.rb"), + b"module SpNativeHelper; end\n", + ); + + let (code, stdout, _) = gem.run(&["apply", "--check", "--json"]); + assert_ne!(code, 0, "{purl}: {stdout}"); + + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 0, "{purl}: apply failed:\n{stdout}\n{stderr}"); + assert_eq!(gem.event(&stdout, purl).0, "applied", "{purl}: {stdout}"); + let env = parse_json_envelope(&stdout); + let mut written: Vec<&str> = common::envelope::event_for(&env, purl)["files"] + .as_array() + .unwrap() + .iter() + .filter_map(|file| file["path"].as_str()) + .collect(); + written.sort_unstable(); + assert_eq!( + written, + ["lib/sp_native.rb", "lib/sp_native/helper.rb"], + "{purl}" + ); + gem.assert_vendor(&patched, purl); + + let (code, stdout, stderr) = gem.run(&["apply", "--check"]); + assert_eq!(code, 0, "{purl}: {stdout}\n{stderr}"); + assert!( + gem.attested(), + "{purl}: vex did not attest the patched copy" + ); + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 0, "{purl}: {stdout}\n{stderr}"); + assert_eq!( + gem.event(&stdout, purl), + ("skipped".to_string(), "already_patched".to_string()), + "{purl}: {stdout}" + ); + + gem.assert_rolls_back(); + gem.assert_no_ruby_ran(); + } +} + +/// A patch that changes nothing but the C build (a new patch to a packed +/// library, a C source the JRuby gem does not ship) has no file in the +/// JRuby build: the run succeeds, writes nothing and says so, and the copy +/// is in sync and attested, because the code the patch fixes is not in it. +#[test] +fn a_patch_of_the_c_build_alone_has_nothing_to_do_on_a_java_gem() { + for purl in [PURL, RUBY_PLATFORM_PURL] { + let gem = JavaGem::new(); + gem.record( + purl, + &[ + (LIBRARY_PATCH_KEY, None, "a patch to the packed library\n"), + ( + "ext/sp_native/only_in_the_ruby_gem.c", + Some("int before;\n"), + "int after;\n", + ), + ], + ); + + for args in [&["apply", "--json", "--dry-run"][..], &["apply", "--json"]] { + let (code, stdout, stderr) = gem.run(args); + assert_eq!(code, 0, "{purl} {args:?}: {stdout}\n{stderr}"); + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "{purl} {args:?}: {stdout}"); + assert_eq!( + gem.event(&stdout, purl), + ("skipped".to_string(), "not_in_platform_build".to_string()), + "{purl} {args:?}: {stdout}" + ); + let reason = common::envelope::event_for(&env, purl)["reason"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + reason.contains("none of the patch's files are part of the JRuby build") + && reason.contains("sp_native-1.0.0-java"), + "{purl} {args:?}: {reason}" + ); + assert_eq!( + common::envelope::warning_codes(&env), + Vec::::new(), + "{purl} {args:?}: {stdout}" + ); + gem.assert_vendor(&gem.pristine, &format!("{purl} {args:?}")); + } + + // In plain words for a person, and counted in the summary. + let (code, stdout, stderr) = gem.run(&["apply"]); + assert_eq!(code, 0, "{purl}: {stdout}\n{stderr}"); + assert!( + stderr.contains("none of the patch's files are part of the JRuby build"), + "{purl}: {stderr}" + ); + assert!( + stdout.contains("0 of 1 targeted patch applied") && stdout.contains("1 not applicable"), + "{purl}: {stdout}" + ); + assert!(!stderr.contains("Error"), "{purl}: {stderr}"); + + let (code, stdout, stderr) = gem.run(&["apply", "--check"]); + assert_eq!(code, 0, "{purl}: {stdout}\n{stderr}"); + assert!(gem.attested(), "{purl}: vex did not attest the copy"); + gem.assert_vendor(&gem.pristine, purl); + + // The statement is truthful about why: nothing was patched here. + // The code is not in this build. + let document = vex_document(|args| gem.run(args)).expect("a vex document"); + let statement = &document["statements"][0]; + assert_eq!(statement["status"], "not_affected", "{document:#}"); + assert_eq!( + statement["justification"], "vulnerable_code_not_present", + "{purl}: {document:#}" + ); + let impact = statement["impact_statement"].as_str().unwrap_or_default(); + assert!( + impact.contains("is not in the installed build of the package") + && impact.contains(UUID) + && !impact.contains("Patched via"), + "{purl}: {impact}" + ); + + // `rollback` says what is true too: nothing of the patch was + // applied to this build, so there is nothing to restore. Not that + // the record lists no files. + for args in [ + &["rollback", "--json", "--dry-run"][..], + &["rollback", "--json"], + ] { + let (code, stdout, stderr) = gem.run(args); + assert_eq!(code, 0, "{purl} {args:?}:\n{stdout}\n{stderr}"); + let env = parse_json_envelope(&stdout); + let event = env["events"] + .as_array() + .into_iter() + .flatten() + .find(|e| e["purl"] == purl && e["action"] == "skipped") + .unwrap_or_else(|| panic!("{purl} {args:?}: no skip:\n{stdout}")); + assert_eq!( + event["errorCode"], "not_in_platform_build", + "{purl} {args:?}: {stdout}" + ); + assert!( + event["reason"] + .as_str() + .is_some_and(|reason| reason.contains("there is nothing to restore")), + "{purl} {args:?}: {stdout}" + ); + assert!(!stdout.contains("no_files"), "{purl} {args:?}: {stdout}"); + gem.assert_vendor(&gem.pristine, &format!("{purl} {args:?}")); + } + gem.assert_no_ruby_ran(); + } +} + +/// A Ruby file is part of every build of a gem. One that the patch +/// replaces and the JRuby copy does not hold (it was deleted) is the usual +/// missing file: the patch fails, and the copy is neither in sync nor +/// attested. It is never taken for a patch with nothing to do there. +#[test] +fn a_ruby_file_missing_from_a_java_gem_is_a_missing_file() { + for purl in [PURL, RUBY_PLATFORM_PURL] { + let gem = JavaGem::new(); + std::fs::remove_file(gem.gem_dir.join("lib/sp_native.rb")).unwrap(); + let without = walk_files(&gem.proj.join("vendor")); + gem.record(purl, &[("lib/sp_native.rb", Some(LIB_RB), PATCHED_RB)]); + + for args in [&["apply", "--json"][..], &["apply", "--json", "--dry-run"]] { + let (code, stdout, stderr) = gem.run(args); + assert_eq!(code, 1, "{purl} {args:?}: {stdout}\n{stderr}"); + assert!( + !stdout.contains("not_in_platform_build"), + "{purl} {args:?}: {stdout}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["summary"]["applied"], 0, "{purl} {args:?}: {stdout}"); + gem.assert_vendor(&without, &format!("{purl} {args:?}")); + } + let (_, stdout, _) = gem.run(&["apply", "--json"]); + let env = parse_json_envelope(&stdout); + let event = common::envelope::event_for(&env, purl); + if purl == PURL { + // The unqualified record reaches the apply, which names the file. + assert_eq!(event["action"], "failed", "{stdout}"); + assert!( + event["error"].as_str().is_some_and( + |e| e.contains("lib/sp_native.rb") && e.contains("File not found") + ), + "{stdout}" + ); + } else { + // A qualified record is matched to a copy by the files it + // replaces: with its one file gone, the copy is not one this + // record can be told to belong to. + assert_eq!(event["errorCode"], "package_not_installed", "{stdout}"); + } + let (code, stdout, _) = gem.run(&["apply", "--check", "--json"]); + assert_ne!(code, 0, "{purl}: {stdout}"); + assert!(!gem.attested(), "{purl}: vex attested a missing file"); + gem.assert_no_ruby_ran(); + } +} + +/// A record that brings the compiled code is the patch, whatever source +/// it changes beside it: the record written for the `java` gem itself (the +/// rebuilt jar and the source it was rebuilt from, or the gem's own diff +/// of a source), and a ruby-platform record that replaces the jar. Its +/// files are written, the copy is in sync and attested, and a second run +/// has nothing to do. It is not held up as a patch whose jars were not +/// rebuilt. +#[test] +fn a_record_that_brings_the_jar_is_not_held_up_by_its_source() { + const JAR_KEY: &str = "lib/sp_native/sp_native.jar"; + let jar: RecordFile<'_> = (JAR_KEY, Some("PK jar"), "PK patched jar"); + let source: RecordFile<'_> = (JAVA_KEY, Some(JAVA_SOURCE), PATCHED_JAVA_SOURCE); + let cases: [(&str, &str, &[RecordFile<'_>]); 3] = [ + ( + "the java gem's jar and source", + JAVA_PLATFORM_PURL, + &[jar, source], + ), + ("the java gem's own source", JAVA_PLATFORM_PURL, &[source]), + ( + "a ruby record with the jar", + RUBY_PLATFORM_PURL, + &[jar, source], + ), + ]; + for (case, purl, entries) in cases { + let gem = JavaGem::new(); + gem.record(purl, entries); + let mut patched = gem.pristine.clone(); + for (key, _, after) in entries { + patched = tree_with(&patched, &gem.vendor_rel(key), after.as_bytes()); + } + + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 0, "{case}: apply failed:\n{stdout}\n{stderr}"); + assert_eq!(gem.event(&stdout, purl).0, "applied", "{case}: {stdout}"); + assert!( + !stdout.contains("native_extension"), + "{case}: the record brings its compiled code: {stdout}" + ); + gem.assert_vendor(&patched, case); + + let (code, stdout, stderr) = gem.run(&["apply", "--check"]); + assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); + assert!(gem.attested(), "{case}: vex did not attest the patch"); + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); + assert_eq!( + gem.event(&stdout, purl), + ("skipped".to_string(), "already_patched".to_string()), + "{case}: {stdout}" + ); + + gem.assert_rolls_back(); + gem.assert_no_ruby_ran(); + } +} + +/// With a record for the copy's own platform in the manifest, that record +/// is the copy's, and the ruby-platform record of the same version is not +/// the copy's for any reader: `apply` does not apply it there and reports +/// it as not installed, `apply --check` does not count it as in sync, and +/// `vex` does not attest it. +#[test] +fn the_copys_own_record_is_its_only_record_for_every_reader() { + const JAR_KEY: &str = "lib/sp_native/sp_native.jar"; + const OWN_UUID: &str = "29962996-2996-4996-8996-299629962996"; + let gem = JavaGem::new(); + let socket = gem.proj.join(".socket"); + let record = |uuid: &str, key: &str, before: Option<&str>, after: &str| { + let before_hash = before.map(|b| git_sha256(b.as_bytes())).unwrap_or_default(); + if let Some(before) = before { + write_blob(&socket, &before_hash, before.as_bytes()); + } + write_blob(&socket, &git_sha256(after.as_bytes()), after.as_bytes()); + serde_json::json!({ + "uuid": uuid, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { key: { + "beforeHash": before_hash, + "afterHash": git_sha256(after.as_bytes()), + }}, + "vulnerabilities": { "GHSA-aaaa-bbbb-cccc": { + "cves": ["CVE-2026-0001"], "summary": "s", "severity": "HIGH", + "description": "d", + }}, + "description": "synthetic test patch", + "license": "MIT", + "tier": "free", + }) + }; + std::fs::create_dir_all(&socket).unwrap(); + let manifest = serde_json::json!({ "patches": { + RUBY_PLATFORM_PURL: record(UUID, LIBRARY_PATCH_KEY, None, "a patch to the packed library\n"), + JAVA_PLATFORM_PURL: record(OWN_UUID, JAR_KEY, Some("PK jar"), "PK patched jar"), + }}); + std::fs::write( + socket.join("manifest.json"), + serde_json::to_string_pretty(&manifest).unwrap(), + ) + .unwrap(); + let patched = tree_with(&gem.pristine, &gem.vendor_rel(JAR_KEY), b"PK patched jar"); + + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!( + gem.event(&stdout, JAVA_PLATFORM_PURL).0, + "applied", + "{stdout}" + ); + assert_eq!( + gem.event(&stdout, RUBY_PLATFORM_PURL), + ("skipped".to_string(), "package_not_installed".to_string()), + "{stdout}" + ); + gem.assert_vendor(&patched, "after apply"); + + // `apply --check`: the copy's record is in sync, and the ruby record + // is no patch of this copy, exactly as `apply` reported it. + let (code, stdout, stderr) = gem.run(&["apply", "--check", "--json"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!( + gem.event(&stdout, JAVA_PLATFORM_PURL), + ("skipped".to_string(), "already_patched".to_string()), + "{stdout}" + ); + assert_eq!( + gem.event(&stdout, RUBY_PLATFORM_PURL), + ("skipped".to_string(), "package_not_installed".to_string()), + "{stdout}" + ); + + // `vex` attests the copy's record, and not the ruby one. + let document = vex_document(|args| gem.run(args)).expect("a vex document"); + assert_eq!( + vex_subcomponents(&document), + [JAVA_PLATFORM_PURL], + "{document:#}" + ); + let impact = document["statements"][0]["impact_statement"] + .as_str() + .unwrap_or_default(); + assert!( + impact.contains(OWN_UUID) && !impact.contains(UUID), + "{impact}" + ); + gem.assert_no_ruby_ran(); +} + +/// A package with one copy that applied and one whose patch is incomplete +/// is not in effect: the run fails, each copy has its own event, and the +/// package is neither listed as patched nor counted as applied. +#[test] +fn a_package_with_a_patched_and_an_incomplete_copy_is_not_in_effect() { + let gem = JavaGem::new(); + // The same gem as a plain `ruby` platform install in another store of + // the project: no extension, no jar, so the record is plain files. + let home = gem.proj.join("vendor/bundle/ruby/3.4.0"); + let plain = home.join("gems").join(FULL_NAME); + for (rel, bytes) in [ + (JAVA_KEY, JAVA_SOURCE.as_bytes()), + ("lib/sp_native.rb", LIB_RB.as_bytes()), + ] { + let path = plain.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write( + home.join("specifications") + .join(format!("{FULL_NAME}.gemspec")), + "Gem::Specification.new do |s|\n s.name = \"sp_native\".freeze\n \ + s.version = \"1.0.0\".freeze\n s.require_paths = [\"lib\".freeze]\nend\n", + ) + .unwrap(); + gem.record( + PURL, + &[ + (JAVA_KEY, Some(JAVA_SOURCE), PATCHED_JAVA_SOURCE), + ("lib/sp_native.rb", Some(LIB_RB), PATCHED_RB), + ], + ); + + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "partialFailure", "{stdout}"); + let mut actions: Vec<(String, String)> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["purl"] == PURL) + .map(|e| { + let field = |key: &str| e[key].as_str().unwrap_or_default().to_string(); + (field("action"), field("errorCode")) + }) + .collect(); + actions.sort(); + assert_eq!( + actions, + [ + ("applied".to_string(), String::new()), + ( + "failed".to_string(), + "native_extension_not_rebuilt".to_string() + ), + ], + "each copy has its own event: {stdout}" + ); + // Both copies hold the patch's files. + for dir in [&plain, &gem.gem_dir] { + assert_eq!( + std::fs::read_to_string(dir.join("lib/sp_native.rb")).unwrap(), + PATCHED_RB, + "{}", + dir.display() + ); + } + + // A second run: one copy already patched, one still incomplete. The + // package is not in effect, and never listed or counted as patched. + let (code, stdout, stderr) = gem.run(&["apply"]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert_eq!( + stderr + .matches(&format!("Error: Patch of {PURL} is incomplete:")) + .count(), + 1, + "{stderr}" + ); + assert!(!stdout.contains("Patched packages:"), "{stdout}"); + assert!( + stdout.contains("0 of 1 targeted patch applied, 0 already patched, 1 not in effect"), + "{stdout}" + ); + let (code, stdout, _) = gem.run(&["apply", "--check", "--json"]); + assert_ne!(code, 0, "{stdout}"); + assert!( + !gem.attested(), + "vex attested a package that is not in effect" + ); + gem.assert_no_ruby_ran(); +} + +/// The jars a JRuby gem runs were built from its Java sources, and nothing +/// here rebuilds a jar: a patch that changes one has its files written and +/// is incomplete. The run fails (exit 1) and says that the jars are not +/// the patch's, the files stay written, and neither `apply --check` nor +/// `vex` ever takes the copy for patched. `rollback` restores the tree. +#[test] +fn a_patch_to_a_java_gems_sources_is_written_and_fails_as_incomplete() { + let jars_not_rebuilt = "the gem's jars were built from Java sources the patch changes"; + for purl in [PURL, RUBY_PLATFORM_PURL] { + let gem = JavaGem::new(); + gem.record( + purl, + &[ + (JAVA_KEY, Some(JAVA_SOURCE), PATCHED_JAVA_SOURCE), + ("lib/sp_native.rb", Some(LIB_RB), PATCHED_RB), + (LIBRARY_PATCH_KEY, None, "a patch to the packed library\n"), + ], + ); + let patched = tree_with( + &tree_with( + &gem.pristine, + &gem.vendor_rel("lib/sp_native.rb"), + PATCHED_RB.as_bytes(), + ), + &gem.vendor_rel("ext/java/sp/SpNative.java"), + PATCHED_JAVA_SOURCE.as_bytes(), + ); + + // Files alone show what a real run comes to, so a dry run fails + // the same way, says what apply would leave undone, and writes + // nothing. + let (code, stdout, stderr) = gem.run(&["apply", "--json", "--dry-run"]); + assert_eq!(code, 1, "{purl}: {stdout}\n{stderr}"); + let event = incomplete_event(&stdout, purl); + let error = event["error"].as_str().unwrap_or_default(); + assert!( + error.starts_with("dry run: apply would write the patch's files") + && error.contains(jars_not_rebuilt), + "{purl}: {stdout}" + ); + assert_eq!(event_files(&event), Vec::::new(), "{purl}"); + gem.assert_vendor(&gem.pristine, &format!("{purl} after a dry run")); + + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 1, "{purl}: {stdout}\n{stderr}"); + let event = incomplete_event(&stdout, purl); + let error = event["error"].as_str().unwrap_or_default(); + assert!( + error.starts_with("the patch's files were written") + && error.contains(jars_not_rebuilt) + && error.contains(JAVA_KEY), + "{purl}: {stdout}" + ); + // The files it takes are written and stay written. + assert_eq!( + event_files(&event), + [JAVA_KEY, "lib/sp_native.rb"], + "{purl}: {stdout}" + ); + gem.assert_vendor(&patched, purl); + assert_eq!(gem.read("lib/sp_native/sp_native.jar"), "PK jar"); + + // The patched source beside the old jar is not a patched gem. + let (code, stdout, _) = gem.run(&["apply", "--check", "--json"]); + assert_ne!(code, 0, "{purl}: {stdout}"); + assert!( + stdout.contains("native_extension_not_rebuilt"), + "{purl}: {stdout}" + ); + assert!( + !gem.attested(), + "{purl}: vex attested a jar that was not rebuilt" + ); + + // A second run has nothing to write, and the patch is as + // incomplete as it was. + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 1, "{purl}: {stdout}\n{stderr}"); + let event = incomplete_event(&stdout, purl); + assert_eq!(event_files(&event), Vec::::new(), "{purl}"); + assert!(!stdout.contains("already_patched"), "{purl}: {stdout}"); + gem.assert_vendor(&patched, &format!("{purl} after a second apply")); + + gem.assert_rolls_back(); + gem.assert_no_ruby_ran(); + } + + // A Java source the gem does not even ship: nothing to write, and the + // jar may still hold the code, so the patch is incomplete as well. + let gem = JavaGem::new(); + gem.record( + RUBY_PLATFORM_PURL, + &[( + "ext/java/sp/NotShipped.java", + Some("class NotShipped { int v = 1; }\n"), + "class NotShipped { int v = 2; }\n", + )], + ); + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + let event = incomplete_event(&stdout, RUBY_PLATFORM_PURL); + let error = event["error"].as_str().unwrap_or_default(); + assert!( + error.contains(jars_not_rebuilt) && error.contains("Nothing was written"), + "{stdout}" + ); + assert_eq!(event_files(&event), Vec::::new(), "{stdout}"); + gem.assert_vendor(&gem.pristine, "a record of a Java source it does not ship"); + // For a person: one error line, and a summary that does not read as + // done. + let (code, stdout, stderr) = gem.run(&["apply"]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!( + stderr.contains(&format!( + "Error: Patch of {RUBY_PLATFORM_PURL} is incomplete:" + )) && stderr.contains(jars_not_rebuilt), + "{stderr}" + ); + assert_eq!(stderr.matches(jars_not_rebuilt).count(), 1, "{stderr}"); + assert!( + stdout.contains("1 not in effect") && !stdout.contains("not applicable"), + "{stdout}" + ); + let (code, stdout, _) = gem.run(&["apply", "--check", "--json"]); + assert_ne!(code, 0, "{stdout}"); + assert!(!gem.attested(), "vex attested a jar that was not rebuilt"); + gem.assert_rolls_back(); + gem.assert_no_ruby_ran(); +} + +/// `--no-gem-native-rebuild` leaves compiling to the caller, on JRuby as +/// anywhere: a patch to a Java source the gem ships is written, the run +/// succeeds with the `native_extension_not_rebuilt` warning that names the +/// flag, and nothing attests the copy until the caller's build is one +/// `apply` knows of. +#[test] +fn the_opt_out_leaves_a_java_gems_jars_to_the_caller() { + let gem = JavaGem::new(); + gem.record( + RUBY_PLATFORM_PURL, + &[ + (JAVA_KEY, Some(JAVA_SOURCE), PATCHED_JAVA_SOURCE), + ("lib/sp_native.rb", Some(LIB_RB), PATCHED_RB), + ], + ); + let patched = tree_with( + &tree_with( + &gem.pristine, + &gem.vendor_rel("lib/sp_native.rb"), + PATCHED_RB.as_bytes(), + ), + &gem.vendor_rel("ext/java/sp/SpNative.java"), + PATCHED_JAVA_SOURCE.as_bytes(), + ); + // A dry run writes nothing, and says what apply would do. + let (code, stdout, stderr) = + gem.run(&["apply", "--json", "--dry-run", "--no-gem-native-rebuild"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + let warning = not_rebuilt_warning(&stdout); + assert!( + warning.contains("dry run") + && warning.contains("apply would write them without rebuilding the jars") + && warning.contains("(--no-gem-native-rebuild)") + && !warning.contains(", written "), + "{warning}" + ); + gem.assert_vendor(&gem.pristine, "after a dry run with the opt-out"); + + let (code, stdout, stderr) = gem.run(&["apply", "--json", "--no-gem-native-rebuild"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!( + gem.event(&stdout, RUBY_PLATFORM_PURL).0, + "applied", + "{stdout}" + ); + let warning = not_rebuilt_warning(&stdout); + assert!( + warning.contains("written without rebuilding them (--no-gem-native-rebuild)") + && warning.contains(JAVA_KEY), + "{stdout}" + ); + gem.assert_vendor(&patched, "with the opt-out"); + let (code, stdout, _) = gem.run(&["apply", "--check", "--json"]); + assert_ne!(code, 0, "{stdout}"); + assert!(!gem.attested(), "vex attested a jar that was not rebuilt"); + gem.assert_rolls_back(); + gem.assert_no_ruby_ran(); +} + +/// A jar the record replaces whole is the code JRuby loads: it is written +/// like any file of the patch, with no warning, and the copy is in sync +/// and attested. Only the sources of a jar cannot take effect here. +#[test] +fn a_jar_the_patch_replaces_whole_is_written_and_attested() { + const JAR_KEY: &str = "lib/sp_native/sp_native.jar"; + for purl in [PURL, RUBY_PLATFORM_PURL] { + let gem = JavaGem::new(); + gem.record( + purl, + &[ + (JAR_KEY, Some("PK jar"), "PK patched jar"), + ("lib/sp_native.rb", Some(LIB_RB), PATCHED_RB), + ], + ); + let patched = tree_with( + &tree_with( + &gem.pristine, + &gem.vendor_rel("lib/sp_native.rb"), + PATCHED_RB.as_bytes(), + ), + &gem.vendor_rel(JAR_KEY), + b"PK patched jar", + ); + + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 0, "{purl}: apply failed:\n{stdout}\n{stderr}"); + assert_eq!(gem.event(&stdout, purl).0, "applied", "{purl}: {stdout}"); + assert!( + !stdout.contains("native_extension"), + "{purl}: a replaced jar is no build input: {stdout}" + ); + gem.assert_vendor(&patched, purl); + + let (code, stdout, stderr) = gem.run(&["apply", "--check"]); + assert_eq!(code, 0, "{purl}: {stdout}\n{stderr}"); + assert!(gem.attested(), "{purl}: vex did not attest the patched jar"); + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 0, "{purl}: {stdout}\n{stderr}"); + assert_eq!( + gem.event(&stdout, purl), + ("skipped".to_string(), "already_patched".to_string()), + "{purl}: {stdout}" + ); + + gem.assert_rolls_back(); + gem.assert_no_ruby_ran(); + } +} + +/// The per-file rule is for the record of the `ruby` platform gem. A +/// record qualified for a platform names the archive it was written for, +/// the copy's own `java` included: every file of it is required, so a file +/// the copy lacks fails the patch like any missing file, and a file it +/// adds is created wherever it goes. +#[test] +fn a_record_qualified_for_a_platform_is_applied_whole_on_a_java_gem() { + // A file the copy does not hold: the usual failure, nothing written. + for purl in [ + JAVA_PLATFORM_PURL, + "pkg:gem/sp_native@1.0.0?platform=x86_64-linux", + ] { + let gem = JavaGem::new(); + gem.record( + purl, + &[ + ("lib/sp_native.rb", Some(LIB_RB), PATCHED_RB), + ( + "lib/sp_native/zz_not_in_this_gem.rb", + Some("before\n"), + "after\n", + ), + ], + ); + for args in [&["apply", "--json"][..], &["apply", "--json", "--dry-run"]] { + let (code, stdout, stderr) = gem.run(args); + assert_eq!(code, 1, "{purl} {args:?}: {stdout}\n{stderr}"); + assert_eq!(gem.event(&stdout, purl).0, "failed", "{purl}: {stdout}"); + assert!( + stdout.contains("zz_not_in_this_gem.rb"), + "{purl} {args:?}: the missing file is named: {stdout}" + ); + gem.assert_vendor(&gem.pristine, &format!("{purl} {args:?}")); + } + let (code, stdout, _) = gem.run(&["apply", "--check", "--json"]); + assert_ne!(code, 0, "{purl}: {stdout}"); + assert!(!gem.attested(), "{purl}: vex attested a failed patch"); + gem.assert_no_ruby_ran(); + } + + // A file it adds under `patches/` is part of that record's gem. + let gem = JavaGem::new(); + gem.record( + JAVA_PLATFORM_PURL, + &[ + ("lib/sp_native.rb", Some(LIB_RB), PATCHED_RB), + (LIBRARY_PATCH_KEY, None, "a file of the java gem's record\n"), + ], + ); + let patched = tree_with( + &tree_with( + &gem.pristine, + &gem.vendor_rel("lib/sp_native.rb"), + PATCHED_RB.as_bytes(), + ), + &gem.vendor_rel(LIBRARY_PATCH_KEY), + b"a file of the java gem's record\n", + ); + let (code, stdout, stderr) = gem.run(&["apply", "--json"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!( + gem.event(&stdout, JAVA_PLATFORM_PURL).0, + "applied", + "{stdout}" + ); + gem.assert_vendor(&patched, "the java record"); + let (code, stdout, stderr) = gem.run(&["apply", "--check"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(gem.attested(), "vex did not attest the java record"); + gem.assert_rolls_back(); + gem.assert_no_ruby_ran(); +} + +/// A `java` gem whose gemspec declares extensions is no JRuby build of a +/// gem in this sense: RubyGems compiled something for it when it was +/// installed (jruby-launcher builds a native launcher), so a patch to that +/// source is rebuilt like any built gem's. Without a Ruby it is refused +/// with nothing written; it is never written and attested without a build. +#[cfg(unix)] +#[test] +fn a_java_gem_that_declares_extensions_keeps_the_native_rebuild() { + const BUILT_JAVA: &str = "sp_native-1.0.0-java"; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().to_path_buf(); + let home = proj.join("vendor/bundle/jruby/3.4.0"); + let gem_dir = home.join("gems").join(BUILT_JAVA); + std::fs::create_dir_all(gem_dir.join("ext/sp_native")).unwrap(); + std::fs::create_dir_all(gem_dir.join("lib/sp_native")).unwrap(); + std::fs::write(gem_dir.join(C_KEY), c_source(1)).unwrap(); + std::fs::write(gem_dir.join("lib/sp_native.rb"), LIB_RB).unwrap(); + std::fs::write( + gem_dir.join("lib/sp_native/sp_native.so"), + b"\x7fELF original", + ) + .unwrap(); + let ext = home.join("extensions/x86_64-linux/3.4.0").join(BUILT_JAVA); + std::fs::create_dir_all(ext.join("sp_native")).unwrap(); + std::fs::write(ext.join("sp_native/sp_native.so"), b"\x7fELF original").unwrap(); + std::fs::write(ext.join("gem.build_complete"), b"").unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write( + home.join("specifications") + .join(format!("{BUILT_JAVA}.gemspec")), + "Gem::Specification.new do |s|\n s.name = \"sp_native\".freeze\n \ + s.version = \"1.0.0\".freeze\n s.platform = \"java\".freeze\n \ + s.require_paths = [\"lib\".freeze]\n \ + s.extensions = [\"ext/sp_native/extconf.rb\".freeze]\nend\n", + ) + .unwrap(); + std::fs::write( + proj.join("Gemfile"), + "source \"https://rubygems.org\"\ngem \"sp_native\"\n", + ) + .unwrap(); + write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + let tree_before = walk_files(&proj.join("vendor")); + + // No Ruby to build with: refused, and nothing is written. + let (code, stdout, stderr) = run_without_ruby(&proj, &["apply", "--json"]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!(stdout.contains("native_extensions_unsupported"), "{stdout}"); + assert_tree(&proj.join("vendor"), &tree_before, "without a Ruby"); + let (code, stdout, _) = run_without_ruby(&proj, &["apply", "--check", "--json"]); + assert_ne!(code, 0, "{stdout}"); + + // With the Ruby that owns the install: built by RubyGems' builder. + let ruby = FakeRuby::new(); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json"], &[]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "applied", "{stdout}"); + assert_eq!(ruby.calls(), ["extensions_dir", "build"]); + assert_eq!( + std::fs::read_to_string(gem_dir.join(C_KEY)).unwrap(), + c_source(2) + ); + assert_eq!( + std::fs::read(gem_dir.join("lib/sp_native/sp_native.so")).unwrap(), + b"rebuilt" + ); + assert!(gem_dir.join(".socket-patch-native-build.json").is_file()); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--check"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + + // The patched source over the install-time build is not a patched gem. + let (code, stdout, stderr) = ruby.run(&proj, &["rollback", "--json"], &[]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_tree(&proj.join("vendor"), &tree_before, "after rollback"); + write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + std::fs::write(gem_dir.join(C_KEY), c_source(2)).unwrap(); + let (code, stdout, _) = run_without_ruby(&proj, &["apply", "--check", "--json"]); + assert_ne!(code, 0, "{stdout}"); + assert!(stdout.contains("native_extension_not_rebuilt"), "{stdout}"); +} + +/// A file the JRuby gem ships is held to the record like any patch file: +/// content that is neither the record's original nor its patched bytes +/// fails the patch, and nothing of it is written. +#[test] +fn a_mismatching_file_of_a_java_gem_still_fails() { + for purl in [PURL, RUBY_PLATFORM_PURL] { + let gem = JavaGem::new(); + std::fs::write(gem.gem_dir.join(C_KEY), c_source(7)).unwrap(); + let modified = walk_files(&gem.proj.join("vendor")); + let (c_before, c_after) = (c_source(1), c_source(2)); + gem.record( + purl, + &[ + ("lib/sp_native.rb", Some(LIB_RB), PATCHED_RB), + (C_KEY, Some(&c_before), &c_after), + (LIBRARY_PATCH_KEY, None, "a patch to the packed library\n"), + ], + ); + + for args in [&["apply", "--json"][..], &["apply", "--json", "--dry-run"]] { + let (code, stdout, stderr) = gem.run(args); + assert_eq!(code, 1, "{purl} {args:?}: {stdout}\n{stderr}"); + assert!( + !stdout.contains("native_extension"), + "{purl} {args:?}: a mismatch is no build refusal: {stdout}" + ); + gem.assert_vendor(&modified, &format!("{purl} {args:?}")); + } + let (code, stdout, _) = gem.run(&["apply", "--check", "--json"]); + assert_ne!(code, 0, "{purl}: {stdout}"); + assert!(!gem.attested(), "{purl}: vex attested a mismatching copy"); + gem.assert_no_ruby_ran(); + } } // ── the capstones: a real build from a real source gem ──────────────── diff --git a/crates/socket-patch-core/src/patch/apply.rs b/crates/socket-patch-core/src/patch/apply.rs index b24ea4874..06bffd0a9 100644 --- a/crates/socket-patch-core/src/patch/apply.rs +++ b/crates/socket-patch-core/src/patch/apply.rs @@ -361,6 +361,11 @@ pub async fn verify_file_patch( /// this naturally yields ≤1 index and their behavior is unchanged. The /// narrow download filter (scan/get) and the rollback dedupe share this /// helper so release selection stays consistent with apply. +/// +/// One more rule for gems, which every reader shares through this +/// function: a platform gem's copy takes the record written for its own +/// platform alone, when that record matches it +/// ([`own_platform_alone`]). pub async fn select_installed_variants( pkg_path: &Path, variants: &[(&str, &HashMap)], @@ -371,7 +376,39 @@ pub async fn select_installed_variants( matched.push(idx); } } - matched + own_platform_alone(pkg_path, variants, matched).await +} + +/// Of the variants `matched` to the gem copy at `pkg_path`, the one written +/// for the copy's own platform alone, when there is one +/// ([`own_platform_record`](crate::patch::gem_ext::own_platform_record)). +/// The ruby-platform record of the same version can match a platform +/// gem's copy too (its sources are what the copy's binary was built from; +/// on a JRuby copy it may take no file at all), and it is not that copy's +/// record: `apply` does not apply it there, so `apply --check`, `vex` and +/// `rollback` do not judge it there either. Any other selection is +/// returned as it is. +async fn own_platform_alone( + pkg_path: &Path, + variants: &[(&str, &HashMap)], + matched: Vec, +) -> Vec { + use crate::crawlers::types::Ecosystem; + let gems = matched.len() > 1 + && matched + .iter() + .all(|&idx| Ecosystem::from_purl(variants[idx].0) == Some(Ecosystem::Gem)); + if !gems { + return matched; + } + let keys = matched.iter().map(|&idx| variants[idx].0); + match crate::patch::gem_ext::own_platform_record(pkg_path, keys).await { + Some(own) => matched + .into_iter() + .filter(|&idx| variants[idx].0 == own) + .collect(), + None => matched, + } } /// [`select_installed_variants`] over every copy in `pkg_paths`: a variant @@ -381,6 +418,19 @@ pub async fn select_installed_variants_any( pkg_paths: &[std::path::PathBuf], variants: &[(&str, &HashMap)], ) -> Vec { + use crate::crawlers::types::Ecosystem; + // Gem copies are selected one by one, so that each takes its own + // platform's record alone. + if variants + .iter() + .any(|(key, _)| Ecosystem::from_purl(key) == Some(Ecosystem::Gem)) + { + let mut matched = std::collections::BTreeSet::new(); + for pkg_path in pkg_paths { + matched.extend(select_installed_variants(pkg_path, variants).await); + } + return matched.into_iter().collect(); + } let mut matched = Vec::new(); for (idx, (key, files)) in variants.iter().enumerate() { for pkg_path in pkg_paths { diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 4688c1a16..2b4975d0e 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -43,9 +43,8 @@ //! to try; a gem RubyGems built must have its extension dir on disk; a //! precompiled one must have a way to its source gem (the cached //! archive, or a run that may download it). Otherwise the purl is -//! refused with [`UNSUPPORTED_CODE`] and nothing is written. So is the -//! JRuby build of a gem, whose jars no source gem's build scripts -//! produce. +//! refused with [`UNSUPPORTED_CODE`] and nothing is written. (The JRuby +//! build of a gem never gets here: see "The JVM build of a gem".) //! 2. The record's files are verified against the copy, and the Ruby that //! owns the install is found (or the purl is refused as in 1). //! 3. The source gem is unpacked into a stage inside the gem home @@ -104,9 +103,12 @@ //! downloads the binary it runs (passenger's agent) has nothing a build //! could put where Ruby loads it. Either way the record's files are //! written, the compiled code stays what it was, no marker is written, and -//! the run warns with [`NOT_REBUILT_REASON`] (`Job::write_without_build`): -//! the patch's Ruby files are in effect, a source the gem compiles later on -//! its own is the patched one, and nothing attests the copy. +//! the patch is incomplete ([`GemCaveat::Incomplete`], +//! `Job::write_without_build`): the patch's Ruby files are in effect, a +//! source the gem compiles later on its own is the patched one, and +//! nothing attests the copy. The result is not a failed one, so nothing is +//! put back; the caller fails the run on the caveat and warns with +//! [`NOT_REBUILT_REASON`]. //! //! A build can take many minutes. The run says when one starts and when //! it ends ([`RubyEnv::progress`]). @@ -123,6 +125,56 @@ //! original build back ([`restore_original_build`]), prebuilt binaries //! byte for byte. //! +//! # The JVM build of a gem +//! +//! JRuby installs a gem's `java` platform build (`nokogiri-1.18.10-java`), +//! whose compiled code is jars. It builds no C extension, so nothing above +//! applies to it: no Ruby is started, nothing is built and no marker is +//! written. (A `java` gem whose gemspec declares extensions is not such a +//! build: RubyGems compiles something for it at install time, and it is +//! rebuilt like any gem RubyGems built.) The records are written for the +//! `ruby` platform gem, and such a copy takes of one what is part of its +//! own build (`jvm_takes`): +//! +//! * An input of a C build by its path (under `ext/`, `patches/`, +//! `ports/`, or a source or build file by name) is the one kind of file +//! that can be left out, since it means nothing to a gem with no C +//! build. One the record replaces is verified and written when the copy +//! holds it (a C source the JVM build ships anyway: dead code there), +//! and skipped when it does not. One the record adds is skipped. +//! * Every other file is taken like any patch file: a Ruby file the +//! record replaces must be there (one that is missing is the usual +//! failure, never a patch with nothing to do), and a file it adds is +//! created. +//! +//! With its applicable files written the record is applied: `apply +//! --check` and `vex` judge the copy by those files alone +//! ([`installed_files`]), and `rollback` undoes those. A record none of +//! whose files is part of the build changes code that is not in it: the +//! run writes nothing, says so ([`NOT_IN_BUILD_CODE`]) and succeeds, and +//! the copy counts as patched. It is the rule Socket's backend follows +//! when it builds a patched `java` platform gem, so a copy patched in +//! place holds the same files as one installed from that gem. +//! +//! That rule is for the ruby-platform record alone (no `platform` +//! qualifier, or `ruby`). A record qualified for a platform names the +//! archive it was written for: every file of it is required, and one the +//! copy lacks is the usual missing file. When the manifest holds a record +//! for the copy's own platform that matches it, that record alone is the +//! copy's, for every reader ([`own_platform_record`]). +//! +//! The one thing that cannot be done here is rebuild a jar. A +//! ruby-platform record that changes a JVM build input +//! (`is_jvm_build_input`: a Java, Kotlin or Scala source, a Maven, Ant or +//! Gradle build file) and brings no compiled code has its files written +//! and nothing built, the patch is incomplete +//! ([`GemCaveat::Incomplete`], with the [`NOT_REBUILT_REASON`] warning), +//! and nothing ever attests the copy ([`verify_native_build`]). A record +//! that replaces or adds a jar or a class file carries the code the JVM +//! loads, and the record written for the copy's own platform is the +//! `java` gem's own diff: neither is held up by a source it also changes +//! (`jvm_unbuilt_inputs`). +//! //! # What is executed, and when //! //! A gem tree can be supplied by the repository being scanned (a committed @@ -244,6 +296,11 @@ pub const RESTORE_FAILED_CODE: &str = "native_extension_restore_failed"; /// The `vex` / `apply --check` routing tag of a copy whose sources carry /// the patch while its compiled extension was not built from them. pub const NOT_REBUILT_REASON: &str = "native_extension_not_rebuilt"; +/// The reason of a copy `apply` skips because no file of the record is part +/// of the build installed there: the JVM build of a gem (what JRuby +/// installs) has none of the C code a record for the `ruby` platform gem +/// may be all about. Nothing is written, and the copy counts as patched. +pub const NOT_IN_BUILD_CODE: &str = "not_in_platform_build"; /// The build marker, in the gem dir (see [`BuildMarker`]). pub const MARKER_FILE: &str = ".socket-patch-native-build.json"; @@ -672,6 +729,19 @@ impl SpecFacts { release, } } + + /// The platform of the JVM build of a gem: a JVM platform + /// ([`is_java_platform`]) and no extension to build. That is what JRuby + /// installs for a gem whose compiled code is jars. A `java` gem that + /// declares extensions (jruby-launcher compiles a native launcher when + /// it is installed) is built by RubyGems like any gem with extensions, + /// and its record is rebuilt like one: it is not one of these. + fn jvm_platform(&self) -> Option<&str> { + if self.extensions.declared { + return None; + } + self.platform.as_deref().filter(|p| is_java_platform(p)) + } } /// Whether `platform` is JRuby's: a `java` gem ships its compiled code as @@ -682,6 +752,185 @@ fn is_java_platform(platform: &str) -> bool { .any(|part| part.eq_ignore_ascii_case("java") || part.eq_ignore_ascii_case("jruby")) } +/// The sources the jars of a JVM gem are built from, by extension. A jar +/// or a class file is not one: a record that replaces one whole puts the +/// patched code where the JVM loads it, like any file replacement. +const JVM_BUILD_EXTENSIONS: &[&str] = &["java", "kt", "scala"]; + +/// The build files of the tools that build those jars, in lowercase: the +/// name is matched whatever its case. +const JVM_BUILD_FILES: &[&str] = &[ + "pom.xml", + "build.xml", + "build.gradle", + "build.gradle.kts", + "mavenfile", +]; + +/// Whether a (normalized) gem file path is a JVM build input by its name: a +/// Java, Kotlin or Scala source, or a build file of Maven, Ant or Gradle. +/// The jars a JVM gem runs were built from these, and nothing here +/// rebuilds a jar. +/// +/// The name alone decides, wherever the file sits, as it does when +/// Socket's backend builds the patched `java` gem: a `pom.xml` that is +/// only a template keeps a copy from being attested, which errs on the +/// side of not attesting. +fn is_jvm_build_input(path: &str) -> bool { + let leaf = leaf_of(path).to_ascii_lowercase(); + JVM_BUILD_FILES.contains(&leaf.as_str()) + || leaf + .rsplit_once('.') + .is_some_and(|(stem, ext)| !stem.is_empty() && JVM_BUILD_EXTENSIONS.contains(&ext)) +} + +/// Whether a file of a patch is an input of a C build by its path: a file +/// under `ext/`, a patch or a port of a library the gem packs +/// (`patches/**`, `ports/**`), or a source or build file by name. +fn is_native_input_by_path(path: &str) -> bool { + ["ext/", "patches/", "ports/"] + .iter() + .any(|dir| path.starts_with(dir)) + || is_native_by_name(path) + || is_build_file_by_name(path) +} + +/// Whether the JVM build of a gem takes one file of a record: `path` +/// (normalized) with the record's `info`, in a copy that holds a file at +/// that path or not (`held`). +/// +/// The records are written for the `ruby` platform gem, and the JVM build +/// of the same release is another archive: it ships the gem's Ruby files, +/// often its C sources too (dead weight there: nothing on JRuby compiles +/// them), and none of what only a C build reads. +/// +/// Only an input of a C build ([`is_native_input_by_path`]) can be left +/// out, because only that is known to mean nothing to a gem with no C +/// build: +/// +/// * One the record replaces (it has a `beforeHash`) is part of this build +/// when the copy holds it: a C source the `java` gem ships is verified +/// and written like any patch file. One the copy does not hold is not +/// part of this platform's gem. +/// * One the record adds is never part of it: a new C source or a new +/// patch to a packed library. +/// +/// Every other file is taken, held or not. A Ruby file the record replaces +/// is part of every build of the gem, so one that is absent from the copy +/// is the usual missing file, never a file to skip: a deleted target must +/// not read as a patch with nothing to do. A file the record adds is +/// created. A path that could leave the gem dir is always taken, so that +/// the apply engine refuses the record for it. +/// +/// Two consequences are deliberate. A copy that takes no file of a record, +/// or only a C source that nothing there compiles, counts as patched +/// (`vex`, `apply --check`): the code the patch fixes is not in that +/// build, which is also the verdict on a copy installed from the patched +/// `java` gem. And a C build input that was deleted from the copy reads as +/// one the build never had: nothing here knows the `java` gem's file list, +/// nothing on JRuby reads such a file, and failing a patch that is applied +/// is the worse error. +fn jvm_takes(path: &str, info: &PatchFileInfo, held: bool) -> bool { + if !is_safe_relative_subpath(path) || !is_native_input_by_path(path) { + return true; + } + !info.before_hash.is_empty() && held +} + +/// Whether a (normalized) gem file path is compiled JVM code: a jar or a +/// class file, what the JVM loads. +fn is_compiled_jvm_code(path: &str) -> bool { + leaf_of(path).rsplit_once('.').is_some_and(|(stem, ext)| { + !stem.is_empty() && ["jar", "class"].contains(&ext.to_ascii_lowercase().as_str()) + }) +} + +/// The files of the record `key` (a manifest purl) that keep a JVM copy of +/// `platform` from running the patch: the sources and build files of its +/// jars ([`is_jvm_build_input`]), sorted, which nothing here compiles. +/// None when the record brings the compiled code itself: +/// +/// * The record written for the copy's own platform is the `java` gem's +/// own diff, applied whole: whatever it changes is what that gem ships. +/// * A record that replaces or adds a jar or a class file carries the code +/// the JVM loads, beside the source it was built from. +fn jvm_unbuilt_inputs( + platform: &str, + key: &str, + files: &HashMap, +) -> Vec { + if names_platform(key, platform) + || files + .keys() + .any(|file| is_compiled_jvm_code(normalize_file_path(file))) + { + return Vec::new(); + } + let mut inputs: Vec = files + .keys() + .filter(|file| is_jvm_build_input(normalize_file_path(file))) + .cloned() + .collect(); + inputs.sort(); + inputs +} + +/// A record as the JVM build of a gem takes it ([`jvm_takes`]). +#[derive(Debug, Clone, Default, PartialEq)] +struct JvmRecord { + /// The record's files that are part of this build. + files: HashMap, + /// The record's keys that keep the copy's jars from being the patch's + /// ([`jvm_unbuilt_inputs`]), sorted, whether the copy holds them or + /// not: the jars it runs may have been built from them. + jvm_inputs: Vec, +} + +/// Whether the manifest record `key` (a purl) is the one written for the +/// `ruby` platform gem: it names no platform, or `ruby`. +fn is_ruby_platform_record(key: &str) -> bool { + crate::utils::purl::purl_qualifier(key, "platform") + .is_none_or(|platform| platform.eq_ignore_ascii_case("ruby")) +} + +/// The record `key` (a manifest purl) with `files`, as the JVM gem copy in +/// `gem_dir` (of `platform`) takes it. +/// +/// Only the record written for the `ruby` platform gem is read file by +/// file ([`jvm_takes`]): that gem is another archive than the one +/// installed, so some of its files are no part of the copy. A record +/// qualified for a platform names the archive it was written for (the +/// copy's own `java`, or another one that was matched to it), and every +/// file of it is taken: one the copy lacks is the usual missing file. +async fn jvm_record( + gem_dir: &Path, + platform: &str, + key: &str, + files: &HashMap, +) -> JvmRecord { + let per_file = is_ruby_platform_record(key); + let mut out = JvmRecord { + files: HashMap::new(), + jvm_inputs: jvm_unbuilt_inputs(platform, key, files), + }; + for (file, info) in files { + let path = normalize_file_path(file); + // Only a C build input the record replaces is looked for. + let held = !per_file + || info.before_hash.is_empty() + || !is_safe_relative_subpath(path) + || !is_native_input_by_path(path) + || !matches!( + tokio::fs::symlink_metadata(gem_dir.join(path)).await, + Err(e) if crate::patch::apply::is_missing_path(&e) + ); + if !per_file || jvm_takes(path, info, held) { + out.files.insert(file.clone(), info.clone()); + } + } + out +} + /// Whether a (normalized) gem file path is a native-extension build input by /// its name alone: a C/C++/Objective-C source or header, a racc/ragel /// grammar, an `extconf.rb`, or a `depend` file under `ext/`. @@ -881,13 +1130,10 @@ fn classify(facts: &SpecFacts, files: &HashMap) -> Native } } -/// The record's native scope on the copy at `pkg_path`, and the copy when it -/// is a RubyGems install whose spec could be read. `None` scope inputs mean -/// the record is plain Ruby for this copy. -async fn scope_of( - pkg_path: &Path, - files: &HashMap, -) -> (NativeScope, Option) { +/// What the installed gemspec of the copy at `pkg_path` says, and the copy +/// when it is a RubyGems install whose spec could be read (the facts are +/// empty otherwise). +async fn facts_of(pkg_path: &Path) -> (SpecFacts, Option) { let copy = GemCopy::of(pkg_path); let spec_text = match © { Some(c) => crate::utils::fs::read_regular_to_string(&c.spec_path) @@ -899,10 +1145,78 @@ async fn scope_of( (Some(copy), Some(text)) => SpecFacts::of(text, ©.full_name), _ => SpecFacts::default(), }; - let scope = classify(&facts, files); - // Without a readable spec nothing proves which scripts the gem builds; - // name-matched inputs still count, and the copy is unusable for a build. - (scope, copy.filter(|_| spec_text.is_some())) + (facts, copy.filter(|_| spec_text.is_some())) +} + +/// One installed gem copy with its gemspec read: what a record is judged +/// against. A caller that asks more than one thing of a copy (the `vex` and +/// `apply --check` verifier asks which files to verify and whether the +/// compiled code is the patch's) reads the gemspec once, here. +#[derive(Debug, Clone)] +pub struct InstalledGem { + /// What the gemspec says; empty when the copy is no RubyGems install + /// or its spec could not be read. + facts: SpecFacts, + /// The copy, when its spec was read. Without a readable spec nothing + /// proves which scripts the gem builds: name-matched inputs still + /// count, and the copy is unusable for a build. + copy: Option, +} + +impl InstalledGem { + /// The gem copy at `pkg_path`. + pub async fn at(pkg_path: &Path) -> InstalledGem { + let (facts, copy) = facts_of(pkg_path).await; + InstalledGem { facts, copy } + } + + /// The copy and its platform, when it is the JVM build of a gem + /// ([`SpecFacts::jvm_platform`]). + fn jvm(&self) -> Option<(&GemCopy, &str)> { + Some((self.copy.as_ref()?, self.facts.jvm_platform()?)) + } + + /// The record's native scope on this copy. No inputs: the record is + /// plain Ruby for it. + fn scope(&self, files: &HashMap) -> NativeScope { + classify(&self.facts, files) + } + + /// The record `key` (a manifest purl) with `files`, as this copy takes + /// it. The JVM build of a gem (what JRuby installs) takes of the + /// ruby-platform record the files that are part of that build + /// ([`jvm_record`]); any other copy, and any other record, takes the + /// record as it is. + /// + /// Whatever compares a record with an installed copy reads it through + /// this (`vex`, `apply --check`, `rollback`), as `apply` wrote it: a + /// file the JVM build has no use for is neither missing from the copy + /// nor there to restore. + pub async fn record_files<'f>( + &self, + key: &str, + files: &'f HashMap, + ) -> std::borrow::Cow<'f, HashMap> { + use std::borrow::Cow; + match self.jvm() { + Some((copy, platform)) if is_ruby_platform_record(key) => { + Cow::Owned(jvm_record(©.gem_dir, platform, key, files).await.files) + } + _ => Cow::Borrowed(files), + } + } +} + +/// [`InstalledGem::record_files`] for the gem copy at `pkg_path`. +pub async fn installed_files<'f>( + pkg_path: &Path, + key: &str, + files: &'f HashMap, +) -> std::borrow::Cow<'f, HashMap> { + InstalledGem::at(pkg_path) + .await + .record_files(key, files) + .await } /// The build marker written into the gem dir after a rebuild. @@ -1167,37 +1481,108 @@ fn built_state( /// at install time, the marker of its rebuilt extension dir; for a /// precompiled platform gem, the marker of the prebuilt binaries replaced /// by a build of the source gem. Errors carry [`NOT_REBUILT_REASON`]. +/// +/// The JVM build of a gem compiles nothing of a record but what its jars +/// were built from, and nothing here rebuilds a jar: the record `key` (a +/// manifest purl) never passes on such a copy when it changes sources of +/// those jars without bringing the compiled code +/// ([`jvm_unbuilt_inputs`]), and any other record passes with no marker +/// (its files are judged through [`InstalledGem::record_files`]). pub async fn verify_native_build( pkg_path: &Path, + key: &str, files: &HashMap, ) -> Result<(), String> { - let (scope, copy) = scope_of(pkg_path, files).await; - if scope.inputs.is_empty() { - return Ok(()); - } - let Some(copy) = copy else { - return Err(NOT_REBUILT_REASON.to_string()); - }; - let files = files.clone(); - let holds = crate::utils::fs::run_blocking(move || { - read_marker_sync(©.gem_dir).is_some_and(|m| marker_holds(&m, ©, &scope, &files)) - }) - .await; - if holds { - Ok(()) - } else { - Err(NOT_REBUILT_REASON.to_string()) + InstalledGem::at(pkg_path) + .await + .verify_native_build(key, files) + .await +} + +impl InstalledGem { + /// [`verify_native_build`] of this copy. + pub async fn verify_native_build( + &self, + key: &str, + files: &HashMap, + ) -> Result<(), String> { + if let Some((_, platform)) = self.jvm() { + return if jvm_unbuilt_inputs(platform, key, files).is_empty() { + Ok(()) + } else { + Err(NOT_REBUILT_REASON.to_string()) + }; + } + let scope = self.scope(files); + if scope.inputs.is_empty() { + return Ok(()); + } + let Some(copy) = self.copy.clone() else { + return Err(NOT_REBUILT_REASON.to_string()); + }; + let files = files.clone(); + let holds = crate::utils::fs::run_blocking(move || { + read_marker_sync(©.gem_dir).is_some_and(|m| marker_holds(&m, ©, &scope, &files)) + }) + .await; + if holds { + Ok(()) + } else { + Err(NOT_REBUILT_REASON.to_string()) + } } } +/// What a gem apply whose result succeeded says beyond that result, when +/// the result alone would read as a copy the patch was applied to and it +/// is not one. The text is the reason in words, without the purl. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GemCaveat { + /// No file of the record is part of the build installed there + /// ([`NOT_IN_BUILD_CODE`]): nothing was verified or written, the code + /// the patch changes is not in that build, nothing is left to do and + /// the copy counts as patched. The caller reports it as skipped. + NotInBuild(String), + /// The patch is incomplete on this copy ([`NOT_REBUILT_REASON`]): the + /// record's files that the copy takes are written (there may be none), + /// and the compiled code it runs is not the patch's, with nothing here + /// to make it so. `result` says what was written, and none of it is + /// undone: the patch's Ruby half stays in effect, and a gem that + /// compiles its patched source later on its own relies on it. The + /// caller fails the run on it. The same text, after the purl, is the + /// run's warning. + Incomplete(String), +} + /// [`apply_gem_package_patch`]'s outcome: the copy's result, and a run /// warning `(code, detail)` the caller surfaces next to it. A result that /// succeeded with a [`NOT_REBUILT_REASON`] warning wrote the record's files -/// and built nothing: the copy's compiled code is not the patch's. +/// and built nothing: the copy's compiled code is not the patch's. Unless +/// the caller compiles it itself (`--no-gem-native-rebuild`), that patch +/// is incomplete, which `caveat` says in a typed way. #[derive(Debug, Clone)] pub struct GemApplied { pub result: ApplyResult, pub warning: Option<(String, String)>, + /// Set when `result` succeeded and is not the whole story + /// ([`GemCaveat`]). + pub caveat: Option, +} + +impl GemApplied { + /// The outcome of a copy whose patch is incomplete because `detail` + /// ([`GemCaveat::Incomplete`]): `result` stands as it is, and the run + /// warning carries the same text. + fn incomplete(result: ApplyResult, package_key: &str, detail: String) -> GemApplied { + GemApplied { + result, + warning: Some(( + NOT_REBUILT_REASON.to_string(), + format!("{package_key}: {detail}"), + )), + caveat: Some(GemCaveat::Incomplete(detail)), + } + } } /// Where the Ruby that builds a copy's extension is looked for and run. @@ -4627,7 +5012,7 @@ async fn files_as_installed( /// (`arm64-darwin`, `x86_64-linux-gnu`, `java`), as its dir name and /// gemspec text say. `None` for a `ruby`-platform copy and for a dir that /// is no RubyGems install. -pub async fn copy_platform(pkg_path: &Path) -> Option { +async fn copy_platform(pkg_path: &Path) -> Option { let copy = GemCopy::of(pkg_path)?; let spec_text = crate::utils::fs::read_regular_to_string(©.spec_path) .await @@ -4635,11 +5020,28 @@ pub async fn copy_platform(pkg_path: &Path) -> Option { SpecFacts::of(&spec_text, ©.full_name).platform } +/// Of the manifest records `keys` (the purls of one gem version), the one +/// written for the platform of the gem copy at `pkg_path` itself: the +/// record that is the copy's own. `None`: the copy is the `ruby` +/// platform's, it is no RubyGems install, or no record names its platform. +/// +/// Every reader that picks records for a copy asks this (`apply`, +/// `apply --check`, `vex`, `rollback`): when the copy's own record matches +/// it, that record alone is the copy's, and the ruby-platform record of +/// the same version is not applied to it or judged on it. +pub async fn own_platform_record<'k>( + pkg_path: &Path, + keys: impl IntoIterator, +) -> Option<&'k str> { + let platform = copy_platform(pkg_path).await?; + keys.into_iter().find(|key| names_platform(key, &platform)) +} + /// Whether the manifest record `key` (a purl) is the one written for gems /// of `platform`: its `platform` qualifier names it. RubyGems spells the /// glibc Linux platform with and without `-gnu`, by version; the two are /// one platform. -pub fn names_platform(key: &str, platform: &str) -> bool { +fn names_platform(key: &str, platform: &str) -> bool { let plain = |p: &str| p.to_ascii_lowercase().trim_end_matches("-gnu").to_string(); crate::utils::purl::purl_qualifier(key, "platform") .is_some_and(|named| plain(named) == plain(platform)) @@ -4653,32 +5055,36 @@ pub fn names_platform(key: &str, platform: &str) -> bool { /// build input of the ruby-platform record that an installed native gem /// does not hold ([`files_as_installed`]): its absence says the copy was /// built, not that it is another gem, and the source gem is where its -/// content is checked. Those files are left out. Any other record or copy: -/// `files` as they are (a `java` record stays unmatched on an MRI copy, and -/// the ruby record on a JRuby copy, which nothing here rebuilds). +/// content is checked. Those files are left out. +/// +/// On the JVM build of a gem (what JRuby installs) the ruby-platform +/// record is matched by the files that build takes of it +/// ([`installed_files`]): one the copy holds must hold the record's +/// content, and one it does not hold says nothing. +/// +/// Any other record or copy: `files` as they are (a `java` record stays +/// unmatched on an MRI copy, and a record qualified for another platform +/// on a JRuby one). pub async fn discriminating_files<'f>( pkg_path: &Path, key: &str, files: &'f HashMap, ) -> std::borrow::Cow<'f, HashMap> { use std::borrow::Cow; - let ruby_record = crate::utils::purl::purl_qualifier(key, "platform") - .is_none_or(|platform| platform.eq_ignore_ascii_case("ruby")); let is_gem = crate::crawlers::types::Ecosystem::from_purl(key) == Some(crate::crawlers::types::Ecosystem::Gem); - if !is_gem || !ruby_record { + if !is_gem || !is_ruby_platform_record(key) { return Cow::Borrowed(files); } - let (scope, copy) = scope_of(pkg_path, files).await; - let Some(copy) = copy.filter(|_| !scope.inputs.is_empty()) else { + let gem = InstalledGem::at(pkg_path).await; + if gem.jvm().is_some() { + return gem.record_files(key, files).await; + } + let scope = gem.scope(files); + let Some(copy) = gem.copy.filter(|_| !scope.inputs.is_empty()) else { return Cow::Borrowed(files); }; - let rebuilt_from_source = scope.builds_extensions - || scope - .precompiled - .as_deref() - .is_some_and(|platform| !is_java_platform(platform)); - if !rebuilt_from_source { + if !scope.builds_extensions && scope.precompiled.is_none() { return Cow::Borrowed(files); } let (_, absent) = files_as_installed(©, &scope, files).await; @@ -4693,13 +5099,16 @@ pub async fn discriminating_files<'f>( /// The record's files as `rollback` undoes them on the gem copy at /// `pkg_path`. A build input `apply` added to a copy that did not hold it /// ([`files_as_installed`]; the copy's backup lists them) is removed, not -/// restored to the content it has in the source gem. Any other copy: -/// `files` as they are. +/// restored to the content it has in the source gem. On the JVM build of a +/// gem, only the files `apply` wrote there for the record `key` (a manifest +/// purl) are undone ([`installed_files`]): one it skipped is not there to +/// restore. Any other copy: `files` as they are. pub async fn rollback_files( pkg_path: &Path, + key: &str, files: &HashMap, ) -> HashMap { - let mut out = files.clone(); + let mut out = installed_files(pkg_path, key, files).await.into_owned(); let Some(copy) = GemCopy::of(pkg_path) else { return out; }; @@ -4737,18 +5146,26 @@ fn gem_name_of(full_name: &str) -> &str { .map_or(full_name, |i| &full_name[..i]) } +/// The result of a copy in which nothing was verified and nothing written: +/// one that was refused (`error` says why), or one left as it was on +/// purpose (no `error`: it succeeded). +fn untouched_result(package_key: &str, pkg_path: &Path, error: Option) -> ApplyResult { + ApplyResult { + package_key: package_key.to_string(), + package_path: pkg_path.display().to_string(), + success: error.is_none(), + files_verified: Vec::new(), + files_patched: Vec::new(), + applied_via: HashMap::new(), + error, + sidecar: None, + } +} + fn refusal(package_key: &str, pkg_path: &Path, code: &str, detail: String) -> GemApplied { GemApplied { - result: ApplyResult { - package_key: package_key.to_string(), - package_path: pkg_path.display().to_string(), - success: false, - files_verified: Vec::new(), - files_patched: Vec::new(), - applied_via: HashMap::new(), - error: Some(format!("{code}: {detail}")), - sidecar: None, - }, + caveat: None, + result: untouched_result(package_key, pkg_path, Some(format!("{code}: {detail}"))), warning: Some((code.to_string(), detail)), } } @@ -4779,6 +5196,7 @@ async fn plain_apply( policy: MismatchPolicy, ) -> GemApplied { GemApplied { + caveat: None, result: apply_package_patch( read_scope, package_key, @@ -4793,6 +5211,65 @@ async fn plain_apply( } } +/// The [`NOT_REBUILT_REASON`] warning of `--no-gem-native-rebuild`: the +/// record's sources (`inputs`) are written and what is compiled from them +/// is left to the caller, the extension of a gem or (`jars`) the jars of a +/// JVM gem. A `dry_run` writes nothing and says what `apply` would do. +fn opted_out_warning( + package_key: &str, + inputs: &str, + jars: bool, + dry_run: bool, +) -> (String, String) { + let detail = match (jars, dry_run) { + (false, false) => format!( + "{package_key}: the patch changes native-extension sources ({inputs}), written \ + without rebuilding the extension (--no-gem-native-rebuild); Ruby loads the old \ + build until it is recompiled, and vex does not attest it" + ), + (false, true) => format!( + "{package_key}: dry run: the patch changes native-extension sources ({inputs}); \ + apply would write them without rebuilding the extension \ + (--no-gem-native-rebuild), Ruby would load the old build until it is recompiled, \ + and vex would not attest it" + ), + (true, false) => format!( + "{package_key}: the patch changes sources of the gem's jars ({inputs}), written \ + without rebuilding them (--no-gem-native-rebuild); JRuby loads the old jars until \ + they are rebuilt, and vex does not attest it" + ), + (true, true) => format!( + "{package_key}: dry run: the patch changes sources of the gem's jars ({inputs}); \ + apply would write them without rebuilding the jars (--no-gem-native-rebuild), \ + JRuby would load the old jars until they are rebuilt, and vex would not attest it" + ), + }; + (NOT_REBUILT_REASON.to_string(), detail) +} + +/// What is wrong with a copy that holds the record's files (or, on a +/// `dry_run`, would hold them once `apply` ran) while its compiled code +/// stays what it was, because `why`: the text of an incomplete patch +/// ([`GemCaveat::Incomplete`]). `inputs` names the record's sources that +/// are in no compiled code ([`list_inputs`]). +fn not_compiled_detail(inputs: &str, why: &str, dry_run: bool) -> String { + if dry_run { + format!( + "dry run: apply would write the patch's files, but its native-extension sources \ + ({inputs}) would not be in the compiled code this install runs: {why}. That code \ + would stay as it was installed, only the patch's other files would be in effect, \ + and vex would not attest the patch" + ) + } else { + format!( + "the patch's files were written, but its native-extension sources ({inputs}) are \ + not in the compiled code this install runs: {why}. That code is as it was \ + installed, only the patch's other files are in effect, and vex does not attest \ + the patch" + ) + } +} + /// One gem copy's record, verified against the copy and about to be built. struct Job<'a> { read_scope: crate::utils::repo_root::ReadScope, @@ -4868,29 +5345,30 @@ impl Job<'_> { ), ) }); - GemApplied { result, warning } + GemApplied { + result, + warning, + caveat: None, + } } - /// The warning of a copy that holds the record's files while its - /// compiled code is what it was: a clean build showed that this install - /// compiles nothing of the record (`why`). No marker is written, so - /// `vex` and `apply --check` do not take the copy for patched - /// ([`verify_native_build`]). - fn not_compiled(&self, why: &str) -> (String, String) { - ( - NOT_REBUILT_REASON.to_string(), - format!( - "{}: the patch's files were written, but its native-extension sources ({}) \ - are not in the compiled code this install runs: {why}. That code is as it was \ - installed, only the patch's other files are in effect, and vex does not \ - attest the patch", - self.package_key, self.inputs - ), + /// The outcome of a copy that holds the record's files (`result` wrote + /// them, or found them written) while its compiled code is what it + /// was: a clean build showed that this install compiles nothing of the + /// record (`why`). The patch is incomplete + /// ([`GemCaveat::Incomplete`]), and nothing is put back. No marker is + /// written, so `vex` and `apply --check` do not take the copy for + /// patched ([`verify_native_build`]). + fn not_compiled(&self, result: ApplyResult, why: &str) -> GemApplied { + GemApplied::incomplete( + result, + self.package_key, + not_compiled_detail(self.inputs, why, false), ) } /// Write the record's files into a copy whose build showed that it - /// compiles nothing of them (`why`), and say so + /// compiles nothing of them (`why`), and report the patch as incomplete /// ([`not_compiled`](Self::not_compiled)): the patch's Ruby files take /// effect, and a file the gem compiles later on its own (one that /// builds its binary when it first runs) is the patched one (#2144). @@ -4910,8 +5388,14 @@ impl Job<'_> { } let originals = self.originals().await; let result = self.write_sources(&originals).await; - let warning = result.success.then(|| self.not_compiled(why)); - GemApplied { result, warning } + if !result.success { + return GemApplied { + result, + warning: None, + caveat: None, + }; + } + self.not_compiled(result, why) } /// The outcome of a copy that is as it was before the run, because @@ -4939,6 +5423,7 @@ impl Job<'_> { } result.error = Some(format!("{BUILD_FAILED_CODE}: {detail}")); GemApplied { + caveat: None, result, warning: Some((BUILD_FAILED_CODE.to_string(), detail)), } @@ -4950,10 +5435,143 @@ impl Job<'_> { const HOSTED_HINT: &str = "Use `socket-patch scan --mode hosted`, which installs the patched gem \ through Bundler so RubyGems compiles it."; +/// Why the jars of a JVM gem are not a build of a record that changes what +/// they were built from ([`Job::not_compiled`]). +const JARS_NOT_REBUILT: &str = "the gem's jars were built from Java sources the patch changes, \ + and they cannot be rebuilt here"; + +/// One record applied to the JVM build of a gem: the copy JRuby installs, +/// whose compiled code is jars. Nothing is built and no Ruby is started. +/// The files the copy takes of the record are written ([`jvm_record`]), +/// and that is the whole patch unless the record changes sources of the +/// gem's jars without bringing the compiled code +/// ([`jvm_unbuilt_inputs`]): the jars were built from those, so the copy's +/// compiled code is then not the patch's, and the patch is incomplete +/// ([`GemCaveat::Incomplete`]). +struct JvmApply<'a> { + read_scope: crate::utils::repo_root::ReadScope, + package_key: &'a str, + pkg_path: &'a Path, + sources: &'a PatchSources<'a>, + dry_run: bool, + policy: MismatchPolicy, + env: &'a RubyEnv, + copy: &'a GemCopy, + /// The copy's platform (`java`). + platform: &'a str, + release: Option, +} + +impl JvmApply<'_> { + /// The result of a copy this run verifies and writes nothing in. + fn untouched(&self) -> ApplyResult { + untouched_result(self.package_key, self.pkg_path, None) + } + + async fn plain(&self, files: &HashMap) -> GemApplied { + plain_apply( + self.read_scope, + self.package_key, + self.pkg_path, + files, + self.sources, + self.dry_run, + self.policy, + ) + .await + } + + async fn apply(&self, files: &HashMap) -> GemApplied { + let record = jvm_record(&self.copy.gem_dir, self.platform, self.package_key, files).await; + let full_name = &self.copy.full_name; + if record.jvm_inputs.is_empty() { + // The code the record changes is not in this build at all. + if record.files.is_empty() && !files.is_empty() { + let detail = format!( + "none of the patch's files are part of the JRuby build of this gem \ + ({full_name}): the code the patch changes is not in that build, so there \ + is nothing to patch and nothing was written" + ); + return GemApplied { + result: self.untouched(), + warning: None, + caveat: Some(GemCaveat::NotInBuild(detail)), + }; + } + return self.plain(&record.files).await; + } + + // The record changes what the gem's jars were built from. + let scope = NativeScope { + inputs: record.jvm_inputs.clone(), + builds_extensions: false, + precompiled: Some(self.platform.to_string()), + release: self.release.clone(), + }; + let inputs = list_inputs(&scope); + // Nothing of the record is in the copy to write, and its jars may + // hold the code the patch fixes: incomplete, whoever compiles. + if record.files.is_empty() { + let detail = format!( + "none of the patch's files are in the JRuby build of this gem ({full_name}) to \ + write, and it changes sources of the gem's jars ({inputs}): \ + {JARS_NOT_REBUILT}. Nothing was written, and vex does not attest the patch" + ); + return GemApplied::incomplete(self.untouched(), self.package_key, detail); + } + // `--no-gem-native-rebuild`: the caller compiles what the patch + // changes itself, so the files are written and the rest is the + // caller's, as for an extension. + if !self.env.rebuild { + let mut applied = self.plain(&record.files).await; + if applied.result.success { + applied.warning = Some(opted_out_warning( + self.package_key, + &inputs, + true, + self.dry_run, + )); + } + return applied; + } + // Files alone show what a real run comes to here, so a dry run + // says the same: the record verifies, and the patch would be + // incomplete. + if self.dry_run { + let verified = self.plain(&record.files).await; + if !verified.result.success { + return verified; + } + return GemApplied::incomplete( + verified.result, + self.package_key, + not_compiled_detail(&inputs, JARS_NOT_REBUILT, true), + ); + } + let job = Job { + read_scope: self.read_scope, + package_key: self.package_key, + pkg_path: self.pkg_path, + files: &record.files, + installed_files: &record.files, + sources: self.sources, + policy: self.policy, + env: self.env, + copy: self.copy, + scope: &scope, + inputs: &inputs, + }; + job.write_without_build(&[], JARS_NOT_REBUILT).await + } +} + /// [`apply_package_patch`] for one installed gem copy, rebuilding its /// native extension when the record changes a build input (see the module /// docs). A record without native inputs is applied exactly as -/// [`apply_package_patch`] applies it. +/// [`apply_package_patch`] applies it. The JVM build of a gem is never +/// rebuilt: it takes the record's files that are part of that build +/// ([`JvmApply`]). A JVM-platform gem that declares extensions is no such +/// build, and is rebuilt like any gem RubyGems built. #[allow(clippy::too_many_arguments)] pub async fn apply_gem_package_patch( read_scope: crate::utils::repo_root::ReadScope, @@ -4965,7 +5583,26 @@ pub async fn apply_gem_package_patch( policy: MismatchPolicy, env: &RubyEnv, ) -> GemApplied { - let (scope, copy) = scope_of(pkg_path, files).await; + let gem = InstalledGem::at(pkg_path).await; + // The JVM build of a gem has no extension to rebuild: the record is + // applied as far as it concerns that build. + if let Some((copy, platform)) = gem.jvm() { + let jvm = JvmApply { + read_scope, + package_key, + pkg_path, + sources, + dry_run, + policy, + env, + copy, + platform, + release: gem.facts.release.clone(), + }; + return jvm.apply(files).await; + } + let scope = gem.scope(files); + let copy = gem.copy; if scope.inputs.is_empty() { return plain_apply( read_scope, @@ -5013,14 +5650,7 @@ pub async fn apply_gem_package_patch( ) .await; if applied.result.success { - applied.warning = Some(( - NOT_REBUILT_REASON.to_string(), - format!( - "{package_key}: the patch changes native-extension sources ({inputs}), \ - written without rebuilding the extension (--no-gem-native-rebuild); Ruby \ - loads the old build until it is recompiled, and vex does not attest it" - ), - )); + applied.warning = Some(opted_out_warning(package_key, &inputs, false, dry_run)); } return applied; } @@ -5050,19 +5680,6 @@ pub async fn apply_gem_package_patch( ), ); } - if let Some(platform) = scope.precompiled.as_deref().filter(|p| is_java_platform(p)) { - return refusal( - package_key, - pkg_path, - UNSUPPORTED_CODE, - format!( - "the patch changes native-extension sources ({inputs}), but the installed gem \ - is the JRuby build ({platform}), whose compiled code ships as jars built from \ - Java sources; they cannot be rebuilt from the source gem here, so the patch \ - cannot take effect; nothing was written." - ), - ); - } let precompiled = scope.precompiled.is_some(); let (installed_files, absent) = files_as_installed(©, &scope, files).await; @@ -5193,6 +5810,7 @@ pub async fn apply_gem_package_patch( .await; if !verified.success { return GemApplied { + caveat: None, result: verified, warning: None, }; @@ -5243,6 +5861,7 @@ pub async fn apply_gem_package_patch( ), }; return GemApplied { + caveat: None, result: verified, warning: Some((REBUILT_CODE.to_string(), detail)), }; @@ -5412,6 +6031,7 @@ async fn rebuild_in_place( let result = job.write_sources(&originals).await; if !result.success { return GemApplied { + caveat: None, result, warning: None, }; @@ -5424,10 +6044,7 @@ async fn rebuild_in_place( match rebuild(job.copy, probe, job.scope, job.files, job.env, true, stale).await { Ok(()) => job.built(result), // The previous build is back, and the sources stay written. - Err(NotRebuilt::NotOfPatch(why)) => { - let warning = Some(job.not_compiled(&why)); - GemApplied { result, warning } - } + Err(NotRebuilt::NotOfPatch(why)) => job.not_compiled(result, &why), Err(NotRebuilt::Failed(diagnostic)) => { // An installed tree may no longer hold what its build needs // (nokogiri's deletes `ports/`): the source gem would. @@ -5470,6 +6087,7 @@ async fn move_into_copy( let result = job.write_sources(&originals).await; if !result.success { return GemApplied { + caveat: None, result, warning: None, }; @@ -5548,6 +6166,7 @@ async fn graft_into_copy( if !result.success { drop_new_backup().await; return GemApplied { + caveat: None, result, warning: None, }; @@ -6844,37 +7463,670 @@ mod tests { assert_eq!(with_ext.inputs, ["ext/x.c"]); } - /// The JRuby build of a gem ships jars: its Java sources are inputs - /// (nothing here rebuilds them, so the patch is refused, never called - /// applied), while its Ruby files and a jar replaced whole are plain. + /// The JRuby build of a gem is told by its platform, from the gem's + /// dir name or its gemspec, and by having nothing for RubyGems to + /// build. A `java` gem that declares extensions (jruby-launcher + /// compiles its launcher at install time) is a gem RubyGems built, and + /// keeps the rebuild every such gem gets. #[test] - fn classify_java_gem() { + fn a_jvm_gem_is_told_by_its_platform() { let spec = to_ruby("nokogiri", Some("java"), &[]); let facts = SpecFacts::of(&spec, "nokogiri-1.18.3-java"); - let scope = classify( - &facts, - &files(&[ - "ext/java/nokogiri/XmlNode.java", - "lib/nokogiri/xml/node.rb", - "lib/nokogiri/nokogiri.jar", - "lib/nokogiri/internals/Helper.java", - ]), - ); - assert_eq!( - scope.inputs, - [ - "ext/java/nokogiri/XmlNode.java", - "lib/nokogiri/internals/Helper.java" - ] - ); - assert_eq!(scope.precompiled.as_deref(), Some("java")); + assert_eq!(facts.jvm_platform(), Some("java")); + let declares = to_ruby("jruby-launcher", Some("java"), &["extconf.rb"]); + let facts = SpecFacts::of(&declares, "jruby-launcher-1.18.3-java"); + assert_eq!(facts.jvm_platform(), None); + let scope = classify(&facts, &files(&["jrubyexe.cpp", "lib/jruby-launcher.rb"])); + assert!(scope.builds_extensions); + assert_eq!(scope.precompiled, None); + assert_eq!(scope.inputs, ["jrubyexe.cpp"]); + let universal = to_ruby("json", Some("universal-java-17"), &[]); + let facts = SpecFacts::of(&universal, "json-1.18.3-universal-java-17"); + assert_eq!(facts.jvm_platform(), Some("universal-java-17")); + for platform in [None, Some("arm64-darwin"), Some("x86_64-linux-gnu")] { + let spec = to_ruby("nokogiri", platform, &[]); + let full_name = match platform { + Some(p) => format!("nokogiri-1.18.3-{p}"), + None => "nokogiri-1.18.3".to_string(), + }; + assert_eq!( + SpecFacts::of(&spec, &full_name).jvm_platform(), + None, + "{platform:?}" + ); + } assert!(is_java_platform("java")); + assert!(is_java_platform("jruby")); assert!(is_java_platform("universal-java-17")); for platform in ["arm64-darwin", "x86_64-linux-gnu", "x64-mingw-ucrt"] { assert!(!is_java_platform(platform), "{platform}"); } } + /// What a JVM gem's jars are built from, by name: sources and the build + /// files of the tools that build them. A jar or a class file is what + /// they are built into: a record that replaces one whole patches the + /// code the JVM loads, and is no build input. + #[test] + fn jvm_build_inputs_are_told_by_name() { + for path in [ + "ext/java/nokogiri/XmlNode.java", + "lib/nokogiri/internals/Helper.JAVA", + "src/main/kotlin/A.kt", + "src/main/scala/B.scala", + "pom.xml", + "ext/POM.XML", + "build.xml", + "build.gradle", + "build.gradle.kts", + "Mavenfile", + "ext/mavenfile", + // Wherever it sits: a template counts too. + "templates/pom.xml", + ] { + assert!(is_jvm_build_input(path), "{path}"); + } + for path in [ + "lib/nokogiri/nokogiri.jar", + "lib/nokogiri/jruby/xerces/xercesImpl.JAR", + "lib/a/B.class", + "lib/nokogiri/xml/node.rb", + "ext/nokogiri/xml_node.c", + "ext/nokogiri/extconf.rb", + "dependencies.yml", + "patches/libxml2/0001.patch", + "lib/java.rb", + "lib/jar", + "lib/.java", + "pom.xml.bak", + "docs/build.gradle.md", + "settings.xml", + ] { + assert!(!is_jvm_build_input(path), "{path}"); + } + } + + /// The per-file rule of a JVM copy: only an input of a C build can be + /// left out. One the record replaces is taken when the copy ships it, + /// one it adds never is. Every other file is taken, held or not: a + /// Ruby file that is missing from the copy is a missing file, not a + /// file to skip. + #[test] + fn a_jvm_copy_takes_the_files_of_its_own_build() { + let replaces = info(&"a".repeat(64)); + let adds = PatchFileInfo { + before_hash: String::new(), + after_hash: "a".repeat(64), + }; + // C build inputs the record replaces: taken when the copy holds + // them (dead code there), skipped when it does not. + for path in [ + "ext/nokogiri/xml_node.c", + "ext/nokogiri/extconf.rb", + "ext/java/nokogiri/XmlNode.java", + "patches/libxml2/0001.patch", + "ports/archives/libxml2-2.13.9.tar.xz", + "gumbo-parser/src/parser.c", + "lib/nokogiri/include/x.h", + ] { + assert!(jvm_takes(path, &replaces, true), "held {path}"); + assert!(!jvm_takes(path, &replaces, false), "not held {path}"); + } + // Any other file the record replaces is part of every build of + // the gem: taken whether the copy holds it or not, so that one + // deleted from the copy fails as a missing file. + for path in [ + "lib/nokogiri/xml/node.rb", + "lib/nokogiri.rb", + "dependencies.yml", + "lib/nokogiri/nokogiri.jar", + "bin/nokogiri", + "README.md", + ] { + assert!(jvm_takes(path, &replaces, true), "held {path}"); + assert!(jvm_takes(path, &replaces, false), "not held {path}"); + } + // Added files a C build alone would read: skipped, even where the + // copy happens to hold something at the path. + for path in [ + "ext/nokogiri/new_source.c", + "ext/nokogiri/include/new.h", + "ext/java/nokogiri/New.java", + "patches/libxml2/0100-fix.patch", + "ports/patches/libxml2/0100-fix.patch", + "ports/archives/libxml2-2.13.9.tar.xz", + "lib/nokogiri/extra.h", + "gumbo-parser/src/new.c", + "Cargo.toml", + "CMakeLists.txt", + "extconf.rb", + ] { + assert!(!jvm_takes(path, &adds, false), "{path}"); + assert!(!jvm_takes(path, &adds, true), "held {path}"); + } + // Any other added file is created. + for path in [ + "lib/nokogiri/xml/new_helper.rb", + "lib/nokogiri/data.yml", + "data/entities.json", + "lib/nokogiri/extra.jar", + "README.md", + ] { + assert!(jvm_takes(path, &adds, false), "{path}"); + } + // A key that could leave the gem dir is never dropped quietly: the + // apply engine refuses the record for it. + for path in ["../outside.c", "/etc/passwd", "ext/../../x.c", ""] { + assert!(jvm_takes(path, &adds, false), "{path:?}"); + assert!(jvm_takes(path, &replaces, false), "{path:?}"); + } + } + + /// The sources of a JVM gem's jars keep a record from being a build of + /// the patch only when the record does not bring the compiled code + /// itself: the copy's own platform's record is the `java` gem's diff, + /// and a record that replaces or adds a jar or a class file carries + /// what the JVM loads. + #[test] + fn jvm_sources_hold_up_only_a_record_without_the_compiled_code() { + let ruby = "pkg:gem/a@1?platform=ruby"; + let source_only = files(&["ext/java/a/A.java", "lib/a.rb"]); + for key in [ruby, "pkg:gem/a@1", "pkg:gem/a@1?platform=arm64-darwin"] { + assert_eq!( + jvm_unbuilt_inputs("java", key, &source_only), + ["ext/java/a/A.java"], + "{key}" + ); + } + // The copy's own record, whichever JVM platform it is. + assert!(jvm_unbuilt_inputs("java", "pkg:gem/a@1?platform=java", &source_only).is_empty()); + assert!(jvm_unbuilt_inputs( + "universal-java-17", + "pkg:gem/a@1?platform=universal-java-17", + &source_only + ) + .is_empty()); + assert_eq!( + jvm_unbuilt_inputs( + "universal-java-17", + "pkg:gem/a@1?platform=java", + &source_only + ), + ["ext/java/a/A.java"] + ); + // The record brings the jar (or a class) built from the source. + for compiled in ["lib/a/a.jar", "lib/a/A.class", "lib/a/B.JAR"] { + let with_code = files(&["ext/java/a/A.java", "pom.xml", compiled]); + assert!( + jvm_unbuilt_inputs("java", ruby, &with_code).is_empty(), + "{compiled}" + ); + assert!(is_compiled_jvm_code(compiled), "{compiled}"); + } + for path in ["lib/a.rb", "lib/jar", "lib/.jar", "ext/java/a/A.java"] { + assert!(!is_compiled_jvm_code(path), "{path}"); + } + // No source, nothing held up. + assert!(jvm_unbuilt_inputs("java", ruby, &files(&["lib/a.rb", "ext/a/a.c"])).is_empty()); + // Sorted, every one of them. + assert_eq!( + jvm_unbuilt_inputs("java", ruby, &files(&["pom.xml", "ext/java/a/A.java"])), + ["ext/java/a/A.java", "pom.xml"] + ); + } + + /// `--no-gem-native-rebuild` warns in the tense of the run: a dry run + /// writes nothing and says what `apply` would do. + #[test] + fn the_opt_out_warning_of_a_dry_run_says_what_apply_would_do() { + for jars in [false, true] { + let (code, wet) = opted_out_warning("pkg:gem/a@1", "ext/a/a.c", jars, false); + assert_eq!(code, NOT_REBUILT_REASON); + assert!(wet.contains("written without rebuilding"), "{wet}"); + assert!(!wet.contains("would"), "{wet}"); + let (code, dry) = opted_out_warning("pkg:gem/a@1", "ext/a/a.c", jars, true); + assert_eq!(code, NOT_REBUILT_REASON); + assert!( + dry.starts_with("pkg:gem/a@1: dry run: ") + && dry.contains("apply would write them without rebuilding") + && dry.contains("vex would not attest it"), + "{dry}" + ); + assert!(!dry.contains(", written "), "{dry}"); + for text in [&wet, &dry] { + assert!(text.contains("(--no-gem-native-rebuild)"), "{text}"); + assert!(text.contains("(ext/a/a.c)"), "{text}"); + } + } + } + + /// A hand-laid JVM copy of the gem `a`: its Ruby file, a C source it + /// ships as dead weight, a Java source and the jar built from it. + fn jvm_gem(home: &Path) -> GemCopy { + let gem_dir = home.join("gems/a-1-java"); + for (rel, bytes) in [ + ("lib/a.rb", &b"require 'a/a.jar'\n"[..]), + ("lib/a/a.jar", b"PK jar"), + ("ext/a/a.c", b"int a;"), + ("ext/java/a/A.java", b"class A {}"), + ] { + let path = gem_dir.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write( + home.join("specifications/a-1-java.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"a\".freeze\n \ + s.version = \"1\".freeze\n s.platform = \"java\".freeze\n \ + s.require_paths = [\"lib\".freeze]\nend\n", + ) + .unwrap(); + GemCopy::of(&gem_dir).unwrap() + } + + fn sorted_keys(files: &HashMap) -> Vec { + let mut keys: Vec = files.keys().cloned().collect(); + keys.sort(); + keys + } + + /// The record a JVM copy is judged by, wherever a record is compared + /// with an installed copy: matching a release variant, `apply --check`, + /// `vex` and `rollback` all read it through the same rule. + #[tokio::test] + async fn a_jvm_copy_is_judged_by_the_files_it_takes() { + let tmp = tempfile::tempdir().unwrap(); + let copy = jvm_gem(&tmp.path().join("jruby")); + let added = |after: &str| PatchFileInfo { + before_hash: String::new(), + after_hash: after.repeat(64), + }; + let record: HashMap = [ + ("lib/a.rb".to_string(), info(&"1".repeat(64))), + ("ext/a/a.c".to_string(), info(&"2".repeat(64))), + // A jar the record replaces whole. + ("lib/a/a.jar".to_string(), info(&"8".repeat(64))), + // A C source this build does not ship: left out. + ("ext/a/gone.c".to_string(), info(&"3".repeat(64))), + // A Ruby file the copy lacks: part of every build of the gem, + // so it is taken, and missing. + ("lib/a/missing.rb".to_string(), info(&"4".repeat(64))), + // Added files: a library patch, and a Ruby file. + ("patches/lib/0001.patch".to_string(), added("5")), + ("lib/a/new.rb".to_string(), added("6")), + ] + .into(); + let taken = [ + "ext/a/a.c", + "lib/a.rb", + "lib/a/a.jar", + "lib/a/missing.rb", + "lib/a/new.rb", + ]; + let gem = InstalledGem::at(©.gem_dir).await; + + // The ruby-platform record, qualified or not, is read file by file. + for purl in ["pkg:gem/a@1", "pkg:gem/a@1?platform=ruby"] { + let view = jvm_record(©.gem_dir, "java", purl, &record).await; + assert_eq!(sorted_keys(&view.files), taken, "{purl}"); + // A replaced jar is a file like any other, not a build input. + assert!(view.jvm_inputs.is_empty(), "{purl}: {:?}", view.jvm_inputs); + assert_eq!( + sorted_keys(&*gem.record_files(purl, &record).await), + taken, + "{purl}" + ); + assert_eq!( + sorted_keys(&*installed_files(©.gem_dir, purl, &record).await), + taken, + "{purl}" + ); + assert_eq!( + sorted_keys(&rollback_files(©.gem_dir, purl, &record).await), + taken, + "{purl}" + ); + let telling = discriminating_files(©.gem_dir, purl, &record).await; + assert_eq!(sorted_keys(&telling), taken, "{purl}"); + } + // A record qualified for a platform names the archive it was + // written for, the copy's own included: every file of it is + // required, in every reader, and one the copy lacks is missing. + for purl in [ + "pkg:gem/a@1?platform=java", + "pkg:gem/a@1?platform=arm64-darwin", + ] { + let view = jvm_record(©.gem_dir, "java", purl, &record).await; + assert_eq!(view.files, record, "{purl}"); + let whole = gem.record_files(purl, &record).await; + assert!(matches!(whole, std::borrow::Cow::Borrowed(_)), "{purl}"); + assert_eq!( + *installed_files(©.gem_dir, purl, &record).await, + record, + "{purl}" + ); + assert_eq!( + rollback_files(©.gem_dir, purl, &record).await, + record, + "{purl}" + ); + let telling = discriminating_files(©.gem_dir, purl, &record).await; + assert_eq!(*telling, record, "{purl}"); + } + // Nothing is built for such a copy, so no marker is asked for: C + // sources, a library patch and a replaced jar are no build inputs + // there. + let purl = "pkg:gem/a@1?platform=ruby"; + assert_eq!( + verify_native_build(©.gem_dir, purl, &record).await, + Ok(()) + ); + assert_eq!(gem.verify_native_build(purl, &record).await, Ok(())); + + // A record of a C build alone: no file of it is part of this build. + let c_only: HashMap = + [("patches/lib/0001.patch".to_string(), added("5"))].into(); + assert!(installed_files(©.gem_dir, purl, &c_only) + .await + .is_empty()); + assert!(rollback_files(©.gem_dir, purl, &c_only) + .await + .is_empty()); + assert_eq!( + verify_native_build(©.gem_dir, purl, &c_only).await, + Ok(()) + ); + + // A ruby-platform record that changes what the jars were built + // from, and brings no jar, is never attested, whether the copy + // ships that source or not. + let own = "pkg:gem/a@1?platform=java"; + for jvm_key in ["ext/java/a/A.java", "ext/java/a/Gone.java", "pom.xml"] { + let mut with_java = record.clone(); + with_java.remove("lib/a/a.jar"); + with_java.insert(jvm_key.to_string(), info(&"7".repeat(64))); + let view = jvm_record(©.gem_dir, "java", purl, &with_java).await; + assert_eq!(view.jvm_inputs, [jvm_key]); + // Only a C build input the copy lacks is left out. + assert_eq!( + view.files.contains_key(jvm_key), + jvm_key != "ext/java/a/Gone.java", + "{jvm_key}" + ); + assert_eq!( + verify_native_build(©.gem_dir, purl, &with_java).await, + Err(NOT_REBUILT_REASON.to_string()), + "{jvm_key}" + ); + // The same record with the jar built from it is the patch. + let mut with_jar = with_java.clone(); + with_jar.insert("lib/a/a.jar".to_string(), info(&"8".repeat(64))); + assert_eq!( + verify_native_build(©.gem_dir, purl, &with_jar).await, + Ok(()), + "{jvm_key}" + ); + // And the copy's own record is the java gem's diff, whole. + let strict = jvm_record(©.gem_dir, "java", own, &with_java).await; + assert!(strict.jvm_inputs.is_empty(), "{jvm_key}"); + assert_eq!(strict.files, with_java, "{jvm_key}"); + assert_eq!( + verify_native_build(©.gem_dir, own, &with_java).await, + Ok(()), + "{jvm_key}" + ); + } + + // Of the records of one version, the copy's own is the one that + // names its platform; an MRI copy and a bare dir have none. + let keys = [purl, "pkg:gem/a@1?platform=arm64-darwin", own]; + assert_eq!(own_platform_record(©.gem_dir, keys).await, Some(own)); + assert_eq!(own_platform_record(©.gem_dir, [purl]).await, None); + assert_eq!(own_platform_record(tmp.path(), keys).await, None); + + // Any other copy takes the record as it is. + let mri = precompiled_gem(&tmp.path().join("mri")); + let whole = installed_files(&mri.gem_dir, purl, &record).await; + assert!(matches!(whole, std::borrow::Cow::Borrowed(_))); + assert_eq!(*whole, record); + assert_eq!(*installed_files(tmp.path(), purl, &record).await, record); + } + + /// With a record for the copy's own platform in the manifest, that + /// record alone is the copy's for every reader that selects records: + /// the ruby-platform record, which would match a JRuby copy by taking + /// no file of it, is not selected beside it. Without one, or when the + /// copy's own record is for other bytes, the selection is as it was. + #[tokio::test] + async fn a_copys_own_platform_record_is_selected_alone() { + use crate::patch::apply::{select_installed_variants, select_installed_variants_any}; + let tmp = tempfile::tempdir().unwrap(); + let copy = jvm_gem(&tmp.path().join("jruby")); + let ruby = "pkg:gem/a@1?platform=ruby"; + let own = "pkg:gem/a@1?platform=java"; + let c_only: HashMap = [( + "patches/lib/0001.patch".to_string(), + PatchFileInfo { + before_hash: String::new(), + after_hash: "5".repeat(64), + }, + )] + .into(); + let jar = |before: &[u8]| -> HashMap { + [( + "lib/a/a.jar".to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(before), + after_hash: "8".repeat(64), + }, + )] + .into() + }; + let (its_jar, another_jar) = (jar(b"PK jar"), jar(b"PK another jar")); + + // Alone, the ruby-platform record matches the copy. + assert_eq!( + select_installed_variants(©.gem_dir, &[(ruby, &c_only)]).await, + [0] + ); + // Beside the copy's own record it is not the copy's. + let both = [(ruby, &c_only), (own, &its_jar)]; + assert_eq!(select_installed_variants(©.gem_dir, &both).await, [1]); + assert_eq!( + select_installed_variants_any(std::slice::from_ref(©.gem_dir), &both).await, + [1] + ); + // An own-platform record written for other bytes does not match, + // and takes nothing from the record that does. + let other_bytes = [(ruby, &c_only), (own, &another_jar)]; + assert_eq!( + select_installed_variants(©.gem_dir, &other_bytes).await, + [0] + ); + // A copy of another platform keeps what it matched. + let mri = precompiled_gem(&tmp.path().join("mri")); + let c_source: HashMap = [( + "ext/a/a.c".to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(b"int a;"), + after_hash: "2".repeat(64), + }, + )] + .into(); + let for_mri = [(ruby, &c_source), (own, &its_jar)]; + assert_eq!(select_installed_variants(&mri.gem_dir, &for_mri).await, [0]); + // Over both copies, each takes its own. + assert_eq!( + select_installed_variants_any(&[mri.gem_dir.clone(), copy.gem_dir.clone()], &for_mri) + .await, + [0, 1] + ); + } + + /// A `java` gem that declares extensions is no JVM build of a gem: its + /// record is read whole and classified like that of any gem RubyGems + /// built, so a C source of it is a build input that needs a rebuild. + #[tokio::test] + async fn a_java_gem_that_builds_an_extension_is_not_read_file_by_file() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("jruby"); + let gem_dir = home.join("gems/a-1-java"); + std::fs::create_dir_all(gem_dir.join("ext/a")).unwrap(); + std::fs::write(gem_dir.join("ext/a/a.c"), b"int a;").unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write( + home.join("specifications/a-1-java.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"a\".freeze\n \ + s.version = \"1\".freeze\n s.platform = \"java\".freeze\n \ + s.require_paths = [\"lib\".freeze]\n \ + s.extensions = [\"ext/a/extconf.rb\".freeze]\nend\n", + ) + .unwrap(); + let record: HashMap = [ + ("ext/a/a.c".to_string(), info(&"2".repeat(64))), + ("lib/a/gone.rb".to_string(), info(&"3".repeat(64))), + ] + .into(); + let gem = InstalledGem::at(&gem_dir).await; + assert!(gem.jvm().is_none()); + let purl = "pkg:gem/a@1?platform=ruby"; + assert_eq!(*gem.record_files(purl, &record).await, record); + assert_eq!(rollback_files(&gem_dir, purl, &record).await, record); + let scope = gem.scope(&record); + assert!(scope.builds_extensions); + assert_eq!(scope.inputs, ["ext/a/a.c"]); + // No marker: the extension was not built from the patched source. + assert_eq!( + gem.verify_native_build(purl, &record).await, + Err(NOT_REBUILT_REASON.to_string()) + ); + } + + /// `apply` on a JVM copy that takes no file of a record writes nothing + /// and says what that means in a typed caveat: the code is not in + /// that build (a patch of the C build alone, which leaves nothing to + /// do), or the record changes sources of the jars and the patch is + /// incomplete. Neither starts a Ruby or reads a blob. + #[tokio::test] + async fn a_jvm_copy_with_nothing_to_write_says_what_that_means() { + let tmp = tempfile::tempdir().unwrap(); + let copy = jvm_gem(&tmp.path().join("jruby")); + let blobs = tmp.path().join("blobs"); + let added = PatchFileInfo { + before_hash: String::new(), + after_hash: "5".repeat(64), + }; + let apply = |purl: &'static str, record: HashMap, rebuild: bool| { + let (copy, blobs, cwd) = (copy.clone(), blobs.clone(), tmp.path().to_path_buf()); + async move { + apply_gem_package_patch( + crate::utils::repo_root::ReadScope::Workspace, + purl, + ©.gem_dir, + &record, + &PatchSources::blobs_only(&blobs), + false, + MismatchPolicy::Strict, + &RubyEnv { + cwd, + rebuild, + offline: true, + progress: None, + }, + ) + .await + } + }; + let ruby_purl = "pkg:gem/a@1?platform=ruby"; + let c_only: HashMap = + [("patches/lib/0001.patch".to_string(), added.clone())].into(); + + let applied = apply(ruby_purl, c_only.clone(), true).await; + assert!(applied.result.success, "{:?}", applied.result.error); + assert!(applied.result.files_verified.is_empty()); + assert!(applied.result.files_patched.is_empty()); + assert_eq!(applied.result.error, None); + assert_eq!(applied.warning, None); + let Some(GemCaveat::NotInBuild(detail)) = applied.caveat else { + panic!("no not-in-build caveat: {:?}", applied.caveat); + }; + assert!( + detail.contains( + "none of the patch's files are part of the JRuby build of this gem (a-1-java)" + ), + "{detail}" + ); + + // A Java source the copy does not ship: the jars may hold it. The + // patch is incomplete, and it is whoever compiles: the flag that + // leaves compiling to the caller leaves nothing to compile here. + let java_only: HashMap = + [("ext/java/a/Gone.java".to_string(), info(&"7".repeat(64)))].into(); + for rebuild in [true, false] { + let applied = apply(ruby_purl, java_only.clone(), rebuild).await; + // The result is not a failure: nothing here undoes anything. + assert!(applied.result.success, "rebuild={rebuild}"); + assert_eq!(applied.result.error, None); + let Some(GemCaveat::Incomplete(detail)) = applied.caveat else { + panic!("no incomplete caveat: {:?}", applied.caveat); + }; + assert!( + detail.contains(JARS_NOT_REBUILT) && detail.contains("Nothing was written"), + "{detail}" + ); + // The warning says the same, after the purl. + assert_eq!( + applied.warning, + Some(( + NOT_REBUILT_REASON.to_string(), + format!("{ruby_purl}: {detail}") + )) + ); + } + + // The same record written for the copy's own platform is applied + // strictly: the file it adds is to be written, and with no blob to + // write it from, that fails. It carries no caveat. + let applied = apply("pkg:gem/a@1?platform=java", c_only, true).await; + assert!(!applied.result.success); + assert_eq!(applied.caveat, None); + } + + /// The text of an incomplete patch says that the files were written, + /// which sources are in no compiled code and why, and carries no purl: + /// the caller puts it after one (the warning, the `Error:` line) or + /// beside one (the event). A dry run says what `apply` would leave. + #[test] + fn the_incomplete_text_says_what_was_written_and_what_is_not_in_effect() { + let wet = not_compiled_detail("ext/a/a.c", "the build read none of it", false); + assert!( + wet.starts_with("the patch's files were written, but its native-extension sources (ext/a/a.c) are not in the compiled code this install runs: the build read none of it."), + "{wet}" + ); + assert!(wet.contains("vex does not attest the patch"), "{wet}"); + let dry = not_compiled_detail("ext/a/a.c", "the build read none of it", true); + assert!( + dry.starts_with("dry run: apply would write the patch's files, but"), + "{dry}" + ); + assert!(dry.contains("would not be in the compiled code"), "{dry}"); + let applied = GemApplied::incomplete( + untouched_result("pkg:gem/a@1", Path::new("/h/gems/a-1"), None), + "pkg:gem/a@1", + wet.clone(), + ); + assert!(applied.result.success); + assert_eq!(applied.caveat, Some(GemCaveat::Incomplete(wet.clone()))); + assert_eq!( + applied.warning, + Some(( + NOT_REBUILT_REASON.to_string(), + format!("pkg:gem/a@1: {wet}") + )) + ); + } + /// A build system's manifest is an input wherever it sits, and a gem /// that requires from its root says nothing about any file. #[test] @@ -7230,12 +8482,13 @@ mod tests { ), ] .into(); - let (scope, found) = scope_of(©.gem_dir, &record).await; - assert!(found.is_some()); + let gem = InstalledGem::at(©.gem_dir).await; + assert!(gem.copy.is_some()); + let scope = gem.scope(&record); assert_eq!(scope.inputs, ["ext/a/a.c", "patches/0001.patch"]); assert_eq!(scope.precompiled.as_deref(), Some("arm64-darwin")); assert_eq!( - verify_native_build(©.gem_dir, &record).await, + verify_native_build(©.gem_dir, "pkg:gem/a@1", &record).await, Err(NOT_REBUILT_REASON.to_string()), "patched sources over the prebuilt binary attest nothing" ); @@ -7267,19 +8520,26 @@ mod tests { marker.lib_artifacts.keys().collect::>(), ["lib/a/3.4/a.bundle"] ); - assert_eq!(verify_native_build(©.gem_dir, &record).await, Ok(())); + assert_eq!( + verify_native_build(©.gem_dir, "pkg:gem/a@1", &record).await, + Ok(()) + ); // Another record, or a binary that is no longer the built one. let mut other = record.clone(); other.get_mut("ext/a/a.c").unwrap().after_hash = "e".repeat(64); - assert!(verify_native_build(©.gem_dir, &other).await.is_err()); + assert!(verify_native_build(©.gem_dir, "pkg:gem/a@1", &other) + .await + .is_err()); std::fs::write(&target, b"reinstalled").unwrap(); - assert!(verify_native_build(©.gem_dir, &record).await.is_err()); + assert!(verify_native_build(©.gem_dir, "pkg:gem/a@1", &record) + .await + .is_err()); std::fs::write(&target, b"rebuilt").unwrap(); // Rollback: the added file is removed (an empty `beforeHash`), the // one the copy shipped is restored. - let undo = rollback_files(©.gem_dir, &record).await; + let undo = rollback_files(©.gem_dir, "pkg:gem/a@1", &record).await; assert_eq!(undo["patches/0001.patch"].before_hash, ""); assert_eq!(undo["ext/a/a.c"], record["ext/a/a.c"]); let env = RubyEnv { @@ -7298,7 +8558,10 @@ mod tests { } assert!(!copy.gem_dir.join(MARKER_FILE).exists()); assert!(!copy.gem_dir.join(BACKUP_DIR).exists()); - assert_eq!(rollback_files(©.gem_dir, &record).await, record); + assert_eq!( + rollback_files(©.gem_dir, "pkg:gem/a@1", &record).await, + record + ); assert_eq!(restore_original_build(©.gem_dir, &env).await, Ok(false)); } @@ -7681,20 +8944,13 @@ mod tests { let telling = discriminating_files(&built.gem_dir, "pkg:gem/a@1", &removed).await; assert!(telling.is_empty(), "{:?}", keys(&telling)); - // The JRuby build is not rebuilt from the source gem: a file it - // lacks still says the ruby record is not its record. - let java_home = tmp.path().join("java"); - let java_dir = java_home.join("gems/a-1-java"); - std::fs::create_dir_all(java_dir.join("lib")).unwrap(); - std::fs::create_dir_all(java_home.join("specifications")).unwrap(); - std::fs::write( - java_home.join("specifications/a-1-java.gemspec"), - "Gem::Specification.new do |s|\n s.name = \"a\".freeze\n \ - s.version = \"1\".freeze\n s.platform = \"java\".freeze\nend\n", - ) - .unwrap(); - let telling = discriminating_files(&java_dir, "pkg:gem/a@1", &record).await; - assert_eq!(keys(&telling), keys(&record)); + // The JRuby build is another archive of the same release: a C + // build input of the ruby record it does not ship says nothing + // about it. A file it ships tells, and so does a Ruby file it + // lacks (`a_jvm_copy_is_judged_by_the_files_it_takes`). + let java = jvm_gem(&tmp.path().join("java")); + let telling = discriminating_files(&java.gem_dir, "pkg:gem/a@1", &record).await; + assert_eq!(keys(&telling), ["ext/a/a.c", "lib/a/gone.rb"]); } /// A gem tree can come from the repository being scanned, so nothing in @@ -7983,7 +9239,7 @@ mod tests { }, )] .into(); - let (scope, _) = scope_of(©.gem_dir, &record).await; + let scope = InstalledGem::at(©.gem_dir).await.scope(&record); assert_eq!(built_state(©, &scope, &record), Built::No); // Ruby 3.4 runs `apply`: attested from here on. @@ -7996,7 +9252,10 @@ mod tests { assert!(back_up_prebuilt(©, &grafts, &[]).unwrap()); graft_binaries(©, &scope, &record, &grafts).unwrap(); assert_eq!(std::fs::read(&for_33).unwrap(), PREBUILT); - assert_eq!(verify_native_build(©.gem_dir, &record).await, Ok(())); + assert_eq!( + verify_native_build(©.gem_dir, "pkg:gem/a@1", &record).await, + Ok(()) + ); // Another Ruby may be the one running `apply` next: it is asked. assert_eq!( built_state(©, &scope, &record), @@ -8019,7 +9278,10 @@ mod tests { marker.lib_artifacts.keys().collect::>(), ["lib/a/3.3/a.bundle", "lib/a/3.4/a.bundle"] ); - assert_eq!(verify_native_build(©.gem_dir, &record).await, Ok(())); + assert_eq!( + verify_native_build(©.gem_dir, "pkg:gem/a@1", &record).await, + Ok(()) + ); // Every binary the gem ships is grafted: no Ruby is left to ask. assert_eq!(built_state(©, &scope, &record), Built::Yes); @@ -8027,7 +9289,7 @@ mod tests { // reinstalled over it): the marker attests nothing. std::fs::write(&for_33, PREBUILT).unwrap(); assert_eq!( - verify_native_build(©.gem_dir, &record).await, + verify_native_build(©.gem_dir, "pkg:gem/a@1", &record).await, Err(NOT_REBUILT_REASON.to_string()) ); assert_eq!(built_state(©, &scope, &record), Built::No); diff --git a/crates/socket-patch-core/src/vex/build.rs b/crates/socket-patch-core/src/vex/build.rs index 8446de398..885fd5122 100644 --- a/crates/socket-patch-core/src/vex/build.rs +++ b/crates/socket-patch-core/src/vex/build.rs @@ -87,11 +87,66 @@ pub fn build_document_marking_unverified( unverified: &[String], opts: &BuildOptions, ) -> Option { + build_document_with( + manifest, + &Attested { + applied, + vendored, + redirected, + unverified, + code_not_present: &[], + }, + opts, + ) +} + +/// The PURLs a document attests, and on what basis each is attested. +#[derive(Debug, Clone, Copy, Default)] +pub struct Attested<'a> { + /// Every attested PURL. + pub applied: &'a [String], + /// Attested from the committed vendor artifact ([`build_document`]). + pub vendored: &'a [String], + /// Attested from hosted wiring ([`build_document`]). + pub redirected: &'a [String], + /// Declared applied with nothing checked on disk + /// ([`build_document_marking_unverified`]). + pub unverified: &'a [String], + /// Attested with nothing applied: no file of the patch is part of any + /// installed build of the package + /// ([`VerifyOutcome::code_not_present`](crate::vex::verify::VerifyOutcome::code_not_present)). + pub code_not_present: &'a [String], +} + +/// What the impact statement says of a PURL in +/// [`Attested::code_not_present`], before the patch's uuid. +pub const CODE_NOT_PRESENT_PREFIX: &str = + "The code this vulnerability is in is not in the installed build of the package: no file of \ + Socket patch"; + +/// [`build_document_marking_unverified`], where the PURLs in +/// `attested.code_not_present` are not affected because the code the patch +/// changes is not in any installed build of the package, with no patch +/// applied to them. Their impact-statement part says so and names the +/// patch whose files were looked for. A statement all of whose PURLs are +/// of that kind carries the justification `vulnerable_code_not_present`; +/// any other keeps `inline_mitigations_already_exist`, with one part per +/// PURL saying which is which. With no such PURL the document is +/// [`build_document_marking_unverified`]'s, byte for byte. +pub fn build_document_with( + manifest: &PatchManifest, + attested: &Attested<'_>, + opts: &BuildOptions, +) -> Option { + fn set(purls: &[String]) -> HashSet<&str> { + purls.iter().map(String::as_str).collect() + } let timestamp = now_rfc3339(); - let applied_set: HashSet<&str> = applied.iter().map(String::as_str).collect(); - let vendored_set: HashSet<&str> = vendored.iter().map(String::as_str).collect(); - let redirected_set: HashSet<&str> = redirected.iter().map(String::as_str).collect(); - let unverified_set: HashSet<&str> = unverified.iter().map(String::as_str).collect(); + let applied_set = set(attested.applied); + let vendored_set = set(attested.vendored); + let redirected_set = set(attested.redirected); + let unverified_set = set(attested.unverified); + let code_not_present_set = set(attested.code_not_present); // vuln-id -> (aliases, impact-statement parts, subcomponent PURLs) // BTreeMap/BTreeSet keep every output field sorted, which keeps @@ -103,11 +158,20 @@ pub fn build_document_marking_unverified( if !applied_set.contains(purl.as_str()) { continue; } + // A basis that rests on the patch's own artifact (vendored, + // redirected) or on no check at all comes first: nothing was + // looked for in an installed build then. + let code_not_present = code_not_present_set.contains(purl.as_str()) + && !vendored_set.contains(purl.as_str()) + && !redirected_set.contains(purl.as_str()) + && !unverified_set.contains(purl.as_str()); for (vuln_id, info) in &record.vulnerabilities { let entry = grouped.entry(vuln_id.clone()).or_default(); entry.aliases.extend(info.cves.iter().cloned()); entry.subcomponents.insert(purl.clone()); - let mut part = if vendored_set.contains(purl.as_str()) { + let mut part = if code_not_present { + format!("{CODE_NOT_PRESENT_PREFIX} {} is part of it", record.uuid) + } else if vendored_set.contains(purl.as_str()) { format!("Patched via Socket patch {} (vendored)", record.uuid) } else if redirected_set.contains(purl.as_str()) { format!("Patched via Socket patch {} (redirected)", record.uuid) @@ -117,6 +181,7 @@ pub fn build_document_marking_unverified( if unverified_set.contains(purl.as_str()) { part.push_str(NOT_VERIFIED_SUFFIX); } + entry.patched |= !code_not_present; entry.impact_parts.insert(part); } } @@ -170,7 +235,13 @@ pub fn build_document_marking_unverified( }], status: Status::NotAffected, supplier: None, - justification: Some(Justification::InlineMitigationsAlreadyExist), + // A patch in place for any subcomponent is a mitigation; with + // none, the statement rests on the code not being there. + justification: Some(if group.patched { + Justification::InlineMitigationsAlreadyExist + } else { + Justification::VulnerableCodeNotPresent + }), impact_statement, action_statement: None, }); @@ -194,6 +265,8 @@ struct VulnGroup { aliases: BTreeSet, subcomponents: BTreeSet, impact_parts: BTreeSet, + /// Some subcomponent is attested because a patch is in place. + patched: bool, } #[cfg(test)] @@ -954,4 +1027,153 @@ mod tests { )) ); } + + /// A package attested because no file of its patch is part of any + /// installed build is not a patched package: the statement says that + /// the vulnerable code is not present, names the patch whose files + /// were looked for, and never says "Patched via". + #[test] + fn code_not_present_is_stated_as_such() { + let mut manifest = PatchManifest::new(); + let purl = "pkg:gem/nokogiri@1.18.10?platform=ruby".to_string(); + manifest.patches.insert( + purl.clone(), + record("u-c", vec![("GHSA-cccc", vec!["CVE-2026-3"])]), + ); + let applied = vec![purl.clone()]; + let doc = build_document_with( + &manifest, + &Attested { + applied: &applied, + code_not_present: &applied, + ..Attested::default() + }, + &opts(), + ) + .unwrap(); + assert_eq!(doc.statements.len(), 1); + let st = &doc.statements[0]; + assert_eq!(st.status, Status::NotAffected); + assert_eq!( + st.justification, + Some(Justification::VulnerableCodeNotPresent) + ); + let impact = st.impact_statement.as_deref().unwrap(); + assert_eq!( + impact, + "The code this vulnerability is in is not in the installed build of the package: \ + no file of Socket patch u-c is part of it" + ); + assert!(!impact.contains("Patched via"), "{impact}"); + assert_eq!(st.products[0].subcomponents[0].id, purl); + + // Without the mark the document is the usual one, byte for byte. + let untimed = |doc: Option| { + let mut doc = doc.unwrap(); + doc.timestamp = String::new(); + for st in &mut doc.statements { + st.timestamp = None; + } + serde_json::to_string(&doc).unwrap() + }; + assert_eq!( + untimed(build_document_with( + &manifest, + &Attested { + applied: &applied, + ..Attested::default() + }, + &opts() + )), + untimed(build_document(&manifest, &applied, &[], &[], &opts())) + ); + } + + /// One statement covers every package of a vulnerability. When one of + /// them is patched, a mitigation is in place and the justification + /// says so; the impact statement still says of each package what is + /// true of it. A basis that rests on the patch's own artifact + /// (vendored, redirected) or on no check keeps its own wording. + #[test] + fn code_not_present_beside_a_patched_package_keeps_the_mitigation_justification() { + let mut manifest = PatchManifest::new(); + let absent = "pkg:gem/nokogiri@1.18.10?platform=ruby".to_string(); + let patched = "pkg:gem/other@1.0.0".to_string(); + manifest + .patches + .insert(absent.clone(), record("u-c", vec![("GHSA-cccc", vec![])])); + manifest + .patches + .insert(patched.clone(), record("u-p", vec![("GHSA-cccc", vec![])])); + let applied = vec![absent.clone(), patched.clone()]; + let not_present = vec![absent.clone()]; + let doc = build_document_with( + &manifest, + &Attested { + applied: &applied, + code_not_present: ¬_present, + ..Attested::default() + }, + &opts(), + ) + .unwrap(); + assert_eq!(doc.statements.len(), 1); + let st = &doc.statements[0]; + assert_eq!( + st.justification, + Some(Justification::InlineMitigationsAlreadyExist) + ); + let impact = st.impact_statement.as_deref().unwrap(); + assert!(impact.contains("Patched via Socket patch u-p"), "{impact}"); + assert!( + impact.contains("no file of Socket patch u-c is part of it"), + "{impact}" + ); + assert!(!impact.contains("Patched via Socket patch u-c"), "{impact}"); + + for (vendored, redirected, unverified, wording) in [ + ( + ¬_present[..], + &[][..], + &[][..], + "Patched via Socket patch u-c (vendored)", + ), + ( + &[][..], + ¬_present[..], + &[][..], + "Patched via Socket patch u-c (redirected)", + ), + ( + &[][..], + &[][..], + ¬_present[..], + "Patched via Socket patch u-c; not verified", + ), + ] { + let doc = build_document_with( + &manifest, + &Attested { + applied: ¬_present, + vendored, + redirected, + unverified, + code_not_present: ¬_present, + }, + &opts(), + ) + .unwrap(); + let st = &doc.statements[0]; + assert_eq!( + st.justification, + Some(Justification::InlineMitigationsAlreadyExist), + "{wording}" + ); + assert!( + st.impact_statement.as_deref().unwrap().contains(wording), + "{:?}", + st.impact_statement + ); + } + } } diff --git a/crates/socket-patch-core/src/vex/mod.rs b/crates/socket-patch-core/src/vex/mod.rs index a9e511f30..615676ba9 100644 --- a/crates/socket-patch-core/src/vex/mod.rs +++ b/crates/socket-patch-core/src/vex/mod.rs @@ -25,7 +25,8 @@ pub mod time; pub mod verify; pub use build::{ - build_document, build_document_marking_unverified, BuildOptions, NOT_VERIFIED_SUFFIX, + build_document, build_document_marking_unverified, build_document_with, Attested, BuildOptions, + CODE_NOT_PRESENT_PREFIX, NOT_VERIFIED_SUFFIX, }; pub use discover::{ discover_patched_refs, discover_patched_refs_in, discover_patched_refs_with, Diag, diff --git a/crates/socket-patch-core/src/vex/verify.rs b/crates/socket-patch-core/src/vex/verify.rs index 866d7269e..8be01fe27 100644 --- a/crates/socket-patch-core/src/vex/verify.rs +++ b/crates/socket-patch-core/src/vex/verify.rs @@ -61,6 +61,13 @@ 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)>, + /// 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 + /// extension). The code the patch changes is not present, which is + /// what the statement must say: it is not a mitigation that was put + /// in place. + pub code_not_present: Vec, } /// Vendored-patch context for [`applied_patches_with_vendor`]. @@ -220,7 +227,14 @@ pub async fn applied_patches_with_copies( } first_failure.map_or(Ok(()), Err) } else if Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) { - verify_every_gem_copy(paths, record).await + match verify_every_gem_copy(purl, paths, record).await { + Ok(GemVerdict::CodeNotPresent) => { + out.code_not_present.push(purl.clone()); + Ok(()) + } + Ok(GemVerdict::Patched) => Ok(()), + Err(reason) => Err(reason), + } } else { verify_every_copy(paths, record).await } @@ -318,10 +332,18 @@ pub async fn applied_patches_with_copies( /// [`installed_copies`](crate::crawlers::gradle_cache::installed_copies): /// every hash directory holding a record file must verify. pub async fn verify_patch_record(pkg_path: &Path, record: &PatchRecord) -> Result<(), String> { - if record.files.is_empty() { + verify_patch_files(pkg_path, &record.files).await +} + +/// [`verify_patch_record`] over a record's `files`. +async fn verify_patch_files( + pkg_path: &Path, + files: &HashMap, +) -> Result<(), String> { + if files.is_empty() { return Err("no_files".to_string()); } - for (dir, files) in crate::crawlers::gradle_cache::installed_copies(pkg_path, &record.files) { + for (dir, files) in crate::crawlers::gradle_cache::installed_copies(pkg_path, files) { let mut keys: Vec<&String> = files.keys().collect(); keys.sort(); for file_name in keys { @@ -489,12 +511,57 @@ async fn verify_every_copy(paths: &[PathBuf], record: &PatchRecord) -> Result<() /// A copy holding the patched sources over the install-time build is /// `native_extension_not_rebuilt`. Hosted copies are judged without this: /// RubyGems compiled the patched gem when Bundler installed it. -async fn verify_every_gem_copy(paths: &[PathBuf], record: &PatchRecord) -> Result<(), String> { +/// +/// A copy is judged by the files of the record `purl` it takes +/// ([`InstalledGem::record_files`](crate::patch::gem_ext::InstalledGem::record_files)): +/// the JVM build of a gem, which JRuby installs, has no use for what only +/// a C build reads, and `apply` writes none of the ruby-platform record's +/// there. Its gemspec is read once for both questions. +/// +/// Two outcomes of that are meant. A JVM copy that takes no file of the +/// record, or only a C source nothing there compiles, passes: the code +/// the patch fixes is not in that build, and a copy installed from the +/// patched `java` gem gets the same verdict. And a C build input that was +/// deleted from the copy is not held against it, because it reads as one +/// the build never had: nothing here knows the `java` gem's file list, +/// and failing a patch that is applied is the worse error. (Any other +/// file the record replaces must be there: a missing Ruby file fails.) +/// +/// When no copy takes any file of the record, nothing was applied +/// anywhere and the verdict says so ([`GemVerdict::CodeNotPresent`]): the +/// statement is then about code that is not present, not about a patch +/// that was put in place. +async fn verify_every_gem_copy( + purl: &str, + paths: &[PathBuf], + record: &PatchRecord, +) -> Result { + use crate::patch::gem_ext::InstalledGem; + if record.files.is_empty() { + return Err("no_files".to_string()); + } + let mut verdict = GemVerdict::CodeNotPresent; for path in paths { - verify_patch_record(path, record).await?; - crate::patch::gem_ext::verify_native_build(path, &record.files).await?; + let gem = InstalledGem::at(path).await; + let files = gem.record_files(purl, &record.files).await; + if !files.is_empty() { + verify_patch_files(path, &files).await?; + verdict = GemVerdict::Patched; + } + gem.verify_native_build(purl, &record.files).await?; } - Ok(()) + Ok(verdict) +} + +/// Why the installed copies of a gem pass ([`verify_every_gem_copy`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum GemVerdict { + /// Some copy holds the patch's files, and every copy that takes any + /// of them holds them patched. + Patched, + /// No copy takes any file of the patch: the code it changes is in no + /// build installed here. + CodeNotPresent, } /// [`HostedCopies`] verdict: no consumed copy is `package_not_found`; every @@ -2966,4 +3033,105 @@ mod tests { .trim_start_matches(['/', '.']) .to_string() } + + /// A hand-laid JRuby copy of the gem `a` (its `java` platform build): + /// a Ruby file and the jar it runs. + fn jruby_gem(home: &Path) -> PathBuf { + let gem_dir = home.join("gems/a-1-java"); + std::fs::create_dir_all(gem_dir.join("lib/a")).unwrap(); + std::fs::write(gem_dir.join("lib/a.rb"), b"patched").unwrap(); + std::fs::write(gem_dir.join("lib/a/a.jar"), b"PK jar").unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write( + home.join("specifications/a-1-java.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"a\".freeze\n \ + s.version = \"1\".freeze\n s.platform = \"java\".freeze\n \ + s.require_paths = [\"lib\".freeze]\nend\n", + ) + .unwrap(); + gem_dir + } + + /// A JRuby copy that takes no file of a ruby-platform record is + /// attested, and the outcome says on what basis: the code the patch + /// changes is not present. A copy that holds a patched file of the + /// record is patched, with one copy of each the package is patched, + /// and a Ruby file the copy lacks is a missing file, not absent code. + #[tokio::test] + async fn a_gem_copy_with_none_of_the_patchs_code_is_code_not_present() { + let tmp = tempfile::tempdir().unwrap(); + let jruby = jruby_gem(&tmp.path().join("jruby")); + let purl = "pkg:gem/a@1?platform=ruby".to_string(); + let file = |before: &str, after: &str| PatchFileInfo { + before_hash: before.to_string(), + after_hash: after.to_string(), + }; + let record_of = |files: &[(&str, PatchFileInfo)]| { + let mut record = record_with_one_file("unused"); + record.files = files + .iter() + .map(|(key, info)| (key.to_string(), info.clone())) + .collect(); + record + }; + let outcome = |record: PatchRecord, copies: Vec| { + let purl = purl.clone(); + async move { + let mut manifest = PatchManifest::new(); + manifest.patches.insert(purl.clone(), record); + let copies = HashMap::from([(purl, copies)]); + applied_patches_with_copies(&manifest, &copies, None).await + } + }; + let patched_hash = compute_git_sha256_from_bytes(b"patched"); + + // A patch to the C build alone: nothing of it is in the JRuby gem. + let c_only = record_of(&[ + ("patches/lib/0001.patch", file("", "bbbb")), + ("ext/a/a.c", file("aaaa", "bbbb")), + ]); + let out = outcome(c_only.clone(), vec![jruby.clone()]).await; + assert_eq!(out.applied, vec![purl.clone()]); + assert_eq!(out.code_not_present, vec![purl.clone()]); + + // A record whose Ruby file the copy holds patched: patched. + let with_ruby = record_of(&[ + ("lib/a.rb", file("aaaa", &patched_hash)), + ("patches/lib/0001.patch", file("", "bbbb")), + ]); + let out = outcome(with_ruby.clone(), vec![jruby.clone()]).await; + assert_eq!(out.applied, vec![purl.clone()]); + assert!(out.code_not_present.is_empty()); + + // The same package in two homes, one of which holds the patch. + let mri = tmp.path().join("mri/gems/a-1"); + std::fs::create_dir_all(mri.join("patches/lib")).unwrap(); + std::fs::create_dir_all(mri.join("lib")).unwrap(); + std::fs::write(mri.join("lib/a.rb"), b"patched").unwrap(); + std::fs::write(mri.join("patches/lib/0001.patch"), b"p").unwrap(); + let both = record_of(&[ + ("lib/a.rb", file("aaaa", &patched_hash)), + ( + "patches/lib/0001.patch", + file("", &compute_git_sha256_from_bytes(b"p")), + ), + ]); + let out = outcome(both, vec![jruby.clone(), mri]).await; + assert_eq!(out.applied, vec![purl.clone()]); + assert!(out.code_not_present.is_empty()); + + // A Ruby file the JRuby copy lacks is missing: the patch is not + // applied, and nothing is said about absent code. + let deleted = record_of(&[("lib/a/gone.rb", file("aaaa", "bbbb"))]); + let out = outcome(deleted, vec![jruby]).await; + assert!(out.applied.is_empty()); + assert!(out.code_not_present.is_empty()); + assert_eq!( + out.failed, + vec![FailedPatch { + purl: purl.clone(), + reason: "file_not_found".to_string(), + }] + ); + } } diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 236ad6665..b1ec79021 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2373,8 +2373,43 @@ mirror of rubygems.org, set `SOCKET_RUBYGEMS_URL` to it. The mirror must be reac (plain `http` is accepted only for a mirror on the same machine, such as `http://localhost:9292`, and such a request never goes through a proxy): the gem's build scripts run, so its archive and checksum are not fetched over a connection someone else could rewrite. Credentials in the URL -are never printed. The JRuby (`-java`) build of a gem ships -jars and is always refused for such a patch. +are never printed. + +JRuby is different. It installs a gem's `java` build (`nokogiri-1.18.10-java`), which runs jars +and has no C extension, so `apply` builds nothing there and needs no compiler. (A `java` gem that +does compile something when it is installed, such as jruby-launcher, is rebuilt like any other +gem with an extension.) Patches are written for the gem's `ruby` build, and on JRuby `apply` +takes from such a patch what is part of the `java` build: + +- A file the patch changes is updated when the installed gem has it: the gem's Ruby code, and + also a C source the `java` gem ships, though nothing on JRuby compiles it. +- A file that only a C build reads is skipped when the installed gem doesn't have it: a C + source or build file, or anything under `ext/`, `patches/` or `ports/`. So is a new file of + that kind, such as a new C source or a new `patches/libxml2/*.patch`. +- Every other file the patch changes must be there. A Ruby file that is missing from the + installed gem is an error, as it is in any other gem: `apply` fails and changes nothing. + +The patch then counts as applied: `apply --check` reports it in sync, `vex` attests it, and +`rollback` restores the files `apply` changed. When no file of a patch is part of the `java` +build (a patch to the libxml2 that nokogiri packs for its C extension), the vulnerable code is not +in that build at all. `apply` exits 0, changes nothing and prints a note saying so (a `skipped` +event with `not_in_platform_build` under `--json`). Nothing was patched, so `vex` says what is +true instead: the vulnerability is `not_affected` with the justification +`vulnerable_code_not_present`. `rollback` reports that there was nothing to restore. + +The one exception is a patch that changes what the gem's jars are built from (a Java, Kotlin or +Scala source, or a Maven, Ant or Gradle build file) and doesn't bring the rebuilt jars. `apply` +can't rebuild a jar, so that patch is incomplete: `apply` writes the patch's files, leaves them +written, and exits 1 with an error that says the jars are not the patch's +(`native_extension_not_rebuilt`). Neither `apply --check` nor `vex` reports the gem as patched. +A patch that replaces a jar itself is different: the patched jar is what JRuby loads, so the +patch is applied and attested like any other, along with any source it changes beside the jar. + +A patch written for the `java` build itself (its purl carries `?platform=java`) is applied whole, +like a patch for any other gem: every file it changes must be in the installed gem. When the +manifest has both that patch and the one for the gem's `ruby` build, only the `java` one belongs +to a JRuby install. `apply` doesn't apply the other one there, and `apply --check`, `vex` and +`rollback` don't look for it there either. A gem that builds a library into its own directory and loads it from there (an FFI gem such as scrypt, a Rakefile build such as digest-crc) is always rebuilt from its installed tree. The @@ -2392,14 +2427,17 @@ patch changes and left compiled code. How a gem builds depends on its configurat installed with `--use-system-libraries` links the operating system's libxml2 and never opens the copy it packs, so a patch that only adds a fix to that packed copy changes nothing there. A gem whose build script downloads the binary it runs (passenger's agent) compiles nothing at all. -`apply` then writes the patch's files, leaves the compiled code as it was installed, and warns -with `native_extension_not_rebuilt`, instead of reporting a patch that is in no compiled code: +The patch is then incomplete, and `apply` says so instead of reporting a patch that is in no +compiled code. It writes the patch's files, leaves the compiled code as it was installed, and +exits 1 with `Error: Patch of is incomplete: …` (`native_extension_not_rebuilt`): -- The patch's Ruby files are in effect, and a source the gem compiles later on its own is the - patched one. +- The patch's files stay written: its Ruby files are in effect, and a source the gem compiles + later on its own is the patched one. Nothing is rolled back for you; `rollback` undoes it. - `apply --check` reports the package as not in sync, and `vex` does not attest the patch. +- A gem installed in more than one place counts as patched only when no copy is incomplete. - On a system-libraries install the library is the operating system's package, and updating that package is what fixes it. +- `scan --mode agent` and `get` exit 1 for such a patch as well, and keep it recorded. A patch to the gem's own C sources is rebuilt as usual. On Linux the check asks the kernel which files the build opened. Elsewhere it needs a filesystem that records file reads; on one that diff --git a/tests/docker/Dockerfile.jruby b/tests/docker/Dockerfile.jruby new file mode 100644 index 000000000..fa989703a --- /dev/null +++ b/tests/docker/Dockerfile.jruby @@ -0,0 +1,72 @@ +# JRuby test image: a JDK, JRuby from its release tarball, Bundler, git and +# curl. For the real-nokogiri harness (tests/nokogiri/nokogiri_e2e.rb) on +# JRuby, where Bundler installs a gem's `java` platform build: the copy +# whose compiled code is jars, and which `apply` patches without building +# anything. +# +# Unlike the other images here, this one holds no socket-patch: the binary +# under test is mounted, so the image does not need Dockerfile.base and is +# not rebuilt for a code change. It must be a Linux binary of the image's +# architecture (`cargo build -p socket-patch-cli` in a Linux container or +# on a Linux host). +# +# The base image is pinned by digest and the JRuby tarball by the sha256 +# its release publishes (the `.sha256` file beside it on Maven Central, +# where jruby.org's downloads come from). +# +# JRuby 9.4 is the Ruby 3.1 line and runs on Java 8 or newer. JRuby 10 +# (10.1 is the Ruby 4.0 line) needs Java 21 or newer, so it is built on +# another JDK: +# +# docker build -f tests/docker/Dockerfile.jruby -t socket-patch-test-jruby:9.4 tests/docker +# docker build -f tests/docker/Dockerfile.jruby -t socket-patch-test-jruby:10.1 \ +# --build-arg JDK_IMAGE=eclipse-temurin@sha256:884a2f8692cc1e2c7e21f95914adf0ae0eafee9a7eb663a12169cc44468256ec \ +# --build-arg JRUBY_VERSION=10.1.3.0 \ +# --build-arg JRUBY_SHA256=3d76fe1fce6aa9f56fd7efb1015a9db95a0aa6f95fe9ec868f9e75d9ddc1871c \ +# tests/docker +# +# Run the harness in it, with the binary and the script mounted read-only. +# The project it builds, and the gems Bundler installs for it, live in the +# container's own temp dir: +# +# docker run --rm \ +# -v "$PWD/tests/nokogiri:/e2e:ro" \ +# -v "$PWD/target/debug/socket-patch:/usr/local/bin/socket-patch:ro" \ +# -e SOCKET_NO_CONFIG=1 -e SOCKET_NO_UPDATE_CHECK=1 -e SOCKET_TELEMETRY_DISABLED=1 \ +# socket-patch-test-jruby:9.4 \ +# ruby /e2e/nokogiri_e2e.rb --socket-patch /usr/local/bin/socket-patch \ +# --nokogiri 1.18.10 --install java +# +# eclipse-temurin:17-jdk (multi-arch index digest, the one Dockerfile.sbt +# pins) by default; the digest above is eclipse-temurin:25-jdk. +ARG JDK_IMAGE=eclipse-temurin@sha256:5d6042fb8cdc14d614e4e421f52e3211fc5aeadddce44cbf9de8ed37c791f824 +FROM ${JDK_IMAGE} + +ARG JRUBY_VERSION=9.4.15.0 +ARG JRUBY_SHA256=c8b8c5a7a1581fdba3ba73f7c375f793f6528117b444cc6baf6fb29bbcf9696d + +# `ruby` is JRuby: the harness and Bundler's scripts start it by that name. +RUN set -eu; \ + if command -v apt-get >/dev/null 2>&1; then \ + apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl git tar gzip \ + && rm -rf /var/lib/apt/lists/*; \ + elif command -v microdnf >/dev/null 2>&1; then \ + microdnf install -y ca-certificates curl git tar gzip findutils && microdnf clean all; \ + fi; \ + curl -fsSL -o /tmp/jruby.tar.gz \ + "https://repo1.maven.org/maven2/org/jruby/jruby-dist/${JRUBY_VERSION}/jruby-dist-${JRUBY_VERSION}-bin.tar.gz"; \ + echo "${JRUBY_SHA256} /tmp/jruby.tar.gz" | sha256sum -c -; \ + mkdir -p /opt/jruby \ + && tar -xzf /tmp/jruby.tar.gz -C /opt/jruby --strip-components=1 \ + && rm /tmp/jruby.tar.gz; \ + ln -s /opt/jruby/bin/jruby /usr/local/bin/ruby + +ENV PATH=/opt/jruby/bin:$PATH \ + LANG=C.UTF-8 + +RUN jruby --version && gem --version \ + && (bundle --version || gem install bundler --no-document) \ + && bundle --version + +WORKDIR /workspace diff --git a/tests/docker/README.md b/tests/docker/README.md index dc2b4c8de..ee44409ef 100644 --- a/tests/docker/README.md +++ b/tests/docker/README.md @@ -98,3 +98,16 @@ for the tested PURLs — what's validated is that the crawler discovers real installed packages and the CLI dispatches correctly through the ecosystem. + +## JRuby image (`Dockerfile.jruby`) + +`Dockerfile.jruby` is not used by a `docker_e2e_*` suite. It is a JDK with +JRuby and Bundler, for running the real-nokogiri harness +(`tests/nokogiri/nokogiri_e2e.rb`) on JRuby on a machine that has neither: +Bundler installs nokogiri's `java` platform gem there, which `apply` +patches without building anything. The image holds no `socket-patch`. The +binary under test is mounted, so it needs no `Dockerfile.base` and is not +rebuilt after a code change. The header of the Dockerfile has the build +commands for JRuby 9.4 and 10.1 and the `docker run` line for the harness. +CI runs the same harness on both JRubies in `nokogiri-compatibility.yml`, +on the runner. diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index 35129706a..13322a175 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -28,14 +28,28 @@ # 1.6.7). nokogiri's build applies it to its vendored libxml2 and # compiles the patch's name into the extension. An install built # with `--use-system-libraries` compiles no vendored libxml2, so -# there the record's file is written, `apply` says that nothing -# compiles it, and nothing attests it. +# there the patch is incomplete: the record's file is written +# and stays written, `apply` fails (exit 1) and says that +# nothing compiles it, and nothing attests it. # # Each scenario runs `apply --check` (not in sync), `apply`, a load of # nokogiri through `bundle exec` in a fresh Ruby, `apply --check` (in sync), # `apply` again (nothing to do), `vex` and `rollback`, and then compares # every file of the gem home with the install it started from. # +# JRuby installs nokogiri's `java` platform gem, which runs jars and has no +# C extension and no libxml2. It takes of a record what is part of that +# build, and nothing is built there: +# +# ruby applied, as on any Ruby. +# c the `java` gem ships the C sources too (nothing compiles them), +# so the file is written and the patch is in sync and attested; +# JRuby loads no C constant and the jars it loaded before. +# libxml2 the `java` gem has no libxml2 patch directory: no file of the +# record is part of it. `apply` exits 0, writes nothing and says +# so, and the install is in sync and attested: the code the +# patch fixes is not in that build. +# # ruby tests/nokogiri/nokogiri_e2e.rb --socket-patch target/debug/socket-patch \ # --nokogiri 1.18.10 --install precompiled # @@ -272,8 +286,9 @@ def describe_install elsif lib == "system" then "system-libraries" else "source" end + loads = @java ? "#{@baseline['jars'].size} jars" : (@baseline["binary"] || "no native binary") puts "Installed #{@full_name}: #{@shape}, libxml2 #{@baseline['libxml_loaded']} (#{lib}), " \ - "#{@baseline['libxml_patches'].size} libxml2 patches, loads #{@baseline['binary'] || 'no native binary'}" + "#{@baseline['libxml_patches'].size} libxml2 patches, loads #{loads}" if @opts[:rails] puts "Rails #{@baseline['rails']} boots and sanitizes HTML through it: #{@baseline['rails_sanitize'].inspect}" check(@baseline["rails"].to_s.start_with?(@opts[:rails].sub(/\A[^0-9]*/, "")[/\A\d+\.\d+/]), @@ -284,6 +299,10 @@ def describe_install end want = @opts.fetch(:install) check(want == "any" || want == @shape, "the install is #{want}", "it is #{@shape}: #{@full_name}") + if @java + check(@baseline["jars"].keys.include?("nokogiri.jar") && @baseline["binary"].nil?, + "JRuby loads nokogiri's jars and no C extension", @baseline["jars"].keys.inspect) + end check(@baseline[RB_CONST].nil? && @baseline[C_CONST].nil?, "a fresh install carries no test marker") check(leftovers.empty?, "a fresh install holds nothing of socket-patch", leftovers.inspect) end @@ -400,6 +419,9 @@ def c_record def libxml2_patch_dir return "patches/libxml2" if File.directory?(File.join(@gem_dir, "patches")) return "ports/patches/libxml2" if File.directory?(File.join(@gem_dir, "ports", "patches")) + # The JRuby gem ships neither, and may ship no build script: the record + # is the one written for the ruby platform gem of a current release. + return "patches/libxml2" if @java && !File.file?(File.join(@gem_dir, "ext/nokogiri/extconf.rb")) # A precompiled gem ships neither; its build script still says which. extconf = installed("ext/nokogiri/extconf.rb") return "ports/patches/libxml2" if extconf =~ /File\.join\(portsdir, *"patches"/ @@ -420,15 +442,23 @@ def scenario(name) case name when "ruby" then applied(ruby_record, :native => false) { |now| now[RB_CONST] == 1 && now[C_CONST].nil? } when "c" - return skip("JRuby loads no C extension") && nil if @java && @opts[:build] == "ok" + # The JRuby gem ships the C source and compiles nothing: the file is + # written, no build is made, and JRuby loads what it loaded before. + if @java + return applied(c_record, :native => false, :what => "JRuby loads no C constant, and the jars it loaded before") do |now| + now[C_CONST].nil? && now[RB_CONST].nil? && now["jars"] == @baseline["jars"] + end + end native(c_record) { |now| now[C_CONST] == 1 } when "libxml2" record = libxml2_record return skip("this release reads no libxml2 patch directory") && nil unless record - return skip("JRuby loads no libxml2") && nil if @java && @opts[:build] == "ok" + # The JRuby gem packs no libxml2: nothing of the record is in it. + return not_in_build(record) if @java # Built against the system's libxml2: the build never opens the copy # the gem packs, so a patch to that copy is compiled into nothing. - # Its file is written, the run says so, and nothing attests it. + # Its file is written, the run fails and says so, and nothing + # attests it. # (Where the filesystem records no reads the CLI cannot tell, and the # leg says so with --unread-check off.) if @shape == "system-libraries" @@ -591,7 +621,6 @@ def native(record, &effect) case @opts.fetch(:build) when "ok" then applied(record, :native => true, &effect) when "unavailable" then not_applied(record, "native_extension_build_failed") - when "refused" then not_applied(record, "native_extensions_unsupported") end end @@ -601,9 +630,13 @@ def events(stdout) [] end + def event(stdout) + events(stdout).find { |e| e["purl"].to_s.start_with?("pkg:gem/nokogiri@#{@version}") } + end + def action(stdout) - event = events(stdout).find { |e| e["purl"].to_s.start_with?("pkg:gem/nokogiri@#{@version}") } - event ? event["action"] : nil + found = event(stdout) + found ? found["action"] : nil end # The `vex` statuses for nokogiri: `["not_affected"]` when the patch is @@ -619,7 +652,16 @@ def vex_statuses [code, statuses, stdout + stderr] end - def applied(record, native:, &effect) + # The statement of the `vex` document the last `vex_statuses` wrote that + # covers nokogiri, or `{}`. + def vex_statement + doc = JSON.parse(File.read(File.join(@proj, "vex.json"))) + (doc["statements"] || []).find { |s| s.to_s.include?("pkg:gem/nokogiri@#{@version}") } || {} + rescue Errno::ENOENT, JSON::ParserError + {} + end + + def applied(record, native:, what: "Ruby loads the patched code", &effect) write_record(record) code, stdout, stderr, = sp("apply", "--check", "--json") @@ -629,8 +671,17 @@ def applied(record, native:, &effect) check(code.zero? && action(stdout) == "applied", "`apply` applies it (#{secs.round}s)", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + # A JRuby gem is patched file by file: every file of the record it + # takes is on disk as the patch wrote it. + if @java + record.each do |path, (_, after)| + check(File.file?(File.join(@gem_dir, path)) && installed(path) == after, "#{path} is written") + end + check(leftovers.empty?, "nothing of a build was left in the gem home", leftovers.join("\n")) + end + now = probe - check(effect.call(now), "Ruby loads the patched code", JSON.pretty_generate(now)) + check(effect.call(now), what, JSON.pretty_generate(now)) check(now["smoke"] == @baseline["smoke"], "nokogiri still parses, queries, transforms and validates", "before #{@baseline['smoke'].inspect}\nafter #{now['smoke'].inspect}") if @opts[:rails] @@ -679,28 +730,89 @@ def not_applied(record, reason) check(code.zero?, "`rollback` of the unapplied record succeeds", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") end + # A record with no file in this install's build of the gem (the JRuby + # gem packs no libxml2, so a patch to it has nothing to change there): + # `apply` succeeds without writing anything and says why, in the event of + # the patch and, for a person, on stderr. The install counts as patched, + # because the code the patch fixes is not in it: `apply --check` is in + # sync and `vex` attests it. + def not_in_build(record) + write_record(record) + + code, stdout, stderr, secs = sp("apply", "--json") + found = event(stdout) || {} + check(code.zero? && found["action"] == "skipped" && found["errorCode"] == "not_in_platform_build", + "`apply` succeeds and reports the patch as not part of this build (#{secs.round}s)", + "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + check(found["reason"].to_s.include?("none of the patch's files are part of the JRuby build"), + "and says so in plain words", found["reason"].inspect) + check(warning_codes(stdout).empty?, "without a warning", warning_codes(stdout).inspect) + code, stdout, stderr, = sp("apply") + check(code.zero? && stderr.include?("none of the patch's files are part of the JRuby build"), + "a person reads the same on stderr, and the run exits 0", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + + diff = tree_diff(snapshot) + check(diff.empty?, "nothing of the install was changed", diff.join("\n")) + check(leftovers.empty?, "and nothing was left in the gem home", leftovers.join("\n")) + check(probe == @baseline, "Ruby loads what it loaded before") + + code, stdout, stderr, = sp("apply", "--check") + check(code.zero?, "`apply --check` is in sync", "exit #{code}\n#{stdout}#{stderr}") + code, statuses, text = vex_statuses + check(code.zero? && statuses == ["not_affected"], "`vex` attests the patch", "exit #{code} #{statuses.inspect}\n#{tail(text)}") + # Nothing was patched, and the statement does not say so: the code is + # not in this build. + statement = vex_statement + check(statement["justification"] == "vulnerable_code_not_present" && + statement["impact_statement"].to_s.include?("is not in the installed build of the package") && + !statement["impact_statement"].to_s.include?("Patched via"), + "as code that is not in this build, not as a patched package", statement.inspect) + + # `rollback` has nothing to restore, and says that. + code, stdout, stderr, = sp("rollback", "--json", "--dry-run") + found = event(stdout) || {} + check(code.zero? && found["action"] == "skipped" && found["errorCode"] == "not_in_platform_build", + "`rollback` reports that nothing of the patch was applied to this build", + "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + + rolled_back + end + def warning_codes(stdout) JSON.parse(stdout).fetch("warnings", []).map { |w| w["code"] } rescue JSON::ParserError [] end - # A record this install compiles nothing of: `apply` writes its files and - # says that no build holds them, Ruby loads the binary it loaded before, - # and neither `apply --check` nor `vex` takes the install for patched. + # A record this install compiles nothing of. The patch is incomplete: + # `apply` writes its files, which stay written, exits 1 and says that no + # build holds them (a `failed` event with `native_extension_not_rebuilt`, + # the warning of the same code, and an `Error:` line for a person). Ruby + # loads the binary it loaded before, and neither `apply --check` nor + # `vex` takes the install for patched. `rollback` takes the files out. def written_not_built(record) write_record(record) code, stdout, stderr, secs = sp("apply", "--json") + found = event(stdout) || {} warned = warning_codes(stdout).include?("native_extension_not_rebuilt") - check(code.zero? && action(stdout) == "applied" && warned, - "`apply` writes the patch and says that nothing compiles it (#{secs.round}s)", + check(code == 1 && found["action"] == "failed" && found["errorCode"] == "native_extension_not_rebuilt" && warned, + "`apply` fails: the patch is incomplete, because nothing compiles it (#{secs.round}s)", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + check(found["error"].to_s.include?("the patch's files were written"), + "and says that its files were written", found["error"].inspect) record.each do |path, (_, after)| check(File.file?(File.join(@gem_dir, path)) && installed(path) == after, "#{path} is written") end check(leftovers.empty?, "nothing of a build was left in the gem home", leftovers.join("\n")) check(probe == @baseline, "Ruby loads what it loaded before") + code, stdout, stderr, = sp("apply") + check(code == 1 && stderr.include?("is incomplete: the patch's files were written"), + "a person reads the same as an error, and the run exits 1", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + record.each do |path, (_, after)| + check(installed(path) == after, "#{path} stays written") + end + code, stdout, stderr, = sp("apply", "--check") check(code != 0, "`apply --check` does not report it in sync", "exit #{code}\n#{stdout}#{stderr}") _, statuses, text = vex_statuses @@ -720,7 +832,8 @@ def rolled_back # Loads nokogiri and prints one `sp_probe` line of JSON: what was loaded # and whether it works. Old and new releases name things differently - # (`libxml2_patches` before 1.11), and JRuby has no libxml2 at all. + # (`libxml2_patches` before 1.11), and JRuby has no libxml2 at all: what + # it loads is the gem's jars. PROBE = <<-'RUBY' require "json" require "digest" @@ -728,6 +841,11 @@ def rolled_back info = Nokogiri::VERSION_INFO lx = info["libxml"] || {} binary = $LOADED_FEATURES.grep(/nokogiri\.(bundle|so|dll)\z/).first +# The jars JRuby loaded (none on any other Ruby), each with its digest. +jars = {} +$LOADED_FEATURES.grep(/\.jar\z/).each do |jar| + jars[File.basename(jar)] = File.file?(jar) ? Digest::SHA256.file(jar).hexdigest : nil +end patches = lx["patches"] || lx["libxml2_patches"] || [] patches = patches.split(" ") if patches.is_a?(String) doc = Nokogiri::XML("onetwo") @@ -753,6 +871,7 @@ def rolled_back "binary" => binary && File.basename(File.dirname(binary)) + "/" + File.basename(binary), "binary_sha256" => binary && Digest::SHA256.file(binary).hexdigest, "loaded_from" => $LOADED_FEATURES.grep(%r{/nokogiri\.rb\z}).first, + "jars" => jars, "libxml_source" => lx["source"], "libxml_loaded" => lx["loaded"], "libxml_patches" => patches, @@ -792,9 +911,9 @@ class SocketPatchE2E < Rails::Application "libxml2), java, or any (default)") { |v| opts[:install] = v } o.on("--[no-]unread-check", "whether this filesystem records file reads (default: yes), which is what tells", "socket-patch that a system-libraries build read nothing of a libxml2 patch") { |v| opts[:unread_check] = v } - o.on("--build RESULT", %w[ok unavailable refused], + o.on("--build RESULT", %w[ok unavailable], "what a patch that needs a rebuild must do: ok (default), unavailable (no toolchain: fail,", - "change nothing), refused (a JRuby install)") { |v| opts[:build] = v } + "change nothing). A JRuby install builds nothing either way") { |v| opts[:build] = v } o.on("--hide-toolchain", "run socket-patch with no compiler or make on PATH (with --build unavailable)") do opts[:hide_toolchain] = true end