Skip to content

Commit 3854491

Browse files
mikolalysenkoclaude
andcommitted
Never patch a pnpm, yarn or vlt dependency the user patched
A package the project patches itself is applied by the package manager on top of whatever tarball the lock names, so a Socket pin of it either fails the install or installs the user's diff stacked on the Socket patch. The CLI's consent gate (patch::user_patches::UserPatchIndex, #1646) already kept `scan` / `get` / `vendor` / `apply` from wiring such pnpm, yarn berry and patch-package packages unless --allow-patch-conflicts, but two consumers did not read that evidence: - vex discovery attested a pnpm, yarn, vlt (or npm / Bun) pin of such a package: a pin written before the patch was declared, or one an --allow-patch-conflicts run wrote. - the in-memory hosted engine (Node addon, hosted-bundle) has no gate in front of it and rewired them. One detector, three consumers. UserPatchIndex's pnpm / yarn / patch-package parse rules are factored into pure helpers (pnpm_yaml, yarn_manifest, yarn_lock, patch_package_dirs, patch_file), which the consent gate keeps using, plus UserPatchIndex::npm_family_in, which reads the same declarations through a ProjectView (disk, snapshot or memory): package.json's pnpm.patchedDependencies, yarn patch: descriptors and patch-package dirs, pnpm-workspace.yaml's patchedDependencies, the patches of the given pnpm locks (top-level map, patch_hash suffixes) and yarn.lock's user patch: locators. It leaves out npm's and Bun's own top-level patchedDependencies, which no other package manager reads and which #711 / #367 / #2010 already judge per resolution. - Discovery: a new vex::discover::user_patched pass marks every npm ref the index protects UnattestedKind::UserPatchedDependency (the ref stays, so rollback / remove / list still find it). The bytes the install runs are Socket's patch alone only when no user patch is declared, so a declared one always withholds the statement, with or without consent. - Hosted: engine::withhold_user_patched drops such candidates from every rewriter and records them skipped `user_patch_conflict` (the consent gate's code), plus a warning in memory. The in-memory engine always applies it; the CLI disk flow applies it unless --allow-patch-conflicts (it adds the Rush lock the consent gate does not read). - Vendored: unchanged. Every vendored entry point already runs the consent gate, which refuses (`vendor`, vendored writers) or skips (`scan`, `apply`) these packages. Override: the existing --allow-patch-conflicts, invocation-only. It already covered pnpm / yarn / patch-package at the consent gate and now also lifts the engine gate; vex never attests while the patch is declared. npm / Bun native patches stay refused even with consent, as before. vlt has no patch mechanism (vlt@1.6.2 has no patchedDependencies, patch_hash or `patch` command; vlt.json modifiers rewrite specs), and neither has yarn classic, so patch-package is what is read for both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 76bb103 commit 3854491

11 files changed

Lines changed: 1039 additions & 107 deletions

File tree

‎crates/socket-patch-cli/CLI_CONTRACT.md‎

Lines changed: 10 additions & 3 deletions
Large diffs are not rendered by default.

‎crates/socket-patch-cli/src/commands/scan/hosted.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -887,6 +887,20 @@ async fn run_redirect_selected_untracked(
887887
&vlt_preflight.withheld_everywhere,
888888
&mut skipped,
889889
);
890+
// The engine's own user-patch gate (pnpm, yarn, patch-package), which
891+
// the in-memory engine applies too. The consent gate above already
892+
// left such packages out unless `--allow-patch-conflicts`, which lifts
893+
// this one as well; it still covers evidence that gate does not read
894+
// (a Rush lock's patched entries). Each such package is a skip event,
895+
// as the consent gate reports it.
896+
let _ = engine::withhold_user_patched(
897+
&view,
898+
&std::collections::BTreeMap::new(),
899+
&mut candidates,
900+
&mut skipped,
901+
common.allow_patch_conflicts,
902+
)
903+
.await;
890904
// A NEW row the lockfiles already pin on the patch server these
891905
// references name (not a configured one, so the recorded view's
892906
// discovery could not see it) is ALREADY: decided here, before the lock

‎crates/socket-patch-cli/src/commands/vex_sources.rs‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -235,8 +235,9 @@ const NOTE_MAVEN_CLASSIFIER_UNPATCHED: &str = "vex_maven_classifier_unpatched";
235235
/// Omission tag and note: a pnpm lock pins the patch, but `gitBranchLockfile`
236236
/// makes pnpm install from a `pnpm-lock.<branch>.yaml` (`vex::Unattested`).
237237
const NOTE_PNPM_GIT_BRANCH_LOCKFILE: &str = "vex_pnpm_git_branch_lockfile";
238-
/// Omission tag and note: an npm or Bun pin's package is one the project
239-
/// patches itself (`patchedDependencies`, `vex::Unattested`).
238+
/// Omission tag and note: an npm-family pin's package is one the project
239+
/// patches itself (npm / Bun / pnpm `patchedDependencies`, a yarn `patch:`
240+
/// descriptor, a patch-package patch; `vex::Unattested`).
240241
const NOTE_NPM_PATCHED_DEPENDENCY: &str = "vex_npm_patched_dependency";
241242

242243
/// The omission tag of an [`Unattested`](socket_patch_core::vex::Unattested)
@@ -282,10 +283,12 @@ fn unattested_note(kind: UnattestedKind) -> (&'static str, &'static str) {
282283
),
283284
UnattestedKind::UserPatchedDependency => (
284285
NOTE_NPM_PATCHED_DEPENDENCY,
285-
"not attested while the project patches the package itself (fold the Socket fix \
286-
into your own patch, or remove the `patchedDependencies` entry and re-run); an \
287-
npm pin an earlier hosted run wrote fails `npm ci` with `EPATCHFAILED` until \
288-
`socket-patch rollback <uuid>` restores the registry entry",
286+
"not attested while the project patches the package itself, even when it was \
287+
wired with `--allow-patch-conflicts` (fold the Socket fix into your own patch, or \
288+
remove your patch: the `patchedDependencies` entry, the yarn `patch:` descriptor \
289+
or the patch-package file, and re-run); an npm pin an earlier hosted run wrote \
290+
fails `npm ci` with `EPATCHFAILED` until `socket-patch rollback <uuid>` restores \
291+
the registry entry",
289292
),
290293
}
291294
}

