Compare commits

...

30 Commits

Author SHA1 Message Date
overtrue 8398f17035 refactor(auth): return owned errors for upload size capabilities 2026-11-23 16:09:06 +08:00
overtrue 25df27a41b refactor(app): restrict the old stream and XML exports to tests 2026-11-23 16:09:06 +08:00
overtrue dec467da27 refactor(gateway): render metadata listings with native XML 2026-11-23 16:08:43 +08:00
overtrue 4b23847a75 refactor(object): retire the unused legacy length interface on PUT limits 2026-11-23 16:03:51 +08:00
overtrue 23405ff83a refactor(gateway): use native restore, version and object lock headers 2026-11-23 16:02:49 +08:00
overtrue 77107f62f3 refactor(http): classify control body digests with native host and path rules 2026-11-23 16:02:49 +08:00
overtrue 63e58d3c18 test(bucket): move request fields into the owner-state envelope 2026-11-23 16:02:49 +08:00
overtrue 6a7761cdb6 test(object): build the gateway post archive envelope directly
Replace the archive refusal fixture's from_s3s call with
RequestEnvelope::from_parts, keeping method, URI, headers, and
extensions. Credentials, region, and service stay absent. The
legacy-provenance, NotImplemented, and unpolled-body assertions are
unchanged.
2026-11-23 16:00:23 +08:00
overtrue 929582bc43 test(gateway): replace legacy configuration projections with frozen wire and cache fixtures 2026-11-23 15:53:00 +08:00
overtrue a1b4f29cc8 refactor(gateway): use native host validation and bucket deletion errors 2026-11-23 15:53:00 +08:00
overtrue 5e6f57c118 refactor(s3-types): render owned errors without the legacy HTTP serializer 2026-11-23 15:52:28 +08:00
overtrue 391e239711 refactor(auth): use gateway header coverage for protocol admission 2026-11-23 15:36:59 +08:00
overtrue db721d9bb1 refactor(gateway): return native lifecycle validation errors 2026-11-23 15:36:59 +08:00
overtrue 7125b37129 refactor(gateway): preserve native Veeam read errors across the cache 2026-11-23 15:36:58 +08:00
overtrue 6cb0e6971b test(bucket): build the owner-state envelope directly
Replace the create-bucket reqinfo fixture's from_s3s call with
RequestEnvelope::from_parts, keeping method, URI, headers, and
extensions. Credentials, region, and service stay absent. The
owner-state assertion is unchanged.
2026-11-23 15:33:18 +08:00
overtrue 41f11d030d refactor(gateway): use native errors for table listings and multipart headers 2026-11-23 15:00:00 +08:00
overtrue 69514b18de style(gateway): format native GET test seam exports 2026-11-23 14:58:03 +08:00
overtrue c66b0b4870 test(gateway): retire the legacy object response and stream adapter 2026-11-23 14:54:35 +08:00
overtrue c0795fa4e8 refactor(gateway): remove unused legacy GET fixture exports 2026-11-23 14:50:06 +08:00
overtrue 95ea979811 test(gateway): retire the remaining legacy GET request fixtures 2026-11-23 14:50:06 +08:00
overtrue 00a3abd6ef test(protocols): freeze the legacy COPY request head observations 2026-11-23 14:50:06 +08:00
overtrue 0ebd1f14ca refactor(gateway): share the native GET field projection 2026-11-23 14:50:06 +08:00
overtrue 18f5090671 fix(test): adapt the shared read benchmark to historical GET APIs 2026-11-23 14:50:06 +08:00
overtrue cd94ed59c5 test(gateway): exercise conditional reads through native GET requests 2026-11-23 14:50:06 +08:00
overtrue c58890f199 test(gateway): use native requests for conditional object copies 2026-11-23 14:50:06 +08:00
overtrue 526dd58f6d test(gateway): exercise copy authorization on the native upload path 2026-11-23 14:50:06 +08:00
overtrue 35a6de6eb5 refactor(gateway): retire legacy storage ETag projections 2026-11-23 14:50:06 +08:00
overtrue 0649e80b62 test(protocols): build the listing session envelope directly
Replace the listing session credential fixture's from_s3s call with
RequestEnvelope::from_parts, keeping method, URI, headers,
extensions, region, service, and credentials. The credential
projection assertions are unchanged.
2026-11-23 14:43:56 +08:00
overtrue f413a76f54 test(gateway): exercise PUT request boundaries with native inputs 2026-11-23 14:38:32 +08:00
overtrue 65d0a9118c refactor(gateway): use native ETags in metadata listings 2026-11-23 14:38:32 +08:00
57 changed files with 2544 additions and 3358 deletions
Generated
+10 -9
View File
@@ -10396,7 +10396,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway" name = "rustfs-gateway"
version = "0.66.0" version = "0.66.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"bytes", "bytes",
@@ -10443,7 +10443,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-core" name = "rustfs-gateway-core"
version = "0.63.0" version = "0.63.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"bytes", "bytes",
"futures-core", "futures-core",
@@ -10464,7 +10464,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-dialect-rustfs-admin" name = "rustfs-gateway-dialect-rustfs-admin"
version = "0.13.0" version = "0.13.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"bytes", "bytes",
"form_urlencoded", "form_urlencoded",
@@ -10478,7 +10478,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-http" name = "rustfs-gateway-http"
version = "0.1.4" version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"hmac 0.13.0", "hmac 0.13.0",
"http 1.5.0", "http 1.5.0",
@@ -10496,7 +10496,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-macros" name = "rustfs-gateway-macros"
version = "0.1.4" version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -10506,7 +10506,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-sig" name = "rustfs-gateway-sig"
version = "0.15.0" version = "0.15.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"hmac 0.13.0", "hmac 0.13.0",
"http 1.5.0", "http 1.5.0",
@@ -10521,7 +10521,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-stream" name = "rustfs-gateway-stream"
version = "0.2.0" version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"bytes", "bytes",
@@ -10532,7 +10532,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-types" name = "rustfs-gateway-types"
version = "0.42.0+aws.2026-10-02" version = "0.42.0+aws.2026-10-02"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"bytes", "bytes",
"crc-fast", "crc-fast",
@@ -10555,7 +10555,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-xml" name = "rustfs-gateway-xml"
version = "0.4.0" version = "0.4.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"quick-xml 0.41.0", "quick-xml 0.41.0",
] ]
@@ -11340,6 +11340,7 @@ dependencies = [
"hyper", "hyper",
"hyper-util", "hyper-util",
"pin-project-lite", "pin-project-lite",
"quick-xml 0.42.0",
"s3s", "s3s",
"serde", "serde",
"serde_json", "serde_json",
+6 -6
View File
@@ -154,16 +154,16 @@ rustfs-zip = { path = "./crates/zip", version = "1.0.5" }
# engine crates move onto from s3s (rustfs/backlog#2745). The one pin of the # engine crates move onto from s3s (rustfs/backlog#2745). The one pin of the
# gateway in this workspace; no crate may enable a `compat-s3s*` feature except # gateway in this workspace; no crate may enable a `compat-s3s*` feature except
# the s3s-facing edge of the rustfs binary. # the s3s-facing edge of the rustfs binary.
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.42.0", default-features = false } rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.2.0", default-features = false } rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", version = "0.2.0", default-features = false }
# The gateway framework itself, consumed for its extension traits by the ring-2 # The gateway framework itself, consumed for its extension traits by the ring-2
# adapter. `default-features = false` keeps the `server` feature, and with it the # adapter. `default-features = false` keeps the `server` feature, and with it the
# server crate, out of the build. # server crate, out of the build.
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.66.0", default-features = false } rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", version = "0.66.0", default-features = false }
# Test-only: builds the `EffectiveHost` a host-resolution test queries with. # Test-only: builds the `EffectiveHost` a host-resolution test queries with.
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", default-features = false } rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.63.0", default-features = false } rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", version = "0.63.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.13.0", default-features = false } rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", version = "0.13.0", default-features = false }
# Async Runtime and Networking # Async Runtime and Networking
async-channel = "2.5.0" async-channel = "2.5.0"
+3 -1
View File
@@ -36,7 +36,7 @@ default = []
# (rustfs/backlog#2734). Off by default; the runtime dependency tree of this # (rustfs/backlog#2734). Off by default; the runtime dependency tree of this
# crate carries no s3s unless a consumer asks. # crate carries no s3s unless a consumer asks.
# DELETE BY T4.2 (rustfs/backlog#2784) together with src/compat_s3s.rs. # DELETE BY T4.2 (rustfs/backlog#2784) together with src/compat_s3s.rs.
compat-s3s = ["dep:legacy-s3s"] compat-s3s = ["dep:legacy-s3s", "dep:quick-xml"]
hotpath = [] hotpath = []
hotpath-alloc = ["hotpath"] hotpath-alloc = ["hotpath"]
hotpath-cpu = ["hotpath"] hotpath-cpu = ["hotpath"]
@@ -48,6 +48,7 @@ http = { workspace = true }
http-body = { workspace = true } http-body = { workspace = true }
http-body-util = { workspace = true } http-body-util = { workspace = true }
pin-project-lite = { workspace = true } pin-project-lite = { workspace = true }
quick-xml = { workspace = true, optional = true }
# The s3s package under the name the legacy edge knows it by. Only # The s3s package under the name the legacy edge knows it by. Only
# src/compat_s3s.rs may use it; see that file's header for the footprint note. # src/compat_s3s.rs may use it; see that file's header for the footprint note.
legacy-s3s = { workspace = true, optional = true } legacy-s3s = { workspace = true, optional = true }
@@ -55,6 +56,7 @@ serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true, features = ["raw_value"] } serde_json = { workspace = true, features = ["raw_value"] }
[dev-dependencies] [dev-dependencies]
quick-xml = { workspace = true }
# Oracle for the parity tests in src/compat_s3s.rs; never a normal dependency. # Oracle for the parity tests in src/compat_s3s.rs; never a normal dependency.
legacy-s3s = { workspace = true } legacy-s3s = { workspace = true }
# The HTTP/1.1 server those parity tests compare bodies through, byte for byte. # The HTTP/1.1 server those parity tests compare bodies through, byte for byte.
+20 -6
View File
@@ -134,12 +134,26 @@ impl From<S3Error> for legacy_s3s::S3Error {
} }
impl S3Error { impl S3Error {
/// The pinned legacy serializer's XML response. Call sites stay on this type. /// An error wrapped with its original cause can retain response fields the caller did not override.
/// DELETE BY T4.2 with the rest of this file. pub(super) fn into_http_response_parts(self) -> crate::S3ErrorParts {
pub fn to_http_response(self) -> Result<http::Response<crate::Body>, Self> { let mut parts = self.into_parts();
let response = legacy_s3s::S3Error::from(self).to_http_response().map_err(Self::from)?; let original = parts
let (parts, body) = response.into_parts(); .source
Ok(http::Response::from_parts(parts, crate::Body::from(body))) .as_deref()
.and_then(|source| source.downcast_ref::<LegacyCause>())
.map(|cause| &cause.0)
.filter(|error| error.code() == &parts.code.clone().into());
if let Some(original) = original {
parts.message = parts
.message
.or_else(|| original.message().map(|text| Cow::Owned(text.to_owned())));
parts.request_id = parts.request_id.or_else(|| original.request_id().map(str::to_owned));
parts.status = parts.status.or_else(|| original.status_code());
parts.headers = parts.headers.or_else(|| original.headers().cloned());
} else if parts.message.is_none() {
parts.message = parts.code.default_message().map(Cow::Borrowed);
}
parts
} }
} }
@@ -0,0 +1,83 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The legacy HTTP response contract for an owned S3 error.
use super::{S3Error, S3ErrorCode};
use crate::Body;
use http::header::{CONTENT_LENGTH, CONTENT_TYPE, TRANSFER_ENCODING};
use http::{HeaderValue, Response, StatusCode};
use quick_xml::escape::escape;
impl S3Error {
/// Renders this error as an HTTP response using the legacy S3 wire format.
///
/// # Errors
///
/// Returns `InternalError` if an XML field contains a disallowed control character.
pub fn to_http_response(self) -> Result<Response<Body>, Self> {
let parts = self.into_http_response_parts();
let status = parts
.status
.or_else(|| parts.code.status_code())
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
let bodyless = status.is_informational()
|| matches!(status, StatusCode::NO_CONTENT | StatusCode::RESET_CONTENT | StatusCode::NOT_MODIFIED);
let mut response = if bodyless {
Response::new(Body::empty())
} else {
let body = xml_body(parts.code.as_str(), parts.message.as_deref(), parts.request_id.as_deref())?;
let mut response = Response::new(body);
response
.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static("application/xml"));
response
};
*response.status_mut() = status;
if let Some(headers) = parts.headers {
*response.headers_mut() = headers;
}
if bodyless {
let headers = response.headers_mut();
headers.remove(CONTENT_LENGTH);
headers.remove(CONTENT_TYPE);
headers.remove(TRANSFER_ENCODING);
}
Ok(response)
}
}
fn xml_body(code: &str, message: Option<&str>, request_id: Option<&str>) -> Result<Body, S3Error> {
let mut xml = String::from(r#"<?xml version="1.0" encoding="UTF-8"?><Error><Code>"#);
xml.push_str(&escape(code));
xml.push_str("</Code>");
if let Some(message) = message {
xml.push_str("<Message>");
xml.push_str(&escape(message));
xml.push_str("</Message>");
}
if let Some(request_id) = request_id {
xml.push_str("<RequestId>");
xml.push_str(&escape(request_id));
xml.push_str("</RequestId>");
}
xml.push_str("</Error>");
if xml.bytes().any(|byte| byte < b' ' && !matches!(byte, b'\t' | b'\n' | b'\r')) {
return Err(S3Error::with_message(
S3ErrorCode::InternalError,
"XML response contains a control character",
));
}
Ok(Body::from(xml))
}
@@ -0,0 +1,148 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Differential wire tests against the pinned legacy HTTP renderer.
use super::{S3Error, S3ErrorCode};
use http::header::{CONTENT_LENGTH, CONTENT_TYPE, TRANSFER_ENCODING};
use http::{HeaderMap, HeaderValue, StatusCode};
use http_body::Body as _;
use http_body_util::BodyExt;
use legacy_s3s::{S3Error as LegacyError, S3ErrorCode as LegacyCode};
fn errors(name: &str) -> (S3Error, LegacyError) {
let Ok(owned) = name.parse();
let Ok(legacy) = name.parse();
(S3Error::new(owned), LegacyError::new(legacy))
}
async fn assert_response(owned: S3Error, legacy: LegacyError) {
let name = legacy.code().as_str().to_owned();
let expected = legacy.to_http_response().expect("legacy response should render");
let actual = owned.to_http_response().expect("owned response should render");
assert_eq!(actual.status(), expected.status(), "{name}");
assert_eq!(actual.headers(), expected.headers(), "{name}");
assert_eq!(actual.body().is_end_stream(), expected.body().is_end_stream(), "{name}");
let length = expected
.body()
.size_hint()
.exact()
.expect("legacy error body has an exact size");
assert_eq!(actual.body().size_hint().exact(), Some(length), "{name}");
let expected = expected
.into_body()
.collect()
.await
.expect("read legacy error body")
.to_bytes();
let actual = actual.into_body().collect().await.expect("read owned error body").to_bytes();
assert_eq!(actual, expected, "{name}");
assert_eq!(u64::try_from(actual.len()).expect("body length fits in u64"), length, "{name}");
}
#[tokio::test]
async fn named_and_custom_code_defaults_match_legacy() {
for code in S3ErrorCode::NAMED {
let (owned, legacy) = errors(code.as_str());
assert_response(owned, legacy).await;
}
for name in ["", "TierNotFound", "Unknown&<Code>"] {
let (owned, legacy) = errors(name);
assert_response(owned, legacy).await;
}
}
#[tokio::test]
async fn explicit_xml_fields_and_headers_match_legacy() {
let mut headers = HeaderMap::new();
headers.append("x-amz-meta-repeated", HeaderValue::from_static("first"));
headers.append("x-amz-meta-repeated", HeaderValue::from_static("second"));
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/custom"));
headers.insert(CONTENT_LENGTH, HeaderValue::from_static("999"));
for (message, request_id, headers) in [
("", "", None),
("雪<&>\"'\t\n\r", "req<&>\"'雪", Some(HeaderMap::new())),
("message", "request", Some(headers)),
] {
let (mut owned, mut legacy) = errors("Custom&Code");
owned.set_message(message);
legacy.set_message(message);
owned.set_request_id(request_id);
legacy.set_request_id(request_id);
owned.set_status_code(StatusCode::CONFLICT);
legacy.set_status_code(StatusCode::CONFLICT);
if let Some(headers) = headers {
owned.set_headers(headers.clone());
legacy.set_headers(headers);
}
assert_response(owned, legacy).await;
}
}
#[tokio::test]
async fn bodyless_statuses_skip_xml_and_strip_framing_like_legacy() {
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/custom"));
headers.insert(CONTENT_LENGTH, HeaderValue::from_static("11"));
headers.insert(TRANSFER_ENCODING, HeaderValue::from_static("chunked"));
headers.append("warning", HeaderValue::from_static("first"));
headers.append("warning", HeaderValue::from_static("second"));
for status in [100, 101, 103, 199, 204, 205, 304] {
let status = StatusCode::from_u16(status).expect("valid status");
let (mut owned, mut legacy) = errors("InvalidRequest");
owned.set_status_code(status);
legacy.set_status_code(status);
owned.set_message("invalid XML \0");
legacy.set_message("invalid XML \0");
owned.set_headers(headers.clone());
legacy.set_headers(headers.clone());
assert_response(owned, legacy).await;
}
}
#[tokio::test]
async fn invalid_xml_in_each_field_returns_the_legacy_error() {
for (code, message, request_id) in [
("Bad\u{1f}Code", "message", "request"),
("InvalidRequest", "bad\u{b}message", "request"),
("InvalidRequest", "message", "bad\0request"),
] {
let (mut owned, mut legacy) = errors(code);
owned.set_message(message);
legacy.set_message(message);
owned.set_request_id(request_id);
legacy.set_request_id(request_id);
let expected = legacy.to_http_response().expect_err("legacy should reject invalid XML");
let actual = owned.to_http_response().expect_err("owned should reject invalid XML");
assert_eq!(actual.code().as_str(), expected.code().as_str());
assert_eq!(actual.message(), expected.message());
assert_response(actual, expected).await;
}
}
#[tokio::test]
async fn legacy_cause_retains_missing_message_until_the_owned_code_changes() {
// set_code on a legacy error retains its original, absent message.
let legacy_without_message = || {
let mut error =
LegacyError::with_source(LegacyCode::Custom("SourceOnly".into()), Box::new(std::io::Error::other("cause")));
error.set_code(LegacyCode::AccessDenied);
error
};
assert_response(S3Error::from(legacy_without_message()), legacy_without_message()).await;
let mut changed = S3Error::from(legacy_without_message());
changed.set_code(S3ErrorCode::NoSuchKey);
assert_response(changed, LegacyError::new(LegacyCode::NoSuchKey)).await;
}
+6 -2
View File
@@ -15,13 +15,17 @@
//! The S3 error carrier shared by every RustFS crate. //! The S3 error carrier shared by every RustFS crate.
//! //!
//! Responsible for: `S3Error` and its accessor contract, `S3Result`, `StdError`, //! Responsible for: `S3Error` and its accessor contract, `S3Result`, `StdError`,
//! `S3ErrorParts`, and the `s3_error` macro. //! `S3ErrorParts`, the `s3_error` macro, and the legacy-compatible HTTP response.
//! Not responsible for: the code set and its statuses (`code.rs`), s3s //! Not responsible for: the code set and its statuses (`code.rs`), s3s
//! conversions (`crate::compat_s3s`), or rendering an error onto the wire. //! conversions (`crate::compat_s3s`), or the gateway listener's rendering policy.
//! Upstream: `http`. Downstream: every crate that raises S3 errors; the legacy //! Upstream: `http`. Downstream: every crate that raises S3 errors; the legacy
//! edge converts through `compat_s3s`, the gateway edge through `into_parts`. //! edge converts through `compat_s3s`, the gateway edge through `into_parts`.
mod code; mod code;
#[cfg(any(test, feature = "compat-s3s"))]
mod http_response;
#[cfg(test)]
mod http_response_tests;
use http::{HeaderMap, StatusCode}; use http::{HeaderMap, StatusCode};
use std::borrow::Cow; use std::borrow::Cow;
+3 -3
View File
@@ -18,9 +18,9 @@
//! Responsible for: `EventName`, the error surface (`S3Error`, `S3ErrorCode`, //! Responsible for: `EventName`, the error surface (`S3Error`, `S3ErrorCode`,
//! `S3Result`, the `s3_error` macro) that every RustFS crate raises S3 errors with, //! `S3Result`, the `s3_error` macro) that every RustFS crate raises S3 errors with,
//! and `Body`, the type-erased body the outbound client crates send. //! and `Body`, the type-erased body the outbound client crates send.
//! Not responsible for: I/O, global state, wire rendering, S3 body semantics //! The `compat-s3s` feature also renders owned errors as HTTP responses and enables
//! (trailers, checksums, framing), or any s3s type; the legacy conversions live //! conversions to legacy types in `compat_s3s`. Transport I/O, shared state, trailers,
//! behind the `compat-s3s` feature in `compat_s3s` only. //! checksums, and body framing belong to the callers.
//! Upstream: `http`, `bytes`, `http-body`, `http-body-util`. Downstream: every //! Upstream: `http`, `bytes`, `http-body`, `http-body-util`. Downstream: every
//! crate that raises or inspects S3 errors, and the crates that build HTTP bodies. //! crate that raises or inspects S3 errors, and the crates that build HTTP bodies.
+1 -1
View File
@@ -383,7 +383,6 @@ pin-project-lite.workspace = true
parking_lot = { workspace = true } parking_lot = { workspace = true }
rust-embed = { workspace = true, features = ["interpolate-folder-path"] } rust-embed = { workspace = true, features = ["interpolate-folder-path"] }
s3s = { workspace = true, features = ["minio"] } s3s = { workspace = true, features = ["minio"] }
s3s-sigv4 = { workspace = true }
shadow-rs = { workspace = true, default-features = false, features = ["build", "metadata"] } shadow-rs = { workspace = true, default-features = false, features = ["build", "metadata"] }
sysinfo = { workspace = true, features = ["multithread"] } sysinfo = { workspace = true, features = ["multithread"] }
thiserror = { workspace = true } thiserror = { workspace = true }
@@ -424,6 +423,7 @@ h2.workspace = true
rustfs-targets = { workspace = true, features = ["test-support"] } rustfs-targets = { workspace = true, features = ["test-support"] }
uuid = { workspace = true, features = ["v4", "v5", "fast-rng", "macro-diagnostics"] } uuid = { workspace = true, features = ["v4", "v5", "fast-rng", "macro-diagnostics"] }
rustfs-iam = { workspace = true, features = ["test-util"] } rustfs-iam = { workspace = true, features = ["test-util"] }
s3s-sigv4 = { workspace = true }
serial_test = { workspace = true } serial_test = { workspace = true }
tempfile = { workspace = true } tempfile = { workspace = true }
aws-config = { workspace = true } aws-config = { workspace = true }
+43 -64
View File
@@ -472,8 +472,7 @@ mod tests {
use crate::app::bucket_usecase::DefaultBucketUsecase; use crate::app::bucket_usecase::DefaultBucketUsecase;
use crate::app::gating_test_env::{run_large_stack_test, shared_gating_ecstore}; use crate::app::gating_test_env::{run_large_stack_test, shared_gating_ecstore};
use crate::app::storage_api::bucket_usecase::s3::{ use crate::app::storage_api::bucket_usecase::s3::{
GetObjectInput, ListObjectsInput, ListObjectsV2Input, ListObjectsV2Output, S3Request, S3Response, XmlSerialize, ListObjectsInput, ListObjectsV2Input, ListObjectsV2Output, S3Request, S3Response, XmlSerialize, XmlSerializer,
XmlSerializer,
}; };
use crate::app::storage_api::test::StoragePutObjReader; use crate::app::storage_api::test::StoragePutObjReader;
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions}; use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions};
@@ -1170,33 +1169,20 @@ mod tests {
let sys = OnDemandMigrationSys::get(); let sys = OnDemandMigrationSys::get();
let old = sys.state(&input.bucket).expect("original source state"); let old = sys.state(&input.bucket).expect("original source state");
let store = shared_gating_ecstore().await; let store = shared_gating_ecstore().await;
let get = S3Request { let object_envelope = |method, extensions| {
input: GetObjectInput { crate::app::RequestEnvelope::from_parts(
bucket: input.bucket.clone(), crate::app::RequestHead {
key: "missing".into(), method,
..Default::default() uri: http::Uri::from_static("/missing"),
}, headers: HeaderMap::new(),
method: http::Method::GET, credentials: None,
uri: http::Uri::from_static("/missing"), region: None,
headers: HeaderMap::new(), service: None,
extensions: http::Extensions::new(), },
credentials: None, extensions,
region: None, )
service: None,
trailing_headers: None,
}; };
// Method GET, URI `/missing`, empty headers, and empty extensions. let get_env = object_envelope(http::Method::GET, http::Extensions::new());
let get_env = crate::app::RequestEnvelope::from_parts(
crate::app::RequestHead {
method: get.method.clone(),
uri: get.uri.clone(),
headers: get.headers.clone(),
credentials: None,
region: None,
service: None,
},
get.extensions.clone(),
);
let authorized_generation = let authorized_generation =
super::super::storage_api::bucket_usecase::access::load_bucket_generation_from_store( super::super::storage_api::bucket_usecase::access::load_bucket_generation_from_store(
&store, &store,
@@ -1225,27 +1211,13 @@ mod tests {
.expect("replacement identity"); .expect("replacement identity");
assert_ne!(replacement, old.incarnation_id()); assert_ne!(replacement, old.incarnation_id());
sys.remove(&input.bucket); sys.remove(&input.bucket);
let mut without_source = get.clone(); let mut without_source_env = object_envelope(http::Method::GET, http::Extensions::new());
let mut without_source_env = crate::app::RequestEnvelope::from_parts(
crate::app::RequestHead {
method: without_source.method.clone(),
uri: without_source.uri.clone(),
headers: without_source.headers.clone(),
credentials: None,
region: None,
service: None,
},
without_source.extensions.clone(),
);
super::super::storage_api::bucket_usecase::access::prepare_odm_read_generation( super::super::storage_api::bucket_usecase::access::prepare_odm_read_generation(
&store, &store,
&mut without_source_env, &mut without_source_env,
&input.bucket, &input.bucket,
) )
.await; .await;
if let Some(guard) = without_source_env.odm_read_generation().cloned() {
without_source.extensions.insert(guard);
}
for state_incarnation in [old.incarnation_id(), replacement] { for state_incarnation in [old.incarnation_id(), replacement] {
sys.apply_for_incarnation(&input.bucket, state_incarnation, Some(old.config())) sys.apply_for_incarnation(&input.bucket, state_incarnation, Some(old.config()))
.await; .await;
@@ -1255,31 +1227,38 @@ mod tests {
if capture == 0 && state_incarnation == replacement { if capture == 0 && state_incarnation == replacement {
continue; continue;
} }
let mut get = if capture == 2 { without_source.clone() } else { get.clone() }; let mut extensions = http::Extensions::new();
if capture == 1 { if capture == 1 {
get.extensions.insert(authorized_generation.clone()); extensions.insert(authorized_generation.clone());
} else if capture == 2
&& let Some(guard) = without_source_env.odm_read_generation().cloned()
{
extensions.insert(guard);
} }
let head_envelope = crate::app::RequestEnvelope::from_parts( let get_envelope = object_envelope(http::Method::GET, extensions.clone());
crate::app::RequestHead { let head_envelope = object_envelope(http::Method::HEAD, extensions.clone());
method: http::Method::HEAD, let get = crate::app::test_seams::get_object_input(&input.bucket, "missing", None);
uri: get.uri.clone(),
headers: get.headers.clone(),
credentials: None,
region: None,
service: None,
},
get.extensions.clone(),
);
let head = crate::app::test_seams::head_object_input(&input.bucket, "missing", None); let head = crate::app::test_seams::head_object_input(&input.bucket, "missing", None);
let mut list = get.clone().map_input(|_| input.clone()); let list = S3Request {
list.uri = http::Uri::from_static("/?list-type=2"); input: input.clone(),
method: http::Method::GET,
uri: http::Uri::from_static("/?list-type=2"),
headers: HeaderMap::new(),
extensions,
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
let usecase = crate::app::object::DefaultObjectUsecase::from_global(); let usecase = crate::app::object::DefaultObjectUsecase::from_global();
let get_error = let get_error = tokio::time::timeout(
tokio::time::timeout(Duration::from_secs(10), crate::app::test_seams::get_object(&usecase, get)) Duration::from_secs(10),
.await crate::app::test_seams::get_object_gateway(&usecase, get_envelope, get),
.expect("GET stays local") )
.expect_err("local object is absent"); .await
assert_eq!(*get_error.code(), S3ErrorCode::NoSuchKey); .expect("GET stays local")
.expect_err("local object is absent");
assert_eq!(get_error.code(), &rustfs_s3_types::S3ErrorCode::NoSuchKey);
let head_error = tokio::time::timeout( let head_error = tokio::time::timeout(
Duration::from_secs(10), Duration::from_secs(10),
crate::app::test_seams::head_object_gateway(&usecase, head_envelope, head), crate::app::test_seams::head_object_gateway(&usecase, head_envelope, head),
+12 -2
View File
@@ -56,7 +56,6 @@ use super::storage_api::bucket_usecase::contract::list::{
}; };
use super::storage_api::bucket_usecase::error::StorageError; use super::storage_api::bucket_usecase::error::StorageError;
use super::storage_api::bucket_usecase::helper::{OperationHelper, spawn_background_with_context}; use super::storage_api::bucket_usecase::helper::{OperationHelper, spawn_background_with_context};
use super::storage_api::bucket_usecase::object_utils::to_s3s_xml_etag;
use super::storage_api::bucket_usecase::s3_api::bucket::{ use super::storage_api::bucket_usecase::s3_api::bucket::{
ListObjectVersionsParams, ListObjectsV2Params, encode_list_objects_v2_continuation_token, parse_list_object_versions_params, ListObjectVersionsParams, ListObjectsV2Params, encode_list_objects_v2_continuation_token, parse_list_object_versions_params,
parse_list_objects_v2_params, rustfs_owner, parse_list_objects_v2_params, rustfs_owner,
@@ -999,7 +998,18 @@ mod tests {
}, },
); );
let envelope = RequestEnvelope::from_s3s(&req); // Same facts `RequestEnvelope::from_s3s` copies. Credentials, region, and service stay absent.
let envelope = RequestEnvelope::from_parts(
crate::app::RequestHead {
method: req.method,
uri: req.uri,
headers: req.headers,
credentials: None,
region: None,
service: None,
},
req.extensions,
);
assert!(envelope.req_info().expect("req info should be present").is_owner); assert!(envelope.req_info().expect("req info should be present").is_owner);
} }
-1
View File
@@ -16,7 +16,6 @@
use super::*; use super::*;
use crate::app::storage_api::bucket_usecase::access::requested_bucket_force_delete; use crate::app::storage_api::bucket_usecase::access::requested_bucket_force_delete;
use crate::app::storage_api::s3::S3Error;
use rustfs_s3_types::Region; use rustfs_s3_types::Region;
/// Whether `CreateBucket` may record `location`: the server's own region, or /// Whether `CreateBucket` may record `location`: the server's own region, or
+21 -4
View File
@@ -15,8 +15,8 @@
//! Bucket lifecycle configuration use-case operations. //! Bucket lifecycle configuration use-case operations.
use super::*; use super::*;
use crate::app::storage_api::s3::{S3Error, S3ErrorCode, s3_error};
use rustfs_gateway_types::persistence::{PersistedLifecycleRule, parse_lifecycle_dto}; use rustfs_gateway_types::persistence::{PersistedLifecycleRule, parse_lifecycle_dto};
use rustfs_s3_types::{S3Error, S3ErrorCode, s3_error};
const ERR_LIFECYCLE_RULE_STATUS: &str = "Rule status must be either Enabled or Disabled"; const ERR_LIFECYCLE_RULE_STATUS: &str = "Rule status must be either Enabled or Disabled";
@@ -271,7 +271,7 @@ impl DefaultBucketUsecase {
let mut input_cfg = prepared_configuration.map_err(to_internal_error)?; let mut input_cfg = prepared_configuration.map_err(to_internal_error)?;
assign_lifecycle_rule_ids(&mut input_cfg.rules); assign_lifecycle_rule_ids(&mut input_cfg.rules);
if let Err(err) = validate_lifecycle_config(&input_cfg, &rcfg).await { if let Err(err) = validate_lifecycle_config(&input_cfg, &rcfg).await {
return Err(lifecycle_validation_error(&err).into()); return Err(lifecycle_validation_error(&err));
} }
if let Err(err) = validate_transition_tier(&input_cfg).await { if let Err(err) = validate_transition_tier(&input_cfg).await {
@@ -695,7 +695,6 @@ mod tests {
) )
.await .await
.expect_err("a Filter And with one predicate is a schema violation"); .expect_err("a Filter And with one predicate is a schema violation");
assert_eq!(*lifecycle_validation_error(&malformed).code(), S3ErrorCode::MalformedXML);
let invalid_value = validate_lifecycle_config( let invalid_value = validate_lifecycle_config(
&rustfs_gateway_types::persistence::PersistedLifecycleConfiguration { &rustfs_gateway_types::persistence::PersistedLifecycleConfiguration {
@@ -722,7 +721,25 @@ mod tests {
) )
.await .await
.expect_err("a negative retention count is rejected"); .expect_err("a negative retention count is rejected");
assert_eq!(*lifecycle_validation_error(&invalid_value).code(), S3ErrorCode::InvalidArgument); for (failure, code, message) in [
(
malformed,
S3ErrorCode::MalformedXML,
"Malformed XML: Filter And must contain at least two predicates",
),
(
invalid_value,
S3ErrorCode::InvalidArgument,
"'NewerNoncurrentVersions' must be a non-negative integer",
),
] {
let error = lifecycle_validation_error(&failure);
assert_eq!(error.code(), &code);
assert_eq!(error.message(), Some(message));
assert_eq!(error.status_code(), Some(StatusCode::BAD_REQUEST));
assert!(error.headers().is_none());
assert!(std::error::Error::source(&error).is_none());
}
} }
#[test] #[test]
+391 -209
View File
@@ -14,17 +14,22 @@
//! Object and version listing use-case operations, including the metadata listing extension. //! Object and version listing use-case operations, including the metadata listing extension.
use super::list_objects::listed_etag;
use super::*; use super::*;
use crate::app::storage_api::bucket_usecase::contract::list::ListOperations as _; use crate::app::storage_api::bucket_usecase::contract::list::ListOperations as _;
#[cfg(test)] #[cfg(test)]
use crate::app::storage_api::s3::S3ErrorCode; use crate::app::storage_api::s3::S3ErrorCode;
use crate::app::storage_api::s3::S3Result;
use crate::app::storage_api::s3::dto::{ use crate::app::storage_api::s3::dto::{
CommonPrefix, DeleteMarkerEntry, EncodingType, ListObjectVersionsInput, ListObjectVersionsOutput, ListObjectsV2Input, CommonPrefix, EncodingType, ListObjectVersionsInput, ListObjectVersionsOutput, ListObjectsV2Input, ListObjectsV2Output,
ListObjectsV2Output, MetadataEntry, Object, ObjectStorageClass, ObjectVersion, ObjectVersionStorageClass, Owner, Timestamp, MetadataEntry, ObjectStorageClass, Owner, Timestamp, TimestampFormat, UserMetadata,
UserMetadata,
}; };
use crate::app::storage_api::s3::xml::{SerResult, SerializeContent}; use quick_xml::{
use crate::app::storage_api::s3::{S3Result, xml}; Writer,
events::{BytesDecl, BytesText, Event},
};
use rustfs_gateway_types::ETag;
use std::io;
type ListObjectVersionsInfo = StorageListObjectVersionsInfo<ObjectInfo>; type ListObjectVersionsInfo = StorageListObjectVersionsInfo<ObjectInfo>;
@@ -47,8 +52,8 @@ pub(crate) struct ObjectMetadataExtension {
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub(crate) enum ListObjectVersionMetadataEntry { pub(crate) enum ListObjectVersionMetadataEntry {
DeleteMarker(DeleteMarkerEntry, ObjectMetadataExtension), DeleteMarker(MetadataObject, ObjectMetadataExtension),
Version(ObjectVersion, ObjectMetadataExtension), Version(ObjectMetadataEntry),
} }
#[derive(Clone, Debug, Default, PartialEq)] #[derive(Clone, Debug, Default, PartialEq)]
@@ -57,9 +62,21 @@ pub(crate) struct ListObjectVersionsMetadataOutput {
pub entries: Vec<ListObjectVersionMetadataEntry>, pub entries: Vec<ListObjectVersionMetadataEntry>,
} }
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct MetadataObject {
key: String,
is_latest: Option<bool>,
last_modified: Option<Timestamp>,
owner: Option<Owner>,
size: Option<i64>,
storage_class: Option<String>,
version_id: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq)] #[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct ObjectMetadataEntry { pub(crate) struct ObjectMetadataEntry {
pub object: Object, pub object: MetadataObject,
pub e_tag: Option<ETag>,
pub extension: ObjectMetadataExtension, pub extension: ObjectMetadataExtension,
} }
@@ -69,137 +86,126 @@ pub(crate) struct ListObjectsV2MetadataOutput {
pub contents: Vec<ObjectMetadataEntry>, pub contents: Vec<ObjectMetadataEntry>,
} }
impl xml::Serialize for ListObjectVersionsMetadataOutput { type ListingWriter = Writer<Vec<u8>>;
fn serialize<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult {
s.content_with_ns("ListVersionsResult", XMLNS_S3, self) fn document(root: &str, content: impl FnOnce(&mut ListingWriter) -> io::Result<()>) -> io::Result<Vec<u8>> {
} let mut writer = Writer::new(Vec::with_capacity(1024));
writer.write_event(Event::Decl(BytesDecl::new("1.0", Some("UTF-8"), None)))?;
writer
.create_element(root)
.with_attribute(("xmlns", XMLNS_S3))
.write_inner_content(content)?;
Ok(writer.into_inner())
} }
impl SerializeContent for ListObjectVersionsMetadataOutput { fn text(xml: &mut Writer<impl Write>, name: &str, value: Option<&str>) -> io::Result<()> {
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { if let Some(value) = value {
if let Some(iter) = &self.output.common_prefixes { xml.create_element(name).write_text_content(BytesText::new(value))?;
s.flattened_list("CommonPrefixes", iter)?; }
} Ok(())
if let Some(ref val) = self.output.delimiter { }
s.content("Delimiter", val)?;
} fn display_field(xml: &mut ListingWriter, name: &str, value: Option<impl Display>) -> io::Result<()> {
if let Some(ref val) = self.output.encoding_type { text(xml, name, value.map(|v| v.to_string()).as_deref())
s.content("EncodingType", val)?; }
}
if let Some(ref val) = self.output.is_truncated { fn write_prefixes(xml: &mut ListingWriter, prefixes: Option<&[CommonPrefix]>) -> io::Result<()> {
s.content("IsTruncated", val)?; for prefix in prefixes.unwrap_or_default() {
} xml.create_element("CommonPrefixes")
if let Some(ref val) = self.output.key_marker { .write_inner_content(|xml| text(xml, "Prefix", prefix.prefix.as_deref()))?;
s.content("KeyMarker", val)?; }
} Ok(())
if let Some(ref val) = self.output.max_keys { }
s.content("MaxKeys", val)?;
} impl ListObjectVersionsMetadataOutput {
if let Some(ref val) = self.output.name { pub(crate) fn to_xml(&self) -> io::Result<Vec<u8>> {
s.content("Name", val)?; let page = &self.output;
} document("ListVersionsResult", |xml| {
if let Some(ref val) = self.output.next_key_marker { write_prefixes(xml, page.common_prefixes.as_deref())?;
s.content("NextKeyMarker", val)?; text(xml, "Delimiter", page.delimiter.as_deref())?;
} text(xml, "EncodingType", page.encoding_type.as_ref().map(EncodingType::as_str))?;
if let Some(ref val) = self.output.next_version_id_marker { display_field(xml, "IsTruncated", page.is_truncated)?;
s.content("NextVersionIdMarker", val)?; text(xml, "KeyMarker", page.key_marker.as_deref())?;
} display_field(xml, "MaxKeys", page.max_keys)?;
if let Some(ref val) = self.output.prefix { text(xml, "Name", page.name.as_deref())?;
s.content("Prefix", val)?; text(xml, "NextKeyMarker", page.next_key_marker.as_deref())?;
} text(xml, "NextVersionIdMarker", page.next_version_id_marker.as_deref())?;
if let Some(ref val) = self.output.version_id_marker { text(xml, "Prefix", page.prefix.as_deref())?;
s.content("VersionIdMarker", val)?; text(xml, "VersionIdMarker", page.version_id_marker.as_deref())?;
} for entry in &self.entries {
for entry in &self.entries { match entry {
match entry { ListObjectVersionMetadataEntry::DeleteMarker(marker, extension) => {
ListObjectVersionMetadataEntry::DeleteMarker(marker, extension) => { xml.create_element("DeleteMarker").write_inner_content(|xml| {
s.content( marker.write_xml(xml)?;
"DeleteMarker", extension.write_xml(xml)
&VersionMetadataContent { })?;
value: marker, }
extension, ListObjectVersionMetadataEntry::Version(entry) => {
}, xml.create_element("Version")
)?; .write_inner_content(|xml| entry.write_xml(xml))?;
} }
ListObjectVersionMetadataEntry::Version(version, extension) => {
s.content(
"Version",
&VersionMetadataContent {
value: version,
extension,
},
)?;
} }
} }
} Ok(())
Ok(()) })
} }
} }
impl xml::Serialize for ListObjectsV2MetadataOutput { impl ListObjectsV2MetadataOutput {
fn serialize<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { pub(crate) fn to_xml(&self) -> io::Result<Vec<u8>> {
s.content_with_ns("ListBucketResult", XMLNS_S3, self) let page = &self.output;
document("ListBucketResult", |xml| {
text(xml, "Name", page.name.as_deref())?;
text(xml, "Prefix", page.prefix.as_deref())?;
display_field(xml, "MaxKeys", page.max_keys)?;
display_field(xml, "KeyCount", page.key_count)?;
text(xml, "ContinuationToken", page.continuation_token.as_deref())?;
display_field(xml, "IsTruncated", page.is_truncated)?;
text(xml, "NextContinuationToken", page.next_continuation_token.as_deref())?;
for entry in &self.contents {
xml.create_element("Contents")
.write_inner_content(|xml| entry.write_xml(xml))?;
}
write_prefixes(xml, page.common_prefixes.as_deref())?;
text(xml, "Delimiter", page.delimiter.as_deref())?;
text(xml, "EncodingType", page.encoding_type.as_ref().map(EncodingType::as_str))?;
text(xml, "StartAfter", page.start_after.as_deref())
})
} }
} }
impl SerializeContent for ListObjectsV2MetadataOutput { impl ObjectMetadataEntry {
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { fn write_xml(&self, xml: &mut ListingWriter) -> io::Result<()> {
if let Some(ref val) = self.output.name { if let Some(etag) = &self.e_tag {
s.content("Name", val)?; // The XML listing uses literal outer quotes even for a weak tag. The opaque text is escaped.
let quoted = format!("\"{}\"", quick_xml::escape::escape(etag.opaque_tag()));
xml.create_element("ETag")
.write_text_content(BytesText::from_escaped(quoted))?;
} }
if let Some(ref val) = self.output.prefix { self.object.write_xml(xml)?;
s.content("Prefix", val)?; self.extension.write_xml(xml)
}
if let Some(ref val) = self.output.max_keys {
s.content("MaxKeys", val)?;
}
if let Some(ref val) = self.output.key_count {
s.content("KeyCount", val)?;
}
if let Some(ref val) = self.output.continuation_token {
s.content("ContinuationToken", val)?;
}
if let Some(ref val) = self.output.is_truncated {
s.content("IsTruncated", val)?;
}
if let Some(ref val) = self.output.next_continuation_token {
s.content("NextContinuationToken", val)?;
}
for entry in &self.contents {
s.content("Contents", entry)?;
}
if let Some(iter) = &self.output.common_prefixes {
s.flattened_list("CommonPrefixes", iter)?;
}
if let Some(ref val) = self.output.delimiter {
s.content("Delimiter", val)?;
}
if let Some(ref val) = self.output.encoding_type {
s.content("EncodingType", val)?;
}
if let Some(ref val) = self.output.start_after {
s.content("StartAfter", val)?;
}
Ok(())
} }
} }
struct VersionMetadataContent<'a, T> { impl MetadataObject {
value: &'a T, fn write_xml(&self, xml: &mut ListingWriter) -> io::Result<()> {
extension: &'a ObjectMetadataExtension, display_field(xml, "IsLatest", self.is_latest)?;
} text(xml, "Key", Some(&self.key))?;
if let Some(date) = &self.last_modified {
impl<T: SerializeContent> SerializeContent for VersionMetadataContent<'_, T> { xml.create_element("LastModified").write_inner_content(|xml| {
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { date.format(TimestampFormat::DateTime, xml.get_mut())
self.value.serialize_content(s)?; .map_err(io::Error::other)
self.extension.serialize_content(s) })?;
} }
} if let Some(owner) = &self.owner {
xml.create_element("Owner").write_inner_content(|xml| {
impl SerializeContent for ObjectMetadataEntry { text(xml, "DisplayName", owner.display_name.as_deref())?;
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { text(xml, "ID", owner.id.as_deref())
self.object.serialize_content(s)?; })?;
self.extension.serialize_content(s) }
display_field(xml, "Size", self.size)?;
text(xml, "StorageClass", self.storage_class.as_deref())?;
text(xml, "VersionId", self.version_id.as_deref())
} }
} }
@@ -237,41 +243,31 @@ fn sanitize_xml_text(value: &str) -> Cow<'_, str> {
} }
} }
impl SerializeContent for ObjectMetadataExtension { impl ObjectMetadataExtension {
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { fn write_xml(&self, xml: &mut ListingWriter) -> io::Result<()> {
if let Some(metadata) = &self.user_metadata { if let Some(metadata) = &self.user_metadata {
s.element("UserMetadata", |s| { xml.create_element("UserMetadata").write_inner_content(|xml| {
for entry in metadata { for entry in metadata {
if let (Some(name), Some(value)) = (&entry.name, &entry.value) { if let (Some(name), Some(value)) = (&entry.name, &entry.value)
// Skip entries whose key is not a valid XML element name and strip && is_valid_xml_name(name)
// XML-illegal control characters from the value, so a single poison {
// object can never corrupt the whole listing document. See issue #2743. text(xml, name, Some(&sanitize_xml_text(value)))?;
if is_valid_xml_name(name) {
let sanitized = sanitize_xml_text(value);
s.content(name, sanitized.as_ref())?;
}
} }
} }
Ok(()) Ok(())
})?; })?;
} }
if let Some(tags) = &self.user_tags { text(xml, "UserTags", self.user_tags.as_deref())?;
s.content("UserTags", tags)?;
}
if let Some(internal) = &self.internal { if let Some(internal) = &self.internal {
s.content("Internal", internal)?; xml.create_element("Internal").write_inner_content(|xml| {
display_field(xml, "K", Some(internal.k))?;
display_field(xml, "M", Some(internal.m))
})?;
} }
Ok(()) Ok(())
} }
} }
impl SerializeContent for ObjectInternalInfo {
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult {
s.content("K", &self.k)?;
s.content("M", &self.m)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct ObjectMetadataPermissions { struct ObjectMetadataPermissions {
metadata_allowed: bool, metadata_allowed: bool,
@@ -441,38 +437,34 @@ fn build_list_object_versions_metadata_output(
if object.delete_marker { if object.delete_marker {
ListObjectVersionMetadataEntry::DeleteMarker( ListObjectVersionMetadataEntry::DeleteMarker(
DeleteMarkerEntry { MetadataObject {
key: Some(object_name), key: object_name,
last_modified: object.mod_time.map(Timestamp::from), last_modified: object.mod_time.map(Timestamp::from),
owner: Some(owner.clone()), owner: Some(owner.clone()),
version_id: Some(version_id), version_id: Some(version_id),
is_latest: Some(object.is_latest), is_latest: Some(object.is_latest),
},
extension,
)
} else {
ListObjectVersionMetadataEntry::Version(
ObjectVersion {
key: Some(object_name),
last_modified: object.mod_time.map(Timestamp::from),
size: Some(object.size),
version_id: Some(version_id),
is_latest: Some(object.is_latest),
e_tag: object
.etag
.as_ref()
.filter(|_| rustfs_utils::http::etag_can_be_listed(&object.user_defined))
.map(|etag| to_s3s_xml_etag(etag)),
storage_class: Some(ObjectVersionStorageClass::from(
object
.storage_class
.unwrap_or_else(|| ObjectVersionStorageClass::STANDARD.to_string()),
)),
owner: Some(owner.clone()),
..Default::default() ..Default::default()
}, },
extension, extension,
) )
} else {
ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry {
e_tag: listed_etag(&object),
object: MetadataObject {
key: object_name,
last_modified: object.mod_time.map(Timestamp::from),
size: Some(object.size),
version_id: Some(version_id),
is_latest: Some(object.is_latest),
storage_class: Some(
object
.storage_class
.unwrap_or_else(|| ObjectStorageClass::STANDARD.to_string()),
),
owner: Some(owner.clone()),
},
extension,
})
} }
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@@ -545,21 +537,17 @@ fn build_list_objects_v2_metadata_output(
}; };
ObjectMetadataEntry { ObjectMetadataEntry {
object: Object { e_tag: listed_etag(object),
key: Some(encode_list_objects_v2_value(&object.name, encoding_type)), object: MetadataObject {
key: encode_list_objects_v2_value(&object.name, encoding_type),
last_modified: object.mod_time.map(Timestamp::from), last_modified: object.mod_time.map(Timestamp::from),
size: Some(object.get_actual_size_or_physical()), size: Some(object.get_actual_size_or_physical()),
e_tag: object storage_class: Some(
.etag
.as_ref()
.filter(|_| rustfs_utils::http::etag_can_be_listed(&object.user_defined))
.map(|etag| to_s3s_xml_etag(etag)),
storage_class: Some(ObjectStorageClass::from(
object object
.storage_class .storage_class
.clone() .clone()
.unwrap_or_else(|| ObjectStorageClass::STANDARD.to_string()), .unwrap_or_else(|| ObjectStorageClass::STANDARD.to_string()),
)), ),
owner: fetch_owner.then_some(owner.clone()), owner: fetch_owner.then_some(owner.clone()),
..Default::default() ..Default::default()
}, },
@@ -743,14 +731,160 @@ mod tests {
use crate::app::bucket_usecase::test_support::owned_envelope; use crate::app::bucket_usecase::test_support::owned_envelope;
use http::Method; use http::Method;
/// Response bodies are not bucket configurations: they are written by the #[test]
/// s3s encoder itself, as the legacy stack does. fn metadata_listings_match_the_legacy_xml_bytes() {
fn serialize_s3s_response<T: xml::Serialize>(value: &T) -> Vec<u8> { let owner = Owner {
let mut buf = Vec::new(); display_name: Some("user<&".into()),
value id: Some("a'b".into()),
.serialize(&mut xml::Serializer::new(&mut buf)) };
.expect("metadata output should serialize"); let at = Timestamp::from(time::OffsetDateTime::from_unix_timestamp_nanos(1_700_000_000_123_456_789).unwrap());
buf let object = MetadataObject {
key: "key&".into(),
last_modified: Some(at),
owner: Some(owner),
..Default::default()
};
let extension = ObjectMetadataExtension {
user_metadata: Some(vec![
MetadataEntry {
name: Some("bad key".into()),
value: Some("absent".into()),
},
MetadataEntry {
name: Some("键名".into()),
value: Some("a\u{1}\t\n\r<&>\"'".into()),
},
]),
user_tags: Some("tag=x&z=y".into()),
internal: Some(ObjectInternalInfo { k: 4, m: 2 }),
};
let prefixes = Some(vec![CommonPrefix {
prefix: Some("dir/".into()),
}]);
let v2 = ListObjectsV2MetadataOutput {
output: ListObjectsV2Output {
name: Some("bucket".into()),
prefix: Some(String::new()),
max_keys: Some(3),
key_count: Some(2),
continuation_token: Some("a+b".into()),
is_truncated: Some(true),
next_continuation_token: Some("c=".into()),
common_prefixes: prefixes.clone(),
delimiter: Some("/".into()),
encoding_type: Some(EncodingType::from_static("url")),
start_after: Some("key\r".into()),
..Default::default()
},
contents: vec![ObjectMetadataEntry {
object: MetadataObject {
size: Some(9),
storage_class: Some("STANDARD".into()),
..object.clone()
},
e_tag: Some(ETag::from_stored("x<&\"'")),
extension: extension.clone(),
}],
};
let versions = ListObjectVersionsMetadataOutput {
output: ListObjectVersionsOutput {
common_prefixes: prefixes,
delimiter: Some("/".into()),
encoding_type: Some(EncodingType::from_static("url")),
is_truncated: Some(false),
key_marker: Some(String::new()),
max_keys: Some(3),
name: Some("bucket".into()),
next_key_marker: Some("mark".into()),
next_version_id_marker: Some("next".into()),
prefix: Some("prefix".into()),
version_id_marker: Some(String::new()),
..Default::default()
},
entries: vec![
ListObjectVersionMetadataEntry::DeleteMarker(
MetadataObject {
is_latest: Some(true),
version_id: Some("null".into()),
..object.clone()
},
ObjectMetadataExtension {
user_metadata: Some(vec![]),
..Default::default()
},
),
ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry {
object: MetadataObject {
is_latest: Some(false),
size: Some(99),
storage_class: Some("GLACIER".into()),
version_id: Some("v1".into()),
..object
},
e_tag: Some(ETag::new_weak("weak").unwrap()),
extension,
}),
],
};
// Complete documents captured from the metadata route's s3s serializer at 056e59af7.
assert_eq!(
v2.to_xml().unwrap(),
concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Name>bucket</Name>",
"<Prefix></Prefix><MaxKeys>3</MaxKeys><KeyCount>2</KeyCount>",
"<ContinuationToken>a+b</ContinuationToken><IsTruncated>true</IsTruncated>",
"<NextContinuationToken>c=</NextContinuationToken><Contents>",
"<ETag>\"x&lt;&amp;&quot;&apos;\"</ETag><Key>key&amp;</Key>",
"<LastModified>2023-11-14T22:13:20.123Z</LastModified><Owner>",
"<DisplayName>user&lt;&amp;</DisplayName><ID>a&apos;b</ID></Owner><Size>9</Size>",
"<StorageClass>STANDARD</StorageClass><UserMetadata>",
"<键名>a\t\n&#13;&lt;&amp;&gt;&quot;&apos;</键名></UserMetadata>",
"<UserTags>tag=x&amp;z=y</UserTags><Internal><K>4</K><M>2</M></Internal></Contents>",
"<CommonPrefixes><Prefix>dir/</Prefix></CommonPrefixes><Delimiter>/</Delimiter>",
"<EncodingType>url</EncodingType><StartAfter>key&#13;</StartAfter></ListBucketResult>",
)
.as_bytes()
);
assert_eq!(
versions.to_xml().unwrap(),
concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"<ListVersionsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><CommonPrefixes>",
"<Prefix>dir/</Prefix></CommonPrefixes><Delimiter>/</Delimiter>",
"<EncodingType>url</EncodingType><IsTruncated>false</IsTruncated><KeyMarker></KeyMarker>",
"<MaxKeys>3</MaxKeys><Name>bucket</Name><NextKeyMarker>mark</NextKeyMarker>",
"<NextVersionIdMarker>next</NextVersionIdMarker><Prefix>prefix</Prefix><VersionIdMarker>",
"</VersionIdMarker><DeleteMarker><IsLatest>true</IsLatest><Key>key&amp;</Key>",
"<LastModified>2023-11-14T22:13:20.123Z</LastModified><Owner>",
"<DisplayName>user&lt;&amp;</DisplayName><ID>a&apos;b</ID></Owner>",
"<VersionId>null</VersionId><UserMetadata></UserMetadata></DeleteMarker><Version>",
"<ETag>\"weak\"</ETag><IsLatest>false</IsLatest><Key>key&amp;</Key>",
"<LastModified>2023-11-14T22:13:20.123Z</LastModified><Owner>",
"<DisplayName>user&lt;&amp;</DisplayName><ID>a&apos;b</ID></Owner><Size>99</Size>",
"<StorageClass>GLACIER</StorageClass><VersionId>v1</VersionId><UserMetadata>",
"<键名>a\t\n&#13;&lt;&amp;&gt;&quot;&apos;</键名></UserMetadata>",
"<UserTags>tag=x&amp;z=y</UserTags><Internal><K>4</K><M>2</M></Internal></Version>",
"</ListVersionsResult>",
)
.as_bytes()
);
assert_eq!(
ListObjectsV2MetadataOutput::default().to_xml().unwrap(),
concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"></ListBucketResult>",
)
.as_bytes()
);
assert_eq!(
ListObjectVersionsMetadataOutput::default().to_xml().unwrap(),
concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"<ListVersionsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"></ListVersionsResult>",
)
.as_bytes()
);
} }
#[tokio::test] #[tokio::test]
@@ -806,6 +940,20 @@ mod tests {
user_defined: Arc::new(HashMap::from([("x-rustfs-encryption-original-size".to_owned(), "10485760".to_owned())])), user_defined: Arc::new(HashMap::from([("x-rustfs-encryption-original-size".to_owned(), "10485760".to_owned())])),
..Default::default() ..Default::default()
}, },
ObjectInfo {
name: "weak".to_owned(),
etag: Some(r#"W/"a&<b""#.to_owned()),
..Default::default()
},
ObjectInfo {
name: "stored-entities".to_owned(),
etag: Some(r#"x"'<>&amp;"#.to_owned()),
..Default::default()
},
ObjectInfo {
name: "no-etag".to_owned(),
..Default::default()
},
]; ];
let listings = build_list_objects_v2_metadata_output( let listings = build_list_objects_v2_metadata_output(
ListObjectsV2Info { ListObjectsV2Info {
@@ -826,15 +974,13 @@ mod tests {
false, false,
&HashMap::new(), &HashMap::new(),
); );
assert!(listings.contents[0].object.e_tag.is_none()); assert!(listings.contents[0].e_tag.is_none());
assert!(listings.contents[1].object.e_tag.is_some()); assert!(listings.contents[1].e_tag.is_some());
assert!(listings.contents[2].object.e_tag.is_some()); assert!(listings.contents[2].e_tag.is_some());
assert_eq!( assert_eq!(
listings.contents[3].object.e_tag, listings.contents[3].e_tag.as_ref().map(ETag::opaque_tag),
Some(to_s3s_xml_etag("1b8a77dff5845270a8d81d86a28f38ea-2")) Some("1b8a77dff5845270a8d81d86a28f38ea-2")
); );
let xml = String::from_utf8(serialize_s3s_response(&listings)).expect("UTF-8 objects");
assert!(!xml.contains(legacy_md5));
let versions = build_list_object_versions_metadata_output( let versions = build_list_object_versions_metadata_output(
ListObjectVersionsInfo { ListObjectVersionsInfo {
@@ -853,13 +999,41 @@ mod tests {
&HashMap::new(), &HashMap::new(),
); );
for (index, entry) in versions.entries.iter().enumerate() { for (index, entry) in versions.entries.iter().enumerate() {
let ListObjectVersionMetadataEntry::Version(version, _) = entry else { let ListObjectVersionMetadataEntry::Version(version) = entry else {
panic!("expected object version"); panic!("expected object version");
}; };
assert_eq!(version.e_tag, listings.contents[index].object.e_tag); assert_eq!(version.e_tag, listings.contents[index].e_tag);
}
#[derive(serde::Deserialize)]
struct Listing {
#[serde(rename = "Contents", alias = "Version")]
entries: Vec<Entry>,
}
#[derive(serde::Deserialize)]
struct Entry {
#[serde(rename = "ETag")]
e_tag: Option<String>,
}
for bytes in [listings.to_xml().unwrap(), versions.to_xml().unwrap()] {
let xml = std::str::from_utf8(&bytes).expect("UTF-8 listing");
assert!(!xml.contains(legacy_md5));
assert!(xml.contains(r#"<ETag>"a&amp;&lt;b"</ETag>"#));
assert!(xml.contains(r#"<ETag>"x&quot;&apos;&lt;&gt;&amp;amp;"</ETag>"#));
let listing: Listing = quick_xml::de::from_str(xml).expect("well-formed listing");
let tags: Vec<_> = listing.entries.iter().map(|entry| entry.e_tag.as_deref()).collect();
assert_eq!(
tags,
[
None,
Some(r#""0123456789abcdef0123456789abcdef""#),
Some(r#""9876543210abcdef9876543210abcdef""#),
Some(r#""1b8a77dff5845270a8d81d86a28f38ea-2""#),
Some(r#""a&<b""#),
Some(r#""x"'<>&amp;""#),
None,
]
);
} }
let xml = String::from_utf8(serialize_s3s_response(&versions)).expect("UTF-8 versions");
assert!(!xml.contains(legacy_md5));
} }
#[test] #[test]
@@ -941,7 +1115,7 @@ mod tests {
&permissions, &permissions,
); );
for (index, entry) in versions.entries.iter().enumerate() { for (index, entry) in versions.entries.iter().enumerate() {
let ListObjectVersionMetadataEntry::Version(_, extension) = entry else { let ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry { extension, .. }) = entry else {
panic!("expected version"); panic!("expected version");
}; };
assert_eq!(extension.user_metadata.is_some(), index >= 2); assert_eq!(extension.user_metadata.is_some(), index >= 2);
@@ -1025,8 +1199,12 @@ mod tests {
assert_eq!(output.entries.len(), 2); assert_eq!(output.entries.len(), 2);
match &output.entries[0] { match &output.entries[0] {
ListObjectVersionMetadataEntry::Version(version, extension) => { ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry {
assert_eq!(version.key.as_deref(), Some("obj-a")); object: version,
extension,
..
}) => {
assert_eq!(version.key, "obj-a");
// A null version's synthesized nil UUID must surface as the // A null version's synthesized nil UUID must surface as the
// literal `null`, never as `00000000-…` (issue #6745). // literal `null`, never as `00000000-…` (issue #6745).
assert_eq!(version.version_id.as_deref(), Some("null")); assert_eq!(version.version_id.as_deref(), Some("null"));
@@ -1045,7 +1223,7 @@ mod tests {
match &output.entries[1] { match &output.entries[1] {
ListObjectVersionMetadataEntry::DeleteMarker(marker, extension) => { ListObjectVersionMetadataEntry::DeleteMarker(marker, extension) => {
assert_eq!(marker.key.as_deref(), Some("obj-b")); assert_eq!(marker.key, "obj-b");
assert_eq!(marker.version_id.as_deref(), Some("null")); assert_eq!(marker.version_id.as_deref(), Some("null"));
assert!(extension.user_tags.is_none()); assert!(extension.user_tags.is_none());
assert_eq!( assert_eq!(
@@ -1107,8 +1285,12 @@ mod tests {
assert_eq!(output.output.next_version_id_marker, None); assert_eq!(output.output.next_version_id_marker, None);
match &output.entries[0] { match &output.entries[0] {
ListObjectVersionMetadataEntry::Version(version, extension) => { ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry {
assert_eq!(version.key.as_deref(), Some("logs%20and%20more%2Fobject%20one.txt")); object: version,
extension,
..
}) => {
assert_eq!(version.key, "logs%20and%20more%2Fobject%20one.txt");
assert!(extension.user_metadata.is_none()); assert!(extension.user_metadata.is_none());
assert!(extension.user_tags.is_none()); assert!(extension.user_tags.is_none());
assert!(extension.internal.is_none()); assert!(extension.internal.is_none());
@@ -1193,7 +1375,7 @@ mod tests {
assert_eq!(output.output.common_prefixes.as_ref().map(Vec::len), Some(1)); assert_eq!(output.output.common_prefixes.as_ref().map(Vec::len), Some(1));
let entry = output.contents.first().unwrap(); let entry = output.contents.first().unwrap();
assert_eq!(entry.object.key.as_deref(), Some("logs/obj%20a.txt")); assert_eq!(entry.object.key, "logs/obj%20a.txt");
assert_eq!(entry.extension.user_tags.as_deref(), Some("env=prod")); assert_eq!(entry.extension.user_tags.as_deref(), Some("env=prod"));
assert_eq!(entry.extension.internal, Some(ObjectInternalInfo { k: 4, m: 2 })); assert_eq!(entry.extension.internal, Some(ObjectInternalInfo { k: 4, m: 2 }));
assert!(entry.object.owner.is_some()); assert!(entry.object.owner.is_some());
@@ -1246,7 +1428,7 @@ mod tests {
}; };
let output = build_list_objects_v2_metadata_output(object_infos, "demo-bucket", &params, None, false, &permissions); let output = build_list_objects_v2_metadata_output(object_infos, "demo-bucket", &params, None, false, &permissions);
let xml = String::from_utf8(serialize_s3s_response(&output)).expect("metadata output should be UTF-8"); let xml = String::from_utf8(output.to_xml().unwrap()).expect("metadata output should be UTF-8");
assert!(xml.contains("<ListBucketResult")); assert!(xml.contains("<ListBucketResult"));
assert!(xml.contains("<Contents>")); assert!(xml.contains("<Contents>"));
@@ -1318,7 +1500,7 @@ mod tests {
}; };
let output = build_list_objects_v2_metadata_output(object_infos, "demo-bucket", &params, None, false, &permissions); let output = build_list_objects_v2_metadata_output(object_infos, "demo-bucket", &params, None, false, &permissions);
let xml = String::from_utf8(serialize_s3s_response(&output)).expect("metadata output should be UTF-8"); let xml = String::from_utf8(output.to_xml().unwrap()).expect("metadata output should be UTF-8");
// Good sibling metadata survives. // Good sibling metadata survives.
assert!(xml.contains("<project>alpha</project>"), "well-formed key must remain: {xml}"); assert!(xml.contains("<project>alpha</project>"), "well-formed key must remain: {xml}");
@@ -1388,7 +1570,7 @@ mod tests {
assert_eq!(output.output.encoding_type.as_ref().map(EncodingType::as_str), Some(EncodingType::URL)); assert_eq!(output.output.encoding_type.as_ref().map(EncodingType::as_str), Some(EncodingType::URL));
let entry = output.contents.first().unwrap(); let entry = output.contents.first().unwrap();
assert_eq!(entry.object.key.as_deref(), Some("logs%20and%20more/object%20one.txt")); assert_eq!(entry.object.key, "logs%20and%20more/object%20one.txt");
assert!(entry.object.owner.is_none()); assert!(entry.object.owner.is_none());
assert!(entry.extension.user_metadata.is_none()); assert!(entry.extension.user_metadata.is_none());
assert!(entry.extension.user_tags.is_none()); assert!(entry.extension.user_tags.is_none());
+21 -21
View File
@@ -16,14 +16,14 @@
//! //!
//! Responsible for: the bucket name, object key, timestamp, owner and stored-configuration //! Responsible for: the bucket name, object key, timestamp, owner and stored-configuration
//! conversions a use case needs to build a gateway output from what the store returned, under the //! conversions a use case needs to build a gateway output from what the store returned, under the
//! rule in [`crate::app`]; and [`seam_error`], the one answer for a value the s3s compatibility //! rule in [`crate::app`].
//! seam refused.
//! NOT responsible for: validating names a client sends (the edge that accepted the request did), //! NOT responsible for: validating names a client sends (the edge that accepted the request did),
//! or deciding what a use case lists. //! or deciding what a use case lists.
//! Upstream: the use cases in `crate::app`. Downstream: `rustfs_gateway_types`. //! Upstream: the use cases in `crate::app`. Downstream: `rustfs_gateway_types`.
use super::storage_api::bucket_usecase::bucket::utils::{BucketConfigXml, serialize}; use super::storage_api::bucket_usecase::bucket::utils::{BucketConfigXml, serialize};
use super::storage_api::bucket_usecase::s3_api::bucket::{RUSTFS_OWNER_DISPLAY_NAME, RUSTFS_OWNER_ID}; use super::storage_api::bucket_usecase::s3_api::bucket::{RUSTFS_OWNER_DISPLAY_NAME, RUSTFS_OWNER_ID};
#[cfg(test)]
use rustfs_gateway_types::compat::{ConversionError, NameRefusal}; use rustfs_gateway_types::compat::{ConversionError, NameRefusal};
use rustfs_gateway_types::dto::Owner; use rustfs_gateway_types::dto::Owner;
use rustfs_gateway_types::{BucketName, ETag, NamePolicy, NameValidator, ObjectKey, Stricter, Timestamp}; use rustfs_gateway_types::{BucketName, ETag, NamePolicy, NameValidator, ObjectKey, Stricter, Timestamp};
@@ -63,7 +63,7 @@ pub(crate) fn stored_bucket_name(name: &str) -> S3Result<BucketName> {
}) })
} }
/// What a legacy edge answers when the s3s compatibility seam refuses a value of an admitted request. /// The legacy error expected by compatibility tests when the s3s seam refuses an admitted value.
/// ///
/// - An object key below the gateway's key floor (empty, over 1024 bytes, a NUL) is refused as /// - An object key below the gateway's key floor (empty, over 1024 bytes, a NUL) is refused as
/// `validate_object_key` refuses one: `400 InvalidArgument`, with a fixed message. An edge whose /// `validate_object_key` refuses one: `400 InvalidArgument`, with a fixed message. An edge whose
@@ -71,6 +71,7 @@ pub(crate) fn stored_bucket_name(name: &str) -> S3Result<BucketName> {
/// - A bucket name below the bucket floor is a server fault: s3s admits only `[a-z0-9.-]{3,63}`, /// - A bucket name below the bucket floor is a server fault: s3s admits only `[a-z0-9.-]{3,63}`,
/// which the floor always accepts, so no bucket a request names reaches it. /// which the floor always accepts, so no bucket a request names reaches it.
/// - Any other refusal is a value the gateway shape cannot hold: a server fault. /// - Any other refusal is a value the gateway shape cannot hold: a server fault.
#[cfg(test)]
pub(crate) fn seam_error(error: ConversionError) -> S3Error { pub(crate) fn seam_error(error: ConversionError) -> S3Error {
match error.name_kind() { match error.name_kind() {
Some(NameRefusal::ObjectKey) => S3Error::with_message(S3ErrorCode::InvalidArgument, "Invalid object key"), Some(NameRefusal::ObjectKey) => S3Error::with_message(S3ErrorCode::InvalidArgument, "Invalid object key"),
@@ -117,7 +118,7 @@ pub(crate) fn owner() -> Owner {
/// The entity tag the store holds, as an answer carries it: every answer that carries a stored tag /// The entity tag the store holds, as an answer carries it: every answer that carries a stored tag
/// converts it here, and none drops, rewrites or refuses one. /// converts it here, and none drops, rewrites or refuses one.
/// ///
/// It reads the stored spelling exactly as the legacy edge always has (`to_s3s_etag`): `W/"…"` is /// It reads the stored spelling exactly as the legacy edge always has: `W/"…"` is
/// a weak tag and one surrounding quote pair is the store's spelling of a strong one; the tag /// a weak tag and one surrounding quote pair is the store's spelling of a strong one; the tag
/// inside is kept byte for byte, so the legacy stack's answer does not change. A weak tag whose /// inside is kept byte for byte, so the legacy stack's answer does not change. A weak tag whose
/// inside the gateway's reader refuses or rewrites cannot stay weak (the gateway has no lossless /// inside the gateway's reader refuses or rewrites cannot stay weak (the gateway has no lossless
@@ -323,31 +324,30 @@ mod tests {
/// Stored tag spellings retain their expected forms across conversions and renderers. /// Stored tag spellings retain their expected forms across conversions and renderers.
#[test] #[test]
fn a_stored_tag_is_answered_as_main_answers_it_on_both_edges() { fn a_stored_tag_is_answered_as_main_answers_it_on_both_edges() {
use crate::app::storage_api::object_usecase::object_utils::to_s3s_etag;
use rustfs_gateway_types::EtagRender; use rustfs_gateway_types::EtagRender;
use rustfs_gateway_types::compat::s3s_5761ddfe::leaf::etag_to_s3s; use rustfs_gateway_types::compat::s3s_5761ddfe::leaf::etag_to_s3s;
// Stored spelling, legacy header, gateway header, and XML text. // Stored spelling, opaque value, weakness, legacy header, gateway header, and XML text.
let rows: [(&str, &str, &str, &str); 11] = [ let rows = [
("abc", r#""abc""#, r#""abc""#, r#""abc""#), ("abc", "abc", false, r#""abc""#, r#""abc""#, r#""abc""#),
(r#""abc""#, r#""abc""#, r#""abc""#, r#""abc""#), (r#""abc""#, "abc", false, r#""abc""#, r#""abc""#, r#""abc""#),
(r#"W/"abc""#, r#"W/"abc""#, r#"W/"abc""#, r#""abc""#), (r#"W/"abc""#, "abc", true, r#"W/"abc""#, r#"W/"abc""#, r#""abc""#),
("abc-3", r#""abc-3""#, r#""abc-3""#, r#""abc-3""#), ("abc-3", "abc-3", false, r#""abc-3""#, r#""abc-3""#, r#""abc-3""#),
(r#""""#, r#""""#, r#""""#, r#""""#), (r#""""#, "", false, r#""""#, r#""""#, r#""""#),
("", r#""""#, r#""""#, r#""""#), ("", "", false, r#""""#, r#""""#, r#""""#),
("W/abc", r#""W/abc""#, r#""W/abc""#, r#""W/abc""#), ("W/abc", "W/abc", false, r#""W/abc""#, r#""W/abc""#, r#""W/abc""#),
("a&b", r#""a&b""#, r#""a&b""#, r#""a&b""#), ("a&b", "a&b", false, r#""a&b""#, r#""a&b""#, r#""a&b""#),
(r#""abc"#, r#"""abc""#, r#""\"abc""#, r#"""abc""#), (r#""abc"#, "\"abc", false, r#"""abc""#, r#""\"abc""#, r#"""abc""#),
(r#"""abc"""#, r#"""abc"""#, r#""\"abc\"""#, r#"""abc"""#), (r#"""abc"""#, "\"abc\"", false, r#"""abc"""#, r#""\"abc\"""#, r#"""abc"""#),
(r#"w/"abc""#, r#""w/"abc"""#, r#""w/\"abc\"""#, r#""w/"abc"""#), (r#"w/"abc""#, "w/\"abc\"", false, r#""w/"abc"""#, r#""w/\"abc\"""#, r#""w/"abc"""#),
]; ];
// Every row is checked before the test fails, so one run names every row that differs. // Every row is checked before the test fails, so one run names every row that differs.
let mut differing = Vec::new(); let mut differing = Vec::new();
for (stored, main_header, gateway_header, xml) in rows { for (stored, opaque, weak, main_header, gateway_header, xml) in rows {
let etag = stored_etag(stored); let etag = stored_etag(stored);
let legacy = to_s3s_etag(stored); let legacy = etag_to_s3s(&etag);
let answered = ( let answered = (
etag_to_s3s(&etag) == legacy, legacy.value() == opaque && legacy.as_weak().is_some() == weak,
legacy.to_http_header().is_ok_and(|header| header == main_header), legacy.to_http_header().is_ok_and(|header| header == main_header),
etag.render(EtagRender::HeaderQuoted) == gateway_header, etag.render(EtagRender::HeaderQuoted) == gateway_header,
etag.render(EtagRender::XmlQuoted) == xml, etag.render(EtagRender::XmlQuoted) == xml,
+10 -13
View File
@@ -28,7 +28,6 @@
use crate::app::RequestEnvelope; use crate::app::RequestEnvelope;
use crate::app::bucket_usecase::DefaultBucketUsecase; use crate::app::bucket_usecase::DefaultBucketUsecase;
use crate::app::storage_api::s3::dto::{EncodingType, ListObjectVersionsInput, ListObjectsV2Input}; use crate::app::storage_api::s3::dto::{EncodingType, ListObjectVersionsInput, ListObjectsV2Input};
use crate::app::storage_api::s3::xml;
use crate::storage::access_owned::listing_multipart::authorize_bucket_listing; use crate::storage::access_owned::listing_multipart::authorize_bucket_listing;
use crate::storage::authorization::AuthorizationRequest; use crate::storage::authorization::AuthorizationRequest;
use http::{HeaderMap, Uri}; use http::{HeaderMap, Uri};
@@ -78,25 +77,23 @@ pub(crate) async fn answer(envelope: &RequestEnvelope, listing: MetadataListing,
match listing { match listing {
MetadataListing::ListObjectVersions => { MetadataListing::ListObjectVersions => {
let input = list_object_versions_input(bucket, envelope.uri(), envelope.headers())?; let input = list_object_versions_input(bucket, envelope.uri(), envelope.headers())?;
render(&usecase.list_object_versions_metadata(envelope, input).await?) usecase
.list_object_versions_metadata(envelope, input)
.await?
.to_xml()
.map_err(S3Error::internal_error)
} }
MetadataListing::ListObjectsV2 => { MetadataListing::ListObjectsV2 => {
let input = list_objects_v2_input(bucket, envelope.uri(), envelope.headers())?; let input = list_objects_v2_input(bucket, envelope.uri(), envelope.headers())?;
render(&usecase.list_objects_v2_metadata(envelope, input).await?) usecase
.list_objects_v2_metadata(envelope, input)
.await?
.to_xml()
.map_err(S3Error::internal_error)
} }
} }
} }
fn render<T: xml::Serialize>(output: &T) -> S3Result<Vec<u8>> {
let mut body = Vec::with_capacity(1024);
let mut serializer = xml::Serializer::new(&mut body);
serializer
.decl()
.and_then(|()| output.serialize(&mut serializer))
.map_err(S3Error::internal_error)?;
Ok(body)
}
fn list_object_versions_input(bucket: String, uri: &Uri, headers: &HeaderMap) -> S3Result<ListObjectVersionsInput> { fn list_object_versions_input(bucket: String, uri: &Uri, headers: &HeaderMap) -> S3Result<ListObjectVersionsInput> {
let query = uri.query().unwrap_or_default(); let query = uri.query().unwrap_or_default();
+63 -44
View File
@@ -49,8 +49,6 @@ use super::storage_api::multipart_usecase::io::{DecryptReader, EncryptReader, Ha
use super::storage_api::multipart_usecase::io::{ use super::storage_api::multipart_usecase::io::{
EtagAlgorithm, HashReader, WriteEncryption, WritePlan, compression_metadata_value, EtagAlgorithm, HashReader, WriteEncryption, WritePlan, compression_metadata_value,
}; };
#[cfg(test)]
use super::storage_api::multipart_usecase::object_utils::{to_s3s_etag, to_s3s_xml_etag};
use super::storage_api::multipart_usecase::options::{ use super::storage_api::multipart_usecase::options::{
copy_src_opts, extract_metadata_from_mime, get_complete_multipart_upload_opts_with_replication_authorization, copy_src_opts, extract_metadata_from_mime, get_complete_multipart_upload_opts_with_replication_authorization,
get_content_sha256_with_query, get_opts, has_replication_retention_update, namespace_reserved_user_metadata, get_content_sha256_with_query, get_opts, has_replication_retention_update, namespace_reserved_user_metadata,
@@ -299,6 +297,32 @@ fn multipart_upload_api_error(err: StorageError) -> S3Error {
ApiError::from(err).into() ApiError::from(err).into()
} }
#[cfg(test)]
fn completion_part(number: i32, stored: Option<&str>) -> rustfs_gateway_types::dto::CompletedPart {
rustfs_gateway_types::dto::CompletedPart {
part_number: number,
e_tag: stored.map(crate::app::dto_values::stored_etag),
..Default::default()
}
}
#[cfg(test)]
fn completion_input(
bucket: &str,
key: &str,
upload_id: &str,
parts: Vec<rustfs_gateway_types::dto::CompletedPart>,
) -> rustfs_gateway_types::dto::CompleteMultipartUploadInput {
use rustfs_gateway_types::{BucketName, ObjectKey, UploadIdClaim, dto};
dto::CompleteMultipartUploadInput {
bucket: BucketName::new(bucket).expect("test bucket"),
key: ObjectKey::new(key).expect("test key"),
upload_id: UploadIdClaim::from_wire(upload_id),
multipart_upload: dto::CompletedMultipartUpload { parts },
..Default::default()
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::test_support::*; use super::test_support::*;
@@ -632,8 +656,7 @@ mod tests {
crate::app::gating_test_env::run_large_stack_test("mpu-kms-current-caller", || async { crate::app::gating_test_env::run_large_stack_test("mpu-kms-current-caller", || async {
use crate::app::storage_api::s3::S3ErrorCode; use crate::app::storage_api::s3::S3ErrorCode;
use crate::app::storage_api::s3::dto::{ use crate::app::storage_api::s3::dto::{
CompleteMultipartUploadInput, CompletedMultipartUpload, CompletedPart, CopySource, StreamingBlob, CompleteMultipartUploadInput, CompletedMultipartUpload, CompletedPart, StreamingBlob, UploadPartInput,
UploadPartCopyInput, UploadPartInput,
}; };
use crate::app::storage_api::test::ReqInfo; use crate::app::storage_api::test::ReqInfo;
use crate::app::storage_api::test::sse::{ use crate::app::storage_api::test::sse::{
@@ -700,26 +723,40 @@ mod tests {
let error = usecase let error = usecase
.execute_upload_part(denied_request(part, authorizer.clone())) .execute_upload_part(denied_request(part, authorizer.clone()))
.await .await
.expect_err("denied part"); .err()
.expect("denied part");
assert_eq!(error.code(), &S3ErrorCode::AccessDenied); assert_eq!(error.code(), &S3ErrorCode::AccessDenied);
let copy = UploadPartCopyInput::builder() let copy_envelope = crate::app::RequestEnvelope::from_s3s(&denied_request((), authorizer.clone()));
.bucket(bucket.clone())
.key(key.to_string())
.upload_id(upload.upload_id.clone())
.part_number(1)
.copy_source(CopySource::Bucket {
bucket: bucket.clone().into(),
key: "source".into(),
version_id: None,
})
.build()
.expect("copy");
let copy_req = denied_request(copy, authorizer.clone());
let error = usecase let error = usecase
.execute_upload_part_copy(copy_req) .execute_upload_part_copy_with_audit(
copy_envelope,
UploadPartCopyWriteInput {
target: UploadPartTarget::Legacy {
bucket: bucket.clone(),
key: key.to_string(),
upload_id: upload.upload_id.clone(),
},
part_number: 1,
copy_source: rustfs_gateway_types::CopySourceValue::Bucket {
bucket: bucket.clone(),
key: "source".to_owned(),
version_id: None,
},
copy_source_range: None,
copy_source_if_match: None,
copy_source_if_none_match: None,
sse_customer_algorithm: None,
sse_customer_key: None,
sse_customer_key_md5: None,
copy_source_sse_customer_algorithm: None,
copy_source_sse_customer_key: None,
copy_source_sse_customer_key_md5: None,
},
)
.await .await
.expect_err("denied destination copy"); .err()
assert_eq!(error.code(), &S3ErrorCode::AccessDenied); .expect("denied destination copy");
assert_eq!(error.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied);
let complete = CompleteMultipartUploadInput::builder() let complete = CompleteMultipartUploadInput::builder()
.bucket(bucket.clone()) .bucket(bucket.clone())
.key(key.to_string()) .key(key.to_string())
@@ -810,10 +847,9 @@ mod tests {
requested_kms_key_id: Option<&str>, requested_kms_key_id: Option<&str>,
customer_key: Option<(&str, &str)>, customer_key: Option<(&str, &str)>,
) -> (Vec<(&'static str, SseResponseFields)>, Vec<String>) { ) -> (Vec<(&'static str, SseResponseFields)>, Vec<String>) {
use crate::app::storage_api::s3::dto::{CompletedPart, CopySource, StreamingBlob, UploadPartInput}; use crate::app::storage_api::s3::dto::{CopySource, StreamingBlob, UploadPartInput};
use crate::app::storage_api::test::contract::object::ObjectIO as _; use crate::app::storage_api::test::contract::object::ObjectIO as _;
use rustfs_gateway::{Limits, MetaView, OperationCodec, TargetKind, WireRequest}; use rustfs_gateway::{Limits, MetaView, OperationCodec, TargetKind, WireRequest};
use rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::complete_multipart_upload;
let store = crate::app::gating_test_env::shared_gating_ecstore().await; let store = crate::app::gating_test_env::shared_gating_ecstore().await;
let usecase = DefaultMultipartUsecase::from_global(); let usecase = DefaultMultipartUsecase::from_global();
@@ -905,27 +941,10 @@ mod tests {
.await .await
.expect("copy part"); .expect("copy part");
let mut complete_input = complete_multipart_upload::input_from_s3s(CompleteMultipartUploadInput { let mut complete_input = completion_input(bucket, key, &upload_id, vec![completion_part(1, part.e_tag.as_deref())]);
bucket: bucket.to_string(), complete_input.sse_customer_algorithm = customer_algorithm;
key: key.to_string(), complete_input.sse_customer_key = customer_key.map(rustfs_gateway_types::SseCustomerKey::new);
upload_id, complete_input.sse_customer_key_md5 = customer_key_md5;
multipart_upload: Some(CompletedMultipartUpload {
parts: Some(vec![CompletedPart {
part_number: Some(1),
..Default::default()
}]),
}),
sse_customer_algorithm: customer_algorithm,
sse_customer_key: customer_key,
sse_customer_key_md5: customer_key_md5,
..Default::default()
})
.map_err(crate::app::dto_values::seam_error)
.expect("owned completion input");
complete_input.multipart_upload.parts[0].e_tag = part
.e_tag
.as_deref()
.map(|tag| rustfs_gateway_types::ETag::from_stored(to_s3s_etag(tag).value().to_owned()));
let complete = Box::pin(usecase.execute_complete_multipart_upload(owned_envelope(Method::POST), complete_input)) let complete = Box::pin(usecase.execute_complete_multipart_upload(owned_envelope(Method::POST), complete_input))
.await .await
.expect("complete multipart upload"); .expect("complete multipart upload");
File diff suppressed because it is too large Load Diff
@@ -543,36 +543,13 @@ impl UploadPartWriteInput {
#[cfg(test)] #[cfg(test)]
impl DefaultMultipartUsecase { impl DefaultMultipartUsecase {
pub async fn execute_upload_part( pub(crate) async fn execute_upload_part(
&self, &self,
req: crate::app::storage_api::s3::S3Request<crate::app::storage_api::s3::dto::UploadPartInput>, req: crate::app::storage_api::s3::S3Request<crate::app::storage_api::s3::dto::UploadPartInput>,
) -> crate::app::storage_api::s3::S3Result< ) -> crate::app::storage_api::s3::S3Result<UploadPartWriteOutput> {
crate::app::storage_api::s3::S3Response<crate::app::storage_api::s3::dto::UploadPartOutput>,
> {
use crate::app::storage_api::s3::{
S3Response,
dto::{ServerSideEncryption, UploadPartOutput},
};
let envelope = RequestEnvelope::from_s3s(&req); let envelope = RequestEnvelope::from_s3s(&req);
let input = UploadPartWriteInput::from_legacy(req.input, req.trailing_headers); let input = UploadPartWriteInput::from_legacy(req.input, req.trailing_headers);
let output = self.execute_upload_part_with_audit(envelope, input).await?; self.execute_upload_part_with_audit(envelope, input).await.map_err(Into::into)
let mut response = S3Response::new(UploadPartOutput {
e_tag: output
.e_tag
.map(|tag| crate::app::storage_api::test::object_utils::to_s3s_etag(&tag)),
checksum_crc32: output.checksum_crc32,
checksum_crc32c: output.checksum_crc32c,
checksum_crc64nvme: output.checksum_crc64nvme,
checksum_sha1: output.checksum_sha1,
checksum_sha256: output.checksum_sha256,
server_side_encryption: output.server_side_encryption.map(ServerSideEncryption::from),
ssekms_key_id: output.ssekms_key_id,
sse_customer_algorithm: output.sse_customer_algorithm,
sse_customer_key_md5: output.sse_customer_key_md5,
..Default::default()
});
response.headers = output.headers;
Ok(response)
} }
} }
@@ -877,7 +854,8 @@ mod tests {
let error = usecase let error = usecase
.execute_upload_part(request) .execute_upload_part(request)
.await .await
.expect_err("unknown or negative logical size"); .err()
.expect("unknown or negative logical size");
assert_eq!( assert_eq!(
error.code(), error.code(),
&if capped || content_length.is_some() { &if capped || content_length.is_some() {
@@ -943,7 +921,8 @@ mod tests {
)); ));
control.advance_wait_for_test(Duration::from_secs(60)); control.advance_wait_for_test(Duration::from_secs(60));
sender.send(Ok(Frame::data(Bytes::from_static(b"x")))).unwrap(); sender.send(Ok(Frame::data(Bytes::from_static(b"x")))).unwrap();
assert_eq!(owner.await.unwrap().unwrap_err().code(), &LegacyErrorCode::RequestTimeout); let error = owner.await.unwrap().err().expect("stalled part must fail");
assert_eq!(error.code(), &LegacyErrorCode::RequestTimeout);
assert!(matches!( assert!(matches!(
manager.admit_put_object(65536).await.unwrap(), manager.admit_put_object(65536).await.unwrap(),
ForegroundWriteAdmission::Admitted(_) ForegroundWriteAdmission::Admitted(_)
@@ -195,7 +195,8 @@ async fn assert_body_timeout_storage_lifecycle(part_size: usize, partial_size: u
let error = tokio::time::timeout(Duration::from_secs(10), upload_future) let error = tokio::time::timeout(Duration::from_secs(10), upload_future)
.await .await
.expect("inline cleanup must complete") .expect("inline cleanup must complete")
.expect_err("stalled part"); .err()
.expect("stalled part");
assert_eq!( assert_eq!(
error.code(), error.code(),
&S3ErrorCode::RequestTimeout, &S3ErrorCode::RequestTimeout,
@@ -225,7 +226,7 @@ async fn assert_body_timeout_storage_lifecycle(part_size: usize, partial_size: u
.await .await
.expect("foreground and capped staging permits must be released") .expect("foreground and capped staging permits must be released")
.expect("same-number retry"); .expect("same-number retry");
old_etag = retry.output.e_tag.map(|etag| etag.value().to_owned()); old_etag = retry.e_tag;
} }
let parts = store let parts = store
.list_object_parts(&bucket, "object", &upload.upload_id, None, 1000, &ObjectOptions::default()) .list_object_parts(&bucket, "object", &upload.upload_id, None, 1000, &ObjectOptions::default())
@@ -352,10 +353,11 @@ fn presigned_part_checksum_survives_completion_and_rejects_bad_retry() {
let result = usecase.execute_upload_part(req).await; let result = usecase.execute_upload_part(req).await;
if payload == b"abc" { if payload == b"abc" {
let response = result.expect("hoisted SHA256 part must be accepted"); let response = result.expect("hoisted SHA256 part must be accepted");
assert_eq!(response.output.checksum_sha256.as_deref(), Some(checksum)); assert_eq!(response.checksum_sha256.as_deref(), Some(checksum));
etag = response.output.e_tag.map(|etag| etag.value().to_owned()); etag = response.e_tag;
} else { } else {
assert_eq!(*result.unwrap_err().code(), S3ErrorCode::BadDigest); let error = result.err().expect("bad checksum must fail");
assert_eq!(*error.code(), S3ErrorCode::BadDigest);
} }
} }
store store
@@ -16,12 +16,6 @@
//! Gateway and protocol clients supply request facts. Storage owns the multipart upload. //! Gateway and protocol clients supply request facts. Storage owns the multipart upload.
use super::*; use super::*;
#[cfg(test)]
use crate::app::storage_api::s3::dto::{
CopyPartResult, CopySource, ETag, ServerSideEncryption, Timestamp, UploadPartCopyInput, UploadPartCopyOutput,
};
#[cfg(test)]
use crate::app::storage_api::s3::{S3Request, S3Response};
use crate::app::{RequestEnvelope, object_usecase::CopySourceCondition}; use crate::app::{RequestEnvelope, object_usecase::CopySourceCondition};
use rustfs_gateway_types::CopySourceValue; use rustfs_gateway_types::CopySourceValue;
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result, s3_error}; use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result, s3_error};
@@ -100,57 +94,6 @@ fn validate_copy_source_range_not_exceeds(range_spec: &HTTPRangeSpec, object_siz
} }
impl DefaultMultipartUsecase { impl DefaultMultipartUsecase {
#[cfg(test)]
pub async fn execute_upload_part_copy(
&self,
req: S3Request<UploadPartCopyInput>,
) -> crate::app::storage_api::s3::S3Result<S3Response<UploadPartCopyOutput>> {
let envelope = RequestEnvelope::from_s3s(&req);
let input = req.input;
let condition = |value| match value {
crate::app::storage_api::s3::dto::ETagCondition::Any => CopySourceCondition::Any,
crate::app::storage_api::s3::dto::ETagCondition::ETag(ETag::Strong(value)) => CopySourceCondition::Strong(value),
crate::app::storage_api::s3::dto::ETagCondition::ETag(ETag::Weak(_)) => CopySourceCondition::Weak,
};
let input = UploadPartCopyWriteInput {
target: UploadPartTarget::Legacy {
bucket: input.bucket,
key: input.key,
upload_id: input.upload_id,
},
part_number: input.part_number,
copy_source: rustfs_gateway_types::compat::s3s_5761ddfe::copy_source::from_s3s(input.copy_source),
copy_source_range: input.copy_source_range,
copy_source_if_match: input.copy_source_if_match.map(condition),
copy_source_if_none_match: input.copy_source_if_none_match.map(condition),
sse_customer_algorithm: input.sse_customer_algorithm,
sse_customer_key: input.sse_customer_key,
sse_customer_key_md5: input.sse_customer_key_md5,
copy_source_sse_customer_algorithm: input.copy_source_sse_customer_algorithm,
copy_source_sse_customer_key: input.copy_source_sse_customer_key,
copy_source_sse_customer_key_md5: input.copy_source_sse_customer_key_md5,
};
let output = self.execute_upload_part_copy_with_audit(envelope, input).await?;
Ok(S3Response::new(UploadPartCopyOutput {
copy_part_result: Some(CopyPartResult {
e_tag: output.e_tag.as_deref().map(to_s3s_xml_etag),
last_modified: output.last_modified.map(Timestamp::from),
checksum_crc32: output.checksum_crc32,
checksum_crc32c: output.checksum_crc32c,
checksum_sha1: output.checksum_sha1,
checksum_sha256: output.checksum_sha256,
checksum_crc64nvme: output.checksum_crc64nvme,
..Default::default()
}),
copy_source_version_id: output.copy_source_version_id,
server_side_encryption: output.server_side_encryption.map(ServerSideEncryption::from),
ssekms_key_id: output.ssekms_key_id,
sse_customer_algorithm: output.sse_customer_algorithm,
sse_customer_key_md5: output.sse_customer_key_md5,
..Default::default()
}))
}
/// Copies plaintext into an existing upload without changing its recorded owner. /// Copies plaintext into an existing upload without changing its recorded owner.
/// Records the gateway audit. The protocol client records its own projected response. /// Records the gateway audit. The protocol client records its own projected response.
pub(crate) async fn execute_upload_part_copy_with_audit( pub(crate) async fn execute_upload_part_copy_with_audit(
@@ -560,7 +503,7 @@ mod tests {
use super::*; use super::*;
use crate::app::multipart_usecase::UploadPartTarget; use crate::app::multipart_usecase::UploadPartTarget;
use crate::app::object_usecase::CopySourceCondition; use crate::app::object_usecase::CopySourceCondition;
use crate::app::storage_api::s3::dto::ETag; use crate::app::storage_api::s3::dto::{CopySource, ETag, UploadPartCopyInput};
#[tokio::test] #[tokio::test]
async fn execute_upload_part_copy_returns_internal_error_when_store_uninitialized() { async fn execute_upload_part_copy_returns_internal_error_when_store_uninitialized() {
@@ -148,12 +148,7 @@ fn upload_part_copy_shares_foreground_admission_with_upload_part() {
Some(0), Some(0),
"success releases the copy permit" "success releases the copy permit"
); );
let etag = copied let etag = copied.e_tag.expect("copy ETag");
.e_tag
.as_deref()
.map(crate::storage::storage_api::to_s3s_xml_etag)
.expect("copy ETag");
let etag = etag.value().trim_matches('"').to_owned();
Arc::clone(&store) Arc::clone(&store)
.complete_multipart_upload( .complete_multipart_upload(
&bucket, &bucket,
@@ -412,12 +407,7 @@ fn upload_part_copy_range_error_and_cancellation_release_foreground_permit() {
Ok(output) => output, Ok(output) => output,
Err(error) => panic!("range copy after failed request released its source and permit: {error:?}"), Err(error) => panic!("range copy after failed request released its source and permit: {error:?}"),
}; };
let etag = copied let etag = copied.e_tag.expect("range ETag");
.e_tag
.as_deref()
.map(crate::storage::storage_api::to_s3s_xml_etag)
.expect("range ETag");
let etag = etag.value().trim_matches('"').to_owned();
Arc::clone(&store) Arc::clone(&store)
.complete_multipart_upload( .complete_multipart_upload(
&bucket, &bucket,
+40 -19
View File
@@ -17,14 +17,43 @@
//! configuration must be set before either process initializes the store. //! configuration must be set before either process initializes the store.
use super::*; use super::*;
use crate::app::storage_api::s3::S3ErrorCode;
use crate::app::storage_api::s3::dto::GetObjectInput;
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions}; use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions};
use futures::stream; use futures::stream;
use http::{HeaderValue, Method}; use http::{HeaderMap, HeaderValue, StatusCode};
use metrics_util::debugging::{DebugValue, DebuggingRecorder}; use metrics_util::debugging::{DebugValue, DebuggingRecorder};
use std::time::Instant; use std::time::Instant;
// The baseline installer replaces only this module to call that revision's GET API.
mod get_api {
use super::*;
use crate::app::test_seams::{get_envelope, get_object_gateway, get_object_input};
use rustfs_gateway_stream::PayloadRead;
use std::future::poll_fn;
pub(super) async fn get(
usecase: &DefaultObjectUsecase,
object: &str,
headers: HeaderMap,
) -> rustfs_s3_types::S3Result<crate::app::Answered<GetObjectOutputFacts>> {
let input = get_object_input("conditional-bench", object, None);
let envelope = get_envelope(headers, http::Extensions::new());
get_object_gateway(usecase, envelope, input).await
}
pub(super) async fn consume(body: GetObjectBody, actual: &mut Vec<u8>) {
match body {
GetObjectBody::Bytes(bytes) => actual.extend_from_slice(&bytes),
GetObjectBody::Stream(mut body) => {
while let PayloadRead::Chunk(chunk) =
poll_fn(|cx| body.as_mut().poll_read(cx)).await.expect("benchmark body chunk")
{
actual.extend_from_slice(&chunk);
}
}
}
}
}
fn percentile(samples: &mut [f64], percent: usize) -> f64 { fn percentile(samples: &mut [f64], percent: usize) -> f64 {
assert!(!samples.is_empty(), "benchmark must collect samples"); assert!(!samples.is_empty(), "benchmark must collect samples");
samples.sort_by(f64::total_cmp); samples.sort_by(f64::total_cmp);
@@ -33,33 +62,25 @@ fn percentile(samples: &mut [f64], percent: usize) -> f64 {
async fn read_once(usecase: &DefaultObjectUsecase, object: &str, etag: &str, kind: &str, expected: &[u8]) -> f64 { async fn read_once(usecase: &DefaultObjectUsecase, object: &str, etag: &str, kind: &str, expected: &[u8]) -> f64 {
let start = Instant::now(); let start = Instant::now();
let mut req = build_request( let mut headers = HeaderMap::new();
GetObjectInput::builder()
.bucket("conditional-bench".to_owned())
.key(object.to_owned())
.build()
.expect("benchmark input"),
Method::GET,
);
if kind != "unconditional" { if kind != "unconditional" {
let tag = if kind == "hit" { etag } else { "unmatched-benchmark-etag" }; let tag = if kind == "hit" { etag } else { "unmatched-benchmark-etag" };
req.headers.insert( headers.insert(
http::header::IF_NONE_MATCH, http::header::IF_NONE_MATCH,
HeaderValue::from_str(&format!("\"{tag}\"")).expect("benchmark condition"), HeaderValue::from_str(&format!("\"{tag}\"")).expect("benchmark condition"),
); );
} }
match usecase.execute_get_object_from_s3s(req).await { match get_api::get(usecase, object, headers).await {
Err(error) => { Err(error) => {
assert_eq!(kind, "hit"); assert_eq!(kind, "hit");
assert_eq!(error.code(), &S3ErrorCode::NotModified); assert_eq!(error.code().as_str(), "NotModified");
assert_eq!(error.status_code(), Some(StatusCode::NOT_MODIFIED));
} }
Ok(mut response) => { Ok(response) => {
assert_ne!(kind, "hit"); assert_ne!(kind, "hit");
let mut body = response.output.body.take().expect("benchmark body"); assert_eq!(response.status.unwrap_or(StatusCode::OK), StatusCode::OK);
let mut actual = Vec::with_capacity(expected.len()); let mut actual = Vec::with_capacity(expected.len());
while let Some(chunk) = body.next().await { get_api::consume(response.output.body.expect("benchmark body"), &mut actual).await;
actual.extend_from_slice(&chunk.expect("benchmark body chunk"));
}
assert_eq!(actual, expected, "benchmark must consume and validate the whole body"); assert_eq!(actual, expected, "benchmark must consume and validate the whole body");
} }
} }
+40 -68
View File
@@ -935,23 +935,25 @@ impl DefaultObjectUsecase {
mod tests { mod tests {
use super::*; use super::*;
/// CopyObject through the owned entry point the gateway handler calls, its error in the s3s fn copy_input(bucket: &str, source: &str, destination: &str, source_version: Option<String>) -> CopyObjectWriteInput {
/// form these tests compare. CopyObjectWriteInput {
async fn copy_owned( bucket: bucket.to_owned(),
usecase: &DefaultObjectUsecase, key: destination.to_owned(),
req: S3Request<CopyObjectInput>, copy_source: Some(CopySourceValue::Bucket {
) -> crate::app::storage_api::s3::S3Result<crate::app::object_usecase::CopyObjectWriteOutput> { bucket: bucket.to_owned(),
let (envelope, input) = crate::app::object_usecase::CopyObjectWriteInput::from_test_request(req); key: source.to_owned(),
usecase.execute_copy_object_owned(envelope, input).await.map_err(Into::into) version_id: source_version,
}),
..Default::default()
}
} }
/// Method-only envelope. `build_request` leaves the URI as `/`, the headers empty, and the trailing headers absent. fn copy_envelope(headers: HeaderMap) -> crate::app::RequestEnvelope {
fn method_only_copy_envelope() -> crate::app::RequestEnvelope {
crate::app::RequestEnvelope::from_parts( crate::app::RequestEnvelope::from_parts(
crate::app::RequestHead { crate::app::RequestHead {
method: Method::PUT, method: Method::PUT,
uri: http::Uri::from_static("/"), uri: http::Uri::from_static("/"),
headers: HeaderMap::new(), headers,
credentials: None, credentials: None,
region: None, region: None,
service: None, service: None,
@@ -966,7 +968,7 @@ mod tests {
) -> crate::app::storage_api::s3::S3Result<crate::app::object_usecase::CopyObjectWriteOutput> { ) -> crate::app::storage_api::s3::S3Result<crate::app::object_usecase::CopyObjectWriteOutput> {
let input = crate::app::object_usecase::CopyObjectWriteInput::from_legacy(input); let input = crate::app::object_usecase::CopyObjectWriteInput::from_legacy(input);
usecase usecase
.execute_copy_object_owned(method_only_copy_envelope(), input) .execute_copy_object_owned(copy_envelope(HeaderMap::new()), input)
.await .await
.map_err(Into::into) .map_err(Into::into)
} }
@@ -1209,21 +1211,13 @@ mod tests {
.await .await
.expect("publish self-copy test policy"); .expect("publish self-copy test policy");
let input = CopyObjectInput::builder() let input = CopyObjectWriteInput {
.copy_source(CopySource::Bucket { metadata_directive: Some("REPLACE".to_owned()),
bucket: bucket.clone().into(), metadata: Some(HashMap::from([("lock-order".to_owned(), "verified".to_owned())])),
key: bucket.clone().into(), ..copy_input(&bucket, &bucket, &bucket, None)
version_id: None, };
}) let mut envelope = copy_envelope(HeaderMap::new());
.bucket(bucket.clone()) envelope.install_req_info(crate::storage::req_info::ReqInfo::default());
.key(bucket.clone())
.metadata_directive(Some(MetadataDirective::from_static(MetadataDirective::REPLACE)))
.metadata(Some(HashMap::from([("lock-order".to_string(), "verified".to_string())])))
.build()
.expect("self-copy input should build");
let mut req = build_request(input, Method::PUT);
req.extensions.insert(crate::storage::req_info::ReqInfo::default());
let (mut envelope, input) = CopyObjectWriteInput::from_test_request(req);
let facts = CopyObjectAuthorization { let facts = CopyObjectAuthorization {
bucket: &bucket, bucket: &bucket,
key: &bucket, key: &bucket,
@@ -1371,26 +1365,18 @@ mod tests {
let source_version_id = old.version_id.expect("historical source should have a version id"); let source_version_id = old.version_id.expect("historical source should have a version id");
let current_version_id = current.version_id.expect("current destination should have a version id"); let current_version_id = current.version_id.expect("current destination should have a version id");
let input = CopyObjectInput::builder() let input = copy_input(&bucket, object, object, Some(source_version_id.to_string()));
.copy_source(CopySource::Bucket { let mut headers = HeaderMap::new();
bucket: bucket.clone().into(), headers.insert(
key: object.to_string().into(),
version_id: Some(source_version_id.to_string().into()),
})
.bucket(bucket.clone())
.key(object.to_string())
.build()
.expect("expected-current historical copy input should build");
let mut req = build_request(input, Method::PUT);
req.headers.insert(
RUSTFS_EXPECTED_CURRENT_VERSION_ID, RUSTFS_EXPECTED_CURRENT_VERSION_ID,
HeaderValue::from_str(&current_version_id.to_string()).expect("current version header should be valid"), HeaderValue::from_str(&current_version_id.to_string()).expect("current version header should be valid"),
); );
let envelope = copy_envelope(headers);
let response = temp_env::async_with_vars( let response = temp_env::async_with_vars(
[(rustfs_config::ENV_OBJECT_LOCK_OPTIMIZATION_ENABLE, Some("false"))], [(rustfs_config::ENV_OBJECT_LOCK_OPTIMIZATION_ENABLE, Some("false"))],
tokio::time::timeout( tokio::time::timeout(
Duration::from_secs(10), Duration::from_secs(10),
copy_owned(&DefaultObjectUsecase::with_context(Some(context)), req), DefaultObjectUsecase::with_context(Some(context)).execute_copy_object_owned(envelope, input),
), ),
) )
.await .await
@@ -1536,20 +1522,14 @@ mod tests {
.await .await
.expect("plaintext copy source should be written"); .expect("plaintext copy source should be written");
let mut input = CopyObjectInput::builder() let input = CopyObjectWriteInput {
.copy_source(CopySource::Bucket { sse_customer_algorithm: Some("AES256".to_owned()),
bucket: bucket.clone().into(), sse_customer_key: Some("KioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKio=".to_owned()),
key: "source.bin".into(), sse_customer_key_md5: Some(customer_key_md5.to_owned()),
version_id: None, ..copy_input(&bucket, "source.bin", "customer-encrypted.bin", None)
}) };
.bucket(bucket.clone()) let response = DefaultObjectUsecase::with_context(Some(context))
.key("customer-encrypted.bin".to_string()) .execute_copy_object_owned(copy_envelope(HeaderMap::new()), input)
.build()
.expect("SSE-C copy input should build");
input.sse_customer_algorithm = Some("AES256".to_string());
input.sse_customer_key = Some("KioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKio=".to_string());
input.sse_customer_key_md5 = Some(customer_key_md5.to_string());
let response = copy_owned(&DefaultObjectUsecase::with_context(Some(context)), build_request(input, Method::PUT))
.await .await
.expect("copying to an SSE-C destination should succeed"); .expect("copying to an SSE-C destination should succeed");
@@ -1617,26 +1597,18 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn execute_copy_object_rejects_expected_version_for_different_destination() { async fn execute_copy_object_rejects_expected_version_for_different_destination() {
let input = CopyObjectInput::builder() let input = copy_input("test-bucket", "source-key", "destination-key", Some(Uuid::new_v4().to_string()));
.copy_source(CopySource::Bucket { let mut headers = HeaderMap::new();
bucket: "test-bucket".into(), headers.insert(
key: "source-key".into(),
version_id: Some(Uuid::new_v4().to_string().into()),
})
.bucket("test-bucket".to_string())
.key("destination-key".to_string())
.build()
.unwrap();
let mut req = build_request(input, Method::PUT);
req.headers.insert(
RUSTFS_EXPECTED_CURRENT_VERSION_ID, RUSTFS_EXPECTED_CURRENT_VERSION_ID,
HeaderValue::from_str(&Uuid::new_v4().to_string()).unwrap(), HeaderValue::from_str(&Uuid::new_v4().to_string()).unwrap(),
); );
let envelope = copy_envelope(headers);
let err = Box::pin(copy_owned(&DefaultObjectUsecase::without_context(), req)) let err = Box::pin(DefaultObjectUsecase::without_context().execute_copy_object_owned(envelope, input))
.await .await
.unwrap_err(); .unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::InvalidRequest); assert_eq!(err.code(), &rustfs_s3_types::S3ErrorCode::InvalidRequest);
} }
#[tokio::test] #[tokio::test]
-8
View File
@@ -147,12 +147,4 @@ impl CopyObjectWriteInput {
checksum_algorithm: input.checksum_algorithm.map(|value| value.as_str().to_owned()), checksum_algorithm: input.checksum_algorithm.map(|value| value.as_str().to_owned()),
} }
} }
/// A test's s3s fixture request as the envelope and input a gateway handler hands the use case.
pub(crate) fn from_test_request(
req: crate::app::storage_api::s3::S3Request<crate::app::storage_api::s3::dto::CopyObjectInput>,
) -> (crate::app::RequestEnvelope, Self) {
let envelope = crate::app::RequestEnvelope::from_s3s(&req);
(envelope, Self::from_legacy(req.input))
}
} }
+39 -67
View File
@@ -1862,8 +1862,9 @@ mod tests {
} }
use super::*; use super::*;
use crate::app::storage_api::s3::dto::GetObjectInput; use crate::app::test_seams::{
use crate::app::test_seams::{head_envelope, head_object_gateway, head_object_input}; get_envelope, get_object_gateway, get_object_input, head_envelope, head_object_gateway, head_object_input, read_get_body,
};
use http::{HeaderMap, HeaderValue, Method}; use http::{HeaderMap, HeaderValue, Method};
use rustfs_gateway_types::dto::Status; use rustfs_gateway_types::dto::Status;
use rustfs_gateway_types::persistence::{ use rustfs_gateway_types::persistence::{
@@ -2246,16 +2247,12 @@ mod tests {
for explicit in [false, true] { for explicit in [false, true] {
let requested_version = explicit.then(|| marker_id.clone()); let requested_version = explicit.then(|| marker_id.clone());
let get = GetObjectInput::builder() let get = get_object_input(&bucket, key, requested_version.clone());
.bucket(bucket.clone())
.key(key.to_string())
.version_id(requested_version.clone())
.build()
.expect("GET request");
let head = head_object_input(&bucket, key, requested_version); let head = head_object_input(&bucket, key, requested_version);
let get_error = crate::app::test_seams::get_object_method_only(&usecase, get) let get_error =
.await get_object_gateway(&usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get)
.expect_err("marker GET"); .await
.expect_err("marker GET");
let head_error = let head_error =
head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head) head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head)
.await .await
@@ -2305,22 +2302,13 @@ mod tests {
} }
let original_id = original.version_id.expect("historical version id").to_string(); let original_id = original.version_id.expect("historical version id").to_string();
let get = GetObjectInput::builder() let get = get_object_input(&bucket, key, Some(original_id.clone()));
.bucket(bucket.clone()) let response = get_object_gateway(&usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get)
.key(key.to_string())
.version_id(Some(original_id.clone()))
.build()
.expect("historical GET request");
let response = crate::app::test_seams::get_object_method_only(&usecase, get)
.await .await
.expect("historical GET"); .expect("historical GET");
assert!(!response.headers.contains_key("x-amz-delete-marker")); assert!(!response.headers.contains_key("x-amz-delete-marker"));
let mut body = response.output.body.expect("historical body"); let body = response.output.body.expect("historical body");
let mut actual = Vec::new(); assert_eq!(read_get_body(body).await.as_ref(), payload);
while let Some(chunk) = body.next().await {
actual.extend_from_slice(&chunk.expect("historical data remains readable"));
}
assert_eq!(actual, payload);
let head = head_object_input(&bucket, key, Some(original_id.clone())); let head = head_object_input(&bucket, key, Some(original_id.clone()));
let response = head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head) let response = head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head)
.await .await
@@ -2330,16 +2318,12 @@ mod tests {
assert!(!response.headers.contains_key("x-amz-delete-marker")); assert!(!response.headers.contains_key("x-amz-delete-marker"));
for (absent_key, version) in [("missing", None), (key, Some(Uuid::new_v4().to_string()))] { for (absent_key, version) in [("missing", None), (key, Some(Uuid::new_v4().to_string()))] {
let get = GetObjectInput::builder() let get = get_object_input(&bucket, absent_key, version.clone());
.bucket(bucket.clone())
.key(absent_key.to_string())
.version_id(version.clone())
.build()
.expect("missing GET request");
let head = head_object_input(&bucket, absent_key, version); let head = head_object_input(&bucket, absent_key, version);
let get_error = crate::app::test_seams::get_object_method_only(&usecase, get) let get_error =
.await get_object_gateway(&usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get)
.expect_err("missing GET"); .await
.expect_err("missing GET");
let head_error = let head_error =
head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head) head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head)
.await .await
@@ -2425,16 +2409,12 @@ mod tests {
assert!(marker.delete_marker); assert!(marker.delete_marker);
let marker_id = delete_response_version_id(marker.version_id, false).expect("marker has a version identity"); let marker_id = delete_response_version_id(marker.version_id, false).expect("marker has a version identity");
assert_eq!(marker_id == "null", suspended); assert_eq!(marker_id == "null", suspended);
let get = GetObjectInput::builder() let get = get_object_input(&bucket, key, Some(marker_id.clone()));
.bucket(bucket.clone()) let get_err =
.key(key.to_string()) Box::pin(get_object_gateway(&usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get))
.version_id(Some(marker_id.clone())) .await
.build() .expect_err("GET of a marker remains forbidden");
.unwrap(); assert_eq!(get_err.code(), &rustfs_s3_types::S3ErrorCode::MethodNotAllowed);
let get_err = Box::pin(crate::app::test_seams::get_object_method_only(&usecase, get))
.await
.expect_err("GET of a marker remains forbidden");
assert_eq!(get_err.code(), &S3ErrorCode::MethodNotAllowed);
let head = head_object_input(&bucket, key, Some(marker_id.clone())); let head = head_object_input(&bucket, key, Some(marker_id.clone()));
let head_err = Box::pin(head_object_gateway( let head_err = Box::pin(head_object_gateway(
&usecase, &usecase,
@@ -2502,34 +2482,26 @@ mod tests {
assert_eq!(remaining.version_id, original.version_id); assert_eq!(remaining.version_id, original.version_id);
assert!(!remaining.delete_marker); assert!(!remaining.delete_marker);
assert_eq!(remaining.size, payload.len() as i64); assert_eq!(remaining.size, payload.len() as i64);
let removed = GetObjectInput::builder() let removed = get_object_input(&bucket, key, Some(marker_id));
.bucket(bucket.clone()) let missing = Box::pin(get_object_gateway(
.key(key.to_string()) &usecase,
.version_id(Some(marker_id)) get_envelope(HeaderMap::new(), http::Extensions::new()),
.build() removed,
.unwrap(); ))
let missing = Box::pin(crate::app::test_seams::get_object_method_only(&usecase, removed)) .await
.await .expect_err("the marker version must actually be gone");
.expect_err("the marker version must actually be gone");
assert_eq!( assert_eq!(
missing.code(), missing.code(),
&S3ErrorCode::NoSuchVersion, &rustfs_s3_types::S3ErrorCode::NoSuchVersion,
"pool_count={pool_count} suspended={suspended} batch={batch}: removed marker lookup returned {missing:?}" "pool_count={pool_count} suspended={suspended} batch={batch}: removed marker lookup returned {missing:?}"
); );
let get = GetObjectInput::builder() let get = get_object_input(&bucket, key, None);
.bucket(bucket.clone()) let response =
.key(key.to_string()) Box::pin(get_object_gateway(&usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get))
.build() .await
.unwrap(); .expect("GET restores the historical payload");
let response = Box::pin(crate::app::test_seams::get_object_method_only(&usecase, get)) let body = response.output.body.expect("GET body");
.await assert_eq!(read_get_body(body).await.as_ref(), payload);
.expect("GET restores the historical payload");
let mut body = response.output.body.expect("GET body");
let mut actual = Vec::new();
while let Some(chunk) = body.next().await {
actual.extend_from_slice(&chunk.expect("historical data remains readable"));
}
assert_eq!(actual, payload);
} }
} }
}); });
File diff suppressed because it is too large Load Diff
+18
View File
@@ -36,6 +36,24 @@ pub(crate) struct GetObjectFields {
pub(crate) sse_customer_key_md5: Option<String>, pub(crate) sse_customer_key_md5: Option<String>,
} }
impl From<dto::GetObjectInput> for GetObjectFields {
fn from(input: dto::GetObjectInput) -> Self {
use rustfs_gateway_types::RangeParse;
Self {
bucket: input.bucket.as_str().to_owned(),
key: input.key.as_str().to_owned(),
version_id: input.version_id,
part_number: input.part_number,
range: input.range.and_then(|range| match RangeParse::parse(range.as_str()) {
RangeParse::One(range) => Some(range),
_ => None,
}),
sse_customer_key: input.sse_customer_key.map(|key| key.expose_secret().to_owned()),
sse_customer_key_md5: input.sse_customer_key_md5,
}
}
}
impl GetObjectFields { impl GetObjectFields {
/// The conditional-read wire format permits a wildcard, a quoted tag, or a bare S3 tag. /// The conditional-read wire format permits a wildcard, a quoted tag, or a bare S3 tag.
pub(crate) fn valid_etag_condition(value: &[u8]) -> bool { pub(crate) fn valid_etag_condition(value: &[u8]) -> bool {
+96 -88
View File
@@ -18,7 +18,11 @@
use super::*; use super::*;
use crate::app::storage_api::s3::dto::Range; use crate::app::storage_api::s3::dto::Range;
use crate::app::storage_api::test::ReqInfo; use crate::app::storage_api::test::ReqInfo;
use crate::app::test_seams::{get_envelope, get_http_body, get_object_gateway, get_object_input};
use http::Method; use http::Method;
use http_body_util::BodyExt as _;
use rustfs_gateway_types::{BucketName, ObjectKey, RangeSpec, dto};
use rustfs_s3_types::S3ErrorCode;
#[test] #[test]
fn website_and_object_lambda_ranges_match_the_legacy_wire_reader() { fn website_and_object_lambda_ranges_match_the_legacy_wire_reader() {
@@ -80,16 +84,15 @@ fn website_and_object_lambda_conditions_match_the_legacy_wire_reader() {
} }
} }
fn get_request(input: GetObjectInput) -> S3Request<GetObjectInput> { fn get_envelope_with_info(input: &dto::GetObjectInput, headers: HeaderMap) -> crate::app::RequestEnvelope {
let info = ReqInfo { let mut extensions = http::Extensions::new();
bucket: Some(input.bucket.clone()), extensions.insert(ReqInfo {
object: Some(input.key.clone()), bucket: Some(input.bucket.as_str().to_owned()),
object: Some(input.key.as_str().to_owned()),
version_id: input.version_id.clone(), version_id: input.version_id.clone(),
..Default::default() ..Default::default()
}; });
let mut request = build_request(input, Method::GET); get_envelope(headers, extensions)
request.extensions.insert(info);
request
} }
async fn wire_get( async fn wire_get(
@@ -98,7 +101,6 @@ async fn wire_get(
headers: &[(&str, &str)], headers: &[(&str, &str)],
admitted: bool, admitted: bool,
) -> http::Response<Bytes> { ) -> http::Response<Bytes> {
use http_body_util::BodyExt as _;
use hyper_util::rt::TokioIo; use hyper_util::rt::TokioIo;
let before = operation_counts(); let before = operation_counts();
let socket = tokio::net::TcpStream::connect(server.address()).await.unwrap(); let socket = tokio::net::TcpStream::connect(server.address()).await.unwrap();
@@ -213,15 +215,13 @@ fn get_boundary(stack: Option<&str>) {
) )
.await .await
.unwrap(); .unwrap();
let request = get_request(GetObjectInput { let input = get_object_input(bucket, &key, None);
bucket: bucket.to_owned(), let response = get_object_gateway(&usecase, get_envelope_with_info(&input, HeaderMap::new()), input)
key: key.clone(), .await
..Default::default() .unwrap();
}); let tag = response.output.etag.expect("unencoded GET retains its ETag");
let response = crate::app::test_seams::get_object(&usecase, request).await.unwrap(); assert_eq!(tag.opaque, ["abc", "", "a\\b", "a\"b", "é", "a\rb", "a\nb", "a\0b"][index]);
let tag = response.output.e_tag.unwrap(); assert_eq!(tag.weak, index == 1);
assert_eq!(tag.value(), ["abc", "", "a\\b", "a\"b", "é", "a\rb", "a\nb", "a\0b"][index]);
assert_eq!(tag.as_weak().is_some(), index == 1);
assert_eq!(response.status, None); assert_eq!(response.status, None);
for (case, suffix, headers) in [ for (case, suffix, headers) in [
("ordinary", String::new(), vec![]), ("ordinary", String::new(), vec![]),
@@ -235,33 +235,28 @@ fn get_boundary(stack: Option<&str>) {
("range", String::new(), vec![("range", "bytes=1-3")]), ("range", String::new(), vec![("range", "bytes=1-3")]),
("unsatisfied", String::new(), vec![("range", "bytes=99-100")]), ("unsatisfied", String::new(), vec![("range", "bytes=99-100")]),
] { ] {
let range = match case { let mut input =
"range" => Some(Range::Int { first: 1, last: Some(3) }), get_object_input(bucket, &key, (case == "version304").then(|| info.version_id.unwrap().to_string()));
"unsatisfied" => Some(Range::Int { input.range = match case {
first: 99, "range" => Some(RangeSpec::new("bytes=1-3")),
last: Some(100), "unsatisfied" => Some(RangeSpec::new("bytes=99-100")),
}),
_ => None, _ => None,
}; };
let input = GetObjectInput { let mut request_headers = HeaderMap::new();
bucket: bucket.to_owned(),
key: key.clone(),
range,
version_id: (case == "version304").then(|| info.version_id.unwrap().to_string()),
..Default::default()
};
let mut request = get_request(input);
for (name, value) in &headers { for (name, value) in &headers {
request.headers.insert( request_headers.insert(
http::header::HeaderName::from_bytes(name.as_bytes()).unwrap(), http::header::HeaderName::from_bytes(name.as_bytes()).unwrap(),
HeaderValue::from_str(value).unwrap(), HeaderValue::from_str(value).unwrap(),
); );
} }
match crate::app::test_seams::get_object(&usecase, request).await { match get_object_gateway(&usecase, get_envelope_with_info(&input, request_headers), input).await {
Ok(response) => { Ok(response) => {
assert!(matches!(case, "ordinary" | "range")); assert!(matches!(case, "ordinary" | "range"));
assert_eq!(response.status, None); assert_eq!(response.status, None);
assert_eq!(response.output.content_range.as_deref(), (case == "range").then_some("bytes 1-3/7")); assert_eq!(
response.output.dto.content_range.as_deref(),
(case == "range").then_some("bytes 1-3/7")
);
} }
Err(error) => { Err(error) => {
let expected = match case { let expected = match case {
@@ -356,16 +351,22 @@ fn get_boundary(stack: Option<&str>) {
for (key, part, range) in [ for (key, part, range) in [
("", Some(0), None), ("", Some(0), None),
("object-0", Some(0), None), ("object-0", Some(0), None),
("object-0", Some(1), Some(Range::Int { first: 0, last: Some(1) })), ("object-0", Some(1), Some(RangeSpec::new("bytes=0-1"))),
] { ] {
let input = GetObjectInput { let input = dto::GetObjectInput {
bucket: "missing-boundary-bucket".to_owned(), bucket: BucketName::new("missing-boundary-bucket").unwrap(),
key: key.to_owned(), // The DTO's missing-key placeholder exercises validation before the invalid part number.
key: if key.is_empty() {
ObjectKey::default()
} else {
ObjectKey::new(key).unwrap()
},
part_number: part, part_number: part,
range, range,
..Default::default() ..Default::default()
}; };
let Err(error) = crate::app::test_seams::get_object(&usecase, get_request(input)).await else { let Err(error) = get_object_gateway(&usecase, get_envelope_with_info(&input, HeaderMap::new()), input).await
else {
panic!("invalid input must fail") panic!("invalid input must fail")
}; };
assert_eq!(error.code(), &S3ErrorCode::InvalidArgument); assert_eq!(error.code(), &S3ErrorCode::InvalidArgument);
@@ -432,16 +433,14 @@ fn get_boundary(stack: Option<&str>) {
) )
.await .await
.unwrap(); .unwrap();
let typed = crate::app::test_seams::get_object( let input = dto::GetObjectInput {
&usecase, bucket: crate::app::dto_values::stored_bucket_name(reserved).unwrap(),
get_request(GetObjectInput { key: ObjectKey::new("object").unwrap(),
bucket: reserved.to_owned(), ..Default::default()
key: "object".to_owned(), };
..Default::default() let typed = get_object_gateway(&usecase, get_envelope_with_info(&input, HeaderMap::new()), input)
}), .await
) .unwrap();
.await
.unwrap();
let wire = wire_get(&server, &format!("/{reserved}/object"), &[], true).await; let wire = wire_get(&server, &format!("/{reserved}/object"), &[], true).await;
assert_eq!(typed.status, None); assert_eq!(typed.status, None);
assert_eq!(wire.status(), StatusCode::OK); assert_eq!(wire.status(), StatusCode::OK);
@@ -524,7 +523,7 @@ async fn signed_override_contract(server: &crate::embedded::RustFSServer, bucket
} }
async fn ssec_wire_contract(usecase: &DefaultObjectUsecase, server: &crate::embedded::RustFSServer, bucket: &str) { async fn ssec_wire_contract(usecase: &DefaultObjectUsecase, server: &crate::embedded::RustFSServer, bucket: &str) {
use crate::app::storage_api::s3::dto::PutObjectInput; use crate::app::object_usecase::PutObjectWriteInput;
use md5::{Digest as _, Md5}; use md5::{Digest as _, Md5};
let key = [0x2a_u8; 32]; let key = [0x2a_u8; 32];
let encoded = base64_simd::STANDARD.encode_to_string(key); let encoded = base64_simd::STANDARD.encode_to_string(key);
@@ -532,33 +531,28 @@ async fn ssec_wire_contract(usecase: &DefaultObjectUsecase, server: &crate::embe
let wrong = [0x2b_u8; 32]; let wrong = [0x2b_u8; 32];
let wrong_encoded = base64_simd::STANDARD.encode_to_string(wrong); let wrong_encoded = base64_simd::STANDARD.encode_to_string(wrong);
let wrong_digest = base64_simd::STANDARD.encode_to_string(Md5::digest(wrong)); let wrong_digest = base64_simd::STANDARD.encode_to_string(Md5::digest(wrong));
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket(bucket.to_owned()) bucket: bucket.to_owned(),
.key("encrypted".to_owned()) key: "encrypted".to_owned(),
.body(Some(StreamingBlob::from_bytes(Bytes::from_static(b"protected payload")))) body: Some(rustfs_gateway_stream::Body::from_bytes(Bytes::from_static(b"protected payload"))),
.content_length(Some(17)) content_length: Some(17),
.sse_customer_algorithm(Some("AES256".to_owned())) sse_customer_algorithm: Some("AES256".to_owned()),
.sse_customer_key(Some(encoded.clone())) sse_customer_key: Some(encoded.clone()),
.sse_customer_key_md5(Some(digest.clone())) sse_customer_key_md5: Some(digest.clone()),
.build() ..Default::default()
.unwrap(); };
{ let envelope = crate::app::RequestEnvelope::from_parts(
let envelope = crate::app::RequestEnvelope::from_parts( crate::app::RequestHead {
crate::app::RequestHead { method: Method::PUT,
method: Method::PUT, uri: http::Uri::from_static("/"),
uri: http::Uri::from_static("/"), headers: http::HeaderMap::new(),
headers: http::HeaderMap::new(), credentials: None,
credentials: None, region: None,
region: None, service: None,
service: None, },
}, http::Extensions::new(),
http::Extensions::new(), );
); crate::app::test_seams::put_object(usecase, envelope, input).await.unwrap();
let input = crate::app::object_usecase::PutObjectWriteInput::from_legacy(input, None);
crate::app::test_seams::put_object(usecase, envelope, input)
}
.await
.unwrap();
for (case, valid, wrong_key, condition, range) in [ for (case, valid, wrong_key, condition, range) in [
("ordinary", true, false, false, false), ("ordinary", true, false, false, false),
("missing", false, false, false, false), ("missing", false, false, false, false),
@@ -657,7 +651,7 @@ async fn get_reader_handoff_preserves_baseline_copy_count() {
remaining: length, remaining: length,
writes: Arc::clone(&writes), writes: Arc::clone(&writes),
}; };
let mut body = DefaultObjectUsecase::build_reader_blob( let blob = DefaultObjectUsecase::build_reader_blob(
reader, reader,
length as i64, length as i64,
"copy-probe", "copy-probe",
@@ -670,13 +664,17 @@ async fn get_reader_handoff_preserves_baseline_copy_count() {
None, None,
) )
.await .await
.unwrap() .unwrap();
.into_s3s(); let mut body = get_http_body(blob);
assert_eq!(http_body::Body::size_hint(&body).exact(), Some(length as u64));
let mut chunks = Vec::new(); let mut chunks = Vec::new();
let mut observed_writes = 0; let mut observed_writes = 0;
let mut retained = 0; let mut retained = 0;
while let Some(chunk) = body.next().await { while let Some(frame) = body.frame().await {
let chunk = chunk.unwrap(); let chunk = frame
.expect("reader body must succeed")
.into_data()
.expect("unexpected reader trailers");
let begin = chunk.as_ptr() as usize; let begin = chunk.as_ptr() as usize;
let end = begin + chunk.len(); let end = begin + chunk.len();
let writes = writes.lock().unwrap(); let writes = writes.lock().unwrap();
@@ -694,6 +692,8 @@ async fn get_reader_handoff_preserves_baseline_copy_count() {
observed_writes = writes.len(); observed_writes = writes.len();
chunks.push(chunk); chunks.push(chunk);
} }
assert!(body.frame().await.is_none(), "EOF must be terminal");
assert_eq!(http_body::Body::size_hint(&body).exact(), Some(0));
let writes = writes.lock().unwrap(); let writes = writes.lock().unwrap();
let total: usize = chunks.iter().map(Bytes::len).sum(); let total: usize = chunks.iter().map(Bytes::len).sum();
assert_eq!(total, length); assert_eq!(total, length);
@@ -713,19 +713,27 @@ async fn get_memory_handoff_retains_the_original_allocation() {
for once in ["false", "true"] { for once in ["false", "true"] {
let bytes = Bytes::from(vec![b'm'; 8193]); let bytes = Bytes::from(vec![b'm'; 8193]);
let address = bytes.as_ptr() as usize; let address = bytes.as_ptr() as usize;
let mut body = temp_env::with_var(ENV_RUSTFS_GET_SMALL_BODY_ONCE_ENABLE, Some(once), || { let blob = temp_env::with_var(ENV_RUSTFS_GET_SMALL_BODY_ONCE_ENABLE, Some(once), || {
DefaultObjectUsecase::build_memory_bytes_blob( DefaultObjectUsecase::build_memory_bytes_blob(
bytes.clone(), bytes.clone(),
bytes.len() as i64, bytes.len() as i64,
GET_MEMORY_BODY_SOURCE_BUFFERED_BODY, GET_MEMORY_BODY_SOURCE_BUFFERED_BODY,
GetObjectBodyLifecycle::disabled(), GetObjectBodyLifecycle::disabled(),
) )
}) });
.into_s3s(); let mut body = get_http_body(blob);
assert_eq!(http_body::Body::size_hint(&body).exact(), Some(bytes.len() as u64));
let mut chunks = Vec::new(); let mut chunks = Vec::new();
while let Some(chunk) = body.next().await { while let Some(frame) = body.frame().await {
chunks.push(chunk.unwrap()); chunks.push(
frame
.expect("memory body must succeed")
.into_data()
.expect("unexpected memory trailers"),
);
} }
assert!(body.frame().await.is_none(), "EOF must be terminal");
assert_eq!(http_body::Body::size_hint(&body).exact(), Some(0));
let retained: usize = chunks let retained: usize = chunks
.iter() .iter()
.map(|chunk| { .map(|chunk| {
+3 -3
View File
@@ -18,12 +18,12 @@ use super::veeam_sosapi;
use super::*; use super::*;
use crate::app::dto_values::{stored_etag, timestamp}; use crate::app::dto_values::{stored_etag, timestamp};
use crate::app::storage_api::s3::header::X_AMZ_RESTORE;
use crate::app::{Answered, RequestEnvelope}; use crate::app::{Answered, RequestEnvelope};
use rustfs_gateway_types::ByteRange; use rustfs_gateway_types::ByteRange;
use rustfs_gateway_types::RangeParse; use rustfs_gateway_types::RangeParse;
use rustfs_gateway_types::dto as gateway_dto; use rustfs_gateway_types::dto as gateway_dto;
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result, s3_error}; use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result, s3_error};
use rustfs_utils::http::headers::AMZ_RESTORE;
use crate::on_demand_migration::{ use crate::on_demand_migration::{
BucketOdmState, HeadPolicy, OdmLookup, OdmOp, OdmOutcome, OnDemandMigrationSys, SourceClient, SourceError, SourceHead, BucketOdmState, HeadPolicy, OdmLookup, OdmOp, OdmOutcome, OnDemandMigrationSys, SourceClient, SourceError, SourceHead,
@@ -809,12 +809,12 @@ impl DefaultObjectUsecase {
response.headers.insert(header_name, header_value); response.headers.insert(header_name, header_value);
} }
if let Some(amz_restore) = metadata_map.get(X_AMZ_RESTORE.as_str()) { if let Some(amz_restore) = metadata_map.get(AMZ_RESTORE) {
let Ok(restore_status) = parse_restore_obj_status(amz_restore) else { let Ok(restore_status) = parse_restore_obj_status(amz_restore) else {
return Err(S3Error::with_message(S3ErrorCode::Custom("ErrMeta".into()), "parse amz_restore failed.")); return Err(S3Error::with_message(S3ErrorCode::Custom("ErrMeta".into()), "parse amz_restore failed."));
}; };
if let Ok(header_value) = HeaderValue::from_str(restore_status.to_string2().as_str()) { if let Ok(header_value) = HeaderValue::from_str(restore_status.to_string2().as_str()) {
response.headers.insert(X_AMZ_RESTORE, header_value); response.headers.insert(AMZ_RESTORE, header_value);
} }
} }
if let Some(amz_restore_request_date) = metadata_map.get(AMZ_RESTORE_REQUEST_DATE) if let Some(amz_restore_request_date) = metadata_map.get(AMZ_RESTORE_REQUEST_DATE)
+57 -49
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//! Regression tests for the HeadObject response facts and their HTTP and legacy projections. //! Regression tests for the HeadObject response facts and their HTTP projection.
//! The existing completion probe exposes the AuditEntry before asynchronous delivery. //! The existing completion probe exposes the AuditEntry before asynchronous delivery.
use super::*; use super::*;
@@ -20,60 +20,68 @@ use crate::app::test_seams::{head_envelope, head_object_input};
use http::Method; use http::Method;
#[test] #[test]
fn head_stored_etag_facts_and_legacy_projection_preserve_spelling() { fn head_stored_etag_facts_and_http_projection_preserve_spelling() {
head_stored_etag_facts_preserve_spelling(); head_stored_etag_facts_preserve_spelling();
head_legacy_etag_projection_preserves_spelling(); head_etag_http_projection_preserves_spelling();
} }
#[test] #[test]
fn head_stored_etag_facts_preserve_spelling() { fn head_stored_etag_facts_preserve_spelling() {
for raw in [ for (raw, opaque, weak) in [
"abc", ("abc", "abc", false),
"\"abc\"", ("\"abc\"", "abc", false),
"W/\"abc\"", ("W/\"abc\"", "abc", true),
"W/\"\"", ("W/\"\"", "", true),
"\"\"", ("\"\"", "", false),
"", ("", "", false),
"*", ("*", "*", false),
" abc ", (" abc ", " abc ", false),
"abc_def", ("abc_def", "abc_def", false),
"a&b", ("a&b", "a&b", false),
"\"a&b\"", ("\"a&b\"", "a&b", false),
"\"a b\"", ("\"a b\"", "a b", false),
"\"a\\b\"", ("\"a\\b\"", "a\\b", false),
"\"a\"b\"", ("\"a\"b\"", "a\"b", false),
"w/\"abc\"", ("w/\"abc\"", "w/\"abc\"", false),
"\"abc", ("\"abc", "\"abc", false),
"W/abc", ("W/abc", "W/abc", false),
"a\rb", ("a\rb", "a\rb", false),
"a\nb", ("a\nb", "a\nb", false),
"a\0b", ("a\0b", "a\0b", false),
"é", ("é", "é", false),
("6af8d12c0c74b78094884349f3c8a079", "6af8d12c0c74b78094884349f3c8a079", false),
("\"6af8d12c0c74b78094884349f3c8a079\"", "6af8d12c0c74b78094884349f3c8a079", false),
("W/\"6af8d12c0c74b78094884349f3c8a079\"", "6af8d12c0c74b78094884349f3c8a079", true),
("\"incomplete", "\"incomplete", false),
("incomplete\"", "incomplete\"", false),
("W/\"incomplete", "incomplete", true),
] { ] {
let expected = to_s3s_etag(raw);
let fact = ResponseEtag::from_stored(raw); let fact = ResponseEtag::from_stored(raw);
assert_eq!(fact.opaque, expected.value(), "{raw:?}"); assert_eq!(fact.opaque, opaque, "{raw:?}");
assert_eq!(fact.weak, expected.as_weak().is_some(), "{raw:?}"); assert_eq!(fact.weak, weak, "{raw:?}");
} }
} }
#[test] #[test]
fn head_legacy_etag_projection_preserves_spelling() { fn head_etag_http_projection_preserves_spelling() {
for weak in [false, true] { for (opaque, strong, weak) in [
for opaque in ["", "abc", "a\\b", "a\"b", "a\rb", "é"] { ("", Some(&b"\"\""[..]), Some(&b"W/\"\""[..])),
("abc", Some(&b"\"abc\""[..]), Some(&b"W/\"abc\""[..])),
("a\\b", Some(&b"\"a\\b\""[..]), Some(&b"W/\"a\\b\""[..])),
("a\"b", Some(&b"\"a\"b\""[..]), Some(&b"W/\"a\"b\""[..])),
("a\rb", None, None),
("é", Some(&b"\"\xc3\xa9\""[..]), Some(&b"W/\"\xc3\xa9\""[..])),
] {
for (weak, expected) in [(false, strong), (true, weak)] {
let fact = ResponseEtag { let fact = ResponseEtag {
opaque: opaque.to_owned(), opaque: opaque.to_owned(),
weak, weak,
}; };
let output = HeadObjectOutputFacts { let actual = fact.to_http_header();
dto: gateway_dto::HeadObjectOutput::default(), match expected {
etag: Some(fact), Some(bytes) => assert_eq!(actual.unwrap().as_bytes(), bytes, "{opaque:?}, weak={weak}"),
None => assert!(actual.is_err(), "{opaque:?}, weak={weak}"),
} }
.into_s3s()
.unwrap();
let tag = output.e_tag.expect("legacy typed caller keeps the fact");
assert_eq!(tag.value(), opaque);
assert_eq!(tag.as_weak().is_some(), weak);
} }
} }
} }
@@ -105,11 +113,16 @@ fn head_proxy_etag_mapping_matches_the_legacy_parser() {
.build(); .build();
let facts = DefaultObjectUsecase::proxy_sdk_head_output(sdk); let facts = DefaultObjectUsecase::proxy_sdk_head_output(sdk);
assert!(facts.dto.e_tag.is_none(), "ETag is carried as a response fact"); assert!(facts.dto.e_tag.is_none(), "ETag is carried as a response fact");
assert_eq!(facts.into_s3s().unwrap().e_tag, expected, "{raw:?}"); assert_eq!(
facts.etag.as_ref().map(|tag| (tag.opaque.as_str(), tag.weak)),
expected.as_ref().map(|tag| (tag.value(), tag.as_weak().is_some())),
"{raw:?}"
);
} }
let absent = let absent =
DefaultObjectUsecase::proxy_sdk_head_output(aws_sdk_s3::operation::head_object::HeadObjectOutput::builder().build()); DefaultObjectUsecase::proxy_sdk_head_output(aws_sdk_s3::operation::head_object::HeadObjectOutput::builder().build());
assert!(absent.into_s3s().unwrap().e_tag.is_none()); assert!(absent.etag.is_none());
assert!(absent.dto.e_tag.is_none());
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -263,14 +276,9 @@ fn head_etag_wire_and_audit(stack: Option<&'static str>, rows: &'static [HeadEta
let internal = crate::app::test_seams::head_object_gateway(&usecase, envelope, input) let internal = crate::app::test_seams::head_object_gateway(&usecase, envelope, input)
.await .await
.expect("unencoded HEAD response"); .expect("unencoded HEAD response");
let typed = internal let fact = internal.output.etag.expect("internal caller retains the ETag");
.output assert_eq!(fact.opaque, row.opaque, "{}", row.stored);
.into_s3s() assert_eq!(fact.weak, row.weak, "{}", row.stored);
.expect("legacy response projection")
.e_tag
.expect("internal caller retains the ETag");
assert_eq!(typed.value(), row.opaque, "{}", row.stored);
assert_eq!(typed.as_weak().is_some(), row.weak, "{}", row.stored);
expected_audits.push((Some("s3:HeadObject".to_owned()), Some("success".to_owned()), Some(200))); expected_audits.push((Some("s3:HeadObject".to_owned()), Some("success".to_owned()), Some(200)));
probe.wait_for(index * 3 + 1, 0).await; probe.wait_for(index * 3 + 1, 0).await;
for conditional in [false, true] { for conditional in [false, true] {
-6
View File
@@ -94,8 +94,6 @@ use super::storage_api::object_usecase::object_cache::GetObjectBodySource;
#[cfg(test)] #[cfg(test)]
use super::storage_api::object_usecase::object_cache::lookup_get_object_body_cache_hook; use super::storage_api::object_usecase::object_cache::lookup_get_object_body_cache_hook;
use super::storage_api::object_usecase::object_cache::{GetObjectBodyCacheHookLookup, get_object_body_cache_plaintext_len}; use super::storage_api::object_usecase::object_cache::{GetObjectBodyCacheHookLookup, get_object_body_cache_plaintext_len};
#[cfg(test)]
use super::storage_api::object_usecase::object_utils::to_s3s_etag;
use super::storage_api::object_usecase::options::{ use super::storage_api::object_usecase::options::{
copy_dst_opts_with_replication_authorization, copy_src_opts, del_opts_with_versioning, extract_metadata, copy_dst_opts_with_replication_authorization, copy_src_opts, del_opts_with_versioning, extract_metadata,
extract_metadata_from_mime_with_object_name, filter_object_metadata, get_content_sha256_with_query, get_opts, extract_metadata_from_mime_with_object_name, filter_object_metadata, get_content_sha256_with_query, get_opts,
@@ -185,8 +183,6 @@ use rustfs_utils::http::{
use rustfs_utils::path::{encode_dir_object, is_dir_object, path_join_buf}; use rustfs_utils::path::{encode_dir_object, is_dir_object, path_join_buf};
use rustfs_utils::retry::{DEFAULT_RETRY_CAP, DEFAULT_RETRY_UNIT, MAX_JITTER, RetryTimer}; use rustfs_utils::retry::{DEFAULT_RETRY_CAP, DEFAULT_RETRY_UNIT, MAX_JITTER, RetryTimer};
use rustfs_zip::{ArchiveLimits, CompressionFormat, ZipError}; use rustfs_zip::{ArchiveLimits, CompressionFormat, ZipError};
#[cfg(test)]
use s3s::{S3Request, S3Response};
/// Remove replication history owned by another source object before a local /// Remove replication history owned by another source object before a local
/// object-creation decision is made. Compatibility keys are case-insensitive, /// object-creation decision is made. Compatibility keys are case-insensitive,
@@ -238,8 +234,6 @@ pub(crate) use native_body::{BodyChunks, FrameTrailers, upload_frame_reader};
pub(crate) use put_input::{PutObjectWriteInput, PutObjectWriteOutput}; pub(crate) use put_input::{PutObjectWriteInput, PutObjectWriteOutput};
pub(crate) mod request_body; pub(crate) mod request_body;
mod restore; mod restore;
#[cfg(test)]
mod s3s_compat;
pub(crate) mod shared; pub(crate) mod shared;
#[cfg(test)] #[cfg(test)]
mod test_support; mod test_support;
@@ -299,7 +299,6 @@ impl OdmWriteBack for OnDemandMigrationWriteBack {
mod tests { mod tests {
use super::*; use super::*;
use crate::app::storage_api::multipart_usecase::contract::multipart::MultipartOperations as _; use crate::app::storage_api::multipart_usecase::contract::multipart::MultipartOperations as _;
use crate::app::storage_api::s3::dto::GetObjectInput;
use crate::app::storage_api::s3::{ use crate::app::storage_api::s3::{
PersistedOptionalReplicationStatus, PersistedReplicationConfiguration, PersistedReplicationDestination, PersistedOptionalReplicationStatus, PersistedReplicationConfiguration, PersistedReplicationDestination,
PersistedReplicationFilter, PersistedReplicationRule, PersistedReplicationTag, Status, PersistedReplicationFilter, PersistedReplicationRule, PersistedReplicationTag, Status,
@@ -307,6 +306,7 @@ mod tests {
use crate::app::storage_api::test::bucket::utils::serialize; use crate::app::storage_api::test::bucket::utils::serialize;
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions}; use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions};
use crate::app::storage_api::test::{get_global_bucket_metadata_sys, set_bucket_metadata}; use crate::app::storage_api::test::{get_global_bucket_metadata_sys, set_bucket_metadata};
use crate::app::test_seams::{get_envelope, get_object_gateway, get_object_input, read_get_body};
use crate::on_demand_migration::{PullFailureReason, SourceSse}; use crate::on_demand_migration::{PullFailureReason, SourceSse};
use rustfs_gateway_types::persistence::{ use rustfs_gateway_types::persistence::{
PersistedBucketEncryptionConfiguration as ServerSideEncryptionConfiguration, PersistedBucketEncryptionConfiguration as ServerSideEncryptionConfiguration,
@@ -420,20 +420,15 @@ mod tests {
} }
async fn get_via_app(bucket: &str, key: &str) -> Vec<u8> { async fn get_via_app(bucket: &str, key: &str) -> Vec<u8> {
let input = GetObjectInput::builder() let response = get_object_gateway(
.bucket(bucket.to_string()) &DefaultObjectUsecase::from_global(),
.key(key.to_string()) get_envelope(HeaderMap::new(), http::Extensions::new()),
.build() get_object_input(bucket, key, None),
.expect("GET input must build"); )
let mut response = crate::app::test_seams::get_object_method_only(&DefaultObjectUsecase::from_global(), input) .await
.await .expect("app-layer GET must succeed");
.expect("app-layer GET must succeed"); let body = response.output.body.expect("GET response must include a body");
let mut body = response.output.body.take().expect("GET response must include a body"); read_get_body(body).await.to_vec()
let mut actual = Vec::new();
while let Some(chunk) = body.next().await {
actual.extend_from_slice(&chunk.expect("GET body chunk"));
}
actual
} }
fn assert_provenance(metadata: &HashMap<String, String>, head: &SourceHead) { fn assert_provenance(metadata: &HashMap<String, String>, head: &SourceHead) {
+182 -197
View File
@@ -20,7 +20,8 @@ use super::*;
use crate::app::RequestEnvelope; use crate::app::RequestEnvelope;
#[cfg(test)] #[cfg(test)]
use crate::app::storage_api::s3::dto::{PutObjectInput, ServerSideEncryption, StorageClass, StreamingBlob}; use crate::app::storage_api::s3::dto::{PutObjectInput, ServerSideEncryption, StorageClass, StreamingBlob};
use crate::app::storage_api::s3::stream::{ByteStream, RemainingLength}; #[cfg(test)]
use crate::app::storage_api::s3::stream::ByteStream;
use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Result, StdError, s3_error}; use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Result, StdError, s3_error};
use futures::FutureExt; use futures::FutureExt;
use rustfs_gateway_stream::Body as NativeBody; use rustfs_gateway_stream::Body as NativeBody;
@@ -210,17 +211,6 @@ impl<S: Stream<Item = Result<Bytes, StdError>> + Unpin> Stream for MaxContentLen
} }
} }
impl<S: ByteStream<Item = Result<Bytes, StdError>> + Unpin> ByteStream for MaxContentLengthStream<S> {
fn remaining_length(&self) -> RemainingLength {
let remaining = usize::try_from(self.limit.saturating_sub(self.received)).unwrap_or(usize::MAX);
let inner = self.inner.remaining_length();
inner
.exact()
.map(|exact| RemainingLength::new_exact(exact.min(remaining)))
.unwrap_or_else(RemainingLength::unknown)
}
}
pub(super) struct PooledBufferReader { pub(super) struct PooledBufferReader {
buffer: PooledBuffer, buffer: PooledBuffer,
len: usize, len: usize,
@@ -2619,34 +2609,22 @@ mod tests {
} }
use super::*; use super::*;
use crate::app::storage_api::s3::dto::{GetObjectInput, ObjectLockRetentionMode}; use crate::app::storage_api::s3::dto::ObjectLockRetentionMode;
use crate::app::test_seams::{head_envelope, head_object_input}; use crate::app::test_seams::{
get_envelope, get_object_gateway, get_object_input, head_envelope, head_object_input, read_get_body,
};
use futures::StreamExt; use futures::StreamExt;
use http::{HeaderMap, HeaderName, HeaderValue, Method}; use http::{HeaderMap, HeaderName, HeaderValue, Method};
use rustfs_gateway_types::SseCustomerKey; use rustfs_gateway_types::SseCustomerKey;
use rustfs_s3_types::S3ErrorCode as OwnedS3ErrorCode; use rustfs_s3_types::S3ErrorCode as OwnedS3ErrorCode;
/// PutObject through the owned entry point the gateway handler calls, its error in the s3s fn write_envelope(method: Method, uri: http::Uri, headers: HeaderMap, mut extensions: http::Extensions) -> RequestEnvelope {
/// form these tests compare. if method == Method::POST {
async fn put_owned(usecase: &DefaultObjectUsecase, req: S3Request<PutObjectInput>) -> S3Result<PutObjectWriteOutput> { extensions.insert(PostObjectRequestMarker);
let (envelope, input) = PutObjectWriteInput::from_test_request(req); }
Box::pin(usecase.execute_put_object_owned(envelope, input))
.await
.map_err(S3Error::from)
}
/// As [`put_owned`], through the archive-extraction entry point.
async fn put_extract_owned(usecase: &DefaultObjectUsecase, req: S3Request<PutObjectInput>) -> S3Result<PutObjectWriteOutput> {
let (envelope, input) = PutObjectWriteInput::from_test_request(req);
Box::pin(usecase.execute_put_object_extract_owned(envelope, input))
.await
.map_err(S3Error::from)
}
fn put_envelope(uri: http::Uri, headers: HeaderMap, extensions: http::Extensions) -> RequestEnvelope {
RequestEnvelope::from_parts( RequestEnvelope::from_parts(
crate::app::RequestHead { crate::app::RequestHead {
method: Method::PUT, method,
uri, uri,
headers, headers,
credentials: None, credentials: None,
@@ -2658,7 +2636,7 @@ mod tests {
} }
fn method_only_put_envelope() -> RequestEnvelope { fn method_only_put_envelope() -> RequestEnvelope {
put_envelope(http::Uri::from_static("/"), HeaderMap::new(), http::Extensions::new()) write_envelope(Method::PUT, http::Uri::from_static("/"), HeaderMap::new(), http::Extensions::new())
} }
fn put_bytes(bucket: String, key: &str, bytes: Bytes) -> PutObjectWriteInput { fn put_bytes(bucket: String, key: &str, bytes: Bytes) -> PutObjectWriteInput {
@@ -2919,23 +2897,18 @@ mod tests {
{ {
for method in [Method::PUT, Method::POST] { for method in [Method::PUT, Method::POST] {
let key = format!("refused-{index}-{method}"); let key = format!("refused-{index}-{method}");
let input = PutObjectInput::builder() let input = put_bytes(bucket.clone(), &key, Bytes::from_static(b"quorum probe"));
.bucket(bucket.clone())
.key(key.clone())
.body(Some(StreamingBlob::from_bytes(Bytes::from_static(b"quorum probe"))))
.content_length(Some(12))
.build()
.expect("quorum probe input must build");
let probe = crate::app::storage_api::object_usecase::helper::MutationCompletionProbe::install(&bucket); let probe = crate::app::storage_api::object_usecase::helper::MutationCompletionProbe::install(&bucket);
let mut req = build_request(input, method.clone()); let envelope = write_envelope(
req.uri = format!("/{bucket}/{key}").parse().expect("PUT URI"); method.clone(),
if method == Method::POST { format!("/{bucket}/{key}").parse().expect("PUT URI"),
req.extensions.insert(PostObjectRequestMarker); HeaderMap::new(),
} http::Extensions::new(),
);
let err = PUT_STORAGE_TEST_FAILURE let err = PUT_STORAGE_TEST_FAILURE
.scope( .scope(
(stage, StorageError::InsufficientReadQuorum("bucket".into(), "object".into())), (stage, StorageError::InsufficientReadQuorum("bucket".into(), "object".into())),
put_owned(&usecase, req), Box::pin(usecase.execute_put_object_owned(envelope, input)),
) )
.await .await
.expect_err("read quorum failure must refuse the upload"); .expect_err("read quorum failure must refuse the upload");
@@ -2947,7 +2920,7 @@ mod tests {
assert_eq!(audits[0].api.status_code, Some(503)); assert_eq!(audits[0].api.status_code, Some(503));
assert!(probe.events.lock().expect("events").is_empty()); assert!(probe.events.lock().expect("events").is_empty());
} }
assert_eq!(err.code(), &S3ErrorCode::ServiceUnavailable, "stage {index}, method {method}"); assert_eq!(err.code(), &OwnedS3ErrorCode::ServiceUnavailable, "stage {index}, method {method}");
assert_eq!(err.status_code(), Some(http::StatusCode::SERVICE_UNAVAILABLE)); assert_eq!(err.status_code(), Some(http::StatusCode::SERVICE_UNAVAILABLE));
assert_eq!(err.message(), Some("The service is unavailable. Please retry.")); assert_eq!(err.message(), Some("The service is unavailable. Please retry."));
assert!(matches!( assert!(matches!(
@@ -3269,14 +3242,11 @@ mod tests {
Arc::clone(&metadata_entered), Arc::clone(&metadata_entered),
Arc::clone(&metadata_resume), Arc::clone(&metadata_resume),
); );
let metadata_input = GetObjectInput::builder() let metadata_input = get_object_input(&bucket, object, None);
.bucket(bucket.clone())
.key(object.to_string())
.build()
.expect("metadata GET input must build");
let metadata_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let metadata_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let metadata_get = let metadata_get = tokio::spawn(async move {
tokio::spawn(async move { crate::app::test_seams::get_object_method_only(&metadata_usecase, metadata_input).await }); get_object_gateway(&metadata_usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), metadata_input).await
});
tokio::time::timeout(Duration::from_secs(2), metadata_entered.wait()) tokio::time::timeout(Duration::from_secs(2), metadata_entered.wait())
.await .await
.expect("GET must enter the bucket metadata stage"); .expect("GET must enter the bucket metadata stage");
@@ -3298,13 +3268,11 @@ mod tests {
.get_write_lock(Duration::from_secs(5)) .get_write_lock(Duration::from_secs(5))
.await .await
.expect("read test namespace lock must be held"); .expect("read test namespace lock must be held");
let get_input = GetObjectInput::builder() let get_input = get_object_input(&bucket, object, None);
.bucket(bucket.clone())
.key(object.to_string())
.build()
.expect("GET input must build");
let get_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let get_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let get = tokio::spawn(async move { crate::app::test_seams::get_object_method_only(&get_usecase, get_input).await }); let get = tokio::spawn(async move {
get_object_gateway(&get_usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get_input).await
});
tokio::time::timeout(Duration::from_secs(2), async { tokio::time::timeout(Duration::from_secs(2), async {
while !object_traffic_health.read_storage_stalled_for_test() { while !object_traffic_health.read_storage_stalled_for_test() {
tokio::task::yield_now().await; tokio::task::yield_now().await;
@@ -3390,7 +3358,8 @@ mod tests {
let payload = Bytes::from_static(b"published despite caller cancellation"); let payload = Bytes::from_static(b"published despite caller cancellation");
let put_input = put_bytes(bucket.clone(), object, payload.clone()); let put_input = put_bytes(bucket.clone(), object, payload.clone());
let put_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let put_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let envelope = put_envelope( let envelope = write_envelope(
Method::PUT,
format!("/{bucket}/{object}").parse().expect("PUT URI"), format!("/{bucket}/{object}").parse().expect("PUT URI"),
HeaderMap::new(), HeaderMap::new(),
http::Extensions::new(), http::Extensions::new(),
@@ -3430,7 +3399,8 @@ mod tests {
assert_eq!(recovered.size, i64::try_from(payload.len()).expect("test payload length must fit i64")); assert_eq!(recovered.size, i64::try_from(payload.len()).expect("test payload length must fit i64"));
probe.wait_for(1, 1).await; probe.wait_for(1, 1).await;
let normal_input = put_bytes(bucket.clone(), "normal.bin", Bytes::from_static(b"normal")); let normal_input = put_bytes(bucket.clone(), "normal.bin", Bytes::from_static(b"normal"));
let envelope = put_envelope( let envelope = write_envelope(
Method::PUT,
format!("/{bucket}/normal.bin").parse().expect("URI"), format!("/{bucket}/normal.bin").parse().expect("URI"),
HeaderMap::new(), HeaderMap::new(),
http::Extensions::new(), http::Extensions::new(),
@@ -3467,8 +3437,12 @@ mod tests {
..put_bytes(bucket.clone(), extra_body_object, Bytes::from_static(b"x")) ..put_bytes(bucket.clone(), extra_body_object, Bytes::from_static(b"x"))
}; };
let extra_body_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let extra_body_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let extra_body_envelope = let extra_body_envelope = write_envelope(
put_envelope(http::Uri::from_static("/"), streaming_headers(Some("0")), http::Extensions::new()); Method::PUT,
http::Uri::from_static("/"),
streaming_headers(Some("0")),
http::Extensions::new(),
);
let extra_body_err = Box::pin(extra_body_usecase.execute_put_object_owned(extra_body_envelope, extra_body_input)) let extra_body_err = Box::pin(extra_body_usecase.execute_put_object_owned(extra_body_envelope, extra_body_input))
.await .await
.expect_err("decoded zero-byte PUT with body data must fail"); .expect_err("decoded zero-byte PUT with body data must fail");
@@ -3503,7 +3477,12 @@ mod tests {
..Default::default() ..Default::default()
}; };
let zero_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let zero_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let zero_envelope = put_envelope(http::Uri::from_static("/"), streaming_headers(Some("0")), http::Extensions::new()); let zero_envelope = write_envelope(
Method::PUT,
http::Uri::from_static("/"),
streaming_headers(Some("0")),
http::Extensions::new(),
);
let zero_put = let zero_put =
tokio::spawn(async move { Box::pin(zero_usecase.execute_put_object_owned(zero_envelope, zero_input)).await }); tokio::spawn(async move { Box::pin(zero_usecase.execute_put_object_owned(zero_envelope, zero_input)).await });
@@ -4054,7 +4033,7 @@ mod tests {
}; };
let mut extensions = http::Extensions::new(); let mut extensions = http::Extensions::new();
extensions.insert(control.clone()); extensions.insert(control.clone());
let envelope = put_envelope(http::Uri::from_static("/"), HeaderMap::new(), extensions); let envelope = write_envelope(Method::PUT, http::Uri::from_static("/"), HeaderMap::new(), extensions);
let usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let owner = tokio::spawn(async move { Box::pin(usecase.execute_put_object_owned(envelope, input)).await }); let owner = tokio::spawn(async move { Box::pin(usecase.execute_put_object_owned(envelope, input)).await });
control.wait_until_pending_for_test().await; control.wait_until_pending_for_test().await;
@@ -4443,31 +4422,30 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn post_object_metadata_cannot_dispatch_legacy_archive_extraction() { async fn post_object_metadata_cannot_dispatch_legacy_archive_extraction() {
let mut req = build_request(PutObjectInput::default(), Method::POST); let input = PutObjectWriteInput::default();
req.extensions.insert(PostObjectRequestMarker); let envelope = write_envelope(Method::POST, http::Uri::from_static("/"), HeaderMap::new(), http::Extensions::new());
let err = Box::pin(put_extract_owned(&DefaultObjectUsecase::without_context(), req)) let err = Box::pin(DefaultObjectUsecase::without_context().execute_put_object_extract_owned(envelope, input))
.await .await
.expect_err("a legacy form cannot authorize archive replay"); .expect_err("a legacy form cannot authorize archive replay");
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
async fn execute_put_object_rejects_post_object_etag_if_none_match_header() { async fn execute_put_object_rejects_post_object_etag_if_none_match_header() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("test-key".to_string()) key: "test-key".to_owned(),
.build() ..Default::default()
.expect("POST-to-PUT input should build without conditional DTO fields"); };
let mut req = build_request(input, Method::POST); let mut headers = HeaderMap::new();
req.extensions.insert(PostObjectRequestMarker); headers.insert(http::header::IF_NONE_MATCH, HeaderValue::from_static("\"different-etag\""));
req.headers
.insert(http::header::IF_NONE_MATCH, HeaderValue::from_static("\"different-etag\""));
let envelope = write_envelope(Method::POST, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)) let err = Box::pin(usecase.execute_put_object_owned(envelope, input))
.await .await
.expect_err("POST header-only ETag precondition must fail before storage access"); .expect_err("POST header-only ETag precondition must fail before storage access");
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
@@ -4483,7 +4461,18 @@ mod tests {
let mut request = build_request(input, Method::POST); let mut request = build_request(input, Method::POST);
request.extensions.insert(PostObjectRequestMarker); request.extensions.insert(PostObjectRequestMarker);
request.headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true")); request.headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
let mut envelope = RequestEnvelope::from_s3s(&request); // Same facts `RequestEnvelope::from_s3s` copies. Credentials, region, and service stay absent.
let mut envelope = RequestEnvelope::from_parts(
crate::app::RequestHead {
method: request.method.clone(),
uri: request.uri.clone(),
headers: request.headers.clone(),
credentials: None,
region: None,
service: None,
},
request.extensions.clone(),
);
assert!(!envelope.is_gateway_post(), "legacy provenance must remain distinct"); assert!(!envelope.is_gateway_post(), "legacy provenance must remain distinct");
envelope.mark_gateway_post(); envelope.mark_gateway_post();
assert!(envelope.fork_for_authorization().is_gateway_post()); assert!(envelope.fork_for_authorization().is_gateway_post());
@@ -4506,56 +4495,54 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn execute_put_object_rejects_post_object_sse_kms_from_input() { async fn execute_put_object_rejects_post_object_sse_kms_from_input() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("test-key".to_string()) key: "test-key".to_owned(),
.server_side_encryption(Some(ServerSideEncryption::from_static(ServerSideEncryption::AWS_KMS))) server_side_encryption: Some(ServerSideEncryption::AWS_KMS.to_owned()),
.build() ..Default::default()
.unwrap(); };
let mut req = build_request(input, Method::POST);
req.extensions.insert(PostObjectRequestMarker);
let envelope = write_envelope(Method::POST, http::Uri::from_static("/"), HeaderMap::new(), http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
async fn execute_put_object_rejects_extract_sse_kms() { async fn execute_put_object_rejects_extract_sse_kms() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("archive.tar".to_string()) key: "archive.tar".to_owned(),
.server_side_encryption(Some(ServerSideEncryption::from_static(ServerSideEncryption::AWS_KMS))) server_side_encryption: Some(ServerSideEncryption::AWS_KMS.to_owned()),
.build() ..Default::default()
.unwrap(); };
let mut headers = HeaderMap::new();
let mut req = build_request(input, Method::PUT); headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
req.headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
let envelope = write_envelope(Method::PUT, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
async fn execute_put_object_extract_rejects_invalid_storage_class() { async fn execute_put_object_extract_rejects_invalid_storage_class() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("archive.tar".to_string()) key: "archive.tar".to_owned(),
.storage_class(Some(StorageClass::from_static("INVALID"))) storage_class: Some("INVALID".to_owned()),
.build() ..Default::default()
.unwrap(); };
let mut headers = HeaderMap::new();
let mut req = build_request(input, Method::PUT); headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
req.headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
let envelope = write_envelope(Method::PUT, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::InvalidStorageClass); assert_eq!(err.code(), &OwnedS3ErrorCode::InvalidStorageClass);
} }
/// issue #7596: a single PUT whose declared length exceeds the 5 GiB /// issue #7596: a single PUT whose declared length exceeds the 5 GiB
@@ -4590,36 +4577,40 @@ mod tests {
let framing_overhead = 1_000_000; let framing_overhead = 1_000_000;
for (decoded, expect_too_large) in [(ceiling, false), (ceiling + 1, true)] { for (decoded, expect_too_large) in [(ceiling, false), (ceiling + 1, true)] {
let (body, polls) = PollCountingBody::streaming_blob(); let polls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let input = PutObjectInput::builder() let body_polls = Arc::clone(&polls);
.bucket("test-bucket".to_string()) let body = super::super::native_body::from_io_stream(futures::stream::repeat_with(move || {
.key("huge.bin".to_string()) body_polls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
.body(Some(body)) Ok(Bytes::from_static(b"x"))
.content_length(Some(decoded + framing_overhead)) }));
.build() let input = PutObjectWriteInput {
.unwrap(); bucket: "test-bucket".to_owned(),
key: "huge.bin".to_owned(),
let mut req = build_request(input, Method::PUT); body: Some(body),
req.headers content_length: Some(decoded + framing_overhead),
.insert(http::header::CONTENT_ENCODING, HeaderValue::from_static("aws-chunked")); ..Default::default()
req.headers.insert( };
let mut headers = HeaderMap::new();
headers.insert(http::header::CONTENT_ENCODING, HeaderValue::from_static("aws-chunked"));
headers.insert(
HeaderName::from_static("x-amz-content-sha256"), HeaderName::from_static("x-amz-content-sha256"),
HeaderValue::from_static("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"), HeaderValue::from_static("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"),
); );
req.headers.insert( headers.insert(
HeaderName::from_static("x-amz-decoded-content-length"), HeaderName::from_static("x-amz-decoded-content-length"),
HeaderValue::from_str(&decoded.to_string()).unwrap(), HeaderValue::from_str(&decoded.to_string()).unwrap(),
); );
let envelope = write_envelope(Method::PUT, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
if expect_too_large { if expect_too_large {
assert_eq!(err.code(), &S3ErrorCode::EntityTooLarge, "decoded {decoded}"); assert_eq!(err.code(), &OwnedS3ErrorCode::EntityTooLarge, "decoded {decoded}");
assert_eq!(polls.load(std::sync::atomic::Ordering::SeqCst), 0, "body must not be polled"); assert_eq!(polls.load(std::sync::atomic::Ordering::SeqCst), 0, "body must not be polled");
} else { } else {
assert_ne!( assert_ne!(
err.code(), err.code(),
&S3ErrorCode::EntityTooLarge, &OwnedS3ErrorCode::EntityTooLarge,
"framed wire length above the cap must not reject a decoded length at the cap" "framed wire length above the cap must not reject a decoded length at the cap"
); );
} }
@@ -4628,40 +4619,36 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn execute_put_object_rejects_post_object_sse_kms_from_headers() { async fn execute_put_object_rejects_post_object_sse_kms_from_headers() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("test-key".to_string()) key: "test-key".to_owned(),
.build() ..Default::default()
.unwrap(); };
let mut headers = HeaderMap::new();
let mut req = build_request(input, Method::POST); headers.insert(AMZ_SERVER_SIDE_ENCRYPTION, HeaderValue::from_static("aws:kms"));
req.extensions.insert(PostObjectRequestMarker);
req.headers
.insert(AMZ_SERVER_SIDE_ENCRYPTION, HeaderValue::from_static("aws:kms"));
let envelope = write_envelope(Method::POST, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
async fn execute_put_object_rejects_post_object_sse_kms_key_id_header() { async fn execute_put_object_rejects_post_object_sse_kms_key_id_header() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("test-key".to_string()) key: "test-key".to_owned(),
.build() ..Default::default()
.unwrap(); };
let mut headers = HeaderMap::new();
let mut req = build_request(input, Method::POST); headers.insert(AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID, HeaderValue::from_static("test-kms-key-id"));
req.extensions.insert(PostObjectRequestMarker);
req.headers
.insert(AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID, HeaderValue::from_static("test-kms-key-id"));
let envelope = write_envelope(Method::POST, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
@@ -4928,27 +4915,24 @@ mod tests {
assert_eq!(head.output.dto.sse_customer_algorithm.as_deref(), Some("AES256")); assert_eq!(head.output.dto.sse_customer_algorithm.as_deref(), Some("AES256"));
assert_eq!(head.output.dto.sse_customer_key_md5.as_deref(), Some(key_md5.as_str())); assert_eq!(head.output.dto.sse_customer_key_md5.as_deref(), Some(key_md5.as_str()));
let get_input = GetObjectInput::builder() let get_input = rustfs_gateway_types::dto::GetObjectInput {
.bucket(bucket.clone()) sse_customer_algorithm: Some("AES256".to_owned()),
.key("ledger.csv".to_string()) sse_customer_key: Some(SseCustomerKey::new(encoded_key)),
.sse_customer_algorithm(Some("AES256".to_string())) sse_customer_key_md5: Some(key_md5.clone()),
.sse_customer_key(Some(encoded_key)) ..get_object_input(&bucket, "ledger.csv", None)
.sse_customer_key_md5(Some(key_md5.clone())) };
.build() let get = Box::pin(get_object_gateway(
.expect("SSE-C GET input must build"); &usecase,
let mut get_request = build_request(get_input, Method::GET); get_envelope(read_headers, http::Extensions::new()),
get_request.headers = read_headers; get_input,
let get = Box::pin(crate::app::test_seams::get_object(&usecase, get_request)) ))
.await .await
.expect("matching SSE-C key must authorize GET"); .expect("matching SSE-C key must authorize GET");
assert_eq!(get.output.server_side_encryption, None); assert_eq!(get.output.dto.server_side_encryption, None);
assert_eq!(get.output.sse_customer_algorithm.as_deref(), Some("AES256")); assert_eq!(get.output.dto.sse_customer_algorithm.as_deref(), Some("AES256"));
assert_eq!(get.output.sse_customer_key_md5.as_deref(), Some(key_md5.as_str())); assert_eq!(get.output.dto.sse_customer_key_md5.as_deref(), Some(key_md5.as_str()));
let mut body = get.output.body.expect("SSE-C GET must include the decrypted body"); let body = get.output.body.expect("SSE-C GET must include the decrypted body");
let mut plaintext = Vec::new(); let plaintext = read_get_body(body).await;
while let Some(chunk) = body.next().await {
plaintext.extend_from_slice(&chunk.expect("SSE-C body must decrypt completely"));
}
assert_eq!(plaintext, payload, "header classification must preserve the complete decrypted payload"); assert_eq!(plaintext, payload, "header classification must preserve the complete decrypted payload");
let stored = store let stored = store
@@ -4991,31 +4975,31 @@ mod tests {
crate::app::gating_test_env::durable_quota_test_bucket("ciphertext-replication-early-reject", 4096).await; crate::app::gating_test_env::durable_quota_test_bucket("ciphertext-replication-early-reject", 4096).await;
let body_polled = Arc::new(AtomicBool::new(false)); let body_polled = Arc::new(AtomicBool::new(false));
let body_polled_in_stream = Arc::clone(&body_polled); let body_polled_in_stream = Arc::clone(&body_polled);
let body = StreamingBlob::wrap(futures::stream::once(async move { let body = super::super::native_body::from_io_stream(futures::stream::once(async move {
body_polled_in_stream.store(true, Ordering::Release); body_polled_in_stream.store(true, Ordering::Release);
Ok::<Bytes, std::io::Error>(Bytes::from_static(b"ciphertext")) Ok::<Bytes, std::io::Error>(Bytes::from_static(b"ciphertext"))
})); }));
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket(bucket) bucket,
.key("object".to_string()) key: "object".to_owned(),
.body(Some(body)) body: Some(body),
.content_length(Some(10)) content_length: Some(10),
.build() ..Default::default()
.expect("ciphertext replication PUT input should build"); };
let mut request = build_request(input, Method::PUT); let mut headers = HeaderMap::new();
insert_header(&mut request.headers, SUFFIX_SOURCE_REPLICATION_REQUEST, "true"); insert_header(&mut headers, SUFFIX_SOURCE_REPLICATION_REQUEST, "true");
request headers.insert(rustfs_utils::http::REPLICATION_SSEC_ALGORITHM_HEADER, HeaderValue::from_static("AES256"));
.headers let mut extensions = http::Extensions::new();
.insert(rustfs_utils::http::REPLICATION_SSEC_ALGORITHM_HEADER, HeaderValue::from_static("AES256")); extensions.insert(crate::storage::req_info::ReqInfo {
request.extensions.insert(crate::storage::req_info::ReqInfo {
replication_request_authorized: true, replication_request_authorized: true,
..Default::default() ..Default::default()
}); });
let err = put_owned(&DefaultObjectUsecase::from_global(), request) let envelope = write_envelope(Method::PUT, http::Uri::from_static("/"), headers, extensions);
let err = Box::pin(DefaultObjectUsecase::from_global().execute_put_object_owned(envelope, input))
.await .await
.expect_err("quota-enabled ciphertext replication should fail at ingress"); .expect_err("quota-enabled ciphertext replication should fail at ingress");
assert_eq!(err.code(), &S3ErrorCode::InvalidRequest); assert_eq!(err.code(), &OwnedS3ErrorCode::InvalidRequest);
assert!(!body_polled.load(Ordering::Acquire), "rejected ciphertext body must not be consumed"); assert!(!body_polled.load(Ordering::Acquire), "rejected ciphertext body must not be consumed");
} }
@@ -5669,9 +5653,10 @@ mod tests {
headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true")); headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
let usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let err = Box::pin( let err = Box::pin(usecase.execute_put_object_owned(
usecase.execute_put_object_owned(put_envelope(http::Uri::from_static("/"), headers, http::Extensions::new()), input), write_envelope(Method::PUT, http::Uri::from_static("/"), headers, http::Extensions::new()),
) input,
))
.await .await
.expect_err("an unreadable bucket encryption configuration must refuse the extract upload"); .expect_err("an unreadable bucket encryption configuration must refuse the extract upload");
-8
View File
@@ -135,12 +135,4 @@ impl PutObjectWriteInput {
checksum_crc64nvme: input.checksum_crc64nvme, checksum_crc64nvme: input.checksum_crc64nvme,
} }
} }
/// A test's s3s fixture request as the envelope and input a gateway handler hands the use case.
pub(crate) fn from_test_request(
req: crate::app::storage_api::s3::S3Request<crate::app::storage_api::s3::PutObjectInput>,
) -> (crate::app::RequestEnvelope, Self) {
let envelope = crate::app::RequestEnvelope::from_s3s(&req);
(envelope, Self::from_legacy(req.input, req.trailing_headers))
}
} }
-162
View File
@@ -1,162 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Compatibility conversions between owned Get/Head object facts and s3s DTOs.
//!
//! Retained for `admin/router.rs` (object-lambda), `app/website.rs`, and `app/test_seams` until
//! T4.2 removes the remaining `s3s` dependency from `admin/router.rs`.
#[cfg(test)]
use crate::app::object_usecase::HeadObjectOutputFacts;
use crate::app::object_usecase::{GetObjectBody, GetObjectFields, GetObjectOutputFacts};
use rustfs_gateway_stream::{BoxPayloadStream, PayloadRead, StreamError, StreamErrorKind};
use rustfs_gateway_types::ByteRange;
use rustfs_gateway_types::compat::ConversionError;
use rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::get_object;
#[cfg(test)]
use rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::head_object;
#[cfg(test)]
use s3s::dto::HeadObjectOutput;
use s3s::dto::{ETag, GetObjectInput, GetObjectOutput, Range, StreamingBlob};
use std::pin::Pin;
use std::sync::{Mutex, PoisonError};
use std::task::{Context, Poll};
#[cfg(test)]
impl HeadObjectOutputFacts {
pub(crate) fn into_s3s(self) -> Result<HeadObjectOutput, ConversionError> {
let mut output = head_object::output_to_s3s(self.dto)?;
output.e_tag = self.etag.map(|etag| {
if etag.weak {
ETag::Weak(etag.opaque)
} else {
ETag::Strong(etag.opaque)
}
});
Ok(output)
}
}
impl GetObjectFields {
pub(crate) fn from_s3s(input: GetObjectInput) -> Self {
Self {
bucket: input.bucket,
key: input.key,
version_id: input.version_id,
part_number: input.part_number,
range: input.range.map(|range| match range {
Range::Int { first, last: Some(last) } => ByteRange::FromTo { first, last },
Range::Int { first, last: None } => ByteRange::From { first },
Range::Suffix { length } => ByteRange::Suffix { length },
}),
sse_customer_key: input.sse_customer_key,
sse_customer_key_md5: input.sse_customer_key_md5,
}
}
}
impl GetObjectOutputFacts {
pub(crate) fn into_s3s(self) -> Result<GetObjectOutput, ConversionError> {
let mut output = get_object::output_to_s3s(self.dto)?;
output.e_tag = self.etag.map(|etag| {
if etag.weak {
ETag::Weak(etag.opaque)
} else {
ETag::Strong(etag.opaque)
}
});
output.body = self.body.map(GetObjectBody::into_s3s);
Ok(output)
}
}
impl GetObjectBody {
pub(crate) fn into_s3s(self) -> StreamingBlob {
match self {
Self::Bytes(bytes) => StreamingBlob::from_bytes(bytes),
Self::Stream(payload) => StreamingBlob::new(LegacyGetStream {
payload: Mutex::new(payload),
done: false,
}),
}
}
}
// The legacy body requires Sync. Polling uses exclusive access, not a mutex lock.
struct LegacyGetStream {
payload: Mutex<BoxPayloadStream>,
done: bool,
}
impl futures::Stream for LegacyGetStream {
type Item = Result<bytes::Bytes, Box<dyn std::error::Error + Send + Sync>>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
if this.done {
return Poll::Ready(None);
}
let event = std::task::ready!(
this.payload
.get_mut()
.unwrap_or_else(PoisonError::into_inner)
.as_mut()
.poll_read(cx)
);
Poll::Ready(match event {
Ok(PayloadRead::Chunk(bytes)) => Some(Ok(bytes)),
Ok(PayloadRead::Eof { trailers }) => {
this.done = true;
if trailers.is_empty() {
None
} else {
Some(Err(Box::new(ConversionError {
field: "body",
reason: "legacy GetObject cannot encode response trailers",
})))
}
}
Err(error) => {
this.done = true;
Some(Err(legacy_get_body_error(error)))
}
})
}
}
fn legacy_get_body_error(error: StreamError) -> Box<dyn std::error::Error + Send + Sync> {
if matches!(error.kind(), StreamErrorKind::Upstream(_)) {
let StreamErrorKind::Upstream(source) = error.into_kind() else {
unreachable!("the owned error kind was checked above")
};
source
} else {
Box::new(error)
}
}
impl s3s::stream::ByteStream for LegacyGetStream {
fn remaining_length(&self) -> s3s::stream::RemainingLength {
match self
.payload
.lock()
.unwrap_or_else(PoisonError::into_inner)
.len_hint()
.and_then(|length| usize::try_from(length).ok())
{
Some(length) => s3s::stream::RemainingLength::new_exact(length),
None => s3s::stream::RemainingLength::unknown(),
}
}
}
+1 -1
View File
@@ -20,9 +20,9 @@ use crate::app::storage_api::s3::dto::ObjectLockRetentionMode;
use crate::app::storage_api::s3::dto::{ChecksumAlgorithm, ServerSideEncryption, Timestamp, TimestampFormat}; use crate::app::storage_api::s3::dto::{ChecksumAlgorithm, ServerSideEncryption, Timestamp, TimestampFormat};
#[cfg(test)] #[cfg(test)]
use crate::app::storage_api::s3::dto::{ObjectLockLegalHoldStatus, ObjectLockMode}; use crate::app::storage_api::s3::dto::{ObjectLockLegalHoldStatus, ObjectLockMode};
use crate::app::storage_api::s3::header::{X_AMZ_DELETE_MARKER, X_AMZ_VERSION_ID};
use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Result, StdError, s3_error}; use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Result, StdError, s3_error};
use crate::on_demand_migration::{OdmStateError, PolicyConfig, SourceErrorPolicy, SourceHead}; use crate::on_demand_migration::{OdmStateError, PolicyConfig, SourceErrorPolicy, SourceHead};
use rustfs_s3_client::constants::{X_AMZ_DELETE_MARKER, X_AMZ_VERSION_ID};
pub(super) const RUSTFS_EXPECTED_CURRENT_VERSION_ID: &str = "x-rustfs-expected-current-version-id"; pub(super) const RUSTFS_EXPECTED_CURRENT_VERSION_ID: &str = "x-rustfs-expected-current-version-id";
+1 -1
View File
@@ -24,11 +24,11 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock}; use std::sync::{Arc, OnceLock};
use std::time::Duration; use std::time::Duration;
use super::super::storage_api::s3::{S3Error, S3ErrorCode, S3Result};
use bytes::Bytes; use bytes::Bytes;
use md5::Digest as _; use md5::Digest as _;
use md5::Md5; use md5::Md5;
use moka::{future::Cache as AsyncCache, sync::Cache as SyncCache}; use moka::{future::Cache as AsyncCache, sync::Cache as SyncCache};
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result};
use time::OffsetDateTime; use time::OffsetDateTime;
use tracing::debug; use tracing::debug;
+8 -17
View File
@@ -61,21 +61,22 @@ pub(crate) mod s3 {
pub(crate) use s3s::auth::Credentials; pub(crate) use s3s::auth::Credentials;
pub(crate) use s3s::dto; pub(crate) use s3s::dto;
#[cfg(test)] #[cfg(test)]
pub(crate) use s3s::dto::PutObjectInput;
#[cfg(test)]
pub(crate) use s3s::dto::{ pub(crate) use s3s::dto::{
BucketLocationConstraint, CreateBucketConfiguration, CreateBucketInput, CreateMultipartUploadInput, DeleteObjectInput, BucketLocationConstraint, CreateBucketConfiguration, CreateBucketInput, CreateMultipartUploadInput, DeleteObjectInput,
ObjectLockRetention, ObjectLockRetention,
}; };
#[cfg(test)] #[cfg(test)]
pub(crate) use s3s::dto::{GetObjectInput, ListObjectsV2Input, ListObjectsV2Output};
#[cfg(test)]
pub(crate) use s3s::dto::{GetObjectOutput, PutObjectInput};
#[cfg(test)]
pub(crate) use s3s::dto::{ListObjectsInput, StreamingBlob}; pub(crate) use s3s::dto::{ListObjectsInput, StreamingBlob};
pub(crate) use s3s::header; #[cfg(test)]
pub(crate) use s3s::dto::{ListObjectsV2Input, ListObjectsV2Output};
pub(crate) use s3s::s3_error; pub(crate) use s3s::s3_error;
#[cfg(test)]
pub(crate) use s3s::stream; pub(crate) use s3s::stream;
#[cfg(test)] #[cfg(test)]
pub(crate) use s3s::stream::upload_stream::UploadStreamError; pub(crate) use s3s::stream::upload_stream::UploadStreamError;
#[cfg(test)]
pub(crate) use s3s::xml; pub(crate) use s3s::xml;
#[cfg(test)] #[cfg(test)]
pub(crate) use s3s::xml::{Serialize as XmlSerialize, Serializer as XmlSerializer}; pub(crate) use s3s::xml::{Serialize as XmlSerialize, Serializer as XmlSerializer};
@@ -1663,12 +1664,6 @@ pub(crate) mod helper {
}; };
} }
pub(crate) mod object_utils {
#[cfg(test)]
pub(crate) use crate::storage::storage_api::to_s3s_etag;
pub(crate) use crate::storage::storage_api::to_s3s_xml_etag;
}
pub(crate) mod io { pub(crate) mod io {
#[cfg(test)] #[cfg(test)]
pub(crate) use crate::storage::storage_api::{DecryptReader, EncryptReader, HardLimitReader, boxed_reader}; pub(crate) use crate::storage::storage_api::{DecryptReader, EncryptReader, HardLimitReader, boxed_reader};
@@ -1778,7 +1773,7 @@ pub(crate) mod bucket_usecase {
} }
} }
pub(crate) use super::{access, bucket, error, helper, object_utils, request_context, s3, s3_api, sse}; pub(crate) use super::{access, bucket, error, helper, request_context, s3, s3_api, sse};
pub(crate) use crate::storage::storage_api::{ pub(crate) use crate::storage::storage_api::{
ECStore, StorageObjectInfo, StorageObjectOptions, get_validated_store, validate_list_object_unordered_with_delimiter, ECStore, StorageObjectInfo, StorageObjectOptions, get_validated_store, validate_list_object_unordered_with_delimiter,
validate_website_configuration, validate_website_configuration,
@@ -1844,8 +1839,6 @@ pub(crate) mod object_usecase {
} }
} }
#[cfg(test)]
pub(crate) use super::object_utils;
pub(crate) use super::{ pub(crate) use super::{
access, bucket, compression, concurrency, data_usage, deadlock_detector, error, head_prefix, helper, io, options, access, bucket, compression, concurrency, data_usage, deadlock_detector, error, head_prefix, helper, io, options,
request_context, s3_api, set_disk, sse, storage_class, timeout_wrapper, request_context, s3_api, set_disk, sse, storage_class, timeout_wrapper,
@@ -1910,8 +1903,6 @@ pub(crate) mod multipart_usecase {
} }
} }
#[cfg(test)]
pub(crate) use super::object_utils;
pub(crate) use super::{ pub(crate) use super::{
access, bucket, compression, data_usage, error, helper, io, options, request_context, s3_api, set_disk, sse, access, bucket, compression, data_usage, error, helper, io, options, request_context, s3_api, set_disk, sse,
}; };
@@ -2012,7 +2003,7 @@ pub(crate) mod test {
RecordingKmsKeyAuthorizer, TestAuthorizationHooks, sse_kms_object_metadata, RecordingKmsKeyAuthorizer, TestAuthorizationHooks, sse_kms_object_metadata,
}; };
} }
pub(crate) use super::{bucket, object_utils, runtime}; pub(crate) use super::{bucket, runtime};
pub(crate) mod data_usage { pub(crate) mod data_usage {
pub(crate) use super::super::data_usage::*; pub(crate) use super::super::data_usage::*;
} }
+3 -3
View File
@@ -18,8 +18,8 @@ use crate::app::storage_api::bucket_usecase::access::{
use crate::app::storage_api::bucket_usecase::contract::list::{ListObjectVersionsInfo, ListObjectsV2Info, ListOperations as _}; use crate::app::storage_api::bucket_usecase::contract::list::{ListObjectVersionsInfo, ListObjectsV2Info, ListOperations as _};
use crate::app::storage_api::bucket_usecase::{ECStore, StorageObjectInfo as ObjectInfo}; use crate::app::storage_api::bucket_usecase::{ECStore, StorageObjectInfo as ObjectInfo};
use crate::app::storage_api::multipart_usecase::contract::multipart::{ListMultipartsInfo, MultipartInfo}; use crate::app::storage_api::multipart_usecase::contract::multipart::{ListMultipartsInfo, MultipartInfo};
use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Result};
use crate::error::ApiError; use crate::error::ApiError;
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result};
use std::collections::HashSet; use std::collections::HashSet;
use std::sync::Arc; use std::sync::Arc;
use uuid::Uuid; use uuid::Uuid;
@@ -70,12 +70,12 @@ pub(crate) struct ListMultipartUploadsRequest<'a> {
fn table_list_scan_limit_error() -> S3Error { fn table_list_scan_limit_error() -> S3Error {
S3Error::with_message( S3Error::with_message(
S3ErrorCode::SlowDown, S3ErrorCode::SlowDown,
"Table listing exceeded the protected scan limit; retry with a narrower prefix".to_string(), "Table listing exceeded the protected scan limit; retry with a narrower prefix",
) )
} }
fn invalid_table_list_cursor() -> S3Error { fn invalid_table_list_cursor() -> S3Error {
S3Error::with_message(S3ErrorCode::InvalidArgument, "Invalid table listing continuation token".to_string()) S3Error::with_message(S3ErrorCode::InvalidArgument, "Invalid table listing continuation token")
} }
fn list_objects_v2_operation(incl_deleted: bool) -> &'static str { fn list_objects_v2_operation(incl_deleted: bool) -> &'static str {
+42 -40
View File
@@ -12,55 +12,57 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use crate::app::object::GetObjectBody;
use crate::app::object_usecase::DefaultObjectUsecase; use crate::app::object_usecase::DefaultObjectUsecase;
use crate::app::storage_api::s3::{GetObjectInput, GetObjectOutput, S3Request, S3Response, S3Result};
/// Calls `DefaultObjectUsecase::execute_get_object` with today's arguments. pub(crate) fn get_envelope(headers: http::HeaderMap, extensions: http::Extensions) -> crate::app::RequestEnvelope {
/// crate::app::RequestEnvelope::from_parts(
/// Owned by the GetObject batch (C). Tests outside that batch's files call this seam instead of the use-case method;
/// when batch C changes the use-case signature it changes only this body.
pub(crate) async fn get_object(
usecase: &DefaultObjectUsecase,
req: S3Request<GetObjectInput>,
) -> S3Result<S3Response<GetObjectOutput>> {
use crate::app::object_usecase::GetObjectFields;
use crate::app::{Answered, RequestEnvelope};
rustfs_io_metrics::record_s3_op(rustfs_s3_ops::S3Operation::GetObject);
let envelope = RequestEnvelope::from_s3s(&req);
let Answered { output, status, headers } = get_object_fields(usecase, envelope, GetObjectFields::from_s3s(req.input)).await?;
let mut response = S3Response::new(output.into_s3s().map_err(crate::app::dto_values::seam_error)?);
response.status = status;
response.headers = headers;
Ok(response)
}
/// [`get_object`] for a fixture that sets nothing but `GET /`.
///
/// `build_request` leaves the URI, headers, and extensions empty, so this envelope matches that request.
#[cfg(test)]
pub(crate) async fn get_object_method_only(
usecase: &DefaultObjectUsecase,
input: GetObjectInput,
) -> S3Result<S3Response<GetObjectOutput>> {
use crate::app::object_usecase::GetObjectFields;
use crate::app::{Answered, RequestEnvelope};
rustfs_io_metrics::record_s3_op(rustfs_s3_ops::S3Operation::GetObject);
let envelope = RequestEnvelope::from_parts(
crate::app::RequestHead { crate::app::RequestHead {
method: http::Method::GET, method: http::Method::GET,
uri: http::Uri::from_static("/"), uri: http::Uri::from_static("/"),
headers: http::HeaderMap::new(), headers,
credentials: None, credentials: None,
region: None, region: None,
service: None, service: None,
}, },
http::Extensions::new(), extensions,
); )
let Answered { output, status, headers } = get_object_fields(usecase, envelope, GetObjectFields::from_s3s(input)).await?; }
let mut response = S3Response::new(output.into_s3s().map_err(crate::app::dto_values::seam_error)?);
response.status = status; pub(crate) fn get_object_input(bucket: &str, key: &str, version_id: Option<String>) -> rustfs_gateway_types::dto::GetObjectInput {
response.headers = headers; rustfs_gateway_types::dto::GetObjectInput {
Ok(response) bucket: rustfs_gateway_types::BucketName::new(bucket).expect("test bucket name"),
key: rustfs_gateway_types::ObjectKey::new(key).expect("test object key"),
version_id,
..Default::default()
}
}
pub(crate) async fn get_object_gateway(
usecase: &DefaultObjectUsecase,
envelope: crate::app::RequestEnvelope,
input: rustfs_gateway_types::dto::GetObjectInput,
) -> rustfs_s3_types::S3Result<crate::app::Answered<crate::app::object_usecase::GetObjectOutputFacts>> {
rustfs_io_metrics::record_s3_op(rustfs_s3_ops::S3Operation::GetObject);
get_object_fields(usecase, envelope, input.into()).await
}
pub(crate) fn get_http_body(body: GetObjectBody) -> rustfs_gateway_stream::Body {
use rustfs_gateway_stream::Body;
match body {
GetObjectBody::Bytes(bytes) => Body::from_bytes(bytes),
GetObjectBody::Stream(stream) => Body::from_stream(stream).expect("valid GET stream"),
}
}
/// Reads a successful GET body to completion where the caller verifies its bytes.
pub(crate) async fn read_get_body(body: GetObjectBody) -> bytes::Bytes {
use http_body_util::BodyExt;
let collected = get_http_body(body).collect().await.expect("GET body must be readable");
assert!(collected.trailers().is_none(), "unexpected GET response trailers");
collected.to_bytes()
} }
/// Calls `DefaultObjectUsecase::execute_get_object_fields` with owned inputs. /// Calls `DefaultObjectUsecase::execute_get_object_fields` with owned inputs.
+3 -3
View File
@@ -23,9 +23,9 @@ mod head_object;
mod list_objects_v2; mod list_objects_v2;
mod put_object; mod put_object;
#[cfg(test)] pub(crate) use get_object::{
pub(crate) use get_object::get_object_method_only; get_envelope, get_http_body, get_object_fields, get_object_gateway, get_object_input, read_get_body,
pub(crate) use get_object::{get_object, get_object_fields}; };
pub(crate) use head_object::{head_envelope, head_object_fields, head_object_gateway, head_object_input}; pub(crate) use head_object::{head_envelope, head_object_fields, head_object_gateway, head_object_input};
#[cfg(test)] #[cfg(test)]
pub(crate) use list_objects_v2::list_objects_v2_method_only; pub(crate) use list_objects_v2::list_objects_v2_method_only;
+99 -117
View File
@@ -25,6 +25,7 @@ use rustfs_iam::sys::{
}; };
use rustfs_policy::policy::action::Action; use rustfs_policy::policy::action::Action;
use rustfs_policy::policy::{ClaimLookup, get_claim_case_insensitive}; use rustfs_policy::policy::{ClaimLookup, get_claim_case_insensitive};
use rustfs_s3_types::{S3Result as OwnedResult, s3_error as owned_error};
use rustfs_trusted_proxies::ClientInfo; use rustfs_trusted_proxies::ClientInfo;
use rustfs_utils::MaskedAccessKey; use rustfs_utils::MaskedAccessKey;
use rustfs_utils::http::metadata_compat::starts_with_ignore_ascii_case; use rustfs_utils::http::metadata_compat::starts_with_ignore_ascii_case;
@@ -33,7 +34,6 @@ use s3s::S3ErrorCode;
use s3s::S3Result; use s3s::S3Result;
use s3s::auth::S3Auth; use s3s::auth::S3Auth;
use s3s::auth::SecretKey; use s3s::auth::SecretKey;
use s3s::auth::SimpleAuth;
use s3s::s3_error; use s3s::s3_error;
use serde_json::Value; use serde_json::Value;
use std::collections::HashMap; use std::collections::HashMap;
@@ -131,33 +131,18 @@ pub enum AuthType {
StreamingUnsignedTrailer, StreamingUnsignedTrailer,
} }
#[derive(Clone)]
pub struct IAMAuth { pub struct IAMAuth {
simple_auth: SimpleAuth,
access_key: String, access_key: String,
secret_key: SecretKey, secret_key: SecretKey,
server_ctx: Option<std::sync::Arc<ServerContextSlot>>, server_ctx: Option<std::sync::Arc<ServerContextSlot>>,
} }
impl Clone for IAMAuth {
fn clone(&self) -> Self {
Self {
simple_auth: SimpleAuth::from_single(self.access_key.clone(), self.secret_key.clone()),
access_key: self.access_key.clone(),
secret_key: self.secret_key.clone(),
server_ctx: self.server_ctx.clone(),
}
}
}
impl IAMAuth { impl IAMAuth {
pub fn new(ak: impl Into<String>, sk: impl Into<SecretKey>) -> Self { pub fn new(ak: impl Into<String>, sk: impl Into<SecretKey>) -> Self {
let access_key = ak.into();
let secret_key = sk.into();
let simple_auth = SimpleAuth::from_single(access_key.clone(), secret_key.clone());
Self { Self {
simple_auth, access_key: ak.into(),
access_key, secret_key: sk.into(),
secret_key,
server_ctx: None, server_ctx: None,
} }
} }
@@ -206,10 +191,6 @@ impl S3Auth for IAMAuth {
return Ok(self.secret_key.clone()); return Ok(self.secret_key.clone());
} }
if let Ok(key) = self.simple_auth.get_secret_key(access_key).await {
return Ok(key);
}
let iam_store = match &self.server_ctx { let iam_store = match &self.server_ctx {
Some(server_ctx) => server_ctx Some(server_ctx) => server_ctx
.installed_app_context() .installed_app_context()
@@ -1014,8 +995,8 @@ const SIGV4_UNSIGNED_ENVELOPE_HEADERS: &[&str] = &[
/// ///
/// Every signed-header list the request carries must cover every `x-amz-*` /// Every signed-header list the request carries must cover every `x-amz-*`
/// header, so an `Authorization` header can never widen a presigned URL and a /// header, so an `Authorization` header can never widen a presigned URL and a
/// query can never widen a header signature. The header is parsed with the /// query can never widen a header signature. The gateway reads the verifier's
/// verifier's own parser so both sides read the same `SignedHeaders` list, and /// header grammar so both sides see the same `SignedHeaders` list, and
/// the algorithm token is pinned because the verifier accepts any token there. /// the algorithm token is pinned because the verifier accepts any token there.
/// A header the parser rejects never authenticates as SigV4 upstream, but one /// A header the parser rejects never authenticates as SigV4 upstream, but one
/// that claims the SigV4 algorithm still fails closed here. SigV2 signs every /// that claims the SigV4 algorithm still fails closed here. SigV2 signs every
@@ -1027,17 +1008,17 @@ pub(crate) fn reject_unsigned_amz_headers_on_sigv4_request(header: &HeaderMap, q
let Ok(value) = value.to_str() else { let Ok(value) = value.to_str() else {
continue; continue;
}; };
let authorization = match s3s_sigv4::AuthorizationV4::parse(value) { let authorization = match rustfs_gateway::sig::SigV4HeaderCoverage::parse(value) {
Ok(authorization) => authorization, Some(authorization) => authorization,
Err(_) if value.starts_with(SIGN_V4_ALGORITHM) => { None if value.starts_with(SIGN_V4_ALGORITHM) => {
return Err(S3Error::with_message( return Err(S3Error::with_message(
S3ErrorCode::AccessDenied, S3ErrorCode::AccessDenied,
"Invalid SigV4 authorization header".to_owned(), "Invalid SigV4 authorization header".to_owned(),
)); ));
} }
Err(_) => continue, None => continue,
}; };
if authorization.algorithm != SIGN_V4_ALGORITHM { if authorization.algorithm() != SIGN_V4_ALGORITHM {
warn!( warn!(
event = EVENT_SIGV4_UNSUPPORTED_ALGORITHM, event = EVENT_SIGV4_UNSUPPORTED_ALGORITHM,
component = LOG_COMPONENT_AUTH, component = LOG_COMPONENT_AUTH,
@@ -1057,10 +1038,7 @@ pub(crate) fn reject_unsigned_amz_headers_on_sigv4_request(header: &HeaderMap, q
if !name.starts_with("x-amz-") if !name.starts_with("x-amz-")
|| SIGV4_UNSIGNED_ENVELOPE_HEADERS.contains(&name) || SIGV4_UNSIGNED_ENVELOPE_HEADERS.contains(&name)
|| PRESIGNED_UNSIGNED_AMZ_HEADER_ALLOWLIST.contains(&name) || PRESIGNED_UNSIGNED_AMZ_HEADER_ALLOWLIST.contains(&name)
|| authorization || authorization.covers_header(name)
.signed_headers
.iter()
.any(|signed_name| signed_name.eq_ignore_ascii_case(name))
{ {
continue; continue;
} }
@@ -1207,7 +1185,7 @@ pub(crate) fn parse_presigned_put_max_content_length(
header: &HeaderMap, header: &HeaderMap,
query: Option<&str>, query: Option<&str>,
verified_presigned: bool, verified_presigned: bool,
) -> S3Result<Option<u64>> { ) -> OwnedResult<Option<u64>> {
let Some(query) = query else { let Some(query) = query else {
return Ok(None); return Ok(None);
}; };
@@ -1218,16 +1196,13 @@ pub(crate) fn parse_presigned_put_max_content_length(
decoded_query.push((name.to_string(), candidate.to_string())); decoded_query.push((name.to_string(), candidate.to_string()));
if name == RUSTFS_MAX_CONTENT_LENGTH_QUERY { if name == RUSTFS_MAX_CONTENT_LENGTH_QUERY {
if value.is_some() { if value.is_some() {
return Err(S3Error::with_message( return Err(owned_error!(InvalidRequest, "{RUSTFS_MAX_CONTENT_LENGTH_QUERY} must appear exactly once"));
S3ErrorCode::InvalidRequest,
format!("{RUSTFS_MAX_CONTENT_LENGTH_QUERY} must appear exactly once"),
));
} }
value = Some(candidate.into_owned()); value = Some(candidate.into_owned());
} else if name.eq_ignore_ascii_case(RUSTFS_MAX_CONTENT_LENGTH_QUERY) { } else if name.eq_ignore_ascii_case(RUSTFS_MAX_CONTENT_LENGTH_QUERY) {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("query parameter name must be exactly {RUSTFS_MAX_CONTENT_LENGTH_QUERY}"), "query parameter name must be exactly {RUSTFS_MAX_CONTENT_LENGTH_QUERY}"
)); ));
} }
} }
@@ -1258,18 +1233,15 @@ pub(crate) fn parse_presigned_put_max_content_length(
|| !is_complete_sigv4_query || !is_complete_sigv4_query
|| !matches!(get_request_auth_type_with_query(header, Some(query)), AuthType::Presigned) || !matches!(get_request_auth_type_with_query(header, Some(query)), AuthType::Presigned)
{ {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_CONTENT_LENGTH_QUERY} requires a SigV4 presigned request"), "{RUSTFS_MAX_CONTENT_LENGTH_QUERY} requires a SigV4 presigned request"
)); ));
} }
let limit = value.parse::<u64>().map_err(|_| { let limit = value
S3Error::with_message( .parse::<u64>()
S3ErrorCode::InvalidRequest, .map_err(|_| owned_error!(InvalidRequest, "{RUSTFS_MAX_CONTENT_LENGTH_QUERY} must be a non-negative 64-bit integer"))?;
format!("{RUSTFS_MAX_CONTENT_LENGTH_QUERY} must be a non-negative 64-bit integer"),
)
})?;
Ok(Some(limit)) Ok(Some(limit))
} }
@@ -1280,11 +1252,11 @@ pub(crate) fn reject_presigned_put_max_content_length_for_other_operation(
header: &HeaderMap, header: &HeaderMap,
query: Option<&str>, query: Option<&str>,
verified_presigned: bool, verified_presigned: bool,
) -> S3Result<()> { ) -> OwnedResult<()> {
if parse_presigned_put_max_content_length(header, query, verified_presigned)?.is_some() { if parse_presigned_put_max_content_length(header, query, verified_presigned)?.is_some() {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_CONTENT_LENGTH_QUERY} is only supported for presigned PutObject"), "{RUSTFS_MAX_CONTENT_LENGTH_QUERY} is only supported for presigned PutObject"
)); ));
} }
Ok(()) Ok(())
@@ -1298,7 +1270,7 @@ pub(crate) fn parse_presigned_multipart_max_total_object_size(
header: &HeaderMap, header: &HeaderMap,
query: Option<&str>, query: Option<&str>,
verified_sigv4: bool, verified_sigv4: bool,
) -> S3Result<Option<u64>> { ) -> OwnedResult<Option<u64>> {
let Some(query) = query else { let Some(query) = query else {
return Ok(None); return Ok(None);
}; };
@@ -1309,16 +1281,16 @@ pub(crate) fn parse_presigned_multipart_max_total_object_size(
decoded_query.push((name.to_string(), candidate.to_string())); decoded_query.push((name.to_string(), candidate.to_string()));
if name == RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY { if name == RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY {
if value.is_some() { if value.is_some() {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} must appear exactly once"), "{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} must appear exactly once"
)); ));
} }
value = Some(candidate.into_owned()); value = Some(candidate.into_owned());
} else if name.eq_ignore_ascii_case(RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY) { } else if name.eq_ignore_ascii_case(RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY) {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("query parameter name must be exactly {RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY}"), "query parameter name must be exactly {RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY}"
)); ));
} }
} }
@@ -1348,16 +1320,16 @@ pub(crate) fn parse_presigned_multipart_max_total_object_size(
let authenticated = verified_sigv4 && (is_header_signed || (is_presigned && complete_presigned_query)); let authenticated = verified_sigv4 && (is_header_signed || (is_presigned && complete_presigned_query));
if !authenticated { if !authenticated {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} requires a verified SigV4 request"), "{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} requires a verified SigV4 request"
)); ));
} }
value.parse::<u64>().map(Some).map_err(|_| { value.parse::<u64>().map(Some).map_err(|_| {
S3Error::with_message( owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} must be a non-negative 64-bit integer"), "{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} must be a non-negative 64-bit integer"
) )
}) })
} }
@@ -1366,11 +1338,11 @@ pub(crate) fn reject_presigned_multipart_max_total_object_size_for_other_operati
header: &HeaderMap, header: &HeaderMap,
query: Option<&str>, query: Option<&str>,
verified_sigv4: bool, verified_sigv4: bool,
) -> S3Result<()> { ) -> OwnedResult<()> {
if parse_presigned_multipart_max_total_object_size(header, query, verified_sigv4)?.is_some() { if parse_presigned_multipart_max_total_object_size(header, query, verified_sigv4)?.is_some() {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} is only supported for CreateMultipartUpload"), "{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} is only supported for CreateMultipartUpload"
)); ));
} }
Ok(()) Ok(())
@@ -1544,8 +1516,8 @@ mod tests {
let iam_auth = IAMAuth::new("test-ak", SecretKey::from("test-sk")); let iam_auth = IAMAuth::new("test-ak", SecretKey::from("test-sk"));
let cloned = iam_auth.clone(); let cloned = iam_auth.clone();
let secret = cloned.get_secret_key("test-ak").await; let secret = cloned.get_secret_key("test-ak").await.expect("cloned root credentials");
assert!(secret.is_ok()); assert_eq!(secret.expose(), "test-sk");
} }
#[tokio::test] #[tokio::test]
@@ -2446,6 +2418,12 @@ mod tests {
assert_eq!(result, Some("value=with=equals")); assert_eq!(result, Some("value=with=equals"));
} }
fn assert_invalid_capability(error: rustfs_s3_types::S3Error, message: &str) {
assert_eq!(error.code(), &rustfs_s3_types::S3ErrorCode::InvalidRequest);
assert_eq!(error.status_code(), Some(http::StatusCode::BAD_REQUEST));
assert_eq!(error.message(), Some(message));
}
#[test] #[test]
fn presigned_put_max_content_length_requires_exactly_one_signed_query_value() { fn presigned_put_max_content_length_requires_exactly_one_signed_query_value() {
let headers = HeaderMap::new(); let headers = HeaderMap::new();
@@ -2464,26 +2442,25 @@ mod tests {
); );
let duplicate = format!("{query}&x-rustfs-max-content-length=1"); let duplicate = format!("{query}&x-rustfs-max-content-length=1");
assert_eq!( assert_invalid_capability(
parse_presigned_put_max_content_length(&headers, Some(&duplicate), true) parse_presigned_put_max_content_length(&headers, Some(&duplicate), true).unwrap_err(),
.unwrap_err() "x-rustfs-max-content-length must appear exactly once",
.code(),
&S3ErrorCode::InvalidRequest
); );
let wrong_case = format!("{signed_prefix}&X-RustFS-Max-Content-Length=1"); let wrong_case = format!("{signed_prefix}&X-RustFS-Max-Content-Length=1");
assert_eq!( assert_invalid_capability(
parse_presigned_put_max_content_length(&headers, Some(&wrong_case), true) parse_presigned_put_max_content_length(&headers, Some(&wrong_case), true).unwrap_err(),
.unwrap_err() "query parameter name must be exactly x-rustfs-max-content-length",
.code(),
&S3ErrorCode::InvalidRequest
); );
assert_eq!( assert_invalid_capability(
reject_presigned_put_max_content_length_for_other_operation(&headers, Some(&query), true) reject_presigned_put_max_content_length_for_other_operation(&headers, Some(&query), true).unwrap_err(),
.unwrap_err() "x-rustfs-max-content-length is only supported for presigned PutObject",
.code(), );
&S3ErrorCode::InvalidRequest let overflow = format!("{signed_prefix}&x-rustfs-max-content-length=18446744073709551616");
assert_invalid_capability(
parse_presigned_put_max_content_length(&headers, Some(&overflow), true).unwrap_err(),
"x-rustfs-max-content-length must be a non-negative 64-bit integer",
); );
} }
@@ -2752,11 +2729,9 @@ mod tests {
fn presigned_put_max_content_length_rejects_unsigned_or_invalid_values() { fn presigned_put_max_content_length_rejects_unsigned_or_invalid_values() {
let headers = HeaderMap::new(); let headers = HeaderMap::new();
let forged = "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=test/credential&X-Amz-Signature=fake&x-rustfs-max-content-length=1"; let forged = "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=test/credential&X-Amz-Signature=fake&x-rustfs-max-content-length=1";
assert_eq!( assert_invalid_capability(
parse_presigned_put_max_content_length(&headers, Some(forged), false) parse_presigned_put_max_content_length(&headers, Some(forged), false).unwrap_err(),
.unwrap_err() "x-rustfs-max-content-length requires a SigV4 presigned request",
.code(),
&S3ErrorCode::InvalidRequest
); );
for query in [ for query in [
"x-rustfs-max-content-length=1", "x-rustfs-max-content-length=1",
@@ -2764,7 +2739,7 @@ mod tests {
"X-Amz-Credential=test/credential&x-rustfs-max-content-length=18446744073709551616", "X-Amz-Credential=test/credential&x-rustfs-max-content-length=18446744073709551616",
] { ] {
let error = parse_presigned_put_max_content_length(&headers, Some(query), true).unwrap_err(); let error = parse_presigned_put_max_content_length(&headers, Some(query), true).unwrap_err();
assert_eq!(error.code(), &S3ErrorCode::InvalidRequest); assert_invalid_capability(error, "x-rustfs-max-content-length requires a SigV4 presigned request");
} }
} }
@@ -2778,11 +2753,14 @@ mod tests {
parse_presigned_multipart_max_total_object_size(&headers, Some(&query), true).unwrap(), parse_presigned_multipart_max_total_object_size(&headers, Some(&query), true).unwrap(),
Some(104_857_600) Some(104_857_600)
); );
assert_eq!( assert_invalid_capability(
reject_presigned_multipart_max_total_object_size_for_other_operation(&headers, Some(&query), true) reject_presigned_multipart_max_total_object_size_for_other_operation(&headers, Some(&query), true).unwrap_err(),
.unwrap_err() "x-rustfs-max-total-object-size is only supported for CreateMultipartUpload",
.code(), );
&S3ErrorCode::InvalidRequest let overflow = format!("{signed_prefix}&x-rustfs-max-total-object-size=18446744073709551616");
assert_invalid_capability(
parse_presigned_multipart_max_total_object_size(&headers, Some(&overflow), true).unwrap_err(),
"x-rustfs-max-total-object-size must be a non-negative 64-bit integer",
); );
} }
@@ -2790,27 +2768,31 @@ mod tests {
fn multipart_max_total_object_size_rejects_tampering_and_invalid_values() { fn multipart_max_total_object_size_rejects_tampering_and_invalid_values() {
let headers = HeaderMap::new(); let headers = HeaderMap::new();
let signed_prefix = "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=test/20260827/us-east-1/s3/aws4_request&X-Amz-Signature=signature"; let signed_prefix = "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=test/20260827/us-east-1/s3/aws4_request&X-Amz-Signature=signature";
for query in [ let auth_message = "x-rustfs-max-total-object-size requires a verified SigV4 request";
"x-rustfs-max-total-object-size=1", for (query, message) in [
"X-RustFS-Max-Total-Object-Size=1", ("x-rustfs-max-total-object-size=1", auth_message),
"X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=1&x-rustfs-max-total-object-size=2", (
"X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=-1", "X-RustFS-Max-Total-Object-Size=1",
"X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=18446744073709551616", "query parameter name must be exactly x-rustfs-max-total-object-size",
),
(
"X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=1&x-rustfs-max-total-object-size=2",
"x-rustfs-max-total-object-size must appear exactly once",
),
("X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=-1", auth_message),
(
"X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=18446744073709551616",
auth_message,
),
] { ] {
assert_eq!( let error = parse_presigned_multipart_max_total_object_size(&headers, Some(query), true).unwrap_err();
parse_presigned_multipart_max_total_object_size(&headers, Some(query), true) assert_invalid_capability(error, message);
.unwrap_err()
.code(),
&S3ErrorCode::InvalidRequest
);
} }
let forged = format!("{signed_prefix}&x-rustfs-max-total-object-size=1"); let forged = format!("{signed_prefix}&x-rustfs-max-total-object-size=1");
assert_eq!( assert_invalid_capability(
parse_presigned_multipart_max_total_object_size(&headers, Some(&forged), false) parse_presigned_multipart_max_total_object_size(&headers, Some(&forged), false).unwrap_err(),
.unwrap_err() "x-rustfs-max-total-object-size requires a verified SigV4 request",
.code(),
&S3ErrorCode::InvalidRequest
); );
} }
+33 -7
View File
@@ -1609,6 +1609,8 @@ mod tests {
#[test] #[test]
fn protocol_mainflow_retention_timestamp_matches_legacy_precision() { fn protocol_mainflow_retention_timestamp_matches_legacy_precision() {
use crate::app::object_usecase::{GetObjectOutputFacts, HeadObjectOutputFacts}; use crate::app::object_usecase::{GetObjectOutputFacts, HeadObjectOutputFacts};
use gateway_s3s_compat::generated::ops::{get_object, head_object};
let instant = rustfs_gateway_types::Timestamp::from_secs_nanos(1_700_000_000, 123_456_789).expect("test timestamp"); let instant = rustfs_gateway_types::Timestamp::from_secs_nanos(1_700_000_000, 123_456_789).expect("test timestamp");
let get = || GetObjectOutputFacts { let get = || GetObjectOutputFacts {
dto: gateway_dto::GetObjectOutput { dto: gateway_dto::GetObjectOutput {
@@ -1624,12 +1626,10 @@ mod tests {
}, },
etag: None, etag: None,
}; };
let old_get = let old_get = get_object::output_to_s3s(get().dto).expect("old GET projection");
gateway_s3s_compat::generated::ops::get_object::output_from_s3s(get().into_s3s().expect("old GET projection")) let old_get = get_object::output_from_s3s(old_get).expect("old GET output");
.expect("old GET output"); let old_head = head_object::output_to_s3s(head().dto).expect("old HEAD projection");
let old_head = let old_head = head_object::output_from_s3s(old_head).expect("old HEAD output");
gateway_s3s_compat::generated::ops::head_object::output_from_s3s(head().into_s3s().expect("old HEAD projection"))
.expect("old HEAD output");
let old = (old_get.object_lock_retain_until_date, old_head.object_lock_retain_until_date); let old = (old_get.object_lock_retain_until_date, old_head.object_lock_retain_until_date);
let expected = let expected =
Some(rustfs_gateway_types::Timestamp::from_secs_nanos(1_700_000_000, 123_000_000).expect("millisecond timestamp")); Some(rustfs_gateway_types::Timestamp::from_secs_nanos(1_700_000_000, 123_000_000).expect("millisecond timestamp"));
@@ -2732,6 +2732,32 @@ mod listing_tests {
); );
assert_eq!(current.buckets[0].creation_date.subsec_nanos(), 123000000); assert_eq!(current.buckets[0].creation_date.subsec_nanos(), 123000000);
} }
/// Same facts `RequestEnvelope::from_s3s` copies: method, URI, headers, extensions, region, service, and credentials.
#[cfg(any(feature = "webdav", feature = "sftp"))]
fn envelope_from_legacy_listing_request<T>(req: &S3Request<T>) -> crate::app::RequestEnvelope {
let credentials = req.credentials.as_ref().map(|credentials| {
let session_token = crate::auth::get_session_token(&req.uri, &req.headers).map(str::to_owned);
crate::app::RequestCredentials::new(
credentials.access_key.clone(),
credentials.secret_key.expose().to_owned(),
session_token.clone(),
)
.unwrap_or_else(|_| crate::app::RequestCredentials::without_secret_key(credentials.access_key.clone(), session_token))
});
crate::app::RequestEnvelope::from_parts(
crate::app::RequestHead {
method: req.method.clone(),
uri: req.uri.clone(),
headers: req.headers.clone(),
credentials,
region: req.region.as_ref().map(|region| region.as_str().to_owned()),
service: req.service.clone(),
},
req.extensions.clone(),
)
}
#[cfg(any(feature = "webdav", feature = "sftp"))] #[cfg(any(feature = "webdav", feature = "sftp"))]
#[test] #[test]
fn protocol_listing_session_credential_projection_matches_legacy() { fn protocol_listing_session_credential_projection_matches_legacy() {
@@ -2767,7 +2793,7 @@ mod listing_tests {
) )
.expect("legacy request"); .expect("legacy request");
legacy.headers = headers.clone(); legacy.headers = headers.clone();
let legacy = crate::app::RequestEnvelope::from_s3s(&legacy); let legacy = envelope_from_legacy_listing_request(&legacy);
let current = let current =
session_list_buckets_envelope(ServerContextSlot::new(), &session, &headers, true, credentials, false); session_list_buckets_envelope(ServerContextSlot::new(), &session, &headers, true, credentials, false);
let legacy = legacy.credentials().expect("legacy credentials"); let legacy = legacy.credentials().expect("legacy credentials");
+39 -48
View File
@@ -325,47 +325,9 @@ fn copy_output_facts(tag: Option<&str>) -> CopyObjectWriteOutput {
} }
} }
/// Same facts `RequestEnvelope::from_s3s` copies: method, URI, headers, extensions, region, service, and credentials.
fn envelope_from_legacy_copy_request(req: &s3s::S3Request<()>) -> crate::app::RequestEnvelope {
let credentials = req.credentials.as_ref().map(|credentials| {
let session_token = crate::auth::get_session_token(&req.uri, &req.headers).map(str::to_owned);
crate::app::RequestCredentials::new(
credentials.access_key.clone(),
credentials.secret_key.expose().to_owned(),
session_token.clone(),
)
.unwrap_or_else(|_| crate::app::RequestCredentials::without_secret_key(credentials.access_key.clone(), session_token))
});
crate::app::RequestEnvelope::from_parts(
crate::app::RequestHead {
method: req.method.clone(),
uri: req.uri.clone(),
headers: req.headers.clone(),
credentials,
region: req.region.as_ref().map(|region| region.as_str().to_owned()),
service: req.service.clone(),
},
req.extensions.clone(),
)
}
#[test] #[test]
fn protocol_copy_request_head_matches_legacy() { fn protocol_copy_request_head_matches_legacy() {
fn facts(envelope: &crate::app::RequestEnvelope) -> serde_json::Value { for (secret, expected_head_secret) in [("copy-secret", Some("copy-secret")), ("", None)] {
let info = envelope.req_info().expect("request info");
let credentials = envelope.credentials().expect("request credentials");
let identity = info.cred.as_ref().expect("request identity");
serde_json::json!({
"method":envelope.method().as_str(),"uri":envelope.uri().to_string(),"headers":format!("{:?}",envelope.headers()),
"credentials":[credentials.access_key(),credentials.secret_key(),credentials.session_token()],
"identity":[identity.access_key,identity.secret_key,identity.session_token],
"bucket":info.bucket,"object":info.object,"version":info.version_id,"owner":info.is_owner,
"keystone":info.keystone_session_present,"replication":info.replication_request_authorized,"region":info.region,
"request_context":info.request_context.is_some(),"suppress_log":info.suppress_denial_log,"suppress_audit":info.suppress_denial_audit,
"head_region":envelope.region(),"service":envelope.service(),"server":envelope.server_context().is_some(),"presigned":envelope.verified_presigned().is_some(),
})
}
for secret in ["copy-secret", ""] {
let credentials = rustfs_credentials::Credentials { let credentials = rustfs_credentials::Credentials {
access_key: "copy-identity".into(), access_key: "copy-identity".into(),
secret_key: secret.into(), secret_key: secret.into(),
@@ -374,15 +336,44 @@ fn protocol_copy_request_head_matches_legacy() {
..Default::default() ..Default::default()
}; };
let uri = build_object_uri("copy-target", "a ?&/%é", &[]).expect("request URI"); let uri = build_object_uri("copy-target", "a ?&/%é", &[]).expect("request URI");
let params = || RequestParams { let envelope = ProtocolStorageClient::create_envelope(
bucket: Some("copy-target".to_owned()), Method::PUT,
object: Some("a ?&/%é".to_owned()), uri,
credentials: &credentials, RequestParams {
}; bucket: Some("copy-target".to_owned()),
let old = ProtocolStorageClient::create_request((), Method::PUT, uri.clone(), params()).expect("legacy request"); object: Some("a ?&/%é".to_owned()),
let old = envelope_from_legacy_copy_request(&old); credentials: &credentials,
let current = ProtocolStorageClient::create_envelope(Method::PUT, uri, params()); },
assert_eq!(facts(&current), facts(&old)); );
assert_eq!(envelope.method(), &Method::PUT);
assert_eq!(envelope.uri().to_string(), "/copy-target/a%20%3F&/%25%C3%A9");
assert!(envelope.headers().is_empty());
assert!(envelope.region().is_none());
assert!(envelope.service().is_none());
assert!(envelope.server_context().is_none());
assert!(envelope.verified_presigned().is_none());
let head_credentials = envelope.credentials().expect("request credentials");
assert_eq!(head_credentials.access_key(), "copy-identity");
assert_eq!(head_credentials.secret_key(), expected_head_secret);
assert!(head_credentials.session_token().is_none());
let info = envelope.req_info().expect("request info");
let identity = info.cred.as_ref().expect("request identity");
assert_eq!(identity.access_key, "copy-identity");
assert_eq!(identity.secret_key, secret);
assert_eq!(identity.session_token, "identity-token");
assert_eq!(info.bucket.as_deref(), Some("copy-target"));
assert_eq!(info.object.as_deref(), Some("a ?&/%é"));
assert!(info.version_id.is_none());
assert!(!info.is_owner);
assert!(info.keystone_session_present.is_none());
assert!(!info.replication_request_authorized);
assert!(info.region.is_none());
assert!(info.request_context.is_some());
assert!(!info.suppress_denial_log);
assert!(!info.suppress_denial_audit);
} }
} }
+4 -4
View File
@@ -156,10 +156,10 @@ pub(super) fn complete_multipart_output(
] { ] {
if let Some(value) = value { if let Some(value) = value {
http::HeaderValue::from_str(&value).map_err(|_| { http::HeaderValue::from_str(&value).map_err(|_| {
crate::app::dto_values::seam_error(rustfs_gateway_types::compat::ConversionError { S3Error::with_message(
field, S3ErrorCode::InternalError,
reason: "not a header value", format!("failed to convert through the gateway compatibility seam: {field}: not a header value"),
}) )
})?; })?;
} }
} }
+59 -31
View File
@@ -187,19 +187,20 @@ fn multipart_complete_projection_matches_original_parts_and_conditions() {
#[test] #[test]
fn multipart_completion_projection_preserves_original_escaped_tags() { fn multipart_completion_projection_preserves_original_escaped_tags() {
for (opaque, weak) in [("abc", false), ("a&b<c", false), ("a\"b", true)] { for (opaque, weak, expected) in [
("abc", false, "abc"),
("a&b<c", false, "a&amp;b&lt;c"),
("a\"b", true, "a&quot;b"),
] {
let input = dto::CompleteMultipartUploadOutput { let input = dto::CompleteMultipartUploadOutput {
e_tag: Some(if weak { ETag::new_weak(opaque) } else { ETag::new(opaque) }.expect("tag")), e_tag: Some(if weak { ETag::new_weak(opaque) } else { ETag::new(opaque) }.expect("tag")),
..Default::default() ..Default::default()
}; };
let mut legacy = let tag = complete_multipart_output(input)
compat::generated::ops::complete_multipart_upload::output_to_s3s(input.clone()).expect("original output"); .expect("completion output")
let stored = if weak { format!("W/\"{opaque}\"") } else { opaque.to_owned() }; .e_tag
legacy.e_tag = Some(crate::app::storage_api::object_utils::to_s3s_xml_etag(&stored)); .expect("ETag");
let expected = compat::generated::ops::complete_multipart_upload::output_from_s3s(legacy).expect("original answer"); assert_eq!((tag.opaque_tag(), tag.is_weak()), (expected, weak));
let actual = complete_multipart_output(input).expect("owned answer");
let tag = |value: Option<ETag>| value.map(|value| (value.opaque_tag().to_owned(), value.is_weak()));
assert_eq!(tag(actual.e_tag), tag(expected.e_tag));
} }
} }
@@ -255,28 +256,55 @@ fn multipart_refusals_match_original_client_errors() {
#[test] #[test]
fn multipart_completion_projection_preserves_header_only_field_behavior() { fn multipart_completion_projection_preserves_header_only_field_behavior() {
let output = dto::CompleteMultipartUploadOutput { let headers = [
checksum_header_xxhash3: Some("AAAAAAAAAAA=".into()), "x-amz-checksum-md5",
sse_customer_algorithm: Some("AES256".into()), "x-amz-checksum-sha512",
sse_customer_key_md5: Some("digest".into()), "x-amz-checksum-xxhash3",
..Default::default() "x-amz-checksum-xxhash64",
}; "x-amz-checksum-xxhash128",
let output = complete_multipart_output(output).expect("header fields remain valid"); "x-amz-server-side-encryption-customer-algorithm",
assert!(output.checksum_header_xxhash3.is_none()); "x-amz-server-side-encryption-customer-key-md5",
assert!(output.sse_customer_algorithm.is_none()); ];
assert!(output.sse_customer_key_md5.is_none()); for first_invalid in 0..=headers.len() {
let error = complete_multipart_output(dto::CompleteMultipartUploadOutput { let valid = ["md5", "sha512", "AAAAAAAAAAA=", "xxhash64", "xxhash128", "AES256", "digest"];
sse_customer_algorithm: Some("bad\nvalue".into()), let value = |index: usize| Some(if index < first_invalid { valid[index] } else { "bad\nvalue" }.to_owned());
..Default::default() let output = dto::CompleteMultipartUploadOutput {
}) checksum_header_md5: value(0),
.expect_err("invalid original response header"); checksum_header_sha512: value(1),
assert_eq!(error.code(), &S3ErrorCode::InternalError); checksum_header_xxhash3: value(2),
assert!( checksum_header_xxhash64: value(3),
error checksum_header_xxhash128: value(4),
.message() sse_customer_algorithm: value(5),
.expect("message") sse_customer_key_md5: value(6),
.contains("x-amz-server-side-encryption-customer-algorithm: not a header value") ..Default::default()
); };
let result = complete_multipart_output(output);
if let Some(header) = headers.get(first_invalid) {
let error = result.expect_err("invalid response header");
assert_eq!(error.code(), &S3ErrorCode::InternalError);
assert_eq!(
error.message(),
Some(format!("failed to convert through the gateway compatibility seam: {header}: not a header value").as_str())
);
assert_eq!(error.status_code(), Some(http::StatusCode::INTERNAL_SERVER_ERROR));
assert!(error.headers().is_none());
assert!(std::error::Error::source(&error).is_none());
} else {
let output = result.expect("valid response headers");
assert_eq!(
[
output.checksum_header_md5,
output.checksum_header_sha512,
output.checksum_header_xxhash3,
output.checksum_header_xxhash64,
output.checksum_header_xxhash128,
output.sse_customer_algorithm,
output.sse_customer_key_md5
],
[const { None }; 7]
);
}
}
} }
#[test] #[test]
+91 -69
View File
@@ -17,7 +17,6 @@
use super::*; use super::*;
use crate::app::multipart_usecase::{DefaultMultipartUsecase, UploadPartCopyWriteInput, UploadPartCopyWriteOutput}; use crate::app::multipart_usecase::{DefaultMultipartUsecase, UploadPartCopyWriteInput, UploadPartCopyWriteOutput};
use crate::app::storage_api::s3::S3Response;
use rustfs_gateway_types::{CopySourceValue, UploadIdClaim, dto}; use rustfs_gateway_types::{CopySourceValue, UploadIdClaim, dto};
use rustfs_protocols::common::client::s3::StorageBackend; use rustfs_protocols::common::client::s3::StorageBackend;
use rustfs_s3_types::S3Error; use rustfs_s3_types::S3Error;
@@ -594,42 +593,70 @@ fn output_facts(raw: Option<&str>) -> crate::app::multipart_usecase::UploadPartC
#[test] #[test]
fn protocol_upload_copy_output_matches_original_composed_codec() { fn protocol_upload_copy_output_matches_original_composed_codec() {
for raw in [ let missing = "failed to convert UploadPartCopy output through the gateway compatibility seam: e_tag: the gateway shape requires this member";
None, let invalid = "failed to convert UploadPartCopy output through the gateway compatibility seam: e_tag: not an entity tag the gateway can write";
Some("abc"), for (raw, expected) in [
Some("\"abc\""), (None, Err(missing)),
Some("W/\"abc\""), (Some("abc"), Ok(("abc", false))),
Some("a&\"b"), (Some("\"abc\""), Ok(("abc", false))),
Some(""), (Some("W/\"abc\""), Ok(("abc", true))),
Some("\"\""), (Some("a&\"b"), Ok(("a&amp;&quot;b", false))),
Some("a\0b"), (Some(""), Err(invalid)),
(Some("\"\""), Err(invalid)),
(Some("a\0b"), Err(invalid)),
] { ] {
let fields = output_facts(raw); let result = multipart::upload_part_copy_output(output_facts(raw));
let legacy = UploadPartCopyOutput { match expected {
copy_part_result: Some(CopyPartResult { Err(message) => {
e_tag: raw.map(crate::app::storage_api::multipart_usecase::object_utils::to_s3s_xml_etag), let error = result.expect_err("unrepresentable stored ETag");
last_modified: fields.last_modified.map(Timestamp::from), assert!(std::error::Error::source(&error).is_none());
checksum_crc32: fields.checksum_crc32, assert_eq!(
checksum_crc32c: fields.checksum_crc32c, error_facts(error),
checksum_sha1: fields.checksum_sha1, (
checksum_sha256: fields.checksum_sha256, "InternalError".to_owned(),
checksum_crc64nvme: fields.checksum_crc64nvme, Some(message.to_owned()),
..Default::default() Some(http::StatusCode::INTERNAL_SERVER_ERROR),
}), None
copy_source_version_id: fields.copy_source_version_id, ),
server_side_encryption: fields.server_side_encryption.map(ServerSideEncryption::from), "{raw:?}"
ssekms_key_id: fields.ssekms_key_id, );
sse_customer_algorithm: fields.sse_customer_algorithm, }
sse_customer_key_md5: fields.sse_customer_key_md5, Ok((opaque, weak)) => {
..Default::default() let output = result.expect("copy output");
}; let expected = dto::UploadPartCopyOutput {
let expected = gateway_s3s_compat::generated::ops::upload_part_copy::output_from_s3s(legacy) e_tag: if weak {
.map(|output| format!("{output:?}")) rustfs_gateway_types::ETag::new_weak(opaque)
.map_err(|error| conversion_error("UploadPartCopy output", error).to_string()); } else {
let actual = multipart::upload_part_copy_output(output_facts(raw)) rustfs_gateway_types::ETag::new(opaque)
.map(|output| format!("{output:?}")) }
.map_err(|error| error.to_string()); .expect("ETag"),
assert_eq!(actual, expected, "stored tag {raw:?}"); last_modified: Some(
rustfs_gateway_types::Timestamp::from_secs_nanos(1_700_000_000, 123_000_000)
.expect("millisecond timestamp"),
),
copy_source_version_id: Some("null".into()),
server_side_encryption: Some(dto::ServerSideEncryption::custom("aws:kms")),
ssekms_key_id: Some("kms-id".into()),
sse_customer_algorithm: Some("AES256".into()),
sse_customer_key_md5: Some("digest".into()),
checksum_crc32: Some("crc32".into()),
checksum_crc32c: Some("crc32c".into()),
checksum_crc64nvme: Some("crc64nvme".into()),
checksum_sha1: Some("sha1".into()),
checksum_sha256: Some("sha256".into()),
bucket_key_enabled: None,
request_charged: None,
checksum_sha512: None,
checksum_md5: None,
checksum_xxhash64: None,
checksum_xxhash3: None,
checksum_xxhash128: None,
};
assert_eq!(format!("{output:?}"), format!("{expected:?}"), "{raw:?}");
assert_eq!(output.ssekms_key_id, expected.ssekms_key_id);
assert_eq!(output.sse_customer_key_md5, expected.sse_customer_key_md5);
}
}
} }
} }
@@ -659,14 +686,6 @@ fn protocol_upload_copy_error_keeps_explicit_message_headers_and_storage_cause()
} }
// Keep construction of the large use-case futures outside the test's async frame. // Keep construction of the large use-case futures outside the test's async frame.
#[inline(never)]
fn legacy_copy_future(
usecase: &DefaultMultipartUsecase,
request: S3Request<UploadPartCopyInput>,
) -> impl std::future::Future<Output = S3Result<S3Response<UploadPartCopyOutput>>> + '_ {
Box::pin(usecase.execute_upload_part_copy(request))
}
#[inline(never)] #[inline(never)]
fn owned_copy_future( fn owned_copy_future(
usecase: &DefaultMultipartUsecase, usecase: &DefaultMultipartUsecase,
@@ -701,40 +720,43 @@ async fn protocol_upload_copy_capabilities_precede_part_validation() {
"x-rustfs-max-total-object-size is only supported for CreateMultipartUpload", "x-rustfs-max-total-object-size is only supported for CreateMultipartUpload",
), ),
] { ] {
let make = || { let uri: http::Uri = format!("/bucket/copy-target?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=fixture/20260827/us-east-1/s3/aws4_request&X-Amz-Signature=fixture{query}").parse().expect("URI");
let mut request = input("bucket", "upload"); let request = ProtocolStorageClient::create_envelope(
request.part_number = 0;
request
};
let source = legacy_copy_source(make().copy_source).expect("source");
let legacy = gateway_s3s_compat::generated::ops::upload_part_copy::input_to_s3s(make(), source).expect("legacy input");
let uri = format!("/bucket/copy-target?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=fixture/20260827/us-east-1/s3/aws4_request&X-Amz-Signature=fixture{query}").parse().expect("URI");
let mut request = ProtocolStorageClient::create_request(
legacy,
Method::PUT, Method::PUT,
uri, uri.clone(),
RequestParams { RequestParams {
bucket: Some("bucket".into()), bucket: Some("bucket".into()),
object: Some("copy-target".into()), object: Some("copy-target".into()),
credentials: &credentials, credentials: &credentials,
}, },
) );
.expect("request"); let mut extensions = http::Extensions::new();
request.extensions.insert(crate::auth::VerifiedSigV4Request); extensions.insert(request.req_info().expect("request identity").clone());
request.extensions.insert(crate::auth::VerifiedPresignedRequest); extensions.insert(crate::auth::VerifiedSigV4Request);
let envelope = crate::app::RequestEnvelope::from_s3s(&request); extensions.insert(crate::auth::VerifiedPresignedRequest);
let usecase = crate::app::multipart_usecase::DefaultMultipartUsecase::without_context(); let envelope = crate::app::RequestEnvelope::from_parts(
let expected = legacy_copy_future(&usecase, request) crate::app::RequestHead {
.await method: Method::PUT,
.err() uri,
.map(S3Error::from) headers: HeaderMap::new(),
.expect("legacy refusal"); credentials: request.credentials().cloned(),
let (_, input) = multipart::prepare_upload_part_copy(make()).expect("owned input"); region: None,
service: None,
},
extensions,
);
let usecase = DefaultMultipartUsecase::without_context();
let mut request = input("bucket", "upload");
request.part_number = 0;
let (_, input) = multipart::prepare_upload_part_copy(request).expect("owned input");
let actual = owned_copy_future(&usecase, envelope, input) let actual = owned_copy_future(&usecase, envelope, input)
.await .await
.err() .err()
.expect("owned refusal"); .expect("owned refusal");
assert_eq!((actual.code().as_str(), actual.message()), (code, Some(message))); assert!(std::error::Error::source(&actual).is_none());
assert_eq!(error_facts(actual), error_facts(expected)); assert_eq!(
error_facts(actual),
(code.to_owned(), Some(message.to_owned()), Some(http::StatusCode::BAD_REQUEST), None)
);
} }
} }
+87 -29
View File
@@ -69,6 +69,7 @@ use rustfs_common::{
GlobalReadiness, GlobalReadiness,
trace_bus::{TelemetryTraceEvent, TelemetryTraceOperation, TelemetryTraceStatus, telemetry_trace_emit}, trace_bus::{TelemetryTraceEvent, TelemetryTraceOperation, TelemetryTraceStatus, telemetry_trace_emit},
}; };
use rustfs_gateway::{LegacyDomainError, LegacyRustfsVirtualHosts};
use rustfs_io_metrics::internode_metrics::{ use rustfs_io_metrics::internode_metrics::{
INTERNODE_OPERATION_GRPC_COMPARE_AND_UPDATE_FILE, INTERNODE_OPERATION_GRPC_OTHER, INTERNODE_OPERATION_GRPC_READ_ALL, INTERNODE_OPERATION_GRPC_COMPARE_AND_UPDATE_FILE, INTERNODE_OPERATION_GRPC_OTHER, INTERNODE_OPERATION_GRPC_READ_ALL,
INTERNODE_OPERATION_GRPC_READ_MULTIPLE, INTERNODE_OPERATION_GRPC_WRITE_ALL, INTERNODE_TRANSPORT_BACKEND_GRPC, INTERNODE_OPERATION_GRPC_READ_MULTIPLE, INTERNODE_OPERATION_GRPC_WRITE_ALL, INTERNODE_TRANSPORT_BACKEND_GRPC,
@@ -83,6 +84,7 @@ use rustfs_protos::proto_gen::node_service::{
}; };
use rustfs_trusted_proxies::ClientInfo; use rustfs_trusted_proxies::ClientInfo;
use rustfs_utils::net::parse_and_resolve_address; use rustfs_utils::net::parse_and_resolve_address;
#[cfg(test)]
use s3s::host::MultiDomain; use s3s::host::MultiDomain;
use socket2::{SockRef, TcpKeepalive}; use socket2::{SockRef, TcpKeepalive};
use std::io::{Error, Result}; use std::io::{Error, Result};
@@ -183,23 +185,23 @@ static HTTP_STATUS_CLASS_METRICS: std::sync::LazyLock<[HttpStatusClassMetrics; 6
static HTTP_TRANSPORT_FAILURES_COUNTER: std::sync::LazyLock<metrics::Counter> = static HTTP_TRANSPORT_FAILURES_COUNTER: std::sync::LazyLock<metrics::Counter> =
std::sync::LazyLock::new(|| counter!(METRIC_HTTP_SERVER_FAILURES_TOTAL, LABEL_HTTP_STATUS_CLASS => "transport")); std::sync::LazyLock::new(|| counter!(METRIC_HTTP_SERVER_FAILURES_TOTAL, LABEL_HTTP_STATUS_CLASS => "transport"));
fn validated_domains(variable: &str, domains: &[String]) -> Result<LegacyRustfsVirtualHosts> {
LegacyRustfsVirtualHosts::new(domains).map_err(|err| {
let reason = match err {
LegacyDomainError::NotADomain => "The domain is invalid",
LegacyDomainError::Overlapping => "Some subdomains overlap with each other",
};
Error::other(format!("invalid {variable} {domains:?}: {reason}"))
})
}
fn s3_host_domains(config: &config::Config) -> Result<Option<Vec<String>>> { fn s3_host_domains(config: &config::Config) -> Result<Option<Vec<String>>> {
if config.server_domains.is_empty() || config.console_enable { if config.server_domains.is_empty() || config.console_enable {
return Ok(None); return Ok(None);
} }
let mut domains = Vec::with_capacity(config.server_domains.len()); let hosts = validated_domains("RUSTFS_SERVER_DOMAINS", &config.server_domains)?;
let mut seen = std::collections::HashSet::with_capacity(config.server_domains.len()); Ok(Some(hosts.domains().map(str::to_owned).collect()))
for domain in &config.server_domains {
if seen.insert(strip_valid_port_suffix(domain).to_string()) {
domains.push(domain.clone());
}
}
MultiDomain::new(&domains)
.map_err(|err| Error::other(format!("invalid RUSTFS_SERVER_DOMAINS {:?}: {err}", config.server_domains)))?;
Ok(Some(domains))
} }
fn website_host_domains(config: &config::Config) -> Result<Option<Vec<String>>> { fn website_host_domains(config: &config::Config) -> Result<Option<Vec<String>>> {
@@ -230,7 +232,7 @@ fn website_host_domains(config: &config::Config) -> Result<Option<Vec<String>>>
if domains.is_empty() { if domains.is_empty() {
Ok(None) Ok(None)
} else { } else {
MultiDomain::new(&domains).map_err(|err| Error::other(format!("invalid RUSTFS_WEBSITE_DOMAINS {:?}: {err}", domains)))?; validated_domains("RUSTFS_WEBSITE_DOMAINS", &domains)?;
Ok(Some(domains)) Ok(Some(domains))
} }
} }
@@ -1693,7 +1695,7 @@ struct ControlBodyDigestService<S> {
idle_timeout: Duration, idle_timeout: Duration,
total_timeout: Duration, total_timeout: Duration,
max_body_size: usize, max_body_size: usize,
virtual_host: Option<Arc<MultiDomain>>, virtual_host: Option<Arc<LegacyRustfsVirtualHosts>>,
} }
/// The largest control-plane XML body read for digest validation: 20 MiB, the XML body limit /// The largest control-plane XML body read for digest validation: 20 MiB, the XML body limit
@@ -1720,13 +1722,15 @@ impl<S> ControlBodyDigestService<S> {
fn with_virtual_host_domains(mut self, domains: Arc<[String]>) -> Self { fn with_virtual_host_domains(mut self, domains: Arc<[String]>) -> Self {
if !domains.is_empty() { if !domains.is_empty() {
// Startup already validated this same domain set for S3Service. // Startup already validated this same domain set for S3Service.
self.virtual_host = Some(Arc::new(MultiDomain::new(domains.iter()).expect("validated S3 host domains"))); self.virtual_host = Some(Arc::new(
LegacyRustfsVirtualHosts::new(domains.iter()).expect("validated S3 host domains"),
));
} }
self self
} }
} }
fn control_body_digest_required<B>(request: &HttpRequest<B>, virtual_host: Option<&MultiDomain>) -> Option<bool> { fn control_body_digest_required<B>(request: &HttpRequest<B>, virtual_host: Option<&LegacyRustfsVirtualHosts>) -> Option<bool> {
let query = url::form_urlencoded::parse(request.uri().query().unwrap_or_default().as_bytes()); let query = url::form_urlencoded::parse(request.uri().query().unwrap_or_default().as_bytes());
// Match s3s' multipart POST precedence, including its unique-header rule. // Match s3s' multipart POST precedence, including its unique-header rule.
if request.method() == Method::POST if request.method() == Method::POST
@@ -1748,9 +1752,8 @@ fn control_body_digest_required<B>(request: &HttpRequest<B>, virtual_host: Optio
} }
if request.method() == Method::POST { if request.method() == Method::POST {
let decoded_path = urlencoding::decode(request.uri().path()).ok()?; let decoded_path = urlencoding::decode(request.uri().path()).ok()?;
use s3s::host::S3Host; use rustfs_gateway_types::{LegacyRustfsNameValidator, NameValidator};
// Use s3s' host parser, including CNAME fallback, and its Host-first // This middleware selects Host first, with an authority fallback on HTTP/2 and HTTP/3.
// precedence. A rate-limit host hint is intentionally only best-effort.
let mut host_values = request.headers().get_all("host").iter(); let mut host_values = request.headers().get_all("host").iter();
let host = host_values.next().and_then(|value| value.to_str().ok()).or_else(|| { let host = host_values.next().and_then(|value| value.to_str().ok()).or_else(|| {
matches!(request.version(), Version::HTTP_2 | Version::HTTP_3) matches!(request.version(), Version::HTTP_2 | Version::HTTP_3)
@@ -1760,14 +1763,19 @@ fn control_body_digest_required<B>(request: &HttpRequest<B>, virtual_host: Optio
if host_values.next().is_some() { if host_values.next().is_some() {
return None; return None;
} }
let host = match (virtual_host, host) { let virtual_bucket = match (virtual_host, host) {
(Some(parser), Some(host)) if host.parse::<SocketAddr>().is_err() && host.parse::<IpAddr>().is_err() => { (Some(parser), Some(host)) => parser.bucket_for_host_header(host).ok()?,
Some(parser.parse_host_header(host).ok()?)
}
_ => None, _ => None,
}; };
let path = s3s::path::parse_virtual_hosted_style(host.as_ref().and_then(|host| host.bucket()), &decoded_path).ok()?; let path = decoded_path.strip_prefix('/')?;
if !matches!(path, s3s::path::S3Path::Bucket { .. }) { let is_bucket = if virtual_bucket.is_some() {
path.is_empty()
} else {
// A path-style bucket can end in one slash. Any remaining slash denotes an object.
let bucket = path.strip_suffix('/').unwrap_or(path);
LegacyRustfsNameValidator.check_bucket(bucket).into_result().is_ok()
};
if !is_bucket {
return None; return None;
} }
let delete_objects = match operation_id.as_deref() { let delete_objects = match operation_id.as_deref() {
@@ -8064,10 +8072,60 @@ mod tests {
let err = s3_host_domains(&config).expect_err("real subdomain overlap must stay rejected"); let err = s3_host_domains(&config).expect_err("real subdomain overlap must stay rejected");
let message = err.to_string(); assert_eq!(
assert!(message.contains("RUSTFS_SERVER_DOMAINS"), "{message}"); err.to_string(),
assert!(message.contains("example.com"), "{message}"); r#"invalid RUSTFS_SERVER_DOMAINS ["example.com", "s3.example.com"]: Some subdomains overlap with each other"#
assert!(message.contains("s3.example.com"), "{message}"); );
}
#[test]
fn s3_host_domains_reports_invalid_entries_before_later_overlaps() {
let config = test_config_with_domains(&["example.com:9000", "example.com", "bad_name", "s3.example.com"]);
assert_eq!(
s3_host_domains(&config).unwrap_err().to_string(),
r#"invalid RUSTFS_SERVER_DOMAINS ["example.com:9000", "example.com", "bad_name", "s3.example.com"]: The domain is invalid"#
);
}
#[test]
fn website_host_domains_preserves_startup_errors_and_normalization() {
let config = test_config_with_domains(&["s3.example:9000"]);
for (value, message) in [
(
"Site.Example, BAD_NAME",
r#"invalid RUSTFS_WEBSITE_DOMAINS ["site.example", "bad_name"]: The domain is invalid"#,
),
(
"SITE.example,k.site.example",
r#"invalid RUSTFS_WEBSITE_DOMAINS ["site.example", "k.site.example"]: Some subdomains overlap with each other"#,
),
("site.example, SITE.example", "duplicate RUSTFS_WEBSITE_DOMAINS entry: SITE.example"),
("website.s3.example", "website domain overlaps RUSTFS_SERVER_DOMAINS: website.s3.example"),
("site.example:9000", "invalid RUSTFS_WEBSITE_DOMAINS entry: site.example:9000"),
("site.example.", "invalid RUSTFS_WEBSITE_DOMAINS entry: site.example."),
] {
temp_env::with_var("RUSTFS_WEBSITE_DOMAINS", Some(value), || {
assert_eq!(website_host_domains(&config).unwrap_err().to_string(), message);
});
}
temp_env::with_var("RUSTFS_WEBSITE_DOMAINS", Some("Z.Example, ,A.Example"), || {
assert_eq!(website_host_domains(&config).unwrap().unwrap(), ["z.example", "a.example"]);
});
}
#[test]
fn startup_host_domains_skip_empty_lists_and_console_configuration() {
let mut config = test_config_with_domains(&[]);
assert_eq!(s3_host_domains(&config).unwrap(), None);
temp_env::with_var("RUSTFS_WEBSITE_DOMAINS", Some(", ,"), || {
assert_eq!(website_host_domains(&config).unwrap(), None);
});
config.server_domains.push("bad_name".to_owned());
config.console_enable = true;
temp_env::with_var("RUSTFS_WEBSITE_DOMAINS", Some("bad_name"), || {
assert_eq!(s3_host_domains(&config).unwrap(), None);
assert_eq!(website_host_domains(&config).unwrap(), None);
});
} }
#[test] #[test]
+3 -1
View File
@@ -20,6 +20,8 @@ pub mod deadlock_detector;
pub(crate) mod denial_audit; pub(crate) mod denial_audit;
pub(crate) mod helper; pub(crate) mod helper;
pub mod options; pub mod options;
#[cfg(test)]
mod replication_config_tests;
pub(crate) mod req_info; pub(crate) mod req_info;
pub mod request_context; pub mod request_context;
pub(crate) mod request_markers; pub(crate) mod request_markers;
@@ -76,7 +78,7 @@ pub(crate) use storage_api::{
helper_consumer, init_background_replication, init_bucket_metadata_sys, init_ecstore_config, helper_consumer, init_background_replication, init_bucket_metadata_sys, init_ecstore_config,
init_local_disks_with_instance_ctx, init_lock_clients, is_err_bucket_not_found, is_err_object_not_found, init_local_disks_with_instance_ctx, init_lock_clients, is_err_bucket_not_found, is_err_object_not_found,
is_err_version_not_found, is_valid_storage_class, options_consumer, prewarm_local_disk_id_map_with_instance_ctx, read_config, is_err_version_not_found, is_valid_storage_class, options_consumer, prewarm_local_disk_id_map_with_instance_ctx, read_config,
record_replication_proxy, rpc_consumer, runtime_sources_consumer, s3_api_consumer, table_catalog_path_hash, to_s3s_etag, record_replication_proxy, rpc_consumer, runtime_sources_consumer, s3_api_consumer, table_catalog_path_hash,
topology_snapshot_from_endpoint_pools_with_capabilities, try_migrate_bucket_metadata, try_migrate_iam_config, topology_snapshot_from_endpoint_pools_with_capabilities, try_migrate_bucket_metadata, try_migrate_iam_config,
try_migrate_server_config, update_bucket_metadata_config, update_bucket_metadata_config_if_incarnation, try_migrate_server_config, update_bucket_metadata_config, update_bucket_metadata_config_if_incarnation,
validate_website_configuration, verify_rpc_signature, wrap_reader, validate_website_configuration, verify_rpc_signature, wrap_reader,
@@ -0,0 +1,263 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Replication fixtures written by the historical S3 codec at 5761ddfe.
//! The XML lives in bucket metadata. The scanner keeps compact MessagePack.
use super::storage_api::ecstore_bucket::{replication::ReplicationConfig, utils::BucketConfigXml};
use rustfs_gateway_types::persistence::{
PersistedAccessControlTranslation, PersistedEncryptionConfiguration, PersistedOptionalReplicationStatus,
PersistedReplicationAnd, PersistedReplicationConfiguration, PersistedReplicationDestination, PersistedReplicationFilter,
PersistedReplicationMetrics, PersistedReplicationRule, PersistedReplicationStatus, PersistedReplicationTag,
PersistedReplicationTime, PersistedReplicationTimeValue, PersistedSourceSelectionCriteria,
};
const ALL_XML: &[u8] = b"<ReplicationConfiguration><Role>arn:aws:iam::123456789012:role/replication</Role><Rule>\
<DeleteMarkerReplication><Status>FutureDeleteMarker</Status></DeleteMarkerReplication>\
<DeleteReplication><Status>FutureDelete</Status></DeleteReplication><Destination>\
<AccessControlTranslation><Owner>FutureOwner</Owner></AccessControlTranslation>\
<Account>123456789012</Account><Bucket>arn:aws:s3:::backup</Bucket><EncryptionConfiguration>\
<ReplicaKmsKeyID>kms-key</ReplicaKmsKeyID></EncryptionConfiguration><Metrics><EventThreshold>\
<Minutes>15</Minutes></EventThreshold><Status>FutureMetrics</Status></Metrics><ReplicationTime>\
<Status>FutureRtc</Status><Time><Minutes>30</Minutes></Time></ReplicationTime>\
<StorageClass>FutureClass</StorageClass></Destination><ExistingObjectReplication>\
<Status>FutureExisting</Status></ExistingObjectReplication><Filter><And><Prefix>docs/</Prefix><Tag>\
<Key>team</Key><Value>storage</Value></Tag><Tag><Key>tier</Key><Value>gold</Value></Tag></And>\
<Prefix>filter/</Prefix><Tag><Key>env</Key><Value>prod</Value></Tag></Filter><ID>every-member</ID>\
<Prefix>legacy/</Prefix><Priority>7</Priority><SourceSelectionCriteria><ReplicaModifications>\
<Status>FutureReplica</Status></ReplicaModifications><SseKmsEncryptedObjects><Status>FutureKms</Status>\
</SseKmsEncryptedObjects></SourceSelectionCriteria><Status>FutureRule</Status></Rule><Rule>\
<Destination><Bucket>arn:aws:s3:::second</Bucket></Destination><Status>Disabled</Status></Rule>\
</ReplicationConfiguration>";
const KEYLESS_XML: &[u8] = b"<ReplicationConfiguration><Role></Role><Rule><Destination><Bucket>arn:aws:s3:::backup</Bucket>\
</Destination><Filter><Tag></Tag></Filter><Status>Enabled</Status></Rule></ReplicationConfiguration>";
const EMPTY_KEY_XML: &[u8] = b"<ReplicationConfiguration><Role></Role><Rule><Destination><Bucket>arn:aws:s3:::backup</Bucket>\
</Destination><Filter><Tag><Key></Key><Value></Value></Tag></Filter><Status>Enabled</Status></Rule>\
</ReplicationConfiguration>";
const LOWERCASE_XML: &[u8] = b"<ReplicationConfiguration><Role></Role><Rule><Destination><Bucket>arn:aws:s3:::backup</Bucket>\
</Destination><Filter></Filter><Status>enabled</Status></Rule></ReplicationConfiguration>";
const MARKER_XML: &[u8] = b"<ReplicationConfiguration><Role></Role><Rule><DeleteMarkerReplication></DeleteMarkerReplication>\
<Destination><Bucket>arn:aws:s3:::backup</Bucket></Destination><Filter></Filter>\
<Status>Enabled</Status></Rule></ReplicationConfiguration>";
const MINIMAL_XML: &[u8] = b"<ReplicationConfiguration><Role></Role><Rule><Destination><Bucket>arn:aws:s3:::backup</Bucket>\
</Destination><Filter></Filter><Status>Enabled</Status></Rule></ReplicationConfiguration>";
const ALL_CACHE: &str = "9292d92a61726e3a6177733a69616d3a3a3132333435363738393031323a726f6c652f7265706c69636174696f6e929a\
91b246757475726544656c6574654d61726b657291ac46757475726544656c6574659791ab4675747572654f776e6572\
ac313233343536373839303132b361726e3a6177733a73333a3a3a6261636b757091a76b6d732d6b657992910fad4675\
747572654d65747269637392a9467574757265527463911eab467574757265436c61737391ae46757475726545786973\
74696e679492a5646f63732f9292a47465616da773746f7261676592a474696572a4676f6c6480a766696c7465722f92\
a3656e76a470726f64ac65766572792d6d656d626572a76c65676163792f079291ad4675747572655265706c69636191\
a94675747572654b6d73aa46757475726552756c659ac0c097c0c0b361726e3a6177733a73333a3a3a7365636f6e64c0\
c0c0c0c0c0c0c0c0c0a844697361626c6564c0";
const EMPTY_TAGS_CACHE: &str = "9292a0919ac0c097c0c0b361726e3a6177733a73333a3a3a6261636b7570c0c0c0c0c09492c09080c0c0c0c0c0c0a745\
6e61626c6564c0";
const ABSENT_TAGS_CACHE: &str = "9292a0919ac0c097c0c0b361726e3a6177733a73333a3a3a6261636b7570c0c0c0c0c09492c0c080c0c0c0c0c0c0a745\
6e61626c6564c0";
fn status(value: &str) -> PersistedReplicationStatus {
PersistedReplicationStatus {
status: value.to_owned(),
}
}
fn tag(key: &str, value: &str) -> PersistedReplicationTag {
PersistedReplicationTag {
key: Some(key.to_owned()),
value: Some(value.to_owned()),
}
}
fn every_member() -> PersistedReplicationConfiguration {
PersistedReplicationConfiguration {
role: "arn:aws:iam::123456789012:role/replication".to_owned(),
rules: vec![
PersistedReplicationRule {
delete_marker_replication: Some(PersistedOptionalReplicationStatus {
status: Some("FutureDeleteMarker".to_owned()),
}),
delete_replication: Some(status("FutureDelete")),
destination: PersistedReplicationDestination {
account: Some("123456789012".to_owned()),
access_control_translation: Some(PersistedAccessControlTranslation {
owner: "FutureOwner".to_owned(),
}),
bucket: "arn:aws:s3:::backup".to_owned(),
encryption_configuration: Some(PersistedEncryptionConfiguration {
replica_kms_key_id: Some("kms-key".to_owned()),
}),
metrics: Some(PersistedReplicationMetrics {
event_threshold: Some(PersistedReplicationTimeValue { minutes: Some(15) }),
status: "FutureMetrics".to_owned(),
}),
replication_time: Some(PersistedReplicationTime {
status: "FutureRtc".to_owned(),
time: PersistedReplicationTimeValue { minutes: Some(30) },
}),
storage_class: Some("FutureClass".to_owned()),
},
existing_object_replication: Some(status("FutureExisting")),
filter: Some(PersistedReplicationFilter {
and: Some(PersistedReplicationAnd {
prefix: Some("docs/".to_owned()),
tags: Some(vec![tag("team", "storage"), tag("tier", "gold")]),
}),
prefix: Some("filter/".to_owned()),
tag: Some(tag("env", "prod")),
}),
id: Some("every-member".to_owned()),
prefix: Some("legacy/".to_owned()),
priority: Some(7),
source_selection_criteria: Some(PersistedSourceSelectionCriteria {
replica_modifications: Some(status("FutureReplica")),
sse_kms_encrypted_objects: Some(status("FutureKms")),
}),
status: "FutureRule".to_owned(),
},
PersistedReplicationRule {
delete_marker_replication: None,
delete_replication: None,
destination: PersistedReplicationDestination {
bucket: "arn:aws:s3:::second".to_owned(),
..Default::default()
},
existing_object_replication: None,
filter: None,
id: None,
prefix: None,
priority: None,
source_selection_criteria: None,
status: "Disabled".to_owned(),
},
],
}
}
fn read_xml(input: &[u8]) -> PersistedReplicationConfiguration {
PersistedReplicationConfiguration::decode_config_xml(input).unwrap()
}
fn read_cache(hex: &str) -> PersistedReplicationConfiguration {
let bytes = hex_simd::decode_to_vec(hex).unwrap();
let cache: ReplicationConfig = rmp_serde::from_slice(&bytes).unwrap();
assert!(cache.remotes.is_none());
assert_eq!(rmp_serde::to_vec(&cache).unwrap(), bytes);
cache.config.unwrap()
}
#[test]
fn full_scanner_cache_keeps_every_member() {
let config = every_member();
assert_eq!(read_cache(ALL_CACHE), config);
let cache = ReplicationConfig::new(Some(config), None);
assert_eq!(rmp_serde::to_vec(&cache).unwrap(), hex_simd::decode_to_vec(ALL_CACHE).unwrap());
}
#[test]
fn bucket_metadata_writes_the_historical_xml_bytes() {
assert_eq!(every_member().encode_config_xml().unwrap(), ALL_XML);
}
#[test]
fn bucket_metadata_reads_every_member_of_the_historical_xml() {
assert_eq!(read_xml(ALL_XML), every_member());
}
#[test]
fn a_tag_without_key_or_value_survives() {
let config = read_xml(KEYLESS_XML);
let tag = config.rules[0].filter.as_ref().unwrap().tag.as_ref().unwrap();
assert_eq!(tag.key, None);
assert_eq!(tag.value, None);
assert_eq!(config.encode_config_xml().unwrap(), KEYLESS_XML);
}
#[test]
fn empty_tag_key_and_value_survive() {
let config = read_xml(EMPTY_KEY_XML);
let tag = config.rules[0].filter.as_ref().unwrap().tag.as_ref().unwrap();
assert_eq!(tag.key.as_deref(), Some(""));
assert_eq!(tag.value.as_deref(), Some(""));
assert_eq!(config.encode_config_xml().unwrap(), EMPTY_KEY_XML);
}
#[test]
fn the_scanner_cache_distinguishes_empty_and_absent_tag_lists() {
for (bytes, expected) in [(EMPTY_TAGS_CACHE, Some(Vec::new())), (ABSENT_TAGS_CACHE, None)] {
let config = read_cache(bytes);
let and = config.rules[0].filter.as_ref().unwrap().and.as_ref().unwrap();
assert_eq!(and.tags, expected);
}
}
#[test]
fn unknown_rule_status_keeps_its_spelling() {
let config = read_xml(LOWERCASE_XML);
assert_eq!(config.rules[0].status, "enabled");
assert_eq!(config.encode_config_xml().unwrap(), LOWERCASE_XML);
}
#[test]
fn a_delete_marker_wrapper_can_lack_status() {
let config = read_xml(MARKER_XML);
assert_eq!(
config.rules[0].delete_marker_replication,
Some(PersistedOptionalReplicationStatus { status: None })
);
assert_eq!(config.encode_config_xml().unwrap(), MARKER_XML);
}
#[test]
fn absent_storage_class_survives() {
let config = read_xml(MINIMAL_XML);
assert_eq!(config.rules[0].destination.storage_class, None);
assert_eq!(config.encode_config_xml().unwrap(), MINIMAL_XML);
}
#[test]
fn bucket_metadata_refuses_historically_invalid_documents() {
let refused: [&[u8]; 7] = [
b"<ReplicationConfiguration><Role></Role><Rule><Future>x</Future><Status>Enabled</Status><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status><Destination><Bucket>b</Bucket><Future>x</Future></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status><Filter><Tag><Key>k</Key><Future>x</Future></Tag></Filter><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status><Priority>high</Priority><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status></Rule></ReplicationConfiguration>",
b"<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>",
];
for input in refused {
assert!(
PersistedReplicationConfiguration::decode_config_xml(input).is_err(),
"{}",
String::from_utf8_lossy(input)
);
}
}
#[test]
fn an_unknown_root_child_is_skipped() {
let input = b"<ReplicationConfiguration><Role></Role><FutureTopLevel>x</FutureTopLevel><Rule><Status>Enabled</Status><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>";
let config = read_xml(input);
assert_eq!(config.rules.len(), 1);
assert_eq!(config.rules[0].destination.bucket, "b");
assert_eq!(config.rules[0].status, "Enabled");
}
-176
View File
@@ -1,176 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The historical GetBucketLifecycleConfiguration output projection used by the XML parity test.
use rustfs_gateway_types::persistence::{PersistedLifecycleConfiguration, PersistedLifecycleRule, PersistedLifecycleTag};
use s3s::dto;
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
#[cfg(test)]
fn date_to_s3s(value: Option<String>) -> std::io::Result<Option<dto::Timestamp>> {
value
.map(|value| {
OffsetDateTime::parse(&value, &Rfc3339)
.map(dto::Timestamp::from)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
})
.transpose()
}
#[cfg(test)]
pub(crate) fn lifecycle_configuration_to_s3s(
value: PersistedLifecycleConfiguration,
) -> std::io::Result<dto::BucketLifecycleConfiguration> {
Ok(dto::BucketLifecycleConfiguration {
expiry_updated_at: date_to_s3s(value.expiry_updated_at)?,
rules: value.rules.into_iter().map(rule_to_s3s).collect::<std::io::Result<_>>()?,
})
}
#[cfg(test)]
fn rule_to_s3s(value: PersistedLifecycleRule) -> std::io::Result<dto::LifecycleRule> {
Ok(dto::LifecycleRule {
abort_incomplete_multipart_upload: value
.abort_incomplete_multipart_upload
.map(|v| dto::AbortIncompleteMultipartUpload {
days_after_initiation: v.days_after_initiation,
}),
del_marker_expiration: value.del_marker_expiration.map(|v| dto::DelMarkerExpiration { days: v.days }),
expiration: value
.expiration
.map(|v| -> std::io::Result<dto::LifecycleExpiration> {
Ok(dto::LifecycleExpiration {
date: date_to_s3s(v.date)?,
days: v.days,
expired_object_all_versions: v.expired_object_all_versions,
expired_object_delete_marker: v.expired_object_delete_marker,
})
})
.transpose()?,
filter: value.filter.map(|v| dto::LifecycleRuleFilter {
and: v.and.map(|v| dto::LifecycleRuleAndOperator {
object_size_greater_than: v.object_size_greater_than,
object_size_less_than: v.object_size_less_than,
prefix: v.prefix,
tags: v.tags.map(|tags| tags.into_iter().map(tag_to_s3s).collect()),
}),
object_size_greater_than: v.object_size_greater_than,
object_size_less_than: v.object_size_less_than,
prefix: v.prefix,
tag: v.tag.map(tag_to_s3s),
cached_tags: Default::default(),
}),
id: value.id,
noncurrent_version_expiration: value.noncurrent_version_expiration.map(|v| dto::NoncurrentVersionExpiration {
newer_noncurrent_versions: v.newer_noncurrent_versions,
noncurrent_days: v.noncurrent_days,
}),
noncurrent_version_transitions: value.noncurrent_version_transitions.map(|values| {
values
.into_iter()
.map(|v| dto::NoncurrentVersionTransition {
newer_noncurrent_versions: v.newer_noncurrent_versions,
noncurrent_days: v.noncurrent_days,
storage_class: v.storage_class.map(Into::into),
})
.collect()
}),
prefix: value.prefix,
status: value.status.into(),
transitions: value
.transitions
.map(|values| {
values
.into_iter()
.map(|v| -> std::io::Result<dto::Transition> {
Ok(dto::Transition {
date: date_to_s3s(v.date)?,
days: v.days,
storage_class: v.storage_class.map(Into::into),
})
})
.collect::<std::io::Result<_>>()
})
.transpose()?,
})
}
#[cfg(test)]
fn tag_to_s3s(value: PersistedLifecycleTag) -> dto::Tag {
dto::Tag {
key: value.key,
value: value.value,
}
}
#[cfg(test)]
mod tests {
use super::lifecycle_configuration_to_s3s;
use crate::app::dto_values::stored_config;
use crate::storage::storage_api::ecstore_bucket::utils::BucketConfigXml;
use rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::get_bucket_lifecycle_configuration::output_to_s3s;
use rustfs_gateway_types::dto as gateway_dto;
use rustfs_gateway_types::persistence::{PersistedLifecycleConfiguration, parse_lifecycle_dto};
use s3s::{dto, xml};
/// Every member the legacy answer carries, the MinIO ones and dates with an offset included.
const STORED: &[u8] = b"<LifecycleConfiguration><Rule><DelMarkerExpiration><Days>7</Days></DelMarkerExpiration>\
<Expiration><Days>30</Days><ExpiredObjectAllVersions>true</ExpiredObjectAllVersions></Expiration><Filter><And><Prefix>logs/\
</Prefix><Tag><Key>tier</Key><Value>cold</Value></Tag><ObjectSizeGreaterThan>1</ObjectSizeGreaterThan></And></Filter>\
<ID>members</ID><NoncurrentVersionExpiration><NoncurrentDays>7</NoncurrentDays><NewerNoncurrentVersions>2\
</NewerNoncurrentVersions></NoncurrentVersionExpiration><NoncurrentVersionTransition><NoncurrentDays>3</NoncurrentDays>\
<StorageClass>WARM</StorageClass></NoncurrentVersionTransition><Status>Enabled</Status><Transition><Days>10</Days>\
<StorageClass>WARM</StorageClass></Transition></Rule><Rule><AbortIncompleteMultipartUpload><DaysAfterInitiation>3\
</DaysAfterInitiation></AbortIncompleteMultipartUpload><Expiration><Date>2099-01-01T00:00:00Z</Date></Expiration><ID>dated\
</ID><Prefix>archive/</Prefix><Status>Disabled</Status><Transition><Date>2098-06-01T08:00:00+08:00</Date><StorageClass>WARM\
</StorageClass></Transition></Rule></LifecycleConfiguration>";
fn s3s_bytes(value: &dto::GetBucketLifecycleConfigurationOutput) -> String {
let mut buf = Vec::new();
xml::Serialize::serialize(value, &mut xml::Serializer::new(&mut buf)).expect("the s3s encoder writes the answer");
String::from_utf8(buf).expect("the s3s encoder writes UTF-8")
}
/// The legacy stack answers a stored configuration through the gateway seam with the bytes it
/// answered through this module's reverse direction.
#[test]
fn the_legacy_answer_through_the_seam_is_the_answer_of_the_reverse_direction() {
let stored = PersistedLifecycleConfiguration::decode_config_xml(STORED).expect("the fixture is a stored document");
let before = dto::GetBucketLifecycleConfigurationOutput {
rules: Some(
lifecycle_configuration_to_s3s(stored.clone())
.expect("reverse direction")
.rules,
),
..Default::default()
};
let answer = gateway_dto::GetBucketLifecycleConfigurationOutput {
rules: stored_config(&stored, parse_lifecycle_dto).expect("gateway answer").rules,
..Default::default()
};
let after = s3s_bytes(&output_to_s3s(answer).expect("seam"));
assert_eq!(after, s3s_bytes(&before));
for member in [
"<DelMarkerExpiration>",
"<ExpiredObjectAllVersions>",
"<Transition>",
"<Date>2098-06-01T",
] {
assert!(after.contains(member), "{member} is missing from {after}");
}
}
}
+1 -3
View File
@@ -12,8 +12,6 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//! Legacy request and configuration conversions used by the compatibility tests. //! Legacy request conversion used by the compatibility tests.
mod envelope; mod envelope;
pub(crate) mod lifecycle;
pub(crate) mod replication;
-524
View File
@@ -1,524 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The s3s edge of the bucket replication configuration.
//!
//! Responsible for: the one conversion between the s3s DTO the legacy S3 stack
//! decodes (`PutBucketReplication`) or encodes (`GetBucketReplication`) and the
//! gateway persistence shape the replication engine, the bucket metadata and
//! site replication work on (`rustfs_gateway_types::persistence`).
//!
//! Not responsible for: validating a configuration (`rustfs-replication`) or
//! storing it (`rustfs-ecstore`).
//!
//! Both directions are total and lossless: every s3s member has a persisted
//! member of the same optionality, and every s3s string enum carries its wire
//! text, so an unknown status or storage class crosses unchanged. The one s3s
//! member without a counterpart, `ReplicationRuleFilter::cached_tags`, is a
//! parse cache with no wire form.
//!
//! Upstream: `storage::ecfs` (`put_bucket_replication`). Downstream:
//! `app::bucket_usecase`, which takes the persistence shape. Answers cross the
//! gateway seam instead; the reverse direction is compiled only as the oracle
//! of this module's tests and goes with the forward one. The gateway HTTP stack retires this edge
//! (T1.8, rustfs/backlog#2749).
use rustfs_gateway_types::persistence::{
PersistedAccessControlTranslation, PersistedEncryptionConfiguration, PersistedOptionalReplicationStatus,
PersistedReplicationAnd, PersistedReplicationConfiguration, PersistedReplicationDestination, PersistedReplicationFilter,
PersistedReplicationMetrics, PersistedReplicationRule, PersistedReplicationStatus, PersistedReplicationTag,
PersistedReplicationTime, PersistedReplicationTimeValue, PersistedSourceSelectionCriteria,
};
use s3s::dto;
/// The decoded `PutBucketReplication` body in the shape the engine stores.
pub(crate) fn replication_configuration_from_s3s(value: dto::ReplicationConfiguration) -> PersistedReplicationConfiguration {
PersistedReplicationConfiguration {
role: value.role,
rules: value.rules.into_iter().map(rule_from_s3s).collect(),
}
}
/// A stored configuration in the shape the s3s encoder takes.
#[cfg(test)]
pub(crate) fn replication_configuration_to_s3s(value: PersistedReplicationConfiguration) -> dto::ReplicationConfiguration {
dto::ReplicationConfiguration {
role: value.role,
rules: value.rules.into_iter().map(rule_to_s3s).collect(),
}
}
/// s3s string enums become their wire text; the persisted shape keeps every
/// value, known or not.
fn status_text(value: &str) -> String {
value.to_owned()
}
fn rule_from_s3s(value: dto::ReplicationRule) -> PersistedReplicationRule {
PersistedReplicationRule {
delete_marker_replication: value
.delete_marker_replication
.map(|wrapper| PersistedOptionalReplicationStatus {
status: wrapper.status.map(|status| status_text(status.as_str())),
}),
delete_replication: value.delete_replication.map(|wrapper| PersistedReplicationStatus {
status: status_text(wrapper.status.as_str()),
}),
destination: destination_from_s3s(value.destination),
existing_object_replication: value.existing_object_replication.map(|wrapper| PersistedReplicationStatus {
status: status_text(wrapper.status.as_str()),
}),
filter: value.filter.map(filter_from_s3s),
id: value.id,
prefix: value.prefix,
priority: value.priority,
source_selection_criteria: value
.source_selection_criteria
.map(|criteria| PersistedSourceSelectionCriteria {
replica_modifications: criteria.replica_modifications.map(|wrapper| PersistedReplicationStatus {
status: status_text(wrapper.status.as_str()),
}),
sse_kms_encrypted_objects: criteria.sse_kms_encrypted_objects.map(|wrapper| PersistedReplicationStatus {
status: status_text(wrapper.status.as_str()),
}),
}),
status: status_text(value.status.as_str()),
}
}
fn destination_from_s3s(value: dto::Destination) -> PersistedReplicationDestination {
PersistedReplicationDestination {
account: value.account,
access_control_translation: value
.access_control_translation
.map(|translation| PersistedAccessControlTranslation {
owner: status_text(translation.owner.as_str()),
}),
bucket: value.bucket,
encryption_configuration: value
.encryption_configuration
.map(|configuration| PersistedEncryptionConfiguration {
replica_kms_key_id: configuration.replica_kms_key_id,
}),
metrics: value.metrics.map(|metrics| PersistedReplicationMetrics {
event_threshold: metrics.event_threshold.map(time_value_from_s3s),
status: status_text(metrics.status.as_str()),
}),
replication_time: value.replication_time.map(|replication_time| PersistedReplicationTime {
status: status_text(replication_time.status.as_str()),
time: time_value_from_s3s(replication_time.time),
}),
storage_class: value.storage_class.map(|class| status_text(class.as_str())),
}
}
fn time_value_from_s3s(value: dto::ReplicationTimeValue) -> PersistedReplicationTimeValue {
PersistedReplicationTimeValue { minutes: value.minutes }
}
fn filter_from_s3s(value: dto::ReplicationRuleFilter) -> PersistedReplicationFilter {
PersistedReplicationFilter {
and: value.and.map(|and| PersistedReplicationAnd {
prefix: and.prefix,
tags: and.tags.map(|tags| tags.into_iter().map(tag_from_s3s).collect()),
}),
prefix: value.prefix,
tag: value.tag.map(tag_from_s3s),
}
}
/// Both members stay optional: a keyless `<Tag/>` (which the console's rule
/// form sends) is a filter the engine reads as absent, not a malformed body.
fn tag_from_s3s(value: dto::Tag) -> PersistedReplicationTag {
PersistedReplicationTag {
key: value.key,
value: value.value,
}
}
#[cfg(test)]
fn rule_to_s3s(value: PersistedReplicationRule) -> dto::ReplicationRule {
dto::ReplicationRule {
delete_marker_replication: value.delete_marker_replication.map(|wrapper| dto::DeleteMarkerReplication {
status: wrapper.status.map(dto::DeleteMarkerReplicationStatus::from),
}),
delete_replication: value.delete_replication.map(|wrapper| dto::DeleteReplication {
status: dto::DeleteReplicationStatus::from(wrapper.status),
}),
destination: destination_to_s3s(value.destination),
existing_object_replication: value
.existing_object_replication
.map(|wrapper| dto::ExistingObjectReplication {
status: dto::ExistingObjectReplicationStatus::from(wrapper.status),
}),
filter: value.filter.map(filter_to_s3s),
id: value.id,
prefix: value.prefix,
priority: value.priority,
source_selection_criteria: value.source_selection_criteria.map(|criteria| dto::SourceSelectionCriteria {
replica_modifications: criteria.replica_modifications.map(|wrapper| dto::ReplicaModifications {
status: dto::ReplicaModificationsStatus::from(wrapper.status),
}),
sse_kms_encrypted_objects: criteria.sse_kms_encrypted_objects.map(|wrapper| dto::SseKmsEncryptedObjects {
status: dto::SseKmsEncryptedObjectsStatus::from(wrapper.status),
}),
}),
status: dto::ReplicationRuleStatus::from(value.status),
}
}
#[cfg(test)]
fn destination_to_s3s(value: PersistedReplicationDestination) -> dto::Destination {
dto::Destination {
access_control_translation: value
.access_control_translation
.map(|translation| dto::AccessControlTranslation {
owner: dto::OwnerOverride::from(translation.owner),
}),
account: value.account,
bucket: value.bucket,
encryption_configuration: value
.encryption_configuration
.map(|configuration| dto::EncryptionConfiguration {
replica_kms_key_id: configuration.replica_kms_key_id,
}),
metrics: value.metrics.map(|metrics| dto::Metrics {
event_threshold: metrics.event_threshold.map(time_value_to_s3s),
status: dto::MetricsStatus::from(metrics.status),
}),
replication_time: value.replication_time.map(|replication_time| dto::ReplicationTime {
status: dto::ReplicationTimeStatus::from(replication_time.status),
time: time_value_to_s3s(replication_time.time),
}),
storage_class: value.storage_class.map(dto::StorageClass::from),
}
}
#[cfg(test)]
fn time_value_to_s3s(value: PersistedReplicationTimeValue) -> dto::ReplicationTimeValue {
dto::ReplicationTimeValue { minutes: value.minutes }
}
#[cfg(test)]
fn filter_to_s3s(value: PersistedReplicationFilter) -> dto::ReplicationRuleFilter {
dto::ReplicationRuleFilter {
and: value.and.map(|and| dto::ReplicationRuleAndOperator {
prefix: and.prefix,
tags: and.tags.map(|tags| tags.into_iter().map(tag_to_s3s).collect()),
}),
prefix: value.prefix,
tag: value.tag.map(tag_to_s3s),
..Default::default()
}
}
#[cfg(test)]
fn tag_to_s3s(value: PersistedReplicationTag) -> dto::Tag {
dto::Tag {
key: value.key,
value: value.value,
}
}
#[cfg(test)]
mod tests {
use super::{replication_configuration_from_s3s, replication_configuration_to_s3s};
use rustfs_gateway_types::persistence::{PersistedReplicationConfiguration, parse_replication, serialize_replication};
use s3s::{dto, xml};
fn s3s_bytes(value: &dto::ReplicationConfiguration) -> Vec<u8> {
let mut buf = Vec::new();
xml::Serialize::serialize(value, &mut xml::Serializer::new(&mut buf)).expect("the s3s encoder writes the fixture");
buf
}
fn tag(key: &str, value: &str) -> dto::Tag {
dto::Tag {
key: Some(key.to_owned()),
value: Some(value.to_owned()),
}
}
/// Every member of the family populated, each string enum carrying a value
/// outside its known set, so a conversion that drops or normalizes one
/// member cannot pass.
fn every_member() -> dto::ReplicationConfiguration {
dto::ReplicationConfiguration {
role: "arn:aws:iam::123456789012:role/replication".to_owned(),
rules: vec![
dto::ReplicationRule {
delete_marker_replication: Some(dto::DeleteMarkerReplication {
status: Some(dto::DeleteMarkerReplicationStatus::from("FutureDeleteMarker".to_owned())),
}),
delete_replication: Some(dto::DeleteReplication {
status: dto::DeleteReplicationStatus::from("FutureDelete".to_owned()),
}),
destination: dto::Destination {
access_control_translation: Some(dto::AccessControlTranslation {
owner: dto::OwnerOverride::from("FutureOwner".to_owned()),
}),
account: Some("123456789012".to_owned()),
bucket: "arn:aws:s3:::backup".to_owned(),
encryption_configuration: Some(dto::EncryptionConfiguration {
replica_kms_key_id: Some("kms-key".to_owned()),
}),
metrics: Some(dto::Metrics {
event_threshold: Some(dto::ReplicationTimeValue { minutes: Some(15) }),
status: dto::MetricsStatus::from("FutureMetrics".to_owned()),
}),
replication_time: Some(dto::ReplicationTime {
status: dto::ReplicationTimeStatus::from("FutureRtc".to_owned()),
time: dto::ReplicationTimeValue { minutes: Some(30) },
}),
storage_class: Some(dto::StorageClass::from("FutureClass".to_owned())),
},
existing_object_replication: Some(dto::ExistingObjectReplication {
status: dto::ExistingObjectReplicationStatus::from("FutureExisting".to_owned()),
}),
filter: Some(dto::ReplicationRuleFilter {
and: Some(dto::ReplicationRuleAndOperator {
prefix: Some("docs/".to_owned()),
tags: Some(vec![tag("team", "storage"), tag("tier", "gold")]),
}),
prefix: Some("filter/".to_owned()),
tag: Some(tag("env", "prod")),
..Default::default()
}),
id: Some("every-member".to_owned()),
prefix: Some("legacy/".to_owned()),
priority: Some(7),
source_selection_criteria: Some(dto::SourceSelectionCriteria {
replica_modifications: Some(dto::ReplicaModifications {
status: dto::ReplicaModificationsStatus::from("FutureReplica".to_owned()),
}),
sse_kms_encrypted_objects: Some(dto::SseKmsEncryptedObjects {
status: dto::SseKmsEncryptedObjectsStatus::from("FutureKms".to_owned()),
}),
}),
status: dto::ReplicationRuleStatus::from("FutureRule".to_owned()),
},
rule("arn:aws:s3:::second", dto::ReplicationRuleStatus::DISABLED),
],
}
}
/// A rule with only its required members.
fn rule(bucket: &str, status: &'static str) -> dto::ReplicationRule {
dto::ReplicationRule {
delete_marker_replication: None,
delete_replication: None,
destination: dto::Destination {
bucket: bucket.to_owned(),
..Default::default()
},
existing_object_replication: None,
filter: None,
id: None,
prefix: None,
priority: None,
source_selection_criteria: None,
status: dto::ReplicationRuleStatus::from_static(status),
}
}
fn one_filter(filter: dto::ReplicationRuleFilter) -> dto::ReplicationConfiguration {
let mut rule = rule("arn:aws:s3:::backup", dto::ReplicationRuleStatus::ENABLED);
rule.filter = Some(filter);
dto::ReplicationConfiguration {
role: String::new(),
rules: vec![rule],
}
}
#[test]
fn every_member_crosses_to_the_engine_and_back_unchanged() {
let crossed = replication_configuration_to_s3s(replication_configuration_from_s3s(every_member()));
assert_eq!(crossed, every_member());
}
#[test]
fn the_engine_shape_persists_the_bytes_the_s3s_encoder_wrote() {
let persisted = serialize_replication(&replication_configuration_from_s3s(every_member()))
.expect("the gateway writer accepts the converted configuration");
assert_eq!(String::from_utf8_lossy(&persisted), String::from_utf8_lossy(&s3s_bytes(&every_member())));
}
#[test]
fn stored_bytes_answer_the_s3s_get_unchanged() {
let stored = parse_replication(&s3s_bytes(&every_member())).expect("the gateway parser reads what s3s wrote");
assert_eq!(replication_configuration_to_s3s(stored), every_member());
}
#[test]
fn a_keyless_tag_stays_keyless_instead_of_becoming_an_empty_key() {
let config = replication_configuration_from_s3s(one_filter(dto::ReplicationRuleFilter {
tag: Some(dto::Tag { key: None, value: None }),
..Default::default()
}));
let tag = config.rules[0]
.filter
.as_ref()
.and_then(|filter| filter.tag.as_ref())
.expect("the keyless tag is kept, not dropped");
assert_eq!(tag.key, None);
assert_eq!(tag.value, None);
}
#[test]
fn an_empty_tag_key_stays_an_empty_key_instead_of_becoming_absent() {
let config = replication_configuration_from_s3s(one_filter(dto::ReplicationRuleFilter {
tag: Some(tag("", "")),
..Default::default()
}));
let tag = config.rules[0].filter.as_ref().and_then(|filter| filter.tag.as_ref());
assert_eq!(tag.and_then(|tag| tag.key.as_deref()), Some(""));
assert_eq!(tag.and_then(|tag| tag.value.as_deref()), Some(""));
}
#[test]
fn an_empty_and_tag_list_stays_distinct_from_an_absent_one() {
let empty = replication_configuration_from_s3s(one_filter(dto::ReplicationRuleFilter {
and: Some(dto::ReplicationRuleAndOperator {
prefix: None,
tags: Some(Vec::new()),
}),
..Default::default()
}));
let absent = replication_configuration_from_s3s(one_filter(dto::ReplicationRuleFilter {
and: Some(dto::ReplicationRuleAndOperator {
prefix: None,
tags: None,
}),
..Default::default()
}));
let tags = |config: &PersistedReplicationConfiguration| {
config.rules[0]
.filter
.as_ref()
.and_then(|filter| filter.and.as_ref())
.map(|and| and.tags.clone())
};
assert_eq!(tags(&empty), Some(Some(Vec::new())));
assert_eq!(tags(&absent), Some(None));
}
#[test]
fn an_unknown_status_keeps_its_text_so_the_capability_gate_still_sees_it() {
let mut source = one_filter(dto::ReplicationRuleFilter::default());
source.rules[0].status = dto::ReplicationRuleStatus::from("enabled".to_owned());
let config = replication_configuration_from_s3s(source);
assert_eq!(
config.rules[0].status, "enabled",
"a lowercase status must reach the capability gate as sent, not normalized into a valid one"
);
let back = replication_configuration_to_s3s(config);
assert_eq!(back.rules[0].status.as_str(), "enabled");
}
#[test]
fn a_delete_marker_wrapper_without_status_stays_without_status() {
let mut source = one_filter(dto::ReplicationRuleFilter::default());
source.rules[0].delete_marker_replication = Some(dto::DeleteMarkerReplication { status: None });
let config = replication_configuration_from_s3s(source);
let wrapper = config.rules[0]
.delete_marker_replication
.as_ref()
.expect("the empty wrapper is kept");
assert_eq!(wrapper.status, None);
let back = replication_configuration_to_s3s(config);
assert_eq!(
back.rules[0].delete_marker_replication,
Some(dto::DeleteMarkerReplication { status: None })
);
}
#[test]
fn an_absent_storage_class_is_not_defaulted() {
let config = replication_configuration_from_s3s(one_filter(dto::ReplicationRuleFilter::default()));
assert_eq!(config.rules[0].destination.storage_class, None);
let back = replication_configuration_to_s3s(config);
assert_eq!(back.rules[0].destination.storage_class, None);
}
fn s3s_reads(input: &[u8]) -> bool {
let mut deserializer = xml::Deserializer::new(input);
<dto::ReplicationConfiguration as xml::Deserialize>::deserialize(&mut deserializer).is_ok()
&& deserializer.expect_eof().is_ok()
}
/// The persisted reader the engine now uses is no more permissive than the
/// s3s reader it replaces: every document s3s refused stays refused.
#[test]
fn the_gateway_reader_refuses_what_the_s3s_reader_refused() {
let refused: [&[u8]; 7] = [
b"<ReplicationConfiguration><Role></Role><Rule><Future>x</Future><Status>Enabled</Status><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status><Destination><Bucket>b</Bucket><Future>x</Future></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status><Filter><Tag><Key>k</Key><Future>x</Future></Tag></Filter><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status><Priority>high</Priority><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status></Rule></ReplicationConfiguration>",
b"<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>",
];
for input in refused {
let text = String::from_utf8_lossy(input);
assert!(!s3s_reads(input), "fixture is not a document s3s refuses: {text}");
assert!(parse_replication(input).is_err(), "the gateway reader accepted what s3s refused: {text}");
}
}
/// The other direction: a root-level element neither reader knows is
/// skipped by both, so the gateway reader is no stricter either.
#[test]
fn both_readers_skip_an_unknown_root_level_element() {
let input: &[u8] = b"<ReplicationConfiguration><Role></Role><FutureTopLevel>x</FutureTopLevel><Rule><Status>Enabled</Status><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>";
assert!(s3s_reads(input));
let stored = parse_replication(input).expect("the gateway reader skips the unknown root element");
assert_eq!(stored.rules.len(), 1);
}
/// Every member the legacy answer carries, the MinIO one included.
const STORED: &[u8] = b"<ReplicationConfiguration><Role>arn:minio:replication::id:target</Role><Rule>\
<DeleteMarkerReplication><Status>Enabled</Status></DeleteMarkerReplication><DeleteReplication><Status>Enabled</Status>\
</DeleteReplication><Destination><Bucket>arn:aws:s3:::dest</Bucket><StorageClass>STANDARD</StorageClass></Destination>\
<ExistingObjectReplication><Status>Enabled</Status></ExistingObjectReplication><Filter><And><Prefix>a/</Prefix><Tag><Key>k\
</Key><Value>v</Value></Tag></And></Filter><ID>r1</ID><Priority>1</Priority><SourceSelectionCriteria><ReplicaModifications>\
<Status>Enabled</Status></ReplicaModifications></SourceSelectionCriteria><Status>Enabled</Status></Rule>\
</ReplicationConfiguration>";
/// The legacy stack answers a stored configuration through the gateway seam with the bytes it
/// answered through this module's reverse direction.
#[test]
fn the_legacy_answer_through_the_seam_is_the_answer_of_the_reverse_direction() {
use crate::app::dto_values::stored_config;
use rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::get_bucket_replication::output_to_s3s;
use rustfs_gateway_types::persistence::parse_replication_dto;
let stored = parse_replication(STORED).expect("the fixture is a stored document");
let before = s3s_bytes(&replication_configuration_to_s3s(stored.clone()));
let answer = rustfs_gateway_types::dto::GetBucketReplicationOutput {
replication_configuration: Some(stored_config(&stored, parse_replication_dto).expect("gateway answer")),
};
let after = output_to_s3s(answer)
.expect("seam")
.replication_configuration
.expect("a configuration");
let after = s3s_bytes(&after);
assert_eq!(String::from_utf8_lossy(&after), String::from_utf8_lossy(&before));
for member in ["<DeleteReplication>", "<ExistingObjectReplication>", "<ReplicaModifications>"] {
assert!(String::from_utf8_lossy(&after).contains(member), "{member} is missing");
}
}
}
-61
View File
@@ -2544,67 +2544,6 @@ pub(crate) fn set_tonic_canonical_body_digest<T>(request: &mut tonic::Request<T>
ecstore_rpc::set_tonic_canonical_body_digest(request, canonical_body) ecstore_rpc::set_tonic_canonical_body_digest(request, canonical_body)
} }
/// Convert a raw stored ETag into the strongly-typed `s3s::dto::ETag`.
///
/// Supports already quoted (`"abc"`), weak (`W/"abc"`), or plain (`abc`) values.
pub(crate) fn to_s3s_etag(etag: &str) -> s3s::dto::ETag {
use s3s::dto::ETag;
if let Some(rest) = etag.strip_prefix("W/\"") {
if let Some(body) = rest.strip_suffix('"') {
return ETag::Weak(body.to_string());
}
return ETag::Weak(rest.to_string());
}
if let Some(body) = etag.strip_prefix('"').and_then(|rest| rest.strip_suffix('"')) {
return ETag::Strong(body.to_string());
}
ETag::Strong(etag.to_string())
}
#[cfg(test)]
mod to_s3s_etag_tests {
use super::to_s3s_etag;
use s3s::dto::ETag;
#[test]
fn test_to_s3s_etag() {
// Test unquoted ETag - should become strong etag
assert_eq!(
to_s3s_etag("6af8d12c0c74b78094884349f3c8a079"),
ETag::Strong("6af8d12c0c74b78094884349f3c8a079".to_string())
);
assert_eq!(
to_s3s_etag("\"6af8d12c0c74b78094884349f3c8a079\""),
ETag::Strong("6af8d12c0c74b78094884349f3c8a079".to_string())
);
assert_eq!(
to_s3s_etag("W/\"6af8d12c0c74b78094884349f3c8a079\""),
ETag::Weak("6af8d12c0c74b78094884349f3c8a079".to_string())
);
assert_eq!(to_s3s_etag(""), ETag::Strong(String::new()));
assert_eq!(to_s3s_etag("\"incomplete"), ETag::Strong("\"incomplete".to_string()));
assert_eq!(to_s3s_etag("incomplete\""), ETag::Strong("incomplete\"".to_string()));
}
}
/// The pinned s3s XML serializer writes ETag values as raw text. Escape only
/// at XML response boundaries; HTTP headers and conditional comparisons keep
/// the original stored value. Existing unsafe ETags must remain listable.
pub(crate) fn to_s3s_xml_etag(etag: &str) -> s3s::dto::ETag {
let mut etag = to_s3s_etag(etag);
let (s3s::dto::ETag::Strong(value) | s3s::dto::ETag::Weak(value)) = &mut etag;
*value = quick_xml::escape::escape(value.as_str()).into_owned();
etag
}
pub(crate) fn table_catalog_path_hash(value: &str) -> String { pub(crate) fn table_catalog_path_hash(value: &str) -> String {
ecstore_bucket::metadata::table_catalog_path_hash(value) ecstore_bucket::metadata::table_catalog_path_hash(value)
} }
@@ -255,9 +255,78 @@ async fn the_configuration_reads_answer_what_is_stored(server: RustFSServer) {
assert_answers_what_is_stored(&root, bucket).await; assert_answers_what_is_stored(&root, bucket).await;
} }
assert_stored_configuration_wire(&server).await;
server.shutdown().await; server.shutdown().await;
} }
async fn assert_stored_configuration_wire(server: &RustFSServer) {
use super::object_write::WireClient;
const LIFECYCLE_INPUT: &[u8] = b"<LifecycleConfiguration><Rule><DelMarkerExpiration><Days>7</Days></DelMarkerExpiration>\
<Expiration><Days>30</Days><ExpiredObjectAllVersions>true</ExpiredObjectAllVersions></Expiration><Filter><And><Prefix>logs/\
</Prefix><Tag><Key>tier</Key><Value>cold</Value></Tag><ObjectSizeGreaterThan>1</ObjectSizeGreaterThan></And></Filter>\
<ID>members</ID><NoncurrentVersionExpiration><NoncurrentDays>7</NoncurrentDays><NewerNoncurrentVersions>2\
</NewerNoncurrentVersions></NoncurrentVersionExpiration><NoncurrentVersionTransition><NoncurrentDays>3</NoncurrentDays>\
<StorageClass>WARM</StorageClass></NoncurrentVersionTransition><Status>Enabled</Status><Transition><Days>10</Days>\
<StorageClass>WARM</StorageClass></Transition></Rule><Rule><AbortIncompleteMultipartUpload><DaysAfterInitiation>3\
</DaysAfterInitiation></AbortIncompleteMultipartUpload><Expiration><Date>2099-01-01T00:00:00Z</Date></Expiration><ID>dated\
</ID><Prefix>archive/</Prefix><Status>Disabled</Status><Transition><Date>2098-06-01T08:00:00+08:00</Date><StorageClass>WARM\
</StorageClass></Transition></Rule></LifecycleConfiguration>";
const REPLICATION_INPUT: &[u8] = b"<ReplicationConfiguration><Role>arn:minio:replication::id:target</Role><Rule>\
<DeleteMarkerReplication><Status>Enabled</Status></DeleteMarkerReplication><DeleteReplication><Status>Enabled</Status>\
</DeleteReplication><Destination><Bucket>arn:aws:s3:::dest</Bucket><StorageClass>STANDARD</StorageClass></Destination>\
<ExistingObjectReplication><Status>Enabled</Status></ExistingObjectReplication><Filter><And><Prefix>a/</Prefix><Tag><Key>k\
</Key><Value>v</Value></Tag></And></Filter><ID>r1</ID><Priority>1</Priority><SourceSelectionCriteria><ReplicaModifications>\
<Status>Enabled</Status></ReplicaModifications></SourceSelectionCriteria><Status>Enabled</Status></Rule>\
</ReplicationConfiguration>";
// Complete GET response bodies captured from the pinned legacy HTTP service.
const LIFECYCLE_RESPONSE: &[u8] =
b"<?xml version=\"1.0\" encoding=\"UTF-8\"?><LifecycleConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\
<Rule><DelMarkerExpiration><Days>7</Days></DelMarkerExpiration><Expiration><Days>30</Days>\
<ExpiredObjectAllVersions>true</ExpiredObjectAllVersions></Expiration><Filter><And><ObjectSizeGreaterThan>1\
</ObjectSizeGreaterThan><Prefix>logs/</Prefix><Tag><Key>tier</Key><Value>cold</Value></Tag></And></Filter>\
<ID>members</ID><NoncurrentVersionExpiration><NewerNoncurrentVersions>2</NewerNoncurrentVersions>\
<NoncurrentDays>7</NoncurrentDays></NoncurrentVersionExpiration><NoncurrentVersionTransition><NoncurrentDays>3\
</NoncurrentDays><StorageClass>WARM</StorageClass></NoncurrentVersionTransition><Status>Enabled</Status>\
<Transition><Days>10</Days><StorageClass>WARM</StorageClass></Transition></Rule><Rule>\
<AbortIncompleteMultipartUpload><DaysAfterInitiation>3</DaysAfterInitiation></AbortIncompleteMultipartUpload>\
<Expiration><Date>2099-01-01T00:00:00.000Z</Date></Expiration><ID>dated</ID><Prefix>archive/</Prefix>\
<Status>Disabled</Status><Transition><Date>2098-06-01T08:00:00.000Z</Date><StorageClass>WARM</StorageClass>\
</Transition></Rule></LifecycleConfiguration>";
const REPLICATION_RESPONSE: &[u8] =
b"<?xml version=\"1.0\" encoding=\"UTF-8\"?><ReplicationConfiguration><Role>arn:minio:replication::id:target</Role>\
<Rule><DeleteMarkerReplication><Status>Enabled</Status></DeleteMarkerReplication><DeleteReplication>\
<Status>Enabled</Status></DeleteReplication><Destination><Bucket>arn:aws:s3:::dest</Bucket>\
<StorageClass>STANDARD</StorageClass></Destination><ExistingObjectReplication><Status>Enabled</Status>\
</ExistingObjectReplication><Filter><And><Prefix>a/</Prefix><Tag><Key>k</Key><Value>v</Value></Tag></And>\
</Filter><ID>r1</ID><Priority>1</Priority><SourceSelectionCriteria><ReplicaModifications><Status>Enabled\
</Status></ReplicaModifications></SourceSelectionCriteria><Status>Enabled</Status></Rule>\
</ReplicationConfiguration>";
let bucket = "a3-stored-wire";
create_bucket_in_the_store(bucket).await;
let endpoint = server.endpoint();
let client = WireClient {
endpoint: &endpoint,
access_key: server.access_key(),
secret_key: server.secret_key(),
};
for (file, query, stored, expected) in [
(BUCKET_LIFECYCLE_CONFIG, "lifecycle", LIFECYCLE_INPUT, LIFECYCLE_RESPONSE),
(BUCKET_REPLICATION_CONFIG, "replication", REPLICATION_INPUT, REPLICATION_RESPONSE),
] {
metadata_sys::update(bucket, file, stored.to_vec())
.await
.expect("seed stored configuration");
let response = client.request("GET", &format!("/{bucket}?{query}"), &[], &[], Some(0)).await;
assert_eq!(response.status, 200, "{query}: {}", response.body);
assert_eq!(response.headers["content-type"], "application/xml", "{query}");
assert_eq!(response.body.as_bytes(), expected, "{query}");
}
}
async fn assert_answers_what_is_stored(root: &Client, bucket: &str) { async fn assert_answers_what_is_stored(root: &Client, bucket: &str) {
let lifecycle = root let lifecycle = root
.get_bucket_lifecycle_configuration() .get_bucket_lifecycle_configuration()
+38 -1
View File
@@ -13,6 +13,42 @@ def replace_once(source, old, new, path):
return source.replace(old, new) return source.replace(old, new)
# The original application entry point on the pre-conditional-read baseline.
# Keep scenario generation, timing, response validation, and metrics in the shared harness.
BASELINE_GET_API = """mod get_api {
use super::*;
pub(super) async fn get(
usecase: &DefaultObjectUsecase,
object: &str,
headers: HeaderMap,
) -> S3Result<S3Response<GetObjectOutput>> {
let input = GetObjectInput::builder()
.bucket("conditional-bench".to_owned())
.key(object.to_owned())
.build()
.expect("benchmark input");
let mut request = build_request(input, http::Method::GET);
request.headers = headers;
usecase.execute_get_object(request).await
}
pub(super) async fn consume(mut body: StreamingBlob, actual: &mut Vec<u8>) {
while let Some(chunk) = body.next().await {
actual.extend_from_slice(&chunk.expect("benchmark body chunk"));
}
}
}"""
def baseline_harness(source):
harness, count = re.subn(r"^mod get_api \{\n.*?^\}", lambda _: BASELINE_GET_API,
source, flags=re.MULTILINE | re.DOTALL)
if count != 1:
raise ValueError("expected one GET adapter module in the shared benchmark harness")
return harness
def prepare(root, baseline, revision): def prepare(root, baseline, revision):
if baseline.resolve() == root.resolve(): if baseline.resolve() == root.resolve():
raise ValueError("baseline must be a separate worktree") raise ValueError("baseline must be a separate worktree")
@@ -56,7 +92,8 @@ def prepare(root, baseline, revision):
"crates/ecstore/src/set_disk/conditional_read_bench.rs"): "crates/ecstore/src/set_disk/conditional_read_bench.rs"):
if (baseline / path).exists(): if (baseline / path).exists():
raise ValueError(f"baseline already contains {path}") raise ValueError(f"baseline already contains {path}")
edits[path] = (root / path).read_text() harness = (root / path).read_text()
edits[path] = baseline_harness(harness) if path.startswith("rustfs/") else harness
# Resolve every anchor before writing; never apply a partial adapter. # Resolve every anchor before writing; never apply a partial adapter.
for path, source in edits.items(): for path, source in edits.items():
(baseline / path).write_text(source) (baseline / path).write_text(source)