Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/socket-patch-cli/CLI_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -2934,7 +2934,7 @@ command's integration tests check its output.
| `vendor_uuid_mismatch` | `skipped` | repair: the manifest's patch uuid moved past the vendored artifact — a re-vendor (`vendor` / `scan --mode vendored`) is pending; repair does not cross patch generations. |
| `content_mismatch_overwritten` | `skipped` (warning) | apply (explicit `--allow-patch-conflicts` / `--force`): a file matched NEITHER beforeHash nor afterHash and was overwritten with the full verified patched content. This includes a file the patch adds (empty beforeHash) that already exists with other content. `--strict` turns this case into a `failed` event instead. Agent-mode `get` / `scan --json` carry it as a `(content_mismatch_overwritten) …` `warnings[]` entry (#1004). |
| `vendor_lock_checksums_unsupported` / `vendor_stale_lock_checksum` | `failed` | vendor (gem): an ambiguous/platform CHECKSUMS entry, or a v1-wired lock whose stale token blocks the hot path (run `vendor --revert` + re-vendor). |
| `platform_gem_unsupported` | `failed` | vendor / scan / get `--mode vendored` (gem): a precompiled platform gem that cannot be vendored. `Gemfile.lock` pins the gem as platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and also holds the plain `<name> (<ver>)` entry of the `ruby` platform, which no platform tree serves (the detail names it and each locked platform that keeps it, `ruby` or one that none of the gem's platform gems serves, with the `bundle lock --remove-platform <platforms>` command that drops them); or it pins the gem as platform gems and its `BUNDLED WITH` is absent or names a Bundler older than 2.3, the oldest the vendored layout is verified on (the detail names the version needed; `bundle update --bundler` re-locks); or the installed copy is a platform gem and the lock names no platform for the gem; or the patch record is for one platform's gem (`?platform=<native>`) and is not vendored as part of its fix: the lock does not pin the gem as platform gems. Nothing is written. A locked platform with no patch of the fix is not this failure: see `vendor_prebuilt_platform_pending`. |
| `platform_gem_unsupported` | `failed` | vendor / scan / get `--mode vendored` (gem): a precompiled platform gem that cannot be vendored. `Gemfile.lock` pins the gem as platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and also holds the plain `<name> (<ver>)` entry of the `ruby` platform, which no platform tree serves (the detail names it and each locked platform that keeps it, `ruby` or one that none of the gem's platform gems serves, with the `bundle lock --remove-platform <platforms>` command that drops them); or it pins the gem as platform gems and its `BUNDLED WITH` is absent or names a Bundler older than 2.3, the oldest the vendored layout is verified on (the detail names the version needed; `bundle update --bundler` re-locks); or the installed copy is a platform gem and the lock names no platform for the gem; or the patch record is for one platform's gem (`?platform=<native>`) and is not vendored as part of its fix: the lock does not pin the gem as platform gems. Nothing is written. In `scan` / `get --mode vendored`, this refusal, like any other pre-download refusal that fails a gem with the same code and detail for several of its selected patches (an expected skip such as `vendor_gem_version_not_locked` stays per patch), is reported once however many of the gem's platform gems have a selected patch: one `failed` event and one `[error]` line (one `skipped` event and one `[would-refuse]` line under `--dry-run`), under the patch of the ruby gem, or under the first of the gem's refused patches in purl order where the ruby gem's is not one of them; the gem's other patches are refused with it and have no event, line or count of their own (#2436). A locked platform with no patch of the fix is not this failure: see `vendor_prebuilt_platform_pending`. |
| `redirect_unattributable` | `skipped` (hosted event) | scan/get `--mode hosted`: the rewriters would pin the patch, but lockfile discovery over the result reads that pin as contested (another lock or requirements file resolves the same version elsewhere, or the pin is not one the package manager consumes), so `vex`, `rollback`, `remove` and `vendor` would refuse it. The candidate is left out of the rewrite, so nothing is written for it; the detail carries discovery's findings. Exit code unchanged. |
| `redirect_mirror_unsupported` / `redirect_mirror_url_refused` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the patch's ecosystem cannot be served through a mirror (`redirect_mirror_unsupported`: Cargo, NuGet; use `--mode vendored`), or its reference could not be moved onto the mirror (`redirect_mirror_url_refused`). Nothing is written for it. See "Patch mirror (experimental)". |
| `redirect_mirror_unavailable` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the mirror did not serve the reference the run asked it for, or could not be reached. That reference is skipped and nothing is written for it. One warning per package, or a single warning about the mirror when it served none of the references it was asked about. |
Expand Down
14 changes: 14 additions & 0 deletions crates/socket-patch-cli/src/commands/agent_download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1408,6 +1408,20 @@ pub(crate) async fn fetch_selected_patches(
} else {
(selected, Vec::new())
};
// A refusal that is the gem's (what its lock says) is reported under
// one patch of the gem, not once for each of its builds' patches: the
// others are refused with it and have no line, event or count of
// their own.
let repeats = socket_patch_core::vendor::refusals::repeated_gem_refusals(
selected.iter().filter_map(|sr| {
let refusal = refusals.get(&sr.purl)?;
Some((sr.purl.as_str(), refusal.code, refusal.detail.as_str()))
}),
);
let selected: Vec<PatchSearchResult> = selected
.into_iter()
.filter(|sr| !repeats.contains(&sr.purl))
.collect();
status.finish();
prefetched.extend(views);
// The callers have already listed the patches (`scan`'s rows, `get`'s
Expand Down
58 changes: 56 additions & 2 deletions crates/socket-patch-cli/src/commands/scan/vendor_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ pub(crate) struct PreviewRow {
#[derive(Debug, Clone, Default)]
pub(crate) struct VendorPreview {
pub(crate) rows: Vec<PreviewRow>,
/// The patches refused with another patch of their gem, whose row
/// reports the refusal for the gem
/// ([`socket_patch_core::vendor::refusals::repeated_gem_refusals`]):
/// refused, with no row of their own.
refused_with_their_gem: HashSet<String>,
}

impl VendorPreview {
Expand Down Expand Up @@ -141,13 +146,16 @@ impl VendorPreview {
.iter()
.filter(|r| matches!(r.verdict, PreviewVerdict::WouldRefuse { .. }))
.map(|r| r.purl.clone())
.chain(self.refused_with_their_gem.iter().cloned())
.collect()
}

/// Keep only the rows of `selected` (the patches the rollout plan left
/// in the run), so a preview computed before planning renders exactly
/// what this run would vendor. Every verdict is per patch, so a row
/// does not depend on which other patches were previewed with it.
/// does not depend on which other patches were previewed with it (but
/// for a gem's refusal, which has one row for the patches refused
/// alike; the plan never takes a refused patch out of the run).
pub(crate) fn retain_selected(&mut self, selected: &[PatchSearchResult]) {
let keep: HashSet<(&str, &str)> = selected
.iter()
Expand Down Expand Up @@ -399,7 +407,21 @@ async fn preview_vendor_with(
})
.collect();
rows.sort_by(|a, b| a.purl.cmp(&b.purl));
VendorPreview { rows }
// As the wet run reports it: a gem's refusal has one row.
let refused_with_their_gem =
socket_patch_core::vendor::refusals::repeated_gem_refusals(rows.iter().filter_map(|row| {
match &row.verdict {
PreviewVerdict::WouldRefuse { code, detail } => {
Some((row.purl.as_str(), code.as_str(), detail.as_str()))
}
_ => None,
}
}));
rows.retain(|row| !refused_with_their_gem.contains(&row.purl));
VendorPreview {
rows,
refused_with_their_gem,
}
}

/// The PyPI purls of `selected` the vendor backend's prelude refuses
Expand Down Expand Up @@ -1646,6 +1668,38 @@ mod preview_tests {
);
}

/// #2436: a gem refused alike under each of its builds' patches has
/// one would-refuse row, under the ruby gem's patch. The others stay
/// refused for the rollout plan, so none of them takes a slot.
#[tokio::test]
async fn preview_reports_a_gems_refusal_once() {
let tmp = tempfile::tempdir().unwrap();
let purls = [
"pkg:gem/preview-gem@1.0.0?platform=arm64-darwin",
"pkg:gem/preview-gem@1.0.0?platform=ruby",
"pkg:gem/preview-gem@1.0.0?platform=x86_64-linux",
];
let selected: Vec<PatchSearchResult> = purls.iter().map(|purl| sel(UUID, purl)).collect();
let refusals: HashMap<String, (&'static str, String)> = purls
.iter()
.map(|purl| (purl.to_string(), ("vendor_test_refusal", "why".to_string())))
.collect();
let preview = preview_vendor_with(tmp.path(), &selected, &[], &refusals).await;
let rows: Vec<&str> = preview.rows.iter().map(|r| r.purl.as_str()).collect();
assert_eq!(rows, [purls[1]]);
assert_eq!(preview.refused_count(), 1);
assert_eq!(
preview.dry_run_line(),
"[dry-run] Would download and vendor 0 of 1 patch (1 would be refused). \
No changes made."
);
let refused = preview.refused_purls();
assert!(
purls.iter().all(|purl| refused.contains(*purl)),
"{refused:?}"
);
}

const UUID: &str = "11111111-1111-4111-8111-111111111111";
const OLD_UUID: &str = "00000000-0000-4000-8000-000000000000";
const NPM: &str = "pkg:npm/preview-bun@1.0.0";
Expand Down
169 changes: 169 additions & 0 deletions crates/socket-patch-cli/tests/in_process_vendor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3717,6 +3717,175 @@ async fn scan_vendor_gem_refuses_a_gitignored_ledger() {
}
}

/// The demo gem locked for the ruby platform beside two platform gems,
/// which vendored mode refuses (`platform_gem_unsupported`).
const GEM_LOCK_RUBY_BESIDE_PLATFORMS: &str = "GEM\n remote: https://rubygems.org/\n specs:\n demo-gem (1.0.0)\n demo-gem (1.0.0-arm64-darwin)\n demo-gem (1.0.0-x86_64-linux)\n\nPLATFORMS\n arm64-darwin\n ruby\n x86_64-linux\n\nDEPENDENCIES\n demo-gem (~> 1.0)\n\nBUNDLED WITH\n 4.1.1\n";

/// Discovery for the demo gem with a patch for the ruby gem and one for
/// each of two platform gems, as the patch service publishes them. No view
/// is mounted: a gem the lock refuses is refused before any view is asked
/// for.
async fn mount_gem_platform_patches(mock: &wiremock::MockServer) {
use wiremock::matchers::{method, path};
use wiremock::{Mock, ResponseTemplate};
const PLATFORM_PATCHES: [(&str, &str); 3] = [
("ruby", GEM_UUID),
("arm64-darwin", GEM_UUID2),
("x86_64-linux", "37373737-3737-4737-8737-373737373737"),
];
let patches: Vec<Value> = PLATFORM_PATCHES
.iter()
.map(|(platform, uuid)| {
json!({
"uuid": uuid,
"purl": format!("{GEM_PURL}?platform={platform}"),
"tier": "free",
"cveIds": ["CVE-2026-0002"],
"ghsaIds": [],
"severity": "high",
"title": "gem vendor target"
})
})
.collect();
Mock::given(method("POST"))
.and(path("/v0/orgs/test-org/patches/batch"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"packages": [{ "purl": GEM_PURL, "patches": patches }],
"canAccessPaidPatches": false,
})))
.mount(mock)
.await;
let listed: Vec<Value> = PLATFORM_PATCHES
.iter()
.map(|(platform, uuid)| {
json!({
"uuid": uuid,
"purl": format!("{GEM_PURL}?platform={platform}"),
"publishedAt": "2026-01-01T00:00:00Z",
"description": "gem vendor patch",
"license": "MIT",
"tier": "free",
"vulnerabilities": {}
})
})
.collect();
Mock::given(method("GET"))
.and(path(
"/v0/orgs/test-org/patches/by-package/pkg%3Agem%2Fdemo-gem%401.0.0",
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"patches": listed,
"canAccessPaidPatches": false,
})))
.mount(mock)
.await;
}