‎crates/socket-patch-cli/tests/hosted_memory_engine.rs‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2202,3 +2202,125 @@ async fn issue_1630_berry_exec_and_git_copies_are_named() {
22022202
}
22032203
}
22042204
}
2205+
2206+
/// REGRESSION: the in-memory engine (no consent gate in front of it, unlike
2207+
/// the CLI) pinned a package the project patches itself with pnpm
2208+
/// (`patchedDependencies`, in `pnpm-workspace.yaml`, `package.json`'s
2209+
/// `pnpm` field or the lock), yarn (a `patch:` descriptor in
2210+
/// `package.json`, or the locator `yarn.lock` resolves) or patch-package,
2211+
/// so the install stacked the user's diff on the hosted
2212+
/// patch. Such a candidate is now withheld from every rewriter, skipped
2213+
/// `user_patch_conflict` with a warning, and its lock left untouched;
2214+
/// another package's patch withholds nothing.
2215+
#[tokio::test]
2216+
async fn user_patched_npm_packages_are_never_pinned() {
2217+
let berry_wrapper =
2218+
"\"left-pad\": \"patch:left-pad@npm%3A^1.3.0#./.yarn/patches/left-pad.patch\"";
2219+
let cases: Vec<(&str, &str, String, &str)> = vec![
2220+
(
2221+
"redirect/npm/pnpm/basic",
2222+
"pnpm-workspace.yaml",
2223+
"patchedDependencies:\n left-pad@1.3.0: patches/left-pad@1.3.0.patch\n".into(),
2224+
"pnpm-lock.yaml",
2225+
),
2226+
(
2227+
"redirect/npm/pnpm/basic",
2228+
"package.json",
2229+
r#"{"pnpm":{"patchedDependencies":{"left-pad":"patches/left-pad.patch"}}}"#.into(),
2230+
"pnpm-lock.yaml",
2231+
),
2232+
(
2233+
"redirect/npm/yarn-berry/basic",
2234+
"package.json",
2235+
String::from_utf8(
2236+
fixture_files(&fixtures_root().join("redirect/npm/yarn-berry/basic/input"))
2237+
["package.json"]
2238+
.clone(),
2239+
)
2240+
.unwrap()
2241+
.replacen("\"left-pad\": \"^1.3.0\"", berry_wrapper, 1),
2242+
"yarn.lock",
2243+
),
2244+
(
2245+
"redirect/npm/yarn-berry/basic",
2246+
"yarn.lock",
2247+
format!(
2248+
"{}\n\"left-pad@patch:left-pad@npm%3A1.3.0#./.yarn/patches/lp.patch\":\n \
2249+
version: 1.3.0\n resolution: \"left-pad@patch:left-pad@npm%3A1.3.0#./.yarn/\
2250+
patches/lp.patch::version=1.3.0&hash=abc123\"\n languageName: node\n \
2251+
linkType: hard\n",
2252+
String::from_utf8(
2253+
fixture_files(&fixtures_root().join("redirect/npm/yarn-berry/basic/input"))
2254+
["yarn.lock"]
2255+
.clone()
2256+
)
2257+
.unwrap()
2258+
),
2259+
"yarn.lock",
2260+
),
2261+
(
2262+
NPM_FIXTURE,
2263+
"patches/left-pad+1.3.0.patch",
2264+
"diff\n".into(),
2265+
"package-lock.json",
2266+
),
2267+
];
2268+
for (fixture, file, text, lock) in cases {
2269+
let dir = fixtures_root().join(fixture);
2270+
let server = MockServer::start().await;
2271+
mount_api(
2272+
&server,
2273+
&patches_from_overrides(&dir.join("overrides.json"), None),
2274+
)
2275+
.await;
2276+
let files = fixture_files(&dir.join("input"));
2277+
let control = run_engine(&server, build_input(&files, &[], options(false))).await;
2278+
assert_eq!(
2279+
control.projects[0].redirected.len(),
2280+
1,
2281+
"{fixture}: control {:?}",
2282+
control.projects[0].skipped
2283+
);
2284+
2285+
let mut files = files;
2286+
files.insert(file.to_string(), text.clone().into_bytes());
2287+
let output = run_engine(&server, build_input(&files, &[], options(false))).await;
2288+
let project = &output.projects[0];
2289+
assert!(project.error.is_none(), "{fixture}: {:?}", project.error);
2290+
assert!(
2291+
project.redirected.is_empty(),
2292+
"{fixture} {file}: {:?}",
2293+
project.redirected
2294+
);
2295+
let skip = project
2296+
.skipped
2297+
.iter()
2298+
.find(|s| s.reason == "user_patch_conflict")
2299+
.unwrap_or_else(|| panic!("{fixture} {file}: {:?}", project.skipped));
2300+
assert_eq!(skip.purl, "pkg:npm/left-pad@1.3.0");
2301+
assert!(
2302+
skip.detail.as_deref().is_some_and(|d| d.contains(file)),
2303+
"{fixture}: {:?}",
2304+
skip.detail
2305+
);
2306+
let warnings = project.redirect["warnings"].as_array().unwrap();
2307+
assert!(
2308+
warnings.iter().any(|w| w["code"] == "user_patch_conflict"),
2309+
"{fixture}: {warnings:?}"
2310+
);
2311+
assert!(
2312+
output.changed_files.iter().all(|f| f.path != lock),
2313+
"{fixture}: {lock} must stay untouched"
2314+
);
2315+
2316+
// Another package's patch withholds nothing.
2317+
let mut files = fixture_files(&dir.join("input"));
2318+
files.insert(
2319+
"pnpm-workspace.yaml".into(),
2320+
b"patchedDependencies:\n is-number@7.0.0: patches/is-number.patch\n".to_vec(),
2321+
);
2322+
files.insert("patches/is-number+7.0.0.patch".into(), b"diff\n".to_vec());
2323+
let output = run_engine(&server, build_input(&files, &[], options(false))).await;
2324+
assert_eq!(output.projects[0].redirected.len(), 1, "{fixture}: other");
2325+
}
2326+
}

