This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch xuanwo/fix-dav-server-integration-bugs
in repository https://gitbox.apache.org/repos/asf/opendal.git

commit 777fdf250b69454694d79b61803fe2e819cd18f2
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 22:21:43 2026 +0100

    fix(integrations/dav-server): handle implicit directories, trailing-slash 
destinations, rename collisions, and dir entry names
---
 integrations/dav-server/src/dir.rs    |  27 +-
 integrations/dav-server/src/file.rs   |  50 +--
 integrations/dav-server/src/fs.rs     |  78 ++---
 integrations/dav-server/src/utils.rs  |  60 ++++
 integrations/dav-server/tests/test.rs | 573 +++++++++++++++++++++++++++++++++-
 5 files changed, 698 insertions(+), 90 deletions(-)

diff --git a/integrations/dav-server/src/dir.rs 
b/integrations/dav-server/src/dir.rs
index 9546a22653..82403872fb 100644
--- a/integrations/dav-server/src/dir.rs
+++ b/integrations/dav-server/src/dir.rs
@@ -21,7 +21,7 @@ use dav_server::fs::{DavDirEntry, DavMetaData, FsResult};
 use futures::StreamExt;
 use futures::{FutureExt, Stream};
 use opendal_core::raw::normalize_path;
-use opendal_core::{Entry, Lister, Operator};
+use opendal_core::{Entry, ErrorKind, Lister, Operator};
 use std::pin::Pin;
 use std::task::Poll::Ready;
 use std::task::{Context, Poll, ready};
