This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/fix-unftp-sbe-path-normalization-and-errors in repository https://gitbox.apache.org/repos/asf/opendal.git
commit 57240570c292edb3f043dfb7a1ab424826496ad6 Author: Xuanwo <[email protected]> AuthorDate: Mon Nov 23 14:55:55 2026 +0100 fix(integrations/unftp-sbe): normalize parent paths and fix del, rename, and error mapping --- integrations/unftp-sbe/src/lib.rs | 214 +++++++++++++++-- integrations/unftp-sbe/tests/ftp_loopback.rs | 30 +++ integrations/unftp-sbe/tests/storage_backend.rs | 305 ++++++++++++++++++++++++ 3 files changed, 530 insertions(+), 19 deletions(-) diff --git a/integrations/unftp-sbe/src/lib.rs b/integrations/unftp-sbe/src/lib.rs index 1ad07a6c7f..287eb4b9c0 100644 --- a/integrations/unftp-sbe/src/lib.rs +++ b/integrations/unftp-sbe/src/lib.rs @@ -119,21 +119,60 @@ impl storage::Metadata for OpendalMetadata { fn convert_err(err: opendal::Error) -> Error { let kind = match err.kind() { - opendal::ErrorKind::NotFound => storage::ErrorKind::PermanentFileNotAvailable, - opendal::ErrorKind::AlreadyExists => storage::ErrorKind::PermanentFileNotAvailable, + opendal::ErrorKind::NotFound + | opendal::ErrorKind::AlreadyExists + | opendal::ErrorKind::IsADirectory + | opendal::ErrorKind::NotADirectory => storage::ErrorKind::PermanentFileNotAvailable, opendal::ErrorKind::PermissionDenied => storage::ErrorKind::PermissionDenied, + opendal::ErrorKind::Unsupported => storage::ErrorKind::CommandNotImplemented, _ => storage::ErrorKind::LocalError, }; Error::new(kind, err) } -fn convert_path(path: &Path) -> storage::Result<&str> { - path.to_str().ok_or_else(|| { +/// Convert an FTP path into a lexically normalized OpenDAL path. +/// +/// Collapses `.` and `..` segments and clamps `..` at the FTP root (`/`). +/// Returns `"/"` for the root; otherwise returns a relative path without a +/// leading `/` and with a trailing `/` preserved for directory paths +/// (including paths ending in `.` or `..`). +fn convert_path(path: &Path) -> storage::Result<String> { + let raw = path.to_str().ok_or_else(|| { Error::new( storage::ErrorKind::LocalError, "Path is not a valid UTF-8 string", ) - }) + })?; + + let mut segments = Vec::new(); + let mut is_dir = false; + + for segment in raw.split('/') { + match segment { + "" => {} + "." => { + is_dir = true; + } + ".." => { + segments.pop(); + is_dir = true; + } + name => { + segments.push(name); + is_dir = false; + } + } + } + + if segments.is_empty() { + return Ok("/".to_string()); + } + + let mut normalized = segments.join("/"); + if is_dir || raw.ends_with('/') { + normalized.push('/'); + } + Ok(normalized) } async fn copy_read_write_loop<R>( @@ -194,7 +233,7 @@ impl<User: UserDetail> StorageBackend<User> for OpendalStorage { ) -> storage::Result<Self::Metadata> { use opendal::ErrorKind::*; - let path = opendal::raw::normalize_path(convert_path(path.as_ref())?); + let path = convert_path(path.as_ref())?; let directory = format!("{}/", path.trim_end_matches('/')); // The FTP root always exists; some backends cannot stat it. @@ -250,7 +289,7 @@ impl<User: UserDetail> StorageBackend<User> for OpendalStorage { where Self::Metadata: storage::Metadata, { - let path = opendal::raw::normalize_path(convert_path(path.as_ref())?); + let path = convert_path(path.as_ref())?; let directory = format!("{}/", path.trim_end_matches('/')); let mut entries = self.op.list(&directory).await.map_err(convert_err)?; if entries.is_empty() && path != directory { @@ -280,9 +319,10 @@ impl<User: UserDetail> StorageBackend<User> for OpendalStorage { path: P, start_pos: u64, ) -> storage::Result<Box<dyn tokio::io::AsyncRead + Send + Sync + Unpin>> { + let path = convert_path(path.as_ref())?; let reader = self .op - .reader(convert_path(path.as_ref())?) + .reader(&path) .await .map_err(convert_err)? .into_futures_async_read(start_pos..) @@ -316,7 +356,7 @@ impl<User: UserDetail> StorageBackend<User> for OpendalStorage { "the storage service does not support appending to an existing file", )); } - match self.op.stat(path).await { + match self.op.stat(&path).await { Ok(meta) if meta.content_length() == start_pos => {} Ok(_) => { return Err(Error::new( @@ -329,9 +369,9 @@ impl<User: UserDetail> StorageBackend<User> for OpendalStorage { } let writer = if append { - self.op.writer_with(path).append(true).await + self.op.writer_with(&path).append(true).await } else { - self.op.writer(path).await + self.op.writer(&path).await } .map_err(convert_err)?; @@ -362,14 +402,34 @@ impl<User: UserDetail> StorageBackend<User> for OpendalStorage { } async fn del<P: AsRef<Path> + Send + Debug>(&self, _: &User, path: P) -> storage::Result<()> { - self.op - .delete(convert_path(path.as_ref())?) - .await - .map_err(convert_err) + if !self.op.info().capability().delete { + return Err(Error::new( + storage::ErrorKind::CommandNotImplemented, + "the storage service does not support deleting", + )); + } + + let path = convert_path(path.as_ref())?; + if path.ends_with('/') { + return Err(Error::new( + storage::ErrorKind::PermanentFileNotAvailable, + format!("{path} is a directory"), + )); + } + + let meta = self.op.stat(&path).await.map_err(convert_err)?; + if meta.is_dir() { + return Err(Error::new( + storage::ErrorKind::PermanentFileNotAvailable, + format!("{path} is a directory"), + )); + } + + self.op.delete(&path).await.map_err(convert_err) } async fn mkd<P: AsRef<Path> + Send + Debug>(&self, _: &User, path: P) -> storage::Result<()> { - let mut path_str = convert_path(path.as_ref())?.to_string(); + let mut path_str = convert_path(path.as_ref())?; if !path_str.ends_with('/') { path_str.push('/'); } @@ -382,7 +442,43 @@ impl<User: UserDetail> StorageBackend<User> for OpendalStorage { from: P, to: P, ) -> storage::Result<()> { - let (from, to) = (convert_path(from.as_ref())?, convert_path(to.as_ref())?); + if !self.op.info().capability().rename { + return Err(Error::new( + storage::ErrorKind::CommandNotImplemented, + "the storage service does not support renaming", + )); + } + + let from = convert_path(from.as_ref())?; + let to = convert_path(to.as_ref())?; + + if from == "/" || to == "/" { + return Err(Error::new( + storage::ErrorKind::PermanentFileNotAvailable, + "cannot rename the FTP root directory", + )); + } + + let (from, to) = if from.ends_with('/') || to.ends_with('/') { + let from_trimmed = from.trim_end_matches('/'); + let to_trimmed = to.trim_end_matches('/'); + // OpenDAL's `Operator::rename` rejects trailing slashes with + // `IsADirectory`. Allow stripping trailing slashes only when the + // source is a directory so file renames do not silently accept + // directory-style paths. + let from_dir = format!("{from_trimmed}/"); + let meta = self.op.stat(&from_dir).await.map_err(convert_err)?; + if !meta.is_dir() { + return Err(Error::new( + storage::ErrorKind::PermanentFileNotAvailable, + format!("{from} is not a directory"), + )); + } + (from_trimmed, to_trimmed) + } else { + (from.as_str(), to.as_str()) + }; + self.op.rename(from, to).await.map_err(convert_err) } @@ -391,7 +487,7 @@ impl<User: UserDetail> StorageBackend<User> for OpendalStorage { user: &User, path: P, ) -> storage::Result<()> { - let path = opendal::raw::normalize_path(convert_path(path.as_ref())?); + let path = convert_path(path.as_ref())?; if path == "/" { return Err(Error::new( storage::ErrorKind::PermissionDenied, @@ -416,7 +512,7 @@ impl<User: UserDetail> StorageBackend<User> for OpendalStorage { // Object stores only address directories with a trailing `/`. // Normalizing to root yields "/", which `trim_end_matches('/')` // preserves. - let path = opendal::raw::normalize_path(convert_path(path.as_ref())?); + let path = convert_path(path.as_ref())?; let directory = format!("{}/", path.trim_end_matches('/')); // The FTP root always exists; some backends cannot stat it. @@ -467,3 +563,83 @@ impl<User: UserDetail> StorageBackend<User> for OpendalStorage { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn convert_err_maps_opendal_error_kinds() { + let cases = [ + ( + opendal::ErrorKind::NotFound, + storage::ErrorKind::PermanentFileNotAvailable, + ), + ( + opendal::ErrorKind::AlreadyExists, + storage::ErrorKind::PermanentFileNotAvailable, + ), + ( + opendal::ErrorKind::IsADirectory, + storage::ErrorKind::PermanentFileNotAvailable, + ), + ( + opendal::ErrorKind::NotADirectory, + storage::ErrorKind::PermanentFileNotAvailable, + ), + ( + opendal::ErrorKind::PermissionDenied, + storage::ErrorKind::PermissionDenied, + ), + ( + opendal::ErrorKind::Unsupported, + storage::ErrorKind::CommandNotImplemented, + ), + ( + opendal::ErrorKind::Unexpected, + storage::ErrorKind::LocalError, + ), + ( + opendal::ErrorKind::RateLimited, + storage::ErrorKind::LocalError, + ), + ]; + + for (input, expected) in cases { + let err = convert_err(opendal::Error::new(input, "test error")); + assert_eq!(err.kind(), expected, "opendal error kind {input:?}"); + } + } + + #[test] + fn convert_path_normalizes_dot_and_parent_segments() { + let cases = [ + ("", "/"), + ("/", "/"), + ("///", "/"), + (".", "/"), + ("/.", "/"), + ("/./", "/"), + ("..", "/"), + ("/..", "/"), + ("/../..", "/"), + ("/dir/..", "/"), + ("/dir/../", "/"), + ("/dir/../top.txt", "top.txt"), + ("/../../escape.txt", "escape.txt"), + ("/a/b/..", "a/"), + ("/a/b/.", "a/b/"), + ("/a/./b", "a/b"), + ("/a/b/../c/", "a/c/"), + ("/a/.hidden", "a/.hidden"), + ("/a/..hidden", "a/..hidden"), + ("dir/file.txt", "dir/file.txt"), + ("dir/", "dir/"), + ]; + + for (input, expected) in cases { + let actual = convert_path(Path::new(input)).expect("valid UTF-8 path"); + assert_eq!(actual, expected, "input path {input:?}"); + } + } +} diff --git a/integrations/unftp-sbe/tests/ftp_loopback.rs b/integrations/unftp-sbe/tests/ftp_loopback.rs index 13b32d05fc..23917c0d89 100644 --- a/integrations/unftp-sbe/tests/ftp_loopback.rs +++ b/integrations/unftp-sbe/tests/ftp_loopback.rs @@ -231,3 +231,33 @@ async fn restart_is_unsupported() -> Result<()> { }) .await } + +#[tokio::test] +async fn parent_traversal_delete_errors_and_dir_rename() -> Result<()> { + with_ftp_client(async |ftp| { + ftp.put_file("top.txt", &mut "top".as_bytes()) + .await + .context("STOR top.txt")?; + ftp.mkdir("dir").await.context("MKD dir")?; + ftp.cwd("dir").await.context("CWD dir")?; + ftp.cwd("..").await.context("CWD ..")?; + assert_eq!(retrieve(ftp, "top.txt").await?, b"top"); + + assert_reply( + ftp.rm("missing.txt").await, + Status::FileUnavailable, + "DELE missing.txt", + ); + assert_reply(ftp.rm("dir").await, Status::FileUnavailable, "DELE dir"); + + ftp.put_file("dir/item.txt", &mut "item".as_bytes()) + .await + .context("STOR dir/item.txt")?; + ftp.rename("dir/", "dir2/") + .await + .context("RNFR dir/ + RNTO dir2/")?; + assert_eq!(retrieve(ftp, "dir2/item.txt").await?, b"item"); + Ok(()) + }) + .await +} diff --git a/integrations/unftp-sbe/tests/storage_backend.rs b/integrations/unftp-sbe/tests/storage_backend.rs index 4cdad3273d..354bb735da 100644 --- a/integrations/unftp-sbe/tests/storage_backend.rs +++ b/integrations/unftp-sbe/tests/storage_backend.rs @@ -882,3 +882,308 @@ async fn put_close_error_aborts_writer() -> Result<()> { ); Ok(()) } + +/// Parent traversal segments (`..`) must resolve lexically and clamp at the +/// FTP root on the filesystem backend instead of escaping or failing with +/// `NotFound`. +#[tokio::test] +async fn path_parent_traversal_on_fs() -> Result<()> { + let (_root, storage) = fs_storage()?; + let user = DefaultUser; + + storage.mkd(&user, "/dir").await.context("mkd /dir")?; + storage + .mkd(&user, "/dir/sub") + .await + .context("mkd /dir/sub")?; + storage + .put(&user, "top".as_bytes(), "/top.txt", 0) + .await + .context("put /top.txt")?; + + storage.cwd(&user, "/dir/..").await.context("cwd /dir/..")?; + storage + .cwd(&user, "/dir/sub/..") + .await + .context("cwd /dir/sub/..")?; + assert_eq!(read_file(&storage, "/dir/../top.txt").await?, "top"); + + let meta = storage + .metadata(&user, "/dir/../top.txt") + .await + .context("metadata /dir/../top.txt")?; + assert!(meta.is_file()); + + let entries = storage + .list(&user, "/dir/..") + .await + .context("list /dir/..")?; + assert!( + entries + .iter() + .any(|entry| entry.path.as_os_str() == "top.txt"), + "list /dir/.. must include top.txt" + ); + + storage + .put(&user, "escaped".as_bytes(), "/dir/../escape.txt", 0) + .await + .context("put /dir/../escape.txt")?; + assert_eq!(read_file(&storage, "/escape.txt").await?, "escaped"); + + storage + .put(&user, "clamped".as_bytes(), "/../../clamped.txt", 0) + .await + .context("put /../../clamped.txt")?; + assert_eq!(read_file(&storage, "/clamped.txt").await?, "clamped"); + + storage + .del(&user, "/dir/../clamped.txt") + .await + .context("del /dir/../clamped.txt")?; + let err = storage + .metadata(&user, "/clamped.txt") + .await + .expect_err("clamped.txt should be deleted"); + assert_eq!(err.kind(), ErrorKind::PermanentFileNotAvailable); + + let err = storage + .rmd(&user, "/dir/..") + .await + .expect_err("rmd /dir/.. must reject the FTP root"); + assert_eq!(err.kind(), ErrorKind::PermissionDenied); + assert_eq!(read_file(&storage, "/top.txt").await?, "top"); + Ok(()) +} + +/// Parent traversal segments (`..`) must not create literal `..` keys on +/// object-store-like backends such as memory, and `rmd /dir/..` must hit the +/// root guard. +#[tokio::test] +async fn path_parent_traversal_on_memory() -> Result<()> { + let op = Operator::new(services::Memory::default())?; + let storage = OpendalStorage::new(op.clone()); + let user = DefaultUser; + + storage + .put(&user, "top".as_bytes(), "/top.txt", 0) + .await + .context("put /top.txt")?; + storage + .put(&user, "nested".as_bytes(), "/dir/nested.txt", 0) + .await + .context("put /dir/nested.txt")?; + + storage.cwd(&user, "/dir/..").await.context("cwd /dir/..")?; + assert_eq!(read_file(&storage, "/dir/../top.txt").await?, "top"); + + storage + .put(&user, "escaped".as_bytes(), "/dir/../escape.txt", 0) + .await + .context("put /dir/../escape.txt")?; + assert_eq!(read_file(&storage, "/escape.txt").await?, "escaped"); + assert!( + !op.exists("dir/../escape.txt").await?, + "literal dir/../escape.txt key must not be created" + ); + + storage + .put(&user, "clamped".as_bytes(), "/../../clamped.txt", 0) + .await + .context("put /../../clamped.txt")?; + assert_eq!(read_file(&storage, "/clamped.txt").await?, "clamped"); + assert!( + !op.exists("../../clamped.txt").await?, + "literal ../../clamped.txt key must not be created" + ); + + let err = storage + .rmd(&user, "/dir/..") + .await + .expect_err("rmd /dir/.. must reject the FTP root"); + assert_eq!(err.kind(), ErrorKind::PermissionDenied); + assert_eq!(read_file(&storage, "/top.txt").await?, "top"); + assert_eq!(read_file(&storage, "/dir/nested.txt").await?, "nested"); + Ok(()) +} + +/// `del` must report missing files as `PermanentFileNotAvailable` and refuse +/// to delete directories on the filesystem backend. +#[tokio::test] +async fn del_missing_and_directory_on_fs() -> Result<()> { + let (_root, storage) = fs_storage()?; + let user = DefaultUser; + + let err = storage + .del(&user, "missing.txt") + .await + .expect_err("del missing.txt must fail"); + assert_eq!(err.kind(), ErrorKind::PermanentFileNotAvailable); + + storage.mkd(&user, "/dir").await.context("mkd /dir")?; + for path in ["/dir", "/dir/", "/", "/dir/.."] { + let err = storage + .del(&user, path) + .await + .expect_err("del on directory must fail"); + assert_eq!( + err.kind(), + ErrorKind::PermanentFileNotAvailable, + "del {path}" + ); + } + assert!(storage.metadata(&user, "/dir").await?.is_dir()); + + storage + .put(&user, "keep".as_bytes(), "/dir/file.txt", 0) + .await + .context("put /dir/file.txt")?; + for path in ["/dir", "/dir/"] { + let err = storage + .del(&user, path) + .await + .expect_err("del on non-empty directory must fail"); + assert_eq!( + err.kind(), + ErrorKind::PermanentFileNotAvailable, + "del {path}" + ); + } + assert_eq!(read_file(&storage, "/dir/file.txt").await?, "keep"); + + storage + .del(&user, "/dir/file.txt") + .await + .context("del /dir/file.txt")?; + let err = storage + .metadata(&user, "/dir/file.txt") + .await + .expect_err("deleted file must not exist"); + assert_eq!(err.kind(), ErrorKind::PermanentFileNotAvailable); + Ok(()) +} + +/// `del` must report missing files as `PermanentFileNotAvailable` and leave +/// directories untouched on memory backends. +#[tokio::test] +async fn del_missing_and_directory_on_memory() -> Result<()> { + let storage = OpendalStorage::new(Operator::new(services::Memory::default())?); + let user = DefaultUser; + + let err = storage + .del(&user, "missing.txt") + .await + .expect_err("del missing.txt must fail"); + assert_eq!(err.kind(), ErrorKind::PermanentFileNotAvailable); + + storage + .put(&user, "keep".as_bytes(), "/dir/file.txt", 0) + .await + .context("put /dir/file.txt")?; + for path in ["/dir", "/dir/", "/", "/dir/.."] { + let err = storage + .del(&user, path) + .await + .expect_err("del on directory must fail"); + assert_eq!( + err.kind(), + ErrorKind::PermanentFileNotAvailable, + "del {path}" + ); + } + assert_eq!(read_file(&storage, "/dir/file.txt").await?, "keep"); + + storage + .del(&user, "/dir/file.txt") + .await + .context("del /dir/file.txt")?; + let err = storage + .metadata(&user, "/dir/file.txt") + .await + .expect_err("deleted file must not exist"); + assert_eq!(err.kind(), ErrorKind::PermanentFileNotAvailable); + Ok(()) +} + +/// Backends without rename capability must report `CommandNotImplemented`. +#[tokio::test] +async fn rename_unsupported_on_memory() -> Result<()> { + let storage = OpendalStorage::new(Operator::new(services::Memory::default())?); + let user = DefaultUser; + + storage + .put(&user, "hello".as_bytes(), "/file.txt", 0) + .await + .context("put /file.txt")?; + + let err = storage + .rename(&user, "/file.txt", "/file2.txt") + .await + .expect_err("rename on memory must fail"); + assert_eq!(err.kind(), ErrorKind::CommandNotImplemented); + + let err = storage + .rename(&user, "/dir/", "/dir2/") + .await + .expect_err("directory rename on memory must fail"); + assert_eq!(err.kind(), ErrorKind::CommandNotImplemented); + Ok(()) +} + +/// Directory renames with trailing slashes must work on rename-capable +/// backends, while trailing-slash renames of regular files and root renames +/// must be rejected. +#[tokio::test] +async fn rename_directory_with_trailing_slash_on_fs() -> Result<()> { + let (_root, storage) = fs_storage()?; + let user = DefaultUser; + + storage.mkd(&user, "/dir").await.context("mkd /dir")?; + storage + .put(&user, "hello".as_bytes(), "/dir/nested.txt", 0) + .await + .context("put /dir/nested.txt")?; + + storage + .rename(&user, "/dir/", "/dir2/") + .await + .context("rename /dir/ -> /dir2/")?; + assert_eq!(read_file(&storage, "/dir2/nested.txt").await?, "hello"); + assert_eq!( + storage + .metadata(&user, "/dir") + .await + .expect_err("old directory must be gone") + .kind(), + ErrorKind::PermanentFileNotAvailable + ); + + storage + .rename(&user, "/dir2/", "/dir3") + .await + .context("rename /dir2/ -> /dir3")?; + storage + .rename(&user, "/dir3", "/dir4/") + .await + .context("rename /dir3 -> /dir4/")?; + assert_eq!(read_file(&storage, "/dir4/nested.txt").await?, "hello"); + + for (from, to) in [ + ("/dir4/nested.txt/", "/other.txt"), + ("/dir4/nested.txt", "/other.txt/"), + ("/dir4/..", "/other"), + ("/dir4", "/"), + ] { + let err = storage + .rename(&user, from, to) + .await + .expect_err("invalid trailing-slash or root rename must fail"); + assert_eq!( + err.kind(), + ErrorKind::PermanentFileNotAvailable, + "rename {from} -> {to}" + ); + } + assert_eq!(read_file(&storage, "/dir4/nested.txt").await?, "hello"); + Ok(()) +}