‎crates/socket-patch-cli/tests/in_process_redirect_pnpm.rs‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3354,3 +3354,75 @@ async fn issue_1268_member_lock_still_hosted_keeps_trust_without_warning() {
33543354
"the workspace file is left as it was"
33553355
);
33563356
}
3357+
3358+
/// A package the project patches itself with pnpm's `patchedDependencies`
3359+
/// is never pinned by default (the consent gate skips it), and only the
3360+
/// explicit `--allow-patch-conflicts` override pins it. pnpm then applies
3361+
/// the user's diff on top of the hosted tarball, so the install never runs
3362+
/// the Socket patch alone: lockfile discovery keeps the pin as a ref (so
3363+
/// `rollback` restores it) but marks it unattested, and `vex` omits it.
3364+
#[tokio::test]
3365+
#[serial]
3366+
async fn hosted_pins_a_pnpm_patched_dependency_only_with_explicit_consent() {
3367+
use socket_patch_core::vex::discover::{
3368+
discover_patched_refs_with, DiscoverOptions, UnattestedKind,
3369+
};
3370+
3371+
let server = MockServer::start().await;
3372+
mock_discovery(&server).await;
3373+
mock_reference(&server).await;
3374+
3375+
let tmp = tempfile::tempdir().unwrap();
3376+
write_pnpm_project(tmp.path());
3377+
let workspace = format!(
3378+
"packages:\n - '.'\npatchedDependencies:\n {NAME}@{VERSION}: patches/{NAME}.patch\n"
3379+
);
3380+
std::fs::write(tmp.path().join("pnpm-workspace.yaml"), &workspace).unwrap();
3381+
let pristine = std::fs::read_to_string(tmp.path().join("pnpm-lock.yaml")).unwrap();
3382+
3383+
// Default: skipped, nothing written.
3384+
let code = run(hosted_args(tmp.path(), server.uri())).await;
3385+
assert_eq!(code, 0, "a user-patch skip alone exits 0");
3386+
assert_eq!(
3387+
std::fs::read_to_string(tmp.path().join("pnpm-lock.yaml")).unwrap(),
3388+
pristine,
3389+
"the user-patched package is left on its registry entry"
3390+
);
3391+
3392+
// Explicit consent: pinned.
3393+
let mut args = hosted_args(tmp.path(), server.uri());
3394+
args.common.allow_patch_conflicts = true;
3395+
let code = run(args).await;
3396+
assert_eq!(code, 0, "the consented run succeeds");
3397+
let lock = std::fs::read_to_string(tmp.path().join("pnpm-lock.yaml")).unwrap();
3398+
assert!(
3399+
lock.contains(&format!("tarball: {HOSTED_URL}")),
3400+
"--allow-patch-conflicts pins the package; got:\n{lock}"
3401+
);
3402+
3403+
// ...but the pin is never attested while pnpm stacks the user's patch.
3404+
let out = discover_patched_refs_with(
3405+
tmp.path(),
3406+
&DiscoverOptions {
3407+
patch_server_origins: vec!["http://patch.test".to_string()],
3408+
},
3409+
)
3410+
.await;
3411+
assert!(
3412+
out.refs.iter().any(|r| r.purl == PURL && r.uuid == UUID),
3413+
"the pin stays a ref: {:?}",
3414+
out.refs
3415+
);
3416+
let marked: Vec<_> = out
3417+
.unattested
3418+
.iter()
3419+
.filter(|u| u.kind == UnattestedKind::UserPatchedDependency)
3420+
.map(|u| (u.purl.as_str(), u.uuid.as_str()))
3421+
.collect();
3422+
assert_eq!(marked, [(PURL, UUID)], "{:#?}", out.unattested);
3423+
assert!(
3424+
out.unattested[0].detail.contains("pnpm-workspace.yaml"),
3425+
"{}",
3426+
out.unattested[0].detail
3427+
);
3428+
}

