diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 27c721324e..81490f9481 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -507,7 +507,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - When several confirmed variant purls resolve to one installed dir, ANY of them judging it patched keeps it quiet. - Staleness needs **positive evidence** — bytes actually read that are not the patched state — so missing or unreadable files never mark a copy stale. - A committed cache-dir archive whose sha256 is readable and differs from the patched artifact's is stale by itself, even with no installed dir at all (a fresh checkout with a committed stale cache). That covers the ruby gem's `-.gem` and each platform build's `--.gem`. -- Standalone `vex` and `apply --check` judge gem copies by the same rule (#1098): when Bundler doesn't use system gems, a copy in a `gem env` home is not one the project loads and is not verified, unless it is a default gem (its spec under `specifications/default/`), which Bundler loads from the system home under any path. +- Standalone `vex` and `apply --check` judge gem copies by the same rule (#1098): when Bundler doesn't use system gems, a copy in a `gem env` home is not one the project loads and is not verified, unless it is a default gem (its spec under `specifications/default/`) or Bundler itself, which Bundler loads from the system home under any path. Agent `apply` writes by that rule too (#2313): it leaves such a copy alone (see "Copy classes"). *The refresh* (default; `--no-gem-install-refresh`, env `SOCKET_NO_GEM_INSTALL_REFRESH`, turns it off). @@ -1518,7 +1518,8 @@ the model is **not uniform** today: "nothing installed" absence the hosted lockfile basis excuses), while `apply`/`rollback` never touch it (#709). Explicit env/config/standalone roots only count when `--cwd` holds a Bundler manifest/lockfile. When the default `vendor/bundle` root holds no store, the gem homes `gem env` - reports are appended (default gems like rexml/json only ever live there). When the Bundler tier that + reports are appended (default gems like json/uri only ever live there); which of the copies + found there are written is the "Copy classes" rule below. When the Bundler tier that decides the install path (the first of the app config, the environment and the global config that sets `path`, `path.system` or `disable_shared_gems`) sets a truthy `path.system` (Bundler's own coercion: anything but `false`/`f`/`no`/`n`/`0`/empty), bundler installs into and loads from the @@ -1555,13 +1556,82 @@ the model is **not uniform** today: *Copy classes (additive to the multi-copy vocabulary):* a copy under a **bundle-path store** (config/env/default root) is PRIMARY — a variant mismatch or write failure there fails the run, as always. A copy in a **`gem env` fallback home** (rvm `@global`, `--user-install`, system gem - dirs — shared, often root-owned) is patched too when it matches and is writable, but becomes - BEST-EFFORT once at least one bundle-store copy applied: its mismatch/write failure surfaces as a - non-fatal `skipped` event (`errorCode: gem_fallback_home_skipped`, detail names the copy's path - and reason; gated stderr twin on the human path) instead of failing a run whose loaded copy is - patched. With **no** bundle-store copy (the historic fallback-only layout, and every `--global` - run) the fallback-home copy IS the primary install and keeps loud-fail parity with pre-bundle-path - `apply`. + dirs — shared, often root-owned) is found only while the default `vendor/bundle` root holds no + store (above). It is a write target of `apply`, and of the apply that `get` and + `scan --mode agent` run, only when Bundler loads it for the project (#2313): + + - when Bundler uses system gems (the rule under "Gem stale-install guard": no deployment store + under `vendor/bundle`, and no explicit or deployment `path`), every copy there is the + project's and is patched; + - under an explicit or deployment `path`, two kinds of copy are patched there, because Bundler + loads them from the gem home they are installed in under any path: a default gem (its spec + under `specifications/default/`: `json`, `uri`, `set`), and Bundler itself (a `bundler-` + dir, as `gem install bundler` leaves it; every installed version, since which one runs also + depends on `BUNDLED WITH`, `BUNDLER_VERSION` and Bundler's own version switch). A bundled gem + (`rexml`, `rake`) has an ordinary spec and follows the ordinary rule: Bundler installs it, + like every other gem, into the path, so a copy of it in a `gem env` home belongs to other + projects on the machine and is never written. + + A gem with no copy `apply` writes is one of three things: + + - **in the project's lock**: not installed yet (a fresh clone before `bundle install`). It is + `package_not_installed` with the lockfile-only detail, a calm skip, exit 0; + - **not in a lock that was read, with a copy in a `gem env` home**: another project's gem. Its + record (one an earlier release wrote when it patched that copy, or one a `get` of the exact + purl wrote) is a `skipped` event with `errorCode: gem_other_project_copy_skipped`, keyed by + the manifest key, whose detail names the copy, says why it was left, and gives the command + that drops the record (`socket-patch rollback `, with `--cwd` when the run had one); the + human run prints it as a `Warning:`, and the summary counts the patch as `not applicable`. It + never fails the run and is not counted as an all-miss; + - **anything else**: `package_not_installed`, with the result a package that is not installed + has (the all-miss error, exit 1, when no targeted patch matched). That covers a gem with no + copy anywhere, a gem the lock holds only as precompiled platform builds (the lock names it, + so it is the project's), and every gem of a project whose Bundler lock was not read: a + project with no lock yet (a gem library that commits none), and the layouts reported as + `gem_lock_unsupported` (an unsupported `BUNDLE_GEMFILE` / `BUNDLE_LOCKFILE`, a `Gemfile` + + `gems.rb` twin). Only a lock that was read can say the project does not use a gem, so no + `rollback` is advised there. + + `scan --mode agent` and `get` in agent mode select by the same rule, so that neither records a + patch its apply step has no copy to write. A gem whose every copy is one `apply` does not write + is not installed for the project, whether or not a lock was read. The scan leaves it out of the + 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 ` + 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 + narrowed, for any package: `get pkg:gem/@` records the patch, and the apply + step reports one of the three cases above. The prune pass (`--prune` / `--sync`) still counts + such a copy as installed, so a record an earlier release wrote for it is kept until `rollback` + or `remove` drops it. + + `apply --check` and `vex` judge the copies `apply` writes. `rollback` and `remove` restore a copy + in a `gem env` home that holds the patch, because a release before this rule may have patched it + there; a copy there that `apply` does not write and that holds nothing of the patch is left out, + whatever its content, and its record is dropped as for a package that is not installed (never a + `hash_mismatch` failure over another project's edit). A copy in a shared gem home that another + project patched with the same patch, in system-gems mode, cannot be told from one this + project's earlier release patched, so `rollback` and `remove` here restore it too. A copy there + that an earlier release patched BESIDE the project's own bundle-path copy stays patched after an + upgrade, and `apply` says nothing of it: the project's copy is the one it writes and reports. + `socket-patch rollback --preserve-state` restores both copies and keeps the record, and + the `socket-patch apply` after it patches the project's copy alone. A `--global` + run patches the `gem env` homes as before. Once the default `vendor/bundle` root holds a store, + no local run searches those homes: a default gem there is not patched, and `rollback` leaves a + copy an earlier run patched there, keeps its manifest record and names + `socket-patch rollback -g` in a warning. + + A fallback-home copy that is written becomes BEST-EFFORT once at least one bundle-store copy + applied: its mismatch/write failure surfaces as a non-fatal `skipped` event + (`errorCode: gem_fallback_home_skipped`, detail names the copy's path and reason; gated stderr + twin on the human path) instead of failing a run whose loaded copy is patched. With **no** + bundle-store copy (Bundler using system gems, a default gem or Bundler that is in no store, and + every `--global` run) the fallback-home copy IS the primary install and keeps loud-fail parity + with pre-bundle-path `apply`. **Intended (gap):** the cwd-only ecosystems *should* also auto-discover per-subproject lockfiles when run from the repo root, matching the npm workspace model. The npm-vs-others asymmetry is a known @@ -2476,6 +2546,8 @@ command's integration tests check its output. |---------------------------|------------------|---------| | `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". | +| `gem_fallback_home_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: a best-effort copy in a `gem env` home (the system gems, `~/.gem`, an rbenv or asdf home) was left unpatched, because it matched no variant or could not be written, while a bundle-path copy of the gem applied. The patch IS in effect on the copy bundler loads. Keyed by the base purl; the detail names the copy's path and the reason. Never flips status or exit. See "Copy classes". | +| `gem_other_project_copy_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: the record is for another project's gem. Its every copy sits in a `gem env` home Bundler does not load the project's gems from, and the project's Bundler lock, which was read, does not list it. Nothing was applied. Keyed by the manifest key; the detail names the copy and gives `socket-patch rollback `, which drops the record and restores the copy if an earlier release patched it. Never flips status or exit; the human summary counts the patch as `not applicable`. With no lock read the gem is `package_not_installed` instead. See "Copy classes". | | `package_not_installed` | `skipped` | apply: manifest entry has no matching installed package (an installed gem or PyPI copy that holds a patched file with content no record of its release was made for is `no_matching_variant` instead). When the project's lockfiles resolve the purl (a platform-gated optional dependency, a devDependency under `--omit=dev`), the detail says it is lockfile-only and the entry never fails the run, even when no other patch matched; only an all-miss run with an unmatched purl that no lock resolves exits 1 (`partialFailure`). **Cargo is never lockfile-only (v5.0, #616)**: `cargo fetch` unpacks every `Cargo.lock` entry (target-gated ones included), so a locked crate missing from `$CARGO_HOME/registry/src` was simply not fetched yet (a cold CI cache, a pruned `registry/src`) and the next `cargo build` would compile it unpatched; it counts as an unresolved purl (an all-miss run exits 1, as in 4.x) and its detail, the human error and the human warning say to run `cargo fetch` first. A crate `Cargo.lock` takes from a path, git, `[patch]` or `[replace]` source is never looked up in the registry cache (#506): cargo does not build that copy, so the same detail also names that case. | | `apply_failed` | `failed` | apply: hash mismatch, write error, archive read error. Also a manifest key that is not a purl (see `invalid_purl`). The copy is left as it was: every file is staged (its blob read and hash-checked, with the file's final mode and owner) before the first is renamed into place, and a rename that fails puts the files already replaced back. The `error` names the file (`Cannot apply patch: - `); a blob that does not hold its hash's bytes is named with the remedy (`blob is corrupt … Run \`socket-patch repair\``). Only when putting a file back fails too does the `error` end with the files left changed; the original of such a file is kept beside it as `.socket-kept--`, a name no later run removes. A run killed between two renames can still leave some files patched; the next `apply` finishes it. A killed run also leaves `.socket-stage--` / `.socket-orig--` files beside the patch's files (staged content and the second names of the files being replaced, never the package's own content); an `apply` or `rollback` of that package removes them once they are ten minutes old. | | `native_extension_not_rebuilt` | `failed` | apply (gem), and the apply that `get` / `scan --mode agent` run: the patch is incomplete. Its files were written into the installed copy and are left there (unlike `apply_failed`, where the copy is as it was), and the compiled code the copy runs is not the patch's: the build compiled nothing of it, or, on the JRuby build of a gem, the patch changes sources of the gem's jars and does not bring the jars. `error` says what was written and what is not in effect; `files` lists what this run wrote. The run exits 1 (`partialFailure`), the patch stays recorded, `apply --check` is out of sync and `vex` does not attest it; `rollback` restores the files. The same code is a `warnings[]` entry of the run, and the `apply --check` / `vex` tag of such a copy. See "A build that builds nothing of the patch". | diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 52175644d2..02661a20d2 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -2586,16 +2586,21 @@ pub async fn download_and_apply_patches_into( // Past the network, about to write to installed packages: a // hot-patch pass is no longer dropped at its time limit. crate::hot_patch::mark_apply_started(); + // Boxed: this frame stays under the whole nested apply (see + // `boxed`). + let command = telemetry_command(env); apply_report = Some( - run_nested_apply( - telemetry_command(env), - nested_apply_args_from_params(params, run, &manifest_path), - params.json, - !params.user_patch_skips_reported, - &recorded, - run.api_client, - lock, - ) + crate::ecosystem_dispatch::boxed(|| { + run_nested_apply( + command, + nested_apply_args_from_params(params, run, &manifest_path), + params.json, + !params.user_patch_skips_reported, + &recorded, + run.api_client, + lock, + ) + }) .await, ); } diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 00d1b9bed4..899b664147 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -36,8 +36,8 @@ use crate::commands::vex::{ generate_vex_from_manifest_path, generate_vex_without_manifest, ManifestlessVex, VexEmbedArgs, }; use crate::ecosystem_dispatch::{ - distinct_install_dirs, distinct_npm_copies, find_all_packages_for_purls, partition_purls, - unsupported_ecosystem_report, unsupported_keys, JvmScope, UnsupportedKey, + boxed, distinct_install_dirs, distinct_npm_copies, find_all_packages_for_purls, + partition_purls, unsupported_ecosystem_report, unsupported_keys, JvmScope, UnsupportedKey, }; use crate::json_envelope::{ AppliedVia, Command, Envelope, EnvelopeError, PatchAction, PatchEvent, PatchEventFile, @@ -1836,6 +1836,7 @@ fn collect_apply_outcomes( ) -> (Vec, Vec) { let mut applied = Vec::new(); skipped.extend(caveats.not_in_build.iter().map(LeftCopy::event)); + skipped.extend(caveats.other_project.iter().map(OtherProjectCopy::event)); for result in results { let event = caveats.event_of(result, dry_run); match event.action { @@ -2060,7 +2061,12 @@ pub(crate) async fn run_locked( NpmPkgManager::Npm | NpmPkgManager::YarnClassic | NpmPkgManager::Unknown => {} } - match apply_patches_inner(&args, manifest, &user_patched, client).await { + // Boxed: this frame stays under the whole apply (see `boxed`). + let outcome = crate::ecosystem_dispatch::boxed(|| { + apply_patches_inner(&args, manifest, &user_patched, client) + }) + .await; + match outcome { Ok(ApplyOutcome { success, results, @@ -2213,6 +2219,9 @@ pub(crate) async fn run_locked( for skip in &fallback_skips { eprintln!("Warning: {}", skip.detail()); } + for copy in &caveats.other_project { + eprintln!("Warning: {}: {}", normalize_purl(©.purl), copy.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 @@ -2447,9 +2456,14 @@ pub(crate) async fn run_locked( for skip in &fallback_skips { env.record( PatchEvent::new(PatchAction::Skipped, skip.purl.clone()) - .with_reason("gem_fallback_home_skipped", skip.detail()), + .with_reason(FALLBACK_HOME_SKIPPED, skip.detail()), ); } + // Another project's gems: a code of their own, and never + // a failure either. + for copy in &caveats.other_project { + env.record(copy.event()); + } // Run-level advisories (the gem config-root containment // skip, the sources-unavailable reason): the envelope's // `warnings[]` is their machine channel — stderr is @@ -2980,7 +2994,8 @@ struct ApplyTally { 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. + /// ([`gem_ext::GemCaveat::NotInBuild`]), or is another project's gem + /// ([`OtherProjectCopy`]). 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 @@ -3017,6 +3032,7 @@ fn tally_results(results: &[ApplyResult], caveats: &GemCaveats) -> ApplyTally { .not_in_build .iter() .map(|copy| copy.purl.as_str()) + .chain(caveats.other_project.iter().map(|copy| copy.purl.as_str())) .filter(|purl| { !by_purl.contains_key(purl) && !vendored.contains(purl) && !not_in_effect.contains(purl) }) @@ -3377,6 +3393,10 @@ struct GemCaveats { /// Installed copies whose files match no record of their release /// (gem or PyPI). Each has a failed result, keyed by the base purl. no_variant: Vec, + /// Gems installed only where Bundler does not load the project's gems + /// from, and not in the Bundler lock the project has: skipped. They + /// have no result and do not fail the run. + other_project: Vec, } impl GemCaveats { @@ -3432,6 +3452,118 @@ fn format_patch_incomplete(purl: &str, what: &str) -> String { format!("Error: Patch of {purl} is incomplete: {what}") } +/// `errorCode` of a best-effort gem copy in a `gem env` home that `apply` +/// left unpatched ([`FallbackHomeSkip`]): the patch is in effect on the +/// copy bundler loads. Keyed by the base purl. +const FALLBACK_HOME_SKIPPED: &str = "gem_fallback_home_skipped"; + +/// `errorCode` of a record for another project's gem +/// ([`OtherProjectCopy`]): nothing was applied. Keyed by the manifest key. +const OTHER_PROJECT_COPY_SKIPPED: &str = "gem_other_project_copy_skipped"; + +/// One gem `apply` left as it was because its every copy sits in a +/// `gem env` home Bundler does not load the project's gems from, and the +/// Bundler lock the project has does not list it: another project's gem +/// (#2313). A record +/// for it is one an earlier release wrote when it patched such a copy, or +/// one a `get` of its purl wrote. It is a `Skipped` event of the patch, +/// not an apply result, and never fails the run. +struct OtherProjectCopy { + /// The manifest key of the patch. + purl: String, + /// Which copy, why it was left, and the `rollback` that drops the + /// record: in words. + detail: String, +} + +impl OtherProjectCopy { + fn event(&self) -> PatchEvent { + PatchEvent::new(PatchAction::Skipped, self.purl.clone()) + .with_reason(OTHER_PROJECT_COPY_SKIPPED, self.detail.as_str()) + } +} + +/// The gems of `unresolved` (the manifest keys with no copy to patch and +/// none in the lock inventory) that are another project's: a Bundler lock +/// was read, it does not name them as platform builds either, and +/// `rollback`'s resolver finds +/// a copy of them where this run's (`all_packages`, the copies `apply` +/// writes) found none, so each sits in a `gem env` home Bundler does not +/// load the project's gems from. The detail holds for a copy an earlier +/// release patched and for one nothing ever touched. +async fn other_project_gem_copies( + common: &GlobalArgs, + unresolved: &[String], + all_packages: &HashMap>, +) -> Vec { + if common.is_global() { + return Vec::new(); + } + let mut candidates: Vec = unresolved + .iter() + .filter(|purl| { + Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) + && !all_packages.contains_key(strip_purl_qualifiers(purl)) + }) + .cloned() + .collect(); + if candidates.is_empty() { + return Vec::new(); + } + // Only a Bundler lock that was read can say the project does not use + // a gem. With none (a gem library that commits no lock, a layout whose + // lock is not read) the gem may be the project's own, not installed in + // its path yet: it stays not installed. + let ctx = crate::commands::context::ProjectContext::new(common); + if !ctx.gem_lock_read().await { + return Vec::new(); + } + // The lock names a gem it holds only as precompiled platform builds, + // though the lock inventory behind `unresolved` leaves it out: that + // gem is the project's, and stays not installed. + let platform_only: HashSet = ctx + .gem_platform_only_purls() + .await + .iter() + .map(|purl| PurlKey::new(purl)) + .collect(); + candidates.retain(|purl| !platform_only.contains(&PurlKey::new(purl))); + if candidates.is_empty() { + return Vec::new(); + } + let mut found = crate::ecosystem_dispatch::find_all_packages_for_rollback( + &partition_purls(&candidates, None), + &common.crawler_options(), + true, + ) + .await; + candidates + .into_iter() + .filter_map(|purl| { + let path = found.remove(&purl)?.into_iter().next()?; + let mut command = format!( + "socket-patch rollback {}", + crate::ui::shell_word(strip_purl_qualifiers(&purl)) + ); + if common.cwd != Path::new(".") { + command.push_str(&format!( + " --cwd {}", + crate::ui::shell_word(&common.cwd.to_string_lossy()) + )); + } + let detail = format!( + "gem-env home copy at {} was not patched: Bundler does not load this \ + project's gems from that gem home, and the project's lock does not list \ + the gem, so it belongs to another project. Run `{command}` to remove the \ + patch from the manifest; it also restores the copy if an earlier release \ + patched it", + path.display() + ); + Some(OtherProjectCopy { purl, detail }) + }) + .collect() +} + /// 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 @@ -3686,6 +3818,12 @@ async fn apply_patches_inner( unmatched.sort(); let lockfile_only = Box::pin(lockfile_resolved(&args.common, &unmatched)).await; let unresolved = unresolved_purls(&unmatched, &lockfile_only); + // Another project's gems are a skip of their own: neither "not + // installed" nor a reason to fail. + let other_project = + boxed(|| other_project_gem_copies(&args.common, &unresolved, &all_packages)).await; + unmatched.retain(|purl| !other_project.iter().any(|copy| copy.purl == *purl)); + let unresolved = unresolved_purls(&unmatched, &lockfile_only); // This diagnostic flips the exit code, so it is an error — and it // prints even under --silent ("errors only", never a mute exit 1); // `--json` @@ -3705,7 +3843,10 @@ async fn apply_patches_inner( run_warnings, fallback_skips, unreported, - caveats: GemCaveats::default(), + caveats: GemCaveats { + other_project, + ..GemCaveats::default() + }, targeted: target_manifest_purls.len(), show_summary: true, nuget: NugetNotes::default(), @@ -3860,18 +4001,22 @@ async fn apply_patches_inner( _ => std::slice::from_ref(pkg_path), }; - // Copy CLASS decides FAILURE semantics (never write scope — - // patching a shared home's vulnerable copy is fine when it - // works): bundle-path store copies are PRIMARY and loud-fail; - // `gem env` fallback-home copies (rvm `@global`, system gem - // dirs — often root-owned, shared machine-wide) are - // BEST-EFFORT once a store copy applied — a mismatch or write - // failure there becomes a non-fatal per-copy Skipped warning, - // because the copy bundler actually loads is already patched. - // With NO store copy the fallback home IS the primary install - // (the historic pre-bundle-path layout, and every --global - // run) and keeps loud-fail parity. Store copies run first so - // best-effort is decidable when the fallback copies come up. + // Write scope is the resolver's: a `gem env` home copy that + // Bundler does not load for the project (under an explicit or + // deployment `path`, any gem but a default gem and Bundler) + // belongs to other projects and is not in `copy_paths` + // (#2313). Copy CLASS + // decides the FAILURE semantics of the copies that are: + // bundle-path store copies are PRIMARY and loud-fail; + // `gem env` home copies (rvm `@global`, system gem dirs — + // often root-owned, shared machine-wide) are BEST-EFFORT once + // a store copy applied — a mismatch or write failure there + // becomes a non-fatal per-copy Skipped warning, because the + // copy bundler actually loads is already patched. With NO store + // copy the home copy IS the primary install (Bundler using + // system gems, a default gem, and every --global run) and + // keeps loud-fail parity. Store copies run first so + // best-effort is decidable when the home copies come up. let (store_copies, home_copies): (Vec<&PathBuf>, Vec<&PathBuf>) = copy_paths .iter() .partition(|p| gem_store_dirs.iter().any(|s| p.starts_with(s))); @@ -4069,21 +4214,27 @@ async fn apply_patches_inner( // 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 outcome = gem_ext::apply_gem_package_patch( - args.common.read_scope(), - variant_purl, - pkg_path, - &patch.files, - &sources, - args.common.dry_run, - policy, - &gem_ext::RubyEnv { - cwd: args.common.cwd.clone(), - rebuild: !args.common.no_gem_native_rebuild, - offline: args.common.offline, - progress: args.common.gem_build_progress(), - }, - ) + let ruby_env = gem_ext::RubyEnv { + cwd: args.common.cwd.clone(), + rebuild: !args.common.no_gem_native_rebuild, + offline: args.common.offline, + progress: args.common.gem_build_progress(), + }; + // Boxed: the gem future is the largest this loop + // awaits, and this frame is under its whole + // rebuild (see `boxed`). + let outcome = crate::ecosystem_dispatch::boxed(|| { + gem_ext::apply_gem_package_patch( + args.common.read_scope(), + variant_purl, + pkg_path, + &patch.files, + &sources, + args.common.dry_run, + policy, + &ruby_env, + ) + }) .await; // A best-effort fallback-home copy's refusal, or // its incomplete patch, is its per-copy skip below, @@ -4464,6 +4615,12 @@ async fn apply_patches_inner( Box::pin(lockfile_resolved(&args.common, &unmatched)).await }; let unresolved = unresolved_purls(&unmatched, &lockfile_only); + // Another project's gems are a skip of their own: neither "not + // installed" nor a reason to fail. + caveats.other_project = + boxed(|| other_project_gem_copies(&args.common, &unresolved, &all_packages)).await; + unmatched.retain(|purl| !caveats.other_project.iter().any(|copy| copy.purl == *purl)); + let unresolved = unresolved_purls(&unmatched, &lockfile_only); // Nothing matched and some purl has no lock evidence either: this // fails the run, so it is an error — and errors print even under diff --git a/crates/socket-patch-cli/src/commands/context.rs b/crates/socket-patch-cli/src/commands/context.rs index ade912e2ba..c0ad7a59c2 100644 --- a/crates/socket-patch-cli/src/commands/context.rs +++ b/crates/socket-patch-cli/src/commands/context.rs @@ -99,6 +99,15 @@ impl<'a> ProjectContext<'a> { .await } + /// Whether bundler loads a lock in the project that socket-patch read + /// (`gem_lock_read_in`), through the same snapshot as [`Self::locks`]. + pub(crate) async fn gem_lock_read(&self) -> bool { + socket_patch_core::vendor::lock_inventory::gem_lock_read_in(&ProjectView::Snapshot( + &self.snapshot, + )) + .await + } + /// The lockfile wiring discovery of `--cwd` ([`super::discover_wiring_in`]). pub(crate) async fn discovery(&self) -> &Discovery { &self.recorded_discovery().await.0 diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index b5c603ab09..9a6c0e60ac 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -1044,7 +1044,25 @@ async fn filter_to_installed_purls( .collect() }; let partitioned = partition_purls(&bases, None); - let found = find_packages_for_rollback(&partitioned, &common.crawler_options(), true).await; + let mut found = find_packages_for_rollback(&partitioned, &common.crawler_options(), true).await; + // Agent mode patches installed copies in place: a gem `apply` has no + // copy to write for (another project's, in a `gem env` home Bundler + // does not load this project's gems from) is not installed here, as in + // `scan --mode agent` (#2313). + if mode == super::scan::ScanMode::Agent { + let options = common.crawler_options(); + // Boxed: the caller's frame holds a pointer, not the future. + let unloaded = crate::ecosystem_dispatch::boxed(|| { + crate::ecosystem_dispatch::gems_apply_never_writes( + found + .iter() + .map(|(purl, path)| (purl.clone(), path.clone())), + &options, + ) + }) + .await; + found.retain(|purl, _| !unloaded.contains(purl)); + } let mut present: HashSet = found.keys().map(|k| PurlKey::new(k)).collect(); let ctx = super::context::ProjectContext::new(common); @@ -1627,8 +1645,27 @@ pub async fn run(args: GetArgs) -> i32 { // no environment of its own is otherwise crawled only for the // packages it declares. let only = args.common.ecosystems.as_deref().filter(|l| !l.is_empty()); - let (all_packages, _, _) = + let (mut all_packages, _, _) = crawl_ecosystems_for_name(&args.common.crawler_options(), only).await; + // Agent mode patches installed copies in place: a gem `apply` + // has no copy to write for is not installed for this project, + // so its name resolves to nothing (#2313). `--save-only` + // applies nothing, and records by name as it does by purl or + // advisory. + if mode == super::scan::ScanMode::Agent && !args.save_only { + let options = args.common.crawler_options(); + // Boxed: `run`'s frame holds a pointer, not the future. + let unloaded = crate::ecosystem_dispatch::boxed(|| { + crate::ecosystem_dispatch::gems_apply_never_writes( + all_packages + .iter() + .map(|pkg| (pkg.purl.clone(), pkg.path.clone())), + &options, + ) + }) + .await; + all_packages.retain(|pkg| !unloaded.contains(&pkg.purl)); + } if all_packages.is_empty() { status.finish(); diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 6261f727c2..daa48cbd42 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -361,34 +361,89 @@ async fn patched_in_other_scope( let (Some(record), Some(paths)) = (manifest.patches.get(purl), found.get(purl)) else { continue; }; - 'copies: for path in paths { + for path in paths { // Both scopes can resolve to one tree (a `--cwd` inside the // global root): this run already verified that copy. if this_scope.contains(path.to_string_lossy().as_ref()) { continue; } - for (file, info) in &record.files { - let v = verify_file_rollback(path, file, info, &blobs).await; - // A file that is there but cannot be hashed may still hold - // the patched bytes: keep the record rather than strand it. - let unverifiable = v.current_hash.is_none() - && v.status != VerifyRollbackStatus::AlreadyOriginal - && !v.is_absent(); - // `Ready` also covers npm's LF-shebang form of a patched - // bin, whose hash is not the afterHash. - if unverifiable - || v.status == VerifyRollbackStatus::Ready - || v.current_hash.as_deref() == Some(info.after_hash.as_str()) - { - patched.push((purl.clone(), path.clone())); - break 'copies; - } + if copy_holds_patch(path, record, &blobs).await { + patched.push((purl.clone(), path.clone())); + break; } } } patched } +/// Whether some file of `record` in the copy at `path` still holds the +/// patch's afterHash content, or cannot be read to tell. +async fn copy_holds_patch(path: &Path, record: &PatchRecord, blobs: &Path) -> bool { + for (file, info) in &record.files { + let v = verify_file_rollback(path, file, info, blobs).await; + // A file that is there but cannot be hashed may still hold + // the patched bytes: keep the record rather than strand it. + let unverifiable = v.current_hash.is_none() + && v.status != VerifyRollbackStatus::AlreadyOriginal + && !v.is_absent(); + // `Ready` also covers npm's LF-shebang form of a patched + // bin, whose hash is not the afterHash. + if unverifiable + || v.status == VerifyRollbackStatus::Ready + || v.current_hash.as_deref() == Some(info.after_hash.as_str()) + { + return true; + } + } + false +} + +/// Drop from `copies` the gem copies this run has nothing to restore in: +/// a copy Bundler never loads for the project (another project's, in a +/// `gem env` home) that holds nothing of the patch. `apply` does not write +/// such a copy (#2313), so its content, as published or not, is neither +/// this project's to restore nor a failure of the rollback. A copy that +/// holds the patch stays, under every record of its release: an earlier +/// release patched it there, and the variant narrowing has to see it. +async fn drop_untouched_unloaded_gem_copies( + copies: &mut HashMap>, + manifest: &PatchManifest, + options: &CrawlerOptions, + blobs: &Path, +) { + let is_gem = |purl: &str| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem); + let mut loaded: HashMap> = copies + .iter() + .filter(|(purl, _)| is_gem(purl)) + .map(|(purl, paths)| (purl.clone(), paths.clone())) + .collect(); + if loaded.is_empty() { + return; + } + crate::ecosystem_dispatch::retain_bundler_loaded_gem_copies(&mut loaded, options).await; + let is_loaded = |purl: &str, path: &PathBuf| loaded.get(purl).is_some_and(|l| l.contains(path)); + // (base purl, copy) of the unloaded copies that hold the patch. + let mut patched: HashSet<(String, PathBuf)> = HashSet::new(); + for (purl, paths) in copies.iter().filter(|(purl, _)| is_gem(purl)) { + let Some(record) = manifest.patches.get(purl) else { + continue; + }; + for path in paths.iter().filter(|path| !is_loaded(purl, path)) { + let key = (strip_purl_qualifiers(purl).to_string(), path.clone()); + if !patched.contains(&key) && copy_holds_patch(path, record, blobs).await { + patched.insert(key); + } + } + } + for (purl, paths) in copies.iter_mut().filter(|(purl, _)| is_gem(purl)) { + let base = strip_purl_qualifiers(purl).to_string(); + paths.retain(|path| { + is_loaded(purl, path) || patched.contains(&(base.clone(), path.clone())) + }); + } + copies.retain(|_, paths| !paths.is_empty()); +} + /// `rollback`'s pointer at the scope that still holds a patched copy: a /// rollback of just that purl, naming `--cwd` when the run used one (the record lives in that /// project's manifest). The command names the release without the record's @@ -3427,6 +3482,18 @@ pub(crate) async fn rollback_patches_inner( common.silent || common.json, ) .await; + // Boxed, so this frame, which stays on the stack for the whole + // rollback, holds a pointer and not the future (see `boxed`). + let blobs_dir = socket_dir.join("blobs"); + crate::ecosystem_dispatch::boxed(|| { + drop_untouched_unloaded_gem_copies( + &mut all_packages_multi, + &scoped_manifest, + &crawler_options, + &blobs_dir, + ) + }) + .await; // The shared-cache copies of the vendored Cargo crates restored above // (#336), including those a `cargo vendor` dir hides from the crawl. let cache_purls: Vec = cache_patched diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 6c1b618640..ba243b791f 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2590,6 +2590,34 @@ async fn scan_project( None => crawl.await, }; + // Agent mode patches installed copies in place, and its apply step + // leaves alone a gem copy Bundler never loads for the project (another + // project's gem in a `gem env` home, under an explicit or deployment + // `path`). A gem with no other copy is not installed for this project + // (#2313): it leaves the crawl here, so one the lock lists is found + // again below as lockfile-only, like a gem with no copy at all, and + // any other is no candidate, like a gem installed nowhere. Nothing + // here says whose the gem is, so no lock is needed. The purls are kept for + // the prune universe: the copies are on disk, and a record an earlier + // release wrote for one must stay until `rollback` restores it. + let unloaded_gems = if apply { + // Boxed, so this frame, which stays on the stack for the whole + // scan, holds a pointer and not the future (see `boxed`). + let unloaded = boxed(|| { + crate::ecosystem_dispatch::gems_apply_never_writes( + all_crawled + .iter() + .map(|pkg| (pkg.purl.clone(), pkg.path.clone())), + &crawler_options, + ) + }) + .await; + all_crawled.retain(|pkg| !unloaded.contains(&pkg.purl)); + unloaded + } else { + HashSet::new() + }; + // Lockfile supplement: dependencies the project's lockfile resolves // that have NO installed copy (fresh clone, partial install). They join // discovery and are flagged "not yet installed". Scoped to the crawled @@ -2689,8 +2717,13 @@ async fn scan_project( // `--package` / PATH filters: prune must judge manifest entries against // the full installed set, or `scan --ecosystems npm --prune` would // delete every other ecosystem's entries. Lockfile-only purls are - // included so a wiped node_modules does not prune them. - let scanned_purls: HashSet = all_crawled.iter().map(|p| p.purl.clone()).collect(); + // included so a wiped node_modules does not prune them, and so are the + // gems an agent run left out of the crawl above. + let scanned_purls: HashSet = all_crawled + .iter() + .map(|p| p.purl.clone()) + .chain(unloaded_gems) + .collect(); // Vendor-ledger purl keys, shared by the prune exemption (a vendored // package's normal state is absent from the crawl) and the @@ -3911,12 +3944,12 @@ async fn scan_project( ); // The engine records into `env` and never prints: one JSON // document per run, a hard engine error included. - apply_code = download_and_apply_patches_into( - &selected, - ¶ms, - &download_run(&args, &api_client), - &mut env, - ) + // Boxed: this frame is under the whole download and apply + // chain, the deepest of a scan (see `boxed`). + let run = download_run(&args, &api_client); + apply_code = crate::ecosystem_dispatch::boxed(|| { + download_and_apply_patches_into(&selected, ¶ms, &run, &mut env) + }) .await; if env.error.is_some() { env.extra.remove("rollout"); diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index e5c28f452e..0004acc1a4 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -845,8 +845,10 @@ pub(crate) fn collapse_to_first(multi: HashMap>) -> HashMap /// For each ecosystem in the partitioned map, create the crawler, discover /// source paths, and look up the given PURLs. Returns a unified `purl -> -/// [paths]` map carrying EVERY physical copy (npm nests duplicates). Used -/// by `apply`, which patches all copies. +/// [paths]` map carrying EVERY physical copy (npm nests duplicates) the +/// project consumes: a Cargo or gem copy it never builds or loads is left +/// out (see the two `retain_*` calls). Used by `apply`, which patches all +/// of them, and by `vendor` to ask whether they all hold a patch. pub async fn find_all_packages_for_purls( partitioned: &HashMap>, options: &CrawlerOptions, @@ -871,6 +873,9 @@ pub async fn find_all_packages_for_purls( ) .await; retain_locked_cargo_copies(&mut found, options).await; + // Boxed, so that this future, which its callers build in their own + // frames, does not grow by the gem probes. + boxed(|| retain_bundler_loaded_gem_copies(&mut found, options)).await; found } @@ -896,6 +901,109 @@ async fn retain_locked_cargo_copies( copies.retain(|purl, _| !is_cargo(purl) || locked.contains_purl(purl)); } +/// Drop the gem copies Bundler never loads for a local project: a copy in +/// a `gem env` home (the system gems, an rbenv or asdf home, `~/.gem`) +/// while the project installs into an explicit or deployment `path` +/// (`RubyCrawler::bundler_unused_system_gem_homes`). Bundler fetches every +/// non-default gem into that path, so such a copy belongs to other +/// projects on the machine: patching it would change their code and +/// nothing this project runs (#2313), and an unpatched one must not block +/// an attestation (#1098). Default gems stay, and so does Bundler itself: +/// Bundler loads those from the gem home they are installed in under any +/// path. A purl left with no copy is dropped: the gem is not installed +/// for this project. The commands that patch, attest or select a patch +/// call this; rollback and remove restore a copy an earlier release +/// patched, and use it to tell that copy from one nothing touched. +pub(crate) async fn retain_bundler_loaded_gem_copies( + copies: &mut HashMap>, + options: &CrawlerOptions, +) { + let is_gem = |purl: &str| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem); + // The gem named `bundler` itself, whatever its version or qualifiers: + // `bundler-audit` and `bundler-2fa` are other gems. + let is_bundler = |purl: &str| { + strip_purl_qualifiers(purl) + .strip_prefix("pkg:gem/") + .and_then(|coordinate| coordinate.rsplit_once('@')) + .is_some_and(|(name, _)| name == "bundler") + }; + if options.global || options.global_prefix.is_some() || !copies.keys().any(|p| is_gem(p)) { + return; + } + // A copy in one of the project's own Bundler stores is always loaded. + // With every copy there (a populated `vendor/bundle`, where the crawler + // never asked `gem env` either) there is no home to ask it for. + let stores = RubyCrawler::discover_bundle_stores(&options.cwd) + .await + .stores; + let in_store = |path: &PathBuf| stores.iter().any(|store| path.starts_with(store)); + if copies + .iter() + .filter(|(purl, _)| is_gem(purl)) + .all(|(_, paths)| paths.iter().all(in_store)) + { + return; + } + let unused = RubyCrawler.bundler_unused_system_gem_homes(options).await; + if unused.is_empty() { + return; + } + for (purl, paths) in copies.iter_mut().filter(|(purl, _)| is_gem(purl)) { + // Bundler is never installed into a project's `path`: the one that + // runs is loaded from the gem home it was installed into, with its + // spec outside `specifications/default/`. Which version runs is not + // decided here (the lock's `BUNDLED WITH`, `BUNDLER_VERSION` and + // Bundler's own switch to the locked version all have a say), so + // every installed version stays. + if is_bundler(purl) { + continue; + } + paths.retain(|path| { + !unused.iter().any(|home| path.starts_with(home)) + || socket_patch_core::crawlers::ruby_crawler::is_default_gem_copy(path) + }); + } + copies.retain(|_, paths| !paths.is_empty()); +} + +/// The gems of `crawled` (a purl and the copy of it a crawl found) that +/// agent `apply` has no copy to write for: every installed copy is one +/// Bundler never loads for the project +/// ([`retain_bundler_loaded_gem_copies`]). For an agent-mode `scan` or +/// `get`, to which such a gem is not installed: selecting its patch would +/// record one the apply step has nowhere to write (#2313). A crawl reports +/// one copy per gem, so a gem that copy rules out is looked up again the +/// way `apply` looks it up: another gem home may hold it as a default gem. +pub(crate) async fn gems_apply_never_writes( + crawled: impl IntoIterator, + options: &CrawlerOptions, +) -> HashSet { + let mut copies: HashMap> = crawled + .into_iter() + .filter(|(purl, _)| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem)) + .map(|(purl, path)| (purl, vec![path])) + .collect(); + let crawled: Vec = copies.keys().cloned().collect(); + boxed(|| retain_bundler_loaded_gem_copies(&mut copies, options)).await; + let ruled_out: Vec = crawled + .into_iter() + .filter(|purl| !copies.contains_key(purl)) + .collect(); + if ruled_out.is_empty() { + return HashSet::new(); + } + let written: HashSet = + find_all_packages_for_purls(&partition_purls(&ruled_out, None), options, true) + .await + .keys() + .map(|purl| PurlKey::new(purl)) + .collect(); + ruled_out + .into_iter() + .filter(|purl| !written.contains(&PurlKey::new(purl))) + .collect() +} + /// Multi-copy variant of `find_packages_for_rollback` (qualified-aware /// merge). Used by `rollback`, which restores every physical copy. pub async fn find_all_packages_for_rollback( @@ -1371,26 +1479,8 @@ pub async fn find_manifest_package_copies_reusing( .map(|(_, paths)| paths), ) .await; - // A `gem env` home Bundler never loads this project's gems from (an - // explicit or deployment `path`) holds no copy the project runs, so an - // unpatched one there must not block the attestation (#1098). Default - // gems stay: Bundler loads those from the system home under any path. - if partitioned.contains_key(&Ecosystem::Gem) { - let unused = RubyCrawler - .bundler_unused_system_gem_homes(&crawler_options) - .await; - if !unused.is_empty() { - for (_, paths) in copies - .iter_mut() - .filter(|(purl, _)| purl.starts_with("pkg:gem/")) - { - paths.retain(|path| { - !unused.iter().any(|home| path.starts_with(home)) - || socket_patch_core::crawlers::ruby_crawler::is_default_gem_copy(path) - }); - } - } - } + // Only the gem copies Bundler loads for the project, as for `apply`. + boxed(|| retain_bundler_loaded_gem_copies(&mut copies, &crawler_options)).await; copies.retain(|_, paths| !paths.is_empty()); // Verification also READS a `.bundle/config` bundle path the crawler // refused as a write root (it resolves outside the project): bundler diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index b4e161706f..617f1ee3c6 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -1426,6 +1426,7 @@ mod tests { Some("package_not_installed"), Some("vendored"), Some("gem_fallback_home_skipped"), + Some("gem_other_project_copy_skipped"), None, ] { assert!(!skip_leaves_patched(code), "{code:?}"); diff --git a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs index 851ef7fb99..bf5739974a 100644 --- a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs +++ b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs @@ -1,22 +1,43 @@ -//! Store-class semantics for the gem multi-copy fan-out. +//! Which gem copies agent `apply` writes in the `gem env` homes (the +//! system gems, rvm `@global`, `--user-install`), and how a failure on +//! one of them is reported. //! -//! `get_gem_paths` appends the `gem env` fallback homes (rvm `@global`, -//! `--user-install`, system gem dirs) after the project's bundle-path -//! stores, and the multi-copy fan-out patches EVERY copy. Patching a -//! shared home's copy is fine (vulnerable bytes are vulnerable bytes) — -//! but its FAILURE semantics must not cross store classes: +//! `get_gem_paths` appends the `gem env` homes after the project's +//! bundle-path stores, because default gems (json, uri, …) only live +//! there. Whether a copy found in such a home is written follows what +//! Bundler loads for the project (#2313): //! -//! * copies in bundle-path stores are PRIMARY — loud-fail (unchanged); -//! * copies in gem-env fallback homes are BEST-EFFORT once at least one -//! bundle-store copy applied: a variant mismatch or write failure -//! there becomes a per-copy non-fatal `Skipped` event -//! (`gem_fallback_home_skipped`, with the path and reason), never a -//! run failure — the copy bundler actually loads was patched; -//! * with NO bundle-store copy (the historic fallback-only layout) the -//! home copy IS primary: loud-fail exactly as plain apply always -//! behaved. +//! * under an explicit Bundler `path` (app config, `BUNDLE_PATH`) or +//! deployment mode, Bundler installs every other gem into that path +//! and never loads one from a `gem env` home. A copy there belongs to +//! other projects on the machine, so `apply` leaves it alone. With no +//! other copy, a gem the lock lists is not installed yet (the calm +//! lockfile-only skip), and one a lock that was read does not list is +//! another project's gem: a skip of its own +//! (`gem_other_project_copy_skipped`) that names the copy and the +//! `rollback` that drops the record, never a failure. With no lock +//! read, nothing says whose the gem is: it stays not installed; +//! * a default gem (its spec under `specifications/default/`) and +//! Bundler itself are loaded from the gem home they are installed in +//! under any path, so they are still written. A bundled gem (rexml, +//! rake, …) has an ordinary spec and follows the ordinary rule; +//! * with no explicit path Bundler installs into and loads from the +//! `gem env` homes, so every copy there is written; +//! * `rollback` and `remove` still restore a copy there that holds the +//! patch: an earlier release may have patched it. //! -//! Unix-only: the fallback homes come from a fake `gem` binary on PATH. +//! FAILURE semantics of the copies that are written: +//! +//! * copies in bundle-path stores are PRIMARY — loud-fail; +//! * a `gem env` home copy is BEST-EFFORT once at least one bundle-store +//! copy applied: a variant mismatch or write failure there becomes a +//! per-copy non-fatal `Skipped` event (`gem_fallback_home_skipped`, +//! with the path and reason), never a run failure — the copy bundler +//! actually loads was patched; +//! * with NO bundle-store copy the home copy IS primary: loud-fail +//! exactly as plain apply always behaved. +//! +//! Unix-only: the `gem env` home comes from a fake `gem` binary on PATH. #![cfg(unix)] @@ -31,6 +52,8 @@ use super::apply_fixture::{ use crate::common::git_sha256; const SKIP_CODE: &str = "gem_fallback_home_skipped"; +const OTHER_PROJECT: &str = "gem_other_project_copy_skipped"; +const NOT_INSTALLED: &str = "package_not_installed"; const ORIGINAL: &[u8] = b"module Rack\n VERSION = 'VULNERABLE'\nend\n"; const MARKER: &[u8] = b"# SOCKET-PATCHED-FALLBACK\n"; @@ -42,7 +65,7 @@ fn patched_bytes() -> Vec { } /// Fake `gem` answering `env gemdir` with `home` (and an empty `gempath` -/// failure), so the crawler's fallback resolves to exactly one home. +/// failure), so the crawler's `gem env` homes resolve to exactly one. fn install_fake_gem(bin_dir: &Path, home: &Path) { use std::os::unix::fs::PermissionsExt; let script = format!( @@ -68,31 +91,71 @@ fn stage_copy(root: &Path, bytes: &[u8]) -> PathBuf { file } +/// Where Bundler installs the project's gems. +#[derive(Clone, Copy, PartialEq)] +enum Store { + /// No `path` setting: Bundler installs into, and loads from, the + /// `gem env` homes. + SystemGems, + /// `BUNDLE_PATH` names a store with nothing installed in it yet (a + /// fresh clone before `bundle install`). + ExplicitEmpty, + /// `BUNDLE_PATH` names a store holding a pristine copy. + Explicit, + /// No `path` setting, and the default `vendor/bundle` holds a + /// pristine copy (a deployment-style install). + VendorBundle, +} + +/// The home copy is an ordinary installed gem, or one of Ruby's default +/// gems (spec under `specifications/default/`). +#[derive(Clone, Copy, PartialEq)] +enum Home { + Installed, + DefaultGem, +} + struct Fixture { project: tempfile::TempDir, store_file: Option, home_file: PathBuf, bin_dir: PathBuf, - store_root: Option, + /// The `BUNDLE_PATH` the runs export, when the store is explicit. + bundle_path: Option, } -/// Project with a Gemfile; optionally an env-`BUNDLE_PATH` store copy -/// (pristine); a gem-env fallback home copy with `home_bytes`; manifest -/// keyed by `purl`. -fn build_fixture(with_store: bool, home_bytes: &[u8], purl: &str) -> Fixture { +/// Project with a Gemfile; a bundle store per `store`; a `gem env` home +/// copy with `home_bytes`; manifest keyed by `purl`, with the patched and +/// the original blob staged (apply reads the first, rollback the second). +fn build_fixture(store: Store, home: Home, home_bytes: &[u8], purl: &str) -> Fixture { let project = tempfile::tempdir().unwrap(); let root = project.path(); std::fs::write(root.join("Gemfile"), b"source 'https://rubygems.org'\n").unwrap(); - let store_root = with_store.then(|| root.join("bundle-store")); - let store_file = store_root.as_ref().map(|s| stage_copy(s, ORIGINAL)); + let store_root = match store { + Store::SystemGems => None, + Store::ExplicitEmpty | Store::Explicit => Some(root.join("bundle-store")), + Store::VendorBundle => Some(root.join("vendor").join("bundle")), + }; + let store_file = match store { + Store::Explicit | Store::VendorBundle => { + Some(stage_copy(store_root.as_ref().unwrap(), ORIGINAL)) + } + Store::SystemGems | Store::ExplicitEmpty => None, + }; + let bundle_path = store_root.filter(|_| store != Store::VendorBundle); - let home = root.join("gem-home"); - let home_file = stage_copy(&home, home_bytes); + let home_root = root.join("gem-home"); + let home_file = stage_copy(&home_root, home_bytes); + if home == Home::DefaultGem { + let default_specs = home_root.join("specifications").join("default"); + std::fs::create_dir_all(&default_specs).unwrap(); + std::fs::write(default_specs.join("rack-3.1.0.gemspec"), b"").unwrap(); + } let bin_dir = root.join("fake-bin"); std::fs::create_dir_all(&bin_dir).unwrap(); - install_fake_gem(&bin_dir, &home); + install_fake_gem(&bin_dir, &home_root); let patched = patched_bytes(); write_manifest( @@ -103,60 +166,807 @@ fn build_fixture(with_store: bool, home_bytes: &[u8], purl: &str) -> Fixture { )}), ); stage_blob(root, &git_sha256(&patched), &patched); + stage_blob(root, &git_sha256(ORIGINAL), ORIGINAL); Fixture { project, store_file, home_file, bin_dir, - store_root, + bundle_path, } } -/// Run apply with the hermetic SOCKET_* env and BUNDLE_* scrubbed, PATH = -/// the fake-gem bin dir only, and BUNDLE_PATH set to the store root when -/// present. -fn run_apply(fx: &Fixture, extra: &[&str]) -> (i32, String, String) { +/// A `Gemfile.lock` that resolves the fixture's gem. +fn write_lock(fx: &Fixture) { + std::fs::write( + fx.project.path().join("Gemfile.lock"), + "GEM\n remote: https://rubygems.org/\n specs:\n rack (3.1.0)\n\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n rack\n\nBUNDLED WITH\n 2.5.22\n", + ) + .unwrap(); +} + +/// A `Gemfile.lock` of the project that does not list the fixture's gem. +fn write_lock_without_the_gem(fx: &Fixture) { + std::fs::write( + fx.project.path().join("Gemfile.lock"), + "GEM\n remote: https://rubygems.org/\n specs:\n colorize (1.1.0)\n\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n colorize\n\nBUNDLED WITH\n 2.5.22\n", + ) + .unwrap(); +} + +/// Run ` --offline --ecosystems gem --cwd ` with +/// the hermetic SOCKET_* env and BUNDLE_* scrubbed, PATH = the fake-gem +/// bin dir only, and BUNDLE_PATH set when the fixture's store is explicit. +fn run_command(fx: &Fixture, command: &[&str], extra: &[&str]) -> (i32, String, String) { let cwd = fx.project.path().to_str().unwrap(); - let mut argv = vec!["apply", "--offline", "--ecosystems", "gem", "--cwd", cwd]; + let mut argv = command.to_vec(); + argv.extend_from_slice(&["--offline", "--ecosystems", "gem", "--cwd", cwd]); argv.extend_from_slice(extra); let bin_dir = fx.bin_dir.to_str().unwrap(); let mut env = vec![("PATH", bin_dir)]; - if let Some(store_root) = &fx.store_root { - env.push(("BUNDLE_PATH", store_root.to_str().unwrap())); + if let Some(bundle_path) = &fx.bundle_path { + env.push(("BUNDLE_PATH", bundle_path.to_str().unwrap())); } run_gem(Path::new("."), &argv, &env) } +fn run_apply(fx: &Fixture, extra: &[&str]) -> (i32, String, String) { + run_command(fx, &["apply"], extra) +} + fn parse_env(stdout: &str) -> serde_json::Value { serde_json::from_str(stdout.trim()) - .unwrap_or_else(|e| panic!("apply must emit JSON: {e}; stdout={stdout}")) + .unwrap_or_else(|e| panic!("the run must emit JSON: {e}; stdout={stdout}")) } -fn find_skip_event(env: &serde_json::Value) -> Option<&serde_json::Value> { +/// The first event with `action` and `errorCode` = `code` (`with_reason` +/// serializes its stable tag as `errorCode`). +fn find_event<'a>( + env: &'a serde_json::Value, + action: &str, + code: &str, +) -> Option<&'a serde_json::Value> { env["events"].as_array().and_then(|events| { events.iter().find(|e| { - e["action"] == "skipped" - // `with_reason` serializes its stable tag as `errorCode`. - && e.get("errorCode").and_then(|c| c.as_str()) == Some(SKIP_CODE) + e["action"] == action && e.get("errorCode").and_then(|c| c.as_str()) == Some(code) }) }) } -/// (a) Store copy patched + home copy that matches NO variant (foreign -/// bytes, qualified record): the home copy becomes a per-copy non-fatal -/// `Skipped` event naming its path — exit 0, `applied` counts the store -/// copy. Before the fix this failed the WHOLE run ("no matching variant -/// found", exit 1) even though the copy bundler loads patched fine. +fn find_skip_event(env: &serde_json::Value) -> Option<&serde_json::Value> { + find_event(env, "skipped", SKIP_CODE) +} + +/// The skip of a record for another project's gem. +fn find_other_project_skip(env: &serde_json::Value) -> Option<&serde_json::Value> { + find_event(env, "skipped", OTHER_PROJECT) +} + +fn home_dir(fx: &Fixture) -> PathBuf { + fx.project.path().join("gem-home") +} + +/// The keys of the fixture's `.socket/manifest.json`. +fn manifest_purls(fx: &Fixture) -> Vec { + let manifest: serde_json::Value = serde_json::from_slice( + &std::fs::read(fx.project.path().join(".socket").join("manifest.json")).unwrap(), + ) + .unwrap(); + manifest["patches"] + .as_object() + .map(|patches| patches.keys().cloned().collect()) + .unwrap_or_default() +} + +// ── Write scope ───────────────────────────────────────────────────────── + +/// Explicit path with the gem installed in it, and a same-version copy in +/// the `gem env` home: only the project's copy is written. Bundler never +/// loads the home copy for this project, and other projects may (#2313). +#[test] +fn explicit_path_leaves_the_gem_env_home_copy_alone() { + let fx = build_fixture(Store::Explicit, Home::Installed, ORIGINAL, QUALIFIED_PURL); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!( + env["summary"]["applied"], 1, + "only the project's copy counts.\nenvelope: {env}" + ); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + patched_bytes(), + "the project's copy must be patched" + ); + assert_eq!( + std::fs::read(&fx.home_file).unwrap(), + ORIGINAL, + "the gem env home copy must be left untouched" + ); + assert!( + !stdout.contains(&home_dir(&fx).display().to_string()), + "no event names the home copy: it is not a copy of this project.\nenvelope: {env}" + ); + assert!(find_skip_event(&env).is_none(), "envelope: {env}"); + + // `apply --check` agrees: the tree is in sync. + let (code, stdout, stderr) = run_apply(&fx, &["--check"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); +} + +/// The human render of the same run: one patched package, one summary +/// line, and no line about the home copy. +#[test] +fn explicit_path_human_run_lists_only_the_project_copy() { + let fx = build_fixture(Store::Explicit, Home::Installed, ORIGINAL, QUALIFIED_PURL); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stdout.contains( + "Summary: 1 of 1 targeted patch applied, 0 already patched, 0 not found on disk" + ), + "stdout={stdout}" + ); + let out = format!("{stdout}{stderr}"); + assert!( + !out.contains(&home_dir(&fx).display().to_string()), + "the home copy is not mentioned; output={out}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// Explicit path with nothing installed in it, and a lock that does not +/// list the gem: the copy in the `gem env` home is another project's. +/// Nothing is written, and the record is a skip of its own that names the +/// copy and the `rollback` that drops the record. It is not "not +/// installed", and it does not fail the run. +#[test] +fn explicit_path_with_only_another_projects_copy_is_a_calm_skip() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + write_lock_without_the_gem(&fx); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!( + std::fs::read(&fx.home_file).unwrap(), + ORIGINAL, + "the gem env home copy must be left untouched" + ); + assert_eq!( + env["summary"]["applied"], 0, + "nothing was applied.\nenvelope: {env}" + ); + assert!( + find_event(&env, "skipped", NOT_INSTALLED).is_none(), + "the gem is installed, elsewhere.\nenvelope: {env}" + ); + let skip = find_other_project_skip(&env) + .unwrap_or_else(|| panic!("the copy must be a {OTHER_PROJECT} skip.\nenvelope: {env}")); + assert_eq!(skip["purl"], QUALIFIED_PURL, "envelope: {env}"); + assert!(find_skip_event(&env).is_none(), "envelope: {env}"); + let reason = skip["reason"].as_str().unwrap_or_default(); + let rollback = format!( + "socket-patch rollback {BASE_PURL} --cwd {}", + fx.project.path().display() + ); + assert!( + reason.contains(&home_dir(&fx).display().to_string()) && reason.contains(&rollback), + "the skip must name the copy and the rollback; got: {reason}" + ); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stderr.contains(&format!("Warning: {QUALIFIED_PURL}: gem-env home copy at ")) + && stderr.contains("belongs to another project") + && stderr.contains(&rollback), + "stderr={stderr}" + ); + assert!(!stderr.contains("Error:"), "stderr={stderr}"); + assert!( + stdout.contains( + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not applicable, \ + 0 not found on disk" + ), + "stdout={stdout}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + + // `--silent` is errors only, and this is not one. + let (code, stdout, stderr) = run_apply(&fx, &["--silent"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(format!("{stdout}{stderr}"), ""); +} + +/// A project with no `Gemfile.lock` (a gem library that commits none): +/// nothing was read that could say the project does not use the gem, so +/// the copy in the `gem env` home is not called another project's and no +/// `rollback` is advised. The gem may be the project's own, not installed +/// in its path yet: it keeps the not-installed result, which fails a run +/// that matched nothing. #[test] -fn mismatched_fallback_home_copy_is_nonfatal_when_store_patched() { +fn lockless_project_keeps_the_not_installed_result() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + assert!(!fx.project.path().join("Gemfile.lock").exists()); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 1, "envelope: {env}\nstderr:\n{stderr}"); + let skip = find_event(&env, "skipped", NOT_INSTALLED) + .unwrap_or_else(|| panic!("the gem must be reported as {NOT_INSTALLED}.\nenvelope: {env}")); + assert_eq!(skip["purl"], QUALIFIED_PURL, "envelope: {env}"); + assert!(find_other_project_skip(&env).is_none(), "envelope: {env}"); + assert!(!stdout.contains("rollback"), "envelope: {env}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 1, "stdout={stdout}\nstderr={stderr}"); + assert!( + stderr.contains("Error: The targeted manifest patch matched no installed package:"), + "stderr={stderr}" + ); + assert!( + !stderr.contains("another project") && !stderr.contains("rollback"), + "stderr={stderr}" + ); + assert!( + stdout.contains( + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not found on disk" + ), + "stdout={stdout}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// A lock on disk that bundler may not load is not a lock that was read: +/// with a `gems.rb` beside the `Gemfile`, which pair loads depends on the +/// Bundler that runs, so the `Gemfile.lock` here says nothing of the gem. +/// It keeps the not-installed result, and no `rollback` is advised. +#[test] +fn unread_lock_of_a_twin_manifest_keeps_the_not_installed_result() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + write_lock_without_the_gem(&fx); + std::fs::write( + fx.project.path().join("gems.rb"), + b"source 'https://rubygems.org'\n", + ) + .unwrap(); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 1, "envelope: {env}\nstderr:\n{stderr}"); + assert!( + find_event(&env, "skipped", NOT_INSTALLED).is_some(), + "envelope: {env}" + ); + assert!(find_other_project_skip(&env).is_none(), "envelope: {env}"); + assert!(!stdout.contains("rollback"), "envelope: {env}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// The gem in no gem home at all, and not in the lock: nothing says where +/// it is, so this stays the all-miss failure of any package that is not +/// installed. +#[test] +fn gem_with_no_copy_anywhere_and_no_lock_entry_still_fails() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + write_lock_without_the_gem(&fx); + std::fs::remove_dir_all(home_dir(&fx).join("gems").join("rack-3.1.0")).unwrap(); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 1, "envelope: {env}\nstderr:\n{stderr}"); + let skip = find_event(&env, "skipped", NOT_INSTALLED) + .unwrap_or_else(|| panic!("the gem must be reported as {NOT_INSTALLED}.\nenvelope: {env}")); + assert_eq!(skip["purl"], QUALIFIED_PURL, "envelope: {env}"); + assert!(find_other_project_skip(&env).is_none(), "envelope: {env}"); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 1, "stdout={stdout}\nstderr={stderr}"); + assert!( + stderr.contains("Error: The targeted manifest patch matched no installed package:"), + "stderr={stderr}" + ); + assert!( + stdout.contains( + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not found on disk" + ), + "stdout={stdout}" + ); +} + +/// A gem the lock holds only as a precompiled platform build is the +/// project's, though the lock inventory leaves it out. With the path +/// still empty and a copy of the version in the `gem env` home, it is not +/// another project's gem: it stays the not-installed failure it was, and +/// nothing tells the user to roll back a patch the project needs. +#[test] +fn gem_the_lock_holds_as_a_platform_build_is_not_another_projects() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + std::fs::write( + fx.project.path().join("Gemfile.lock"), + "GEM\n remote: https://rubygems.org/\n specs:\n rack (3.1.0-x86_64-linux)\n\n\ + PLATFORMS\n x86_64-linux\n\nDEPENDENCIES\n rack\n\nBUNDLED WITH\n 2.5.22\n", + ) + .unwrap(); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert!( + find_other_project_skip(&env).is_none(), + "the gem is the project's.\nenvelope: {env}" + ); + assert!( + find_event(&env, "skipped", NOT_INSTALLED).is_some(), + "envelope: {env}" + ); + assert_eq!(code, 1, "envelope: {env}\nstderr:\n{stderr}"); + assert!(!stdout.contains("rollback"), "envelope: {env}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// The other project's copy beside a gem of this project that is patched: +/// the run still succeeds, the copy has its skip, and nothing is reported +/// as having no installed package. +#[test] +fn another_projects_copy_beside_a_patched_gem_is_a_skip_not_a_warning() { + let fx = build_fixture(Store::Explicit, Home::DefaultGem, ORIGINAL, QUALIFIED_PURL); + write_lock(&fx); + // A second record, for a gem only the gem env home holds. + let other = home_dir(&fx) + .join("gems") + .join("thor-1.3.0") + .join("lib") + .join("thor.rb"); + std::fs::create_dir_all(other.parent().unwrap()).unwrap(); + std::fs::write(&other, ORIGINAL).unwrap(); + let patched = patched_bytes(); + write_manifest( + fx.project.path(), + json!({ + QUALIFIED_PURL: patch_record( + "66616c6c-6261-4b63-8368-6f6d65000000", + one_file("lib/rack.rb", ORIGINAL, &patched), + ), + "pkg:gem/thor@1.3.0?platform=ruby": patch_record( + "66616c6c-6261-4b63-8368-6f6d65000001", + one_file("lib/thor.rb", ORIGINAL, &patched), + ), + }), + ); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stdout.contains( + "Summary: 1 of 2 targeted patches applied, 0 already patched, 1 not applicable, \ + 0 not found on disk" + ), + "stdout={stdout}" + ); + assert!( + stderr.contains("Warning: pkg:gem/thor@1.3.0?platform=ruby: gem-env home copy at "), + "stderr={stderr}" + ); + assert!( + !stderr.contains("had no matching installed package"), + "stderr={stderr}" + ); + assert_eq!(std::fs::read(&other).unwrap(), ORIGINAL); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched); +} + +/// The same fresh clone with a `Gemfile.lock` that resolves the gem: a +/// calm lockfile-only skip, exit 0. The `bundle install` that follows puts +/// the gem in the project's path, and the next `apply` patches it there. +#[test] +fn explicit_path_with_nothing_installed_is_a_calm_skip_under_a_lock() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + write_lock(&fx); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!(env["summary"]["applied"], 0, "envelope: {env}"); + let skip = find_event(&env, "skipped", NOT_INSTALLED) + .unwrap_or_else(|| panic!("the gem must be reported as {NOT_INSTALLED}.\nenvelope: {env}")); + assert_eq!(skip["purl"], QUALIFIED_PURL, "envelope: {env}"); + assert!( + skip["reason"] + .as_str() + .unwrap_or_default() + .contains("lockfile-only"), + "envelope: {env}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stderr.contains( + "Note: 1 manifest patch targets a package not installed on this host \ + (resolved by the project lockfile; skipped):" + ), + "stderr={stderr}" + ); + assert!( + stdout.contains( + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not found on disk" + ), + "stdout={stdout}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// A default gem only ever lives in the system home, and Bundler loads it +/// from there under any path: it is still patched. +#[test] +fn default_gem_in_the_gem_env_home_is_still_patched() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::DefaultGem, + ORIGINAL, + QUALIFIED_PURL, + ); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!(env["summary"]["applied"], 1, "envelope: {env}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched_bytes()); + + let (code, stdout, stderr) = run_apply(&fx, &["--check"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); +} + +/// A default gem beside the same version in the project's path: both +/// copies are patched (the multi-copy guarantee), exit 0, applied counts +/// both. +#[test] +fn default_gem_home_copy_is_patched_beside_the_store_copy() { + let fx = build_fixture(Store::Explicit, Home::DefaultGem, ORIGINAL, QUALIFIED_PURL); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + env["summary"]["applied"], 2, + "both copies count.\nenvelope: {env}" + ); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + patched_bytes() + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched_bytes()); + assert!( + find_skip_event(&env).is_none(), + "healthy home copies are patched, never best-effort-skipped.\nenvelope: {env}" + ); +} + +/// With no explicit path Bundler installs into and loads from the +/// `gem env` homes: the copy there is the project's, and is patched. +#[test] +fn system_gems_home_copy_is_patched() { + let fx = build_fixture(Store::SystemGems, Home::Installed, ORIGINAL, QUALIFIED_PURL); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!(env["summary"]["applied"], 1, "envelope: {env}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched_bytes()); + + // The human render, on a fresh tree. + let fx = build_fixture(Store::SystemGems, Home::Installed, ORIGINAL, QUALIFIED_PURL); + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stdout.contains( + "Summary: 1 of 1 targeted patch applied, 0 already patched, 0 not found on disk" + ), + "stdout={stdout}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched_bytes()); +} + +/// Bundler is never installed into the project's path: the copy that +/// `gem install bundler` put in the gem home, with its spec outside +/// `specifications/default/`, is the one the project runs. `apply` +/// patches it, and `apply --check` judges it: drift before, in sync after. +#[test] +fn bundler_in_the_gem_env_home_is_patched_and_checked() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + write_lock_without_the_gem(&fx); + let home = home_dir(&fx); + std::fs::remove_dir_all(home.join("gems").join("rack-3.1.0")).unwrap(); + let file = home + .join("gems") + .join("bundler-2.6.9") + .join("lib") + .join("bundler.rb"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, ORIGINAL).unwrap(); + std::fs::write( + home.join("specifications").join("bundler-2.6.9.gemspec"), + b"", + ) + .unwrap(); + // A gem whose name only starts with `bundler-` is an ordinary gem, + // even when a digit follows. + let other = home + .join("gems") + .join("bundler-2fa-1.0.0") + .join("lib") + .join("bundler-2fa.rb"); + std::fs::create_dir_all(other.parent().unwrap()).unwrap(); + std::fs::write(&other, ORIGINAL).unwrap(); + let patched = patched_bytes(); + const BUNDLER: &str = "pkg:gem/bundler@2.6.9?platform=ruby"; + const OTHER: &str = "pkg:gem/bundler-2fa@1.0.0?platform=ruby"; + write_manifest( + fx.project.path(), + json!({ + BUNDLER: patch_record( + "66616c6c-6261-4b63-8368-6f6d65000002", + one_file("lib/bundler.rb", ORIGINAL, &patched), + ), + OTHER: patch_record( + "66616c6c-6261-4b63-8368-6f6d65000003", + one_file("lib/bundler-2fa.rb", ORIGINAL, &patched), + ), + }), + ); + + let (code, stdout, stderr) = run_apply(&fx, &["--check"]); + assert_eq!( + code, 1, + "the unpatched Bundler is drift.\nstdout={stdout}\nstderr={stderr}" + ); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "envelope: {env}"); + assert_eq!(std::fs::read(&file).unwrap(), patched); + assert_eq!( + std::fs::read(&other).unwrap(), + ORIGINAL, + "bundler-2fa is another project's gem" + ); + let skip = find_other_project_skip(&env) + .unwrap_or_else(|| panic!("bundler-2fa must be a {OTHER_PROJECT} skip.\nenvelope: {env}")); + assert_eq!(skip["purl"], OTHER, "envelope: {env}"); + + let (code, stdout, stderr) = run_apply(&fx, &["--check"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); +} + +/// A deployment-style install under the default `vendor/bundle`: that +/// store is the project's one gem source, so the `gem env` home is not +/// searched and its copy is left alone. +#[test] +fn vendor_bundle_store_leaves_the_gem_env_home_copy_alone() { + let fx = build_fixture( + Store::VendorBundle, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "envelope: {env}"); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + patched_bytes() + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// A copy in the `gem env` home that an earlier release patched under an +/// explicit path stays restorable: `rollback` finds and restores it, with +/// the project's copy. +#[test] +fn rollback_restores_a_home_copy_an_earlier_run_patched() { + let patched = patched_bytes(); + let fx = build_fixture(Store::Explicit, Home::Installed, &patched, QUALIFIED_PURL); + std::fs::write(fx.store_file.as_ref().unwrap(), &patched).unwrap(); + + let (code, stdout, stderr) = run_command(&fx, &["rollback"], &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(&fx.home_file).unwrap(), + ORIGINAL, + "the home copy must be restored.\nenvelope: {env}" + ); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + ORIGINAL, + "the project's copy must be restored.\nenvelope: {env}" + ); +} + +/// A copy in the `gem env` home that an earlier release patched BESIDE +/// the project's own copy stays patched, and `apply` says nothing of it. +/// `rollback --preserve-state` restores both and keeps the record, and +/// the `apply` after it patches the project's copy alone. +#[test] +fn rollback_preserving_state_then_apply_unpatches_only_the_shared_copy() { + let patched = patched_bytes(); + let fx = build_fixture(Store::Explicit, Home::Installed, &patched, QUALIFIED_PURL); + write_lock(&fx); + let store_file = fx.store_file.as_ref().unwrap(); + std::fs::write(store_file, &patched).unwrap(); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + !format!("{stdout}{stderr}").contains(&home_dir(&fx).display().to_string()), + "apply does not mention the shared copy.\nstdout={stdout}\nstderr={stderr}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched); + + let (code, stdout, stderr) = run_command(&fx, &["rollback"], &["--preserve-state"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(std::fs::read(store_file).unwrap(), ORIGINAL); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + assert_eq!(manifest_purls(&fx), vec![QUALIFIED_PURL.to_string()]); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(std::fs::read(store_file).unwrap(), patched); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// The `rollback` that `apply` names for another project's copy works +/// whatever that copy holds: one an earlier release patched is restored, +/// and one nothing ever wrote (as published, or with other content) is +/// left as it is. The record goes each time, and the run exits 0. +#[test] +fn rollback_of_another_projects_copy_drops_the_record_whatever_it_holds() { + let patched = patched_bytes(); + let mut diverged = ORIGINAL.to_vec(); + diverged.extend_from_slice(b"# another project's edit\n"); + for (held, left) in [ + (patched.as_slice(), ORIGINAL), + (ORIGINAL, ORIGINAL), + (diverged.as_slice(), diverged.as_slice()), + ] { + let fx = build_fixture(Store::ExplicitEmpty, Home::Installed, held, QUALIFIED_PURL); + write_lock_without_the_gem(&fx); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), held); + + let (code, stdout, stderr) = run_command(&fx, &["rollback"], &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(&fx.home_file).unwrap(), + left, + "envelope: {env}" + ); + assert_eq!(manifest_purls(&fx), Vec::::new(), "envelope: {env}"); + } +} + +/// A copy of another project that holds neither side of the patch, beside +/// the project's own patched copy: `rollback` restores the project's copy +/// and does not fail on a copy `apply` never wrote. +#[test] +fn rollback_does_not_fail_on_another_projects_diverged_copy() { + let mut diverged = ORIGINAL.to_vec(); + diverged.extend_from_slice(b"# another project's edit\n"); + let fx = build_fixture(Store::Explicit, Home::Installed, &diverged, QUALIFIED_PURL); + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + patched_bytes() + ); + + let (code, stdout, stderr) = run_command(&fx, &["rollback"], &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + ORIGINAL + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), diverged); + assert_eq!(manifest_purls(&fx), Vec::::new(), "envelope: {env}"); +} + +/// `remove` restores such a copy too, and drops the record. +#[test] +fn remove_restores_a_home_copy_an_earlier_run_patched() { + let patched = patched_bytes(); + let fx = build_fixture(Store::Explicit, Home::Installed, &patched, QUALIFIED_PURL); + std::fs::write(fx.store_file.as_ref().unwrap(), &patched).unwrap(); + + let (code, stdout, stderr) = run_command(&fx, &["remove", BASE_PURL], &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(&fx.home_file).unwrap(), + ORIGINAL, + "the home copy must be restored.\nenvelope: {env}" + ); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + ORIGINAL, + "the project's copy must be restored.\nenvelope: {env}" + ); + assert_eq!( + manifest_purls(&fx), + Vec::::new(), + "the record must be dropped" + ); +} + +// ── Failure semantics of a home copy that is written ──────────────────── + +/// Store copy patched + a default gem's home copy that matches NO variant +/// (foreign bytes, qualified record): the home copy becomes a per-copy +/// non-fatal `Skipped` event naming its path — exit 0, `applied` counts +/// the store copy. +#[test] +fn mismatched_home_copy_is_nonfatal_when_store_patched() { let foreign = b"totally different bytes\n"; - let fx = build_fixture(true, foreign, QUALIFIED_PURL); + let fx = build_fixture(Store::Explicit, Home::DefaultGem, foreign, QUALIFIED_PURL); let (code, stdout, stderr) = run_apply(&fx, &["--json"]); let env = parse_env(&stdout); assert_eq!( code, 0, - "a mismatched fallback-home copy must not fail the run.\nenvelope: {env}\nstderr:\n{stderr}" + "a mismatched home copy must not fail the run.\nenvelope: {env}\nstderr:\n{stderr}" ); assert_eq!(env["status"], "success", "envelope: {env}"); assert_eq!( @@ -180,26 +990,23 @@ fn mismatched_fallback_home_copy_is_nonfatal_when_store_patched() { assert_eq!(skip["purl"], BASE_PURL, "envelope: {env}"); let reason = skip["reason"].as_str().unwrap_or_default(); assert!( - reason.contains( - &fx.home_file - .parent() - .unwrap() - .parent() - .unwrap() - .display() - .to_string() - ) || reason.contains(&fx.home_file.display().to_string()), - "skip reason must name the fallback-home copy path; got: {reason}" + reason.contains(&home_dir(&fx).display().to_string()), + "skip reason must name the home copy path; got: {reason}" ); } /// `apply --check` uses the same copy classes: once the store copy is -/// patched, a fallback-home copy no variant matches is no drift — `apply` -/// left it alone and exited 0, so the check must not send CI back to an -/// `apply` that will never act on it. +/// patched, a home copy no variant matches is no drift — `apply` left it +/// alone and exited 0, so the check must not send CI back to an `apply` +/// that will never act on it. #[test] -fn check_ignores_a_mismatched_fallback_home_copy_when_store_patched() { - let fx = build_fixture(true, b"totally different bytes\n", QUALIFIED_PURL); +fn check_ignores_a_mismatched_home_copy_when_store_patched() { + let fx = build_fixture( + Store::Explicit, + Home::DefaultGem, + b"totally different bytes\n", + QUALIFIED_PURL, + ); let (code, _, stderr) = run_apply(&fx, &["--json"]); assert_eq!(code, 0, "stderr:\n{stderr}"); @@ -210,18 +1017,23 @@ fn check_ignores_a_mismatched_fallback_home_copy_when_store_patched() { ); } -/// (b) Parity pin: with NO bundle-store copy, the fallback-home copy IS -/// the primary install — a mismatch there is a loud failure (exit 1), as -/// in plain apply. +/// Parity pin: with NO bundle-store copy (Bundler uses system gems), the +/// home copy IS the primary install — a mismatch there is a loud failure +/// (exit 1), as in plain apply. #[test] -fn fallback_only_mismatch_keeps_loud_failure_parity() { - let fx = build_fixture(false, b"totally different bytes\n", QUALIFIED_PURL); +fn home_only_mismatch_keeps_loud_failure_parity() { + let fx = build_fixture( + Store::SystemGems, + Home::Installed, + b"totally different bytes\n", + QUALIFIED_PURL, + ); let (code, stdout, _stderr) = run_apply(&fx, &["--json"]); let env = parse_env(&stdout); assert_ne!( code, 0, - "fallback-only mismatch must still fail the run (parity).\nenvelope: {env}" + "a home-only mismatch must still fail the run (parity).\nenvelope: {env}" ); assert!( find_skip_event(&env).is_none(), @@ -249,51 +1061,25 @@ fn fallback_only_mismatch_keeps_loud_failure_parity() { ); } -/// (c) Both copies healthy: both patched (the multi-copy guarantee is -/// unchanged by the class split), exit 0, applied counts both. -#[test] -fn writable_fallback_home_copy_still_patched() { - let fx = build_fixture(true, ORIGINAL, QUALIFIED_PURL); - - let (code, stdout, stderr) = run_apply(&fx, &["--json"]); - let env = parse_env(&stdout); - assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); - assert_eq!( - env["summary"]["applied"], 2, - "both copies count.\nenvelope: {env}" - ); - assert_eq!( - std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), - patched_bytes() - ); - assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched_bytes()); - assert!( - find_skip_event(&env).is_none(), - "healthy home copies are patched, never best-effort-skipped.\nenvelope: {env}" - ); -} - -/// An ATTEMPTED apply that FAILS on the fallback-home copy converts to +/// An ATTEMPTED apply that FAILS on a default gem's home copy converts to /// the same non-fatal per-copy skip when the store copy applied. The /// deterministic non-root failure: an UNQUALIFIED record's home copy with /// locally-diverged bytes under `--strict` — the singleton exemption /// drives it past the variant gate into `apply_package_patch`, whose -/// strict mismatch policy then refuses the write. (A root-owned rvm -/// `@global` EACCES is the production shape; owner-run tests can't +/// strict mismatch policy then refuses the write. (A root-owned system +/// gem dir's EACCES is the production shape; owner-run tests can't /// produce it — `DirWriteGuard` defeats read-only-dir setups by design.) -/// Before the fix: a `Failed` event + exit 1 even though the copy bundler -/// loads patched fine. #[test] -fn failing_fallback_home_copy_write_is_nonfatal_when_store_patched() { +fn failing_home_copy_write_is_nonfatal_when_store_patched() { let mut diverged = ORIGINAL.to_vec(); diverged.extend_from_slice(b"# local tweak\n"); - let fx = build_fixture(true, &diverged, BASE_PURL); + let fx = build_fixture(Store::Explicit, Home::DefaultGem, &diverged, BASE_PURL); let (code, stdout, stderr) = run_apply(&fx, &["--json", "--strict"]); let env = parse_env(&stdout); assert_eq!( code, 0, - "a failing fallback-home write must not fail the run once the store copy applied.\nenvelope: {env}\nstderr:\n{stderr}" + "a failing home copy write must not fail the run once the store copy applied.\nenvelope: {env}\nstderr:\n{stderr}" ); assert_eq!(env["status"], "success", "envelope: {env}"); assert_eq!( @@ -330,12 +1116,12 @@ fn failing_fallback_home_copy_write_is_nonfatal_when_store_patched() { ); } -/// The human render of (a): the per-copy warning names the skipped -/// copy's path and says why the skip is safe. +/// The human render of the mismatch skip: the per-copy warning names the +/// skipped copy's path and says why the skip is safe. #[test] -fn mismatched_fallback_home_copy_warns_on_human_stderr() { +fn mismatched_home_copy_warns_on_human_stderr() { let foreign = b"totally different bytes\n"; - let fx = build_fixture(true, foreign, QUALIFIED_PURL); + let fx = build_fixture(Store::Explicit, Home::DefaultGem, foreign, QUALIFIED_PURL); let (code, _stdout, stderr) = run_apply(&fx, &[]); assert_eq!(code, 0, "stderr={stderr}"); @@ -343,10 +1129,9 @@ fn mismatched_fallback_home_copy_warns_on_human_stderr() { stderr.contains("Warning: ") && stderr.contains("was not patched"), "the best-effort skip must print its human warning; stderr={stderr}" ); - let home = fx.project.path().join("gem-home"); assert!( - stderr.contains(&format!("gem-env home copy at {}", home.display())), - "the warning must name the fallback-home copy; stderr={stderr}" + stderr.contains(&format!("gem-env home copy at {}", home_dir(&fx).display())), + "the warning must name the home copy; stderr={stderr}" ); assert!( stderr.contains("bundle-path copy — the one bundler loads — is patched"), diff --git a/crates/socket-patch-cli/tests/common/gem_env_home.rs b/crates/socket-patch-cli/tests/common/gem_env_home.rs new file mode 100644 index 0000000000..76e4133322 --- /dev/null +++ b/crates/socket-patch-cli/tests/common/gem_env_home.rs @@ -0,0 +1,288 @@ +//! A Ruby project with an explicit Bundler `path`, beside a `gem env` home +//! that a fake `gem` binary reports, and a mock patch API for its gems. +//! For the suites of #2313: which gems agent mode selects and writes when +//! a gem sits in a gem home Bundler does not load the project's gems from. +//! +//! Pulled in per test binary with +//! `#[path = "../common/gem_env_home.rs"] mod gem_env_home;` beside +//! `mod common;`. Unix-only: the fake `gem` is a shell script. + +#![cfg(unix)] +#![allow(dead_code)] + +use std::path::{Path, PathBuf}; + +use base64::Engine; +use wiremock::matchers::{body_string_contains, method, path, path_regex}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +use crate::common::hermetic::{self, Extra}; +use crate::common::{binary, git_sha256, hermetic_command, jvm_env}; + +/// The org of the mock patch API. +pub const ORG: &str = "test-org"; + +/// Stage `/gems/-/lib/.rb` = `bytes` plus the +/// `specifications/` marker of a gem home; returns the staged file. +pub fn stage_gem(home: &Path, name: &str, version: &str, bytes: &[u8]) -> PathBuf { + let file = home + .join("gems") + .join(format!("{name}-{version}")) + .join("lib") + .join(format!("{name}.rb")); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, bytes).unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + file +} + +/// Make the staged `-` of `home` one of Ruby's default +/// gems: its spec under `specifications/default/`. +pub fn mark_default_gem(home: &Path, name: &str, version: &str) { + let specs = home.join("specifications").join("default"); + std::fs::create_dir_all(&specs).unwrap(); + std::fs::write(specs.join(format!("{name}-{version}.gemspec")), b"").unwrap(); +} + +/// The project: a `Gemfile`, a `Gemfile.lock`, the Bundler path +/// `bundle-store` (exported as `BUNDLE_PATH` by [`GemProject::run`]) and +/// the `gem env` home `gem-home`. +pub struct GemProject { + dir: tempfile::TempDir, +} + +impl GemProject { + /// `lock` is the `specs:` lines of the `Gemfile.lock` + /// (`"rack (3.1.0)"`). Neither the path nor the home holds a gem yet. + pub fn new(lock: &[&str]) -> Self { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::write(root.join("Gemfile"), "source \"https://rubygems.org\"\n").unwrap(); + let specs: String = lock.iter().map(|spec| format!(" {spec}\n")).collect(); + std::fs::write( + root.join("Gemfile.lock"), + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n{specs}\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n\nBUNDLED WITH\n 2.5.22\n" + ), + ) + .unwrap(); + let home = root.join("gem-home"); + std::fs::create_dir_all(home.join("gems")).unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + let bin_dir = root.join("fake-bin"); + std::fs::create_dir_all(&bin_dir).unwrap(); + let gem = bin_dir.join("gem"); + std::fs::write( + &gem, + format!( + "#!/bin/sh\nif [ \"$1\" = env ] && [ \"$2\" = gemdir ]; then\n printf '%s\\n' \"{}\"\n exit 0\nfi\nexit 1\n", + home.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&gem, std::fs::Permissions::from_mode(0o755)).unwrap(); + Self { dir } + } + + pub fn root(&self) -> &Path { + self.dir.path() + } + + /// The `gem env` home: another project's gems, Ruby's default gems, + /// and Bundler. + pub fn home(&self) -> PathBuf { + self.root().join("gem-home") + } + + /// The project's Bundler `path`. + pub fn store(&self) -> PathBuf { + self.root().join("bundle-store") + } + + /// Run `socket-patch --ecosystems gem --cwd ` + /// in the hermetic env with the ambient `BUNDLE_*` scrubbed, PATH = the + /// fake-gem bin dir only, and `BUNDLE_PATH` naming the store. + pub fn run(&self, command: &[&str], args: &[&str]) -> (i32, String, String) { + let mut cmd = hermetic_command(&binary()); + cmd.args(command) + .args(["--ecosystems", "gem", "--cwd"]) + .arg(self.root()) + .args(args); + jvm_env::isolate_cli(&mut cmd); + hermetic::scrub_extra(&mut cmd, &[Extra::Bundle]); + cmd.env("PATH", self.root().join("fake-bin")) + .env("BUNDLE_PATH", self.store()); + let out = cmd.output().expect("run socket-patch"); + ( + out.status.code().unwrap_or(-1), + String::from_utf8_lossy(&out.stdout).to_string(), + String::from_utf8_lossy(&out.stderr).to_string(), + ) + } + + /// The keys of `.socket/manifest.json`, sorted; empty with no manifest. + pub fn manifest_purls(&self) -> Vec { + let path = self.root().join(".socket").join("manifest.json"); + let Ok(raw) = std::fs::read(&path) else { + return Vec::new(); + }; + let manifest: serde_json::Value = serde_json::from_slice(&raw).unwrap(); + let mut purls: Vec = manifest["patches"] + .as_object() + .map(|patches| patches.keys().cloned().collect()) + .unwrap_or_default(); + purls.sort(); + purls + } +} + +/// The flags pointing a run at the mock API with a fake token and [`ORG`]. +pub fn api_args(api_url: &str) -> Vec<&str> { + vec![ + "--api-url", + api_url, + "--api-token", + "fake-token-for-test", + "--org", + ORG, + ] +} + +/// One free patch of `lib/.rb` in ` `. +pub struct GemPatch { + pub name: &'static str, + pub version: &'static str, + pub uuid: &'static str, + /// The advisory the patch fixes (`by-ghsa/` serves it). + pub ghsa: &'static str, +} + +impl GemPatch { + /// The file as published. + pub fn before(&self) -> Vec { + format!("module {}\n VERSION = 'VULNERABLE'\nend\n", self.name).into_bytes() + } + + /// The file as patched. + pub fn after(&self) -> Vec { + let mut bytes = self.before(); + bytes.extend_from_slice(b"# SOCKET-PATCHED\n"); + bytes + } + + /// `pkg:gem/@`. + pub fn purl(&self) -> String { + format!("pkg:gem/{}@{}", self.name, self.version) + } + + /// The record's key: [`Self::purl`] with `?platform=ruby`. + pub fn record(&self) -> String { + format!("{}?platform=ruby", self.purl()) + } + + fn search_result(&self) -> serde_json::Value { + serde_json::json!({ + "uuid": self.uuid, "purl": self.record(), "publishedAt": "2024-01-01T00:00:00Z", + "description": self.name, "license": "MIT", "tier": "free", "vulnerabilities": {}, + }) + } + + /// Mount the patch API for this patch: the batch lookup offers it only + /// to a query that names the gem (any other query finds nothing), and + /// the by-package search, the advisory search and the view serve it. + pub async fn mount(&self, mock: &MockServer) { + let found = |patches: serde_json::Value| { + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": patches, + "canAccessPaidPatches": false, + })) + }; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .and(body_string_contains(self.purl())) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [{ + "purl": self.purl(), + "patches": [{ + "uuid": self.uuid, "purl": self.record(), "tier": "free", + "cveIds": [], "ghsaIds": [self.ghsa], "severity": "high", + "title": self.name, + }], + }], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(mock) + .await; + 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, + }))) + .mount(mock) + .await; + Mock::given(method("GET")) + .and(path_regex(format!( + "^/v0/orgs/{ORG}/patches/by-package/.*{}.*$", + self.name + ))) + .respond_with(found(serde_json::json!([self.search_result()]))) + .mount(mock) + .await; + Mock::given(method("GET")) + .and(path(format!( + "/v0/orgs/{ORG}/patches/by-ghsa/{}", + self.ghsa + ))) + .respond_with(found(serde_json::json!([self.search_result()]))) + .mount(mock) + .await; + let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes); + let file = format!("lib/{}.rb", self.name); + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{}", self.uuid))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": self.uuid, + "purl": self.record(), + "publishedAt": "2024-01-01T00:00:00Z", + "files": { + file: { + "beforeHash": git_sha256(&self.before()), + "afterHash": git_sha256(&self.after()), + "blobContent": b64(&self.after()), + "beforeBlobContent": b64(&self.before()), + } + }, + "vulnerabilities": {}, + "description": self.name, + "license": "MIT", + "tier": "free", + }))) + .mount(mock) + .await; + } +} + +/// Every request the mock received. +pub async fn requests(mock: &MockServer) -> Vec { + mock.received_requests().await.unwrap_or_default() +} + +/// Whether some batch lookup named `purl`. +pub async fn batch_queried(mock: &MockServer, purl: &str) -> bool { + requests(mock).await.iter().any(|r| { + r.url.path().ends_with("/patches/batch") && String::from_utf8_lossy(&r.body).contains(purl) + }) +} + +/// How many times the view of the patch `uuid` was fetched: the download. +pub async fn view_gets(mock: &MockServer, uuid: &str) -> usize { + requests(mock) + .await + .iter() + .filter(|r| r.url.path().ends_with(&format!("/patches/view/{uuid}"))) + .count() +} diff --git a/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs b/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs new file mode 100644 index 0000000000..cc65b57fbc --- /dev/null +++ b/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs @@ -0,0 +1,178 @@ +//! `get` in agent mode and a gem that only a `gem env` home holds (#2313). +//! +//! Under an explicit Bundler `path` a gem in the system gems is another +//! project's: Bundler never loads it for this one, and the apply step +//! leaves it alone. So `get` must not take it for an installed package: +//! +//! * a package NAME resolves among the installed packages, and such a +//! gem is not one of them; +//! * an ADVISORY is narrowed to the versions installed here, and such a +//! gem's version is not one of them: a calm `package_not_installed` +//! skip, as for a version that is installed nowhere; +//! * an exact PURL is never narrowed, for any package: its patch is +//! recorded, and the apply step says where the gem is and why it was +//! left alone; +//! * Bundler itself is loaded from the gem home it is installed in under +//! any path, so its name still resolves and it is patched there. +//! +//! Unix-only: the `gem env` home comes from a fake `gem` binary on PATH. + +#![cfg(unix)] + +use std::path::PathBuf; + +use wiremock::MockServer; + +use crate::common::envelope::{event_purls, has_event, parse_json_envelope}; +use crate::gem_env_home::{api_args, stage_gem, view_gets, GemPatch, GemProject}; + +const RACK: GemPatch = GemPatch { + name: "rack", + version: "3.1.0", + uuid: "11111111-1111-4111-8111-111111111111", + ghsa: "GHSA-aaaa-bbbb-cccc", +}; + +const BUNDLER: GemPatch = GemPatch { + name: "bundler", + version: "2.6.9", + uuid: "22222222-2222-4222-8222-222222222222", + ghsa: "GHSA-dddd-eeee-ffff", +}; + +/// `get --mode agent ` against the mock API. +fn get( + project: &GemProject, + api_url: &str, + identifier: &str, + extra: &[&str], +) -> (i32, String, String) { + let mut args = vec!["--mode", "agent", "--yes"]; + args.extend(api_args(api_url)); + args.extend_from_slice(extra); + project.run(&["get", identifier], &args) +} + +/// A project whose own gem is installed in its path and whose lock lists +/// nothing else, with `patch`'s gem, as published, only in the `gem env` +/// home. Returns the home copy's file. +fn project_beside(patch: &GemPatch) -> (GemProject, PathBuf) { + let project = GemProject::new(&["colorize (1.1.0)"]); + stage_gem( + &project.store(), + "colorize", + "1.1.0", + b"module Colorize\nend\n", + ); + let file = stage_gem(&project.home(), patch.name, patch.version, &patch.before()); + (project, file) +} + +/// `get rack`, with `rack` only in the gem home: the name matches no +/// package of this project. Nothing is downloaded or recorded, exit 0. +#[tokio::test] +async fn name_of_a_foreign_gem_matches_no_installed_package() { + let (project, home_file) = project_beside(&RACK); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = get(&project, &mock.uri(), "rack", &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stdout.contains("No packages matching \"rack\" found."), + "stdout={stdout}" + ); + assert_eq!(view_gets(&mock, RACK.uuid).await, 0); + assert_eq!(project.manifest_purls(), Vec::::new()); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); +} + +/// `get rack --save-only` records a patch and applies nothing, so it has +/// no installed copy to ask for: the name resolves from the crawl as it +/// always did, and the patch is recorded, as by advisory or by purl. +#[tokio::test] +async fn save_only_records_a_foreign_gem_by_name() { + let (project, home_file) = project_beside(&RACK); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = get(&project, &mock.uri(), "rack", &["--save-only"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(project.manifest_purls(), vec![RACK.record()]); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); +} + +/// `get ` for an advisory patched in `rack 3.1.0`, with that version +/// only in the gem home: narrowed away as not installed here, the calm +/// skip a version installed nowhere gets. No download, no record, exit 0. +#[tokio::test] +async fn advisory_for_a_foreign_gem_is_narrowed_as_not_installed() { + let (project, home_file) = project_beside(&RACK); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = get(&project, &mock.uri(), RACK.ghsa, &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert!( + has_event(&env, "skipped", "package_not_installed", &RACK.record()), + "envelope: {env}" + ); + assert_eq!(view_gets(&mock, RACK.uuid).await, 0); + assert_eq!(project.manifest_purls(), Vec::::new()); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); + + // The version installed in no gem home at all reads the same. + std::fs::remove_dir_all(project.home().join("gems").join("rack-3.1.0")).unwrap(); + let (again, stdout, stderr) = get(&project, &mock.uri(), RACK.ghsa, &["--json"]); + let absent = parse_json_envelope(&stdout); + assert_eq!(again, 0, "envelope: {absent}\nstderr:\n{stderr}"); + assert_eq!(absent["events"], env["events"]); +} + +/// `get pkg:gem/rack@3.1.0`: an exact purl is not narrowed to what is +/// installed. The patch is recorded, and the apply step leaves the other +/// project's copy alone with the skip that names it, exit 0. +#[tokio::test] +async fn exact_purl_of_a_foreign_gem_is_recorded_and_its_copy_left_alone() { + let (project, home_file) = project_beside(&RACK); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = get(&project, &mock.uri(), &RACK.purl(), &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert!( + has_event( + &env, + "skipped", + "gem_other_project_copy_skipped", + &RACK.record() + ), + "envelope: {env}" + ); + assert!(event_purls(&env, "applied").is_empty(), "envelope: {env}"); + assert_eq!(project.manifest_purls(), vec![RACK.record()]); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); +} + +/// `get bundler`: Bundler is never installed into the project's path. The +/// copy in the gem home is the one the project runs, so the name resolves +/// to it and it is patched. +#[tokio::test] +async fn name_of_bundler_resolves_to_the_gem_home_copy() { + let (project, home_file) = project_beside(&BUNDLER); + let mock = MockServer::start().await; + BUNDLER.mount(&mock).await; + + let (code, stdout, stderr) = get(&project, &mock.uri(), "bundler", &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + event_purls(&env, "applied"), + vec![BUNDLER.record()], + "envelope: {env}" + ); + assert_eq!(project.manifest_purls(), vec![BUNDLER.record()]); + assert_eq!(std::fs::read(&home_file).unwrap(), BUNDLER.after()); +} diff --git a/crates/socket-patch-cli/tests/get/main.rs b/crates/socket-patch-cli/tests/get/main.rs index e5da1bf593..10f4b923f2 100644 --- a/crates/socket-patch-cli/tests/get/main.rs +++ b/crates/socket-patch-cli/tests/get/main.rs @@ -6,6 +6,8 @@ #[path = "../common/mod.rs"] mod common; +#[path = "../common/gem_env_home.rs"] +mod gem_env_home; #[path = "../npm_e2e_common/manifestless.rs"] mod npm_e2e_common; #[path = "../prebuilt_common/mod.rs"] @@ -24,6 +26,7 @@ mod get_edge_cases_e2e; mod get_envelope_shape; mod get_failure_paths; mod get_fixture; +mod get_gem_unloaded_homes; mod get_invariants; mod get_modes_e2e; mod get_nested_apply_api_flags_e2e; diff --git a/crates/socket-patch-cli/tests/scan/main.rs b/crates/socket-patch-cli/tests/scan/main.rs index 4233b89fce..00a6db5cf4 100644 --- a/crates/socket-patch-cli/tests/scan/main.rs +++ b/crates/socket-patch-cli/tests/scan/main.rs @@ -8,6 +8,8 @@ #[path = "../common/mod.rs"] mod common; +#[path = "../common/gem_env_home.rs"] +mod gem_env_home; #[path = "../prebuilt_common/mod.rs"] mod prebuilt_common; #[path = "../common/pty_io.rs"] @@ -33,6 +35,7 @@ mod scan_batch_sizing_e2e; mod scan_ecosystems_scope_e2e; mod scan_failure_paths; mod scan_fixture; +mod scan_gem_unloaded_homes; mod scan_invariants; mod scan_nested_project_e2e; mod scan_ordered_concurrency_e2e; diff --git a/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs b/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs new file mode 100644 index 0000000000..16c5c7258d --- /dev/null +++ b/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs @@ -0,0 +1,240 @@ +//! `scan --mode agent` and a gem that only a `gem env` home holds (#2313). +//! +//! Under an explicit Bundler `path` the project's gems are installed into +//! that path, and a gem in the system gems (an rbenv or asdf home, +//! `~/.gem`) is another project's: Bundler never loads it for this one, +//! and the apply step leaves it alone. The scan's crawl still finds it, so +//! the scan must treat it as not installed for this project. Selecting it +//! would download and record a patch the apply step then writes nowhere. +//! +//! * a gem the project's lock does not list is no candidate: it is not +//! queried, nothing is downloaded or recorded, and the run exits 0; +//! * a gem the lock lists is lockfile-only (a fresh clone before +//! `bundle install`), exactly as when no gem home holds it: reported +//! as not installed, and skipped before any download; +//! * a default gem (its spec under `specifications/default/`) and +//! Bundler itself are loaded from the gem home they are installed in +//! under any path, so they are still selected and patched there. +//! +//! Unix-only: the `gem env` home comes from a fake `gem` binary on PATH. + +#![cfg(unix)] + +use wiremock::MockServer; + +use crate::common::envelope::{event_purls, has_event, parse_json_envelope}; +use crate::gem_env_home::{ + api_args, batch_queried, mark_default_gem, stage_gem, view_gets, GemPatch, GemProject, +}; + +const RACK: GemPatch = GemPatch { + name: "rack", + version: "3.1.0", + uuid: "11111111-1111-4111-8111-111111111111", + ghsa: "GHSA-aaaa-bbbb-cccc", +}; + +const BUNDLER: GemPatch = GemPatch { + name: "bundler", + version: "2.6.9", + uuid: "22222222-2222-4222-8222-222222222222", + ghsa: "GHSA-dddd-eeee-ffff", +}; + +/// `scan --mode agent ` against the mock API. +fn scan(project: &GemProject, api_url: &str, extra: &[&str]) -> (i32, String, String) { + let mut args = vec!["--mode", "agent"]; + args.extend(api_args(api_url)); + args.extend_from_slice(extra); + project.run(&["scan"], &args) +} + +/// A project whose own gem is installed in its path, with `patch`'s gem, +/// as published, only in the `gem env` home. Returns the home copy's file. +fn project_beside(patch: &GemPatch, lock: &[&str]) -> (GemProject, std::path::PathBuf) { + let project = GemProject::new(lock); + stage_gem( + &project.store(), + "colorize", + "1.1.0", + b"module Colorize\nend\n", + ); + let file = stage_gem(&project.home(), patch.name, patch.version, &patch.before()); + (project, file) +} + +/// `rack` is only in the `gem env` home and not in the lock: another +/// project's copy. The scan does not ask about it, downloads and records +/// nothing, and exits 0; so does the `apply` after it. +#[tokio::test] +async fn foreign_gem_in_a_gem_env_home_is_not_selected() { + let (project, home_file) = project_beside(&RACK, &["colorize (1.1.0)"]); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = scan(&project, &mock.uri(), &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!( + env["scannedPackages"], 1, + "only the project's own gem counts.\nenvelope: {env}" + ); + assert!( + !stdout.contains(&RACK.purl()), + "the envelope must not name the foreign gem.\nenvelope: {env}" + ); + assert!( + batch_queried(&mock, "colorize").await, + "the project's own gem is still scanned" + ); + assert!( + !batch_queried(&mock, &RACK.purl()).await, + "the foreign gem must not be queried" + ); + assert_eq!(view_gets(&mock, RACK.uuid).await, 0); + assert_eq!(project.manifest_purls(), Vec::::new()); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); + + let (code, stdout, stderr) = project.run(&["apply"], &["--offline"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); +} + +/// The human run of the same project: no error, no failed apply, and +/// nothing about the foreign gem. +#[tokio::test] +async fn foreign_gem_in_a_gem_env_home_leaves_the_human_run_clean() { + let (project, home_file) = project_beside(&RACK, &["colorize (1.1.0)"]); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = scan(&project, &mock.uri(), &[]); + let out = format!("{stdout}{stderr}"); + assert_eq!(code, 0, "output={out}"); + assert!( + out.contains("No patches available for installed packages."), + "output={out}" + ); + assert!( + !out.contains("rack") && !out.contains("Error:"), + "output={out}" + ); + assert!(!batch_queried(&mock, &RACK.purl()).await); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); +} + +/// A record an earlier release wrote for another project's gem survives +/// `scan --sync`: the copy is on disk and may hold the patch, so the prune +/// counts the gem as installed and `rollback` can still restore it. +#[tokio::test] +async fn sync_keeps_a_record_for_a_foreign_gem() { + let (project, home_file) = project_beside(&RACK, &["colorize (1.1.0)"]); + super::scan_fixture::seed_manifest(project.root(), &[(&RACK.record(), RACK.uuid)]); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let api_url = mock.uri(); + let mut args = vec!["--sync", "--json"]; + args.extend(api_args(&api_url)); + let (code, stdout, stderr) = project.run(&["scan"], &args); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + project.manifest_purls(), + vec![RACK.record()], + "the record must not be pruned.\nenvelope: {env}" + ); + assert!( + !batch_queried(&mock, &RACK.purl()).await, + "the foreign gem is still no candidate" + ); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); +} + +/// A fresh clone before `bundle install`: the lock lists `rack`, the path +/// holds nothing yet, and the `gem env` home has the same version. The +/// home copy is not the project's, so the gem is lockfile-only, as when no +/// gem home holds it: reported as not installed, with no download and no +/// record, exit 0. +#[tokio::test] +async fn locked_gem_with_only_a_foreign_copy_is_lockfile_only() { + let project = GemProject::new(&["rack (3.1.0)"]); + let home_file = stage_gem(&project.home(), RACK.name, RACK.version, &RACK.before()); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = scan(&project, &mock.uri(), &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert!( + batch_queried(&mock, &RACK.purl()).await, + "the locked gem is still looked up" + ); + assert!( + has_event(&env, "skipped", "package_not_installed", &RACK.record()), + "envelope: {env}" + ); + assert_eq!( + view_gets(&mock, RACK.uuid).await, + 0, + "nothing is downloaded for a gem that is not installed.\nenvelope: {env}" + ); + assert_eq!(project.manifest_purls(), Vec::::new()); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); + + // The same project with no copy in any gem home reports the same. + std::fs::remove_dir_all(project.home().join("gems").join("rack-3.1.0")).unwrap(); + let (again, stdout, stderr) = scan(&project, &mock.uri(), &["--json"]); + let without = parse_json_envelope(&stdout); + assert_eq!(again, 0, "envelope: {without}\nstderr:\n{stderr}"); + assert_eq!( + without["events"], env["events"], + "both fresh-clone states report the same events" + ); + assert_eq!(without["scannedPackages"], env["scannedPackages"]); +} + +/// A default gem the lock does not list is still a candidate: Bundler +/// loads it from the system home under any path, and the apply step +/// patches it there. +#[tokio::test] +async fn default_gem_in_a_gem_env_home_is_still_patched() { + let (project, home_file) = project_beside(&RACK, &["colorize (1.1.0)"]); + mark_default_gem(&project.home(), RACK.name, RACK.version); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = scan(&project, &mock.uri(), &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + event_purls(&env, "applied"), + vec![RACK.record()], + "envelope: {env}" + ); + assert_eq!(project.manifest_purls(), vec![RACK.record()]); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.after()); +} + +/// Bundler is never installed into the project's path, and the lock names +/// it only under `BUNDLED WITH`: the copy `gem install bundler` put in the +/// gem home is the one the project runs, so it is selected and patched. +#[tokio::test] +async fn bundler_in_a_gem_env_home_is_still_patched() { + let (project, home_file) = project_beside(&BUNDLER, &["colorize (1.1.0)"]); + let mock = MockServer::start().await; + BUNDLER.mount(&mock).await; + + let (code, stdout, stderr) = scan(&project, &mock.uri(), &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + event_purls(&env, "applied"), + vec![BUNDLER.record()], + "envelope: {env}" + ); + assert_eq!(project.manifest_purls(), vec![BUNDLER.record()]); + assert_eq!(std::fs::read(&home_file).unwrap(), BUNDLER.after()); +} diff --git a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs index c829bc7fd2..288418faa9 100644 --- a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs @@ -34,7 +34,7 @@ impl RubyCrawler { /// a store (a deployment-style install), those stores are the whole /// answer; otherwise, if the cwd holds a Bundler manifest or lockfile, /// the gem homes `gem env` reports are appended (deduped) — default - /// gems (rexml, json, …) never live in a bundle path, so an + /// gems (json, uri, …) never live in a bundle path, so an /// env/config-rooted project still needs them. /// /// In global mode, queries `gem env gemdir` and `gem env gempath`, plus @@ -124,7 +124,7 @@ impl RubyCrawler { // `vendor/bundle` probe: a deployment-style install is the // project's one gem source, so the ambient gem homes don't apply. // Stores found via an env/config root do NOT suppress the fallback - // below: default gems (rexml, json, …) never live in a bundle path + // below: default gems (json, uri, …) never live in a bundle path // — they ship with ruby in the DEFAULT/system gem homes — so an // env-`BUNDLE_PATH` project still needs the `gem env` homes to see // them (the explicit-roots feature briefly suppressed that @@ -832,14 +832,17 @@ impl RubyCrawler { ) } - /// The `gem env` homes Bundler never loads this project's gems from, - /// for read-only verifiers (`vex`): [`Self::get_gem_paths`] keeps them - /// as apply write targets for default gems, but under an explicit or - /// deployment `path` Bundler fetches every other gem into that path, so - /// an unpatched copy there is not one the project runs (#1098). Empty - /// in global / `--global-prefix` mode and whenever Bundler uses system - /// gems. A home that is also one of the project's Bundler stores is - /// never listed. + /// The `gem env` homes Bundler never loads this project's gems from. + /// [`Self::get_gem_paths`] keeps them for default gems, but under an + /// explicit or deployment `path` Bundler fetches every other gem into + /// that path, so a copy there that is neither a default gem + /// ([`is_default_gem_copy`]) nor Bundler itself is not one the + /// project runs: `apply` does not write it (#2313), and the + /// read-only verifiers (`vex`, `apply --check`) do not judge it + /// (#1098). Empty in global / + /// `--global-prefix` mode and whenever Bundler uses system gems. A + /// home that is also one of the project's Bundler stores is never + /// listed. pub async fn bundler_unused_system_gem_homes(&self, options: &CrawlerOptions) -> Vec { if options.global || options.global_prefix.is_some() { return Vec::new(); @@ -859,8 +862,8 @@ impl RubyCrawler { /// gem homes for the project at `cwd`: a Ruby project with no /// deployment store under the default `vendor/bundle` and no explicit /// install `path` ([`bundler_sets_explicit_path`], which also counts - /// `deployment`). The one answer both the stale-install guard - /// ([`Self::bundler_install_homes`]) and `vex` + /// `deployment`). The one answer the stale-install guard + /// ([`Self::bundler_install_homes`]), `apply` and `vex` /// ([`Self::bundler_unused_system_gem_homes`]) use. async fn bundler_uses_system_gems(cwd: &Path, discovery: &BundleStoreDiscovery) -> bool { if discovery.default_root_has_stores || !Self::has_bundler_manifest(cwd).await { @@ -1506,8 +1509,9 @@ pub(crate) fn bundler_sets_explicit_path(tiers: BundlerPathTiers) -> bool { /// Whether the installed gem dir `copy` (`/gems/-`) /// is a default gem: its spec sits in `/specifications/default/`. /// Bundler loads a default gem from the system home even under an explicit -/// `path`, so a verifier that drops the unused `gem env` homes -/// ([`RubyCrawler::bundler_unused_system_gem_homes`]) still judges it. +/// `path`, so `apply` still patches it and a verifier still judges it +/// where they drop every other copy in the unused `gem env` homes +/// ([`RubyCrawler::bundler_unused_system_gem_homes`]). pub fn is_default_gem_copy(copy: &Path) -> bool { let (Some(dir_name), Some(home)) = (copy.file_name(), copy.parent().and_then(Path::parent)) else { 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 b187f38547..ac0af32038 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs @@ -74,6 +74,17 @@ pub async fn gem_platform_only_purls_in(view: &ProjectView<'_>) -> Vec { } } +/// Whether bundler loads a lock here and socket-patch read it. `false` for +/// a project with no lock yet (a gem library that commits none) and for the +/// layouts [`unsupported_gem_layout_in`] reports. Only a lock that was read +/// can say that the project does not use a gem. +pub async fn gem_lock_read_in(view: &ProjectView<'_>) -> bool { + match bundler_loaded_lock_in(view).await { + Some(lock) => view.read_text(lock).await.is_ok(), + None => false, + } +} + /// The builds the Bundler lock bundler loads names for each gem of `purls` /// ([`locked_gem_builds`](crate::formats::gem::locked_gem_builds)): element /// `i` answers `purls[i]`. Empty for every gem when bundler loads no lock diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs b/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs index 759937ece2..afeba42ac5 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs @@ -76,7 +76,9 @@ pub(crate) mod vlt; pub(crate) mod yarn; pub use self::bun::{bun_binary_lock_drives, bun_text_lock_drives}; -pub use self::gem::{gem_locked_builds_in, gem_platform_only_purls_in, gem_resolved_builds_in}; +pub use self::gem::{ + gem_lock_read_in, gem_locked_builds_in, gem_platform_only_purls_in, gem_resolved_builds_in, +}; pub(crate) use self::npm::{ npm_lock_bundled_nodes, npm_lock_entries, npm_lock_legacy_mirror_nodes, npm_lock_located_nodes, NpmLockEntry, NpmLockNode, NpmLockSection, diff --git a/docs/ecosystems.md b/docs/ecosystems.md index cd0c19270f..7511b68ec4 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5326,6 +5326,64 @@ A shared gem home also holds gem versions this project doesn't use: the gems Rub mode warns `redirect_gem_version_not_locked`, vendored mode reports a `skipped` event with `vendor_gem_version_not_locked` and doesn't download its patch. The run exits 0. +Agent mode (`apply`, and the apply step of `scan --mode agent` and `get`) patches installed gems +in place, and follows the same principle. It writes the copies Bundler loads for the project and +no other: + +- With a Bundler `path` (`bundle config set --local path vendor/gems`, `BUNDLE_PATH`) or + deployment mode, Bundler installs the project's gems into that path, and `apply` patches them + there. A copy of the same gem version in a shared gem home is left alone: Bundler never loads it + for this project, and another project may. Two kinds of gem are the exception, because Bundler + loads them from the gem home they are installed in under any path, so `apply` patches them + there: a default gem, one Ruby ships as part of itself (`json`, `uri`, `set`), and Bundler + (every installed version of it). A bundled gem (`rexml`, `rake`) is an ordinary gem that Ruby + merely ships along, and follows the ordinary rule. The exception stops once `vendor/bundle`, + the default path, holds the project's gems: `apply` then looks only there, and neither a + default gem nor Bundler is patched. +- With no `path`, Bundler installs into the shared gem homes and loads the project's gems from + them, so `apply` patches them there. Another project that uses the same gem version then runs + the patched code too. Set a `path` (the `bundle config` line above) to keep the patch inside the + project. + +An agent-mode scan, and `get` by package name or by advisory, select patches by the same rule. A +gem that is only in a shared gem home is not installed for this project. If `Gemfile.lock` lists +it, the scan reports it as not installed yet and records nothing, as it does when no gem home +holds it. Otherwise the scan doesn't report it, a name finds no package, and an advisory skips +that version as not installed. (`get --save-only` only records a patch, so it still finds the gem +by name.) + +On a fresh clone with a `path`, run `bundle install` before `apply`. Before it the path holds no +gem, so `apply` patches nothing and reports the gems `Gemfile.lock` lists as not installed (`0 of +1 targeted patch applied, 0 already patched, 1 not found on disk`), with exit 0. A recorded patch +for a gem that no lock lists and no gem home holds makes a run that matched nothing exit 1, as +for any package that is not installed. + +Releases up to 5.1.0 patched a copy in a shared gem home under a `path` as well, and their scans +recorded patches for other projects' gems. When `Gemfile.lock` doesn't list the gem, `apply` +skips such a record with a warning that names the copy and the command to run (`1 not applicable` +in the summary, exit 0): + +``` +socket-patch rollback pkg:gem/rack@2.2.8 +``` + +It removes the patch from the manifest and restores the copy if it still holds the patch. A copy +that doesn't hold it is left as it is, whatever it holds, since it is another project's. Another +project that patched the same copy with the same patch, with no `path` of its own, can't be told +apart: its copy is restored too, and its own `apply` patches it again. A project with no +`Gemfile.lock` can't tell `apply` that the gem is not its own, so there the record is reported +as not installed, like any other, and the same command removes it. + +A shared copy that such a release patched beside the project's own copy of the same gem stays +patched after the upgrade, and `apply` doesn't mention it. To restore it, run +`socket-patch rollback --preserve-state`, which restores both copies and keeps the patch +recorded, and then `socket-patch apply`, which patches the project's copy alone. + +Once `vendor/bundle` holds the project's gems, `rollback` and `remove` look only there: +`rollback` then keeps the patch recorded and warns that the shared copy is still patched, naming +the command that restores it (`socket-patch rollback -g`). `apply --global` patches the +gems in the shared gem homes whatever the project's Bundler settings are. + ## Ruby gems: gems vendored mode refuses Vendored mode rewrites one top-level `gem` line to a `path:` source, and Bundler builds nothing