From dea2b45e8adabda7572fd95d6818b8ab9ef78d0d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 09:26:44 +0000 Subject: [PATCH 1/3] Start fix for platform-only gems in vendored scan Refs #2394 Assisted-by: Claude Code:claude-fable-5-2 From fdb8d80b3e3ba4077bbcf58d5e0fa69b6b9464f6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 09:52:05 +0000 Subject: [PATCH 2/3] Look up platform-only gems in every scan mode The scan's lockfile supplement named a gem that Gemfile.lock holds only as precompiled platform gems for a hosted run alone. That limit predates vendoring from prebuilt platform gems, so a vendored scan of a checkout with nothing installed never asked the patch service about such a gem: it was skipped without a message and the run ended with "Nothing left to patch." The supplement now names these gems in every mode. A vendored run vendors the gem from the lock alone, and an agent run counts it among the packages that are not installed. The stand-in patch service of the nokogiri end-to-end test now answers a lookup for the gem only when the run asks about it, as the service does, and the vendored scenario scans a checkout with nothing installed first. Fixes #2394 Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- crates/socket-patch-cli/src/commands/get.rs | 5 +- .../src/commands/scan/discovery.rs | 26 ++-- .../tests/e2e_redirect_gem_stale_install.rs | 139 ++++++++++++++++++ .../src/vendor/lock_inventory/gem.rs | 12 +- tests/nokogiri/nokogiri_e2e.rb | 25 ++++ tests/nokogiri/patch_service.rb | 8 + 7 files changed, 197 insertions(+), 20 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 3c5c1c75b7..5d042202f7 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -501,7 +501,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Throttling: bounded retry, then a reported failure.** Every patch-API JSON call (the batch query, the per-package patch lists, patch views and VEX record fetches, hosted package references) retries an HTTP `429` or `503` answer up to 3 times (`SOCKET_API_MAX_RETRIES=`, `0`-`10`; `0` = no retry). The wait honors `Retry-After` (delta-seconds or HTTP-date); a `Retry-After` over 30 s is not waited out — the answer is final at once — and one under the jittered first backoff step (`0`, a past date) waits that step instead. Without one it backs off 0.5 s / 1 s / 2 s (each step up to 8 s, with jitter in its upper half). All retries in one run share a 60 s wall-clock window that opens with the run's first retry: a retry whose wait would end after it closes is refused and the answer is final. Parallel requests wait in parallel, so each still gets its retries while the run adds at most about 60 s. Nothing else is retried (401/403 still drive the proxy fallback on the first answer; the public proxy's permanent `503 "Patch API is not configured"` is never retried on any path — the batch query still degrades to the per-package path at once, and a per-package lookup or patch view answering it is the same non-throttle failure it always was, which on the legacy per-package path leaves that package unanswered, see above), and a retried answer folds exactly where the first attempt's would have, so output is identical to an unthrottled run's. A request still throttled after that is a failure in the channel its siblings use: a failed batch is the human `Warning: API batch of failed: ` line and, under `--json`, a run-level `warnings[]` entry `{code: "api_batch_failed", detail: "API batch of failed: "}` (additive; `status` stays `success`, exit 0 — the other batches' packages are reported); a failed per-package patch-list query in the agent / hosted / vendored flows is the human `Warning: could not fetch details for : ` line and, under `--json`, `{code: "patch_details_failed", detail: "could not fetch details for : "}`. When every batch (or every patch-list query) fails, the existing all-failed error envelope and exit 1 apply. The error names the exhausted retry: `Rate limit exceeded (HTTP 429, gave up after 3 retries). Please try again later.` / `API request failed with status 503: (gave up after 3 retries)` (or `(Retry-After s exceeds the 30 s retry cap)` / `(the run's 60 s retry window has closed)`); with retries off it is the pre-retry text. On the token-less legacy per-package proxy path (a proxy without `POST /patch/batch`), a package still throttled (429 / over-capacity 503) after its retries is an unanswered package (see "No patches" needs an answer above): the batch's answered packages are used and it is reported as `patch_lookup_failed` (`partialFailure`, exit 1); when it leaves no package of its batch answered, the batch fails through the batch-failure channel above. Only a PURL the service itself refuses (its own `400`) is skipped individually. Pinned by `tests/scan_api_retry_e2e.rs` and the core crate's `tests/api_retry_e2e.rs`. -**Lockfile supplement (v3.4)**: `scan` discovery is no longer limited to installed trees. The project's lockfiles (`package-lock.json`/`npm-shrinkwrap.json`, `pnpm-lock.yaml` v9, `yarn.lock` classic + berry, `bun.lock`, `vlt-lock.json` (registry nodes, Socket-hosted pins included; vendored `file` nodes are left to the vendor ledger), `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`, `uv.lock`/`poetry.lock`/pinned `requirements.txt`) are inventoried and dependencies with NO installed copy join discovery — counts, the API lookup, the rows of what a hosted or vendored run patches (an agent or report-only run, which patches installed copies, gets a stderr note that they are not installed), and the prune "scanned" set (a wiped node_modules no longer prunes lockfile-listed entries). JSON gains a top-level `lockfileOnlyPackages` count and an additive `notInstalled: true` on matching `packages[]` entries. Agent mode partitions lockfile-only patches out BEFORE download (calm `skipped`/`package_not_installed` events — never an error exit, never a manifest write); vendored mode passes them through to the vendor engine's server download. Vendored-ledger entries likewise stay discoverable on a fresh clone (the committed artifact is the dependency). The `Gemfile.lock` inventory lists a gem by its ruby-platform entry; a gem the lock resolves ONLY as precompiled platform builds (`nokogiri (1.18.10-arm64-darwin)`, no `nokogiri (1.18.10)`) joins the supplement of a hosted run alone (`scan` / `get --mode hosted`, and the in-memory hosted engine), which can redirect it to its per-platform prebuilds from the lock; agent and vendored runs see it only through an installed copy, as before. Global scans (`--global`) get no supplement. **Rush monorepos** (no root lockfile, `rush.json` present): the npm-lock inventory falls back to the Rush source-of-truth locks — `common/config/rush/pnpm-lock.yaml` plus every `common/config/subspaces/*/pnpm-lock.yaml` (`read_dir`-sorted, repo-relative paths preserved) — so a Rush repo's dependencies still join discovery. **Plug'n'Play layouts are an explicit refusal, not an empty inventory**: a `.pnp.*` loader means the npm packages are structurally unreachable in EVERY mode (under yarn PnP the installed-tree crawl is empty too — no `node_modules/`), so `scan` surfaces an additive top-level `warnings[]` array (`{code, detail}` objects, omitted when empty) carrying `yarn_pnp_unsupported` (same code as apply's refusal; remedy `yarn patch `) or `pnpm_pnp_unsupported` (pnpm's `node-linker=pnp` twin; pnpm remedies), plus a stderr `Warning: …` line on the human path. Exit code and `status` are deliberately unchanged (exit 0 / `success` — the same posture as hosted refusals, which exit 0 with no `applied` event); the warning is the machine-readable signal that nothing was checked. Pinned by `tests/e2e_safety_yarn_pnp.rs`. **A Bundler lock socket-patch cannot read is likewise a warning, not an empty inventory**: when the project holds gem files but bundler loads no `Gemfile.lock` / `gems.locked` socket-patch reads (`BUNDLE_GEMFILE` or bundler 4's `BUNDLE_LOCKFILE` naming another file, or a `Gemfile` + `gems.rb` twin, whose loaded pair depends on the bundler major that runs), `warnings[]` carries the additive `gem_lock_unsupported` (detail names the setting or the twin) and its lockfile-only gems are not discovered. Same exit-0 / `success` posture. **The jars of a pinned rules_jvm_external hub join the supplement of a hosted run at the root of a Bazel workspace (additive)**: **Experimental** (Bazel workspaces). `scan --mode hosted` (the inferred default included) and `get --mode hosted` take, for each hub of the root `MODULE.bazel` that names a lock (`maven_install.json`), the jar without a classifier of each artifact the hub fetches, at the lock's version, as a Maven package of the project: it counts in `scannedPackages`, and in `lockfileOnlyPackages` with `notInstalled: true` unless a crawl found that version installed, and a patch found for it is pinned in the block of `MODULE.bazel` (the `maven_bazel_*` rows below). A jar whose repository has no known name is such a package too (a patch found for it gets `maven_bazel_artifact`). No jar is guessed for a hub that was not read with certainty: `warnings[]` then carries `maven_bazel_hub_not_read` once, and the jars of the hubs that were read are still looked up. A patch of a hub's jar is a patch of the run like any other, so the run writes for it what `get --mode hosted` writes in that checkout: beside a Gradle build the hosted Gradle pin too (`settings.gradle` and the files under `.socket/gradle/`, with that pin's warnings), and beside a `pom.xml` what the pom lane pins or says (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`, which speak of `pom.xml` alone). **A stale entry of the block is taken out by `scan --mode hosted` (additive)**: when every hub was read and none fetches the jar of an entry at its version any more (the lock moved on, so Bazel stops at the entry), the scan restores it before the rewrite as the withdrawn-pin sweep above restores a pin: the entry alone, under the apply lock, `--dry-run` previewing it, one `rolledBack` event (`verified` on a dry run) with `uuid`, `errorCode: "maven_bazel_entry_stale"` and `details.mode: "hosted"`, also on a scan that finds no package; a pin of the same patch in a `pom.xml` or Gradle file stays; a restore that fails is the `redirect_withdrawn_restore_failed` warning. `get` takes no stale entry out, and no scan takes out a stale entry of vendored mode (a `local_repository` over `.socket/vendor/maven//`): its directory and its ledger entry are vendored mode's, so it stays for `rollback `, `remove ` or `vendor --revert`, which take all three out, and `vendor --check` names it. No other mode, no run whose `--ecosystems` leaves Maven out, no `--global` run and no run of a project below the Bazel root takes a package from a hub, gives that warning or takes a stale entry out: its packages are those of the run without the workspace. A run of a project in no Bazel workspace is, byte for byte, the run it was. See docs/ecosystems.md "Bazel workspaces: Maven". +**Lockfile supplement (v3.4)**: `scan` discovery is no longer limited to installed trees. The project's lockfiles (`package-lock.json`/`npm-shrinkwrap.json`, `pnpm-lock.yaml` v9, `yarn.lock` classic + berry, `bun.lock`, `vlt-lock.json` (registry nodes, Socket-hosted pins included; vendored `file` nodes are left to the vendor ledger), `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`, `uv.lock`/`poetry.lock`/pinned `requirements.txt`) are inventoried and dependencies with NO installed copy join discovery — counts, the API lookup, the rows of what a hosted or vendored run patches (an agent or report-only run, which patches installed copies, gets a stderr note that they are not installed), and the prune "scanned" set (a wiped node_modules no longer prunes lockfile-listed entries). JSON gains a top-level `lockfileOnlyPackages` count and an additive `notInstalled: true` on matching `packages[]` entries. Agent mode partitions lockfile-only patches out BEFORE download (calm `skipped`/`package_not_installed` events — never an error exit, never a manifest write); vendored mode passes them through to the vendor engine's server download. Vendored-ledger entries likewise stay discoverable on a fresh clone (the committed artifact is the dependency). The `Gemfile.lock` inventory lists a gem by its ruby-platform entry; a gem the lock resolves ONLY as precompiled platform builds (`nokogiri (1.18.10-arm64-darwin)`, no `nokogiri (1.18.10)`) joins the supplement too, in every mode (`scan`, `get --mode hosted` / `--mode vendored`, and the in-memory hosted engine): a hosted run redirects it to its per-platform prebuilds from the lock, a vendored run vendors it from them, and an agent or report-only run counts it among the packages that are not installed. Before this, only a hosted run named it, and a vendored scan of a checkout with nothing installed never looked it up. Global scans (`--global`) get no supplement. **Rush monorepos** (no root lockfile, `rush.json` present): the npm-lock inventory falls back to the Rush source-of-truth locks — `common/config/rush/pnpm-lock.yaml` plus every `common/config/subspaces/*/pnpm-lock.yaml` (`read_dir`-sorted, repo-relative paths preserved) — so a Rush repo's dependencies still join discovery. **Plug'n'Play layouts are an explicit refusal, not an empty inventory**: a `.pnp.*` loader means the npm packages are structurally unreachable in EVERY mode (under yarn PnP the installed-tree crawl is empty too — no `node_modules/`), so `scan` surfaces an additive top-level `warnings[]` array (`{code, detail}` objects, omitted when empty) carrying `yarn_pnp_unsupported` (same code as apply's refusal; remedy `yarn patch `) or `pnpm_pnp_unsupported` (pnpm's `node-linker=pnp` twin; pnpm remedies), plus a stderr `Warning: …` line on the human path. Exit code and `status` are deliberately unchanged (exit 0 / `success` — the same posture as hosted refusals, which exit 0 with no `applied` event); the warning is the machine-readable signal that nothing was checked. Pinned by `tests/e2e_safety_yarn_pnp.rs`. **A Bundler lock socket-patch cannot read is likewise a warning, not an empty inventory**: when the project holds gem files but bundler loads no `Gemfile.lock` / `gems.locked` socket-patch reads (`BUNDLE_GEMFILE` or bundler 4's `BUNDLE_LOCKFILE` naming another file, or a `Gemfile` + `gems.rb` twin, whose loaded pair depends on the bundler major that runs), `warnings[]` carries the additive `gem_lock_unsupported` (detail names the setting or the twin) and its lockfile-only gems are not discovered. Same exit-0 / `success` posture. **The jars of a pinned rules_jvm_external hub join the supplement of a hosted run at the root of a Bazel workspace (additive)**: **Experimental** (Bazel workspaces). `scan --mode hosted` (the inferred default included) and `get --mode hosted` take, for each hub of the root `MODULE.bazel` that names a lock (`maven_install.json`), the jar without a classifier of each artifact the hub fetches, at the lock's version, as a Maven package of the project: it counts in `scannedPackages`, and in `lockfileOnlyPackages` with `notInstalled: true` unless a crawl found that version installed, and a patch found for it is pinned in the block of `MODULE.bazel` (the `maven_bazel_*` rows below). A jar whose repository has no known name is such a package too (a patch found for it gets `maven_bazel_artifact`). No jar is guessed for a hub that was not read with certainty: `warnings[]` then carries `maven_bazel_hub_not_read` once, and the jars of the hubs that were read are still looked up. A patch of a hub's jar is a patch of the run like any other, so the run writes for it what `get --mode hosted` writes in that checkout: beside a Gradle build the hosted Gradle pin too (`settings.gradle` and the files under `.socket/gradle/`, with that pin's warnings), and beside a `pom.xml` what the pom lane pins or says (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`, which speak of `pom.xml` alone). **A stale entry of the block is taken out by `scan --mode hosted` (additive)**: when every hub was read and none fetches the jar of an entry at its version any more (the lock moved on, so Bazel stops at the entry), the scan restores it before the rewrite as the withdrawn-pin sweep above restores a pin: the entry alone, under the apply lock, `--dry-run` previewing it, one `rolledBack` event (`verified` on a dry run) with `uuid`, `errorCode: "maven_bazel_entry_stale"` and `details.mode: "hosted"`, also on a scan that finds no package; a pin of the same patch in a `pom.xml` or Gradle file stays; a restore that fails is the `redirect_withdrawn_restore_failed` warning. `get` takes no stale entry out, and no scan takes out a stale entry of vendored mode (a `local_repository` over `.socket/vendor/maven//`): its directory and its ledger entry are vendored mode's, so it stays for `rollback `, `remove ` or `vendor --revert`, which take all three out, and `vendor --check` names it. No other mode, no run whose `--ecosystems` leaves Maven out, no `--global` run and no run of a project below the Bazel root takes a package from a hub, gives that warning or takes a stale entry out: its packages are those of the run without the workspace. A run of a project in no Bazel workspace is, byte for byte, the run it was. See docs/ecosystems.md "Bazel workspaces: Maven". **Server artifact acquisition (v5.0)**: vendoring downloads the patched artifact for the selected UUID, including on a fresh checkout with no installed package. The CLI no longer downloads pristine packages, stages patch blobs, applies patches to vendor copies, or constructs archives. Backend lock and package-identity checks still run before acquisition; git and custom-registry Cargo sources are refused with `vendor_source_unsupported`. Healthy committed artifacts are reused offline. A changed UUID downloads a fresh server artifact; an unhealthy artifact at the recorded UUID uses the exact redownload procedure below, except that a directory copy whose ledger entry has no file inventory (vendored before v5.0) is rebuilt by its backend from a fresh verified download, and a missing or stale Bun workspace mirror over a healthy canonical tarball is rewritten from that tarball by the backend; those cases report the backend's own failure codes. diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index d8a49acfb2..ac3e1fd395 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -1088,8 +1088,9 @@ async fn filter_to_installed_purls( pnp_diags.retain(|diag| maven || diag.code != hub); if mode != super::scan::ScanMode::Agent { present.extend(supplement.entries.iter().map(|e| PurlKey::new(&e.purl))); - // A hosted run's supplement also names the gems the lock - // resolves only as precompiled platform builds. + // The supplement also names the gems the lock resolves only + // as precompiled platform builds, and a hosted run's the jars + // of a Bazel workspace's hubs. present.extend(supplement.purls.iter().cloned()); let vendored = super::scan::project_vendored_supplement(&ctx, &[], &ctx.loaded().await.vendor) diff --git a/crates/socket-patch-cli/src/commands/scan/discovery.rs b/crates/socket-patch-cli/src/commands/scan/discovery.rs index 577eaad21d..02e3d30fcd 100644 --- a/crates/socket-patch-cli/src/commands/scan/discovery.rs +++ b/crates/socket-patch-cli/src/commands/scan/discovery.rs @@ -44,9 +44,10 @@ pub(crate) struct LockfileSupplement { /// of re-parsing every project lockfile. Empty for global scans. pub(crate) entries: Vec, /// The gems the Bundler lock resolves only as precompiled platform - /// builds, as `pkg:gem/@`. `entries` leaves them out, - /// in every mode, and the lock names them all the same: with - /// `entries` they are what the project's lockfiles resolve. + /// builds, as `pkg:gem/@`. `entries` leaves them out + /// and the lock names them all the same: with `entries` they are what + /// the project's lockfiles resolve, and one with no installed copy is + /// in `packages` like any other. pub(crate) platform_gems: Vec, /// npm layouts the lockfile inventory REFUSED (Plug'n'Play loaders). /// Scan surfaces these as refusal warnings: under PnP the installed-tree @@ -73,12 +74,15 @@ pub(crate) struct LockfileSupplement { /// lockfile-only, since there is no crawl to tell whether it is installed. /// `entries` still holds the full inventory. /// -/// `hosted`: the run is a hosted scan. The inventory leaves out a gem the -/// Bundler lock resolves only as precompiled platform builds (`nokogiri -/// (1.18.10-arm64-darwin)`: no one `.gem` stands for it, so it cannot be -/// vendored from the lock, and an in-place patch needs the installed copy). -/// Hosted mode redirects such a gem to its per-platform prebuilds from the -/// lock alone, so a hosted supplement names it too. It also names the jars +/// The inventory leaves out a gem the Bundler lock resolves only as +/// precompiled platform builds (`nokogiri (1.18.10-arm64-darwin)`: no one +/// `.gem` stands for it). The lock resolves it all the same, and a hosted +/// or vendored run patches it from the lock alone, through the prebuilt +/// patched gem of each locked platform, so the supplement names it too, +/// in every mode: left out, a checkout with nothing installed would never +/// ask about it. +/// +/// `hosted`: the run is a hosted scan. Its supplement also names the jars /// of [`hub_jars`], and what was not read of the hubs joins `unsupported`. pub(crate) async fn lockfile_supplement( ctx: &crate::commands::context::ProjectContext<'_>, @@ -112,12 +116,10 @@ pub(crate) async fn lockfile_supplement( if entries.is_empty() && platform_gems.is_empty() && jars.is_empty() { return out; } - // Only a hosted supplement names a platform-only gem that has no - // installed copy (see above). let resolved = entries .iter() .map(|entry| entry.purl.as_str()) - .chain(platform_gems.iter().filter(|_| hosted).map(String::as_str)) + .chain(platform_gems.iter().map(String::as_str)) .chain(jars.iter().map(String::as_str)); (out.packages, out.purls) = lockfile_only_packages(resolved, crawled, only, &common.cwd); out.entries = entries.clone(); diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index 1f195d3fc5..45eeb2c8cd 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -4223,6 +4223,145 @@ async fn refused_platform_gem_is_counted_as_left_to_patch() { } } +/// A checkout with nothing installed whose lock names the gem only as +/// platform builds, beside a plain gem: a vendored run and an agent run +/// ask the patch service about the gem, as a hosted run does (#2394). +/// The fix has no patch for one locked platform, so the vendored run +/// skips the gem by name and counts its advisory as left to patch +/// where it used to end with "Nothing left to patch." The agent run, +/// which patches installed copies only, counts the gem among the +/// packages that are not installed and leaves it. +#[tokio::test(flavor = "multi_thread")] +async fn platform_only_gem_is_looked_up_on_a_fresh_checkout() { + const LEFT: &str = + "\n1 vulnerability left to patch: 1 is in packages this run did not patch.\n"; + let arm_sha = sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM)); + for mode in ["vendored", "agent"] { + let server = MockServer::start().await; + // The service answers for the gem only when the run asks about it. + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [], + "canAccessPaidPatches": false, + }))) + .with_priority(2) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .and(body_string_contains(DEP)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [{ + "purl": PURL, + "patches": [{ + "uuid": UUID, "purl": PURL, "tier": "free", + "cveIds": [], "ghsaIds": [GHSA], "severity": "high", + "title": "gem stale-install fixture" + }] + }], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(&server) + .await; + mount_api_with( + &server, + None, + &sha256_of(&real_gem(PATCHED_LIB)), + &[(PLATFORM, arm_sha.clone())], + ) + .await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + let gemfile = format!( + "source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\ngem \ + \"plain-probe-gem\", \"1.0.0\"\n" + ); + let lock = platform_lock(&"1".repeat(64), &"2".repeat(64)) + .replace(" specs:\n", " specs:\n plain-probe-gem (1.0.0)\n") + .replace( + "DEPENDENCIES\n", + "DEPENDENCIES\n plain-probe-gem (= 1.0.0)\n", + ); + assert!( + lock.contains(" plain-probe-gem (1.0.0)\n") + && !lock.contains(&format!(" {DEP} ({DEP_VERSION})\n")), + "the lock holds a plain gem, and {DEP} as platform builds only:\n{lock}" + ); + std::fs::write(proj.join("Gemfile"), &gemfile).unwrap(); + std::fs::write(proj.join("Gemfile.lock"), &lock).unwrap(); + + let uri = server.uri(); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &[ + "scan", + "--mode", + mode, + "--yes", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--patch-server-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + ], + &[], + ); + let asked = server + .received_requests() + .await + .unwrap() + .iter() + .filter(|request| request.url.path().ends_with("/patches/batch")) + .any(|request| String::from_utf8_lossy(&request.body).contains(DEP)); + assert!( + asked, + "{mode}: the lookup names the gem the lock holds as platform builds\n\ + stdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + lock, + "{mode}: the lock is untouched" + ); + assert!( + !proj.join(".socket").join("vendor").exists(), + "{mode}: nothing is vendored" + ); + assert_eq!(code, 0, "{mode}\nstdout:\n{stdout}\nstderr:\n{stderr}"); + if mode == "vendored" { + // One locked platform has no patch, so the gem is skipped. + assert!( + stderr.contains(&format!( + "no patch of this fix is available for every platform gem of `{DEP}` that \ + Gemfile.lock locks (`{OTHER_PLATFORM}`: no patch on offer" + )), + "{mode}: the run names the gem it skips\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + stdout.ends_with(LEFT), + "{mode}: the skipped gem is left to patch\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + } else { + assert!( + stderr.contains( + "Note: 2 packages from project lockfiles are not yet installed \ + (lockfile-only)." + ), + "{mode}: both locked gems count as not installed\n\ + stdout:\n{stdout}\nstderr:\n{stderr}" + ); + } + } +} + /// Human output of the run that refreshes: one progress line per kind, /// no warning, and the committed archive in the files to commit. #[tokio::test(flavor = "multi_thread")] diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs b/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs index ac0af32038..fd7511d6d0 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs @@ -18,7 +18,8 @@ use super::{dedup_prefer_integrity, LockfileEntry, UnsupportedNpmLayout}; /// indent; deeper lines are dependency ranges) plus the bundler ≥ 2.6 /// `CHECKSUMS` section's sha256 values when present (older locks stay /// discovery-only). Platform-suffixed specs (`nokogiri (1.16.5-arm64-…)`) -/// are skipped — platform gems are unsupported for vendoring anyway. +/// are skipped: no one `.gem` stands for such a gem, and +/// [`gem_platform_only_purls_in`] names the gems the lock holds only so. /// /// Multi-source locks: bundler ≥ 2 emits ONE GEM section per source /// (Gemfile `source … do` blocks; verified against bundler 4.0.15) and @@ -60,10 +61,11 @@ pub(super) async fn inventory_gemfile_lock_raw_in( /// The gems the Bundler lock bundler loads resolves only as precompiled /// platform builds ([`GemfileLock::platform_only_purls`]), which -/// [`inventory_gemfile_lock`] leaves out. Hosted mode's lockfile discovery -/// adds them: it redirects such a gem to its per-platform prebuilds, so a -/// lock that has no installed copy beside it (a fresh checkout, the -/// in-memory engine) must still name it. +/// [`inventory_gemfile_lock`] leaves out. Lockfile discovery adds them: +/// hosted mode redirects such a gem to its per-platform prebuilds and +/// vendored mode vendors it from them, so a lock that has no installed +/// copy beside it (a fresh checkout, the in-memory engine) must still +/// name it. pub async fn gem_platform_only_purls_in(view: &ProjectView<'_>) -> Vec { let Some(lock) = bundler_loaded_lock_in(view).await else { return Vec::new(); diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index ad4c02d1f6..00c094bac0 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -573,6 +573,7 @@ def delivered(mode) service.bring_up gemfile, lock = File.read(File.join(@proj, "Gemfile")), File.read(lock_path) platforms = locked_platforms + vendored_from_the_lock_alone(lock, platforms) if mode == "vendored" code, stdout, stderr, secs = sp_service("scan", "--mode", mode, "--yes", "--json") check(code.zero?, "`scan --mode #{mode}` succeeds (#{secs.round}s)", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") @@ -683,6 +684,30 @@ def delivered(mode) check(probe == @baseline, "after `bundle install`, Ruby loads what it loaded before the patch") end + # A vendored scan of a checkout with nothing installed. A lock that names + # nokogiri only as platform gems is all the scan has to go by, and it is + # enough: the gem is vendored from the patched gem of each locked + # platform, and the checkout installs from that tree. (A lock that also + # has the ruby platform's entry is refused in vendored mode either way.) + def vendored_from_the_lock_alone(lock, platforms) + return if lock =~ /^ nokogiri \(#{Regexp.escape(@version)}\)$/ + checkout = fresh_checkout + in_project(checkout) do + code, stdout, stderr, = sp_service("scan", "--mode", "vendored", "--yes", "--json") + check(code.zero?, "`scan --mode vendored` succeeds on a checkout with nothing installed", + "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + vendored = Dir.glob(File.join(@proj, ".socket", "vendor", "gem", "**", "*.gemspec")) + check(vendored.size >= platforms.size, "it vendors a patched gem for each platform from the lock alone", + "#{vendored.inspect}\n#{tail(stdout)}#{tail(stderr)}") + code, out = bundle_install("BUNDLE_FROZEN" => "true") + check(code.zero?, "that checkout installs with the lock frozen", tail(out)) + now = probe + check(now[RB_CONST] == 1 && now["loaded_from"].to_s.include?("/.socket/vendor/"), + "and Ruby there loads the patched nokogiri from the vendored tree", JSON.pretty_generate(now)) + end + FileUtils.rm_rf(checkout) + end + def skip(why) puts " skip #{why}" true diff --git a/tests/nokogiri/patch_service.rb b/tests/nokogiri/patch_service.rb index b94c3dcbf3..f30d6f5066 100644 --- a/tests/nokogiri/patch_service.rb +++ b/tests/nokogiri/patch_service.rb @@ -287,6 +287,14 @@ def json(body) def respond(verb, path, body) api = "/v0/orgs/#{ORG}/patches" if verb == "POST" && path == "#{api}/batch" + # As the service does, answer for the gem only to a run that asks + # about it. + asked = begin + JSON.parse(body.to_s).fetch("components", []).map { |c| c["purl"].to_s.split("?").first } + rescue JSON::ParserError + [] + end + return json("packages" => [], "canAccessPaidPatches" => false) unless asked.include?(base_purl) patches = all_gems.map do |g| { "uuid" => g.uuid, "purl" => patch_purl(g), "tier" => "free", "cveIds" => [], "ghsaIds" => [@ghsa], "severity" => "high", "title" => "nokogiri end-to-end test" } From 94099f5c5ffa252d113038c02919f753651f88a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 10:16:04 +0000 Subject: [PATCH 3/3] Test vendoring a platform-only gem from the lock Add a hermetic test of the success path: a vendored scan of a checkout with nothing installed vendors a gem the lock holds only as platform gems, one tree per locked platform, when the service has a patch for each. The service of the test answers a lookup for the gem only when the run asks about it. Bring the contract's agent-mode paragraph and the comments that still called these gems hosted-only in line with the code. Refs #2394 Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 6 +- .../tests/e2e_redirect_gem_stale_install.rs | 197 +++++++++++++++++- .../socket-patch-core/src/formats/gem/mod.rs | 8 +- 3 files changed, 201 insertions(+), 10 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 5d042202f7..5f67803816 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1788,9 +1788,9 @@ the model is **not uniform** today: crawl: one the lock lists is then lockfile-only, exactly as when no gem home holds it (`notInstalled`, skipped as `package_not_installed` before any download, nothing recorded), and any other is no candidate at all (not counted in `scannedPackages`, not queried, not shown), - like a gem that is installed nowhere. That includes a gem the lock holds only as precompiled - platform builds: an agent-mode scan's lockfile supplement never names those, so such a gem is - not reported as not installed, with or without a copy in a `gem env` home. `get ` + like a gem that is installed nowhere. A gem the lock holds only as precompiled platform + builds is one the lock lists: the lockfile supplement names it in every mode, so it is + lockfile-only too, with or without a copy in a `gem env` home. `get ` resolves a name among the installed packages, so such a gem's name matches nothing, and `get ` narrows it away as `package_not_installed`. `--save-only` applies nothing and is not narrowed: by name, advisory or purl it records the patch. An exact purl is never diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index 45eeb2c8cd..2c532d7a42 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -4102,9 +4102,8 @@ async fn gem_hosted_pair_already_moved_converges_or_is_kept() { /// A lock that names the gem only as platform builds, beside a plain /// gem, and a fix without a patch for every locked platform: /// the run refuses the gem. The lock still resolves it, so the closing -/// totals count its advisory as left to patch, in hosted mode (which -/// reads the gem from the lock alone) and in vendored mode (which reads -/// the installed platform copy). +/// totals count its advisory as left to patch, in hosted mode (nothing +/// installed) and in vendored mode (beside the installed platform copy). #[tokio::test(flavor = "multi_thread")] async fn refused_platform_gem_is_counted_as_left_to_patch() { const LEFT: &str = @@ -4362,6 +4361,198 @@ async fn platform_only_gem_is_looked_up_on_a_fresh_checkout() { } } +/// The same checkout, with a patch for every locked platform: the +/// vendored run vendors the gem from the lock alone (#2394). Nothing is +/// installed, so the patched platform gems the service serves are all it +/// has: one tree per locked platform under the directory of the fix's +/// source patch, the lock's entries moved to that path, and the ledger +/// recording each platform's own patch. +#[tokio::test(flavor = "multi_thread")] +async fn platform_only_gem_is_vendored_from_the_lock_alone() { + use base64::Engine as _; + use sha2::{Digest as _, Sha512}; + let server = MockServer::start().await; + let platforms = [PLATFORM, OTHER_PLATFORM]; + let prebuilds = platforms.map(|platform| real_gem_for(PATCHED_LIB, platform)); + mount_api_with( + &server, + None, + &sha256_of(&real_gem(PATCHED_LIB)), + &[ + (PLATFORM, sha256_of(&prebuilds[0])), + (OTHER_PLATFORM, sha256_of(&prebuilds[1])), + ], + ) + .await; + // The service answers for the gem only when the run asks about it. + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .and(|request: &wiremock::Request| !String::from_utf8_lossy(&request.body).contains(DEP)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(&server) + .await; + // The package reference of each platform gem's patch, as vendored mode + // reads it: the patched gem and its stub gemspec. + let mut results = serde_json::Map::new(); + for (platform, gem) in platforms.iter().zip(&prebuilds) { + let uuid = platform_patch_uuid(UUID, platform); + let leaf = format!("{DEP}-{DEP_VERSION}-{platform}"); + let stub = format!( + "Gem::Specification.new do |s|\n s.name = \"{DEP}\".freeze\n s.version = \ + \"{DEP_VERSION}\".freeze\n s.platform = \"{platform}\".freeze\n s.summary = \ + \"fixture\".freeze\n s.authors = [\"e2e\".freeze]\n s.licenses = \ + [\"MIT\".freeze]\n s.files = [\"lib/stale_probe_gem.rb\".freeze]\n \ + s.require_paths = [\"lib\".freeze]\nend\n" + ); + let mut artifacts = Vec::new(); + for (kind, file, bytes) in [ + ("tarball", format!("{leaf}.gem"), gem.clone()), + ( + "gem-stub-gemspec", + format!("{leaf}.gemspec"), + stub.into_bytes(), + ), + ] { + let route = format!("/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{uuid}/{file}"); + artifacts.push(serde_json::json!({ + "kind": kind, + "url": format!("{}{route}", server.uri()), + "integrity": { "sha512": format!( + "sha512-{}", + base64::engine::general_purpose::STANDARD.encode(Sha512::digest(&bytes)) + ) }, + })); + Mock::given(method("GET")) + .and(path(route)) + .respond_with( + ResponseTemplate::new(200).set_body_raw(bytes, "application/octet-stream"), + ) + .mount(&server) + .await; + } + results.insert( + uuid, + serde_json::json!({ + "status": "granted", + "purl": platform_purl(platform), + "url": artifacts[0]["url"], + "rebuiltFromUuid": UUID, + "artifacts": artifacts, + }), + ); + } + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(move |request: &wiremock::Request| { + let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let asked: serde_json::Map = body["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| uuid.as_str()) + .filter_map(|uuid| Some((uuid.to_string(), results.get(uuid)?.clone()))) + .collect(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": asked })) + }) + .with_priority(1) + .mount(&server) + .await; + + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + let gemfile = format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"); + let lock = platform_lock( + &sha256_of(&real_gem_for(UPSTREAM_LIB, PLATFORM)), + &sha256_of(&real_gem_for(UPSTREAM_LIB, OTHER_PLATFORM)), + ); + std::fs::write(proj.join("Gemfile"), &gemfile).unwrap(); + std::fs::write(proj.join("Gemfile.lock"), &lock).unwrap(); + + let uri = server.uri(); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &[ + "scan", + "--mode", + "vendored", + "--yes", + "--json", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--patch-server-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + ], + &[], + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + env["lockfileOnlyPackages"], 1, + "the gem is in the lock and not installed: {env}" + ); + assert_eq!( + env["summary"]["applied"], 2, + "one applied event per platform gem: {env}" + ); + let copy = proj + .join(".socket") + .join("vendor") + .join("gem") + .join(UUID) + .join(format!("{DEP}-{DEP_VERSION}")); + for platform in platforms { + assert_eq!( + std::fs::read_to_string(copy.join(platform).join("lib").join("stale_probe_gem.rb")) + .unwrap_or_default(), + PATCHED_LIB, + "{platform}: the vendored tree holds the patched file\n{env}\nstderr:\n{stderr}" + ); + } + let vendored_lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!( + vendored_lock.contains(&format!( + "PATH\n remote: .socket/vendor/gem/{UUID}/{DEP}-{DEP_VERSION}" + )) && !vendored_lock.contains(&format!(" {DEP} ({DEP_VERSION})\n")), + "the lock takes every platform entry from the vendored path:\n{vendored_lock}" + ); + let ledger: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(proj.join(".socket").join("vendor").join("state.json")).unwrap(), + ) + .unwrap(); + let mut built: Vec<(String, String)> = ledger["entries"] + .as_object() + .into_iter() + .flat_map(|entries| entries.values()) + .flat_map(|entry| entry["gemBuilds"].as_array().cloned().unwrap_or_default()) + .map(|build| { + let field = |key: &str| build[key].as_str().unwrap_or_default().to_string(); + (field("platform"), field("uuid")) + }) + .collect(); + built.sort(); + let mut expected: Vec<(String, String)> = platforms + .iter() + .map(|platform| (platform.to_string(), platform_patch_uuid(UUID, platform))) + .collect(); + expected.sort(); + assert_eq!( + built, expected, + "each platform's tree under its own patch: {ledger}" + ); +} + /// Human output of the run that refreshes: one progress line per kind, /// no warning, and the committed archive in the files to commit. #[tokio::test(flavor = "multi_thread")] diff --git a/crates/socket-patch-core/src/formats/gem/mod.rs b/crates/socket-patch-core/src/formats/gem/mod.rs index 85d77bf406..400818ce3d 100644 --- a/crates/socket-patch-core/src/formats/gem/mod.rs +++ b/crates/socket-patch-core/src/formats/gem/mod.rs @@ -511,9 +511,9 @@ impl GemfileLock<'_> { /// `pkg:gem/@` for each gem version with `name /// (version-)` specs in a `GEM` section and no ruby-platform /// `name (version)` beside them, sorted. [`Self::entries`] leaves them - /// out (no single `.gem` stands for such a gem). Hosted mode patches - /// one through its per-platform prebuilds, so its discovery asks for - /// them here. + /// out (no single `.gem` stands for such a gem). Hosted and vendored + /// mode patch one through its per-platform prebuilds, so lockfile + /// discovery asks for them here, in every mode. pub fn platform_only_purls(&self) -> Vec { let specs = || { self.gem_sections() @@ -1023,7 +1023,7 @@ mod tests { assert_eq!(GemBuild::of_leaf(purl, "nokogiri-1.18.10-2.0"), None); assert_eq!(GemBuild::of_leaf(purl, "nokogiri-1.18.9-java"), None); // The registry inventory lists only gems with a ruby-platform - // entry; hosted discovery asks for the platform-only ones apart. + // entry; lockfile discovery asks for the platform-only ones apart. assert_eq!( lock.platform_only_purls(), [