‎crates/socket-patch-core/src/hosted/engine.rs‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,105 @@ pub fn withhold_everywhere(
337337
candidates.retain(|c| !withheld_everywhere.contains_key(&c.dep.patch_uuid));
338338
}
339339

340+
/// Skip reason of an npm candidate withheld because the project patches
341+
/// that package itself ([`withhold_user_patched`]): the code the CLI's
342+
/// consent gate reports for the same packages.
343+
pub const USER_PATCH_CONFLICT: &str = "user_patch_conflict";
344+
345+
/// The pnpm and yarn locks [`withhold_user_patched`] reads when `files`
346+
/// does not already hold them.
347+
const USER_PATCH_LOCKS: [&str; 4] = [
348+
"pnpm-lock.yaml",
349+
"shrinkwrap.yaml",
350+
"yarn.lock",
351+
crate::constants::npm_family::RUSH_COMMON_LOCK_REL,
352+
];
353+
354+
/// Withhold from every rewriter each npm candidate whose package the
355+
/// project patches itself with pnpm (`patchedDependencies`), yarn (a
356+
/// `patch:` descriptor) or patch-package, recording each as skipped
357+
/// ([`USER_PATCH_CONFLICT`]). The package manager applies the user's
358+
/// diff on top of whatever tarball the lock names, so a hosted pin either
359+
/// fails the install once the diff no longer applies or installs bytes
360+
/// that are neither the user's package nor the Socket patch. The
361+
/// evidence is [`UserPatchIndex::npm_family_in`], which `vex` discovery
362+
/// reads too, over `files` (the candidate texts already read: a member's
363+
/// own pnpm lock) and the root pnpm, yarn and Rush locks. npm's and Bun's
364+
/// own `patchedDependencies` are not read here: their rewriters skip such
365+
/// a package per resolution (#711, #367). `allow` is the caller's explicit
366+
/// consent (the CLI's `--allow-patch-conflicts`): nothing is withheld.
367+
/// Returns one [`USER_PATCH_CONFLICT`] warning per withheld candidate,
368+
/// with the skip's detail.
369+
///
370+
/// [`UserPatchIndex::npm_family_in`]: crate::patch::user_patches::UserPatchIndex::npm_family_in
371+
pub async fn withhold_user_patched(
372+
view: &ProjectView<'_>,
373+
files: &BTreeMap<String, String>,
374+
candidates: &mut Vec<Candidate>,
375+
skipped: &mut Vec<SkippedPatch>,
376+
allow: bool,
377+
) -> Vec<RewriteWarning> {
378+
let mut warnings = Vec::new();
379+
if allow || !candidates.iter().any(|c| c.dep.ecosystem == "npm") {
380+
return warnings;
381+
}
382+
let mut read: Vec<(String, String)> = Vec::new();
383+
for rel in USER_PATCH_LOCKS {
384+
if files.contains_key(rel) {
385+
continue;
386+
}
387+
if let Ok(text) = view.read_text(rel).await {
388+
read.push((rel.to_string(), text));
389+
}
390+
}
391+
let locks: Vec<(&str, &str)> = files
392+
.iter()
393+
.chain(read.iter().map(|(rel, text)| (rel, text)))
394+
.filter(|(rel, _)| {
395+
matches!(
396+
rel.rsplit('/').next(),
397+
Some("pnpm-lock.yaml" | "shrinkwrap.yaml" | "yarn.lock")
398+
)
399+
})
400+
.map(|(rel, text)| (rel.as_str(), text.as_str()))
401+
.collect();
402+
let index = crate::patch::user_patches::UserPatchIndex::npm_family_in(view, &locks).await;
403+
if index.is_empty() {
404+
return warnings;
405+
}
406+
candidates.retain(|c| {
407+
if c.dep.ecosystem != "npm" {
408+
return true;
409+
}
410+
let sources = index.conflicts(&c.purl);
411+
if sources.is_empty() {
412+
return true;
413+
}
414+
let detail = user_patched_detail(&c.purl, &sources);
415+
warnings.push(warning(USER_PATCH_CONFLICT, detail.clone()));
416+
skipped.push(SkippedPatch {
417+
detail: Some(detail),
418+
..SkippedPatch::new(&c.purl, &c.dep.patch_uuid, USER_PATCH_CONFLICT)
419+
});
420+
false
421+
});
422+
warnings
423+
}
424+
425+
/// [`withhold_user_patched`]'s skip detail.
426+
fn user_patched_detail(purl: &str, sources: &[String]) -> String {
427+
format!(
428+
"{purl}: {} declares a patch the project applies to this package itself (pnpm \
429+
`patchedDependencies`, a yarn `patch:` descriptor, or a patch-package patch); the \
430+
package manager applies it on top of whatever tarball the lock names, so pinning the \
431+
hosted patch would stack the two (or fail every install once the user's diff no \
432+
longer applies). It is left unchanged and stays without the Socket patch: fold the \
433+
Socket fix into your own patch, or remove the user patch and re-run (the CLI's \
434+
explicit `--allow-patch-conflicts` wires it anyway)",
435+
sources.join(", ")
436+
)
437+
}
438+
340439
/// The project's candidate files as the rewriters read them.
341440
#[derive(Debug, Clone, Default)]
342441
pub struct CandidateFiles {

‎crates/socket-patch-core/src/hosted/memory/stages.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,12 @@ pub(crate) async fn plan(
207207
} else {
208208
engine::read_candidate_files(&view, &unreadable, &candidates).await
209209
};
210+
// A package the project patches itself (pnpm, yarn, patch-package) is
211+
// never wired: the in-memory engine has no consent knob.
212+
pre_warnings.extend(
213+
engine::withhold_user_patched(&view, &read.files, &mut candidates, &mut skipped, false)
214+
.await,
215+
);
210216
let wheels = engine::wheel_targets(&candidates, &read.files)
211217
.into_iter()
212218
.map(|(dep, sha256)| (dep.artifact_url.clone(), sha256.to_string()))

0 commit comments

Comments
 (0)