From 12a8dc51db76cefaf083ec3e7a0c47e13873daee Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 11:02:09 -0600 Subject: [PATCH 1/2] fix(id): confine REPL match-derived download paths (#2307) --- pkgs/id/src/commands/find.rs | 37 +------ pkgs/id/src/helpers.rs | 38 +++++++ pkgs/id/src/lib.rs | 3 +- pkgs/id/src/repl/runner.rs | 194 +++++++++++++++++++++++++++++++---- 4 files changed, 214 insertions(+), 58 deletions(-) diff --git a/pkgs/id/src/commands/find.rs b/pkgs/id/src/commands/find.rs index a67697bc12..baf99e957f 100644 --- a/pkgs/id/src/commands/find.rs +++ b/pkgs/id/src/commands/find.rs @@ -78,8 +78,8 @@ use iroh_base::EndpointId; use crate::{ CLIENT_KEY_FILE, FindMatch, META_ALPN, MetaRequest, MetaResponse, TaggedMatch, cmd_get_one, - cmd_get_one_remote, load_or_create_keypair, match_kind, open_store, print_match_cli, - print_matches_cli, + cmd_get_one_remote, helpers::download_output_path, load_or_create_keypair, match_kind, + open_store, print_match_cli, print_matches_cli, }; /// Options for filtering and limiting search results. @@ -149,39 +149,6 @@ impl SearchOptions { } } -/// Build the local write path for a downloaded find/search match. -/// -/// A match name is untrusted input: in remote mode both the name and the -/// blob content come from the queried node, so the name must never be used -/// as a filesystem path verbatim (`../` and absolute names would overwrite -/// arbitrary local files — issue #1614). The write path is derived from the -/// name's final path component only (`Path::file_name` ruling), optionally -/// under `dir`. A name with no final component (`..`, `/`, a trailing -/// separator, empty) is refused and nothing is written. Ordinary -/// single-segment names produce byte-identical paths to the previous -/// verbatim behaviour. -fn download_output_path(dir: Option<&str>, name: &str) -> Result { - if name.is_empty() || name.ends_with('/') { - bail!( - "refusing download of match with unsafe name {:?}: no final path component", - name - ); - } - let Some(file_name) = std::path::Path::new(name) - .file_name() - .and_then(|c| c.to_str()) - else { - bail!( - "refusing download of match with unsafe name {:?}: no final path component", - name - ); - }; - Ok(match dir { - Some(dir) => format!("{}/{}", dir, file_name), - None => file_name.to_owned(), - }) -} - /// Plan all bulk-download destinations before creating directories or writing files. /// /// Match names are deduplicated the same way as the output loops. Distinct matches diff --git a/pkgs/id/src/helpers.rs b/pkgs/id/src/helpers.rs index ba38e0d1ec..41f9a99134 100644 --- a/pkgs/id/src/helpers.rs +++ b/pkgs/id/src/helpers.rs @@ -34,6 +34,7 @@ use crate::commands::text::{plain_field, tsv_row}; use crate::protocol::{FindMatch, MatchKind, TaggedMatch}; +use anyhow::{Result, bail}; /// Parses a put specification into path and optional name. /// @@ -292,6 +293,43 @@ fn format_match_repl(query: &str, m: &FindMatch, format: &str) -> String { /// backwards compatibility. pub use crate::match_kind; +/// Build the local write path for a downloaded find/search match. +/// +/// A match name is untrusted input: in remote mode both the name and the +/// blob content come from the queried node, so the name must never be used +/// as a filesystem path verbatim (`../` and absolute names would overwrite +/// arbitrary local files — issues #1614, #2307). The write path is derived +/// from the name's final path component only (`Path::file_name` ruling), +/// optionally under `dir`. A name with no final component (`..`, `/`, a +/// trailing separator, empty) is refused and nothing is written. Ordinary +/// single-segment names produce byte-identical paths to the previous +/// verbatim behaviour. +/// +/// This is the single shared implementation used by both the CLI +/// (`commands/find.rs`) and the REPL (`repl/runner.rs`); do not copy this +/// rule elsewhere. +pub fn download_output_path(dir: Option<&str>, name: &str) -> Result { + if name.is_empty() || name.ends_with('/') { + bail!( + "refusing download of match with unsafe name {:?}: no final path component", + name + ); + } + let Some(file_name) = std::path::Path::new(name) + .file_name() + .and_then(|c| c.to_str()) + else { + bail!( + "refusing download of match with unsafe name {:?}: no final path component", + name + ); + }; + Ok(match dir { + Some(dir) => format!("{}/{}", dir, file_name), + None => file_name.to_owned(), + }) +} + /// Parse a duration such as `45s`, `90m`, `12h` or `3d` into seconds. /// /// # Errors diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 295e62c0e0..89266c7fa9 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -286,7 +286,8 @@ pub use discovery::{ STALE_CHECK_INTERVAL, STALE_THRESHOLD, defaults, parse_defaults, resolve_config, }; pub use helpers::{ - parse_get_spec, parse_put_spec, print_match_cli, print_match_repl, print_matches_cli, + download_output_path, parse_get_spec, parse_put_spec, print_match_cli, print_match_repl, + print_matches_cli, }; pub use protocol::{FindMatch, MatchKind, MetaProtocol, MetaRequest, MetaResponse, TaggedMatch}; pub use repl::run_repl; diff --git a/pkgs/id/src/repl/runner.rs b/pkgs/id/src/repl/runner.rs index 9b19257d22..bac8f4aa94 100644 --- a/pkgs/id/src/repl/runner.rs +++ b/pkgs/id/src/repl/runner.rs @@ -41,7 +41,8 @@ use std::io::Write; use super::{ReplInput, continue_heredoc, preprocess_repl_line}; use crate::{ - FindMatch, MatchKind, PeekOptions, ReplContext, SearchOptions, is_node_id, print_match_repl, + FindMatch, MatchKind, PeekOptions, ReplContext, SearchOptions, download_output_path, is_node_id, + print_match_repl, }; /// Run the interactive REPL. @@ -840,11 +841,16 @@ async fn handle_find_command( if filtered_matches.len() == 1 { let (_, m) = &filtered_matches[0]; let output = if args.to_file { - args.output_file.unwrap_or(&m.name) + match args.output_file { + // Explicit user path stays the user's choice. + Some(path) => path.to_owned(), + // Match-derived default: confine via the shared CLI ruling. + None => download_output_path(None, &m.name)?, + } } else { - "-" + "-".to_owned() }; - return ctx.get(&m.name, Some(output)).await; + return ctx.get(&m.name, Some(&output)).await; } // Multiple matches - interactive selection @@ -910,8 +916,13 @@ async fn handle_search_command(ctx: &mut ReplContext, rest: &[&str]) -> Result<( // If --file or >filename, also output first match to file if args.to_file { let (_, m) = &filtered_matches[0]; - let output = args.output_file.unwrap_or(&m.name); - ctx.get(&m.name, Some(output)).await + let output = match args.output_file { + // Explicit user path stays the user's choice. + Some(path) => path.to_owned(), + // Match-derived default: confine via the shared CLI ruling. + None => download_output_path(None, &m.name)?, + }; + ctx.get(&m.name, Some(&output)).await } else { Ok(()) } @@ -1102,20 +1113,44 @@ async fn output_all_matches_filtered( format: &str, ) -> Result<()> { if let Some(dir_path) = dir { - if let Err(e) = std::fs::create_dir_all(dir_path) { - println!("error creating directory: {e}"); - return Ok(()); - } + // Preflight every destination through the shared final-component + // ruling before creating the directory or writing anything, so a + // single unsafe name or basename collision writes nothing (mirrors + // the CLI `plan_download_paths` batch refusal, #2178). let mut seen = std::collections::HashSet::new(); - for (query, m) in filtered_matches { + let mut destinations = std::collections::HashMap::new(); + let mut plan: Vec<(&(String, FindMatch), String)> = Vec::new(); + for entry @ (_, m) in filtered_matches { let key = format!("{}:{}", m.hash, m.name); - if seen.insert(key) { - let output_path = format!("{}/{}", dir_path, m.name); - if let Err(e) = ctx.get(&m.name, Some(&output_path)).await { + if !seen.insert(key) { + continue; + } + let output_path = match download_output_path(Some(dir_path), &m.name) { + Ok(path) => path, + Err(e) => { println!("error: {e}"); - } else { - print_match_repl(query, m, format); + return Ok(()); } + }; + if let Some(previous) = destinations.insert(output_path.clone(), m.name.as_str()) + { + println!( + "refusing bulk download: destination collision between matches {:?} and {:?} at {:?}", + previous, m.name, output_path + ); + return Ok(()); + } + plan.push((entry, output_path)); + } + if let Err(e) = std::fs::create_dir_all(dir_path) { + println!("error creating directory: {e}"); + return Ok(()); + } + for ((query, m), output_path) in plan { + if let Err(e) = ctx.get(&m.name, Some(&output_path)).await { + println!("error: {e}"); + } else { + print_match_repl(query, m, format); } } } else { @@ -1174,9 +1209,30 @@ async fn output_selected_matches_to_dir( filtered_matches: &[(String, FindMatch)], dir_path: &str, ) { + // Preflight the selected destinations through the shared final-component + // ruling before writing anything, so one unsafe name or basename + // collision writes nothing (batch refusal, consistent with #2178). + let mut destinations = std::collections::HashMap::new(); + let mut plan: Vec<(&FindMatch, String)> = Vec::new(); for n in selections { let (_, m) = &filtered_matches[n - 1]; - let output_path = format!("{}/{}", dir_path, m.name); + let output_path = match download_output_path(Some(dir_path), &m.name) { + Ok(path) => path, + Err(e) => { + println!("error: {e}"); + return; + } + }; + if let Some(previous) = destinations.insert(output_path.clone(), m.name.as_str()) { + println!( + "refusing bulk download: destination collision between matches {:?} and {:?} at {:?}", + previous, m.name, output_path + ); + return; + } + plan.push((m, output_path)); + } + for (m, output_path) in plan { if let Err(e) = ctx.get_match(&m.name, Some(&output_path)).await { println!("error: {e}"); } @@ -1260,11 +1316,48 @@ async fn select_and_output_matches_filtered( } output_selected_matches_to_dir(ctx, &selections, filtered_matches, dir_path).await; } else if to_file { - for n in &selections { - let (_, m) = &filtered_matches[n - 1]; - let output = output_file.unwrap_or(&m.name); - if let Err(e) = ctx.get(&m.name, Some(output)).await { - println!("error: {e}"); + // Preflight match-derived defaults through the shared ruling so + // colliding basenames are refused before any write; an explicit + // user path stays the user's choice. + if output_file.is_some() { + for n in &selections { + let (_, m) = &filtered_matches[n - 1]; + let output = output_file.unwrap_or(&m.name); + if let Err(e) = ctx.get(&m.name, Some(output)).await { + println!("error: {e}"); + } + } + } else { + let mut destinations = std::collections::HashSet::new(); + let mut plan: Vec<(&FindMatch, String)> = Vec::new(); + let mut refused = false; + for n in &selections { + let (_, m) = &filtered_matches[n - 1]; + match download_output_path(None, &m.name) { + Ok(output) => { + if !destinations.insert(output.clone()) { + println!( + "refusing bulk download: destination collision at {:?}", + output + ); + refused = true; + break; + } + plan.push((m, output)); + } + Err(e) => { + println!("error: {e}"); + refused = true; + break; + } + } + } + if !refused { + for (m, output) in plan { + if let Err(e) = ctx.get(&m.name, Some(&output)).await { + println!("error: {e}"); + } + } } } } else { @@ -1660,6 +1753,63 @@ mod tests { ); } + #[tokio::test] + async fn test_interactive_dir_confines_traversal_to_final_component() { + // #2307: match-derived directory destinations must never escape the + // requested directory; the shared final-component ruling applies. + let cases = [ + ("../victim.txt", "downloads/victim.txt"), + ("../../x", "downloads/x"), + ("a/../../y", "downloads/y"), + ("/tmp/x", "downloads/x"), + ("/absolute.txt", "downloads/absolute.txt"), + ("plain.txt", "downloads/plain.txt"), + ("my file.txt", "downloads/my file.txt"), + ("ünïcode_ß.txt", "downloads/ünïcode_ß.txt"), + ]; + for (name, expected) in cases { + let matches = vec![test_find_match(name)]; + let mut rec = RecordingGetter::default(); + output_selected_matches_to_dir(&mut rec, &[1], &matches, "downloads").await; + assert_eq!( + rec.calls, + vec![(name.to_owned(), Some(expected.to_owned()))], + "name {name:?} must be confined to its final component" + ); + } + } + + #[tokio::test] + async fn test_interactive_dir_refuses_names_without_final_component() { + // Names with no final component are refused and nothing is written. + for name in ["", "..", "/", "trailing/"] { + let matches = vec![test_find_match(name)]; + let mut rec = RecordingGetter::default(); + output_selected_matches_to_dir(&mut rec, &[1], &matches, "downloads").await; + assert!( + rec.calls.is_empty(), + "name {name:?} must refuse without writing" + ); + } + } + + #[tokio::test] + async fn test_interactive_dir_refuses_basename_collisions_without_partial_writes() { + // Distinct matches reducing to the same final component are refused + // as a batch before any write (consistent with #2178 CLI batching). + let matches = vec![ + test_find_match("a/same.txt"), + test_find_match("b/same.txt"), + ]; + let mut rec = RecordingGetter::default(); + output_selected_matches_to_dir(&mut rec, &[1, 2], &matches, "downloads").await; + assert!( + rec.calls.is_empty(), + "colliding basenames must write nothing, got {:?}", + rec.calls + ); + } + #[test] fn test_substitute_heredoc_content_midline() { // Supported form: the placeholder sits before the name, and From b61edc38655553a40b9083b9381b2053c15e7572 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 11:11:31 -0600 Subject: [PATCH 2/2] fix(id): keep derived dash filenames off the stdout sentinel; dedupe identical interactive selections (#2307, Codex PR #4472) --- pkgs/id/src/commands/find.rs | 13 +++++++++++++ pkgs/id/src/helpers.rs | 5 +++++ pkgs/id/src/repl/runner.rs | 28 ++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/pkgs/id/src/commands/find.rs b/pkgs/id/src/commands/find.rs index baf99e957f..b2dcaa24ce 100644 --- a/pkgs/id/src/commands/find.rs +++ b/pkgs/id/src/commands/find.rs @@ -1050,6 +1050,19 @@ mod tests { assert_eq!(download_output_path(None, "/tmp/x").unwrap(), "x"); } + #[test] + #[test] + fn test_download_output_path_dash_name_is_not_the_stdout_sentinel() { + // A match-derived "-" must name a file, not the stdout sentinel; + // only an explicit user-supplied "-" means stdout. + assert_eq!(download_output_path(None, "-").unwrap(), "./-"); + assert_eq!(download_output_path(None, "nested/-").unwrap(), "./-"); + assert_eq!( + download_output_path(Some("out"), "nested/-").unwrap(), + "out/-" + ); + } + #[test] fn test_download_output_path_refuses_names_without_final_component() { for name in ["..", "/", "", "foo/", "../", "."] { diff --git a/pkgs/id/src/helpers.rs b/pkgs/id/src/helpers.rs index 41f9a99134..36d978d6bb 100644 --- a/pkgs/id/src/helpers.rs +++ b/pkgs/id/src/helpers.rs @@ -326,6 +326,11 @@ pub fn download_output_path(dir: Option<&str>, name: &str) -> Result { }; Ok(match dir { Some(dir) => format!("{}/{}", dir, file_name), + // A derived bare "-" would collide with the stdout sentinel in + // export_blob ("-" means stdout there); write the file as "./-" + // instead. An explicit user-supplied "-" is untouched and still + // means stdout (Codex review on PR #4472). + None if file_name == "-" => "./-".to_owned(), None => file_name.to_owned(), }) } diff --git a/pkgs/id/src/repl/runner.rs b/pkgs/id/src/repl/runner.rs index bac8f4aa94..9670f32172 100644 --- a/pkgs/id/src/repl/runner.rs +++ b/pkgs/id/src/repl/runner.rs @@ -1213,9 +1213,15 @@ async fn output_selected_matches_to_dir( // ruling before writing anything, so one unsafe name or basename // collision writes nothing (batch refusal, consistent with #2178). let mut destinations = std::collections::HashMap::new(); + let mut seen = std::collections::HashSet::new(); let mut plan: Vec<(&FindMatch, String)> = Vec::new(); for n in selections { let (_, m) = &filtered_matches[n - 1]; + // Identical matches listed twice (overlapping queries) are one + // download, not a collision (Codex review on PR #4472). + if !seen.insert(format!("{}:{}", m.hash, m.name)) { + continue; + } let output_path = match download_output_path(Some(dir_path), &m.name) { Ok(path) => path, Err(e) => { @@ -1329,10 +1335,16 @@ async fn select_and_output_matches_filtered( } } else { let mut destinations = std::collections::HashSet::new(); + let mut seen = std::collections::HashSet::new(); let mut plan: Vec<(&FindMatch, String)> = Vec::new(); let mut refused = false; for n in &selections { let (_, m) = &filtered_matches[n - 1]; + // Identical matches listed twice are one download, + // not a collision (Codex review on PR #4472). + if !seen.insert(format!("{}:{}", m.hash, m.name)) { + continue; + } match download_output_path(None, &m.name) { Ok(output) => { if !destinations.insert(output.clone()) { @@ -1810,6 +1822,22 @@ mod tests { ); } + #[tokio::test] + async fn test_interactive_dir_duplicate_identical_selections_fetch_once() { + // Overlapping queries can list the same (hash, name) match twice; + // selecting both entries is one download, not a basename collision. + let matches = vec![test_find_match("report.txt"), test_find_match("report.txt")]; + let mut rec = RecordingGetter::default(); + output_selected_matches_to_dir(&mut rec, &[1, 2], &matches, "downloads").await; + assert_eq!( + rec.calls, + vec![( + "report.txt".to_owned(), + Some("downloads/report.txt".to_owned()) + )] + ); + } + #[test] fn test_substitute_heredoc_content_midline() { // Supported form: the placeholder sits before the name, and