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

Xuanwo pushed a commit to branch xuanwo/fix-webdav-weak-etag-preconditions
in repository https://gitbox.apache.org/repos/asf/opendal.git

commit e181870594826dbc4b7abf9205bbf6d7410576b7
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 21:40:30 2026 +0100

    fix(services/webdav): use tagged WebDAV If header for weak ETag 
preconditions
---
 core/services/webdav/README.md      |   7 +-
 core/services/webdav/src/backend.rs | 197 +++++++++++++++++++++++++++++++++++-
 core/services/webdav/src/core.rs    | 100 +++++++++++++-----
 core/services/webdav/src/docs.md    |  34 ++++---
 4 files changed, 289 insertions(+), 49 deletions(-)

diff --git a/core/services/webdav/README.md b/core/services/webdav/README.md
index b32c91c89e..1570893511 100644
--- a/core/services/webdav/README.md
+++ b/core/services/webdav/README.md
@@ -6,10 +6,9 @@ with Apache OpenDAL™.
 > **Warning:** Verify conditional writes and deletes against your endpoint 
 > before
 > relying on them. In the tested configurations, nginx’s `ngx_http_dav_module`
 > ignored PUT preconditions and `If-Match` on DELETE. Apache `mod_dav_fs` 
 > allowed
-> concurrent `If-None-Match: *` creates to succeed and allowed an overwrite 
with
-> a matching weak `If-None-Match`. Nextcloud and ownCloud could reuse an ETag
-> after a same-second overwrite, allowing a stale `If-Match` to overwrite or
-> delete newer content.
+> concurrent `If-None-Match: *` creates to succeed. Nextcloud and ownCloud 
could
+> reuse an ETag after a same-second overwrite, allowing a stale `If-Match` to
+> overwrite or delete newer content.
 >
 > Use `CapabilityOverrideLayer` to disable the affected capabilities. OpenDAL
 > returns `ErrorKind::Unsupported` before sending a conditional write or delete
diff --git a/core/services/webdav/src/backend.rs 
b/core/services/webdav/src/backend.rs
index 2d23de7562..9268363b8f 100644
--- a/core/services/webdav/src/backend.rs
+++ b/core/services/webdav/src/backend.rs
@@ -250,7 +250,7 @@ impl Builder for WebdavBuilder {
 
                 ..Default::default()
             },
-            endpoint: endpoint.to_string(),
+            endpoint: endpoint.trim_end_matches('/').to_string(),
             server_path,
             authorization,
             root,
@@ -478,6 +478,7 @@ mod tests {
         method: String,
         path: String,
         destination: Option<String>,
+        headers: http::HeaderMap,
     }
 
     #[derive(Clone, Default)]
@@ -502,8 +503,8 @@ mod tests {
         async fn fetch(&self, req: Request<Buffer>) -> 
Result<Response<HttpBody>> {
             let method = req.method().as_str().to_string();
             let path = req.uri().path().to_string();
-            let destination = req
-                .headers()
+            let headers = req.headers().clone();
+            let destination = headers
                 .get("Destination")
                 .and_then(|v| v.to_str().ok())
                 .map(str::to_owned);
@@ -512,12 +513,14 @@ mod tests {
                 method: method.clone(),
                 path: path.clone(),
                 destination,
+                headers,
             });
 
             let (status, body) = match (method.as_str(), path.as_str()) {
                 ("PROPFIND", "/src.txt") => (StatusCode::MULTI_STATUS, 
FILE_STAT_RESPONSE),
                 ("PROPFIND", _) => (StatusCode::NOT_FOUND, ""),
                 ("MKCOL", _) | ("COPY", _) | ("MOVE", _) | ("PUT", _) => 
(StatusCode::CREATED, ""),
+                ("DELETE", _) => (StatusCode::NO_CONTENT, ""),
                 _ => (StatusCode::METHOD_NOT_ALLOWED, ""),
             };
 
@@ -533,11 +536,14 @@ mod tests {
         }
     }
 
