mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-25 17:54:58 +00:00
test(e2e): serve programmable remote faults through the native gateway
This commit is contained in:
Generated
+12
-9
@@ -4277,6 +4277,9 @@ dependencies = [
|
||||
"rustfs-data-usage",
|
||||
"rustfs-ecstore",
|
||||
"rustfs-filemeta",
|
||||
"rustfs-gateway",
|
||||
"rustfs-gateway-stream",
|
||||
"rustfs-gateway-types",
|
||||
"rustfs-heal",
|
||||
"rustfs-lock",
|
||||
"rustfs-madmin",
|
||||
@@ -10396,7 +10399,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway"
|
||||
version = "0.66.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=5ea2ef14a1e7bd9e8025c7327ff65d8c86445864#5ea2ef14a1e7bd9e8025c7327ff65d8c86445864"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
@@ -10443,7 +10446,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-core"
|
||||
version = "0.63.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=5ea2ef14a1e7bd9e8025c7327ff65d8c86445864#5ea2ef14a1e7bd9e8025c7327ff65d8c86445864"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
@@ -10464,7 +10467,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-dialect-rustfs-admin"
|
||||
version = "0.13.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=5ea2ef14a1e7bd9e8025c7327ff65d8c86445864#5ea2ef14a1e7bd9e8025c7327ff65d8c86445864"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"form_urlencoded",
|
||||
@@ -10478,7 +10481,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-http"
|
||||
version = "0.1.4"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=5ea2ef14a1e7bd9e8025c7327ff65d8c86445864#5ea2ef14a1e7bd9e8025c7327ff65d8c86445864"
|
||||
dependencies = [
|
||||
"hmac 0.13.0",
|
||||
"http 1.5.0",
|
||||
@@ -10496,7 +10499,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-macros"
|
||||
version = "0.1.4"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=5ea2ef14a1e7bd9e8025c7327ff65d8c86445864#5ea2ef14a1e7bd9e8025c7327ff65d8c86445864"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -10506,7 +10509,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-sig"
|
||||
version = "0.15.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=5ea2ef14a1e7bd9e8025c7327ff65d8c86445864#5ea2ef14a1e7bd9e8025c7327ff65d8c86445864"
|
||||
dependencies = [
|
||||
"hmac 0.13.0",
|
||||
"http 1.5.0",
|
||||
@@ -10521,7 +10524,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-stream"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=5ea2ef14a1e7bd9e8025c7327ff65d8c86445864#5ea2ef14a1e7bd9e8025c7327ff65d8c86445864"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytes",
|
||||
@@ -10532,7 +10535,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-types"
|
||||
version = "0.42.0+aws.2026-10-02"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=5ea2ef14a1e7bd9e8025c7327ff65d8c86445864#5ea2ef14a1e7bd9e8025c7327ff65d8c86445864"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"crc-fast",
|
||||
@@ -10555,7 +10558,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-xml"
|
||||
version = "0.4.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=5ea2ef14a1e7bd9e8025c7327ff65d8c86445864#5ea2ef14a1e7bd9e8025c7327ff65d8c86445864"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
]
|
||||
|
||||
+6
-6
@@ -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
|
||||
# gateway in this workspace; no crate may enable a `compat-s3s*` feature except
|
||||
# the s3s-facing edge of the rustfs binary.
|
||||
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 = "1c7486f1113769f643144d635ede30520e735141", version = "0.2.0", default-features = false }
|
||||
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", version = "0.42.0", default-features = false }
|
||||
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", version = "0.2.0", default-features = false }
|
||||
# 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
|
||||
# server crate, out of the build.
|
||||
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", version = "0.66.0", default-features = false }
|
||||
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", version = "0.66.0", default-features = false }
|
||||
# Test-only: builds the `EffectiveHost` a host-resolution test queries with.
|
||||
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 = "1c7486f1113769f643144d635ede30520e735141", version = "0.63.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 }
|
||||
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", default-features = false }
|
||||
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", version = "0.63.0", default-features = false }
|
||||
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", version = "0.13.0", default-features = false }
|
||||
|
||||
# Async Runtime and Networking
|
||||
async-channel = "2.5.0"
|
||||
|
||||
@@ -138,6 +138,9 @@ rustls = { workspace = true, default-features = false, features = ["aws-lc-rs",
|
||||
clap = { workspace = true, features = ["derive", "env"] }
|
||||
|
||||
[dev-dependencies]
|
||||
rustfs-gateway.workspace = true
|
||||
rustfs-gateway-types.workspace = true
|
||||
rustfs-gateway-stream.workspace = true
|
||||
serde-value.workspace = true
|
||||
s3s = { workspace = true, features = ["minio"] }
|
||||
s3s-sigv4.workspace = true
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Programmable fake S3 target
|
||||
|
||||
This module is the shared failure-injection boundary for replication end-to-end tests and the programmable external source for on-demand-migration (ODM) tests. It runs an in-process, path-style S3 endpoint backed by `s3s`; no production crate depends on it.
|
||||
This module is the shared failure-injection boundary for replication end-to-end tests and the programmable external source for on-demand-migration (ODM) tests. It runs an in-process, path-style S3 endpoint with the RustFS gateway and an in-memory store.
|
||||
|
||||
`FakeS3Target::start()` creates the listener. Add target buckets with `create_bucket`, point a RustFS remote target at `address()`, use `FAKE_ACCESS_KEY` / `FAKE_SECRET_KEY`, then enqueue per-operation faults with `inject`. Faults for one operation are consumed in FIFO order and do not consume faults queued for another operation. A fault is consumed only after `s3s` verifies the full request signature, so anonymous, other-access-key, and bad-signature traffic cannot disturb a script.
|
||||
`FakeS3Target::start()` creates the listener. Add target buckets with `create_bucket`, point a RustFS remote target at `address()`, use `FAKE_ACCESS_KEY` / `FAKE_SECRET_KEY`, then enqueue per-operation faults with `inject`. Faults for one operation are consumed in FIFO order and do not consume faults queued for another operation. A fault is consumed only after the gateway verifies the request signature, so anonymous, other-access-key, and bad-signature traffic cannot disturb a script.
|
||||
|
||||
Supported data operations are HeadBucket, GetBucketVersioning, ListObjectsV2, PUT/GET/HEAD/DELETE Object, Get/Put/Delete ObjectTagging (tags live per version; Put replaces the whole set, Delete clears it), and create/upload/complete/abort multipart upload. `create_bucket` models general-purpose buckets in S3's shared global namespace; account-regional namespace buckets and their `-an` names are intentionally out of scope. Buckets created with `create_bucket` are versioned: PUT creates a version, DELETE without `versionId` creates a delete marker, and DELETE with `versionId` removes exactly that version. Internal source version IDs must be UUIDs and are stored canonically. Source mtime is honored only for source-replication PUT/DELETE requests; absent or invalid values use receipt time, matching RustFS, while multipart completion always uses receipt time. Replicated versions are ordered newest-first by source mtime so late older versions and delete markers do not become current. Equal mtimes prefer objects over delete markers, then canonical UUID order; RustFS's internal FileMeta signature tie-break is intentionally out of scope because it is not part of the target S3 protocol. Multipart part numbers follow S3's `1..=10000` range, and every completed part except the final part must be at least 5 MiB.
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
// 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.
|
||||
|
||||
use super::*;
|
||||
use rustfs_gateway::{ETag, ObjectKey, dto};
|
||||
|
||||
impl FakeBackend {
|
||||
pub(super) async fn head_bucket(
|
||||
&self,
|
||||
req: TargetRequest<dto::HeadBucketInput>,
|
||||
) -> S3Result<TargetResponse<dto::HeadBucketOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
if !lock(&self.store).buckets.contains_key(req.input.bucket.as_str()) {
|
||||
return Err(s3_error!(NoSuchBucket, "bucket does not exist"));
|
||||
}
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::HeadBucketOutput::default()),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn get_bucket_versioning(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetBucketVersioningInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetBucketVersioningOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let versioned = lock(&self.store)
|
||||
.buckets
|
||||
.get(req.input.bucket.as_str())
|
||||
.map(|bucket| bucket.versioned)
|
||||
.ok_or_else(|| s3_error!(NoSuchBucket, "bucket does not exist"))?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::GetBucketVersioningOutput {
|
||||
status: versioned.then_some(dto::Status::ENABLED),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn get_object_lock_configuration(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetObjectLockConfigurationInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetObjectLockConfigurationOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let object_lock = lock(&self.store)
|
||||
.buckets
|
||||
.get(req.input.bucket.as_str())
|
||||
.map(|bucket| bucket.object_lock)
|
||||
.ok_or_else(|| s3_error!(NoSuchBucket, "bucket does not exist"))?;
|
||||
if !object_lock {
|
||||
return Err(s3_error!(
|
||||
ObjectLockConfigurationNotFoundError,
|
||||
"Object Lock configuration does not exist for this bucket"
|
||||
));
|
||||
}
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::GetObjectLockConfigurationOutput {
|
||||
object_lock_configuration: Some(dto::ObjectLockConfiguration {
|
||||
object_lock_enabled: Some(dto::ObjectLockEnabled::ENABLED),
|
||||
..Default::default()
|
||||
}),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Current versions only (a key whose newest version is a delete marker
|
||||
/// is hidden), keys in byte order, `delimiter` folding into common
|
||||
/// prefixes that count toward `max-keys`, and `start-after` /
|
||||
/// `continuation-token` cursors. `encoding-type` and `fetch-owner` are
|
||||
/// accepted but ignored.
|
||||
pub(super) async fn list_objects_v2(
|
||||
&self,
|
||||
req: TargetRequest<dto::ListObjectsV2Input>,
|
||||
) -> S3Result<TargetResponse<dto::ListObjectsV2Output>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let prefix = input.prefix.unwrap_or_default();
|
||||
let delimiter = input.delimiter.as_deref().filter(|delimiter| !delimiter.is_empty());
|
||||
let max_keys = input.max_keys.unwrap_or(MAX_LIST_KEYS).clamp(0, MAX_LIST_KEYS);
|
||||
let resume_after = input
|
||||
.continuation_token
|
||||
.as_ref()
|
||||
.map(|token| decode_continuation_token(token.as_str()))
|
||||
.transpose()?;
|
||||
let mut cursors = Vec::with_capacity(2);
|
||||
if let Some(start_after) = input.start_after.as_deref() {
|
||||
cursors.push(ListCursor {
|
||||
after: start_after,
|
||||
skips_group: false,
|
||||
});
|
||||
}
|
||||
if let Some(resume_after) = resume_after.as_deref() {
|
||||
cursors.push(ListCursor {
|
||||
after: resume_after,
|
||||
skips_group: delimiter.is_some_and(|delimiter| resume_after.ends_with(delimiter)),
|
||||
});
|
||||
}
|
||||
let page = {
|
||||
let state = lock(&self.store);
|
||||
let bucket_state = state
|
||||
.buckets
|
||||
.get(input.bucket.as_str())
|
||||
.ok_or_else(|| s3_error!(NoSuchBucket, "bucket does not exist"))?;
|
||||
list_page(
|
||||
bucket_state,
|
||||
&prefix,
|
||||
delimiter,
|
||||
&cursors,
|
||||
usize::try_from(max_keys).map_err(S3Error::internal_error)?,
|
||||
)
|
||||
};
|
||||
let next_continuation_token = page
|
||||
.truncated
|
||||
.then(|| {
|
||||
page.entries
|
||||
.last()
|
||||
.map(|entry| encode_continuation_token(entry.name()).into())
|
||||
})
|
||||
.flatten();
|
||||
let key_count = i32::try_from(page.entries.len()).map_err(S3Error::internal_error)?;
|
||||
let mut contents = Vec::new();
|
||||
let mut common_prefixes = Vec::new();
|
||||
for entry in page.entries {
|
||||
match entry {
|
||||
ListEntry::Object {
|
||||
key,
|
||||
e_tag,
|
||||
last_modified,
|
||||
size,
|
||||
} => contents.push(dto::Object {
|
||||
key: ObjectKey::new(key).map_err(S3Error::internal_error)?,
|
||||
e_tag: Some(ETag::from_stored(e_tag)),
|
||||
last_modified,
|
||||
size: i64::try_from(size).map_err(S3Error::internal_error)?,
|
||||
storage_class: dto::StorageClass::STANDARD,
|
||||
..Default::default()
|
||||
}),
|
||||
ListEntry::CommonPrefix(prefix) => common_prefixes.push(dto::CommonPrefix { prefix }),
|
||||
}
|
||||
}
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::ListObjectsV2Output {
|
||||
name: input.bucket,
|
||||
prefix,
|
||||
delimiter: input.delimiter,
|
||||
max_keys,
|
||||
key_count,
|
||||
continuation_token: input.continuation_token,
|
||||
start_after: input.start_after,
|
||||
encoding_type: input.encoding_type,
|
||||
is_truncated: page.truncated,
|
||||
next_continuation_token,
|
||||
contents,
|
||||
common_prefixes,
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Prefix + max-keys subset only — enough for the replication-check probe
|
||||
/// key allocation. No pagination markers or delimiter folding.
|
||||
pub(super) async fn list_object_versions(
|
||||
&self,
|
||||
req: TargetRequest<dto::ListObjectVersionsInput>,
|
||||
) -> S3Result<TargetResponse<dto::ListObjectVersionsOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let state = lock(&self.store);
|
||||
let Some(bucket_state) = state.buckets.get(req.input.bucket.as_str()) else {
|
||||
return Err(s3_error!(NoSuchBucket, "bucket does not exist"));
|
||||
};
|
||||
let prefix = req.input.prefix.as_deref().unwrap_or_default();
|
||||
let max_keys = usize::try_from(req.input.max_keys.unwrap_or(MAX_LIST_KEYS).max(0)).map_err(S3Error::internal_error)?;
|
||||
|
||||
let mut keys: Vec<&String> = bucket_state.objects.keys().filter(|key| key.starts_with(prefix)).collect();
|
||||
keys.sort();
|
||||
|
||||
let mut versions = Vec::new();
|
||||
let mut delete_markers = Vec::new();
|
||||
'keys: for key in keys {
|
||||
for version in bucket_state.objects[key].iter().rev() {
|
||||
if versions.len() + delete_markers.len() >= max_keys {
|
||||
break 'keys;
|
||||
}
|
||||
if version.delete_marker {
|
||||
delete_markers.push(dto::DeleteMarkerEntry {
|
||||
key: ObjectKey::new(key.clone()).map_err(S3Error::internal_error)?,
|
||||
version_id: version.version_id.clone().into(),
|
||||
last_modified: version.last_modified,
|
||||
..Default::default()
|
||||
});
|
||||
} else {
|
||||
versions.push(dto::ObjectVersion {
|
||||
key: ObjectKey::new(key.clone()).map_err(S3Error::internal_error)?,
|
||||
version_id: version.version_id.clone().into(),
|
||||
last_modified: version.last_modified,
|
||||
e_tag: Some(ETag::from_stored(version.e_tag.clone())),
|
||||
size: i64::try_from(version.body.len()).map_err(S3Error::internal_error)?,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(state);
|
||||
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::ListObjectVersionsOutput {
|
||||
name: req.input.bucket,
|
||||
versions,
|
||||
delete_markers,
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,327 @@
|
||||
// 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.
|
||||
|
||||
//! Multipart staging and publication for the programmable remote S3 target.
|
||||
|
||||
use super::*;
|
||||
use rustfs_gateway::{BucketName, ObjectKey, RecordedUpload, UploadIdClaim, dto};
|
||||
use rustfs_s3_types::{S3Result, s3_error};
|
||||
|
||||
impl RecordedUpload for MultipartState {
|
||||
fn bucket(&self) -> &str {
|
||||
&self.bucket
|
||||
}
|
||||
|
||||
fn key(&self) -> &str {
|
||||
&self.key
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_upload<'id, 'store>(
|
||||
state: &'store StoreState,
|
||||
claim: &'id UploadIdClaim,
|
||||
bucket: &BucketName,
|
||||
key: &ObjectKey,
|
||||
) -> S3Result<(&'id str, &'store MultipartState)> {
|
||||
let (id, upload) = rustfs_gateway::resolve_upload(claim, bucket, key, |id| state.uploads.get(id))
|
||||
.map_err(|_| s3_error!(NoSuchUpload, "multipart upload does not exist"))?;
|
||||
Ok((id.id(), upload))
|
||||
}
|
||||
|
||||
impl FakeBackend {
|
||||
pub(super) async fn create_multipart_upload(
|
||||
&self,
|
||||
req: TargetRequest<dto::CreateMultipartUploadInput>,
|
||||
) -> S3Result<TargetResponse<dto::CreateMultipartUploadOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let headers = req.headers;
|
||||
let input = req.input;
|
||||
let mut state = lock(&self.store);
|
||||
if !state.buckets.contains_key(input.bucket.as_str()) {
|
||||
return Err(s3_error!(NoSuchBucket, "bucket does not exist"));
|
||||
}
|
||||
ensure_upload_budget(&state)?;
|
||||
let metadata = (!input.metadata.is_empty()).then(|| input.metadata.into_iter().collect());
|
||||
validate_stored_metadata(&input.content_type, &metadata)?;
|
||||
let standard_headers = StandardHeaders {
|
||||
cache_control: input.cache_control,
|
||||
content_disposition: input.content_disposition,
|
||||
content_encoding: input.content_encoding,
|
||||
content_language: input.content_language,
|
||||
expires: input.expires.map(|value| value.as_str().to_owned()),
|
||||
};
|
||||
standard_headers.validate()?;
|
||||
let upload_id = Uuid::new_v4().to_string();
|
||||
// Read the flags before the mutable borrow of `state.uploads` below
|
||||
// (and never re-lock the store: the mutex is not reentrant).
|
||||
let mint_own = state.assign_own_version_ids || state.assign_own_multipart_version_ids;
|
||||
let drop_unlisted = state.drop_unlisted_replication_headers;
|
||||
let version_id = if bucket_versioned(&state, input.bucket.as_str()) {
|
||||
new_version_id(&headers, mint_own)?
|
||||
} else {
|
||||
NULL_VERSION_ID.to_string()
|
||||
};
|
||||
state.uploads.insert(
|
||||
upload_id.clone(),
|
||||
MultipartState {
|
||||
bucket: input.bucket.as_str().to_owned(),
|
||||
key: input.key.as_str().to_owned(),
|
||||
version_id,
|
||||
content_type: input.content_type,
|
||||
metadata,
|
||||
standard_headers,
|
||||
replication_sse_headers: captured_replication_sse_headers(&headers, drop_unlisted),
|
||||
lock: VersionLock::from_headers(
|
||||
input.object_lock_mode,
|
||||
input.object_lock_retain_until_date,
|
||||
input.object_lock_legal_hold_status,
|
||||
),
|
||||
parts: BTreeMap::new(),
|
||||
},
|
||||
);
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::CreateMultipartUploadOutput {
|
||||
bucket: input.bucket,
|
||||
key: input.key,
|
||||
upload_id,
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn upload_part(
|
||||
&self,
|
||||
req: TargetRequest<dto::UploadPartInput>,
|
||||
) -> S3Result<TargetResponse<dto::UploadPartOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
let declared_actual_size = req
|
||||
.headers
|
||||
.get("x-rustfs-replication-part-actual-size")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.parse::<usize>().ok());
|
||||
let _body_permit = timeout(MAX_FAULT_DURATION, Arc::clone(&self.body_limit).acquire_owned())
|
||||
.await
|
||||
.map_err(|_| s3_error!(RequestTimeout, "fake target body limiter wait exceeded 30 seconds"))?
|
||||
.map_err(|_| s3_error!(ServiceUnavailable, "fake target body limiter closed"))?;
|
||||
let input = req.input;
|
||||
if !(1..=10_000).contains(&input.part_number) {
|
||||
return Err(s3_error!(InvalidArgument, "part number must be in 1..=10000"));
|
||||
}
|
||||
let max_object_bytes = lock(&self.store).limits.max_object_bytes;
|
||||
let body =
|
||||
collect_stream(input.body, Some(input.content_length), fault.as_ref(), &self.control, max_object_bytes).await?;
|
||||
let (digest, _body_permit) = md5_digest(body.clone(), _body_permit).await?;
|
||||
let e_tag = hex_simd::encode_to_string(digest, hex_simd::AsciiCase::Lower);
|
||||
let mut state = lock(&self.store);
|
||||
let (upload_id, upload) = resolve_upload(&state, &input.upload_id, &input.bucket, &input.key)?;
|
||||
let existing = upload.parts.get(&input.part_number);
|
||||
let existing_bytes = existing.map_or(0, |part| part.body.len());
|
||||
let adds_part = existing.is_none();
|
||||
ensure_part_budget(&state, adds_part)?;
|
||||
ensure_store_budget(&state, existing_bytes, body.len(), false)?;
|
||||
state.total_bytes = state.total_bytes - existing_bytes + body.len();
|
||||
if adds_part {
|
||||
state.total_parts += 1;
|
||||
}
|
||||
let upload = state.uploads.get_mut(upload_id).expect("upload existence checked above");
|
||||
upload.parts.insert(
|
||||
input.part_number,
|
||||
MultipartPart {
|
||||
body,
|
||||
e_tag: e_tag.clone(),
|
||||
digest,
|
||||
actual_size: declared_actual_size,
|
||||
},
|
||||
);
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::UploadPartOutput {
|
||||
e_tag: rustfs_gateway::ETag::from_stored(maybe_wrong_etag(fault.as_ref(), e_tag)),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn complete_multipart_upload(
|
||||
&self,
|
||||
mut req: TargetRequest<dto::CompleteMultipartUploadInput>,
|
||||
) -> S3Result<TargetResponse<dto::CompleteMultipartUploadOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let _body_permits = match req.extensions.remove::<PrebodyPermit>().and_then(PrebodyPermit::take) {
|
||||
Some(permit) => permit,
|
||||
None => timeout(
|
||||
MAX_FAULT_DURATION,
|
||||
Arc::clone(&self.body_limit).acquire_many_owned(MAX_CONCURRENT_BODY_REQUESTS as u32),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| s3_error!(RequestTimeout, "fake target body limiter wait exceeded 30 seconds"))?
|
||||
.map_err(|_| s3_error!(ServiceUnavailable, "fake target body limiter closed"))?,
|
||||
};
|
||||
let headers = req.headers;
|
||||
let input = req.input;
|
||||
let requested = input.multipart_upload.parts;
|
||||
if requested.is_empty() {
|
||||
return Err(s3_error!(InvalidPart, "completion omitted parts"));
|
||||
}
|
||||
let mut requested_parts = Vec::with_capacity(requested.len());
|
||||
let mut previous = 0;
|
||||
for part in &requested {
|
||||
let number = part.part_number;
|
||||
if number <= previous {
|
||||
return Err(s3_error!(InvalidPartOrder, "parts are not strictly ordered"));
|
||||
}
|
||||
previous = number;
|
||||
let requested_etag = part
|
||||
.e_tag
|
||||
.as_ref()
|
||||
.ok_or_else(|| s3_error!(InvalidPart, "part ETag is missing"))?;
|
||||
requested_parts.push((number, normalize_etag(requested_etag.opaque_tag())));
|
||||
}
|
||||
|
||||
let (upload_id, upload, selected_parts) = {
|
||||
let state = lock(&self.store);
|
||||
let (upload_id, upload) = resolve_upload(&state, &input.upload_id, &input.bucket, &input.key)?;
|
||||
let mut selected = Vec::with_capacity(requested_parts.len());
|
||||
for (index, (number, requested_etag)) in requested_parts.iter().enumerate() {
|
||||
let stored = upload
|
||||
.parts
|
||||
.get(number)
|
||||
.ok_or_else(|| s3_error!(InvalidPart, "part was not uploaded"))?;
|
||||
if requested_etag != &stored.e_tag {
|
||||
return Err(s3_error!(InvalidPart, "part ETag does not match"));
|
||||
}
|
||||
if index + 1 != requested_parts.len()
|
||||
&& stored.actual_size.unwrap_or(stored.body.len()) < MIN_MULTIPART_PART_BYTES
|
||||
{
|
||||
return Err(s3_error!(EntityTooSmall, "non-final multipart part is smaller than 5 MiB"));
|
||||
}
|
||||
selected.push((*number, stored.clone()));
|
||||
}
|
||||
(
|
||||
upload_id,
|
||||
MultipartState {
|
||||
bucket: upload.bucket.clone(),
|
||||
key: upload.key.clone(),
|
||||
version_id: upload.version_id.clone(),
|
||||
content_type: upload.content_type.clone(),
|
||||
metadata: upload.metadata.clone(),
|
||||
standard_headers: upload.standard_headers.clone(),
|
||||
replication_sse_headers: upload.replication_sse_headers.clone(),
|
||||
lock: upload.lock.clone(),
|
||||
parts: BTreeMap::new(),
|
||||
},
|
||||
selected,
|
||||
)
|
||||
};
|
||||
let max_total_bytes = lock(&self.store).limits.max_total_bytes;
|
||||
let total_len = selected_parts.iter().try_fold(0usize, |total, (_, part)| {
|
||||
total
|
||||
.checked_add(part.body.len())
|
||||
.filter(|total| *total <= max_total_bytes)
|
||||
.ok_or_else(|| s3_error!(EntityTooLarge, "multipart object exceeds {max_total_bytes} bytes"))
|
||||
})?;
|
||||
let assembly_parts = selected_parts
|
||||
.iter()
|
||||
.map(|(_, stored)| (stored.body.clone(), stored.digest))
|
||||
.collect();
|
||||
let (body, digests, _body_permits) = assemble_multipart(assembly_parts, total_len, _body_permits).await?;
|
||||
let part_count = requested.len();
|
||||
let ignore_source_etags = lock(&self.store).ignore_source_etags;
|
||||
let e_tag = source_etag(&headers)?
|
||||
.filter(|_| !ignore_source_etags)
|
||||
.unwrap_or_else(|| format!("{}-{part_count}", md5_hex(digests)));
|
||||
let version = ObjectVersion {
|
||||
version_id: upload.version_id.clone(),
|
||||
body,
|
||||
e_tag: e_tag.clone(),
|
||||
last_modified: now_timestamp(),
|
||||
delete_marker: false,
|
||||
content_type: upload.content_type,
|
||||
metadata: upload.metadata,
|
||||
standard_headers: upload.standard_headers,
|
||||
tags: Vec::new(),
|
||||
replication_sse_headers: upload.replication_sse_headers,
|
||||
lock: upload.lock,
|
||||
};
|
||||
let mut state = lock(&self.store);
|
||||
let versioned = bucket_versioned(&state, input.bucket.as_str());
|
||||
let current = state
|
||||
.uploads
|
||||
.get(upload_id)
|
||||
.filter(|current| current.bucket == input.bucket.as_str() && current.key == input.key.as_str())
|
||||
.ok_or_else(|| s3_error!(NoSuchUpload, "multipart upload does not exist"))?;
|
||||
for (part, (selected_number, selected_part)) in requested.iter().zip(&selected_parts) {
|
||||
let number = part.part_number;
|
||||
debug_assert_eq!(number, *selected_number);
|
||||
let current_part = current
|
||||
.parts
|
||||
.get(&number)
|
||||
.ok_or_else(|| s3_error!(InvalidPart, "part changed during completion"))?;
|
||||
if current_part.e_tag != selected_part.e_tag {
|
||||
return Err(s3_error!(InvalidPart, "part changed during completion"));
|
||||
}
|
||||
}
|
||||
let upload_bytes = current.parts.values().map(|part| part.body.len()).sum::<usize>();
|
||||
let upload_part_count = current.parts.len();
|
||||
let existing = state
|
||||
.buckets
|
||||
.get(input.bucket.as_str())
|
||||
.ok_or_else(|| s3_error!(NoSuchBucket, "bucket does not exist"))?
|
||||
.objects
|
||||
.get(input.key.as_str())
|
||||
.and_then(|versions| versions.iter().find(|candidate| candidate.version_id == version.version_id))
|
||||
.map(|version| version.body.len());
|
||||
ensure_store_budget(
|
||||
&state,
|
||||
upload_bytes + existing.unwrap_or_default(),
|
||||
version.body.len(),
|
||||
existing.is_none(),
|
||||
)?;
|
||||
state.total_bytes -= upload_bytes;
|
||||
state.total_parts -= upload_part_count;
|
||||
state.uploads.remove(upload_id);
|
||||
upsert_version(&mut state, input.bucket.as_str(), input.key.as_str().to_owned(), version)?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::CompleteMultipartUploadOutput {
|
||||
bucket: Some(input.bucket),
|
||||
key: Some(input.key),
|
||||
e_tag: Some(rustfs_gateway::ETag::from_stored(maybe_wrong_etag(fault.as_ref(), e_tag))),
|
||||
version_id: versioned.then_some(upload.version_id),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn abort_multipart_upload(
|
||||
&self,
|
||||
req: TargetRequest<dto::AbortMultipartUploadInput>,
|
||||
) -> S3Result<TargetResponse<dto::AbortMultipartUploadOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let mut state = lock(&self.store);
|
||||
let (upload_id, _) = resolve_upload(&state, &input.upload_id, &input.bucket, &input.key)?;
|
||||
let removed = state.uploads.remove(upload_id).expect("upload existence checked above");
|
||||
state.total_bytes -= removed.parts.values().map(|part| part.body.len()).sum::<usize>();
|
||||
state.total_parts -= removed.parts.len();
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::AbortMultipartUploadOutput::default()),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
// 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.
|
||||
|
||||
//! Object operations for the programmable S3 target.
|
||||
|
||||
use super::*;
|
||||
use rustfs_gateway::{ByteStream, ETag, dto};
|
||||
|
||||
impl FakeBackend {
|
||||
pub(super) async fn put_object(
|
||||
&self,
|
||||
req: TargetRequest<dto::PutObjectInput>,
|
||||
) -> S3Result<TargetResponse<dto::PutObjectOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
let _body_permit = timeout(MAX_FAULT_DURATION, Arc::clone(&self.body_limit).acquire_owned())
|
||||
.await
|
||||
.map_err(|_| s3_error!(RequestTimeout, "fake target body limiter wait exceeded 30 seconds"))?
|
||||
.map_err(|_| s3_error!(ServiceUnavailable, "fake target body limiter closed"))?;
|
||||
let headers = req.headers;
|
||||
let input = req.input;
|
||||
let (assign_own, drop_unlisted, require_checksum, ignore_source_etags, limits, versioned) = {
|
||||
let state = lock(&self.store);
|
||||
(
|
||||
state.assign_own_version_ids,
|
||||
state.drop_unlisted_replication_headers,
|
||||
state.require_checksum_for_object_lock,
|
||||
state.ignore_source_etags,
|
||||
state.limits,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
let transport = TransportSnapshot::from_headers(&headers);
|
||||
if require_checksum
|
||||
&& transport.object_lock_params
|
||||
&& transport.content_md5.is_none()
|
||||
&& transport.checksum_headers.is_empty()
|
||||
{
|
||||
return Err(s3_error!(
|
||||
InvalidRequest,
|
||||
"Content-MD5 OR x-amz-checksum- HTTP header is required for Put Object requests with Object Lock parameters"
|
||||
));
|
||||
}
|
||||
let body = collect_stream(
|
||||
input.body,
|
||||
Some(input.content_length),
|
||||
fault.as_ref(),
|
||||
&self.control,
|
||||
limits.max_object_bytes,
|
||||
)
|
||||
.await?;
|
||||
let mut body_permit = _body_permit;
|
||||
if let Some(expected) = &transport.content_md5 {
|
||||
let (digest, permit) = md5_digest(body.clone(), body_permit).await?;
|
||||
body_permit = permit;
|
||||
if BASE64_STANDARD.encode_to_string(digest) != expected.trim() {
|
||||
return Err(s3_error!(BadDigest, "The Content-MD5 you specified did not match what we received."));
|
||||
}
|
||||
}
|
||||
let metadata = (!input.metadata.is_empty()).then(|| input.metadata.into_iter().collect());
|
||||
validate_stored_metadata(&input.content_type, &metadata)?;
|
||||
let standard_headers = StandardHeaders {
|
||||
cache_control: input.cache_control,
|
||||
content_disposition: input.content_disposition,
|
||||
content_encoding: input.content_encoding,
|
||||
content_language: input.content_language,
|
||||
expires: input.expires.map(|value| value.into_string()),
|
||||
};
|
||||
standard_headers.validate()?;
|
||||
let version_id = if versioned {
|
||||
new_version_id(&headers, assign_own)?
|
||||
} else {
|
||||
NULL_VERSION_ID.to_string()
|
||||
};
|
||||
let e_tag = match source_etag(&headers)?.filter(|_| !ignore_source_etags) {
|
||||
Some(value) => value,
|
||||
None => {
|
||||
let (digest, permit) = md5_digest(body.clone(), body_permit).await?;
|
||||
body_permit = permit;
|
||||
hex_simd::encode_to_string(digest, hex_simd::AsciiCase::Lower)
|
||||
}
|
||||
};
|
||||
// Held until the version is stored, like every other body-bearing op.
|
||||
let _body_permit = body_permit;
|
||||
let version = ObjectVersion {
|
||||
version_id: version_id.clone(),
|
||||
body,
|
||||
e_tag: e_tag.clone(),
|
||||
last_modified: source_mtime(&headers),
|
||||
delete_marker: false,
|
||||
content_type: input.content_type,
|
||||
metadata,
|
||||
standard_headers,
|
||||
tags: Vec::new(),
|
||||
replication_sse_headers: captured_replication_sse_headers(&headers, drop_unlisted),
|
||||
lock: VersionLock::from_headers(
|
||||
input.object_lock_mode,
|
||||
input.object_lock_retain_until_date,
|
||||
input.object_lock_legal_hold_status,
|
||||
),
|
||||
};
|
||||
upsert_version(&mut lock(&self.store), input.bucket.as_str(), input.key.as_str().to_owned(), version)?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::PutObjectOutput {
|
||||
e_tag: ETag::from_stored(maybe_wrong_etag(fault.as_ref(), e_tag)),
|
||||
version_id: versioned.then_some(version_id),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn get_object(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetObjectInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetObjectOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let held_get = lock(&self.control)
|
||||
.held_get
|
||||
.as_ref()
|
||||
.filter(|held| held.bucket == input.bucket.as_str() && held.key == input.key.as_str())
|
||||
.cloned();
|
||||
if let Some(mut held) = held_get {
|
||||
held.entered.send_modify(|count| *count += 1);
|
||||
// Keep the gate installed when a request is cancelled or times out:
|
||||
// a retry must cross the same boundary before returning any bytes.
|
||||
let _ = held.released.wait_for(|released| *released).await;
|
||||
}
|
||||
let (version, versioned) = {
|
||||
let state = lock(&self.store);
|
||||
(
|
||||
find_version(&state, input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref())?,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
let sse_customer_algorithm = stored_sse_customer_algorithm(&version);
|
||||
let served = resolve_range(input.range.as_ref(), version.body.len())?;
|
||||
let body = version.body.slice(served.range.clone());
|
||||
let body = match fault.as_ref().map(|fault| &fault.action) {
|
||||
Some(FaultAction::TruncateBodyAt(truncate_at)) => truncated_body(body, *truncate_at),
|
||||
Some(FaultAction::SlowSendBody { chunk_bytes, delay }) => slow_sent_body(body, *chunk_bytes, *delay),
|
||||
_ => ByteStream::from_bytes(body),
|
||||
};
|
||||
let mut response = TargetResponse::new(dto::GetObjectOutput {
|
||||
body: Some(body),
|
||||
content_length: Some(served.len() as i64),
|
||||
content_range: served.content_range,
|
||||
accept_ranges: Some("bytes".to_string()),
|
||||
content_type: version.content_type,
|
||||
metadata: version.metadata.unwrap_or_default().into_iter().collect(),
|
||||
cache_control: version.standard_headers.cache_control,
|
||||
content_disposition: version.standard_headers.content_disposition,
|
||||
content_encoding: version.standard_headers.content_encoding,
|
||||
content_language: version.standard_headers.content_language,
|
||||
expires: version.standard_headers.expires.map(Into::into),
|
||||
e_tag: Some(ETag::from_stored(version.e_tag)),
|
||||
last_modified: Some(version.last_modified),
|
||||
version_id: versioned.then_some(version.version_id),
|
||||
sse_customer_algorithm,
|
||||
object_lock_mode: version
|
||||
.lock
|
||||
.retention
|
||||
.as_ref()
|
||||
.map(|(mode, _)| dto::ObjectLockMode::custom(mode.clone())),
|
||||
object_lock_retain_until_date: version.lock.retention.as_ref().map(|(_, until)| *until),
|
||||
object_lock_legal_hold_status: version.lock.legal_hold_status(),
|
||||
..Default::default()
|
||||
});
|
||||
response.status = served.status;
|
||||
Ok(apply_response_fault(response, fault.as_ref()))
|
||||
}
|
||||
|
||||
pub(super) async fn head_object(
|
||||
&self,
|
||||
req: TargetRequest<dto::HeadObjectInput>,
|
||||
) -> S3Result<TargetResponse<dto::HeadObjectOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let (version, versioned) = {
|
||||
let state = lock(&self.store);
|
||||
(
|
||||
find_version(&state, input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref())?,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
let sse_customer_algorithm = stored_sse_customer_algorithm(&version);
|
||||
let served = resolve_range(input.range.as_ref(), version.body.len())?;
|
||||
let mut response = TargetResponse::new(dto::HeadObjectOutput {
|
||||
content_length: Some(served.len() as i64),
|
||||
content_range: served.content_range,
|
||||
accept_ranges: Some("bytes".to_string()),
|
||||
content_type: version.content_type,
|
||||
metadata: version.metadata.unwrap_or_default().into_iter().collect(),
|
||||
cache_control: version.standard_headers.cache_control,
|
||||
content_disposition: version.standard_headers.content_disposition,
|
||||
content_encoding: version.standard_headers.content_encoding,
|
||||
content_language: version.standard_headers.content_language,
|
||||
expires: version.standard_headers.expires.map(Into::into),
|
||||
e_tag: Some(ETag::from_stored(version.e_tag)),
|
||||
last_modified: Some(version.last_modified),
|
||||
version_id: versioned.then_some(version.version_id),
|
||||
sse_customer_algorithm,
|
||||
object_lock_mode: version
|
||||
.lock
|
||||
.retention
|
||||
.as_ref()
|
||||
.map(|(mode, _)| dto::ObjectLockMode::custom(mode.clone())),
|
||||
object_lock_retain_until_date: version.lock.retention.as_ref().map(|(_, until)| *until),
|
||||
object_lock_legal_hold_status: version.lock.legal_hold_status(),
|
||||
..Default::default()
|
||||
});
|
||||
response.status = served.status;
|
||||
Ok(apply_response_fault(response, fault.as_ref()))
|
||||
}
|
||||
|
||||
pub(super) async fn get_object_tagging(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetObjectTaggingInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetObjectTaggingOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let (version, versioned) = {
|
||||
let state = lock(&self.store);
|
||||
(
|
||||
find_version(&state, input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref())?,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
let tag_set = version
|
||||
.tags
|
||||
.into_iter()
|
||||
.map(|(key, value)| dto::Tag {
|
||||
key: Some(key),
|
||||
value: Some(value),
|
||||
})
|
||||
.collect();
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::GetObjectTaggingOutput {
|
||||
tag_set,
|
||||
version_id: versioned.then_some(version.version_id),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn put_object_tagging(
|
||||
&self,
|
||||
req: TargetRequest<dto::PutObjectTaggingInput>,
|
||||
) -> S3Result<TargetResponse<dto::PutObjectTaggingOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let tags = input
|
||||
.tagging
|
||||
.tag_set
|
||||
.into_iter()
|
||||
.map(|tag| (tag.key.unwrap_or_default(), tag.value.unwrap_or_default()))
|
||||
.collect();
|
||||
let (version_id, versioned) = {
|
||||
let mut state = lock(&self.store);
|
||||
(
|
||||
set_version_tags(&mut state, input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref(), tags)?,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::PutObjectTaggingOutput {
|
||||
version_id: versioned.then_some(version_id),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn get_object_retention(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetObjectRetentionInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetObjectRetentionOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let version = find_version(&lock(&self.store), input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref())?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::GetObjectRetentionOutput {
|
||||
retention: version.lock.retention.map(|(mode, until)| dto::ObjectLockRetention {
|
||||
mode: Some(dto::Mode::custom(mode)),
|
||||
retain_until_date: Some(until),
|
||||
..Default::default()
|
||||
}),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn put_object_retention(
|
||||
&self,
|
||||
req: TargetRequest<dto::PutObjectRetentionInput>,
|
||||
) -> S3Result<TargetResponse<dto::PutObjectRetentionOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let retention = input
|
||||
.retention
|
||||
.mode
|
||||
.zip(input.retention.retain_until_date)
|
||||
.map(|(mode, until)| (mode.as_str().to_string(), until));
|
||||
update_version_lock(
|
||||
&mut lock(&self.store),
|
||||
input.bucket.as_str(),
|
||||
input.key.as_str(),
|
||||
input.version_id.as_deref(),
|
||||
|lock| {
|
||||
lock.retention = retention;
|
||||
},
|
||||
)?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::PutObjectRetentionOutput::default()),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn get_object_legal_hold(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetObjectLegalHoldInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetObjectLegalHoldOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let version = find_version(&lock(&self.store), input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref())?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::GetObjectLegalHoldOutput {
|
||||
legal_hold: Some(dto::ObjectLockLegalHold {
|
||||
status: Some(if version.lock.legal_hold == Some(true) {
|
||||
dto::Status::ON
|
||||
} else {
|
||||
dto::Status::OFF
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn put_object_legal_hold(
|
||||
&self,
|
||||
req: TargetRequest<dto::PutObjectLegalHoldInput>,
|
||||
) -> S3Result<TargetResponse<dto::PutObjectLegalHoldOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let legal_hold_on = input
|
||||
.legal_hold
|
||||
.status
|
||||
.is_some_and(|status| status.as_str().eq_ignore_ascii_case("ON"));
|
||||
update_version_lock(
|
||||
&mut lock(&self.store),
|
||||
input.bucket.as_str(),
|
||||
input.key.as_str(),
|
||||
input.version_id.as_deref(),
|
||||
|lock| {
|
||||
lock.legal_hold = Some(legal_hold_on);
|
||||
},
|
||||
)?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::PutObjectLegalHoldOutput::default()),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn delete_object_tagging(
|
||||
&self,
|
||||
req: TargetRequest<dto::DeleteObjectTaggingInput>,
|
||||
) -> S3Result<TargetResponse<dto::DeleteObjectTaggingOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let (version_id, versioned) = {
|
||||
let mut state = lock(&self.store);
|
||||
(
|
||||
set_version_tags(
|
||||
&mut state,
|
||||
input.bucket.as_str(),
|
||||
input.key.as_str(),
|
||||
input.version_id.as_deref(),
|
||||
Vec::new(),
|
||||
)?,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::DeleteObjectTaggingOutput {
|
||||
version_id: versioned.then_some(version_id),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn delete_object(
|
||||
&self,
|
||||
req: TargetRequest<dto::DeleteObjectInput>,
|
||||
) -> S3Result<TargetResponse<dto::DeleteObjectOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let headers = req.headers;
|
||||
let input = req.input;
|
||||
let held_delete = lock(&self.control)
|
||||
.held_delete
|
||||
.as_ref()
|
||||
.filter(|held| held.bucket == input.bucket.as_str() && held.key == input.key.as_str())
|
||||
.cloned();
|
||||
if let Some(mut held) = held_delete {
|
||||
held.entered.send_modify(|count| *count += 1);
|
||||
let _ = held.released.wait_for(|released| *released).await;
|
||||
}
|
||||
let mut state = lock(&self.store);
|
||||
let Some(versioned) = state.buckets.get(input.bucket.as_str()).map(|bucket| bucket.versioned) else {
|
||||
return Err(s3_error!(NoSuchBucket, "bucket does not exist"));
|
||||
};
|
||||
if !versioned {
|
||||
// Unversioned buckets know only the `null` version: DELETE removes
|
||||
// the key outright and never writes a delete marker.
|
||||
if input
|
||||
.version_id
|
||||
.as_deref()
|
||||
.is_some_and(|version_id| version_id != NULL_VERSION_ID)
|
||||
{
|
||||
return Err(s3_error!(InvalidArgument, "invalid version id specified"));
|
||||
}
|
||||
let removed = state
|
||||
.buckets
|
||||
.get_mut(input.bucket.as_str())
|
||||
.expect("bucket existence checked above")
|
||||
.objects
|
||||
.remove(input.key.as_str())
|
||||
.unwrap_or_default();
|
||||
state.total_bytes -= removed.iter().map(|version| version.body.len()).sum::<usize>();
|
||||
state.total_versions -= removed.len();
|
||||
return Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::DeleteObjectOutput::default()),
|
||||
fault.as_ref(),
|
||||
));
|
||||
}
|
||||
if let Some(version_id) = input.version_id {
|
||||
let reject_unknown = state.reject_unknown_version_deletes;
|
||||
let (removed_bytes, removed_versions, delete_marker, remove_key) = {
|
||||
let Some(versions) = state
|
||||
.buckets
|
||||
.get_mut(input.bucket.as_str())
|
||||
.expect("bucket existence checked above")
|
||||
.objects
|
||||
.get_mut(input.key.as_str())
|
||||
else {
|
||||
if reject_unknown {
|
||||
return Err(s3_error!(NoSuchVersion, "The specified version does not exist."));
|
||||
}
|
||||
return Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::DeleteObjectOutput {
|
||||
version_id: Some(version_id),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
));
|
||||
};
|
||||
if reject_unknown && !versions.iter().any(|version| version.version_id == version_id) {
|
||||
return Err(s3_error!(NoSuchVersion, "The specified version does not exist."));
|
||||
}
|
||||
let mut removed_bytes = 0usize;
|
||||
let mut removed_versions = 0usize;
|
||||
let mut delete_marker = None;
|
||||
versions.retain(|version| {
|
||||
if version.version_id == version_id {
|
||||
removed_bytes += version.body.len();
|
||||
removed_versions += 1;
|
||||
delete_marker.get_or_insert(version.delete_marker);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
(removed_bytes, removed_versions, delete_marker, versions.is_empty())
|
||||
};
|
||||
if remove_key {
|
||||
state
|
||||
.buckets
|
||||
.get_mut(input.bucket.as_str())
|
||||
.expect("bucket existence checked above")
|
||||
.objects
|
||||
.remove(input.key.as_str());
|
||||
}
|
||||
state.total_bytes -= removed_bytes;
|
||||
state.total_versions -= removed_versions;
|
||||
return Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::DeleteObjectOutput {
|
||||
delete_marker,
|
||||
version_id: Some(version_id),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
));
|
||||
}
|
||||
|
||||
// `state` is the live store guard: read the flag from it. Re-locking
|
||||
// would self-deadlock (the store mutex is not reentrant).
|
||||
let version_id = new_version_id(&headers, state.assign_own_version_ids)?;
|
||||
upsert_version(
|
||||
&mut state,
|
||||
input.bucket.as_str(),
|
||||
input.key.as_str().to_owned(),
|
||||
ObjectVersion {
|
||||
version_id: version_id.clone(),
|
||||
body: Bytes::new(),
|
||||
e_tag: String::new(),
|
||||
last_modified: source_mtime(&headers),
|
||||
delete_marker: true,
|
||||
content_type: None,
|
||||
metadata: None,
|
||||
standard_headers: StandardHeaders::default(),
|
||||
tags: Vec::new(),
|
||||
replication_sse_headers: Vec::new(),
|
||||
lock: VersionLock::default(),
|
||||
},
|
||||
)?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::DeleteObjectOutput {
|
||||
delete_marker: Some(true),
|
||||
version_id: Some(version_id),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// 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 loopback target's authenticated gateway and scripted wire responses.
|
||||
|
||||
use super::*;
|
||||
use rustfs_gateway::{
|
||||
Authorizer, AuthzRequest, BoxFuture, CodecError, Credentials, Decision, ErrorCode, Handler, HandlerDeadlineConfig,
|
||||
HandlerError, HandlerErrorContext, HandlerResult, InputAuthzRequest, InputDecisions, LegacyRustfsFacts, LegacyRustfsRefusal,
|
||||
Operation as GatewayOperation, PlaintextCustomerKeyAck, RegionSet, Req, RequestBodyDeadlineConfig, RequestContext, Resp,
|
||||
ServiceBuilder, ServiceConfig, SigV4Authenticator, SseConfig, StaticCredentials,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct RequestState(Arc<State>);
|
||||
|
||||
struct State {
|
||||
method: Method,
|
||||
uri: Uri,
|
||||
headers: HeaderMap,
|
||||
sequence: RequestSequence,
|
||||
admitted: OnceLock<http::Extensions>,
|
||||
// A scripted target can deliberately replace a typed header such as ETag on the wire.
|
||||
response_headers: OnceLock<(u16, HeaderMap)>,
|
||||
}
|
||||
|
||||
impl RequestState {
|
||||
pub(super) fn new<B>(request: &Request<B>) -> Self {
|
||||
Self(Arc::new(State {
|
||||
method: request.method().clone(),
|
||||
uri: request.uri().clone(),
|
||||
headers: request.headers().clone(),
|
||||
sequence: RequestSequence::default(),
|
||||
admitted: OnceLock::new(),
|
||||
response_headers: OnceLock::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn sequence(&self) -> Option<u64> {
|
||||
self.0.sequence.0.get().copied()
|
||||
}
|
||||
|
||||
fn save_headers(&self, status: u16, headers: HeaderMap) {
|
||||
if !headers.is_empty() {
|
||||
let _ = self.0.response_headers.set((status, headers));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn apply_response<B>(&self, response: &mut Response<B>) {
|
||||
let Some((status, headers)) = self.0.response_headers.get() else { return };
|
||||
if *status == response.status().as_u16() {
|
||||
response.headers_mut().extend(headers.clone());
|
||||
} else if let Some(disconnect) = headers.get(DISCONNECT_HEADER) {
|
||||
// Dropping a partially consumed upload can also produce a gateway body error. The
|
||||
// scripted transport disconnect was already reached and must still close the socket.
|
||||
response.headers_mut().insert(DISCONNECT_HEADER, disconnect.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn error(&self, error: S3Error) -> HandlerError {
|
||||
let parts = error.into_parts();
|
||||
let status = parts
|
||||
.status
|
||||
.or_else(|| parts.code.status_code())
|
||||
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
let code = ErrorCode::custom(parts.code.as_str().to_owned(), status);
|
||||
let message = parts
|
||||
.message
|
||||
.map(|message| message.into_owned())
|
||||
.or_else(|| parts.code.default_message().map(str::to_owned));
|
||||
match LegacyRustfsRefusal::new(code, message, LegacyRustfsFacts::default()) {
|
||||
Ok(refusal) => {
|
||||
self.save_headers(status.as_u16(), parts.headers.unwrap_or_default());
|
||||
HandlerErrorContext::legacy_rustfs(refusal).into()
|
||||
}
|
||||
Err(_) => HandlerError::internal_error("invalid fake target error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn credential_decision(request: &AuthzRequest<'_>) -> Decision {
|
||||
if request
|
||||
.identity
|
||||
.is_some_and(|identity| identity.access_key_id() == FAKE_ACCESS_KEY)
|
||||
{
|
||||
Decision::Allow
|
||||
} else {
|
||||
Decision::Deny
|
||||
}
|
||||
}
|
||||
|
||||
impl Authorizer for FaultAccess {
|
||||
fn authorize_route<'a>(&'a self, _context: &'a RequestContext<'a>, request: &'a AuthzRequest<'a>) -> BoxFuture<'a, Decision> {
|
||||
Box::pin(async move { credential_decision(request) })
|
||||
}
|
||||
|
||||
fn authorize_route_result<'a>(
|
||||
&'a self,
|
||||
context: &'a RequestContext<'a>,
|
||||
request: &'a AuthzRequest<'a>,
|
||||
) -> BoxFuture<'a, Result<Decision, HandlerError>> {
|
||||
Box::pin(async move {
|
||||
if credential_decision(request) != Decision::Allow {
|
||||
return Err(HandlerError::new(ErrorCode::ACCESS_DENIED, "valid fixture credentials are required"));
|
||||
}
|
||||
let state = context.server_extensions().get::<RequestState>().ok_or_else(missing_state)?;
|
||||
// The gateway can ask several permissions for a single operation. Dispatch consumes
|
||||
// one fault and journals one request, after the signature has been verified.
|
||||
if state.0.admitted.get().is_none() {
|
||||
let extensions = self
|
||||
.admit(
|
||||
&state.0.method,
|
||||
&state.0.uri,
|
||||
&state.0.headers,
|
||||
operation_from_s3_name(request.operation),
|
||||
&state.0.sequence,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| state.error(error))?;
|
||||
state
|
||||
.0
|
||||
.admitted
|
||||
.set(extensions)
|
||||
.map_err(|_| HandlerError::internal_error("fixture request admitted twice"))?;
|
||||
}
|
||||
Ok(Decision::Allow)
|
||||
})
|
||||
}
|
||||
|
||||
fn authorize_input<'a>(
|
||||
&'a self,
|
||||
_context: &'a RequestContext<'a>,
|
||||
request: &'a InputAuthzRequest<'a>,
|
||||
) -> BoxFuture<'a, InputDecisions> {
|
||||
Box::pin(async move { request.decide_all(credential_decision(request.route()), credential_decision) })
|
||||
}
|
||||
}
|
||||
|
||||
fn missing_state() -> HandlerError {
|
||||
HandlerError::internal_error("missing fake target request state")
|
||||
}
|
||||
|
||||
fn target_request<O: GatewayOperation>(request: Req<O>) -> Result<(RequestState, TargetRequest<O::Input>), HandlerError> {
|
||||
let state = request
|
||||
.context()
|
||||
.transport_extensions()
|
||||
.get::<RequestState>()
|
||||
.cloned()
|
||||
.ok_or_else(missing_state)?;
|
||||
let extensions = state.0.admitted.get().cloned().ok_or_else(missing_state)?;
|
||||
let target = TargetRequest {
|
||||
input: request.into_input(),
|
||||
headers: state.0.headers.clone(),
|
||||
extensions,
|
||||
};
|
||||
Ok((state, target))
|
||||
}
|
||||
|
||||
fn target_response<O: GatewayOperation>(state: &RequestState, response: S3Result<TargetResponse<O::Output>>) -> HandlerResult<O> {
|
||||
let TargetResponse { output, headers, status } = response.map_err(|error| state.error(error))?;
|
||||
let response = match status {
|
||||
Some(status) => Resp::<O>::with_status(output, status.as_u16()),
|
||||
None => Resp::<O>::new(output),
|
||||
};
|
||||
state.save_headers(response.status(), headers);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
macro_rules! fixture_operations {
|
||||
($($operation:ident => $method:ident),+ $(,)?) => {
|
||||
$(impl Handler<dto::$operation> for FakeBackend {
|
||||
async fn call(&self, request: Req<dto::$operation>) -> HandlerResult<dto::$operation> {
|
||||
let (state, request) = target_request(request)?;
|
||||
target_response::<dto::$operation>(&state, self.$method(request).await)
|
||||
}
|
||||
})+
|
||||
|
||||
fn register_operations(builder: ServiceBuilder, backend: &Arc<FakeBackend>) -> ServiceBuilder {
|
||||
builder$(.register::<dto::$operation, _>(Arc::clone(backend)))+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fixture_operations! {
|
||||
HeadBucket => head_bucket,
|
||||
GetBucketVersioning => get_bucket_versioning,
|
||||
GetObjectLockConfiguration => get_object_lock_configuration,
|
||||
ListObjectsV2 => list_objects_v2,
|
||||
ListObjectVersions => list_object_versions,
|
||||
PutObject => put_object,
|
||||
GetObject => get_object,
|
||||
HeadObject => head_object,
|
||||
GetObjectTagging => get_object_tagging,
|
||||
PutObjectTagging => put_object_tagging,
|
||||
DeleteObjectTagging => delete_object_tagging,
|
||||
GetObjectRetention => get_object_retention,
|
||||
PutObjectRetention => put_object_retention,
|
||||
GetObjectLegalHold => get_object_legal_hold,
|
||||
PutObjectLegalHold => put_object_legal_hold,
|
||||
DeleteObject => delete_object,
|
||||
CreateMultipartUpload => create_multipart_upload,
|
||||
UploadPart => upload_part,
|
||||
AbortMultipartUpload => abort_multipart_upload,
|
||||
}
|
||||
|
||||
impl Handler<dto::CompleteMultipartUpload> for FakeBackend {
|
||||
async fn call(&self, request: Req<dto::CompleteMultipartUpload>) -> HandlerResult<dto::CompleteMultipartUpload> {
|
||||
let (state, request) = target_request(request)?;
|
||||
target_response::<dto::CompleteMultipartUpload>(&state, self.complete_multipart_upload(request).await)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn build(backend: FakeBackend, access: FaultAccess) -> Result<S3Service, BoxError> {
|
||||
let credentials = Credentials::new(FAKE_ACCESS_KEY, FAKE_SECRET_KEY.as_bytes())?;
|
||||
let authenticator =
|
||||
SigV4Authenticator::new(Arc::new(StaticCredentials::new().with(credentials)), RegionSet::new(["us-east-1"])?);
|
||||
// The target bounds the body reader and the entire request itself. A scripted delay or
|
||||
// slow drain must reach that bound without the gateway timing it out earlier.
|
||||
let config = ServiceConfig::new(MAX_BUFFERED_BODY_BYTES as u64)
|
||||
.with_handler_deadlines(HandlerDeadlineConfig::new(MAX_REQUEST_DURATION, MAX_REQUEST_DURATION)?)
|
||||
.with_request_body_deadlines(
|
||||
RequestBodyDeadlineConfig::S3
|
||||
.without_idle_deadlines()
|
||||
.without_throughput_floor(),
|
||||
);
|
||||
let (builder, _) = ServiceBuilder::new()
|
||||
.rustfs_profile()
|
||||
.authenticate_before_rejecting_unframed_upload_trailers()
|
||||
.config(config);
|
||||
let backend = Arc::new(backend);
|
||||
let service = register_operations(builder, &backend)
|
||||
.sse_config(SseConfig::allowing_customer_keys_over_plaintext(
|
||||
PlaintextCustomerKeyAck::i_understand_customer_keys_will_be_sent_in_the_clear(),
|
||||
))
|
||||
.authenticator(authenticator.rustfs_profile())
|
||||
.authorizer(access)
|
||||
.register_with_decode_error_mapping::<dto::CompleteMultipartUpload, _>(
|
||||
backend,
|
||||
CodecError::malformed_xml("the body omits a member the schema requires").about("PartNumber"),
|
||||
CodecError::new(ErrorCode::INVALID_PART, "part number is missing"),
|
||||
)
|
||||
.build()?;
|
||||
Ok(service)
|
||||
}
|
||||
@@ -114,7 +114,7 @@ async fn select_projects_encryption_headers_and_rejects_invalid_sse_c_before_str
|
||||
let log_path = format!("{}/server.log", kms.base_env.temp_dir);
|
||||
kms.base_env.capture_log_path = Some(log_path.clone());
|
||||
kms.base_env
|
||||
.start_rustfs_server_with_env(Vec::new(), &[("RUST_LOG", "s3s=debug,rustfs=info")])
|
||||
.start_rustfs_server_with_env(Vec::new(), &[("RUST_LOG", "rustfs_gateway=debug,rustfs=info")])
|
||||
.await?;
|
||||
let key_id = kms.configure_local_kms().await?;
|
||||
start_kms(&kms.base_env.url, &kms.base_env.access_key, &kms.base_env.secret_key).await?;
|
||||
|
||||
Reference in New Issue
Block a user