Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions pkgs/id/src/commands/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -88,7 +89,7 @@ pub async fn cmd_list(node: Option<String>, no_relay: bool) -> Result<()> {
println!("(no files stored)");
} else {
for (hash, name) in items {
println!("{hash}\t{name}");
println!("{}", tsv_row(hash, &name));
}
}
Ok(())
Expand All @@ -107,7 +108,7 @@ pub async fn cmd_list(node: Option<String>, 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 {
Expand Down Expand Up @@ -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(())
Expand Down
8 changes: 4 additions & 4 deletions pkgs/id/src/commands/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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));
}
}
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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));
}
}
}
Expand Down
21 changes: 21 additions & 0 deletions pkgs/id/src/commands/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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");
}
}
126 changes: 104 additions & 22 deletions pkgs/id/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
),
}
}

Expand All @@ -190,37 +197,50 @@ 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<String> {
let mut lines = Vec::new();
match format {
"group" => {
// Group by query
let mut current_query: Option<&str> = None;
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" => {
// Deduplicated by hash
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.
Expand All @@ -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)
),
}
}

Expand Down Expand Up @@ -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)")
);
}
}
40 changes: 40 additions & 0 deletions pkgs/id/tests/cli_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down