/// The arguments of a vendored scan of `root` against `mock_uri`, less
/// `--json`.
fn scan_vendor_argv<'a>(root: &'a Path, mock_uri: &'a str) -> Vec<&'a str> {
vec![
"scan",
"--mode",
"vendored",
"--yes",
"--api-url",
mock_uri,
"--api-token",
"fake-token",
"--org",
"test-org",
"--cwd",
root.to_str().unwrap(),
]
}

/// A refusal `Gemfile.lock` gives for a gem is the gem's, whichever of its
/// builds a patch is for: a gem with a patch per locked build is refused
/// once, under the patch of its ruby gem, and counted as one failure
/// (#2436). Nothing is written.
#[tokio::test]
async fn scan_vendor_gem_lock_refusal_is_reported_once_per_gem() {
let mock = wiremock::MockServer::start().await;
mount_gem_platform_patches(&mock).await;
let fx = gem_fixture();
std::fs::write(fx.lock_path(), GEM_LOCK_RUBY_BESIDE_PLATFORMS).unwrap();
let uri = mock.uri();

let (code, env) = run_scan_vendor(fx.root(), &uri, &[]);
assert_eq!(code, 1, "{env:#}");
let failed: Vec<&Value> = env["events"]
.as_array()
.unwrap()
.iter()
.filter(|e| e["action"] == "failed")
.collect();
assert_eq!(failed.len(), 1, "one refusal for the gem: {env:#}");
assert_eq!(failed[0]["purl"], GEM_PURL_QUALIFIED, "{env:#}");
assert_eq!(failed[0]["uuid"], GEM_UUID, "{env:#}");
assert_eq!(
failed[0]["errorCode"], "platform_gem_unsupported",
"{env:#}"
);
assert_eq!(env["summary"]["failed"], 1, "{env:#}");

let (code, stdout, stderr) = run_cli(fx.root(), &scan_vendor_argv(fx.root(), &uri), &[]);
assert_eq!(code, 1, "stdout:\n{stdout}\nstderr:\n{stderr}");
let refusals: Vec<&str> = stderr
.lines()
.filter(|line| line.contains("platform_gem_unsupported"))
.collect();
assert_eq!(refusals.len(), 1, "stdout:\n{stdout}\nstderr:\n{stderr}");
assert!(
refusals[0].contains(&format!("[error] {GEM_PURL_QUALIFIED} (")),
"{refusals:?}"
);
let all = format!("{stdout}{stderr}");
assert!(
all.contains("Nothing was vendored: 1 patch failed (see above)."),
"stdout:\n{stdout}\nstderr:\n{stderr}"
);

// The dry run previews the same single refusal.
let mut argv = scan_vendor_argv(fx.root(), &uri);
argv.push("--dry-run");
let (code, stdout, stderr) = run_cli(fx.root(), &argv, &[]);
assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
let previewed: Vec<&str> = stdout
.lines()
.filter(|line| line.contains("[would-refuse]"))
.collect();
assert_eq!(previewed.len(), 1, "stdout:\n{stdout}\nstderr:\n{stderr}");
assert!(
previewed[0].contains(&format!(
"[would-refuse] {GEM_PURL_QUALIFIED} (platform_gem_unsupported)"
)),
"{previewed:?}"
);
argv.push("--json");
let (code, stdout, stderr) = run_cli(fx.root(), &argv, &[]);
assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
let env: Value = serde_json::from_str(stdout.trim()).unwrap();
let skipped: Vec<&Value> = env["events"]
.as_array()
.unwrap()
.iter()
.filter(|e| e["errorCode"] == "platform_gem_unsupported")
.collect();
assert_eq!(skipped.len(), 1, "{env:#}");
assert_eq!(skipped[0]["purl"], GEM_PURL_QUALIFIED, "{env:#}");

assert!(!fx.root().join(".socket/vendor").exists());
assert_eq!(
std::fs::read_to_string(fx.lock_path()).unwrap(),
GEM_LOCK_RUBY_BESIDE_PLATFORMS
);
assert_eq!(
std::fs::read_to_string(fx.gemfile_path()).unwrap(),
GEM_GEMFILE
);
}

/// A gem `scan --mode vendored` run at patch A, then the bytes of the
/// files that wiring owns: Gemfile, lock, ledger and the vendored lib.
async fn gem_vendored_at_a() -> (GemFixture, [Vec<u8>; 4]) {
Expand Down
Loading
Loading