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 df84ebab96 fix(services/webdav): validate ranged responses, harden
href/XML parsing, accept 200/202 DELETE, and fix 401/429 mapping (#8958)
df84ebab96 is described below
commit df84ebab96f9970ec900746d535529ad649cbcb0
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 09:05:41 2026 +0800
fix(services/webdav): validate ranged responses, harden href/XML parsing,
accept 200/202 DELETE, and fix 401/429 mapping (#8958)
* fix(services/webdav): validate ranged responses, harden href/XML parsing,
accept 200/202 DELETE, and fix 401/429 mapping
* fix(services/webdav): fix typo and tighten PROPPATCH XML validation
---
core/services/webdav/src/core.rs | 602 ++++++++++++++++++++++++++++--------
core/services/webdav/src/deleter.rs | 74 ++++-
core/services/webdav/src/lister.rs | 300 ++++++++++++++++--
core/services/webdav/src/reader.rs | 302 +++++++++++++++++-
4 files changed, 1124 insertions(+), 154 deletions(-)
diff --git a/core/services/webdav/src/core.rs b/core/services/webdav/src/core.rs
index 4874a63a3a..ff38fda6cf 100644
--- a/core/services/webdav/src/core.rs
+++ b/core/services/webdav/src/core.rs
@@ -25,13 +25,16 @@ use http::Request;
use http::Response;
use http::StatusCode;
use http::header;
-use quick_xml::Reader;
+use quick_xml::NsReader;
use quick_xml::Writer;
use quick_xml::escape::escape;
use quick_xml::events::BytesEnd;
+use quick_xml::events::BytesRef;
use quick_xml::events::BytesStart;
use quick_xml::events::BytesText;
use quick_xml::events::Event;
+use quick_xml::name::Namespace;
+use quick_xml::name::ResolveResult;
use serde::Deserialize;
use opendal_core::raw::*;
@@ -216,7 +219,19 @@ impl WebdavCore {
}
if !range.is_full() {
- req = req.header(header::RANGE, range.to_header());
+ let range_header = range.to_header();
+ if range_header.is_empty() {
+ let mut err = Error::new(
+ ErrorKind::RangeNotSatisfied,
+ "range has no valid HTTP Range header representation",
+ )
+ .with_context("offset", range.offset());
+ if let Some(size) = range.size() {
+ err = err.with_context("size", size);
+ }
+ return Err(err);
+ }
+ req = req.header(header::RANGE, range_header);
}
let req = req
@@ -670,175 +685,291 @@ pub fn build_proppatch_request(
String::from_utf8(writer.into_inner().into_inner()).expect("valid utf8")
}
-/// Parse user metadata from the raw XML response using quick-xml Reader.
+fn is_dav_element(ns: &ResolveResult<'_>, local_name: &str, expected: &str) ->
bool {
+ local_name.eq_ignore_ascii_case(expected)
+ && matches!(
+ ns,
+ ResolveResult::Bound(Namespace("DAV:")) | ResolveResult::Unbound
+ )
+}
+
+fn parse_status_code(status: &str) -> Option<u16> {
+ let mut parts = status.split_whitespace();
+ parts.next()?;
+ parts.next()?.parse::<u16>().ok()
+}
+
+fn decode_general_ref(entity: &BytesRef<'_>, out: &mut String) {
+ match entity.resolve_char_ref() {
+ Ok(Some(ch)) => out.push(ch),
+ Ok(None) => match entity.as_ref() {
+ "lt" => out.push('<'),
+ "gt" => out.push('>'),
+ "amp" => out.push('&'),
+ "quot" => out.push('"'),
+ "apos" => out.push('\''),
+ _ => {}
+ },
+ Err(_) => {}
+ }
+}
+
+/// Parse user metadata from the raw XML response using quick-xml NsReader.
///
-/// This function extracts properties in the specified namespace
-/// from the PROPFIND response and returns them as a HashMap.
+/// This function extracts properties in the specified namespace from 2xx
+/// `<D:propstat>` blocks of the first `<D:response>` in the PROPFIND response
+/// and returns them as a HashMap.
///
/// Note: WebDAV servers like Nextcloud/ownCloud may use dynamic namespace
prefixes
-/// (e.g., x1:, x2:) instead of the prefix we send. The namespace URI is the
-/// reliable identifier, not the prefix.
+/// (e.g., x1:, x2:) or default namespaces instead of the prefix we send. The
+/// namespace URI is the reliable identifier, not the prefix.
///
/// # Arguments
/// * `xml` - The raw XML response string
/// * `namespace_uri` - The namespace URI to look for
pub fn parse_user_metadata_from_xml(xml: &str, namespace_uri: &str) ->
HashMap<String, String> {
let mut user_metadata = HashMap::new();
- let mut reader = Reader::from_str(xml);
- reader.config_mut().trim_text(true);
+ let mut reader = NsReader::from_str(xml);
- // Track namespace prefix -> URI mappings
- let mut ns_prefixes: HashMap<String, String> = HashMap::new();
- // Track which prefixes map to our target namespace URI
- let mut target_prefixes: Vec<String> = Vec::new();
-
- // Current element state for tracking property values
- let mut current_prop_key: Option<String> = None;
+ let mut depth: usize = 0;
+ let mut response_depth: Option<usize> = None;
+ let mut propstat_depth: Option<usize> = None;
+ let mut prop_depth: Option<usize> = None;
+ let mut in_status = false;
+ let mut status_text = String::new();
+ let mut propstat_status: Option<u16> = None;
+ let mut propstat_props: HashMap<String, String> = HashMap::new();
+ let mut current_prop: Option<(String, usize)> = None;
let mut current_prop_value = String::new();
- let mut buf = Vec::new();
loop {
- let event = reader.read_event_into(&mut buf);
- match event {
- Ok(Event::Start(ref e)) => {
- // Extract namespace declarations from attributes
- for attr in e.attributes().flatten() {
- let key = attr.key.as_ref().to_string();
- if key.starts_with("xmlns:") {
- let prefix =
key.strip_prefix("xmlns:").unwrap_or("").to_string();
- let uri = attr.value.to_string();
- if uri == namespace_uri &&
!target_prefixes.contains(&prefix) {
- target_prefixes.push(prefix.clone());
- }
- ns_prefixes.insert(prefix, uri);
- }
- }
-
- // Check if this element is in our target namespace
- let name = e.name().as_ref().to_string();
- if let Some(colon_pos) = name.find(':') {
- let prefix = &name[..colon_pos];
- let local_name = &name[colon_pos + 1..];
- if target_prefixes.contains(&prefix.to_string()) {
- current_prop_key = Some(local_name.to_string());
+ match reader.read_resolved_event() {
+ Ok((ns, Event::Start(e))) => {
+ depth += 1;
+ let local_name = e.local_name();
+ let local_name = local_name.into_inner();
+
+ if response_depth.is_none() && is_dav_element(&ns, local_name,
"response") {
+ response_depth = Some(depth);
+ } else if propstat_depth.is_none() && is_dav_element(&ns,
local_name, "propstat") {
+ propstat_depth = Some(depth);
+ prop_depth = None;
+ in_status = false;
+ status_text.clear();
+ propstat_status = None;
+ propstat_props.clear();
+ } else if let Some(ps_d) = propstat_depth {
+ if depth == ps_d + 1 && is_dav_element(&ns, local_name,
"prop") {
+ prop_depth = Some(depth);
+ } else if depth == ps_d + 1 && is_dav_element(&ns,
local_name, "status") {
+ in_status = true;
+ status_text.clear();
+ } else if let Some(p_d) = prop_depth
+ && depth == p_d + 1
+ && matches!(ns, ResolveResult::Bound(Namespace(uri))
if uri == namespace_uri)
+ {
+ current_prop = Some((local_name.to_string(), depth));
current_prop_value.clear();
}
}
}
- Ok(Event::Empty(ref e)) => {
- // Extract namespace declarations from attributes
- for attr in e.attributes().flatten() {
- let key = attr.key.as_ref().to_string();
- if key.starts_with("xmlns:") {
- let prefix =
key.strip_prefix("xmlns:").unwrap_or("").to_string();
- let uri = attr.value.to_string();
- if uri == namespace_uri &&
!target_prefixes.contains(&prefix) {
- target_prefixes.push(prefix.clone());
- }
- ns_prefixes.insert(prefix, uri);
- }
+ Ok((ns, Event::Empty(e))) => {
+ let elem_depth = depth + 1;
+ if let Some(p_d) = prop_depth
+ && elem_depth == p_d + 1
+ && matches!(ns, ResolveResult::Bound(Namespace(uri)) if
uri == namespace_uri)
+ {
+
propstat_props.insert(e.local_name().into_inner().to_string(), String::new());
}
-
- // For Empty events (self-closing tags), immediately insert
with empty value
- let name = e.name().as_ref().to_string();
- if let Some(colon_pos) = name.find(':') {
- let prefix = &name[..colon_pos];
- let local_name = &name[colon_pos + 1..];
- if target_prefixes.contains(&prefix.to_string()) {
- user_metadata.insert(local_name.to_string(),
String::new());
- }
+ }
+ Ok((_, Event::Text(e))) => {
+ if current_prop.is_some() {
+ current_prop_value.push_str(e.as_ref());
+ } else if in_status {
+ status_text.push_str(e.as_ref());
}
}
- Ok(Event::Text(ref e)) if current_prop_key.is_some() => {
- // Text content - add directly (no escaping needed)
- current_prop_value.push_str(e.as_ref());
+ Ok((_, Event::CData(e))) => {
+ if current_prop.is_some() {
+ current_prop_value.push_str(e.as_ref());
+ } else if in_status {
+ status_text.push_str(e.as_ref());
+ }
}
- Ok(Event::GeneralRef(ref e)) if current_prop_key.is_some() => {
- // Handle XML entity references (e.g., < > & "
')
- let decoded = match e.as_ref() {
- "lt" => "<",
- "gt" => ">",
- "amp" => "&",
- "quot" => "\"",
- "apos" => "'",
- _ => "", // Unknown entity, skip
- };
- current_prop_value.push_str(decoded);
+ Ok((_, Event::GeneralRef(e))) => {
+ if current_prop.is_some() {
+ decode_general_ref(&e, &mut current_prop_value);
+ } else if in_status {
+ decode_general_ref(&e, &mut status_text);
+ }
}
- Ok(Event::End(ref e)) => {
- let name = e.name().as_ref().to_string();
- if let Some(colon_pos) = name.find(':') {
- let prefix = &name[..colon_pos];
- let local_name = &name[colon_pos + 1..];
- if target_prefixes.contains(&prefix.to_string())
- && let Some(key) = current_prop_key.take()
- && key == local_name
- {
- user_metadata.insert(key, current_prop_value.clone());
- current_prop_value.clear();
+ Ok((_, Event::End(_))) => {
+ if let Some((_, prop_elem_depth)) = ¤t_prop
+ && *prop_elem_depth == depth
+ && let Some((key, _)) = current_prop.take()
+ {
+ propstat_props.insert(key, std::mem::take(&mut
current_prop_value));
+ } else if in_status && propstat_depth.is_some_and(|ps_d| depth
== ps_d + 1) {
+ propstat_status = parse_status_code(&status_text);
+ in_status = false;
+ } else if prop_depth == Some(depth) {
+ prop_depth = None;
+ } else if propstat_depth == Some(depth) {
+ if propstat_status.is_some_and(|code|
(200..300).contains(&code)) {
+ user_metadata.extend(propstat_props.drain());
+ } else {
+ propstat_props.clear();
}
+ propstat_depth = None;
+ prop_depth = None;
+ in_status = false;
+ propstat_status = None;
+ } else if response_depth == Some(depth) {
+ break;
}
+ depth = depth.saturating_sub(1);
}
- Ok(Event::Eof) => break,
+ Ok((_, Event::Eof)) => break,
Err(_) => break,
_ => {}
}
- buf.clear();
}
user_metadata
}
-/// Check if a PROPPATCH 207 Multi-Status response indicates success using
quick-xml Reader.
+/// Check if a PROPPATCH 207 Multi-Status response indicates success using
quick-xml NsReader.
///
/// A 207 status code only indicates that there is detailed information
available,
/// not success or failure. We need to parse the response body to check if all
-/// property updates were successful (status 200).
+/// property updates were successful (2xx status).
///
-/// Returns Ok(()) if all properties were successfully updated, or an error
-/// with details about the failure.
+/// Returns Ok(()) if the XML is well-formed, every `<D:propstat>` contains a
+/// `<D:status>`, and all reported `<D:status>` elements succeeded with a 2xx
+/// status code, or an error otherwise.
pub fn check_proppatch_response(xml: &str) -> Result<()> {
- let mut reader = Reader::from_str(xml);
- reader.config_mut().trim_text(true);
+ let mut reader = NsReader::from_str(xml);
- let mut buf = Vec::new();
- let mut in_status = false;
+ let mut depth: usize = 0;
+ let mut root_closed = false;
+ let mut propstat_depth: Option<usize> = None;
+ let mut propstat_has_status = false;
+ let mut status_depth: Option<usize> = None;
let mut status_text = String::new();
+ let mut has_status = false;
loop {
- match reader.read_event_into(&mut buf) {
- Ok(Event::Start(ref e)) => {
- let name = e.name().as_ref().to_lowercase();
- // Match status element regardless of namespace prefix
- if name.ends_with(":status") || name == "status" {
- in_status = true;
+ match reader.read_resolved_event() {
+ Ok((ns, Event::Start(e))) => {
+ if root_closed {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "PROPPATCH response XML has trailing element after
root",
+ ));
+ }
+ depth += 1;
+ let local_name = e.local_name();
+ let local_name = local_name.into_inner();
+ if propstat_depth.is_none() && is_dav_element(&ns, local_name,
"propstat") {
+ propstat_depth = Some(depth);
+ propstat_has_status = false;
+ } else if status_depth.is_none() && is_dav_element(&ns,
local_name, "status") {
+ status_depth = Some(depth);
status_text.clear();
}
}
- Ok(Event::Text(ref e)) if in_status => {
+ Ok((ns, Event::Empty(e))) => {
+ if root_closed {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "PROPPATCH response XML has trailing element after
root",
+ ));
+ }
+ let local_name = e.local_name();
+ let local_name = local_name.into_inner();
+ if is_dav_element(&ns, local_name, "status") {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "PROPPATCH response has empty status",
+ ));
+ }
+ if is_dav_element(&ns, local_name, "propstat") {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "PROPPATCH response propstat missing status",
+ ));
+ }
+ if depth == 0 {
+ root_closed = true;
+ }
+ }
+ Ok((_, Event::Text(e))) if status_depth.is_some() => {
status_text.push_str(e.as_ref());
}
- Ok(Event::End(ref e)) => {
- let name = e.name().as_ref().to_lowercase();
- if name.ends_with(":status") || name == "status" {
- // Parse status code from "HTTP/1.1 XXX Description"
- if let Some(code_str) =
status_text.split_whitespace().nth(1)
- && let Ok(code) = code_str.parse::<u16>()
- && !(200..300).contains(&code)
- {
+ Ok((_, Event::GeneralRef(e))) if status_depth.is_some() => {
+ decode_general_ref(&e, &mut status_text);
+ }
+ Ok((_, Event::End(_))) => {
+ if status_depth == Some(depth) {
+ let Some(code) = parse_status_code(&status_text) else {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ format!(
+ "PROPPATCH response has invalid status: {}",
+ status_text.trim()
+ ),
+ ));
+ };
+ if !(200..300).contains(&code) {
return Err(Error::new(
ErrorKind::Unexpected,
- format!("PROPPATCH failed with status:
{status_text}"),
+ format!("PROPPATCH failed with status: {}",
status_text.trim()),
));
}
- in_status = false;
+ has_status = true;
+ if propstat_depth.is_some_and(|ps_d| depth == ps_d + 1) {
+ propstat_has_status = true;
+ }
+ status_depth = None;
+ } else if propstat_depth == Some(depth) {
+ if !propstat_has_status {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "PROPPATCH response propstat missing status",
+ ));
+ }
+ propstat_depth = None;
+ propstat_has_status = false;
+ }
+ depth = depth.saturating_sub(1);
+ if depth == 0 {
+ root_closed = true;
}
}
- Ok(Event::Eof) => break,
- Err(_) => break,
+ Ok((_, Event::Eof)) => break,
+ Err(err) => {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "parse webdav proppatch response xml",
+ )
+ .set_source(err));
+ }
_ => {}
}
- buf.clear();
+ }
+
+ if depth != 0 {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "PROPPATCH response XML is truncated",
+ ));
+ }
+
+ if !has_status {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "PROPPATCH response missing status",
+ ));
}
Ok(())
@@ -895,7 +1026,7 @@ pub fn parse_propstat(propstat: &Propstat) ->
Result<Metadata> {
));
}
- let mode: EntryMode = if resourcetype.value ==
Some(ResourceType::Collection) {
+ let mode: EntryMode = if resourcetype.collection.is_some() {
EntryMode::DIR
} else {
EntryMode::FILE
@@ -984,15 +1115,11 @@ pub struct Prop {
#[derive(Deserialize, Debug, PartialEq, Eq, Clone, Default)]
pub struct ResourceTypeContainer {
- #[serde(rename = "$value")]
- pub value: Option<ResourceType>,
+ pub collection: Option<Collection>,
}
-#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
-#[serde(rename_all = "lowercase")]
-pub enum ResourceType {
- Collection,
-}
+#[derive(Deserialize, Debug, PartialEq, Eq, Clone, Default)]
+pub struct Collection {}
#[cfg(test)]
mod tests {
@@ -1008,7 +1135,7 @@ mod tests {
getetag: None,
getcontentlength: getcontentlength.map(str::to_string),
getcontenttype: None,
- resourcetype: ResourceTypeContainer { value: None },
+ resourcetype: ResourceTypeContainer::default(),
},
}
}
@@ -1036,10 +1163,7 @@ mod tests {
propstat.prop.getlastmodified.as_deref(),
Some("Tue, 01 May 2022 06:39:47 GMT")
);
- assert_eq!(
- propstat.prop.resourcetype.value,
- Some(ResourceType::Collection)
- );
+ assert!(propstat.prop.resourcetype.collection.is_some());
assert_eq!(propstat.status, "HTTP/1.1 200 OK");
}
@@ -1089,10 +1213,7 @@ mod tests {
response.propstat[0].prop.getlastmodified.as_deref(),
Some("Tue, 01 May 2022 06:39:47 GMT")
);
- assert_eq!(
- response.propstat[0].prop.resourcetype.value,
- Some(ResourceType::Collection)
- );
+ assert!(response.propstat[0].prop.resourcetype.collection.is_some());
assert_eq!(response.propstat[0].status, "HTTP/1.1 200 OK");
}
@@ -1132,7 +1253,7 @@ mod tests {
response.propstat[0].prop.getcontentlength.as_deref(),
Some("1")
);
- assert_eq!(response.propstat[0].prop.resourcetype.value, None);
+ assert_eq!(response.propstat[0].prop.resourcetype.collection, None);
assert_eq!(response.propstat[0].status, "HTTP/1.1 200 OK");
}
@@ -1746,6 +1867,217 @@ mod tests {
);
assert_eq!(err.kind(), ErrorKind::ConditionNotMatch);
}
+
+ #[test]
+ fn test_parse_error_maps_401_and_429() {
+ let resp_401 = Response::builder()
+ .status(StatusCode::UNAUTHORIZED)
+ .body(Buffer::from("unauthorized"))
+ .unwrap();
+ let err_401 = parse_error(ErrorContext::new(ServiceOperation("Get")),
resp_401);
+ assert_eq!(err_401.kind(), ErrorKind::PermissionDenied);
+ assert!(!err_401.is_temporary());
+
+ let resp_429 = Response::builder()
+ .status(StatusCode::TOO_MANY_REQUESTS)
+ .body(Buffer::from("rate limited"))
+ .unwrap();
+ let err_429 = parse_error(ErrorContext::new(ServiceOperation("Get")),
resp_429);
+ assert_eq!(err_429.kind(), ErrorKind::RateLimited);
+ assert!(err_429.is_temporary());
+ }
+
+ #[test]
+ fn test_deserialize_extension_resourcetype_elements() {
+ let xml = r#"<?xml version="1.0" encoding="utf-8"?>
+ <D:multistatus xmlns:D="DAV:"
xmlns:cal="urn:ietf:params:xml:ns:caldav"
xmlns:card="urn:ietf:params:xml:ns:carddav">
+ <D:response>
+ <D:href>/calendar/</D:href>
+ <D:propstat>
+ <D:prop>
+ <D:getlastmodified>Sat, 07 May 2022 06:39:47
GMT</D:getlastmodified>
+ <D:resourcetype><D:collection/><cal:calendar/></D:resourcetype>
+ </D:prop>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ </D:propstat>
+ </D:response>
+ <D:response>
+ <D:href>/addressbook/</D:href>
+ <D:propstat>
+ <D:prop>
+ <D:getlastmodified>Sat, 07 May 2022 06:39:47
GMT</D:getlastmodified>
+ <D:resourcetype>
+ <card:addressbook><card:nested/></card:addressbook>
+ <D:collection xmlns:D="DAV:"/>
+ </D:resourcetype>
+ </D:prop>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ </D:propstat>
+ </D:response>
+ <D:response>
+ <D:href>/principal</D:href>
+ <D:propstat>
+ <D:prop>
+ <D:getcontentlength>42</D:getcontentlength>
+ <D:getlastmodified>Sat, 07 May 2022 06:39:47
GMT</D:getlastmodified>
+ <D:resourcetype><D:principal/></D:resourcetype>
+ </D:prop>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ </D:propstat>
+ </D:response>
+ </D:multistatus>"#;
+
+ let ms = deserialize_multistatus(xml.as_bytes()).unwrap();
+ assert_eq!(ms.response.len(), 3);
+
+ let cal_meta = parse_propstats(&ms.response[0].propstat).unwrap();
+ assert!(cal_meta.is_dir());
+
+ let card_meta = parse_propstats(&ms.response[1].propstat).unwrap();
+ assert!(card_meta.is_dir());
+
+ let principal_meta =
parse_propstats(&ms.response[2].propstat).unwrap();
+ assert!(principal_meta.is_file());
+ assert_eq!(principal_meta.content_length(), 42);
+ }
+
+ #[test]
+ fn test_parse_user_metadata_preserves_whitespace_entities_and_char_refs() {
+ let xml = r#"<?xml version="1.0" encoding="utf-8"?>
+ <D:multistatus xmlns:D="DAV:"
xmlns:opendal="https://opendal.apache.org/ns">
+ <D:response>
+ <D:propstat>
+ <D:prop>
+ <opendal:spaced>hello & world</opendal:spaced>
+ <opendal:padded> keep spaces </opendal:padded>
+ <opendal:numref>a b
c😀</opendal:numref>
+ <opendal:cdata><![CDATA[ raw & <text> ]]></opendal:cdata>
+ </D:prop>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ </D:propstat>
+ </D:response>
+ </D:multistatus>"#;
+
+ let user_metadata = parse_user_metadata_from_xml(xml,
DEFAULT_USER_METADATA_URI);
+
+ assert_eq!(
+ user_metadata.get("spaced").map(String::as_str),
+ Some("hello & world")
+ );
+ assert_eq!(
+ user_metadata.get("padded").map(String::as_str),
+ Some(" keep spaces ")
+ );
+ assert_eq!(
+ user_metadata.get("numref").map(String::as_str),
+ Some(
+ "a
+b
+c😀"
+ )
+ );
+ assert_eq!(
+ user_metadata.get("cdata").map(String::as_str),
+ Some(" raw & <text> ")
+ );
+ }
+
+ #[test]
+ fn test_parse_user_metadata_default_namespace_scoping_and_404_filtering() {
+ let xml = r#"<?xml version="1.0" encoding="utf-8"?>
+ <D:multistatus xmlns:D="DAV:" xmlns:x="https://opendal.apache.org/ns">
+ <D:response>
+ <D:propstat>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ <D:prop>
+ <defns xmlns="https://opendal.apache.org/ns">seen</defns>
+ <empty_defns xmlns="https://opendal.apache.org/ns"/>
+ <x:kept>yes</x:kept>
+ <x:shadowed
xmlns:x="https://other.example.com/ns">no</x:shadowed>
+ </D:prop>
+ </D:propstat>
+ <D:propstat>
+ <D:prop>
+ <x:missing/>
+ <x:denied>secret</x:denied>
+ <def_missing xmlns="https://opendal.apache.org/ns"/>
+ </D:prop>
+ <D:status>HTTP/1.1 404 Not Found</D:status>
+ </D:propstat>
+ </D:response>
+ <D:response>
+ <D:propstat>
+ <D:prop>
+ <x:second_response>ignored</x:second_response>
+ </D:prop>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ </D:propstat>
+ </D:response>
+ </D:multistatus>"#;
+
+ let user_metadata = parse_user_metadata_from_xml(xml,
DEFAULT_USER_METADATA_URI);
+
+ assert_eq!(user_metadata.len(), 3);
+ assert_eq!(user_metadata.get("defns").map(String::as_str),
Some("seen"));
+ assert_eq!(
+ user_metadata.get("empty_defns").map(String::as_str),
+ Some("")
+ );
+ assert_eq!(user_metadata.get("kept").map(String::as_str), Some("yes"));
+ assert!(!user_metadata.contains_key("shadowed"));
+ assert!(!user_metadata.contains_key("missing"));
+ assert!(!user_metadata.contains_key("denied"));
+ assert!(!user_metadata.contains_key("def_missing"));
+ assert!(!user_metadata.contains_key("second_response"));
+ }
+
+ #[test]
+ fn
test_check_proppatch_response_rejects_malformed_truncated_and_missing_status() {
+ let invalid_cases = [
+ // Malformed closing tag
+ r#"<D:multistatus
xmlns:D="DAV:"><D:response></D:wrong></D:multistatus>"#,
+ // Syntax error inside tag
+ r#"<D:multistatus xmlns:D="DAV:"><D:response"#,
+ // Truncated after 200 OK status before closing tags
+ r#"<D:multistatus
xmlns:D="DAV:"><D:response><D:propstat><D:status>HTTP/1.1 200 OK</D:status>"#,
+ // Missing any status element
+ r#"<D:multistatus
xmlns:D="DAV:"><D:response><D:propstat><D:prop/></D:propstat></D:response></D:multistatus>"#,
+ // Empty body
+ "",
+ // Self-closing empty status element
+ r#"<D:multistatus
xmlns:D="DAV:"><D:response><D:propstat><D:status/></D:propstat></D:response></D:multistatus>"#,
+ // Unparsable status line
+ r#"<D:multistatus
xmlns:D="DAV:"><D:response><D:propstat><D:status>broken</D:status></D:propstat></D:response></D:multistatus>"#,
+ // Mixed 200 and 424 propstats
+ r#"<D:multistatus
xmlns:D="DAV:"><D:response><D:propstat><D:status>HTTP/1.1 200
OK</D:status></D:propstat><D:propstat><D:status>HTTP/1.1 424 Failed
Dependency</D:status></D:propstat></D:response></D:multistatus>"#,
+ // One 200 propstat alongside another propstat missing status
+ r#"<D:multistatus
xmlns:D="DAV:"><D:response><D:propstat><D:status>HTTP/1.1 200
OK</D:status></D:propstat><D:propstat><D:prop/></D:propstat></D:response></D:multistatus>"#,
+ // One 200 propstat alongside a self-closing empty propstat
+ r#"<D:multistatus
xmlns:D="DAV:"><D:response><D:propstat><D:status>HTTP/1.1 200
OK</D:status></D:propstat><D:propstat/></D:response></D:multistatus>"#,
+ // Trailing start element after root closes
+ r#"<D:multistatus
xmlns:D="DAV:"><D:response><D:propstat><D:status>HTTP/1.1 200
OK</D:status></D:propstat></D:response></D:multistatus><extra></extra>"#,
+ // Trailing empty element after root closes
+ r#"<D:multistatus
xmlns:D="DAV:"><D:response><D:propstat><D:status>HTTP/1.1 200
OK</D:status></D:propstat></D:response></D:multistatus><extra/>"#,
+ ];
+
+ for xml in invalid_cases {
+ let err = check_proppatch_response(xml)
+ .expect_err(&format!("proppatch XML must fail: {xml}"));
+ assert_eq!(err.kind(), ErrorKind::Unexpected, "{xml}");
+ }
+
+ // Default DAV: namespace and non-DAV <status> element inside <prop>
must still succeed.
+ let valid_default_ns = r#"<?xml version="1.0" encoding="utf-8"?>
+ <multistatus xmlns="DAV:"
xmlns:opendal="https://opendal.apache.org/ns">
+ <response>
+ <propstat>
+ <prop><opendal:status>HTTP/1.1 500
Ignored</opendal:status></prop>
+ <status>HTTP/1.1 200 OK</status>
+ </propstat>
+ </response>
+ </multistatus>"#;
+ assert!(check_proppatch_response(valid_default_ns).is_ok());
+ }
}
/// Context needed to classify an error from this service.
@@ -1778,6 +2110,7 @@ pub(crate) fn parse_error(ctx: ErrorContext, resp:
Response<Buffer>) -> Error {
let (kind, retryable) = match parts.status {
StatusCode::NOT_FOUND => (ErrorKind::NotFound, false),
+ StatusCode::UNAUTHORIZED => (ErrorKind::PermissionDenied, false),
// Some services (like owncloud) return 403 while file locked.
StatusCode::FORBIDDEN => (ErrorKind::PermissionDenied, true),
// RFC 7232: 412 means an If-Match / If-Unmodified-Since
@@ -1793,6 +2126,7 @@ pub(crate) fn parse_error(ctx: ErrorContext, resp:
Response<Buffer>) -> Error {
(ErrorKind::ConditionNotMatch, false)
}
StatusCode::RANGE_NOT_SATISFIABLE => (ErrorKind::RangeNotSatisfied,
false),
+ StatusCode::TOO_MANY_REQUESTS => (ErrorKind::RateLimited, true),
// Allowing retry for resource locked.
StatusCode::LOCKED => (ErrorKind::Unexpected, true),
StatusCode::INTERNAL_SERVER_ERROR
diff --git a/core/services/webdav/src/deleter.rs
b/core/services/webdav/src/deleter.rs
index 9940d989ad..4e981407bd 100644
--- a/core/services/webdav/src/deleter.rs
+++ b/core/services/webdav/src/deleter.rs
@@ -42,7 +42,7 @@ impl oio::OneShotDelete for WebdavDeleter {
let status = resp.status();
match status {
- StatusCode::NO_CONTENT => Ok(()),
+ StatusCode::OK | StatusCode::ACCEPTED | StatusCode::NO_CONTENT =>
Ok(()),
StatusCode::NOT_FOUND if args.if_match().is_some() =>
Err(Error::new(
ErrorKind::ConditionNotMatch,
"delete precondition requires a live target",
@@ -58,3 +58,75 @@ impl oio::OneShotDelete for WebdavDeleter {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use futures::stream;
+ use http::{Request, Response, StatusCode};
+
+ use super::super::backend::WebdavBuilder;
+ use super::*;
+
+ struct FixedStatusTransport {
+ status: StatusCode,
+ }
+
+ impl HttpTransport for FixedStatusTransport {
+ async fn fetch(&self, _req: Request<Buffer>) ->
Result<Response<HttpBody>> {
+ Ok(Response::builder()
+ .status(self.status)
+ .body(HttpBody::new(stream::empty(), Some(0)))
+ .unwrap())
+ }
+ }
+
+ fn operator_with_status(status: StatusCode) -> Result<Operator> {
+ Ok(
+
Operator::new(WebdavBuilder::default().endpoint("http://localhost:8080"))?
+ .with_context(
+ OperationContext::new()
+
.with_http_transport(HttpTransporter::new(FixedStatusTransport { status })),
+ ),
+ )
+ }
+
+ #[tokio::test]
+ async fn test_delete_accepts_200_202_204_and_404() -> Result<()> {
+ for status in [
+ StatusCode::OK,
+ StatusCode::ACCEPTED,
+ StatusCode::NO_CONTENT,
+ StatusCode::NOT_FOUND,
+ ] {
+ let op = operator_with_status(status)?;
+ op.delete("file.txt").await?;
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_delete_maps_401_and_429_and_conditional_404() -> Result<()> {
+ let err = operator_with_status(StatusCode::UNAUTHORIZED)?
+ .delete("file.txt")
+ .await
+ .unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::PermissionDenied);
+ assert!(!err.is_temporary());
+
+ let err = operator_with_status(StatusCode::TOO_MANY_REQUESTS)?
+ .delete("file.txt")
+ .await
+ .unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::RateLimited);
+ assert!(err.is_temporary());
+
+ let err = operator_with_status(StatusCode::NOT_FOUND)?
+ .delete_with("file.txt")
+ .if_match("\"etag\"")
+ .await
+ .unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::ConditionNotMatch);
+
+ Ok(())
+ }
+}
diff --git a/core/services/webdav/src/lister.rs
b/core/services/webdav/src/lister.rs
index 042ae5e4db..8f8bf56872 100644
--- a/core/services/webdav/src/lister.rs
+++ b/core/services/webdav/src/lister.rs
@@ -41,6 +41,79 @@ impl WebdavLister {
args,
}
}
+
+ fn resolve_href(&self, href: &str, is_dir: bool) -> Result<String> {
+ let raw_path = extract_href_path(href);
+ if !raw_path.starts_with('/') {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "webdav propfind href is not an absolute path or URI",
+ )
+ .with_context("href", href));
+ }
+
+ let stripped = if self.core.server_path.is_empty() {
+ raw_path
+ } else if raw_path == self.core.server_path {
+ ""
+ } else if let Some(rest) =
raw_path.strip_prefix(&self.core.server_path)
+ && rest.starts_with('/')
+ {
+ rest
+ } else {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "webdav propfind href does not start with server path",
+ )
+ .with_context("href", href)
+ .with_context("server_path", &self.core.server_path));
+ };
+
+ let mut path = percent_decode_path(stripped);
+
+ // Append `/` to path if it's a dir
+ if !path.ends_with('/') && is_dir {
+ path.push('/');
+ }
+
+ if path == self.core.root {
+ return Ok("/".to_owned());
+ }
+
+ match path.strip_prefix(&self.core.root) {
+ Some(rel) => Ok(rel.to_owned()),
+ None => Err(Error::new(
+ ErrorKind::Unexpected,
+ "webdav propfind href is outside configured root",
+ )
+ .with_context("href", href)
+ .with_context("root", &self.core.root)),
+ }
+ }
+}
+
+/// Extract the URI path component from a WebDAV `<D:href>` value.
+///
+/// Per RFC 4918 §8.3, `href` may be either a `path-absolute` (e.g.
`/dav/file`)
+/// or an `absolute-URI` (e.g. `https://host/dav/file`).
+fn extract_href_path(href: &str) -> &str {
+ if let Some((scheme, rest)) = href.split_once("://")
+ && scheme
+ .as_bytes()
+ .first()
+ .is_some_and(u8::is_ascii_alphabetic)
+ && scheme
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' |
b'.'))
+ {
+ let authority_and_path = rest.split(['?', '#']).next().unwrap_or("");
+ return match authority_and_path.find('/') {
+ Some(idx) => &authority_and_path[idx..],
+ None => "/",
+ };
+ }
+
+ href
}
impl oio::PageList for WebdavLister {
@@ -81,25 +154,8 @@ impl oio::PageList for WebdavLister {
let result: Multistatus = deserialize_multistatus(&bs.to_bytes())?;
for res in result.response {
- let mut path = res
- .href
- .strip_prefix(&self.core.server_path)
- .unwrap_or(&res.href)
- .to_string();
-
let meta = parse_propstats(&res.propstat)?;
-
- // Append `/` to path if it's a dir
- if !path.ends_with('/') && meta.is_dir() {
- path += "/"
- }
-
- let decoded_path = percent_decode_path(&path);
- let normalized_path = if self.core.root != decoded_path {
- build_relative_path(&self.core.root, &decoded_path)
- } else {
- "/".to_owned()
- };
+ let normalized_path = self.resolve_href(&res.href, meta.is_dir())?;
if directory != self.path &&
!normalized_path.starts_with(&self.path) {
continue;
@@ -122,3 +178,211 @@ impl oio::PageList for WebdavLister {
Ok(())
}
}
+
+#[cfg(test)]
+mod tests {
+ use bytes::Bytes;
+ use futures::stream;
+ use http::{Request, Response, StatusCode};
+
+ use super::super::backend::WebdavBuilder;
+ use super::*;
+
+ struct StaticPropfindTransport {
+ body: String,
+ }
+
+ impl HttpTransport for StaticPropfindTransport {
+ async fn fetch(&self, _req: Request<Buffer>) ->
Result<Response<HttpBody>> {
+ let data = Bytes::from(self.body.clone());
+ let size = data.len() as u64;
+ Ok(Response::builder()
+ .status(StatusCode::MULTI_STATUS)
+ .body(HttpBody::new(
+ stream::iter([Ok(Buffer::from(data))]),
+ Some(size),
+ ))
+ .unwrap())
+ }
+ }
+
+ fn operator_with_propfind(endpoint: &str, root: &str, xml: &str) ->
Result<Operator> {
+ Ok(
+
Operator::new(WebdavBuilder::default().endpoint(endpoint).root(root))?.with_context(
+
OperationContext::new().with_http_transport(HttpTransporter::new(
+ StaticPropfindTransport {
+ body: xml.to_string(),
+ },
+ )),
+ ),
+ )
+ }
+
+ #[tokio::test]
+ async fn
test_list_handles_absolute_href_uris_and_extension_resourcetypes() ->
Result<()> {
+ let xml = r#"<?xml version="1.0" encoding="utf-8"?>
+ <D:multistatus xmlns:D="DAV:"
xmlns:cal="urn:ietf:params:xml:ns:caldav">
+ <D:response>
+ <D:href>http://localhost:8080/dav/sub</D:href>
+ <D:propstat>
+ <D:prop>
+ <D:getlastmodified>Sat, 07 May 2022 06:39:47
GMT</D:getlastmodified>
+ <D:resourcetype><D:collection/></D:resourcetype>
+ </D:prop>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ </D:propstat>
+ </D:response>
+ <D:response>
+
<D:href>https://proxy.example.com/dav/sub/my%20file.txt?rev=1#frag</D:href>
+ <D:propstat>
+ <D:prop>
+ <D:getcontentlength>12</D:getcontentlength>
+ <D:getlastmodified>Sat, 07 May 2022 06:40:10
GMT</D:getlastmodified>
+ <D:resourcetype><D:principal/></D:resourcetype>
+ </D:prop>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ </D:propstat>
+ </D:response>
+ <D:response>
+ <D:href>http://localhost:8080/dav/sub/calendar</D:href>
+ <D:propstat>
+ <D:prop>
+ <D:getlastmodified>Sat, 07 May 2022 06:40:10
GMT</D:getlastmodified>
+ <D:resourcetype><D:collection/><cal:calendar/></D:resourcetype>
+ </D:prop>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ </D:propstat>
+ </D:response>
+ </D:multistatus>"#;
+
+ let op = operator_with_propfind("http://localhost:8080/dav/", "/sub/",
xml)?;
+ let entries = op.list("").await?;
+
+ let mut listed: Vec<(String, EntryMode)> = entries
+ .into_iter()
+ .map(|e| (e.path().to_string(), e.metadata().mode()))
+ .collect();
+ listed.sort_by(|a, b| a.0.cmp(&b.0));
+
+ assert_eq!(
+ listed,
+ vec![
+ ("/".to_string(), EntryMode::DIR),
+ ("calendar/".to_string(), EntryMode::DIR),
+ ("my file.txt".to_string(), EntryMode::FILE),
+ ]
+ );
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_list_handles_server_path_root_without_trailing_slash() ->
Result<()> {
+ let xml = r#"<?xml version="1.0" encoding="utf-8"?>
+ <D:multistatus xmlns:D="DAV:">
+ <D:response>
+ <D:href>/remote.php/webdav</D:href>
+ <D:propstat>
+ <D:prop>
+ <D:getlastmodified>Sat, 07 May 2022 06:39:47
GMT</D:getlastmodified>
+ <D:resourcetype><D:collection/></D:resourcetype>
+ </D:prop>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ </D:propstat>
+ </D:response>
+ <D:response>
+ <D:href>/remote.php/webdav/a.txt</D:href>
+ <D:propstat>
+ <D:prop>
+ <D:getcontentlength>3</D:getcontentlength>
+ <D:getlastmodified>Sat, 07 May 2022 06:40:10
GMT</D:getlastmodified>
+ <D:resourcetype/>
+ </D:prop>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ </D:propstat>
+ </D:response>
+ </D:multistatus>"#;
+
+ let op =
operator_with_propfind("http://localhost:8080/remote.php/webdav/", "/", xml)?;
+ let entries = op.list("").await?;
+ let mut paths: Vec<String> = entries.into_iter().map(|e|
e.path().to_string()).collect();
+ paths.sort();
+
+ assert_eq!(paths, vec!["/".to_string(), "a.txt".to_string()]);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn
test_list_rejects_short_empty_or_out_of_root_hrefs_without_panicking() ->
Result<()> {
+ let cases = [
+ // Shorter than root
+ ("http://localhost:8080", "/sub/", "<D:href>/</D:href>", true),
+ // Empty href under non-root
+ ("http://localhost:8080", "/sub/", "<D:href/>", false),
+ // Empty href under root even when marked as collection
+ ("http://localhost:8080", "/", "<D:href/>", true),
+ // Sibling prefix sharing string prefix without path boundary
+ (
+ "http://localhost:8080",
+ "/sub/",
+ "<D:href>/sub2/file.txt</D:href>",
+ false,
+ ),
+ // Absolute URI outside root
+ (
+ "http://localhost:8080",
+ "/sub/",
+ "<D:href>http://localhost:8080/other/file.txt</D:href>",
+ false,
+ ),
+ // Outside server_path (shares prefix without slash boundary)
+ (
+ "http://localhost:8080/dav",
+ "/",
+ "<D:href>/dav2/file.txt</D:href>",
+ false,
+ ),
+ // Non-absolute relative href
+ (
+ "http://localhost:8080",
+ "/sub/",
+ "<D:href>sub/file.txt</D:href>",
+ false,
+ ),
+ ];
+
+ for (endpoint, root, href_xml, is_dir) in cases {
+ let prop_xml = if is_dir {
+ "<D:resourcetype><D:collection/></D:resourcetype>"
+ } else {
+ "<D:getcontentlength>1</D:getcontentlength><D:resourcetype/>"
+ };
+ let xml = format!(
+ r#"<?xml version="1.0" encoding="utf-8"?>
+ <D:multistatus xmlns:D="DAV:">
+ <D:response>
+ {href_xml}
+ <D:propstat>
+ <D:prop>
+ <D:getlastmodified>Sat, 07 May 2022 06:39:47
GMT</D:getlastmodified>
+ {prop_xml}
+ </D:prop>
+ <D:status>HTTP/1.1 200 OK</D:status>
+ </D:propstat>
+ </D:response>
+ </D:multistatus>"#
+ );
+
+ let op = operator_with_propfind(endpoint, root, &xml)?;
+ let err = op.list("").await.expect_err(&format!(
+ "href {href_xml} under {endpoint} / {root} must fail"
+ ));
+ assert_eq!(err.kind(), ErrorKind::Unexpected, "{href_xml}");
+ assert!(
+ err.to_string().contains("href"),
+ "expected href error for {href_xml}, got: {err}"
+ );
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/services/webdav/src/reader.rs
b/core/services/webdav/src/reader.rs
index df6be65e63..c229ca6bb8 100644
--- a/core/services/webdav/src/reader.rs
+++ b/core/services/webdav/src/reader.rs
@@ -67,6 +67,30 @@ fn parse_read_reply(path: &str, status: StatusCode, headers:
&http::HeaderMap) -
Ok(RpRead::new(parse_into_metadata(path, headers)?))
}
+/// Returns whether a `200 OK` response carrying the full representation
+/// satisfies the requested `range` without dropping or shifting any bytes.
+///
+/// Some WebDAV servers (such as `dav-server`) respond with `200 OK` instead of
+/// `206 Partial Content` when a prefix or suffix range covers the entire
+/// resource (for example `bytes=-2048` or `bytes=0-2047` on a 1024-byte file).
+/// That response is exact only when `Content-Length` is known and within the
+/// requested range; otherwise a `200 OK` response to a ranged read must be
+/// rejected to avoid silently returning bytes starting at offset 0.
+fn ok_response_matches_range(range: BytesRange, content_length: Option<u64>)
-> bool {
+ match range {
+ BytesRange::Range {
+ offset: 0,
+ size: None,
+ } => true,
+ BytesRange::Range {
+ offset: 0,
+ size: Some(size),
+ }
+ | BytesRange::Suffix { size } => content_length.is_some_and(|len| len
<= size),
+ BytesRange::Range { .. } => false,
+ }
+}
+
impl oio::StreamRead for WebdavReader {
async fn open(&self, range: BytesRange) -> Result<(RpRead, Box<dyn
oio::ReadStreamDyn>)> {
let backend = &self.backend;
@@ -80,7 +104,28 @@ impl oio::StreamRead for WebdavReader {
let status = resp.status();
let (rp, stream) = match status {
- StatusCode::OK | StatusCode::PARTIAL_CONTENT => (
+ StatusCode::OK => {
+ let content_length = parse_content_length(resp.headers())?;
+ if !ok_response_matches_range(range, content_length) {
+ // RFC 9110 section 14.2: a server that ignores Range
responds
+ // with 200 OK and the complete representation starting at
byte
+ // 0. Drop the body without draining it so a large object
is not
+ // buffered into memory.
+ let (part, _body) = resp.into_parts();
+ let err = Error::new(
+ ErrorKind::Unexpected,
+ "webdav server returned 200 OK for ranged read instead
of 206 Partial Content",
+ )
+ .with_context("service_operation", "Get")
+ .with_context("range", range.to_header());
+ return Err(with_error_response_context(err, part));
+ }
+ (
+ parse_read_reply(path, status, resp.headers())?,
+ resp.into_body(),
+ )
+ }
+ StatusCode::PARTIAL_CONTENT => (
parse_read_reply(path, status, resp.headers())?,
resp.into_body(),
),
@@ -160,4 +205,259 @@ mod tests {
assert!(parse_read_reply("file", StatusCode::OK, &headers).is_err());
}
+
+ struct Always200Transport {
+ body: &'static [u8],
+ include_content_length: bool,
+ body_polled: std::sync::Arc<std::sync::atomic::AtomicBool>,
+ }
+
+ impl HttpTransport for Always200Transport {
+ async fn fetch(&self, _req: http::Request<Buffer>) ->
Result<Response<HttpBody>> {
+ let mut builder = Response::builder().status(StatusCode::OK);
+ let body_len = if self.include_content_length {
+ builder = builder.header(CONTENT_LENGTH, self.body.len());
+ Some(self.body.len() as u64)
+ } else {
+ None
+ };
+ let data = bytes::Bytes::from_static(self.body);
+ let body_polled = self.body_polled.clone();
+ let mut yielded = false;
+ let body = futures::stream::poll_fn(move |_cx| {
+ body_polled.store(true, std::sync::atomic::Ordering::Relaxed);
+ if yielded {
+ std::task::Poll::Ready(None)
+ } else {
+ yielded = true;
+
std::task::Poll::Ready(Some(Ok(Buffer::from(data.clone()))))
+ }
+ });
+ Ok(builder.body(HttpBody::new(body, body_len)).unwrap())
+ }
+ }
+
+ struct RangeAwareTransport {
+ content: &'static [u8],
+ }
+
+ impl HttpTransport for RangeAwareTransport {
+ async fn fetch(&self, req: http::Request<Buffer>) ->
Result<Response<HttpBody>> {
+ let total = self.content.len();
+ let (status, slice, content_range) = match req
+ .headers()
+ .get(http::header::RANGE)
+ .and_then(|v| v.to_str().ok())
+ {
+ None => (StatusCode::OK, self.content, None),
+ Some(header) => {
+ let spec = header.strip_prefix("bytes=").expect("bytes=
prefix");
+ let (start, end_inclusive) = if let Some(suffix) =
spec.strip_prefix('-') {
+ let suffix: usize = suffix.parse().unwrap();
+ (total.saturating_sub(suffix), total - 1)
+ } else {
+ let (s, e) = spec.split_once('-').unwrap();
+ let start: usize = s.parse().unwrap();
+ let end: usize = if e.is_empty() {
+ total - 1
+ } else {
+ e.parse::<usize>().unwrap().min(total - 1)
+ };
+ (start, end)
+ };
+ (
+ StatusCode::PARTIAL_CONTENT,
+ &self.content[start..=end_inclusive],
+ Some(format!("bytes {start}-{end_inclusive}/{total}")),
+ )
+ }
+ };
+
+ let mut builder = Response::builder()
+ .status(status)
+ .header(CONTENT_LENGTH, slice.len());
+ if let Some(cr) = content_range {
+ builder = builder.header(CONTENT_RANGE, cr);
+ }
+ let body = HttpBody::new(
+
futures::stream::iter([Ok(Buffer::from(bytes::Bytes::copy_from_slice(slice)))]),
+ Some(slice.len() as u64),
+ );
+ Ok(builder.body(body).unwrap())
+ }
+ }
+
+ struct CountingTransport {
+ requests: std::sync::Arc<std::sync::atomic::AtomicUsize>,
+ }
+
+ impl HttpTransport for CountingTransport {
+ async fn fetch(&self, _req: http::Request<Buffer>) ->
Result<Response<HttpBody>> {
+ self.requests
+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ Ok(Response::builder()
+ .status(StatusCode::OK)
+ .body(HttpBody::new(futures::stream::empty(), Some(0)))
+ .unwrap())
+ }
+ }
+
+ #[tokio::test]
+ async fn test_ranged_read_rejects_200_ok() -> Result<()> {
+ let ranged_cases = [
+ BytesRange::from(0..4),
+ BytesRange::from(4..),
+ BytesRange::from(4..8),
+ BytesRange::suffix(4),
+ ];
+
+ for include_content_length in [false, true] {
+ let body_polled =
std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let op =
+
Operator::new(WebdavBuilder::default().endpoint("http://localhost:8080"))?
+ .with_context(OperationContext::new().with_http_transport(
+ HttpTransporter::new(Always200Transport {
+ body: b"0123456789",
+ include_content_length,
+ body_polled: body_polled.clone(),
+ }),
+ ));
+
+ for range in ranged_cases {
+ body_polled.store(false, std::sync::atomic::Ordering::Relaxed);
+ let err = op
+ .read_with("file.txt")
+ .range(range)
+ .await
+ .expect_err(&format!(
+ "ranged read {range:?}
(content_length={include_content_length}) must reject 200 OK"
+ ));
+ assert_eq!(err.kind(), ErrorKind::Unexpected);
+ assert!(!err.is_temporary());
+ assert!(
+ !body_polled.load(std::sync::atomic::Ordering::Relaxed),
+ "rejected 200 OK body must not be drained for {range:?}"
+ );
+ }
+
+ let full = op.read("file.txt").await?;
+ assert_eq!(full.to_bytes(), b"0123456789".as_slice());
+
+ let from_zero = op.read_with("file.txt").range(0..).await?;
+ assert_eq!(from_zero.to_bytes(), b"0123456789".as_slice());
+
+ // Prefix/suffix ranges covering the full representation can
accept 200 OK
+ // only when Content-Length proves the body fits within the
requested range.
+ for covering_range in [
+ BytesRange::from(0..10),
+ BytesRange::suffix(10),
+ BytesRange::suffix(20),
+ ] {
+ body_polled.store(false, std::sync::atomic::Ordering::Relaxed);
+ if include_content_length {
+ let buf =
op.read_with("file.txt").range(covering_range).await?;
+ assert_eq!(
+ buf.to_bytes(),
+ b"0123456789".as_slice(),
+ "{covering_range:?}"
+ );
+ } else {
+ let err = op
+ .read_with("file.txt")
+ .range(covering_range)
+ .await
+ .expect_err(&format!(
+ "chunked 200 OK without Content-Length must reject
{covering_range:?}"
+ ));
+ assert_eq!(err.kind(), ErrorKind::Unexpected,
"{covering_range:?}");
+ assert!(
+
!body_polled.load(std::sync::atomic::Ordering::Relaxed),
+ "rejected chunked 200 OK body must not be drained for
{covering_range:?}"
+ );
+ }
+ }
+
+ // `.limit(20)` on a 10-byte file opens `0..20` and clamps to EOF
when length is known.
+ body_polled.store(false, std::sync::atomic::Ordering::Relaxed);
+ if include_content_length {
+ let buf = op.read_with("file.txt").limit(20).await?;
+ assert_eq!(buf.to_bytes(), b"0123456789".as_slice());
+ } else {
+ let err = op
+ .read_with("file.txt")
+ .limit(20)
+ .await
+ .expect_err("chunked 200 OK without Content-Length must
reject limit(20)");
+ assert_eq!(err.kind(), ErrorKind::Unexpected);
+ assert!(
+ !body_polled.load(std::sync::atomic::Ordering::Relaxed),
+ "rejected chunked 200 OK body must not be drained for
limit(20)"
+ );
+ }
+ }
+
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_ranged_read_accepts_206_partial_content() -> Result<()> {
+ let op =
Operator::new(WebdavBuilder::default().endpoint("http://localhost:8080"))?
+ .with_context(
+
OperationContext::new().with_http_transport(HttpTransporter::new(
+ RangeAwareTransport {
+ content: b"0123456789",
+ },
+ )),
+ );
+
+ let cases: &[(BytesRange, &[u8])] = &[
+ (BytesRange::from(..), b"0123456789"),
+ (BytesRange::from(0..), b"0123456789"),
+ (BytesRange::from(0..4), b"0123"),
+ (BytesRange::from(4..), b"456789"),
+ (BytesRange::from(4..8), b"4567"),
+ (BytesRange::suffix(4), b"6789"),
+ ];
+
+ for &(range, expected) in cases {
+ let buf = op.read_with("file.txt").range(range).await?;
+ assert_eq!(buf.to_bytes(), expected, "{range:?}");
+ }
+
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_overflowing_range_never_sends_request() -> Result<()> {
+ let requests =
std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let op =
Operator::new(WebdavBuilder::default().endpoint("http://localhost:8080"))?
+ .with_context(
+
OperationContext::new().with_http_transport(HttpTransporter::new(
+ CountingTransport {
+ requests: requests.clone(),
+ },
+ )),
+ );
+
+ for range in [
+ BytesRange::new(u64::MAX, Some(2)),
+ BytesRange::new(2, Some(u64::MAX)),
+ ] {
+ let err = op
+ .read_with("file.txt")
+ .range(range)
+ .await
+ .expect_err(&format!("overflowing range {range:?} must fail"));
+ assert_eq!(err.kind(), ErrorKind::RangeNotSatisfied, "{range:?}");
+ assert!(!err.is_temporary(), "{range:?}");
+ }
+
+ assert_eq!(
+ requests.load(std::sync::atomic::Ordering::Relaxed),
+ 0,
+ "overflowing ranges must fail before sending an HTTP request"
+ );
+
+ Ok(())
+ }
}