Skip to content

Commit 5178ef8

Browse files
committed
Harden opt-in note dedup and terminal text
Suppress a nested note only when its UUID, flag, and full note match what the caller displayed. Keep changed API instructions visible. Strip control characters from decoded PURLs in note output. Add regressions for differing search/view notes, terminal controls, and UUID deduplication. Assisted-by: Claude Code:kimi-k3p1-pro
1 parent 2f5652b commit 5178ef8

6 files changed

Lines changed: 150 additions & 15 deletions

File tree

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,7 @@ pub struct DownloadParams {
390390
/// `--patch-server-url`: the extra origin whose URLs count as hosted
391391
/// when lockfile discovery reads the project's hosted pins.
392392
pub patch_server_url: Option<String>,
393-
pub opt_in_notes_shown: Vec<String>,
393+
pub opt_in_notes_shown: Vec<crate::ui::ShownOptIn>,
394394
}
395395

396396
impl DownloadParams {
@@ -1412,7 +1412,7 @@ pub(crate) async fn run_nested_apply(
14121412
common: GlobalArgs,
14131413
json: bool,
14141414
report_user_patch_skips: bool,
1415-
shown_opt_in_uuids: Vec<String>,
1415+
shown_opt_ins: Vec<crate::ui::ShownOptIn>,
14161416
recorded: &[(String, String)],
14171417
client: &ApiClient,
14181418
lock: LockGuard,
@@ -1427,7 +1427,7 @@ pub(crate) async fn run_nested_apply(
14271427
nested: Some(super::apply::NestedApply {
14281428
caller_json: json,
14291429
report_user_patch_skips,
1430-
shown_opt_in_uuids,
1430+
shown_opt_ins,
14311431
}),
14321432
};
14331433
// The nested apply runs on the host's client: seeded, never rebuilt.

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

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ pub struct NestedApply {
186186
/// (`get`) checked only its own selection. `scan` already reported
187187
/// every protected installed package, so it passes `false`.
188188
pub report_user_patch_skips: bool,
189-
pub shown_opt_in_uuids: Vec<String>,
189+
pub shown_opt_ins: Vec<crate::ui::ShownOptIn>,
190190
}
191191

192192
impl ApplyArgs {
@@ -1849,12 +1849,12 @@ pub(crate) async fn run_locked(
18491849
for line in block {
18501850
println!("{line}");
18511851
}
1852-
let shown_opt_in_uuids = args
1852+
let shown_opt_ins = args
18531853
.nested
18541854
.as_ref()
1855-
.map_or(&[][..], |nested| nested.shown_opt_in_uuids.as_slice());
1855+
.map_or(&[][..], |nested| nested.shown_opt_ins.as_slice());
18561856
if let Some(notes) =
1857-
format_opt_in_notes(&opt_ins, &results, &unmatched, shown_opt_in_uuids)
1857+
format_opt_in_notes(&opt_ins, &results, &unmatched, shown_opt_ins)
18581858
{
18591859
println!("\n{notes}");
18601860
}
@@ -2402,7 +2402,7 @@ fn format_opt_in_notes(
24022402
opt_ins: &OptInPatches,
24032403
results: &[ApplyResult],
24042404
unmatched: &[String],
2405-
shown_opt_in_uuids: &[String],
2405+
shown_opt_ins: &[crate::ui::ShownOptIn],
24062406
) -> Option<String> {
24072407
let shown: HashSet<&str> = results
24082408
.iter()
@@ -2411,7 +2411,11 @@ fn format_opt_in_notes(
24112411
.collect();
24122412
crate::ui::opt_in_note_block(opt_ins.iter().filter_map(
24132413
|(purl, uuid, requires_opt_in, opt_in_note)| {
2414-
if !shown.contains(purl.as_str()) || shown_opt_in_uuids.contains(uuid) {
2414+
if !shown.contains(purl.as_str())
2415+
|| shown_opt_ins
2416+
.iter()
2417+
.any(|shown| shown.matches(uuid, *requires_opt_in, opt_in_note.as_deref()))
2418+
{
24152419
return None;
24162420
}
24172421
Some(crate::ui::OptInEntry {

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1297,7 +1297,7 @@ pub async fn run(args: GetArgs) -> i32 {
12971297
let note = crate::ui::terminal_text(note).replace('\n', "\n ");
12981298
println!(
12991299
"Opt-in required for {}: {note}",
1300-
normalize_purl(&patch.purl)
1300+
crate::ui::terminal_purl(&patch.purl)
13011301
);
13021302
}
13031303
}
@@ -1813,7 +1813,10 @@ pub async fn run(args: GetArgs) -> i32 {
18131813

18141814
// Download and apply (agent mode), with the run's client and flags.
18151815
let mut params = get_download_params(&args, args.save_only, /*persist_blobs=*/ true);
1816-
params.opt_in_notes_shown = selected.iter().map(|patch| patch.uuid.clone()).collect();
1816+
params.opt_in_notes_shown = selected
1817+
.iter()
1818+
.map(crate::ui::ShownOptIn::from_search)
1819+
.collect();
18171820
let run = DownloadRun {
18181821
api_client: &api_client,
18191822
lock_timeout: args.common.lock_timeout,
@@ -2162,7 +2165,7 @@ async fn save_and_apply_patch(
21622165
nested_apply_args(&args.common, &manifest_path, quiet),
21632166
args.common.json,
21642167
true,
2165-
vec![patch.uuid.clone()],
2168+
vec![crate::ui::ShownOptIn::from_response(patch)],
21662169
&recorded,
21672170
client,
21682171
lock,

‎crates/socket-patch-cli/src/ui/mod.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,11 @@ use crate::args::GlobalArgs;
2323
pub(crate) use prompt::confirm;
2424
pub use prompt::{select_one, SelectError};
2525
pub(crate) use status::StatusLine;
26+
pub use text::ShownOptIn;
2627
pub(crate) use text::{
2728
agent_next_steps, manifest_error_message, next_steps, next_steps_installed, opt_in_note_block,
28-
plural, sentence_case, shell_word, short_uuid, sweep_failure, terminal_text, truncate,
29-
OptInEntry,
29+
plural, sentence_case, shell_word, short_uuid, sweep_failure, terminal_purl, terminal_text,
30+
truncate, OptInEntry,
3031
};
3132

3233
/// [`text::no_patches_message`] for this run: the manifest path is named

‎crates/socket-patch-cli/src/ui/text.rs‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,13 @@ pub(crate) fn terminal_text(s: &str) -> String {
255255
.collect()
256256
}
257257

258+
pub(crate) fn terminal_purl(purl: &str) -> String {
259+
socket_patch_core::utils::purl::normalize_purl(purl)
260+
.chars()
261+
.filter(|c| !c.is_control())
262+
.collect()
263+
}
264+
258265
#[derive(Clone, Copy)]
259266
pub(crate) struct OptInEntry<'a> {
260267
pub purl: &'a str,
@@ -274,6 +281,50 @@ impl<'a> OptInEntry<'a> {
274281
}
275282
}
276283

284+
#[derive(Clone, Debug, Default, PartialEq, Eq)]
285+
pub struct ShownOptIn {
286+
uuid: String,
287+
requires_opt_in: Option<bool>,
288+
opt_in_note: Option<String>,
289+
}
290+
291+
impl ShownOptIn {
292+
fn new(uuid: &str, requires_opt_in: Option<bool>, opt_in_note: Option<&str>) -> Self {
293+
Self {
294+
uuid: uuid.to_string(),
295+
requires_opt_in,
296+
opt_in_note: opt_in_note.map(str::to_string),
297+
}
298+
}
299+
300+
pub fn from_search(patch: &socket_patch_core::api::types::PatchSearchResult) -> Self {
301+
Self::new(
302+
&patch.uuid,
303+
patch.requires_opt_in,
304+
patch.opt_in_note.as_deref(),
305+
)
306+
}
307+
308+
pub fn from_response(patch: &socket_patch_core::api::types::PatchResponse) -> Self {
309+
Self::new(
310+
&patch.uuid,
311+
patch.requires_opt_in,
312+
patch.opt_in_note.as_deref(),
313+
)
314+
}
315+
316+
pub(crate) fn matches(
317+
&self,
318+
uuid: &str,
319+
requires_opt_in: Option<bool>,
320+
opt_in_note: Option<&str>,
321+
) -> bool {
322+
self.uuid == uuid
323+
&& self.requires_opt_in == requires_opt_in
324+
&& self.opt_in_note.as_deref() == opt_in_note
325+
}
326+
}
327+
277328
pub(crate) fn opt_in_note_block<'a>(
278329
entries: impl IntoIterator<Item = OptInEntry<'a>>,
279330
) -> Option<String> {
@@ -293,7 +344,7 @@ pub(crate) fn opt_in_note_block<'a>(
293344
continue;
294345
}
295346
let note = note.replace('\n', "\n ");
296-
let purl = socket_patch_core::utils::purl::normalize_purl(entry.purl);
347+
let purl = terminal_purl(entry.purl);
297348
let block = block.get_or_insert_with(|| "Opt-in required:".to_string());
298349
block.push_str(&format!("\n {purl}: {note}"));
299350
}
@@ -335,6 +386,30 @@ mod tests {
335386
assert_eq!(plural(7, "patch", "patches"), "7 patches");
336387
}
337388

389+
#[test]
390+
fn opt_in_block_sanitizes_purls_and_dedups_uuids() {
391+
let block = opt_in_note_block([
392+
OptInEntry {
393+
purl: "pkg:npm/bad%1Bname%09more\r\nnext@1.0.0",
394+
uuid: "uuid-a",
395+
requires_opt_in: Some(true),
396+
opt_in_note: Some("Enable safe mode."),
397+
},
398+
OptInEntry {
399+
purl: "pkg:npm/other@1.0.0",
400+
uuid: "uuid-a",
401+
requires_opt_in: Some(true),
402+
opt_in_note: Some("Enable safe mode."),
403+
},
404+
])
405+
.unwrap();
406+
assert_eq!(
407+
block,
408+
"Opt-in required:\n pkg:npm/badnamemorenext@1.0.0: Enable safe mode."
409+
);
410+
assert!(!block.contains('\x1b') && !block.contains('\r') && !block.contains('\t'));
411+
}
412+
338413
#[test]
339414
fn truncate_short_input_is_untouched() {
340415
assert_eq!(truncate("hello", 60), "hello");

‎crates/socket-patch-cli/tests/get/get_render.rs‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,58 @@ async fn opt_in_note_renders_and_persists_in_human_and_json_get() {
439439
assert_eq!(event["details"]["optInNote"], NOTE);
440440
}
441441

442+
#[tokio::test]
443+
async fn changed_view_opt_in_note_is_not_suppressed_in_nested_apply() {
444+
const PREVIEW_NOTE: &str = "Preview configuration instruction.";
445+
const LATEST_NOTE: &str = "Latest configuration instruction.";
446+
let server = MockServer::start().await;
447+
let cve = "CVE-2024-4245";
448+
Mock::given(method("GET"))
449+
.and(path(format!("/v0/orgs/{ORG}/patches/by-cve/{cve}")))
450+
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
451+
"patches": [{
452+
"uuid": UUID, "purl": PURL,
453+
"publishedAt": "2024-01-01T00:00:00Z",
454+
"description": "Opt-in metadata changes", "license": "MIT", "tier": "free",
455+
"vulnerabilities": {},
456+
"requiresOptIn": true, "optInNote": PREVIEW_NOTE,
457+
}],
458+
"canAccessPaidPatches": false,
459+
})))
460+
.mount(&server)
461+
.await;
462+
Mock::given(method("GET"))
463+
.and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}")))
464+
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
465+
"uuid": UUID,
466+
"purl": PURL,
467+
"publishedAt": "2024-01-01T00:00:00Z",
468+
"files": one_file_view(),
469+
"vulnerabilities": {},
470+
"description": "Opt-in metadata changes",
471+
"license": "MIT",
472+
"tier": "free",
473+
"requiresOptIn": true,
474+
"optInNote": LATEST_NOTE,
475+
})))
476+
.mount(&server)
477+
.await;
478+
let tmp = tempfile::tempdir().unwrap();
479+
write_project(tmp.path());
480+
481+
let (code, stdout, stderr) = run_get_bin(tmp.path(), &server.uri(), &[cve]);
482+
assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}");
483+
assert!(stdout.contains(PREVIEW_NOTE), "{stdout}");
484+
assert!(
485+
stdout.contains(&format!("Opt-in required:\n {PURL}: {LATEST_NOTE}")),
486+
"nested apply must show the refreshed view's note: {stdout}"
487+
);
488+
assert_eq!(
489+
manifest_json(tmp.path())["patches"][PURL]["optInNote"],
490+
LATEST_NOTE
491+
);
492+
}
493+
442494
#[tokio::test]
443495
async fn unchanged_uuid_refreshes_and_clears_opt_in_metadata_on_both_save_paths() {
444496
async fn mount_api(server: &MockServer, cve: &str, note: Option<&str>) {

0 commit comments

Comments
 (0)