@@ -80,16 +80,29 @@ impl OpendalDirEntry {
 
 impl DavDirEntry for OpendalDirEntry {
     fn name(&self) -> Vec<u8> {
-        self.dir_entry.name().as_bytes().to_vec()
+        self.dir_entry
+            .name()
+            .trim_end_matches('/')
+            .as_bytes()
+            .to_vec()
     }
 
     fn metadata(&self) -> dav_server::fs::FsFuture<'_, Box<dyn DavMetaData>> {
         async move {
-            self.op
-                .stat(self.dir_entry.path())
-                .await
-                .map(|metadata| Box::new(OpendalMetaData::new(metadata)) as 
Box<dyn DavMetaData>)
-                .map_err(convert_error)
+            match self.op.stat(self.dir_entry.path()).await {
+                Ok(metadata) => {
+                    Ok(Box::new(OpendalMetaData::new(metadata)) as Box<dyn 
DavMetaData>)
+                }
+                Err(err)
+                    if err.kind() == ErrorKind::NotFound && 
self.dir_entry.metadata().is_dir() =>
+                {
+                    Ok(
+                        
Box::new(OpendalMetaData::new(self.dir_entry.metadata().clone()))
+                            as Box<dyn DavMetaData>,
+                    )
+                }
+                Err(err) => Err(convert_error(err)),
+            }
         }
         .boxed()
     }
diff --git a/integrations/dav-server/src/file.rs 
b/integrations/dav-server/src/file.rs
index 81a0e38f40..976e0f6a02 100644
--- a/integrations/dav-server/src/file.rs
+++ b/integrations/dav-server/src/file.rs
@@ -23,7 +23,7 @@ use dav_server::fs::{DavFile, OpenOptions};
 use dav_server::fs::{DavMetaData, FsResult};
 use dav_server::fs::{FsError, FsFuture};
 use futures::FutureExt;
-use futures::{AsyncReadExt, AsyncSeekExt, StreamExt};
+use futures::{AsyncReadExt, AsyncSeekExt};
 use opendal_core::{ErrorKind, FuturesAsyncReader, Operator, Writer};
 
 use super::metadata::OpendalMetaData;
@@ -68,48 +68,6 @@ enum State {
 }
 
 impl OpendalFile {
-    /// Return whether `dir_path` (ending with `/`) exists as an explicit
-    /// directory marker or an implicit prefix with children.
-    async fn dir_exists(op: &Operator, dir_path: &str) -> FsResult<bool> {
-        let capability = op.info().capability();
-        if capability.stat {
-            match op.stat(dir_path).await {
-                Ok(meta) => {
-                    if meta.is_dir() {
-                        return Ok(true);
-                    }
-                }
-                Err(err) if err.kind() == ErrorKind::NotADirectory => return 
Ok(false),
-                Err(err) if err.kind() == ErrorKind::NotFound => {}
-                Err(err) => return Err(convert_error(err)),
-            }
-        }
-
-        if capability.list {
-            let mut lister = match op.lister_with(dir_path).limit(1).await {
-                Ok(lister) => lister,
-                Err(err)
-                    if matches!(err.kind(), ErrorKind::NotFound | 
ErrorKind::NotADirectory) =>
-                {
-                    return Ok(false);
-                }
-                Err(err) => return Err(convert_error(err)),
-            };
-            match lister.next().await {
-                Some(Ok(_)) => return Ok(true),
-                Some(Err(err))
-                    if matches!(err.kind(), ErrorKind::NotFound | 
ErrorKind::NotADirectory) =>
-                {
-                    return Ok(false);
-                }
-                Some(Err(err)) => return Err(convert_error(err)),
-                None => return Ok(false),
-            }
-        }
-
-        Ok(false)
-    }
-
     /// Create a new opendal file.
     pub async fn open(op: Operator, path: String, options: OpenOptions) -> 
FsResult<Self> {
         if path.is_empty() || path.ends_with('/') {
@@ -126,7 +84,7 @@ impl OpendalFile {
                     }
                     Err(err) if err.kind() == ErrorKind::NotFound => {
                         let dir_path = format!("{path}/");
-                        if Self::dir_exists(&op, &dir_path).await? {
+                        if dir_exists(&op, &dir_path).await? {
                             return Err(FsError::Forbidden);
                         }
                         return Err(FsError::NotFound);
@@ -135,7 +93,7 @@ impl OpendalFile {
                 }
             } else {
                 let dir_path = format!("{path}/");
-                if Self::dir_exists(&op, &dir_path).await? {
+                if dir_exists(&op, &dir_path).await? {
                     return Err(FsError::Forbidden);
                 }
             }
@@ -154,7 +112,7 @@ impl OpendalFile {
             // separate keys, so writing `dir` would otherwise shadow the
             // collection in `metadata` and `PROPFIND`.
             let dir_path = format!("{path}/");
-            if Self::dir_exists(&op, &dir_path).await? {
+            if dir_exists(&op, &dir_path).await? {
                 return Err(if options.create_new {
                     FsError::Exists
                 } else {
diff --git a/integrations/dav-server/src/fs.rs 
b/integrations/dav-server/src/fs.rs
index b27017c64d..c6cae52876 100644
--- a/integrations/dav-server/src/fs.rs
+++ b/integrations/dav-server/src/fs.rs
@@ -24,13 +24,13 @@ use dav_server::fs::{DavFileSystem, ReadDirMeta};
 use futures::FutureExt;
 use futures::StreamExt;
 use opendal_core::raw::normalize_path;
-use opendal_core::{ErrorKind, Operator};
+use opendal_core::{ErrorKind, MetadataBuilder, Operator};
 use std::path::Path;
 
 use super::dir::OpendalStream;
 use super::file::OpendalFile;
 use super::metadata::OpendalMetaData;
-use super::utils::convert_error;
+use super::utils::{convert_error, dir_exists, implicit_dir_exists};
 
 /// OpendalFs is a `DavFileSystem` implementation for opendal.
 ///
@@ -153,12 +153,32 @@ impl DavFileSystem for OpendalFs {
             let path = self.fs_path(path)?;
             let metadata = match self.op.stat(path.as_str()).await {
                 Ok(metadata) => metadata,
+                Err(e) if path == "/" && e.kind() == ErrorKind::NotFound => {
+                    MetadataBuilder::dir().build()
+                }
+                Err(e) if Self::is_dir_path(&path) && e.kind() == 
ErrorKind::NotFound => {
+                    if implicit_dir_exists(&self.op, path.as_str()).await? {
+                        MetadataBuilder::dir().build()
+                    } else {
+                        return Err(FsError::NotFound);
+                    }
+                }
                 Err(e)
                     if !Self::is_dir_path(&path)
                         && matches!(e.kind(), ErrorKind::NotFound | 
ErrorKind::IsADirectory) =>
                 {
-                    let path = Self::into_dir_path(path);
-                    self.op.stat(path.as_str()).await.map_err(convert_error)?
+                    let dir_path = Self::into_dir_path(path);
+                    match self.op.stat(dir_path.as_str()).await {
+                        Ok(metadata) => metadata,
+                        Err(dir_err) if dir_err.kind() == ErrorKind::NotFound 
=> {
+                            if implicit_dir_exists(&self.op, 
dir_path.as_str()).await? {
+                                MetadataBuilder::dir().build()
+                            } else {
+                                return Err(FsError::NotFound);
+                            }
+                        }
+                        Err(dir_err) => return Err(convert_error(dir_err)),
+                    }
                 }
                 Err(e) => return Err(convert_error(e)),
             };
@@ -192,26 +212,16 @@ impl DavFileSystem for OpendalFs {
             if let Some(parent) = Path::new(&dir_path).parent()
                 && !parent.as_os_str().is_empty()
             {
-                match self
-                    .op
-                    .exists(format!("{}/", parent.display()).as_str())
-                    .await
-                {
-                    Ok(exist) => {
-                        if !exist {
-                            return Err(FsError::NotFound);
-                        }
-                    }
-                    Err(e) => {
-                        return Err(convert_error(e));
-                    }
+                let parent_dir = format!("{}/", parent.display());
+                if !dir_exists(&self.op, parent_dir.as_str()).await? {
+                    return Err(FsError::NotFound);
                 }
             }
 
             // Some backends keep files and directory markers as separate keys,
             // so "foo" and "foo/" can both exist. MKCOL must fail with Exists
             // when either form already names a resource (RFC 4918 9.3.1).
-            if self.path_exists(file_path).await? || 
self.path_exists(&dir_path).await? {
+            if self.path_exists(file_path).await? || dir_exists(&self.op, 
&dir_path).await? {
                 return Err(FsError::Exists);
             }
 
@@ -288,12 +298,8 @@ impl DavFileSystem for OpendalFs {
                     return Err(FsError::Forbidden);
                 }
 
-                if self
-                    .op
-                    .exists(to_path.as_str())
-                    .await
-                    .map_err(convert_error)?
-                {
+                let to_file_path = to_path.trim_end_matches('/');
+                if self.path_exists(to_file_path).await? || 
dir_exists(&self.op, &to_path).await? {
                     return Err(FsError::Exists);
                 }
 
@@ -304,10 +310,7 @@ impl DavFileSystem for OpendalFs {
                 if self.op.info().capability().rename {
                     match self
                         .op
-                        .rename(
-                            from_path.trim_end_matches('/'),
-                            to_path.trim_end_matches('/'),
-                        )
+                        .rename(from_path.trim_end_matches('/'), to_file_path)
                         .await
                     {
                         Ok(()) => return Ok(()),
@@ -321,11 +324,8 @@ impl DavFileSystem for OpendalFs {
                             // destination collection appeared after the check
                             // above, refuse the move instead of clobbering it.
                             ErrorKind::IsADirectory => {
-                                if self
-                                    .op
-                                    .exists(to_path.as_str())
-                                    .await
-                                    .map_err(convert_error)?
+                                if self.path_exists(to_file_path).await?
+                                    || dir_exists(&self.op, &to_path).await?
                                 {
                                     return Err(FsError::Exists);
                                 }
@@ -368,8 +368,12 @@ impl DavFileSystem for OpendalFs {
 
             let from_path = self.fs_path(from)?;
             let to_path = self.fs_path(to)?;
+            if from_path == "/" || to_path == "/" {
+                return Err(FsError::Forbidden);
+            }
+            let to_path = to_path.trim_end_matches('/');
             self.op
-                .rename(from_path.as_str(), to_path.as_str())
+                .rename(from_path.as_str(), to_path)
                 .await
                 .map_err(convert_error)
         }
@@ -380,8 +384,12 @@ impl DavFileSystem for OpendalFs {
         async move {
             let from_path = self.fs_path(from)?;
             let to_path = self.fs_path(to)?;
+            if from_path == "/" || to_path == "/" {
+                return Err(FsError::Forbidden);
+            }
+            let to_path = to_path.trim_end_matches('/');
             self.op
-                .copy(from_path.as_str(), to_path.as_str())
+                .copy(from_path.as_str(), to_path)
                 .await
                 .map(|_| ())
                 .map_err(convert_error)
diff --git a/integrations/dav-server/src/utils.rs 
b/integrations/dav-server/src/utils.rs
index 6a6ee4b829..bde291c968 100644
--- a/integrations/dav-server/src/utils.rs
+++ b/integrations/dav-server/src/utils.rs
@@ -15,6 +15,9 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use futures::StreamExt;
+use opendal_core::{ErrorKind, Operator};
+
 pub fn convert_error(opendal_error: opendal_core::Error) -> 
dav_server::fs::FsError {
     match opendal_error.kind() {
         opendal_core::ErrorKind::Unsupported => 
dav_server::fs::FsError::NotImplemented,
@@ -28,3 +31,60 @@ pub fn convert_error(opendal_error: opendal_core::Error) -> 
dav_server::fs::FsEr
         _ => dav_server::fs::FsError::GeneralFailure,
     }
 }
+
+/// Return whether `dir_path` (ending with `/`) exists as an implicit prefix
+/// containing at least one entry.
+pub(crate) async fn implicit_dir_exists(
+    op: &Operator,
+    dir_path: &str,
+) -> dav_server::fs::FsResult<bool> {
+    if !op.info().capability().list {
+        return Ok(false);
+    }
+
+    let mut lister = match op.lister_with(dir_path).limit(1).await {
+        Ok(lister) => lister,
+        Err(err)
+            if matches!(
+                err.kind(),
+                ErrorKind::NotFound | ErrorKind::NotADirectory | 
ErrorKind::Unsupported
+            ) =>
+        {
+            return Ok(false);
+        }
+        Err(err) => return Err(convert_error(err)),
+    };
+
+    match lister.next().await {
+        Some(Ok(_)) => Ok(true),
+        Some(Err(err))
+            if matches!(
+                err.kind(),
+                ErrorKind::NotFound | ErrorKind::NotADirectory | 
ErrorKind::Unsupported
+            ) =>
+        {
+            Ok(false)
+        }
+        Some(Err(err)) => Err(convert_error(err)),
+        None => Ok(false),
+    }
+}
+
+/// Return whether `dir_path` (ending with `/`) exists as an explicit
+/// directory marker or an implicit prefix with children.
+pub(crate) async fn dir_exists(op: &Operator, dir_path: &str) -> 
dav_server::fs::FsResult<bool> {
+    if op.info().capability().stat {
+        match op.stat(dir_path).await {
+            Ok(meta) => {
+                if meta.is_dir() {
+                    return Ok(true);
+                }
+            }
+            Err(err) if err.kind() == ErrorKind::NotADirectory => return 
Ok(false),
+            Err(err) if err.kind() == ErrorKind::NotFound => {}
+            Err(err) => return Err(convert_error(err)),
+        }
+    }
+
+    implicit_dir_exists(op, dir_path).await
+}
diff --git a/integrations/dav-server/tests/test.rs 
b/integrations/dav-server/tests/test.rs
index 2393b66124..0b3b29ab77 100644
--- a/integrations/dav-server/tests/test.rs
+++ b/integrations/dav-server/tests/test.rs
@@ -437,8 +437,8 @@ async fn test_read_dir() {
         .collect::<Vec<_>>();
     println!("{entries:?}");
     assert_eq!(entries.len(), 2);
-    assert!(entries.contains(&format!("{TEST_PATH_DECODED_1}/")));
-    assert!(entries.contains(&format!("{TEST_PATH_DECODED_2}/")));
+    assert!(entries.contains(&TEST_PATH_DECODED_1.to_string()));
+    assert!(entries.contains(&TEST_PATH_DECODED_2.to_string()));
 
     fs::remove_dir_all(TMP_PATH).unwrap();
 }
@@ -1543,3 +1543,572 @@ async fn 
test_delete_implicit_collection_depth_zero_and_infinity() -> Result<()>
     assert_eq!(status, StatusCode::NOT_FOUND);
     Ok(())
 }
+
+struct CopyFromInnerCopier {
+    op: Operator,
+    from: String,
+    to: String,
+    copied: Option<usize>,
+}
+
+impl oio::Copy for CopyFromInnerCopier {
+    async fn next(&mut self) -> opendal_core::Result<Option<usize>> {
+        if self.copied.is_some() {
+            return Ok(None);
+        }
+        let data = self.op.read(&self.from).await?;
+        let len = data.len();
+        self.op.write(&self.to, data).await?;
+        self.copied = Some(len);
+        Ok(Some(len))
+    }
+
+    async fn close(&mut self) -> opendal_core::Result<Metadata> {
+        let len = self.copied.unwrap_or(0) as u64;
+        Ok(MetadataBuilder::file(len).build())
+    }
+
+    async fn abort(&mut self) -> opendal_core::Result<()> {
+        Ok(())
+    }
+}
+
+#[derive(Debug)]
+struct MemoryWithCopyService {
+    inner: Servicer,
+}
+
+impl Service for MemoryWithCopyService {
+    type Reader = oio::Reader;
+    type Writer = oio::Writer;
+    type Lister = oio::Lister;
+    type Deleter = oio::Deleter;
+    type Copier = CopyFromInnerCopier;
+    type Composer = oio::Composer;
+
+    fn info(&self) -> ServiceInfo {
+        self.inner.info_dyn()
+    }
+
+    fn capability(&self) -> Capability {
+        let mut cap = self.inner.capability_dyn();
+        cap.copy = true;
+        cap
+    }
+
+    async fn create_dir(
+        &self,
+        ctx: &OperationContext,
+        path: &str,
+        args: OpCreateDir,
+    ) -> opendal_core::Result<RpCreateDir> {
+        self.inner.create_dir_dyn(ctx, path, args).await
+    }
+
+    async fn stat(
+        &self,
+        ctx: &OperationContext,
+        path: &str,
+        args: OpStat,
+    ) -> opendal_core::Result<RpStat> {
+        self.inner.stat_dyn(ctx, path, args).await
+    }
+
+    fn read(
+        &self,
+        ctx: &OperationContext,
+        path: &str,
+        args: OpRead,
+    ) -> opendal_core::Result<Self::Reader> {
+        self.inner.read_dyn(ctx, path, args)
+    }
+
+    fn write(
+        &self,
+        ctx: &OperationContext,
+        path: &str,
+        args: OpWrite,
+    ) -> opendal_core::Result<Self::Writer> {
+        self.inner.write_dyn(ctx, path, args)
+    }
+
+    fn delete(&self, ctx: &OperationContext) -> 
opendal_core::Result<Self::Deleter> {
+        self.inner.delete_dyn(ctx)
+    }
+
+    fn list(
+        &self,
+        ctx: &OperationContext,
+        path: &str,
+        args: OpList,
+    ) -> opendal_core::Result<Self::Lister> {
+        self.inner.list_dyn(ctx, path, args)
+    }
+
+    fn copy(
+        &self,
+        ctx: &OperationContext,
+        from: &str,
+        to: &str,
+        _args: OpCopy,
+    ) -> opendal_core::Result<Self::Copier> {
+        Ok(CopyFromInnerCopier {
+            op: Operator::from_parts(ctx.clone(), self.inner.clone()),
+            from: from.to_string(),
+            to: to.to_string(),
+            copied: None,
+        })
+    }
+
+    fn compose(
+        &self,
+        ctx: &OperationContext,
+        to: &str,
+        args: OpCompose,
+    ) -> opendal_core::Result<Self::Composer> {
+        self.inner.compose_dyn(ctx, to, args)
+    }
+
+    async fn rename(
+        &self,
+        ctx: &OperationContext,
+        from: &str,
+        to: &str,
+        args: OpRename,
+    ) -> opendal_core::Result<RpRename> {
+        self.inner.rename_dyn(ctx, from, to, args).await
+    }
+
+    async fn restore(
+        &self,
+        ctx: &OperationContext,
+        path: &str,
+        args: OpRestore,
+    ) -> opendal_core::Result<RpRestore> {
+        self.inner.restore_dyn(ctx, path, args).await
+    }
+
+    async fn presign(
+        &self,
+        ctx: &OperationContext,
+        path: &str,
+        args: OpPresign,
+    ) -> opendal_core::Result<RpPresign> {
+        self.inner.presign_dyn(ctx, path, args).await
+    }
+}
+
+fn memory_without_stat_dir_simulation() -> Result<Operator> {
+    let raw_mem = Arc::new(opendal_core::Builder::build(
+        opendal::services::Memory::default(),
+    )?) as Servicer;
+    let service = Arc::new(MemoryWithCopyService { inner: raw_mem }) as 
Servicer;
+    Ok(Operator::from_parts(OperationContext::default(), service)
+        
.layer(opendal_core::layers::SimulateLayer::default().with_stat_dir(false)))
+}
+
+fn propfind_hrefs(xml: &[u8]) -> Result<Vec<String>> {
+    let text = std::str::from_utf8(xml)?;
+    let doc = roxmltree::Document::parse(text)?;
+    Ok(doc
+        .descendants()
+        .filter(|node| node.tag_name().name() == "href")
+        .filter_map(|node| node.text().map(ToOwned::to_owned))
+        .collect())
+}
+
+#[tokio::test]
+async fn 
test_implicit_directories_propfind_copy_delete_without_stat_dir_simulation() -> 
Result<()>
+{
+    let op = memory_without_stat_dir_simulation()?;
+    op.write("a/b/c.txt", "hello").await?;
+    op.write("foo", "file").await?;
+
+    // Confirm the backend genuinely reports NotFound when stat-ing implicit
+    // directory prefixes so this test exercises OpendalFs's fallback path.
+    assert!(matches!(
+        op.stat("a/").await,
+        Err(err) if err.kind() == ErrorKind::NotFound
+    ));
+    assert!(matches!(
+        op.stat("a/b/").await,
+        Err(err) if err.kind() == ErrorKind::NotFound
+    ));
+
+    let webdavfs = OpendalFs::new(op.clone());
+    assert!(webdavfs.metadata(&DavPath::new("/")?).await?.is_dir());
+    for dir in ["/a", "/a/", "/a/b", "/a/b/"] {
+        let meta = webdavfs.metadata(&DavPath::new(dir)?).await?;
+        assert!(meta.is_dir(), "{dir} should be detected as a directory");
+    }
+    let file_meta = webdavfs.metadata(&DavPath::new("/a/b/c.txt")?).await?;
+    assert!(file_meta.is_file());
+    assert_eq!(file_meta.len(), 5);
+
+    let foo_meta = webdavfs.metadata(&DavPath::new("/foo")?).await?;
+    assert!(foo_meta.is_file());
+    assert!(matches!(
+        webdavfs.metadata(&DavPath::new("/foo/")?).await,
+        Err(FsError::NotFound)
+    ));
+    for missing in ["/missing", "/missing/", "/a/missing/"] {
+        assert!(
+            matches!(
+                webdavfs.metadata(&DavPath::new(missing)?).await,
+                Err(FsError::NotFound)
+            ),
+            "{missing} should be NotFound"
+        );
+    }
+
+    let dav = DavHandler::builder()
+        .filesystem(OpendalFs::new(op.clone()))
+        .build_handler();
+
+    // PROPFIND / (Depth: 1) must include the implicit directory /a/ instead of
+    // dropping it when OpendalDirEntry::metadata() stats "a/".
+    let (status, body) = dav_request(
+        &dav,
+        Request::builder()
+            .method("PROPFIND")
+            .uri("/")
+            .header("Depth", "1")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::MULTI_STATUS);
+    let hrefs = propfind_hrefs(&body)?;
+    assert!(hrefs.iter().any(|h| h == "/a/"), "missing /a/ in {hrefs:?}");
+    assert!(
+        hrefs.iter().any(|h| h == "/foo"),
+        "missing /foo in {hrefs:?}"
+    );
+
+    // PROPFIND /a/ (Depth: 1) must list the nested implicit directory /a/b/.
+    let (status, body) = dav_request(
+        &dav,
+        Request::builder()
+            .method("PROPFIND")
+            .uri("/a/")
+            .header("Depth", "1")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::MULTI_STATUS);
+    let hrefs = propfind_hrefs(&body)?;
+    assert!(
+        hrefs.iter().any(|h| h == "/a/b/"),
+        "missing /a/b/ in {hrefs:?}"
+    );
+
+    // PROPFIND /a/b/ (Depth: 0) must report a collection; missing must be 404.
+    let (status, body) = dav_request(
+        &dav,
+        Request::builder()
+            .method("PROPFIND")
+            .uri("/a/b/")
+            .header("Depth", "0")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::MULTI_STATUS);
+    assert!(propfind_is_collection(&body)?);
+
+    let (status, _) = dav_request(
+        &dav,
+        Request::builder()
+            .method("PROPFIND")
+            .uri("/missing/")
+            .header("Depth", "0")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::NOT_FOUND);
+
+    // MKCOL onto an implicit directory reports 405; MKCOL under it succeeds.
+    let (status, _) = dav_request(
+        &dav,
+        Request::builder()
+            .method("MKCOL")
+            .uri("/a/")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
+
+    let (status, _) = dav_request(
+        &dav,
+        Request::builder()
+            .method("MKCOL")
+            .uri("/a/sibling/")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::CREATED);
+
+    // Recursive COPY of an implicit directory must copy nested entries.
+    let (status, _) = dav_request(
+        &dav,
+        Request::builder()
+            .method("COPY")
+            .uri("/a/")
+            .header("Destination", "/copied/")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::CREATED);
+
+    let (status, body) = dav_request(
+        &dav,
+        Request::builder()
+            .method(Method::GET)
+            .uri("/copied/b/c.txt")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::OK);
+    assert_eq!(body.as_ref(), b"hello");
+
+    // Recursive DELETE of an implicit directory must remove its entire 
subtree.
+    let (status, _) = dav_request(
+        &dav,
+        Request::builder()
+            .method(Method::DELETE)
+            .uri("/a/")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::NO_CONTENT);
+
+    let (status, _) = dav_request(
+        &dav,
+        Request::builder()
+            .method("PROPFIND")
+            .uri("/a/")
+            .header("Depth", "0")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::NOT_FOUND);
+    assert!(!op.exists("a/b/c.txt").await?);
+    Ok(())
+}
+
+#[tokio::test]
+async fn test_file_move_and_copy_to_trailing_slash_destination() -> Result<()> 
{
+    let root = tempfile::tempdir()?;
+    let op = Operator::new(Fs::default().root(root.path().to_str().unwrap()))?;
+    let dav = DavHandler::builder()
+        .filesystem(OpendalFs::new(op.clone()))
+        .build_handler();
+
+    // MOVE file onto an existing collection with trailing slash and 
Overwrite: T.
+    op.write("src.txt", "moved-data").await?;
+    op.create_dir("dst/").await?;
+    op.write("dst/old.txt", "old").await?;
+
+    let (status, _) = dav_request(
+        &dav,
+        Request::builder()
+            .method("MOVE")
+            .uri("/src.txt")
+            .header("Destination", "/dst/")
+            .header("Overwrite", "T")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::NO_CONTENT);
+
+    let (status, body) = dav_request(
+        &dav,
+        Request::builder()
+            .method(Method::GET)
+            .uri("/dst")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::OK);
+    assert_eq!(body.as_ref(), b"moved-data");
+    assert!(!op.exists("src.txt").await?);
+    assert!(root.path().join("dst").is_file());
+    assert!(!root.path().join("dst/old.txt").exists());
+
+    // COPY file onto an existing collection with trailing slash and 
Overwrite: T.
+    op.write("src2.txt", "copied-data").await?;
+    op.create_dir("copy_dst/").await?;
+    op.write("copy_dst/old.txt", "old").await?;
+
+    let (status, _) = dav_request(
+        &dav,
+        Request::builder()
+            .method("COPY")
+            .uri("/src2.txt")
+            .header("Destination", "/copy_dst/")
+            .header("Overwrite", "T")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::NO_CONTENT);
+
+    let (status, body) = dav_request(
+        &dav,
+        Request::builder()
+            .method(Method::GET)
+            .uri("/copy_dst")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::OK);
+    assert_eq!(body.as_ref(), b"copied-data");
+    assert_eq!(
+        op.read("src2.txt").await?.to_bytes().as_ref(),
+        b"copied-data"
+    );
+
+    // COPY and MOVE to a non-existent destination with trailing slash.
+    let (status, _) = dav_request(
+        &dav,
+        Request::builder()
+            .method("COPY")
+            .uri("/src2.txt")
+            .header("Destination", "/fresh_copy/")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::CREATED);
+    assert_eq!(
+        op.read("fresh_copy").await?.to_bytes().as_ref(),
+        b"copied-data"
+    );
+
+    let (status, _) = dav_request(
+        &dav,
+        Request::builder()
+            .method("MOVE")
+            .uri("/src2.txt")
+            .header("Destination", "/fresh_move/")
+            .body(Body::empty())?,
+    )
+    .await?;
+    assert_eq!(status, StatusCode::CREATED);
+    assert_eq!(
+        op.read("fresh_move").await?.to_bytes().as_ref(),
+        b"copied-data"
+    );
+    assert!(!op.exists("src2.txt").await?);
+
+    // Root "/" must be rejected as source or destination for file rename/copy.
+    let webdavfs = OpendalFs::new(op);
+    assert!(matches!(
+        webdavfs
+            .rename(&DavPath::new("/fresh_move")?, &DavPath::new("/")?)
+            .await,
+        Err(FsError::Forbidden)
+    ));
+    assert!(matches!(
+        webdavfs
+            .copy(&DavPath::new("/fresh_move")?, &DavPath::new("/")?)
+            .await,
+        Err(FsError::Forbidden)
+    ));
+    assert!(matches!(
+        webdavfs
+            .copy(&DavPath::new("/")?, &DavPath::new("/out")?)
+            .await,
+        Err(FsError::Forbidden)
+    ));
+    Ok(())
+}
+
+#[tokio::test]
+async fn 
test_collection_rename_fallback_rejects_existing_file_and_implicit_dir() -> 
Result<()> {
+    let op = Operator::new(opendal::services::Memory::default())?;
+    op.create_dir("dir/").await?;
+    op.write("file", "keep").await?;
+    let webdavfs = OpendalFs::new(op.clone());
+
+    for dst in ["/file", "/file/"] {
+        assert!(
+            matches!(
+                webdavfs
+                    .rename(&DavPath::new("/dir/")?, &DavPath::new(dst)?)
+                    .await,
+                Err(FsError::Exists)
+            ),
+            "renaming /dir/ onto existing file via {dst} must fail with Exists"
+        );
+    }
+
+    assert_eq!(op.read("file").await?.to_bytes().as_ref(), b"keep");
+    assert!(!op.exists("file/").await?);
+    assert!(op.exists("dir/").await?);
+
+    // Also reject renaming an empty collection onto an implicit directory when
+    // stat_dir simulation is disabled.
+    let implicit_op = memory_without_stat_dir_simulation()?;
+    implicit_op.create_dir("empty/").await?;
+    implicit_op.write("implicit/child.txt", "keep").await?;
+    let implicit_fs = OpendalFs::new(implicit_op.clone());
+
+    assert!(matches!(
+        implicit_fs
+            .rename(&DavPath::new("/empty/")?, &DavPath::new("/implicit/")?)
+            .await,
+        Err(FsError::Exists)
+    ));
+    assert!(implicit_op.exists("empty/").await?);
+    assert_eq!(
+        implicit_op
+            .read("implicit/child.txt")
+            .await?
+            .to_bytes()
+            .as_ref(),
+        b"keep"
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn test_autoindex_directory_name_has_single_slash() -> Result<()> {
+    let memory = Operator::new(opendal::services::Memory::default())?;
+    let root = tempfile::tempdir()?;
+    let fs_op = 
Operator::new(Fs::default().root(root.path().to_str().unwrap()))?;
+
+    for (label, op) in [("memory", memory), ("fs", fs_op)] {
+        op.create_dir("sub/").await?;
+        op.write("sub/file.txt", "hi").await?;
+
+        let webdavfs = OpendalFs::new(op.clone());
+        let entries: Vec<String> = webdavfs
+            .read_dir(&DavPath::new("/")?, ReadDirMeta::None)
+            .await?
+            .map(|entry| String::from_utf8(entry.unwrap().name()).unwrap())
+            .collect()
+            .await;
+        assert_eq!(entries, vec!["sub".to_string()], "{label}: bare entry 
name");
+
+        let dav = DavHandler::builder()
+            .filesystem(OpendalFs::new(op))
+            .autoindex(true)
+            .build_handler();
+        let (status, body) = dav_request(
+            &dav,
+            Request::builder()
+                .method(Method::GET)
+                .uri("/")
+                .body(Body::empty())?,
+        )
+        .await?;
+        assert_eq!(status, StatusCode::OK, "{label}: GET / autoindex");
+        let html = std::str::from_utf8(&body)?;
+        assert!(
+            html.contains("sub/"),
+            "{label}: expected single-slash sub/ in {html}"
+        );
+        assert!(
+            !html.contains("sub//"),
+            "{label}: unexpected double-slash sub// in {html}"
+        );
+    }
+    Ok(())
+}

Reply via email to