This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/fix-s3-presign-delete-lister-and-error-bugs in repository https://gitbox.apache.org/repos/asf/opendal.git
commit c7931a64d1f42cbe84718751a8322be9426db267 Author: Xuanwo <[email protected]> AuthorDate: Tue Nov 24 02:31:50 2026 +0100 fix(services/s3): fix presign checksums, DeleteObjects/416/complete_part errors, version pagination, md5 multipart capability, and endpoint scheme --- core/services/s3/src/backend.rs | 377 +++++++++++++++++++++++----------- core/services/s3/src/core.rs | 68 +++++- core/services/s3/src/deleter.rs | 116 +++++++++++ core/services/s3/src/lister.rs | 208 ++++++++++++++++++- core/services/s3/src/writer.rs | 166 ++++++++++++++- dev/src/generate/capabilities_docs.rs | 3 + website/data/capabilities.json | 6 +- 7 files changed, 800 insertions(+), 144 deletions(-) diff --git a/core/services/s3/src/backend.rs b/core/services/s3/src/backend.rs index 04585e3de4..dac533981a 100644 --- a/core/services/s3/src/backend.rs +++ b/core/services/s3/src/backend.rs @@ -604,6 +604,24 @@ impl S3Builder { true } + /// Normalize an endpoint by ensuring it has a lowercase `http://` or + /// `https://` scheme prefix without misclassifying scheme-less hostnames + /// that begin with `"http"` (for example `http-proxy.internal:9000`). + fn normalize_endpoint_scheme(endpoint: &str) -> String { + if let Some(prefix) = endpoint.get(..7) + && prefix.eq_ignore_ascii_case("http://") + { + format!("http://{}", &endpoint[7..]) + } else if let Some(prefix) = endpoint.get(..8) + && prefix.eq_ignore_ascii_case("https://") + { + format!("https://{}", &endpoint[8..]) + } else { + // Prefix https if endpoint doesn't start with scheme. + format!("https://{endpoint}") + } + } + /// Build endpoint with given region. fn build_endpoint(config: &S3Config, region: &str) -> String { let bucket = { @@ -613,14 +631,7 @@ impl S3Builder { }; let mut endpoint = match &config.endpoint { - Some(endpoint) => { - if endpoint.starts_with("http") { - endpoint.to_string() - } else { - // Prefix https if endpoint doesn't start with scheme. - format!("https://{endpoint}") - } - } + Some(endpoint) => Self::normalize_endpoint_scheme(endpoint), None => "https://s3.amazonaws.com".to_string(), }; @@ -674,11 +685,7 @@ impl S3Builder { let endpoint = match &config.endpoint { Some(endpoint) => { - let endpoint = if endpoint.starts_with("http") { - endpoint.to_string() - } else { - format!("https://{endpoint}") - }; + let endpoint = Self::normalize_endpoint_scheme(endpoint); let endpoint = Url::parse(&endpoint).map_err(|err| { Self::invalid_s3_express_config("invalid S3 endpoint").set_source(err) })?; @@ -822,12 +829,7 @@ impl S3Builder { let endpoint = endpoint.trim_end_matches('/'); // Make sure the endpoint contains the scheme. - let mut endpoint = if endpoint.starts_with("http") { - endpoint.to_string() - } else { - // Prefix https if endpoint doesn't start with scheme. - format!("https://{endpoint}") - }; + let mut endpoint = Self::normalize_endpoint_scheme(endpoint); // Remove bucket name from endpoint. endpoint = endpoint.replace(&format!("//{bucket}."), "//"); @@ -1169,114 +1171,129 @@ impl S3Builder { is_express: is_s3_express, }; + // S3 CreateMultipartUpload does not support MD5 checksum_algorithm; + // only single-shot PutObject supports Content-MD5. + let s3_write_can_multi = !matches!(checksum_algorithm, Some(ChecksumAlgorithm::Md5)); + + let mut capability = Capability { + stat: true, + stat_with_if_match: true, + stat_with_if_none_match: true, + stat_with_if_modified_since: true, + stat_with_if_unmodified_since: true, + stat_with_override_cache_control: true, + stat_with_override_content_disposition: true, + stat_with_override_content_type: true, + stat_with_version: !is_s3_express, + + read: true, + read_with_if_match: true, + read_with_if_none_match: true, + read_with_if_modified_since: true, + read_with_if_unmodified_since: true, + read_with_override_cache_control: true, + read_with_override_content_disposition: true, + read_with_override_content_type: true, + read_with_version: !is_s3_express, + read_with_suffix: true, + + write: true, + write_can_empty: true, + write_can_multi: s3_write_can_multi, + write_can_append: true, + write_can_copy_from: checksum_algorithm.is_none(), + + write_with_cache_control: true, + write_with_content_type: true, + write_with_content_disposition: true, + write_with_content_encoding: !is_s3_express, + write_with_content_language: true, + write_with_if_match: true, + write_with_if_not_exists: true, + write_with_user_metadata: true, + + // The min multipart size of S3 is 5 MiB. + // + // ref: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html> + write_multi_min_size: Some(5 * 1024 * 1024), + // The max multipart size of S3 is 5 GiB. + // + // ref: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html> + write_multi_max_size: if cfg!(target_pointer_width = "64") { + Some(5 * 1024 * 1024 * 1024) + } else { + Some(usize::MAX) + }, + // S3 allows at most 10,000 parts and 5 GiB for each part. + // + // ref: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html> + write_total_max_size: if cfg!(target_pointer_width = "64") { + Some(10_000 * 5 * 1024 * 1024 * 1024) + } else { + None + }, + + delete: true, + delete_max_size: Some(DEFAULT_BATCH_MAX_OPERATIONS), + delete_with_version: !is_s3_express, + delete_with_if_match: true, + + copy: true, + copy_can_multi: true, + copy_with_if_not_exists: true, + copy_with_if_match: true, + copy_with_source_version: !is_s3_express, + copy_with_user_metadata: true, + copy_with_content_type: true, + copy_with_content_language: true, + // The min multipart size of S3 is 5 MiB. + // + // ref: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html> + copy_multi_min_size: Some(5 * 1024 * 1024), + // The max multipart size of S3 is 5 GiB. + // + // ref: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html> + copy_multi_max_size: if cfg!(target_pointer_width = "64") { + Some(5 * 1024 * 1024 * 1024) + } else { + Some(usize::MAX) + }, + + restore: !is_s3_express, + restore_with_version: !is_s3_express, + restore_with_if_not_exists: !is_s3_express, + + list: true, + list_with_limit: true, + list_with_start_after: !is_s3_express, + list_with_recursive: !is_s3_express, + list_with_versions: !is_s3_express, + list_with_deleted: !is_s3_express, + + presign: true, + presign_stat: true, + presign_read: true, + presign_write: true, + presign_delete: true, + + shared: true, + + ..Default::default() + }; + + if !s3_write_can_multi { + capability.write_multi_min_size = None; + capability.write_multi_max_size = None; + #[cfg(target_pointer_width = "64")] + { + capability.write_total_max_size = Some(5 * 1024 * 1024 * 1024); + } + } + Ok(S3Backend { core: Arc::new(S3Core { info: ServiceInfo::new(scheme, &root, bucket), - capability: Capability { - stat: true, - stat_with_if_match: true, - stat_with_if_none_match: true, - stat_with_if_modified_since: true, - stat_with_if_unmodified_since: true, - stat_with_override_cache_control: true, - stat_with_override_content_disposition: true, - stat_with_override_content_type: true, - stat_with_version: !is_s3_express, - - read: true, - read_with_if_match: true, - read_with_if_none_match: true, - read_with_if_modified_since: true, - read_with_if_unmodified_since: true, - read_with_override_cache_control: true, - read_with_override_content_disposition: true, - read_with_override_content_type: true, - read_with_version: !is_s3_express, - read_with_suffix: true, - - write: true, - write_can_empty: true, - write_can_multi: true, - write_can_append: true, - write_can_copy_from: checksum_algorithm.is_none(), - - write_with_cache_control: true, - write_with_content_type: true, - write_with_content_disposition: true, - write_with_content_encoding: !is_s3_express, - write_with_content_language: true, - write_with_if_match: true, - write_with_if_not_exists: true, - write_with_user_metadata: true, - - // The min multipart size of S3 is 5 MiB. - // - // ref: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html> - write_multi_min_size: Some(5 * 1024 * 1024), - // The max multipart size of S3 is 5 GiB. - // - // ref: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html> - write_multi_max_size: if cfg!(target_pointer_width = "64") { - Some(5 * 1024 * 1024 * 1024) - } else { - Some(usize::MAX) - }, - // S3 allows at most 10,000 parts and 5 GiB for each part. - // - // ref: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html> - write_total_max_size: if cfg!(target_pointer_width = "64") { - Some(10_000 * 5 * 1024 * 1024 * 1024) - } else { - None - }, - - delete: true, - delete_max_size: Some(DEFAULT_BATCH_MAX_OPERATIONS), - delete_with_version: !is_s3_express, - delete_with_if_match: true, - - copy: true, - copy_can_multi: true, - copy_with_if_not_exists: true, - copy_with_if_match: true, - copy_with_source_version: !is_s3_express, - copy_with_user_metadata: true, - copy_with_content_type: true, - copy_with_content_language: true, - // The min multipart size of S3 is 5 MiB. - // - // ref: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html> - copy_multi_min_size: Some(5 * 1024 * 1024), - // The max multipart size of S3 is 5 GiB. - // - // ref: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html> - copy_multi_max_size: if cfg!(target_pointer_width = "64") { - Some(5 * 1024 * 1024 * 1024) - } else { - Some(usize::MAX) - }, - - restore: !is_s3_express, - restore_with_version: !is_s3_express, - restore_with_if_not_exists: !is_s3_express, - - list: true, - list_with_limit: true, - list_with_start_after: !is_s3_express, - list_with_recursive: !is_s3_express, - list_with_versions: !is_s3_express, - list_with_deleted: !is_s3_express, - - presign: true, - presign_stat: true, - presign_read: true, - presign_write: true, - presign_delete: true, - - shared: true, - - ..Default::default() - }, + capability, bucket: bucket.to_string(), endpoint, root, @@ -3716,6 +3733,49 @@ mod tests { assert_eq!(builder.config.profile.as_deref(), Some("selected")); } + #[tokio::test] + async fn test_presign_write_omits_checksum_headers() { + for (algorithm, header_name) in + [("crc32c", "x-amz-checksum-crc32c"), ("md5", "content-md5")] + { + let op = Operator::new( + S3Builder::default() + .bucket("test") + .region("us-east-1") + .endpoint("http://127.0.0.1:9000") + .access_key_id("test-access-key") + .secret_access_key("test-secret-key") + .disable_config_load() + .disable_ec2_metadata() + .checksum_algorithm(algorithm), + ) + .unwrap(); + + let presigned = op + .presign_write("test.txt", std::time::Duration::from_secs(60)) + .await + .unwrap(); + + assert!( + !presigned.header().contains_key(header_name), + "presign_write with {algorithm} must not attach {header_name}: {:?}", + presigned.header() + ); + + let url = url::Url::parse(&presigned.uri().to_string()).unwrap(); + let signed_headers = url + .query_pairs() + .find_map(|(k, v)| (k == "X-Amz-SignedHeaders").then(|| v.into_owned())) + .expect("presigned URL must contain X-Amz-SignedHeaders"); + assert!( + !signed_headers + .split(';') + .any(|h| h.eq_ignore_ascii_case(header_name)), + "presign_write with {algorithm} must not sign {header_name}: {signed_headers}" + ); + } + } + #[test] fn test_write_can_copy_from_capability() { let backend = S3Builder::default() @@ -3725,6 +3785,12 @@ mod tests { .build() .unwrap(); assert!(backend.capability().write_can_copy_from); + assert!(backend.capability().write_can_multi); + assert_eq!( + backend.capability().write_multi_min_size, + Some(5 * 1024 * 1024) + ); + assert!(backend.capability().write_multi_max_size.is_some()); let backend = S3Builder::default() .bucket("test") @@ -3734,6 +3800,28 @@ mod tests { .build() .unwrap(); assert!(!backend.capability().write_can_copy_from); + assert!(backend.capability().write_can_multi); + assert_eq!( + backend.capability().write_multi_min_size, + Some(5 * 1024 * 1024) + ); + + let backend = S3Builder::default() + .bucket("test") + .region("us-east-1") + .endpoint("http://127.0.0.1:9000") + .checksum_algorithm("md5") + .build() + .unwrap(); + assert!(!backend.capability().write_can_copy_from); + assert!(!backend.capability().write_can_multi); + assert_eq!(backend.capability().write_multi_min_size, None); + assert_eq!(backend.capability().write_multi_max_size, None); + #[cfg(target_pointer_width = "64")] + assert_eq!( + backend.capability().write_total_max_size, + Some(5 * 1024 * 1024 * 1024) + ); } #[test] @@ -3789,6 +3877,47 @@ mod tests { } } + #[tokio::test] + async fn test_build_endpoint_scheme_prefix() { + let cases = [ + ( + "http-proxy.internal:9000", + "https://http-proxy.internal:9000/test", + ), + ("httpbin.org", "https://httpbin.org/test"), + ("https-proxy.internal", "https://https-proxy.internal/test"), + ("http://127.0.0.1:9000", "http://127.0.0.1:9000/test"), + ("HTTP://127.0.0.1:9000", "http://127.0.0.1:9000/test"), + ( + "HTTPS://s3.amazonaws.com", + "https://s3.us-east-2.amazonaws.com/test", + ), + ]; + + for (input, expected) in cases { + let builder = S3Builder::default().bucket("test").endpoint(input); + assert_eq!( + S3Builder::build_endpoint(&builder.config, "us-east-2"), + expected, + "endpoint={input}" + ); + } + + assert_eq!( + S3Builder::detect_region("HTTPS://s3.amazonaws.com", "test").await, + Some("us-east-1".to_string()) + ); + + let express_builder = S3Builder::default() + .bucket("example--usw2-az1--x-s3") + .endpoint("http-proxy.internal:9000"); + assert!( + S3Builder::resolve_s3_express_config(&express_builder.config, "us-west-2") + .expect("non-AWS schemeless http-prefixed host must parse cleanly") + .is_none() + ); + } + #[test] fn test_resolve_s3_express_config() { let directory_bucket = "example--usw2-az1--x-s3"; diff --git a/core/services/s3/src/core.rs b/core/services/s3/src/core.rs index f6e974577c..9595f62fd5 100644 --- a/core/services/s3/src/core.rs +++ b/core/services/s3/src/core.rs @@ -749,8 +749,12 @@ impl S3Core { ); } - // Calculate Checksum. - if let Some(checksum) = self.calculate_checksum(&body) { + // Calculate checksum only when we have an actual payload (`size.is_some()`). + // Presigned PUT requests pass `size = None` with a placeholder empty buffer + // and must not sign an empty-body checksum header into the presigned URL. + if size.is_some() + && let Some(checksum) = self.calculate_checksum(&body) + { // Set Checksum header. req = self.insert_checksum_header(req, &checksum); } @@ -2361,6 +2365,7 @@ pub fn parse_error(ctx: ErrorContext, resp: Response<Buffer>) -> Error { 401 | 403 => (ErrorKind::PermissionDenied, false), 404 => (ErrorKind::NotFound, false), 304 | 412 if ctx.caller_condition => (ErrorKind::ConditionNotMatch, false), + 416 => (ErrorKind::RangeNotSatisfied, false), // Service like R2 could return 499 error with a message like: // Client Disconnect, we should retry it. 499 => (ErrorKind::Unexpected, true), @@ -2405,10 +2410,14 @@ pub fn parse_s3_error_code(ctx: ErrorContext, code: &str) -> Option<(ErrorKind, // Although the status code is 404, NoSuchBucket is // a config invalid error, and it's not retryable from OpenDAL. "NoSuchBucket" => Some((ErrorKind::ConfigInvalid, false)), - // S3 Express can return 200 OK with an embedded NoSuchKey error for - // CopyObject. Classify the error code explicitly because the HTTP - // status alone cannot preserve the NotFound semantics in this case. - "NoSuchKey" => Some((ErrorKind::NotFound, false)), + // AccessDenied can appear inside HTTP 200 OK XML error payloads + // (such as DeleteObjects, CopyObject, and CompleteMultipartUpload) + // where the HTTP status does not carry 403 Forbidden. + "AccessDenied" => Some((ErrorKind::PermissionDenied, false)), + // S3 Express and batch/copy operations can return 200 OK with an + // embedded NoSuchKey or NoSuchVersion error. Classify them explicitly + // because the HTTP status alone cannot preserve NotFound semantics. + "NoSuchKey" | "NoSuchVersion" => Some((ErrorKind::NotFound, false)), // On CompleteMultipartUpload, NoSuchUpload means the upload session no // longer exists rather than a missing target key, so it must not map to // NotFound or be rewritten to ConditionNotMatch under if_match. @@ -2574,4 +2583,51 @@ mod error_tests { assert!(!err.is_temporary(), "{operation}"); } } + + #[test] + fn access_denied_and_no_such_version_classify_in_200_xml_errors() { + let ctx = ErrorContext::new(ServiceOperation("DeleteObjects")); + assert_eq!( + parse_s3_error_code(ctx, "AccessDenied"), + Some((ErrorKind::PermissionDenied, false)) + ); + assert_eq!( + parse_s3_error_code(ctx, "NoSuchVersion"), + Some((ErrorKind::NotFound, false)) + ); + + let access_denied_xml = r#"<?xml version="1.0" encoding="UTF-8"?> +<Error> + <Code>AccessDenied</Code> + <Message>Access Denied</Message> +</Error>"#; + let resp = Response::builder() + .status(200) + .body(Buffer::from(access_denied_xml)) + .unwrap(); + let err = parse_error( + ErrorContext::new(ServiceOperation("CompleteMultipartUpload")), + resp, + ); + assert_eq!(err.kind(), ErrorKind::PermissionDenied); + assert!(!err.is_temporary()); + } + + #[test] + fn http_416_maps_to_range_not_satisfied_without_xml_error_code() { + let ctx = ErrorContext::new(ServiceOperation("GetObject")); + for body in [ + "", + "Requested Range Not Satisfiable", + r#"<Error><Code>InvalidRange</Code><Message>The requested range is not valid</Message></Error>"#, + ] { + let resp = Response::builder() + .status(416) + .body(Buffer::from(body)) + .unwrap(); + let err = parse_error(ctx, resp); + assert_eq!(err.kind(), ErrorKind::RangeNotSatisfied, "body={body:?}"); + assert!(!err.is_temporary(), "body={body:?}"); + } + } } diff --git a/core/services/s3/src/deleter.rs b/core/services/s3/src/deleter.rs index 5ab77395a8..9d5aa9dd1e 100644 --- a/core/services/s3/src/deleter.rs +++ b/core/services/s3/src/deleter.rs @@ -280,4 +280,120 @@ mod tests { assert_eq!(requests.load(Ordering::Relaxed), 2); } + + #[derive(Clone)] + struct StaticBatchDeleteTransport { + body: &'static str, + } + + impl HttpTransport for StaticBatchDeleteTransport { + async fn fetch(&self, req: Request<Buffer>) -> Result<Response<HttpBody>> { + assert_eq!(req.method(), Method::POST); + assert!( + req.uri().query().is_some_and(|q| q.contains("delete")), + "expected DeleteObjects query, got {:?}", + req.uri() + ); + + let body = Buffer::from(Bytes::from_static(self.body.as_bytes())); + let size = body.len() as u64; + Ok(Response::builder() + .status(StatusCode::OK) + .body(HttpBody::new( + futures::stream::iter(vec![Ok(body)]), + Some(size), + )) + .expect("mock response must build")) + } + } + + #[tokio::test] + async fn delete_batch_maps_200_xml_access_denied_to_permission_denied() { + for (body, op_delete, expected_kind) in [ + ( + r#"<?xml version="1.0" encoding="UTF-8"?> +<DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> + <Deleted> + <Key>allowed.txt</Key> + </Deleted> + <Error> + <Key>target.txt</Key> + <Code>AccessDenied</Code> + <Message>Access Denied</Message> + </Error> +</DeleteResult>"#, + options::DeleteOptions::default(), + ErrorKind::PermissionDenied, + ), + ( + r#"<?xml version="1.0" encoding="UTF-8"?> +<DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> + <Deleted> + <Key>allowed.txt</Key> + </Deleted> + <Error> + <Key>target.txt</Key> + <VersionId>v1</VersionId> + <Code>NoSuchVersion</Code> + <Message>The specified version does not exist.</Message> + </Error> +</DeleteResult>"#, + options::DeleteOptions { + version: Some("v1".to_string()), + ..Default::default() + }, + ErrorKind::NotFound, + ), + ( + r#"<?xml version="1.0" encoding="UTF-8"?> +<DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> + <Deleted> + <Key>allowed.txt</Key> + </Deleted> + <Error> + <Key>target.txt</Key> + <VersionId>v2</VersionId> + <Code>NoSuchVersion</Code> + <Message>The specified version does not exist.</Message> + </Error> +</DeleteResult>"#, + options::DeleteOptions { + version: Some("v2".to_string()), + if_match: Some("\"etag\"".to_string()), + ..Default::default() + }, + ErrorKind::ConditionNotMatch, + ), + ] { + let op = Operator::new( + S3Builder::default() + .bucket("example") + .region("us-east-1") + .skip_signature() + .disable_config_load() + .disable_ec2_metadata(), + ) + .expect("S3 operator must build") + .with_context( + OperationContext::new() + .with_http_transport(HttpTransporter::new(StaticBatchDeleteTransport { body })), + ); + + let mut deleter = op.deleter().await.expect("deleter must initialize"); + deleter + .delete("allowed.txt") + .await + .expect("queue allowed.txt"); + deleter + .delete(("target.txt".to_string(), op_delete)) + .await + .expect("queue target.txt"); + let err = deleter + .close() + .await + .expect_err("batch delete must surface XML Error entry"); + assert_eq!(err.kind(), expected_kind, "body={body}"); + assert!(!err.is_temporary(), "body={body}"); + } + } } diff --git a/core/services/s3/src/lister.rs b/core/services/s3/src/lister.rs index a1ac4899a7..f4cf19a341 100644 --- a/core/services/s3/src/lister.rs +++ b/core/services/s3/src/lister.rs @@ -314,7 +314,7 @@ impl S3ObjectVersionsLister { impl oio::PageList for S3ObjectVersionsLister { async fn next_page(&self, ctx: &mut PageContext) -> Result<()> { - let markers = ctx.token.rsplit_once(" "); + let markers = ctx.token.split_once('\0'); let (key_marker, version_id_marker) = if let Some(data) = markers { data } else if let Some(start_after) = &self.abs_start_after { @@ -351,16 +351,19 @@ impl oio::PageList for S3ObjectVersionsLister { // we allow retries to obtain the correct data. .map_err(Error::set_temporary)?; - ctx.done = if let Some(is_truncated) = output.is_truncated { - !is_truncated + // Terminate pagination unless the server explicitly reports truncation + // and provides a non-empty NextKeyMarker. Join markers with NUL (`\0`), + // which is disallowed in XML 1.0 character data, so spaces in keys or + // version IDs cannot corrupt pagination tokens. + let next_key_marker = output.next_key_marker.as_deref().unwrap_or_default(); + let next_version_id_marker = output.next_version_id_marker.as_deref().unwrap_or_default(); + if output.is_truncated == Some(true) && !next_key_marker.is_empty() { + ctx.done = false; + ctx.token = format!("{next_key_marker}\0{next_version_id_marker}"); } else { - false - }; - ctx.token = format!( - "{} {}", - output.next_key_marker.unwrap_or_default(), - output.next_version_id_marker.unwrap_or_default() - ); + ctx.done = true; + ctx.token.clear(); + } for prefix in output.common_prefixes { let de = oio::Entry::new( @@ -426,3 +429,188 @@ impl oio::PageList for S3ObjectVersionsLister { Ok(()) } } + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::sync::Arc; + use std::sync::Mutex; + + use bytes::Bytes; + use http::Request; + use http::Response; + use http::StatusCode; + use opendal_core::*; + + use crate::backend::S3Builder; + + #[derive(Clone)] + struct ScriptedListTransport { + responses: Arc<Mutex<VecDeque<&'static str>>>, + queries: Arc<Mutex<Vec<String>>>, + } + + impl ScriptedListTransport { + fn new(responses: Vec<&'static str>) -> Self { + Self { + responses: Arc::new(Mutex::new(responses.into())), + queries: Arc::new(Mutex::new(Vec::new())), + } + } + } + + impl HttpTransport for ScriptedListTransport { + async fn fetch(&self, req: Request<Buffer>) -> Result<Response<HttpBody>> { + self.queries + .lock() + .unwrap() + .push(req.uri().query().unwrap_or_default().to_string()); + + let body = self + .responses + .lock() + .unwrap() + .pop_front() + .expect("unexpected extra pagination request"); + let buf = Buffer::from(Bytes::from_static(body.as_bytes())); + let size = buf.len() as u64; + Ok(Response::builder() + .status(StatusCode::OK) + .body(HttpBody::new( + futures::stream::iter(vec![Ok(buf)]), + Some(size), + )) + .expect("mock response must build")) + } + } + + fn operator_with_responses( + responses: Vec<&'static str>, + ) -> (Operator, Arc<Mutex<Vec<String>>>) { + let transport = ScriptedListTransport::new(responses); + let queries = transport.queries.clone(); + let op = Operator::new( + S3Builder::default() + .bucket("example") + .region("us-east-1") + .skip_signature() + .disable_config_load() + .disable_ec2_metadata(), + ) + .expect("S3 operator must build") + .with_context(OperationContext::new().with_http_transport(HttpTransporter::new(transport))); + (op, queries) + } + + #[tokio::test] + async fn object_versions_lister_stops_when_is_truncated_missing() { + let page = r#"<?xml version="1.0" encoding="UTF-8"?> +<ListVersionsResult> + <Version> + <Key>alpha.txt</Key> + <VersionId>v1</VersionId> + <IsLatest>true</IsLatest> + <LastModified>2026-01-01T00:00:00.000Z</LastModified> + <Size>5</Size> + </Version> +</ListVersionsResult>"#; + + let (op, queries) = operator_with_responses(vec![page]); + let entries = op.list_with("").versions(true).await.unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].path(), "alpha.txt"); + assert_eq!(queries.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn object_versions_lister_stops_when_next_key_marker_missing_or_empty() { + for page in [ + r#"<?xml version="1.0" encoding="UTF-8"?> +<ListVersionsResult> + <IsTruncated>true</IsTruncated> + <Version> + <Key>alpha.txt</Key> + <VersionId>v1</VersionId> + <IsLatest>true</IsLatest> + <LastModified>2026-01-01T00:00:00.000Z</LastModified> + <Size>5</Size> + </Version> +</ListVersionsResult>"#, + r#"<?xml version="1.0" encoding="UTF-8"?> +<ListVersionsResult> + <IsTruncated>true</IsTruncated> + <NextKeyMarker></NextKeyMarker> + <NextVersionIdMarker>v1</NextVersionIdMarker> + <Version> + <Key>alpha.txt</Key> + <VersionId>v1</VersionId> + <IsLatest>true</IsLatest> + <LastModified>2026-01-01T00:00:00.000Z</LastModified> + <Size>5</Size> + </Version> +</ListVersionsResult>"#, + ] { + let (op, queries) = operator_with_responses(vec![page]); + let entries = op.list_with("").versions(true).await.unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(queries.lock().unwrap().len(), 1); + } + } + + #[tokio::test] + async fn object_versions_lister_preserves_spaces_in_key_and_version_markers() { + let page1 = r#"<?xml version="1.0" encoding="UTF-8"?> +<ListVersionsResult> + <IsTruncated>true</IsTruncated> + <NextKeyMarker>dir with spaces/file one.txt</NextKeyMarker> + <NextVersionIdMarker>ver 1 alpha</NextVersionIdMarker> + <Version> + <Key>dir with spaces/file one.txt</Key> + <VersionId>ver 1 alpha</VersionId> + <IsLatest>true</IsLatest> + <LastModified>2026-01-01T00:00:00.000Z</LastModified> + <Size>3</Size> + </Version> +</ListVersionsResult>"#; + let page2 = r#"<?xml version="1.0" encoding="UTF-8"?> +<ListVersionsResult> + <IsTruncated>false</IsTruncated> + <Version> + <Key>dir with spaces/file two.txt</Key> + <VersionId>ver 2 beta</VersionId> + <IsLatest>true</IsLatest> + <LastModified>2026-01-02T00:00:00.000Z</LastModified> + <Size>4</Size> + </Version> +</ListVersionsResult>"#; + + let (op, queries) = operator_with_responses(vec![page1, page2]); + let entries = op + .list_with("") + .versions(true) + .recursive(true) + .await + .unwrap(); + let paths: Vec<_> = entries.iter().map(|e| e.path()).collect(); + assert_eq!( + paths, + vec![ + "dir with spaces/file one.txt", + "dir with spaces/file two.txt", + ] + ); + + let recorded = queries.lock().unwrap(); + assert_eq!(recorded.len(), 2); + assert!( + recorded[1].contains("key-marker=dir%20with%20spaces/file%20one.txt"), + "second page query must preserve key-marker with spaces: {}", + recorded[1] + ); + assert!( + recorded[1].contains("version-id-marker=ver%201%20alpha"), + "second page query must preserve version-id-marker with spaces: {}", + recorded[1] + ); + } +} diff --git a/core/services/s3/src/writer.rs b/core/services/s3/src/writer.rs index f72879f554..536b7964de 100644 --- a/core/services/s3/src/writer.rs +++ b/core/services/s3/src/writer.rs @@ -283,7 +283,7 @@ impl oio::MultipartWrite for S3Writer { let ret: CompleteMultipartUploadResult = quick_xml::de::from_reader(bs.as_ref()).map_err(new_xml_deserialize_error)?; - if !ret.code.is_empty() { + if !ret.code.is_empty() || ret.etag.is_empty() { let err = parse_error( self.error_context(ServiceOperation("CompleteMultipartUpload")), Response::from_parts(parts, Buffer::from(bs)), @@ -398,3 +398,167 @@ impl oio::AppendWrite for S3Writer { } } } + +#[cfg(test)] +mod tests { + use bytes::Bytes; + use http::Method; + use http::Request; + use http::Response; + use http::StatusCode; + use http::header::ETAG; + use opendal_core::*; + + use crate::backend::S3Builder; + + #[derive(Clone)] + struct MultipartCompleteTransport { + complete_body: &'static str, + } + + impl HttpTransport for MultipartCompleteTransport { + async fn fetch(&self, req: Request<Buffer>) -> Result<Response<HttpBody>> { + let query = req.uri().query().unwrap_or_default(); + match (req.method(), query) { + (&Method::POST, "uploads") => { + let body = Buffer::from(Bytes::from_static( + b"<InitiateMultipartUploadResult><UploadId>u1</UploadId></InitiateMultipartUploadResult>", + )); + let size = body.len() as u64; + Ok(Response::builder() + .status(StatusCode::OK) + .body(HttpBody::new( + futures::stream::iter(vec![Ok(body)]), + Some(size), + )) + .expect("mock response must build")) + } + (&Method::PUT, q) if q.contains("partNumber=") => Ok(Response::builder() + .status(StatusCode::OK) + .header(ETAG, "\"part-etag\"") + .body(HttpBody::new(futures::stream::empty(), Some(0))) + .expect("mock response must build")), + (&Method::POST, q) if q.contains("uploadId=u1") => { + let body = Buffer::from(Bytes::from_static(self.complete_body.as_bytes())); + let size = body.len() as u64; + Ok(Response::builder() + .status(StatusCode::OK) + .body(HttpBody::new( + futures::stream::iter(vec![Ok(body)]), + Some(size), + )) + .expect("mock response must build")) + } + (method, q) => panic!("unexpected request: {method} ?{q}"), + } + } + } + + #[tokio::test] + async fn complete_part_rejects_empty_etag_and_200_xml_errors() { + const PART_SIZE: usize = 5 * 1024 * 1024; + let part_payload = Bytes::from(vec![0u8; PART_SIZE]); + + for (body, expected_kind, expected_temporary) in [ + ( + "<CompleteMultipartUploadResult/>", + ErrorKind::Unexpected, + false, + ), + ( + "<Error><Message>missing code</Message></Error>", + ErrorKind::Unexpected, + false, + ), + ( + "<Error><Code>AccessDenied</Code><Message>Access Denied</Message></Error>", + ErrorKind::PermissionDenied, + false, + ), + ( + "<Error><Code>InternalError</Code><Message>retry me</Message></Error>", + ErrorKind::Unexpected, + true, + ), + ] { + let op = Operator::new( + S3Builder::default() + .bucket("example") + .region("us-east-1") + .skip_signature() + .disable_config_load() + .disable_ec2_metadata(), + ) + .expect("S3 operator must build") + .with_context( + OperationContext::new().with_http_transport(HttpTransporter::new( + MultipartCompleteTransport { + complete_body: body, + }, + )), + ); + + let mut writer = op.writer("object.bin").await.expect("writer must open"); + writer + .write(part_payload.clone()) + .await + .expect("first 5 MiB part"); + writer.write("tail").await.expect("second part"); + let err = writer + .close() + .await + .expect_err("complete_part must reject empty ETag / 200-OK XML error"); + assert_eq!(err.kind(), expected_kind, "body={body}"); + assert_eq!(err.is_temporary(), expected_temporary, "body={body}"); + } + } + + #[derive(Clone)] + struct SinglePutMd5Transport; + + impl HttpTransport for SinglePutMd5Transport { + async fn fetch(&self, req: Request<Buffer>) -> Result<Response<HttpBody>> { + assert_eq!( + req.method(), + Method::PUT, + "checksum_algorithm=md5 write must use single PutObject, not multipart: {} {:?}", + req.method(), + req.uri() + ); + assert!( + req.headers().contains_key("content-md5"), + "single PutObject with checksum_algorithm=md5 must attach content-md5" + ); + Ok(Response::builder() + .status(StatusCode::OK) + .header(ETAG, "\"single-put-etag\"") + .body(HttpBody::new(futures::stream::empty(), Some(0))) + .expect("mock response must build")) + } + } + + #[tokio::test] + async fn md5_checksum_writes_over_5mib_in_single_put_without_multipart() { + let op = Operator::new( + S3Builder::default() + .bucket("example") + .region("us-east-1") + .checksum_algorithm("md5") + .skip_signature() + .disable_config_load() + .disable_ec2_metadata(), + ) + .expect("S3 operator must build") + .with_context( + OperationContext::new() + .with_http_transport(HttpTransporter::new(SinglePutMd5Transport)), + ); + + let payload = Bytes::from(vec![b'a'; 6 * 1024 * 1024]); + let meta = op + .write("large-md5.bin", payload) + .await + .expect("single write >5 MiB with checksum_algorithm=md5 must succeed via PutObject"); + assert_eq!(meta.etag(), Some("\"single-put-etag\"")); + } +} diff --git a/dev/src/generate/capabilities_docs.rs b/dev/src/generate/capabilities_docs.rs index bff07ea9e7..a86110b0b6 100644 --- a/dev/src/generate/capabilities_docs.rs +++ b/dev/src/generate/capabilities_docs.rs @@ -682,6 +682,9 @@ fn describe_bool_condition(expr: &Expr, rel_path: &str) -> Result<String> { .to_string(), ); } + if ident == "s3_write_can_multi" { + return Ok("When `checksum_algorithm` is not `md5`".to_string()); + } if let Some(rest) = ident.strip_prefix("has_") { return Ok(format!("Requires `{rest}`")); } diff --git a/website/data/capabilities.json b/website/data/capabilities.json index dde27b3861..07ed34859f 100644 --- a/website/data/capabilities.json +++ b/website/data/capabilities.json @@ -1604,7 +1604,7 @@ "write_can_append": true, "write_can_copy_from": "When `checksum_algorithm` is not set", "write_can_empty": true, - "write_can_multi": true, + "write_can_multi": "When `checksum_algorithm` is not `md5`", "write_with_cache_control": true, "write_with_content_disposition": true, "write_with_content_encoding": "Standard S3 buckets (not S3 Express One Zone)", @@ -1927,7 +1927,7 @@ "write_can_append": true, "write_can_copy_from": "When `checksum_algorithm` is not set", "write_can_empty": true, - "write_can_multi": true, + "write_can_multi": "When `checksum_algorithm` is not `md5`", "write_with_cache_control": true, "write_with_content_disposition": true, "write_with_content_encoding": "Standard S3 buckets (not S3 Express One Zone)", @@ -2056,7 +2056,7 @@ "write_can_append": true, "write_can_copy_from": "When `checksum_algorithm` is not set", "write_can_empty": true, - "write_can_multi": true, + "write_can_multi": "When `checksum_algorithm` is not `md5`", "write_with_cache_control": true, "write_with_content_disposition": true, "write_with_content_encoding": "Standard S3 buckets (not S3 Express One Zone)",
