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

Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git


The following commit(s) were added to refs/heads/main by this push:
     new ba77dba77e fix(integrations/dav-server): fix MKCOL / panic and MOVE on 
non-empty collections (#8731)
ba77dba77e is described below

commit ba77dba77e5f678097d64e86d4c29daad2e74da5
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 06:00:21 2026 +0800

    fix(integrations/dav-server): fix MKCOL / panic and MOVE on non-empty 
collections (#8731)
    
    * fix(integrations/dav-server): fix MKCOL / panic and MOVE on non-empty 
collections
    
    MKCOL / panicked on Path::new("/").parent().unwrap() before reaching the
    existence check. Skip the parent-existence check for paths without a
    parent so MKCOL / returns FsError::Exists (HTTP 405) per RFC 4918 9.3.1,
    while a missing parent still fails with 409 Conflict.
    
    MOVE on a non-empty collection returned 501 even on backends whose
    native Operator::rename moves directories atomically. Attempt the native
    rename when capability().rename is advertised, and keep the existing
    empty-collection fallback otherwise.
    
    Add HTTP loopback coverage for MKCOL /, MKCOL with a missing parent, and
    MOVE of a non-empty collection including Overwrite F/T semantics.
    
    * fix(integrations/dav-server): handle IsADirectory rename fallback and run 
unit tests in CI
    
    Backends like smb advertise rename but reject directory renames with
    IsADirectory; catching it keeps empty-collection MOVE working instead of
    regressing to 403. Because some backends also report IsADirectory when
    the destination is an existing collection, re-check the destination and
    return 405 instead of clobbering it through the create_dir + delete
    fallback. Moving from or onto / is refused outright as Forbidden.
    
    Cover the fallback, the destination re-check, root refusal, and the
    non-rename-backend path with unit tests, extend the loopback MOVE test
    to a non-empty destination under Overwrite: T, and run the full
    dav-server test suite in CI instead of only the loopback binary.
---
 .github/workflows/ci_integration_dav_server.yml  |   4 +-
 integrations/dav-server/src/fs.rs                |  72 +++++-
 integrations/dav-server/tests/test.rs            | 303 ++++++++++++++++++++++-
 integrations/dav-server/tests/webdav_loopback.rs | 139 +++++++++++
 4 files changed, 503 insertions(+), 15 deletions(-)

diff --git a/.github/workflows/ci_integration_dav_server.yml 
b/.github/workflows/ci_integration_dav_server.yml
index b2105bb9b2..ad554d4f6d 100644
--- a/.github/workflows/ci_integration_dav_server.yml
+++ b/.github/workflows/ci_integration_dav_server.yml
@@ -48,6 +48,6 @@ jobs:
         working-directory: integrations/dav-server
         run: cargo clippy --all-targets --all-features -- -D warnings
 
-      - name: WebDAV loopback tests
+      - name: Cargo test
         working-directory: integrations/dav-server
-        run: cargo test --test webdav_loopback
+        run: cargo test
diff --git a/integrations/dav-server/src/fs.rs 
b/integrations/dav-server/src/fs.rs
index 25db711d9d..9e31ba30e5 100644
--- a/integrations/dav-server/src/fs.rs
+++ b/integrations/dav-server/src/fs.rs
@@ -158,19 +158,25 @@ impl DavFileSystem for OpendalFs {
             // check if the parent path is exist.
             // During MKCOL processing, a server MUST make the Request-URI a 
member of its parent collection, unless the Request-URI is "/".  If no such 
ancestor exists, the method MUST fail.
             // refer to 
https://datatracker.ietf.org/doc/html/rfc2518#section-8.3.1
-            let parent = Path::new(&path).parent().unwrap();
-            match self
-                .op
-                .exists(format!("{}/", parent.display()).as_str())
-                .await
+            // The root and paths without a parent separator have no parent; 
skip
+            // the check so they hit the existence check below instead.
+            if let Some(parent) = Path::new(&path).parent()
+                && parent != Path::new("/")
+                && !parent.as_os_str().is_empty()
             {
-                Ok(exist) => {
-                    if !exist && parent != Path::new("/") {
-                        return Err(FsError::NotFound);
+                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));
                     }
-                }
-                Err(e) => {
-                    return Err(convert_error(e));
                 }
             }
 
@@ -216,6 +222,12 @@ impl DavFileSystem for OpendalFs {
                 let from_path = self.fs_dir_path(from)?;
                 let to_path = self.fs_dir_path(to)?;
 
+                // Moving the root or onto the root is not a collection move.
+                // Refuse it before it can reach the create_dir + delete below.
+                if from_path == "/" || to_path == "/" {
+                    return Err(FsError::Forbidden);
+                }
+
                 if self
                     .op
                     .exists(to_path.as_str())
@@ -225,6 +237,44 @@ impl DavFileSystem for OpendalFs {
                     return Err(FsError::Exists);
                 }
 
+                // Services with native rename can move a non-empty collection
+                // atomically. Fall back to the empty-collection move when the
+                // service cannot rename this collection. `Operator::rename`
+                // takes file paths, so drop the collection trailing slashes.
+                if self.op.info().capability().rename {
+                    match self
+                        .op
+                        .rename(
+                            from_path.trim_end_matches('/'),
+                            to_path.trim_end_matches('/'),
+                        )
+                        .await
+                    {
+                        Ok(()) => return Ok(()),
+                        Err(e) => match e.kind() {
+                            // The service does not move collections; fall back
+                            // to the empty-collection move below.
+                            ErrorKind::Unsupported | ErrorKind::NotFound => {}
+                            // Some services report IsADirectory when they
+                            // cannot rename directories (smb) and also when
+                            // the destination is an existing directory. If a
+                            // 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)?
+                                {
+                                    return Err(FsError::Exists);
+                                }
+                            }
+                            _ => return Err(convert_error(e)),
+                        },
+                    }
+                }
+
                 let mut lister = self
                     .op
                     .lister_with(from_path.as_str())
diff --git a/integrations/dav-server/tests/test.rs 
b/integrations/dav-server/tests/test.rs
index 618c36ea74..62a44aa02a 100644
--- a/integrations/dav-server/tests/test.rs
+++ b/integrations/dav-server/tests/test.rs
@@ -28,8 +28,9 @@ use http::{HeaderValue, Method, Request, Response, 
StatusCode, header::ETAG};
 use opendal::services::{Fs, Http};
 use opendal::{HttpBody, HttpTransport, HttpTransporter, Operator};
 use opendal_core::raw::{
-    OpCopy, OpCreateDir, OpList, OpPresign, OpRead, OpRename, OpStat, OpWrite, 
RpCreateDir,
-    RpPresign, RpRename, RpStat, Service, ServiceInfo, oio,
+    OpCompose, OpCopy, OpCreateDir, OpList, OpPresign, OpRead, OpRename, 
OpRestore, OpStat,
+    OpWrite, RpCreateDir, RpPresign, RpRename, RpRestore, RpStat, Service, 
ServiceDyn, ServiceInfo,
+    Servicer, oio,
 };
 use opendal_core::{
     Buffer, Capability, Error, ErrorKind, Metadata, MetadataBuilder, 
OperationContext,
@@ -517,3 +518,301 @@ async fn test_failed_close_aborts_before_returning() {
         "close failure must abort the writer"
     );
 }
+
+/// Wrapper that advertises `rename` but rejects it with `IsADirectory`,
+/// mirroring backends such as `smb` that cannot move directories. It can also
+/// hide one path from `stat` for a single call to simulate a destination
+/// collection appearing between the adapter's existence check and rename.
+#[derive(Debug)]
+struct DirRenameDenyService {
+    inner: Servicer,
+    hidden_path: String,
+    hidden: AtomicBool,
+}
+
+impl Service for DirRenameDenyService {
+    type Reader = oio::Reader;
+    type Writer = oio::Writer;
+    type Lister = oio::Lister;
+    type Deleter = oio::Deleter;
+    type Copier = oio::Copier;
+    type Composer = oio::Composer;
+
+    fn info(&self) -> ServiceInfo {
+        self.inner.info_dyn()
+    }
+
+    fn capability(&self) -> Capability {
+        let mut capability = self.inner.capability_dyn();
+        capability.rename = true;
+        capability
+    }
+
+    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> {
+        if path == self.hidden_path && self.hidden.swap(false, 
Ordering::Relaxed) {
+            return Err(Error::new(ErrorKind::NotFound, "hidden for test"));
+        }
+        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> {
+        self.inner.copy_dyn(ctx, from, to, args)
+    }
+
+    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,
+        _: &OperationContext,
+        _: &str,
+        _: &str,
+        _: OpRename,
+    ) -> opendal_core::Result<RpRename> {
+        Err(Error::new(
+            ErrorKind::IsADirectory,
+            "cannot rename a directory",
+        ))
+    }
+
+    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 deny_dir_rename_op(hidden_path: Option<&str>) -> Operator {
+    let inner = Operator::new(opendal::services::Memory::default())
+        .unwrap()
+        .service()
+        .clone();
+    Operator::from_parts(
+        OperationContext::default(),
+        Arc::new(DirRenameDenyService {
+            inner,
+            hidden_path: hidden_path.unwrap_or_default().to_string(),
+            hidden: AtomicBool::new(hidden_path.is_some()),
+        }),
+    )
+}
+
+#[tokio::test]
+async fn test_collection_move_falls_back_when_backend_denies_dir_rename() -> 
Result<()> {
+    let webdavfs = OpendalFs::new(deny_dir_rename_op(None));
+
+    // An empty collection falls back to create + delete.
+    webdavfs
+        .create_dir(&DavPath::new("/empty/").unwrap())
+        .await
+        .unwrap();
+    webdavfs
+        .rename(
+            &DavPath::new("/empty/").unwrap(),
+            &DavPath::new("/renamed/").unwrap(),
+        )
+        .await
+        .unwrap();
+    assert!(matches!(
+        webdavfs.metadata(&DavPath::new("/renamed/")?).await,
+        Ok(metadata) if metadata.is_dir()
+    ));
+
+    // A non-empty collection still reports NotImplemented.
+    webdavfs
+        .create_dir(&DavPath::new("/dir/").unwrap())
+        .await
+        .unwrap();
+    webdavfs.op.write("dir/file", b"x".to_vec()).await?;
+    assert!(matches!(
+        webdavfs
+            .rename(
+                &DavPath::new("/dir/").unwrap(),
+                &DavPath::new("/moved/").unwrap(),
+            )
+            .await,
+        Err(FsError::NotImplemented)
+    ));
+
+    // Moving a missing collection reports NotFound.
+    assert!(matches!(
+        webdavfs
+            .rename(
+                &DavPath::new("/gone/").unwrap(),
+                &DavPath::new("/nowhere/").unwrap(),
+            )
+            .await,
+        Err(FsError::NotFound)
+    ));
+    Ok(())
+}
+
+#[tokio::test]
+async fn test_collection_move_denies_root() -> Result<()> {
+    for op in [
+        deny_dir_rename_op(None),
+        Operator::new(opendal::services::Memory::default()).unwrap(),
+    ] {
+        let webdavfs = OpendalFs::new(op);
+        assert!(matches!(
+            webdavfs
+                .rename(&DavPath::new("/")?, &DavPath::new("/moved/")?)
+                .await,
+            Err(FsError::Forbidden)
+        ));
+        webdavfs
+            .create_dir(&DavPath::new("/dir/").unwrap())
+            .await
+            .unwrap();
+        assert!(matches!(
+            webdavfs
+                .rename(&DavPath::new("/dir/")?, &DavPath::new("/")?)
+                .await,
+            Err(FsError::Forbidden)
+        ));
+    }
+    Ok(())
+}
+
+#[tokio::test]
+async fn test_collection_move_into_existing_dir_is_exists() -> Result<()> {
+    // `/moved/` exists but is hidden from the first stat, so the adapter's
+    // existence check sees a free destination and only the rename-time
+    // IsADirectory re-check observes it.
+    let webdavfs = OpendalFs::new(deny_dir_rename_op(Some("moved/")));
+    webdavfs
+        .create_dir(&DavPath::new("/dir/").unwrap())
+        .await
+        .unwrap();
+    webdavfs
+        .create_dir(&DavPath::new("/moved/").unwrap())
+        .await
+        .unwrap();
+
+    assert!(matches!(
+        webdavfs
+            .rename(
+                &DavPath::new("/dir/").unwrap(),
+                &DavPath::new("/moved/").unwrap(),
+            )
+            .await,
+        Err(FsError::Exists)
+    ));
+
+    // Neither collection is touched by the refused move.
+    for path in ["/dir/", "/moved/"] {
+        assert!(matches!(
+            webdavfs.metadata(&DavPath::new(path)?).await,
+            Ok(metadata) if metadata.is_dir()
+        ));
+    }
+    Ok(())
+}
+
+#[tokio::test]
+async fn test_collection_move_without_backend_rename() -> Result<()> {
+    // Memory has no native rename; the empty-collection move keeps working.
+    let op = Operator::new(opendal::services::Memory::default()).unwrap();
+    let webdavfs = OpendalFs::new(op);
+
+    webdavfs
+        .create_dir(&DavPath::new("/empty/").unwrap())
+        .await
+        .unwrap();
+    webdavfs
+        .rename(
+            &DavPath::new("/empty/").unwrap(),
+            &DavPath::new("/renamed/").unwrap(),
+        )
+        .await
+        .unwrap();
+    assert!(matches!(
+        webdavfs.metadata(&DavPath::new("/renamed/")?).await,
+        Ok(metadata) if metadata.is_dir()
+    ));
+
+    webdavfs
+        .create_dir(&DavPath::new("/dir/").unwrap())
+        .await
+        .unwrap();
+    webdavfs.op.write("dir/file", b"x".to_vec()).await?;
+    assert!(matches!(
+        webdavfs
+            .rename(
+                &DavPath::new("/dir/").unwrap(),
+                &DavPath::new("/moved/").unwrap(),
+            )
+            .await,
+        Err(FsError::NotImplemented)
+    ));
+    Ok(())
+}
diff --git a/integrations/dav-server/tests/webdav_loopback.rs 
b/integrations/dav-server/tests/webdav_loopback.rs
index 39997eaced..f390eefdab 100644
--- a/integrations/dav-server/tests/webdav_loopback.rs
+++ b/integrations/dav-server/tests/webdav_loopback.rs
@@ -313,3 +313,142 @@ async fn nested_utf8_file_lifecycle() -> Result<()> {
     );
     Ok(())
 }
+
+#[tokio::test]
+async fn mkcol_root_and_missing_parent() -> Result<()> {
+    // MKCOL / must fail with 405 instead of panicking on the missing parent
+    // of "/"; the connection and server stay usable afterwards.
+    let dav = WebDav::new().await?;
+    dav.send(
+        dav.request("MKCOL", "/"),
+        b"",
+        StatusCode::METHOD_NOT_ALLOWED,
+    )
+    .await?;
+
+    dav.send(
+        dav.request("MKCOL", "/missing/child/"),
+        b"",
+        StatusCode::CONFLICT,
+    )
+    .await?;
+    dav.send(dav.request("MKCOL", "/alive/"), b"", StatusCode::CREATED)
+        .await?;
+    assert_eq!(
+        dav.propfind("/", "1").await?,
+        [
+            ("/".to_string(), Resource::Collection),
+            ("/alive/".to_string(), Resource::Collection)
+        ]
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn move_non_empty_collection() -> Result<()> {
+    // The fs backend supports native rename, so MOVE on a non-empty
+    // collection must relocate it instead of failing with 501.
+    let dav = WebDav::new().await?;
+    dav.send(dav.request("MKCOL", "/dir/"), b"", StatusCode::CREATED)
+        .await?;
+    dav.send(
+        dav.request("MKCOL", "/dir/nested/"),
+        b"",
+        StatusCode::CREATED,
+    )
+    .await?;
+    let content = b"nested file";
+    dav.send(
+        dav.request("PUT", "/dir/nested/blob.bin"),
+        content,
+        StatusCode::CREATED,
+    )
+    .await?;
+    dav.send(
+        dav.request("PUT", "/dir/top.bin"),
+        b"top",
+        StatusCode::CREATED,
+    )
+    .await?;
+
+    let move_request = dav
+        .request("MOVE", "/dir/")
+        .header("Destination", format!("http://{}/moved/";, dav.addr));
+    dav.send(move_request, b"", StatusCode::CREATED).await?;
+
+    dav.send(
+        dav.request("PROPFIND", "/dir/").header("Depth", "0"),
+        b"",
+        StatusCode::NOT_FOUND,
+    )
+    .await?;
+    assert_eq!(
+        dav.propfind("/moved/", "1").await?,
+        [
+            ("/moved/".to_string(), Resource::Collection),
+            ("/moved/nested/".to_string(), Resource::Collection),
+            ("/moved/top.bin".to_string(), Resource::File(3))
+        ]
+    );
+    let get = dav
+        .send(
+            dav.request("GET", "/moved/nested/blob.bin"),
+            b"",
+            StatusCode::OK,
+        )
+        .await?;
+    assert_eq!(get.body().as_ref(), content);
+
+    // MOVE with `Overwrite: F` onto an existing collection fails with 412.
+    dav.send(dav.request("MKCOL", "/occupied/"), b"", StatusCode::CREATED)
+        .await?;
+    dav.send(
+        dav.request("PUT", "/occupied/old.bin"),
+        b"old",
+        StatusCode::CREATED,
+    )
+    .await?;
+    let overwrite_f = dav
+        .request("MOVE", "/moved/")
+        .header("Destination", format!("http://{}/occupied/";, dav.addr))
+        .header("Overwrite", "F");
+    dav.send(overwrite_f, b"", StatusCode::PRECONDITION_FAILED)
+        .await?;
+
+    // With `Overwrite: T` dav-server deletes the existing destination first
+    // and the move succeeds with 204.
+    let overwrite_t = dav
+        .request("MOVE", "/moved/")
+        .header("Destination", format!("http://{}/occupied/";, dav.addr))
+        .header("Overwrite", "T");
+    dav.send(overwrite_t, b"", StatusCode::NO_CONTENT).await?;
+    dav.send(
+        dav.request("PROPFIND", "/moved/").header("Depth", "0"),
+        b"",
+        StatusCode::NOT_FOUND,
+    )
+    .await?;
+    dav.send(
+        dav.request("GET", "/occupied/old.bin"),
+        b"",
+        StatusCode::NOT_FOUND,
+    )
+    .await?;
+    assert_eq!(
+        dav.propfind("/occupied/", "1").await?,
+        [
+            ("/occupied/".to_string(), Resource::Collection),
+            ("/occupied/nested/".to_string(), Resource::Collection),
+            ("/occupied/top.bin".to_string(), Resource::File(3))
+        ]
+    );
+    let get = dav
+        .send(
+            dav.request("GET", "/occupied/nested/blob.bin"),
+            b"",
+            StatusCode::OK,
+        )
+        .await?;
+    assert_eq!(get.body().as_ref(), content);
+    Ok(())
+}

Reply via email to