-    fn test_operator(disable_create_dir: bool) -> Result<(Operator, 
RecordingHttpTransport)> {
+    fn test_operator_with_endpoint(
+        endpoint: &str,
+        disable_create_dir: bool,
+    ) -> Result<(Operator, RecordingHttpTransport)> {
         let transport = RecordingHttpTransport::default();
         let op = Operator::new(
             WebdavBuilder::default()
-                .endpoint("http://localhost:8080";)
+                .endpoint(endpoint)
                 .disable_create_dir(disable_create_dir),
         )?
         .with_context(
@@ -546,6 +552,10 @@ mod tests {
         Ok((op, transport))
     }
 
+    fn test_operator(disable_create_dir: bool) -> Result<(Operator, 
RecordingHttpTransport)> {
+        test_operator_with_endpoint("http://localhost:8080";, 
disable_create_dir)
+    }
+
     #[test]
     fn depth_infinity_is_enabled_by_default() -> Result<()> {
         let service = WebdavBuilder::default()
@@ -700,4 +710,181 @@ mod tests {
         );
         Ok(())
     }
+
+    #[tokio::test]
+    async fn strong_etag_if_match_uses_if_match_header_only() -> Result<()> {
+        let (op, transport) = test_operator(true)?;
+
+        op.write_with("nested/file.txt", "hello")
+            .if_match("\"strong-1\"")
+            .await?;
+        op.delete_with("nested/file.txt")
+            .if_match("\"strong-1\"")
+            .await?;
+
+        let requests = transport.requests();
+        assert_eq!(requests.len(), 2);
+
+        for (req, expected_method) in requests.iter().zip(["PUT", "DELETE"]) {
+            assert_eq!(req.method, expected_method);
+            assert_eq!(
+                req.headers
+                    .get(http::header::IF_MATCH)
+                    .and_then(|v| v.to_str().ok()),
+                Some("\"strong-1\"")
+            );
+            assert!(req.headers.get("If").is_none());
+        }
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn weak_etag_if_match_uses_tagged_dav_if_header_only() -> Result<()> 
{
+        let (op, transport) = 
test_operator_with_endpoint("http://localhost:8080/dav/";, true)?;
+
+        op.write_with("nested/my file.txt", "hello")
+            .if_match(" W/\"weak-1\" ")
+            .await?;
+        op.delete_with("nested/my file.txt")
+            .if_match("W/\"weak-1\"")
+            .await?;
+
+        let requests = transport.requests();
+        assert_eq!(requests.len(), 2);
+
+        let expected_if = "<http://localhost:8080/dav/nested/my%20file.txt> 
([W/\"weak-1\"])";
+        for (req, expected_method) in requests.iter().zip(["PUT", "DELETE"]) {
+            assert_eq!(req.method, expected_method);
+            assert_eq!(req.path, "/dav/nested/my%20file.txt");
+            assert!(req.headers.get(http::header::IF_MATCH).is_none());
+            assert_eq!(req.headers.get_all("If").iter().count(), 1);
+            assert_eq!(
+                req.headers.get("If").and_then(|v| v.to_str().ok()),
+                Some(expected_if)
+            );
+        }
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn 
strong_etag_if_none_match_and_if_not_exists_use_if_none_match_only() -> 
Result<()> {
+        let (op, transport) = test_operator(true)?;
+
+        op.write_with("a.txt", "1")
+            .if_none_match("\"strong-1\"")
+            .await?;
+        op.write_with("b.txt", "2").if_none_match("*").await?;
+        op.write_with("c.txt", "3").if_not_exists(true).await?;
+
+        let requests = transport.requests();
+        assert_eq!(requests.len(), 3);
+
+        for (req, expected) in requests.iter().zip(["\"strong-1\"", "*", "*"]) 
{
+            assert_eq!(req.method, "PUT");
+            assert_eq!(
+                req.headers
+                    .get(http::header::IF_NONE_MATCH)
+                    .and_then(|v| v.to_str().ok()),
+                Some(expected)
+            );
+            assert!(req.headers.get("If").is_none());
+        }
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn weak_etag_if_none_match_uses_if_none_match_and_tagged_dav_if() -> 
Result<()> {
+        let (op, transport) = 
test_operator_with_endpoint("http://localhost:8080/dav/";, true)?;
+
+        op.write_with("nested/file.txt", "hello")
+            .if_none_match(" W/\"weak-1\" ")
+            .await?;
+
+        let requests = transport.requests();
+        assert_eq!(requests.len(), 1);
+        let req = &requests[0];
+        assert_eq!(req.method, "PUT");
+        assert_eq!(
+            req.headers
+                .get(http::header::IF_NONE_MATCH)
+                .and_then(|v| v.to_str().ok()),
+            Some("W/\"weak-1\"")
+        );
+        assert_eq!(req.headers.get_all("If").iter().count(), 1);
+        assert_eq!(
+            req.headers.get("If").and_then(|v| v.to_str().ok()),
+            Some("<http://localhost:8080/dav/nested/file.txt> (Not 
[W/\"weak-1\"])")
+        );
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn 
combined_weak_if_match_and_if_none_match_merges_into_single_dav_if() -> 
Result<()> {
+        let (op, transport) = test_operator(true)?;
+
+        op.write_with("file.txt", "hello")
+            .if_match("W/\"a\"")
+            .if_none_match("W/\"b\"")
+            .await?;
+
+        let requests = transport.requests();
+        assert_eq!(requests.len(), 1);
+        let req = &requests[0];
+        assert!(req.headers.get(http::header::IF_MATCH).is_none());
+        assert_eq!(
+            req.headers
+                .get(http::header::IF_NONE_MATCH)
+                .and_then(|v| v.to_str().ok()),
+            Some("W/\"b\"")
+        );
+        assert_eq!(req.headers.get_all("If").iter().count(), 1);
+        assert_eq!(
+            req.headers.get("If").and_then(|v| v.to_str().ok()),
+            Some("<http://localhost:8080/file.txt> ([W/\"a\"] Not [W/\"b\"])")
+        );
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn invalid_weak_etag_returns_config_invalid_for_put_and_delete() -> 
Result<()> {
+        let (op, transport) = test_operator(true)?;
+
+        for invalid in ["W/\"bad]\"", "W/unquoted", "W/\"a\" \"b\"", "W/\"a"] {
+            let err = op
+                .write_with("file.txt", "hello")
+                .if_match(invalid)
+                .await
+                .unwrap_err();
+            assert_eq!(
+                err.kind(),
+                ErrorKind::ConfigInvalid,
+                "PUT if_match: {invalid}"
+            );
+
+            let err = op
+                .write_with("file.txt", "hello")
+                .if_none_match(invalid)
+                .await
+                .unwrap_err();
+            assert_eq!(
+                err.kind(),
+                ErrorKind::ConfigInvalid,
+                "PUT if_none_match: {invalid}"
+            );
+
+            let err = op
+                .delete_with("file.txt")
+                .if_match(invalid)
+                .await
+                .unwrap_err();
+            assert_eq!(
+                err.kind(),
+                ErrorKind::ConfigInvalid,
+                "DELETE if_match: {invalid}"
+            );
+        }
+
+        assert!(transport.requests().is_empty());
+        Ok(())
+    }
 }
diff --git a/core/services/webdav/src/core.rs b/core/services/webdav/src/core.rs
index 35fffc9017..28a6127e8b 100644
--- a/core/services/webdav/src/core.rs
+++ b/core/services/webdav/src/core.rs
@@ -67,6 +67,14 @@ static HEADER_DEPTH: &str = "Depth";
 ///
 /// reference: [RFC4918: 10.3.  Destination 
Header](https://datatracker.ietf.org/doc/html/rfc4918#section-10.3)
 static HEADER_DESTINATION: &str = "Destination";
+/// The WebDAV `If` header for conditional requests with state tokens or 
entity tags.
+///
+/// Used as a tagged-list precondition (`<{url}> (...)`) for weak ETags on PUT 
and DELETE
+/// because HTTP `If-Match` requires strong comparison and some servers (such 
as Apache
+/// `mod_dav`) also apply strong comparison to `If-None-Match` on non-GET/HEAD 
methods.
+///
+/// reference: [RFC4918: 10.4.  If 
Header](https://datatracker.ietf.org/doc/html/rfc4918#section-10.4)
+static HEADER_IF: &str = "If";
 /// The header to specify the overwrite behavior of the query
 ///
 /// The Overwrite request header specifies whether the server should
@@ -246,27 +254,13 @@ impl WebdavCore {
             req = req.header(header::CONTENT_DISPOSITION, v)
         }
 
-        if let Some(etag) = args.if_match() {
-            if let Some(weak) = etag.strip_prefix("W/") {
-                // The DAV If header expects a single entity tag inside the 
list.
-                let opaque_tag = weak.strip_prefix('"').and_then(|tag| 
tag.strip_suffix('"'));
-                if !opaque_tag.is_some_and(|tag| {
-                    tag.bytes()
-                        .all(|byte| matches!(byte, b'!' | 0x23..=0x7e | 
0x80..=0xff))
-                }) {
-                    return Err(Error::new(ErrorKind::ConfigInvalid, "Invalid 
weak ETag"));
-                }
-                req = req.header("If", format!("([{etag}])"));
-            } else {
-                req = req.header(header::IF_MATCH, etag);
-            }
-        }
-
-        if args.if_not_exists() {
-            req = req.header(header::IF_NONE_MATCH, "*");
-        } else if let Some(etag) = args.if_none_match() {
-            req = req.header(header::IF_NONE_MATCH, etag);
-        }
+        req = apply_etag_preconditions(
+            req,
+            &url,
+            args.if_not_exists(),
+            args.if_match(),
+            args.if_none_match(),
+        )?;
 
         let req = req
             .extension(Operation::Write)
@@ -332,9 +326,7 @@ impl WebdavCore {
             req = req.header(header::AUTHORIZATION, auth.clone())
         }
 
-        if let Some(if_match) = args.if_match() {
-            req = req.header(header::IF_MATCH, if_match);
-        }
+        req = apply_etag_preconditions(req, &url, false, args.if_match(), 
None)?;
 
         let req = req
             .extension(Operation::Delete)
@@ -526,6 +518,66 @@ impl WebdavCore {
     }
 }
 
+fn validate_weak_etag(etag: &str) -> Result<()> {
+    // RFC 9110 §8.8.3 defines entity-tag = [ weak ] DQUOTE *etagc DQUOTE,
+    // where etagc = %x21 / %x23-7E / obs-text. Also reject `]` because
+    // RFC 4918 §10.4.2 wraps entity-tags in `[...]` and servers such as
+    // Apache mod_dav terminate the bracketed token at the first `]`.
+    let opaque_tag = etag
+        .strip_prefix("W/")
+        .and_then(|weak| weak.strip_prefix('"'))
+        .and_then(|tag| tag.strip_suffix('"'));
+    if !opaque_tag.is_some_and(|tag| {
+        tag.bytes()
+            .all(|byte| matches!(byte, b'!' | 0x23..=0x7e | 0x80..=0xff) && 
byte != b']')
+    }) {
+        return Err(Error::new(ErrorKind::ConfigInvalid, "Invalid weak ETag"));
+    }
+    Ok(())
+}
+
+/// Apply ETag preconditions for mutating WebDAV requests (PUT and DELETE).
+///
+/// Strong ETags and `*` use standard HTTP `If-Match` / `If-None-Match` 
headers.
+/// Weak ETags (`W/"..."`) are encoded as a single tagged-list WebDAV `If` 
header
+/// (`<{url}> (...)`) targeting the resource URI so parent collections are not
+/// evaluated on DELETE or new-file PUT. Weak `if_none_match` also retains
+/// `If-None-Match` for non-DAV HTTP servers that implement RFC 9110 weak 
matching.
+fn apply_etag_preconditions(
+    mut req: http::request::Builder,
+    url: &str,
+    if_not_exists: bool,
+    if_match: Option<&str>,
+    if_none_match: Option<&str>,
+) -> Result<http::request::Builder> {
+    let mut dav_if = Vec::new();
+
+    if let Some(etag) = if_match.map(str::trim) {
+        if etag.starts_with("W/") {
+            validate_weak_etag(etag)?;
+            dav_if.push(format!("[{etag}]"));
+        } else {
+            req = req.header(header::IF_MATCH, etag);
+        }
+    }
+
+    if if_not_exists {
+        req = req.header(header::IF_NONE_MATCH, "*");
+    } else if let Some(etag) = if_none_match.map(str::trim) {
+        if etag.starts_with("W/") {
+            validate_weak_etag(etag)?;
+            dav_if.push(format!("Not [{etag}]"));
+        }
+        req = req.header(header::IF_NONE_MATCH, etag);
+    }
+
+    if !dav_if.is_empty() {
+        req = req.header(HEADER_IF, format!("<{url}> ({})", dav_if.join(" ")));
+    }
+
+    Ok(req)
+}
+
 /// Build a PROPPATCH request body to set user-defined metadata.
 ///
 /// The request uses the specified namespace to store metadata as dead 
properties
diff --git a/core/services/webdav/src/docs.md b/core/services/webdav/src/docs.md
index 9bb2d44d7d..61781d117a 100644
--- a/core/services/webdav/src/docs.md
+++ b/core/services/webdav/src/docs.md
@@ -1,10 +1,9 @@
 > **Warning:** Verify conditional writes and deletes against your endpoint 
 > before
 > relying on them. In the tested configurations, nginx’s `ngx_http_dav_module`
 > ignored PUT preconditions and `If-Match` on DELETE. Apache `mod_dav_fs` 
 > allowed
-> concurrent `If-None-Match: *` creates to succeed and allowed an overwrite 
with
-> a matching weak `If-None-Match`. Nextcloud and ownCloud could reuse an ETag
-> after a same-second overwrite, allowing a stale `If-Match` to overwrite or
-> delete newer content.
+> concurrent `If-None-Match: *` creates to succeed. Nextcloud and ownCloud 
could
+> reuse an ETag after a same-second overwrite, allowing a stale `If-Match` to
+> overwrite or delete newer content.
 >
 > Use 
 > [`CapabilityOverrideLayer`][opendal_core::layers::CapabilityOverrideLayer]
 > to disable the affected capabilities. OpenDAL returns
@@ -88,28 +87,31 @@ with per-resource failures, for example on a locked or 
read-only subtree.
 OpenDAL reports that response as an error while some descendants may already
 have been deleted.
 
-### Conditional writes
+### Conditional writes and deletes
 
-OpenDAL sends write preconditions on the PUT that writes the destination file.
-`if_match` uses HTTP `If-Match` for strong ETags and WebDAV `If` for weak 
ETags.
-`if_none_match` uses HTTP `If-None-Match`, and `if_not_exists` uses
-`If-None-Match: *`. OpenDAL reports HTTP 412 as
-[`opendal_core::ErrorKind::ConditionNotMatch`].
+OpenDAL sends write preconditions on the PUT that writes the destination file
+and delete preconditions on the DELETE that removes the target resource.
+`if_match` on PUT and DELETE uses HTTP `If-Match` for strong ETags and a tagged
+WebDAV `If` header (`If: <url> ([W/"..."])`) for weak ETags. `if_none_match` on
+PUT uses HTTP `If-None-Match` for strong ETags, and sends both `If-None-Match`
+and a tagged WebDAV `If` header (`If: <url> (Not [W/"..."])`) for weak ETags.
+`if_not_exists` uses `If-None-Match: *`. OpenDAL reports HTTP 412 (and HTTP 404
+on conditional DELETE) as [`opendal_core::ErrorKind::ConditionNotMatch`].
 
-The three write capabilities are enabled by default. Verify that your endpoint
+These conditional capabilities are enabled by default. Verify that your 
endpoint
 honors the preconditions and preserves the destination on failure. These
 results were observed using real servers and reading back the written files.
 Each concurrent create trial used eight requests against the same missing path.
 
-| Server | `if_match` | `if_none_match` | `if_not_exists` |
+| Server | `if_match` (PUT & DELETE) | `if_none_match` | `if_not_exists` |
 | --- | --- | --- | --- |
-| nginx 1.30.7 with `ngx_http_dav_module` | Ignores both headers and 
overwrites the file. | Ignores the condition and overwrites the file. | Ignores 
the condition. All eight requests succeeded in each trial. |
+| nginx 1.30.7 with `ngx_http_dav_module` | Ignores both headers and 
overwrites or deletes the file. | Ignores the condition and overwrites the 
file. | Ignores the condition. All eight requests succeeded in each trial. |
 | ownCloud 10.16.0 and Nextcloud 35.0.3 (SabreDAV) | Accepts a matching strong 
ETag and rejects a different one. Both reject the weak form and can reuse a 
strong ETag on same-second overwrites, allowing a stale match. | Rejects a 
matching strong ETag. Allows a different ETag or a missing file. | Rejects an 
existing file and creates a missing one. One request succeeded per trial. Other 
requests returned HTTP 412 or 423, or HTTP 404 on Nextcloud. |
-| Apache HTTP Server 2.4.71 with `mod_dav_fs` | Accepts a matching strong or 
weak ETag and rejects a stale tag. | Rejects a matching strong ETag and allows 
creation of a missing file. A matching weak ETag immediately after a write 
allowed an overwrite. | Rejects an existing file sequentially. All eight 
requests succeeded in each concurrent trial. |
+| Apache HTTP Server 2.4.71 with `mod_dav_fs` | Accepts a matching strong or 
weak ETag on PUT and DELETE (including nested paths) and rejects a stale tag or 
missing target. | Rejects a matching strong or weak ETag (including a weak ETag 
after the server upgrades it to a strong ETag) and allows a different ETag or 
creation of a missing file. | Rejects an existing file sequentially. All eight 
requests succeeded in each concurrent trial. |
 | `dav-server` 0.12.0 with `LocalFs` | Accepts a matching strong ETag and 
rejects a different one. A weak form of the current strong tag returned HTTP 
412. | Rejects a matching strong ETag. Allows a different ETag or a missing 
file. | Rejects an existing file and creates a missing one. One request 
succeeded and seven returned HTTP 412 per trial. |
 
-Apache HTTP Server, ownCloud, Nextcloud, and `dav-server` also accepted an
-overwrite when `If-None-Match` supplied the weak form of a current strong ETag.
+ownCloud, Nextcloud, and `dav-server` also accepted an overwrite when
+`if_none_match` supplied the weak form of a current strong ETag.
 
 For the nginx deployment above, use `CapabilityOverrideLayer` to disable all
 four conditional write and delete capabilities.

Reply via email to