From 25c509504ca14926f3918bdcc78e8e6ca83282b7 Mon Sep 17 00:00:00 2001 From: repo-worker-code Date: Tue, 3 Nov 2026 10:55:36 -0600 Subject: [PATCH] fix(id): refuse padded and empty-component names at FileOps (#4102) FileOps stored put names verbatim while validate_target trimmed rename/copy targets, so a padded put created a name that rename/copy could never address. Make the name rule canonical at the one entry point (design #4766 Phase 3): - validate_name now refuses leading/trailing padding and empty path components (a//b, a/, a\) with InvalidName, alongside the existing rooted, drive-prefix and . / .. refusals. - validate_target no longer trims; put, rename and copy now share the same verbatim rule. - Forgiving user-facing surfaces trim before calling in: CLI put, the REPL put/rename/copy (and @NODE put), and the web rename/copy routes keep their existing trim and now map InvalidName to 400. Tests pin padding and empty-component refusals for put, rename and copy, and prove no untargetable twin is created. Refs #4102, #4766 --- pkgs/id/src/commands/put.rs | 18 ++++ pkgs/id/src/commands/repl.rs | 22 ++++ pkgs/id/src/fileops.rs | 189 ++++++++++++++++++++++++++++++++++- pkgs/id/src/web/routes.rs | 10 ++ 4 files changed, 236 insertions(+), 3 deletions(-) diff --git a/pkgs/id/src/commands/put.rs b/pkgs/id/src/commands/put.rs index 09c1208e30..e29ee6617c 100644 --- a/pkgs/id/src/commands/put.rs +++ b/pkgs/id/src/commands/put.rs @@ -154,9 +154,19 @@ pub async fn push_and_name( } } +/// Trim a name typed at the forgiving CLI surface before FileOps sees it. +/// +/// FileOps stores names verbatim and refuses padding (#4102 / design #4766 +/// Phase 3), so a stray leading or trailing space is treated as a typing slip +/// here rather than failing the command. +fn trim_surface_name(name: &str) -> &str { + name.trim() +} + /// Store `data` under `name`: on the local server if one is running, otherwise /// directly in the local stores (with the same metadata a server would record). async fn put_named(name: &str, data: Vec) -> Result<()> { + let name = trim_surface_name(name); if let Some(serve_info) = get_serve_info().await { let store = open_store(true).await?; let store_handle = store.as_store(); @@ -477,6 +487,14 @@ mod tests { assert!(!is_node_id("not_a_node_id")); } + #[test] + fn cli_put_name_is_trimmed_before_fileops() { + for input in [" report.txt", "report.txt ", "\treport.txt\n"] { + assert_eq!(trim_surface_name(input), "report.txt"); + } + assert_eq!(trim_surface_name("my report.txt"), "my report.txt"); + } + #[test] fn test_parse_put_spec_integration() { // Simple path diff --git a/pkgs/id/src/commands/repl.rs b/pkgs/id/src/commands/repl.rs index 509a86186a..ed96ef314d 100644 --- a/pkgs/id/src/commands/repl.rs +++ b/pkgs/id/src/commands/repl.rs @@ -101,6 +101,11 @@ use crate::{ is_node_id, load_or_create_keypair, open_store, }; +/// Trim names entered at the forgiving REPL surface before calling FileOps. +fn trim_file_name(name: &str) -> &str { + name.trim() +} + /// The current Unix time in seconds, or `0` if the clock is before the epoch. fn now_secs() -> u64 { std::time::SystemTime::now() @@ -534,6 +539,10 @@ impl ReplContext { (data, filename) }; + // Forgiving REPL surface: trim what the user typed. FileOps stores + // names verbatim and refuses padding (#4102 / design #4766 Phase 3). + let filename = trim_file_name(&filename).to_owned(); + let store_handle = self.store_handle(); let (hash, _guard) = add_raw(&store_handle, data).await?; @@ -671,6 +680,7 @@ impl ReplContext { /// /// Returns an error if `from` is not found. pub async fn rename(&mut self, from: &str, to: &str) -> Result<()> { + let to = trim_file_name(to); let req = MetaRequest::Rename { from: from.to_owned(), to: to.to_owned(), @@ -697,6 +707,7 @@ impl ReplContext { /// /// Returns an error if `from` is not found. pub async fn copy(&mut self, from: &str, to: &str) -> Result<()> { + let to = trim_file_name(to); let req = MetaRequest::Copy { from: from.to_owned(), to: to.to_owned(), @@ -931,6 +942,9 @@ impl ReplContext { (data, filename) }; + // The remote REPL path is still a forgiving user-facing surface. + let filename = trim_file_name(&filename).to_owned(); + let store_handle = self.store_handle(); let (hash, _guard) = add_raw(&store_handle, data).await?; // Bytes first, name second (see `put`). @@ -1186,6 +1200,14 @@ mod tests { use super::*; use iroh_base::SecretKey; + #[test] + fn user_entered_file_targets_are_trimmed_before_fileops() { + for input in [" report.txt", "report.txt ", "\treport.txt\n"] { + assert_eq!(trim_file_name(input), "report.txt"); + } + assert_eq!(trim_file_name("my report.txt"), "my report.txt"); + } + fn announcement(name: Option<&str>) -> PeerAnnouncement { PeerAnnouncement { node_id: SecretKey::from_bytes(&[9u8; 32]).public(), diff --git a/pkgs/id/src/fileops.rs b/pkgs/id/src/fileops.rs index 7aa2b0092d..c534b2e41d 100644 --- a/pkgs/id/src/fileops.rs +++ b/pkgs/id/src/fileops.rs @@ -218,6 +218,14 @@ impl<'a> FileOps<'a> { } } + /// The single canonical-name rule for every FileOps entry point. + /// + /// A name is stored exactly as given, so any name that cannot be + /// re-specified identically is refused rather than stored under a + /// look-alike: leading or trailing padding, empty components + /// (`a//b`, `a/`, `a\`), rooted names, drive prefixes, and `.`/`..` + /// components all fail with [`FileOpError::InvalidName`]. Forgiving + /// surfaces (CLI, REPL, web) trim user input before calling in. fn validate_name(name: &str) -> Result<(), FileOpError> { if name.trim().is_empty() { return Err(FileOpError::EmptyName); @@ -225,20 +233,23 @@ impl<'a> FileOps<'a> { let bytes = name.as_bytes(); let has_windows_drive_prefix = bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'; - if name.starts_with('/') + if name != name.trim() + || name.starts_with('/') || name.starts_with('\\') || has_windows_drive_prefix || name .split(['/', '\\']) - .any(|component| matches!(component, "." | "..")) + .any(|component| component.is_empty() || matches!(component, "." | "..")) { return Err(FileOpError::InvalidName(name.to_owned())); } Ok(()) } + /// Validate a rename/copy target without normalising it: the target is + /// stored verbatim, so trimming here would create the padded-value twins + /// the canonical-name rule exists to prevent. fn validate_target(from: &str, to: &str) -> Result { - let to = to.trim(); Self::validate_name(to)?; if from == to { return Err(FileOpError::SameName); @@ -1068,3 +1079,175 @@ mod delete_tests { node.shutdown().await.unwrap(); } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod name_rule_tests { + use crate::local::LocalNode; + + use super::*; + + async fn put(node: &LocalNode, name: &str, data: &[u8]) { + let guard = node + .blobs() + .add_bytes(data.to_vec()) + .temp_tag() + .await + .unwrap(); + node.ops().put(name, guard.hash()).await.unwrap(); + } + + fn assert_invalid(name: &str) { + assert!( + matches!( + FileOps::validate_name(name), + Err(FileOpError::InvalidName(_)) + ), + "{name:?} must be refused as InvalidName" + ); + } + + /// Padding and empty components are refused by the one canonical rule + /// (#4102 / design #4766 Phase 3), so a name can never be stored in a + /// form that rename/copy would normalise away. + #[test] + fn refuses_padding_and_empty_components() { + for name in [ + " report.txt", + "report.txt ", + "\treport.txt", + "report.txt\n", + "a//b", + "a/", + "a\\", + "a//b/c", + "a/b/", + ] { + assert_invalid(name); + } + } + + /// The pre-existing refusals stay in place: rooted names, drive + /// prefixes, and `.`/`..` traversal components. + #[test] + fn preserves_traversal_refusals() { + for name in [ + "/etc/passwd", + "\\windows", + "C:file.txt", + ".", + "..", + "a/./b", + "a/../b", + ] { + assert_invalid(name); + } + assert!(matches!( + FileOps::validate_name(" "), + Err(FileOpError::EmptyName) + )); + // Padding is a refusal, but interior spaces in a name are not. + assert!(FileOps::validate_name("my report.txt").is_ok()); + assert!(FileOps::validate_name("a/b").is_ok()); + } + + /// A padded `put` cannot create an untargetable twin, and a padded + /// rename/copy target is refused instead of being silently trimmed. + #[tokio::test] + async fn padded_names_cannot_create_twins() { + let node = LocalNode::open(true).await.unwrap(); + put(&node, "report.txt", b"report").await; + + let guard = node + .blobs() + .add_bytes(b"report".to_vec()) + .temp_tag() + .await + .unwrap(); + assert!(matches!( + node.ops().put(" report.txt", guard.hash()).await, + Err(FileOpError::InvalidName(_)) + )); + assert!( + node.blobs() + .tags() + .get(" report.txt") + .await + .unwrap() + .is_none() + ); + assert!( + node.blobs() + .tags() + .get("report.txt") + .await + .unwrap() + .is_some() + ); + + assert!(matches!( + node.ops().rename("report.txt", "other.txt ", false).await, + Err(FileOpError::InvalidName(_)) + )); + assert!( + node.blobs() + .tags() + .get("other.txt") + .await + .unwrap() + .is_none() + ); + + assert!(matches!( + node.ops().copy("report.txt", " copy.txt").await, + Err(FileOpError::InvalidName(_)) + )); + assert!( + node.blobs() + .tags() + .get(" copy.txt") + .await + .unwrap() + .is_none() + ); + assert!(node.blobs().tags().get("copy.txt").await.unwrap().is_none()); + + node.shutdown().await.unwrap(); + } + + /// Empty components are refused at put and at rename/copy targets alike. + #[tokio::test] + async fn empty_components_refused_across_put_rename_copy() { + let node = LocalNode::open(true).await.unwrap(); + put(&node, "a/b", b"body").await; + + let guard = node + .blobs() + .add_bytes(b"body".to_vec()) + .temp_tag() + .await + .unwrap(); + for name in ["a//b", "a/", "a\\"] { + assert!(matches!( + node.ops().put(name, guard.hash()).await, + Err(FileOpError::InvalidName(_)) + )); + assert!(matches!( + node.ops().rename("a/b", name, false).await, + Err(FileOpError::InvalidName(_)) + )); + assert!(matches!( + node.ops().copy("a/b", name).await, + Err(FileOpError::InvalidName(_)) + )); + assert!(node.blobs().tags().get(name).await.unwrap().is_none()); + } + + // The canonical source is untouched and ordinary names still work. + assert!(node.blobs().tags().get("a/b").await.unwrap().is_some()); + node.ops().copy("a/b", "a/c").await.unwrap(); + assert!(node.blobs().tags().get("a/c").await.unwrap().is_some()); + + node.shutdown().await.unwrap(); + } +} diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index 9ddf46a3f0..d478bb4cef 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -1898,6 +1898,11 @@ async fn rename_handler(State(state): State, Json(req): Json (StatusCode::NOT_FOUND, "File not found").into_response(), + Err(FileOpError::InvalidName(_)) => ( + StatusCode::BAD_REQUEST, + "New name must be a safe relative path without padding", + ) + .into_response(), Err(err) => { tracing::error!("[routes] rename failed: {err}"); (StatusCode::INTERNAL_SERVER_ERROR, "Failed to rename file").into_response() @@ -1942,6 +1947,11 @@ async fn copy_handler(State(state): State, Json(req): Json { (StatusCode::NOT_FOUND, "Source file not found").into_response() } + Err(FileOpError::InvalidName(_)) => ( + StatusCode::BAD_REQUEST, + "New name must be a safe relative path without padding", + ) + .into_response(), Err(err) => { tracing::error!("[routes] copy failed: {err}"); (StatusCode::INTERNAL_SERVER_ERROR, "Failed to copy file").into_response()