diff --git a/pkgs/id/src/commands/list.rs b/pkgs/id/src/commands/list.rs index 03399695be..1e7ad94b7d 100644 --- a/pkgs/id/src/commands/list.rs +++ b/pkgs/id/src/commands/list.rs @@ -30,6 +30,7 @@ use iroh_base::EndpointId; use crate::commands::client::create_local_client_endpoint; use crate::commands::serve::get_serve_info; +use crate::commands::text::tsv_row; use crate::protocol::{MetaRequest, MetaResponse}; use crate::store::{load_or_create_keypair, open_store}; use crate::{CLIENT_KEY_FILE, META_ALPN, is_node_id}; @@ -88,7 +89,7 @@ pub async fn cmd_list(node: Option, no_relay: bool) -> Result<()> { println!("(no files stored)"); } else { for (hash, name) in items { - println!("{hash}\t{name}"); + println!("{}", tsv_row(hash, &name)); } } Ok(()) @@ -107,7 +108,7 @@ pub async fn cmd_list(node: Option, no_relay: bool) -> Result<()> { while let Some(item) = list.next().await { let item = item?; let name = String::from_utf8_lossy(item.name.as_ref()); - println!("{}\t{}", item.hash, name); + println!("{}", tsv_row(item.hash, &name)); count += 1; } if count == 0 { @@ -154,7 +155,7 @@ pub async fn cmd_list_remote(server_node_id: EndpointId, no_relay: bool) -> Resu println!("(no files stored)"); } else { for (hash, name) in items { - println!("{hash}\t{name}"); + println!("{}", tsv_row(hash, &name)); } } Ok(()) diff --git a/pkgs/id/src/commands/repl.rs b/pkgs/id/src/commands/repl.rs index a4f7fa801f..8b22043d9f 100644 --- a/pkgs/id/src/commands/repl.rs +++ b/pkgs/id/src/commands/repl.rs @@ -92,7 +92,7 @@ use crate::commands::client::create_local_client_endpoint; use crate::commands::put::{add_raw, push_and_name}; use crate::commands::serve::get_serve_info; use crate::commands::tag::{self as tag, TagDisplayOptions}; -use crate::commands::text::plain_field; +use crate::commands::text::{plain_field, tsv_row}; use crate::discovery::PeerAnnouncement; use crate::local::LocalNode; use crate::meta_client::{MetaRequester, expect_ok, read_capped_response, request_over}; @@ -465,7 +465,7 @@ impl ReplContext { println!("(no files stored)"); } else { for (hash, name) in items { - println!("{hash}\t{name}"); + println!("{}", tsv_row(hash, &name)); } } } @@ -478,7 +478,7 @@ impl ReplContext { while let Some(item) = list.next().await { let item = item?; let name = String::from_utf8_lossy(item.name.as_ref()); - println!("{}\t{}", item.hash, name); + println!("{}", tsv_row(item.hash, &name)); count += 1; } if count == 0 { @@ -874,7 +874,7 @@ impl ReplContext { println!("(no files stored on @{})", &node_str[..8]); } else { for (hash, name) in items { - println!("{hash}\t{name}"); + println!("{}", tsv_row(hash, &name)); } } } diff --git a/pkgs/id/src/commands/text.rs b/pkgs/id/src/commands/text.rs index 68b1fc5f4f..8bb243b37c 100644 --- a/pkgs/id/src/commands/text.rs +++ b/pkgs/id/src/commands/text.rs @@ -33,6 +33,8 @@ //! original bytes can parse it as JSON. Values with no structure-breaking //! character are the common case and stay unwrapped, exactly as before. +use std::fmt::Display; + /// Returns `true` for characters that could break a tab-separated row. /// /// Control characters cover `LF`, `CR`, `TAB`, NUL and every other C0/C1 @@ -87,6 +89,11 @@ pub fn plain_field(value: &str) -> String { rendered } +/// Formats one tab-separated row whose name field may contain untrusted text. +pub fn tsv_row(hash: impl Display, name: &str) -> String { + format!("{hash}\t{}", plain_field(name)) +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { @@ -150,4 +157,18 @@ mod tests { assert_eq!(rendered.matches('\t').count(), 0); assert!(!rendered.contains('\n')); } + + #[test] + fn tsv_row_keeps_control_characters_inside_the_name_field() { + let row = tsv_row("hash", "x\nforged\tcolumn"); + assert_eq!(row, format!("hash\t{}", r#""x\nforged\tcolumn""#)); + assert_eq!( + row.matches('\t').count(), + 1, + "only the real delimiter remains" + ); + assert!(!row.contains('\n'), "the name cannot add a physical row"); + + assert_eq!(tsv_row("hash", "ordinary name"), "hash\tordinary name"); + } } diff --git a/pkgs/id/src/helpers.rs b/pkgs/id/src/helpers.rs index 808b7447d8..ba38e0d1ec 100644 --- a/pkgs/id/src/helpers.rs +++ b/pkgs/id/src/helpers.rs @@ -32,6 +32,7 @@ //! - **group**: Matches grouped under their query headers //! - **union**: Deduplicated matches by hash +use crate::commands::text::{plain_field, tsv_row}; use crate::protocol::{FindMatch, MatchKind, TaggedMatch}; /// Parses a put specification into path and optional name. @@ -153,18 +154,24 @@ pub fn parse_get_spec(spec: &str) -> (&str, Option<&str>) { /// abc123... config.json /// ``` pub fn print_match_cli(m: &TaggedMatch, format: &str) { + println!("{}", format_match_cli(m, format)); +} + +fn format_match_cli(m: &TaggedMatch, format: &str) -> String { match format { - "group" => { - println!("[{}]", m.query); - println!(" {}\t{}", m.hash, m.name); - } - "union" => { - println!("{}\t{}", m.hash, m.name); - } - _ => { - // "tag" format (default) - println!("{}\t{}\t({})", m.hash, m.name, m.query); - } + "group" => format!( + "[{}]\n {}", + plain_field(&m.query), + tsv_row(&m.hash, &m.name) + ), + "union" => tsv_row(&m.hash, &m.name), + // "tag" format (default) + _ => format!( + "{}\t{}\t({})", + m.hash, + plain_field(&m.name), + plain_field(&m.query) + ), } } @@ -190,6 +197,13 @@ pub fn print_match_cli(m: &TaggedMatch, format: &str) { /// print_matches_cli(&matches, "group"); /// ``` pub fn print_matches_cli(matches: &[TaggedMatch], format: &str) { + for line in format_matches_cli(matches, format) { + println!("{line}"); + } +} + +fn format_matches_cli(matches: &[TaggedMatch], format: &str) -> Vec { + let mut lines = Vec::new(); match format { "group" => { // Group by query @@ -197,12 +211,12 @@ pub fn print_matches_cli(matches: &[TaggedMatch], format: &str) { for m in matches { if current_query != Some(&m.query) { if current_query.is_some() { - println!(); // Blank line between groups + lines.push(String::new()); // Blank line between groups } - println!("[{}]", m.query); + lines.push(format!("[{}]", plain_field(&m.query))); current_query = Some(&m.query); } - println!(" {}\t{}", m.hash, m.name); + lines.push(format!(" {}", tsv_row(&m.hash, &m.name))); } } "union" => { @@ -210,17 +224,23 @@ pub fn print_matches_cli(matches: &[TaggedMatch], format: &str) { let mut seen = std::collections::HashSet::new(); for m in matches { if seen.insert(m.hash) { - println!("{}\t{}", m.hash, m.name); + lines.push(tsv_row(&m.hash, &m.name)); } } } _ => { // "tag" format (default) for m in matches { - println!("{}\t{}\t({})", m.hash, m.name, m.query); + lines.push(format!( + "{}\t{}\t({})", + m.hash, + plain_field(&m.name), + plain_field(&m.query) + )); } } } + lines } /// Prints a single match in REPL format with match kind details. @@ -244,18 +264,24 @@ pub fn print_matches_cli(matches: &[TaggedMatch], format: &str) { /// abc123... config.json /// ``` pub fn print_match_repl(query: &str, m: &FindMatch, format: &str) { + println!("{}", format_match_repl(query, m, format)); +} + +fn format_match_repl(query: &str, m: &FindMatch, format: &str) -> String { let kind_str = match m.kind { MatchKind::Exact => "exact", MatchKind::Prefix => "prefix", MatchKind::Contains => "contains", }; match format { - "group" | "union" => { - println!(" {}\t{}", m.hash, m.name); - } - _ => { - println!(" {}\t{}\t[{}, {}]", m.hash, m.name, kind_str, query); - } + "group" | "union" => format!(" {}", tsv_row(&m.hash, &m.name)), + _ => format!( + " {}\t{}\t[{}, {}]", + m.hash, + plain_field(&m.name), + kind_str, + plain_field(query) + ), } } @@ -441,4 +467,60 @@ mod tests { print_match_repl("query", &m, "group"); print_match_repl("query", &m, "union"); } + + #[test] + fn match_renderers_quote_control_characters_in_names_and_queries() { + let hash = Hash::from_bytes([0u8; 32]); + let name = format!("x\n{}\tforged", "0".repeat(64)); + let query = "find\nquery"; + let tagged = TaggedMatch { + query: query.to_owned(), + hash, + name: name.clone(), + kind: MatchKind::Exact, + is_hash_match: false, + }; + + let tag = format_match_cli(&tagged, "tag"); + assert_eq!(tag.matches('\t').count(), 2); + assert!(!tag.contains('\n')); + assert!(tag.contains(r#""x\n"#)); + assert!(tag.ends_with(r#"("find\nquery")"#)); + + let group = format_match_cli(&tagged, "group"); + let group_lines: Vec<_> = group.lines().collect(); + assert_eq!(group_lines.len(), 2); + assert!(group_lines[0].contains(r#""find\nquery""#)); + assert_eq!(group_lines[1].matches('\t').count(), 1); + assert!(group_lines[1].contains(r#""x\n"#)); + + let matches = format_matches_cli(&[tagged], "group"); + assert_eq!(matches.len(), 2); + assert!(matches[0].contains(r#""find\nquery""#)); + assert_eq!(matches[1].matches('\t').count(), 1); + + let found = FindMatch { + hash, + name, + kind: MatchKind::Exact, + is_hash_match: false, + }; + let repl = format_match_repl(query, &found, "tag"); + assert_eq!(repl.matches('\t').count(), 2); + assert!(!repl.contains('\n')); + assert!(repl.contains(r#""x\n"#)); + assert!(repl.ends_with(r#"[exact, "find\nquery"]"#)); + + let plain = TaggedMatch { + query: "simple query".to_owned(), + hash, + name: "ordinary name".to_owned(), + kind: MatchKind::Exact, + is_hash_match: false, + }; + assert_eq!( + format_match_cli(&plain, "tag"), + format!("{hash}\tordinary name\t(simple query)") + ); + } } diff --git a/pkgs/id/tests/cli_integration.rs b/pkgs/id/tests/cli_integration.rs index 427833b436..e1d97660ff 100644 --- a/pkgs/id/tests/cli_integration.rs +++ b/pkgs/id/tests/cli_integration.rs @@ -552,6 +552,46 @@ mod list_tests { } } } + + #[test] + fn test_list_quotes_control_characters_in_names() { + let tmp = TempDir::new().unwrap(); + let test_file = tmp.path().join("test.list-control.txt"); + fs::write(&test_file, b"Control character list test").unwrap(); + + let name = "unsafe\nforged\tcolumn"; + let put_spec = format!("{}:{name}", test_file.display()); + // A second plain file takes cmd_put past its single-item + // stdin auto-detect (a lone `path:name` spec does not exist + // as a file, so it would be read as a stdin blob name and + // parse_put_spec would never run). + run_cmd_success( + &["put", &put_spec, test_file.to_str().unwrap()], + tmp.path(), + ); + + let output = run_cmd_success_stdout(&["list"], tmp.path()); + let rows: Vec<_> = output.lines().filter(|line| line.contains('\t')).collect(); + assert_eq!( + rows.len(), + 2, + "the stored name must not forge another row: {output:?}" + ); + let mut quoted_names = 0; + for row in &rows { + let fields: Vec<_> = row.split('\t').collect(); + assert_eq!( + fields.len(), + 2, + "the stored name must not forge a column: {output:?}" + ); + assert_eq!(fields[0].len(), 64); + if fields[1] == r#""unsafe\nforged\tcolumn""# { + quoted_names += 1; + } + } + assert_eq!(quoted_names, 1, "the unsafe name must appear quoted: {output:?}"); + } } mod find_search_tests {