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
18 changes: 18 additions & 0 deletions pkgs/id/src/commands/put.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>) -> 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();
Expand Down Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions pkgs/id/src/commands/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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?;

Expand Down Expand Up @@ -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(),
Expand All @@ -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(),
Expand Down Expand Up @@ -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`).
Expand Down Expand Up @@ -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(),
Expand Down
189 changes: 186 additions & 3 deletions pkgs/id/src/fileops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,27 +218,38 @@ 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);
}
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<String, FileOpError> {
let to = to.trim();
Self::validate_name(to)?;
if from == to {
return Err(FileOpError::SameName);
Expand Down Expand Up @@ -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();
}
}
10 changes: 10 additions & 0 deletions pkgs/id/src/web/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1898,6 +1898,11 @@ async fn rename_handler(State(state): State<AppState>, Json(req): Json<RenameReq
)
.into_response(),
Err(FileOpError::NotFound(_)) => (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()
Expand Down Expand Up @@ -1942,6 +1947,11 @@ async fn copy_handler(State(state): State<AppState>, Json(req): Json<CopyRequest
Err(FileOpError::NotFound(_)) => {
(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()
Expand Down
Loading