Skip to content

Commit 74b3306

Browse files
Fix unquoted purls in printed commands (#2182) (#2204)
* Start fix for unquoted purls in commands Claims #2182. The fix follows in later commits. Assisted-by: Claude Code:claude-fable-5-2 * Test the purl in printed rollback commands A gem record's purl carries ?platform=ruby. The hosted hold note prints it as the rollback target, where it matches no hosted pin and its ? is a glob character. The other-scope rollback warning prints a manifest key unquoted. Both tests fail until the next commit. Refs #2182 Assisted-by: Claude Code:claude-fable-5-2 * Name a pin rollback can select in printed commands The hosted gem hold note printed the patch record's purl as the rollback target. A gem record's purl carries ?platform=ruby, which selects no hosted pin, and its ? is a glob character: zsh refuses the command, and bash with nullglob drops the argument and runs a bare rollback, which unwinds every patch in the project. The note and the mirror-pin warning now name the hosted pin by its base purl, as rollback selects it. The other messages that print a command with a purl (list, the withdrawn-patch warning, the prune keep warnings, the other-scope rollback warning) pass it through ui::shell_word, so a manifest key with qualifiers is quoted. The gem e2e serves the record with its qualifier and runs the printed command through a nullglob bash. Fixes #2182 Assisted-by: Claude Code:claude-fable-5-2 * Name the release in the other-scope hint The other-scope rollback warning keeps a record with its whole variant group, so the command it prints names the base purl, which selects that group, instead of one qualified key. The gem e2e now reads the printed command from the scan's own output. Refs #2182 Assisted-by: Claude Code:claude-fable-5-2 --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 54e3792 commit 74b3306

7 files changed

Lines changed: 238 additions & 21 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1088,7 +1088,7 @@ async fn list_project(args: &ListArgs, browsing: bool) -> Listed {
10881088
more; `socket-patch remove {}` removes that entry alone",
10891089
pin.files.join(", "),
10901090
pin.purl,
1091-
pin.purl
1091+
crate::ui::shell_word(&pin.purl)
10921092
)
10931093
} else {
10941094
format!(
@@ -1097,7 +1097,7 @@ async fn list_project(args: &ListArgs, browsing: bool) -> Listed {
10971097
uv_metadata.join(", "),
10981098
pin.purl,
10991099
pin.files.join(", "),
1100-
pin.purl
1100+
crate::ui::shell_word(&pin.purl)
11011101
)
11021102
};
11031103
if args.common.json {

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

Lines changed: 58 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -351,18 +351,26 @@ async fn patched_in_other_scope(
351351

352352
/// `rollback`'s pointer at the scope that still holds a patched copy: a
353353
/// rollback of just that purl, naming `--cwd` when the run used one (the record lives in that
354-
/// project's manifest).
354+
/// project's manifest). The command names the release without the record's
355+
/// qualifiers (`?platform=ruby`, `?artifact_id=...`): the record was kept
356+
/// with its whole variant group, a base purl selects that group, and a `?`
357+
/// is a glob character to the shell. The purl and the directory are quoted
358+
/// where a shell would otherwise read them as more than one word.
355359
fn patched_in_other_scope_warning(purl: &str, path: &Path, common: &GlobalArgs) -> String {
360+
let word = crate::ui::shell_word(strip_purl_qualifiers(purl));
356361
let (scope, mut command) = if common.is_global() {
357-
("the project", format!("socket-patch rollback {purl}"))
362+
("the project", format!("socket-patch rollback {word}"))
358363
} else {
359364
(
360365
"the global install",
361-
format!("socket-patch rollback {purl} -g"),
366+
format!("socket-patch rollback {word} -g"),
362367
)
363368
};
364369
if common.cwd != Path::new(".") {
365-
command.push_str(&format!(" --cwd {}", common.cwd.display()));
370+
command.push_str(&format!(
371+
" --cwd {}",
372+
crate::ui::shell_word(&common.cwd.to_string_lossy())
373+
));
366374
}
367375
format!(
368376
"{purl}: its copy in {scope} ({}) is still patched or could not be \
@@ -4612,6 +4620,52 @@ mod tests {
46124620
use socket_patch_core::manifest::schema::{PatchManifest, PatchRecord};
46134621
use std::collections::HashMap;
46144622

4623+
/// The command this warning tells the user to run is one they paste.
4624+
/// A record's purl can carry qualifiers (`?platform=ruby`,
4625+
/// `?artifact_id=...`), and `?` is a glob character: the command names
4626+
/// the release, which selects the variant group the run kept. What is
4627+
/// left that a shell reads specially (`%40`, a space in `--cwd`) is
4628+
/// quoted (#2182).
4629+
#[test]
4630+
fn other_scope_warning_prints_a_command_a_shell_reads_as_written() {
4631+
let quoted = |word: &str| {
4632+
if cfg!(windows) {
4633+
format!("\"{word}\"")
4634+
} else {
4635+
format!("'{word}'")
4636+
}
4637+
};
4638+
let purl = "pkg:gem/rack@3.1.8?platform=ruby";
4639+
let path = Path::new("/gems/rack-3.1.8");
4640+
let local = crate::args::GlobalArgs::default();
4641+
let warning = patched_in_other_scope_warning(purl, path, &local);
4642+
assert!(
4643+
warning.contains("run `socket-patch rollback pkg:gem/rack@3.1.8 -g` to"),
4644+
"{warning}"
4645+
);
4646+
// The message's own naming of the record stays its full purl.
4647+
assert!(
4648+
warning.starts_with(&format!("{purl}: its copy in")),
4649+
"{warning}"
4650+
);
4651+
4652+
let scoped = "pkg:npm/%40scope/a@1.0.0";
4653+
let global = crate::args::GlobalArgs {
4654+
global: true,
4655+
cwd: PathBuf::from("my app"),
4656+
..crate::args::GlobalArgs::default()
4657+
};
4658+
let warning = patched_in_other_scope_warning(scoped, path, &global);
4659+
assert!(
4660+
warning.contains(&format!(
4661+
"run `socket-patch rollback {} --cwd {}` to",
4662+
quoted(scoped),
4663+
quoted("my app")
4664+
)),
4665+
"{warning}"
4666+
);
4667+
}
4668+
46154669
// The legacy path-taking delegation shape, kept for the unit tests below
46164670
// (`remove` now threads its already-loaded manifest and ledger straight
46174671
// into `rollback_patches_inner`; this wrapper reads them from disk). The

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,12 +396,13 @@ async fn keep_patched_cargo_copies(
396396
prunable.retain(|p| !kept.contains(p));
397397
kept.into_iter()
398398
.map(|purl| {
399+
let word = crate::ui::shell_word(&purl);
399400
(
400401
"cargo_cache_patch_kept",
401402
format!(
402403
"kept {purl}: the project no longer resolves it, but its copy in the \
403404
shared Cargo registry cache is still patched (or could not be \
404-
read to tell); run `socket-patch rollback {purl}` (with `--global` \
405+
read to tell); run `socket-patch rollback {word}` (with `--global` \
405406
when a `cargo vendor` dir hides the registry cache) to restore \
406407
that copy and drop the entry"
407408
),
@@ -435,12 +436,13 @@ async fn keep_patched_pypi_copies(
435436
prunable.retain(|p| !kept.contains(p));
436437
kept.into_iter()
437438
.map(|purl| {
439+
let word = crate::ui::shell_word(&purl);
438440
(
439441
"pypi_installed_patch_kept",
440442
format!(
441443
"kept {purl}: the scan no longer reports it as one of the project's \
442444
packages, but an installed copy is still patched (or could not be \
443-
read to tell); run `socket-patch rollback {purl}` (with `--global` \
445+
read to tell); run `socket-patch rollback {word}` (with `--global` \
444446
when the copy is in another interpreter or a tool's environment) \
445447
to restore that copy and drop the entry"
446448
),

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

Lines changed: 58 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,10 @@ fn mirror_pins_not_moved(
141141
`socket-patch rollback {}` and then this command again",
142142
c.purl,
143143
mirror_sources.base(),
144-
c.purl
144+
// As `rollback` selects a hosted pin: no qualifiers.
145+
crate::ui::shell_word(socket_patch_core::utils::purl::strip_purl_qualifiers(
146+
&c.purl
147+
))
145148
),
146149
))
147150
})
@@ -3277,23 +3280,32 @@ fn format_gem_hold_note(
32773280
if dry_run {
32783281
return Some(note);
32793282
}
3280-
// The one gem's own purl, when exactly one confirmed pin carries its
3281-
// name; else the shape of one, for the user to fill in.
3283+
// The one gem's own pin, when the confirmed pins of its name are one
3284+
// release; else the shape of one, for the user to fill in. A pin is
3285+
// named as `rollback` selects it, without the record's qualifiers
3286+
// (`?platform=ruby` on every gem record): with them the command
3287+
// matches no hosted pin, and under bash's `nullglob` the unquoted `?`
3288+
// drops the argument, leaving the bare `rollback` this note must not
3289+
// give.
32823290
let purl = one.and_then(|name| {
32833291
let prefix = format!("pkg:gem/{name}@");
3284-
let mut pins = confirmed
3292+
let mut pins: Vec<&str> = confirmed
32853293
.iter()
3286-
.map(|(purl, _)| purl.as_str())
3287-
.filter(|purl| purl.starts_with(&prefix));
3288-
match (pins.next(), pins.next()) {
3289-
(Some(purl), None) => Some(purl),
3294+
.map(|(purl, _)| socket_patch_core::utils::purl::strip_purl_qualifiers(purl))
3295+
.filter(|purl| purl.starts_with(&prefix))
3296+
.collect();
3297+
pins.sort_unstable();
3298+
pins.dedup();
3299+
match pins.as_slice() {
3300+
[purl] => Some(crate::ui::shell_word(purl)),
32903301
_ => None,
32913302
}
32923303
});
3304+
let placeholder = || "pkg:gem/<gem>@<version>".to_string();
32933305
let (move_one, target, update_arg) = match (one, purl) {
32943306
(Some(name), Some(purl)) => ("it", purl, name),
3295-
(Some(name), None) => ("it", "pkg:gem/<gem>@<version>", name),
3296-
(None, _) => ("one", "pkg:gem/<gem>@<version>", "<gem>"),
3307+
(Some(name), None) => ("it", placeholder(), name),
3308+
(None, _) => ("one", placeholder(), "<gem>"),
32973309
};
32983310
let again = if command == "scan" {
32993311
"then `socket-patch scan` again"
@@ -5938,6 +5950,42 @@ mod tests {
59385950
`socket-patch scan` again."
59395951
)
59405952
);
5953+
// A gem record's purl carries `?platform=ruby`. The note names the
5954+
// pin as `rollback` selects it, without the qualifier: with it the
5955+
// command matches no hosted pin, and its `?` is a glob character
5956+
// that zsh refuses and bash under `nullglob` drops, leaving a bare
5957+
// `rollback` (#2182).
5958+
let qualified = [
5959+
pin("pkg:gem/rack@3.1.8?platform=ruby"),
5960+
pin("pkg:gem/nokogiri@1.16.0?platform=x86_64-linux"),
5961+
];
5962+
for command in ["scan", "get"] {
5963+
let note =
5964+
super::format_gem_hold_note(&edits[..1], &qualified, command, false).unwrap();
5965+
assert!(
5966+
note.contains("run `socket-patch rollback pkg:gem/rack@3.1.8`, then"),
5967+
"{note}"
5968+
);
5969+
assert!(!note.contains('?'), "{note}");
5970+
}
5971+
// Two records of the one release (a ruby and a platform build) are
5972+
// one pin, so the note still names it.
5973+
let builds = [
5974+
pin("pkg:gem/rack@3.1.8?platform=ruby"),
5975+
pin("pkg:gem/rack@3.1.8?platform=x86_64-linux"),
5976+
];
5977+
let note = super::format_gem_hold_note(&edits[..1], &builds, "scan", false).unwrap();
5978+
assert!(
5979+
note.contains("run `socket-patch rollback pkg:gem/rack@3.1.8`, then"),
5980+
"{note}"
5981+
);
5982+
// Two versions of it are two pins: the user fills in which.
5983+
let versions = [pin("pkg:gem/rack@3.1.8"), pin("pkg:gem/rack@2.2.8")];
5984+
let note = super::format_gem_hold_note(&edits[..1], &versions, "scan", false).unwrap();
5985+
assert!(
5986+
note.contains("run `socket-patch rollback pkg:gem/<gem>@<version>`, then"),
5987+
"{note}"
5988+
);
59415989
// No bare `socket-patch rollback` anywhere: it unwinds every patch.
59425990
for edits in [&edits[..], &edits[..1]] {
59435991
for confirmed in [&confirmed[..], &[]] {

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,9 @@ pub(super) async fn sweep(
246246
"{} is pinned to patch {}, which is no longer published \
247247
({status}), but it was not restored: {message}; re-run, or run \
248248
`socket-patch rollback {}`",
249-
pin.purl, pin.uuid, pin.purl
249+
pin.purl,
250+
pin.uuid,
251+
crate::ui::shell_word(&pin.purl)
250252
),
251253
);
252254
}

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

Lines changed: 112 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6345,13 +6345,84 @@ async fn release_upstream_1_1_0(fx: &RedirectFixture) {
63456345
}
63466346
}
63476347

6348+
/// Serve the patch record's purl the way the patch service spells a gem
6349+
/// record's: with its `?platform=ruby` qualifier, on every route that
6350+
/// carries it (the package a batch result is filed under stays bare). Each
6351+
/// route answers what the fixture's own does, respelled, and outranks it.
6352+
async fn serve_record_purl_with_platform(fx: &RedirectFixture) {
6353+
let api = fx._server.uri();
6354+
let bare = format!("\"purl\":\"{PURL}\"");
6355+
let qualified = format!("\"purl\":\"{PURL}?platform=ruby\"");
6356+
let client = reqwest::Client::new();
6357+
let post = |route: &str| client.post(format!("{api}{route}")).body("{}");
6358+
let get = |route: &str| client.get(format!("{api}{route}"));
6359+
let batch = format!("/v0/orgs/{ORG}/patches/batch");
6360+
let by_package = format!("/v0/orgs/{ORG}/patches/by-package/{DEP}");
6361+
let reference = format!("/v0/orgs/{ORG}/patches/package");
6362+
let view = format!("/v0/orgs/{ORG}/patches/view/{UUID}");
6363+
for (verb, route, request, keep_first) in [
6364+
("POST", batch.as_str(), post(&batch), true),
6365+
("GET", by_package.as_str(), get(&by_package), false),
6366+
("POST", reference.as_str(), post(&reference), false),
6367+
("GET", view.as_str(), get(&view), false),
6368+
] {
6369+
let body = request
6370+
.send()
6371+
.await
6372+
.expect("fixture API reachable")
6373+
.text()
6374+
.await
6375+
.expect("fixture API body");
6376+
assert!(body.contains(&bare), "{route} carries the purl: {body}");
6377+
let respelled = if keep_first {
6378+
let (head, tail) = body.split_once(&bare).expect("checked above");
6379+
format!("{head}{bare}{}", tail.replace(&bare, &qualified))
6380+
} else {
6381+
body.replace(&bare, &qualified)
6382+
};
6383+
assert!(respelled.contains(&qualified), "{route}: {respelled}");
6384+
let matcher = if route == by_package {
6385+
Mock::given(method(verb)).and(path_regex(format!(
6386+
"^/v0/orgs/{ORG}/patches/by-package/.+$"
6387+
)))
6388+
} else {
6389+
Mock::given(method(verb)).and(path(route))
6390+
};
6391+
matcher
6392+
.respond_with(ResponseTemplate::new(200).set_body_raw(respelled, "application/json"))
6393+
.with_priority(1)
6394+
.mount(&fx._server)
6395+
.await;
6396+
}
6397+
}
6398+
6399+
/// The words a bash with `nullglob` set reads `command` as: a word that
6400+
/// holds an unquoted glob character and matches no file is dropped.
6401+
fn bash_nullglob_words(cwd: &Path, command: &str) -> Vec<String> {
6402+
let out = Command::new("bash")
6403+
.args(["-O", "nullglob", "-c", &format!("printf '%s\\n' {command}")])
6404+
.current_dir(cwd)
6405+
.output()
6406+
.expect("bash runs");
6407+
assert!(out.status.success(), "bash reads `{command}`: {out:?}");
6408+
String::from_utf8(out.stdout)
6409+
.expect("utf8 words")
6410+
.lines()
6411+
.map(str::to_owned)
6412+
.collect()
6413+
}
6414+
63486415
/// A hosted gem's only source is its patch's registry, which serves one
63496416
/// version, so the gem leaves `bundle outdated` and `bundle update` cannot
63506417
/// move it (#2070). The scan has to say so, and what it says has to be true
63516418
/// of the real Bundler: with a newer upstream release out, `bundle outdated`
63526419
/// lists the gem before the scan and not after, `bundle update` leaves the
63536420
/// scanned lock at the patched version, and the way past the hold the scan
63546421
/// names (`rollback`, then `bundle update <gem>`) does move the gem.
6422+
///
6423+
/// The `rollback` it names is run as printed, through a shell (#2182): the
6424+
/// record's purl carries `?platform=ruby`, which selects no hosted pin and
6425+
/// which a shell globs, so the command names the pin without it.
63556426
#[tokio::test(flavor = "multi_thread")]
63566427
#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 1.17); \
63576428
the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"]
@@ -6430,6 +6501,7 @@ async fn gem_hosted_scan_says_the_gem_is_held_at_its_version() {
64306501

64316502
// The scan, in human output: it names the gem it now holds and the way
64326503
// past the hold.
6504+
serve_record_purl_with_platform(&fx).await;
64336505
let (code, stdout, stderr) = run_socket(
64346506
&fx.proj,
64356507
&[
@@ -6477,8 +6549,47 @@ async fn gem_hosted_scan_says_the_gem_is_held_at_its_version() {
64776549
);
64786550

64796551
// And the way past it works: roll back, then `bundle update <gem>`.
6552+
// The rollback is the command the note printed, as a shell reads it.
64806553
std::fs::write(&lock_path, &scanned_lock).unwrap();
6481-
rollback();
6554+
let printed = stdout
6555+
.lines()
6556+
.find(|line| line.starts_with("Bundler now takes "))
6557+
.and_then(|line| {
6558+
line.split('`')
6559+
.find(|span| span.starts_with("socket-patch rollback "))
6560+
})
6561+
.expect("the scan's hold line names a rollback");
6562+
let words = bash_nullglob_words(&fx.proj, printed);
6563+
assert_eq!(
6564+
words,
6565+
["socket-patch", "rollback", PURL],
6566+
"a shell passes the printed command on whole"
6567+
);
6568+
let mut argv: Vec<&str> = words[1..].iter().map(String::as_str).collect();
6569+
argv.extend([
6570+
"--json",
6571+
"--cwd",
6572+
cwd,
6573+
"--api-url",
6574+
&api,
6575+
"--org",
6576+
ORG,
6577+
"--api-token",
6578+
"fake",
6579+
"--patch-server-url",
6580+
&api,
6581+
]);
6582+
let (code, stdout, stderr) =
6583+
run_socket_env(&fx.proj, &argv, &[("SOCKET_RUBYGEMS_URL", &upstream)]);
6584+
assert_eq!(
6585+
code, 0,
6586+
"`{printed}`:\nstdout:\n{stdout}\nstderr:\n{stderr}"
6587+
);
6588+
assert_eq!(
6589+
String::from_utf8_lossy(&std::fs::read(&lock_path).unwrap()),
6590+
String::from_utf8_lossy(&fx.pristine_lock),
6591+
"`{printed}` hands the lock back byte for byte"
6592+
);
64826593
let (updated, update) = bundle_cold(&["update", DEP]);
64836594
assert!(updated, "`bundle update {DEP}` after rollback:\n{update}");
64846595
assert!(

0 commit comments

Comments
 (0)