mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-28 03:18:15 +08:00
feat(gateway): serve HeadObject through native response facts
Share HEAD authorization and its use case across both request edges. Keep
stored and proxy ETag parsing distinct, preserve conditional headers and
version bytes, and finish auditing before terminal header encoding. Pin
gateway to 1afff6a for the measured 304 response profile.
Verified 785 affected and embedded tests, then 12 tests after test-only
module/import cleanup. Both all-target Clippy configurations, script tests,
wiring and prepush checks passed. Tests cover malformed stored tags,
separate replication denial, conditional status conflicts and ordinary
success controls; the proxy oracle checks 779 spellings.
Observed 39 effective isolated faults: authorization/delegation, execution,
metadata exposure, stored/legacy/proxy tags, raw header escaping/repetition,
framing conflicts, length/counting, range boundaries, checksum and storage
class, ordinary completion, terminal code/status/default resolution, and
each of the seven 304 fields. An ineffective fallback mutation was retained
as a failed experiment and replaced with an explicit-status-only fault.
The 785-test base was c13232996; final module tests and Clippy ran on
fc22c11d1. No GetObject migration added. Cross-binary pinned acceptance,
remote proxy/ODM integration, SSE-C real-storage wire and performance were
not verified. Existing assertions were not weakened.
This commit is contained in:
1 parent
247aecf7b8
commit
925e5d0c0c
23 files changed
+1586
-299
No files matched your search
Generated
+8
-8
@@ -10024,7 +10024,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway"
|
||||
version = "0.63.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1bbef5758bfe27aed9b14c38c312de6ebe24a122#1bbef5758bfe27aed9b14c38c312de6ebe24a122"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1afff6a91882ec47999f529245a717d10bc4c0fb#1afff6a91882ec47999f529245a717d10bc4c0fb"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
@@ -10071,7 +10071,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-core"
|
||||
version = "0.60.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1bbef5758bfe27aed9b14c38c312de6ebe24a122#1bbef5758bfe27aed9b14c38c312de6ebe24a122"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1afff6a91882ec47999f529245a717d10bc4c0fb#1afff6a91882ec47999f529245a717d10bc4c0fb"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
@@ -10092,7 +10092,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-http"
|
||||
version = "0.1.4"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1bbef5758bfe27aed9b14c38c312de6ebe24a122#1bbef5758bfe27aed9b14c38c312de6ebe24a122"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1afff6a91882ec47999f529245a717d10bc4c0fb#1afff6a91882ec47999f529245a717d10bc4c0fb"
|
||||
dependencies = [
|
||||
"hmac 0.13.0",
|
||||
"http 1.5.0",
|
||||
@@ -10110,7 +10110,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-macros"
|
||||
version = "0.1.4"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1bbef5758bfe27aed9b14c38c312de6ebe24a122#1bbef5758bfe27aed9b14c38c312de6ebe24a122"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1afff6a91882ec47999f529245a717d10bc4c0fb#1afff6a91882ec47999f529245a717d10bc4c0fb"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -10120,7 +10120,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-sig"
|
||||
version = "0.15.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1bbef5758bfe27aed9b14c38c312de6ebe24a122#1bbef5758bfe27aed9b14c38c312de6ebe24a122"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1afff6a91882ec47999f529245a717d10bc4c0fb#1afff6a91882ec47999f529245a717d10bc4c0fb"
|
||||
dependencies = [
|
||||
"hmac 0.13.0",
|
||||
"http 1.5.0",
|
||||
@@ -10135,7 +10135,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-stream"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1bbef5758bfe27aed9b14c38c312de6ebe24a122#1bbef5758bfe27aed9b14c38c312de6ebe24a122"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1afff6a91882ec47999f529245a717d10bc4c0fb#1afff6a91882ec47999f529245a717d10bc4c0fb"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytes",
|
||||
@@ -10146,7 +10146,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-types"
|
||||
version = "0.40.0+aws.2026-10-02"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1bbef5758bfe27aed9b14c38c312de6ebe24a122#1bbef5758bfe27aed9b14c38c312de6ebe24a122"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1afff6a91882ec47999f529245a717d10bc4c0fb#1afff6a91882ec47999f529245a717d10bc4c0fb"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"crc-fast",
|
||||
@@ -10169,7 +10169,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-xml"
|
||||
version = "0.4.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1bbef5758bfe27aed9b14c38c312de6ebe24a122#1bbef5758bfe27aed9b14c38c312de6ebe24a122"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=1afff6a91882ec47999f529245a717d10bc4c0fb#1afff6a91882ec47999f529245a717d10bc4c0fb"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
]
|
||||
|
||||
+4
-4
@@ -147,14 +147,14 @@ 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 = "1bbef5758bfe27aed9b14c38c312de6ebe24a122", version = "0.40.0", default-features = false }
|
||||
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "1bbef5758bfe27aed9b14c38c312de6ebe24a122", version = "0.2.0", default-features = false }
|
||||
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "1afff6a91882ec47999f529245a717d10bc4c0fb", version = "0.40.0", default-features = false }
|
||||
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "1afff6a91882ec47999f529245a717d10bc4c0fb", 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 = "1bbef5758bfe27aed9b14c38c312de6ebe24a122", version = "0.63.0", default-features = false }
|
||||
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "1afff6a91882ec47999f529245a717d10bc4c0fb", version = "0.63.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 = "1bbef5758bfe27aed9b14c38c312de6ebe24a122", default-features = false }
|
||||
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "1afff6a91882ec47999f529245a717d10bc4c0fb", default-features = false }
|
||||
|
||||
# Async Runtime and Networking
|
||||
async-channel = "2.5.0"
|
||||
|
||||
@@ -178,13 +178,6 @@ pub(crate) struct RequestHead {
|
||||
/// There is deliberately no generic extension lookup: a payload the app layer
|
||||
/// needs gets a named field here, so an edge that builds an envelope can see
|
||||
/// everything it has to supply.
|
||||
#[cfg_attr(
|
||||
not(test),
|
||||
expect(
|
||||
dead_code,
|
||||
reason = "fields read only by the crate-private accessors stay unread until call sites move in T1.8 (rustfs/backlog#2749)"
|
||||
)
|
||||
)]
|
||||
pub struct RequestEnvelope {
|
||||
method: Method,
|
||||
uri: Uri,
|
||||
@@ -286,10 +279,6 @@ impl RequestEnvelope {
|
||||
/// budget. The table publication guards are one shared set, so a lock the copy's
|
||||
/// authorization retains stays held for the original's write too. Anything else installed on
|
||||
/// the copy does not show on the original.
|
||||
#[cfg_attr(
|
||||
not(test),
|
||||
expect(dead_code, reason = "the PutObject archive member loop of batch D is its first caller")
|
||||
)]
|
||||
pub(crate) fn fork_for_authorization(&self) -> Self {
|
||||
Self {
|
||||
method: self.method.clone(),
|
||||
|
||||
@@ -422,9 +422,7 @@ async fn website_head_redirect(
|
||||
req_info.cred = None;
|
||||
req_info.is_owner = false;
|
||||
S3Access::head_object(&crate::storage::ecfs::FS::with_server_ctx(Arc::clone(server_ctx)), &mut request).await?;
|
||||
let response = DefaultObjectUsecase::with_context(server_ctx.installed_app_context())
|
||||
.execute_head_object(request)
|
||||
.await?;
|
||||
let response = s3s::S3::head_object(&crate::storage::ecfs::FS::with_server_ctx(Arc::clone(server_ctx)), request).await?;
|
||||
Ok(response.output.website_redirect_location)
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
use super::*;
|
||||
use crate::app::storage_api::s3::dto::{
|
||||
CompleteMultipartUploadInput, CompleteMultipartUploadOutput, CompletedPart, ETag, ServerSideEncryption,
|
||||
ChecksumType, CompleteMultipartUploadInput, CompleteMultipartUploadOutput, CompletedPart, ETag, ServerSideEncryption,
|
||||
};
|
||||
use crate::app::storage_api::s3::header::{
|
||||
X_AMZ_OBJECT_LOCK_LEGAL_HOLD, X_AMZ_OBJECT_LOCK_MODE, X_AMZ_OBJECT_LOCK_RETAIN_UNTIL_DATE,
|
||||
@@ -560,7 +560,7 @@ impl DefaultMultipartUsecase {
|
||||
None
|
||||
};
|
||||
let checksum_type = if disclose_checksums {
|
||||
classified.checksum_type.or(input.checksum_type)
|
||||
classified.checksum_type.map(ChecksumType::from).or(input.checksum_type)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -17,8 +17,8 @@
|
||||
use super::*;
|
||||
use crate::app::storage_api::object_usecase::object_utils::to_s3s_xml_etag;
|
||||
use crate::app::storage_api::s3::dto::{
|
||||
CopyObjectInput, CopyObjectOutput, CopyObjectResult, CopySource, ETag, MetadataDirective, StorageClass, TaggingDirective,
|
||||
Timestamp,
|
||||
ChecksumType, CopyObjectInput, CopyObjectOutput, CopyObjectResult, CopySource, ETag, MetadataDirective, StorageClass,
|
||||
TaggingDirective, Timestamp,
|
||||
};
|
||||
use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Request, S3Response, S3Result, s3_error};
|
||||
use futures::FutureExt;
|
||||
@@ -912,7 +912,7 @@ impl DefaultObjectUsecase {
|
||||
checksum_xxhash3,
|
||||
checksum_xxhash64,
|
||||
checksum_xxhash128,
|
||||
checksum_type: response_checksums.checksum_type,
|
||||
checksum_type: response_checksums.checksum_type.map(ChecksumType::from),
|
||||
};
|
||||
|
||||
let output = CopyObjectOutput {
|
||||
|
||||
@@ -4165,7 +4165,7 @@ impl DefaultObjectUsecase {
|
||||
checksum_sha1: checksums.sha1,
|
||||
checksum_sha256: checksums.sha256,
|
||||
checksum_crc64nvme: checksums.crc64nvme,
|
||||
checksum_type: checksums.checksum_type,
|
||||
checksum_type: checksums.checksum_type.map(ChecksumType::from),
|
||||
version_id: output_version_id,
|
||||
restore,
|
||||
expiration,
|
||||
@@ -4855,7 +4855,7 @@ impl DefaultObjectUsecase {
|
||||
checksum_sha1,
|
||||
checksum_sha256,
|
||||
checksum_crc64nvme,
|
||||
checksum_type,
|
||||
checksum_type: checksum_type.map(ChecksumType::from),
|
||||
..Default::default()
|
||||
})
|
||||
} else {
|
||||
@@ -6362,8 +6362,7 @@ mod tests {
|
||||
http::header::IF_NONE_MATCH,
|
||||
HeaderValue::from_str(&format!("\"{etag}\"")).expect("ETag header"),
|
||||
);
|
||||
let error = usecase
|
||||
.execute_head_object(req)
|
||||
let error = crate::app::test_seams::head_object(&usecase, req)
|
||||
.await
|
||||
.expect_err("conditional HEAD returns 304");
|
||||
assert_eq!(error.code(), &S3ErrorCode::NotModified);
|
||||
|
||||
+328
-193
@@ -16,17 +16,103 @@
|
||||
|
||||
use super::veeam_sosapi;
|
||||
use super::*;
|
||||
use crate::app::storage_api::object_usecase::access::replication_proxy_allowed;
|
||||
use crate::app::storage_api::s3::dto::{
|
||||
ChecksumType, ContentType, ETag, HeadObjectInput, HeadObjectOutput, SSECustomerAlgorithm, ServerSideEncryption, StorageClass,
|
||||
Timestamp,
|
||||
};
|
||||
|
||||
use crate::app::dto_values::{stored_etag, timestamp};
|
||||
use crate::app::storage_api::s3::header::X_AMZ_RESTORE;
|
||||
use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Request, S3Response, S3Result, s3_error};
|
||||
use crate::app::{Answered, RequestEnvelope};
|
||||
use rustfs_gateway_types::ByteRange;
|
||||
#[cfg(feature = "gateway-stack")]
|
||||
use rustfs_gateway_types::RangeParse;
|
||||
use rustfs_gateway_types::dto as gateway_dto;
|
||||
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result, s3_error};
|
||||
|
||||
use crate::on_demand_migration::{
|
||||
BucketOdmState, HeadPolicy, OdmLookup, OdmOp, OdmOutcome, OnDemandMigrationSys, SourceClient, SourceError, SourceHead,
|
||||
};
|
||||
|
||||
/// The DTO holds ordinary fields; ETag remains a native fact until either edge encodes it.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct HeadObjectOutputFacts {
|
||||
pub(crate) dto: gateway_dto::HeadObjectOutput,
|
||||
pub(crate) etag: Option<ResponseEtag>,
|
||||
}
|
||||
|
||||
/// Stored spellings may be weak, empty, or unencodable as an HTTP header.
|
||||
/// Neither normalization nor header validation may erase that fact before the response edge.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct ResponseEtag {
|
||||
pub(crate) opaque: String,
|
||||
pub(crate) weak: bool,
|
||||
}
|
||||
|
||||
impl ResponseEtag {
|
||||
fn from_stored(value: &str) -> Self {
|
||||
let weak = value.starts_with("W/\"");
|
||||
let etag = stored_etag(value);
|
||||
Self {
|
||||
opaque: etag.opaque_tag().to_owned(),
|
||||
weak,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_proxy(value: &str) -> Option<Self> {
|
||||
let (opaque, weak) = if let Some(rest) = value.strip_prefix("W/\"") {
|
||||
(rest.strip_suffix('"')?, true)
|
||||
} else if let Some(rest) = value.strip_prefix('"') {
|
||||
(rest.strip_suffix('"')?, false)
|
||||
} else {
|
||||
if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') {
|
||||
return None;
|
||||
}
|
||||
(value, false)
|
||||
};
|
||||
opaque
|
||||
.bytes()
|
||||
.all(|byte| byte == b'\t' || (b' '..=b'~').contains(&byte))
|
||||
.then(|| Self {
|
||||
opaque: opaque.to_owned(),
|
||||
weak,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw decoded fields preserve legacy validation order, including keys below the wire floor.
|
||||
/// No Debug implementation: the customer key is bearer material.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct HeadObjectFields {
|
||||
pub(crate) bucket: String,
|
||||
pub(crate) key: String,
|
||||
pub(crate) version_id: Option<String>,
|
||||
pub(crate) part_number: Option<i32>,
|
||||
pub(crate) range: Option<ByteRange>,
|
||||
pub(crate) sse_customer_key: Option<String>,
|
||||
pub(crate) sse_customer_key_md5: Option<String>,
|
||||
}
|
||||
|
||||
async fn head_answer(
|
||||
bucket: &str,
|
||||
method: &http::Method,
|
||||
headers: &HeaderMap,
|
||||
output: HeadObjectOutputFacts,
|
||||
) -> Answered<HeadObjectOutputFacts> {
|
||||
let mut answer = Answered::new(output);
|
||||
if headers.contains_key(http::header::ORIGIN)
|
||||
&& let Some(cors) = crate::app::storage_api::object_usecase::head_cors_headers(bucket, method, headers).await
|
||||
{
|
||||
answer.headers = cors;
|
||||
}
|
||||
answer
|
||||
}
|
||||
|
||||
fn complete_head(helper: OperationHelper, result: &S3Result<Answered<HeadObjectOutputFacts>>) {
|
||||
let headers = HeaderMap::new();
|
||||
let (status, headers) = match result {
|
||||
Ok(answer) => (answer.status.unwrap_or(StatusCode::OK), &answer.headers),
|
||||
Err(_) => (StatusCode::OK, &headers),
|
||||
};
|
||||
let _ = helper.complete_owned(result, status, headers);
|
||||
}
|
||||
|
||||
/// Whether the caller asked for the tag set itself (`x-amz-tagging-directive: ACCESS`).
|
||||
fn tagging_directive_is_access(headers: &http::HeaderMap) -> bool {
|
||||
headers
|
||||
@@ -34,28 +120,18 @@ fn tagging_directive_is_access(headers: &http::HeaderMap) -> bool {
|
||||
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"ACCESS"))
|
||||
}
|
||||
|
||||
async fn head_metadata_action_allowed(req: &S3Request<HeadObjectInput>, action: S3Action) -> S3Result<bool> {
|
||||
let Ok(info) = req_info_ref(req) else {
|
||||
async fn head_metadata_action_allowed(req: &RequestEnvelope, action: S3Action) -> S3Result<bool> {
|
||||
// Metadata permissions still bind the owner when a policy explicitly denies them.
|
||||
let mut probe = req.fork_for_authorization();
|
||||
let Some(info) = probe.req_info_mut() else {
|
||||
return Ok(false);
|
||||
};
|
||||
// No owner shortcut: an explicit bucket-policy Deny on these metadata
|
||||
// actions binds the owner too (see `owner_can_bypass_policy_deny`).
|
||||
let mut info = info.clone();
|
||||
info.suppress_denial_log = true;
|
||||
info.suppress_denial_audit = true;
|
||||
let mut probe = S3Request {
|
||||
input: (),
|
||||
method: req.method.clone(),
|
||||
uri: req.uri.clone(),
|
||||
headers: req.headers.clone(),
|
||||
extensions: req.extensions.clone(),
|
||||
credentials: req.credentials.clone(),
|
||||
region: req.region.clone(),
|
||||
service: req.service.clone(),
|
||||
trailing_headers: req.trailing_headers.clone(),
|
||||
};
|
||||
probe.extensions.insert(info);
|
||||
match authorize_request(&mut probe, Action::S3Action(action)).await {
|
||||
match authorize_request(&mut probe, Action::S3Action(action))
|
||||
.await
|
||||
.map_err(S3Error::from)
|
||||
{
|
||||
Ok(()) => Ok(true),
|
||||
Err(err) if err.code() == &S3ErrorCode::AccessDenied => Ok(false),
|
||||
Err(err) => Err(err),
|
||||
@@ -100,7 +176,7 @@ pub(super) fn odm_head_verdict(lookup: OdmLookup, miss: OdmLocalMiss) -> OdmHead
|
||||
let stats = state.stats();
|
||||
let unavailable = |error| {
|
||||
stats.record_request(OdmOp::Head, OdmOutcome::SourceError);
|
||||
OdmHeadVerdict::Fail(odm_source_error_response(policy, odm_state_error_class(error)))
|
||||
OdmHeadVerdict::Fail(odm_source_error_response(policy, odm_state_error_class(error)).into())
|
||||
};
|
||||
match &lookup {
|
||||
OdmLookup::NegativeCached { .. } => {
|
||||
@@ -128,27 +204,30 @@ pub(super) fn odm_head_verdict(lookup: OdmLookup, miss: OdmLocalMiss) -> OdmHead
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps the source's HEAD onto the s3s output. Only what the source can
|
||||
/// Maps the source's HEAD onto the owned output. Only what the source can
|
||||
/// vouch for is returned: the ETag and Last-Modified are the source's (the
|
||||
/// object is not local yet), no version id, no SSE headers and no storage
|
||||
/// class are reported.
|
||||
pub(super) fn odm_head_output(head: SourceHead) -> S3Result<HeadObjectOutput> {
|
||||
pub(super) fn odm_head_output(head: SourceHead) -> S3Result<HeadObjectOutputFacts> {
|
||||
let content_length = i64::try_from(head.size)
|
||||
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, "source object size exceeds the content-length range"))?;
|
||||
Ok(HeadObjectOutput {
|
||||
let dto = gateway_dto::HeadObjectOutput {
|
||||
content_length: Some(content_length),
|
||||
content_type: head.content_type.as_deref().and_then(|v| ContentType::from_str(v).ok()),
|
||||
content_type: head.content_type,
|
||||
content_encoding: head.content_encoding,
|
||||
content_disposition: head.content_disposition,
|
||||
content_language: head.content_language,
|
||||
cache_control: head.cache_control,
|
||||
expires: head.expires,
|
||||
expires: head.expires.map(Into::into),
|
||||
accept_ranges: Some(ACCEPT_RANGES_BYTES.to_string()),
|
||||
e_tag: head.etag.as_deref().map(to_s3s_etag),
|
||||
last_modified: head.last_modified.map(OffsetDateTime::from).map(Timestamp::from),
|
||||
metadata: (!head.user_metadata.is_empty()).then_some(head.user_metadata),
|
||||
last_modified: head.last_modified.map(OffsetDateTime::from).map(timestamp),
|
||||
metadata: head.user_metadata.into_iter().collect(),
|
||||
website_redirect_location: head.website_redirect_location,
|
||||
..Default::default()
|
||||
};
|
||||
Ok(HeadObjectOutputFacts {
|
||||
dto,
|
||||
etag: head.etag.as_deref().map(ResponseEtag::from_stored),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -159,7 +238,7 @@ pub(super) async fn odm_head_from_source<S: OdmHeadSource>(
|
||||
state: &BucketOdmState,
|
||||
source: &S,
|
||||
key: &str,
|
||||
) -> S3Result<HeadObjectOutput> {
|
||||
) -> S3Result<HeadObjectOutputFacts> {
|
||||
let started = Instant::now();
|
||||
let result = source.head_object(key).await;
|
||||
state.observe_source(started.elapsed(), key, result.as_ref().err());
|
||||
@@ -175,28 +254,40 @@ pub(super) async fn odm_head_from_source<S: OdmHeadSource>(
|
||||
}
|
||||
Err(err @ SourceError::Unsupported(_)) => {
|
||||
stats.record_request(OdmOp::Head, OdmOutcome::Unsupported);
|
||||
Err(odm_source_unavailable_error(err.class_label()))
|
||||
Err(odm_source_unavailable_error(err.class_label()).into())
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_request(OdmOp::Head, OdmOutcome::SourceError);
|
||||
Err(odm_source_error_response(&state.config().policy, err.class_label()))
|
||||
Err(odm_source_error_response(&state.config().policy, err.class_label()).into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl DefaultObjectUsecase {
|
||||
async fn execute_head_object_from_s3s(
|
||||
&self,
|
||||
req: crate::app::storage_api::s3::S3Request<crate::app::storage_api::s3::dto::HeadObjectInput>,
|
||||
) -> crate::app::storage_api::s3::S3Result<
|
||||
crate::app::storage_api::s3::S3Response<crate::app::storage_api::s3::dto::HeadObjectOutput>,
|
||||
> {
|
||||
crate::app::test_seams::head_object(self, req).await
|
||||
}
|
||||
}
|
||||
|
||||
impl DefaultObjectUsecase {
|
||||
/// On-demand migration HEAD passthrough (rustfs/backlog#2155): consulted
|
||||
/// only after the local lookup and the replication proxy both missed.
|
||||
/// `None` means the runtime does not intervene and the caller keeps its
|
||||
/// original 404. The source answer is never written back or queued.
|
||||
async fn on_demand_migration_head(
|
||||
req: &S3Request<HeadObjectInput>,
|
||||
req: &RequestEnvelope,
|
||||
store: &ECStore,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
opts: &ObjectOptions,
|
||||
miss: OdmLocalMiss,
|
||||
) -> Option<S3Result<HeadObjectOutput>> {
|
||||
) -> Option<S3Result<HeadObjectOutputFacts>> {
|
||||
if !odm_request_may_consult_source(opts) {
|
||||
return None;
|
||||
}
|
||||
@@ -216,7 +307,7 @@ impl DefaultObjectUsecase {
|
||||
let expected_incarnation = match odm_read_generation(req, bucket) {
|
||||
Ok(Some(incarnation)) => incarnation,
|
||||
Ok(None) => return None,
|
||||
Err(err) => return Some(Err(err)),
|
||||
Err(err) => return Some(Err(err.into())),
|
||||
};
|
||||
match store.bucket_incarnation_id(bucket).await {
|
||||
Ok(current) if current == expected_incarnation => {}
|
||||
@@ -235,37 +326,37 @@ impl DefaultObjectUsecase {
|
||||
}
|
||||
|
||||
async fn finish_on_demand_migration_head(
|
||||
req: &S3Request<HeadObjectInput>,
|
||||
req: &RequestEnvelope,
|
||||
bucket: &str,
|
||||
helper: OperationHelper,
|
||||
output: HeadObjectOutput,
|
||||
) -> S3Result<S3Response<HeadObjectOutput>> {
|
||||
let mut response = wrap_response_with_cors(bucket, &req.method, &req.headers, output).await;
|
||||
output: HeadObjectOutputFacts,
|
||||
) -> S3Result<Answered<HeadObjectOutputFacts>> {
|
||||
let mut response = head_answer(bucket, req.method(), req.headers(), output).await;
|
||||
mark_on_demand_migration_response(&mut response.headers);
|
||||
let result = Ok(response);
|
||||
let _ = helper.complete(&result);
|
||||
complete_head(helper, &result);
|
||||
result
|
||||
}
|
||||
|
||||
/// Serve a HEAD whose local lookup failed with not-found by proxying to
|
||||
/// the bucket's replication targets (MinIO `proxyHeadToRepTarget`).
|
||||
async fn proxy_head_object_to_replication_targets(
|
||||
req: &S3Request<HeadObjectInput>,
|
||||
req: &RequestEnvelope,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
opts: &ObjectOptions,
|
||||
) -> Option<HeadObjectOutput> {
|
||||
part_number: Option<i32>,
|
||||
) -> Option<HeadObjectOutputFacts> {
|
||||
let targets = get_read_proxy_targets(bucket, key, opts).await;
|
||||
if targets.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let extra_headers = Self::proxy_read_passthrough_headers(&req.headers);
|
||||
let extra_headers = Self::proxy_read_passthrough_headers(req.headers());
|
||||
let range = req
|
||||
.headers
|
||||
.headers()
|
||||
.get(http::header::RANGE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_owned);
|
||||
let part_number = req.input.part_number;
|
||||
|
||||
for target in targets {
|
||||
match target
|
||||
@@ -283,7 +374,7 @@ impl DefaultObjectUsecase {
|
||||
// MinIO-aligned accounting: one total per proxy attempt,
|
||||
// one failed when no target served it.
|
||||
record_replication_proxy(bucket, "HeadObject", false).await;
|
||||
return Some(Self::proxy_sdk_head_output_to_s3s(remote));
|
||||
return Some(Self::proxy_sdk_head_output(remote));
|
||||
}
|
||||
Err(err) if Self::proxy_sdk_error_is_not_found(&err) => {
|
||||
debug!(bucket, key, arn = %target.arn, "read proxy: target does not have the object");
|
||||
@@ -297,38 +388,39 @@ impl DefaultObjectUsecase {
|
||||
None
|
||||
}
|
||||
|
||||
/// Translate a proxied SDK HEAD response into the s3s output.
|
||||
/// Translate a proxied SDK HEAD response into the owned output.
|
||||
///
|
||||
/// Known gaps: the SDK's HeadObjectOutput does not model 206/Content-Range
|
||||
/// for a ranged HEAD (the SDK exposes no content_range member on HEAD),
|
||||
/// and s3s' typed HeadObjectOutput has no tag_count field (the local path
|
||||
/// and the typed HeadObjectOutput has no tag_count field (the local path
|
||||
/// injects x-amz-tagging-count as a raw header) — both are dropped for
|
||||
/// proxied HEADs.
|
||||
fn proxy_sdk_head_output_to_s3s(remote: aws_sdk_s3::operation::head_object::HeadObjectOutput) -> HeadObjectOutput {
|
||||
HeadObjectOutput {
|
||||
fn proxy_sdk_head_output(remote: aws_sdk_s3::operation::head_object::HeadObjectOutput) -> HeadObjectOutputFacts {
|
||||
let dto = gateway_dto::HeadObjectOutput {
|
||||
content_length: remote.content_length,
|
||||
content_type: remote.content_type.as_deref().and_then(|v| ContentType::from_str(v).ok()),
|
||||
content_type: remote.content_type,
|
||||
content_encoding: remote.content_encoding,
|
||||
content_disposition: remote.content_disposition,
|
||||
content_language: remote.content_language,
|
||||
cache_control: remote.cache_control,
|
||||
accept_ranges: Some(ACCEPT_RANGES_BYTES.to_string()),
|
||||
e_tag: remote.e_tag.as_deref().and_then(|v| ETag::from_str(v).ok()),
|
||||
last_modified: remote
|
||||
.last_modified
|
||||
.and_then(|dt| OffsetDateTime::from_unix_timestamp_nanos(dt.as_nanos()).ok())
|
||||
.map(Timestamp::from),
|
||||
metadata: remote.metadata,
|
||||
.map(timestamp),
|
||||
metadata: remote.metadata.unwrap_or_default().into_iter().collect(),
|
||||
version_id: remote.version_id,
|
||||
server_side_encryption: remote
|
||||
.server_side_encryption
|
||||
.map(|sse| ServerSideEncryption::from(sse.as_str().to_string())),
|
||||
.map(|sse| gateway_dto::ServerSideEncryption::custom(sse.as_str().to_string())),
|
||||
sse_customer_algorithm: remote.sse_customer_algorithm,
|
||||
sse_customer_key_md5: remote.sse_customer_key_md5,
|
||||
ssekms_key_id: remote.ssekms_key_id,
|
||||
parts_count: remote.parts_count,
|
||||
storage_class: remote.storage_class.map(|sc| StorageClass::from(sc.as_str().to_string())),
|
||||
expiration: remote.expiration,
|
||||
storage_class: remote
|
||||
.storage_class
|
||||
.map(|sc| gateway_dto::StorageClass::custom(sc.as_str().to_string())),
|
||||
expiration: remote.expiration.map(Into::into),
|
||||
restore: remote.restore,
|
||||
website_redirect_location: remote.website_redirect_location,
|
||||
checksum_crc32: remote.checksum_crc32,
|
||||
@@ -336,34 +428,41 @@ impl DefaultObjectUsecase {
|
||||
checksum_crc64nvme: remote.checksum_crc64_nvme,
|
||||
checksum_sha1: remote.checksum_sha1,
|
||||
checksum_sha256: remote.checksum_sha256,
|
||||
checksum_type: remote.checksum_type.map(|ct| ChecksumType::from(ct.as_str().to_string())),
|
||||
checksum_type: remote
|
||||
.checksum_type
|
||||
.map(|ct| gateway_dto::ChecksumType::custom(ct.as_str().to_string())),
|
||||
..Default::default()
|
||||
};
|
||||
HeadObjectOutputFacts {
|
||||
dto,
|
||||
etag: remote.e_tag.as_deref().and_then(ResponseEtag::from_proxy),
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve_veeam_sosapi_head(
|
||||
&self,
|
||||
req: &S3Request<HeadObjectInput>,
|
||||
req: &RequestEnvelope,
|
||||
bucket: &str,
|
||||
store: &Arc<ECStore>,
|
||||
kind: veeam_sosapi::SosapiKind,
|
||||
part_number: Option<usize>,
|
||||
range: Option<&HTTPRangeSpec>,
|
||||
) -> S3Result<S3Response<HeadObjectOutput>> {
|
||||
let representation =
|
||||
veeam_sosapi::read_representation(store, &req.input.bucket, kind, &req.headers, part_number, range).await?;
|
||||
let content_type = ContentType::from_str(veeam_sosapi::CONTENT_TYPE)
|
||||
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, "invalid SOSAPI content type"))?;
|
||||
) -> S3Result<Answered<HeadObjectOutputFacts>> {
|
||||
let representation = veeam_sosapi::read_representation(store, bucket, kind, req.headers(), part_number, range).await?;
|
||||
let content_type = veeam_sosapi::CONTENT_TYPE.to_owned();
|
||||
let content_range = representation.content_range;
|
||||
let output = HeadObjectOutput {
|
||||
let dto = gateway_dto::HeadObjectOutput {
|
||||
content_length: Some(representation.content_length),
|
||||
content_type: Some(content_type),
|
||||
accept_ranges: Some(ACCEPT_RANGES_BYTES.to_string()),
|
||||
last_modified: Some(Timestamp::from(representation.last_modified)),
|
||||
e_tag: Some(to_s3s_etag(&representation.etag_hex)),
|
||||
last_modified: Some(timestamp(representation.last_modified)),
|
||||
..Default::default()
|
||||
};
|
||||
let mut response = wrap_response_with_cors(&req.input.bucket, &req.method, &req.headers, output).await;
|
||||
inject_accept_ranges_header(&mut response.headers);
|
||||
let output = HeadObjectOutputFacts {
|
||||
dto,
|
||||
etag: Some(ResponseEtag::from_stored(&representation.etag_hex)),
|
||||
};
|
||||
let mut response = head_answer(bucket, req.method(), req.headers(), output).await;
|
||||
if let Some(content_range) = content_range {
|
||||
response.headers.insert(
|
||||
http::header::CONTENT_RANGE,
|
||||
@@ -375,29 +474,56 @@ impl DefaultObjectUsecase {
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[instrument(level = "debug", skip(self, req))]
|
||||
pub async fn execute_head_object(&self, mut req: S3Request<HeadObjectInput>) -> S3Result<S3Response<HeadObjectOutput>> {
|
||||
#[cfg(feature = "gateway-stack")]
|
||||
pub(crate) async fn execute_head_object(
|
||||
&self,
|
||||
envelope: RequestEnvelope,
|
||||
input: gateway_dto::HeadObjectInput,
|
||||
) -> S3Result<Answered<HeadObjectOutputFacts>> {
|
||||
self.execute_head_object_fields(
|
||||
envelope,
|
||||
HeadObjectFields {
|
||||
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,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[instrument(level = "debug", skip(self, req, input))]
|
||||
pub(crate) async fn execute_head_object_fields(
|
||||
&self,
|
||||
mut req: RequestEnvelope,
|
||||
input: HeadObjectFields,
|
||||
) -> S3Result<Answered<HeadObjectOutputFacts>> {
|
||||
if let Some(context) = &self.context {
|
||||
let _ = context.object_store();
|
||||
}
|
||||
|
||||
let mut helper = OperationHelper::new(&req, EventName::ObjectAccessedHead, S3Operation::HeadObject).suppress_event();
|
||||
// mc get 2
|
||||
let HeadObjectInput {
|
||||
let mut helper = OperationHelper::from_view(&req.audit_view(), EventName::ObjectAccessedHead, S3Operation::HeadObject)
|
||||
.suppress_event();
|
||||
let HeadObjectFields {
|
||||
bucket,
|
||||
key,
|
||||
version_id,
|
||||
part_number,
|
||||
range,
|
||||
..
|
||||
} = req.input.clone();
|
||||
|
||||
} = input.clone();
|
||||
// Validate object key
|
||||
validate_object_key(&key, "HEAD")?;
|
||||
// Parse part number from Option<i32> to Option<usize> with validation
|
||||
let part_number: Option<usize> = parse_part_number_i32_to_usize(part_number, "HEAD")?;
|
||||
|
||||
let rs = range.map(range_to_http_range_spec).transpose()?;
|
||||
let rs = range.map(byte_range_to_http_range_spec).transpose()?;
|
||||
|
||||
if rs.is_some() && part_number.is_some() {
|
||||
return Err(s3_error!(InvalidArgument, "range and part_number invalid"));
|
||||
@@ -417,14 +543,14 @@ impl DefaultObjectUsecase {
|
||||
&& let Some(kind) = veeam_sosapi::handled_kind(&key)
|
||||
{
|
||||
let response = self
|
||||
.serve_veeam_sosapi_head(&req, &store, kind, part_number, rs.as_ref())
|
||||
.serve_veeam_sosapi_head(&req, &bucket, &store, kind, part_number, rs.as_ref())
|
||||
.await?;
|
||||
let result = Ok(response);
|
||||
let _ = helper.complete(&result);
|
||||
complete_head(helper, &result);
|
||||
return result;
|
||||
}
|
||||
|
||||
let mut opts: ObjectOptions = get_opts(&bucket, &key, version_id, part_number, &req.headers)
|
||||
let mut opts: ObjectOptions = get_opts(&bucket, &key, version_id, part_number, req.headers())
|
||||
.await
|
||||
.map_err(ApiError::from)?;
|
||||
if is_lockless_cache_bucket(&bucket) {
|
||||
@@ -460,14 +586,13 @@ impl DefaultObjectUsecase {
|
||||
// Active-active replication lag window: an object missing
|
||||
// locally may still be served by proxying the HEAD to a
|
||||
// replication target (backlog#1675 P1-5).
|
||||
if replication_proxy_allowed(&req.extensions)
|
||||
&& let Some(output) = Self::proxy_head_object_to_replication_targets(&req, &bucket, &key, &opts).await
|
||||
if req.object_tag_conditions().is_none()
|
||||
&& let Some(output) =
|
||||
Self::proxy_head_object_to_replication_targets(&req, &bucket, &key, &opts, input.part_number).await
|
||||
{
|
||||
let response = wrap_response_with_cors(&bucket, &req.method, &req.headers, output).await;
|
||||
let response = head_answer(&bucket, req.method(), req.headers(), output).await;
|
||||
let result = Ok(response);
|
||||
let _ = helper
|
||||
.version_id(req.input.version_id.clone().unwrap_or_default())
|
||||
.complete(&result);
|
||||
complete_head(helper.version_id(input.version_id.clone().unwrap_or_default()), &result);
|
||||
return result;
|
||||
}
|
||||
if let Some(miss) = odm_miss
|
||||
@@ -480,12 +605,15 @@ impl DefaultObjectUsecase {
|
||||
&bucket,
|
||||
&key,
|
||||
&opts,
|
||||
S3Error::new(S3ErrorCode::NoSuchKey),
|
||||
S3Error::new(S3ErrorCode::NoSuchKey).into(),
|
||||
)
|
||||
.await);
|
||||
.await
|
||||
.into());
|
||||
}
|
||||
// Other errors, such as insufficient permissions, still return the original error
|
||||
return Err(enrich_delete_marker_read_error(&store, &bucket, &key, &opts, ApiError::from(err).into()).await);
|
||||
return Err(enrich_delete_marker_read_error(&store, &bucket, &key, &opts, ApiError::from(err).into())
|
||||
.await
|
||||
.into());
|
||||
}
|
||||
};
|
||||
if info.delete_marker {
|
||||
@@ -497,35 +625,32 @@ impl DefaultObjectUsecase {
|
||||
{
|
||||
return Self::finish_on_demand_migration_head(&req, &bucket, helper, result?).await;
|
||||
}
|
||||
return Err(with_delete_marker_read_headers(S3Error::new(S3ErrorCode::NoSuchKey), &info, None));
|
||||
return Err(with_delete_marker_read_headers(S3Error::new(S3ErrorCode::NoSuchKey).into(), &info, None).into());
|
||||
}
|
||||
return Err(with_delete_marker_read_headers(
|
||||
S3Error::new(S3ErrorCode::MethodNotAllowed),
|
||||
S3Error::new(S3ErrorCode::MethodNotAllowed).into(),
|
||||
&info,
|
||||
opts.version_id.as_deref(),
|
||||
));
|
||||
)
|
||||
.into());
|
||||
}
|
||||
// An authorized replication convergence check only needs etag/size/mtime
|
||||
// to compare source and replica; it holds no customer key, so the SSE-C
|
||||
// read validation is skipped for it (and only it).
|
||||
let replication_check = replication_request_authorized(&req)
|
||||
&& get_header(&req.headers, SUFFIX_SOURCE_REPLICATION_CHECK).as_deref() == Some("true");
|
||||
&& get_header(req.headers(), SUFFIX_SOURCE_REPLICATION_CHECK).as_deref() == Some("true");
|
||||
if !replication_check {
|
||||
validate_sse_headers_for_read(&info.user_defined, &req.headers)?;
|
||||
validate_sse_headers_for_read(&info.user_defined, req.headers())?;
|
||||
|
||||
// Validate SSE-C: if the object was encrypted with a customer-provided key,
|
||||
// the caller must supply the matching key even for HEAD requests (per S3 spec).
|
||||
validate_ssec_for_read(
|
||||
&info.user_defined,
|
||||
req.input.sse_customer_key.as_ref(),
|
||||
req.input.sse_customer_key_md5.as_ref(),
|
||||
)?;
|
||||
validate_ssec_for_read(&info.user_defined, input.sse_customer_key.as_ref(), input.sse_customer_key_md5.as_ref())?;
|
||||
}
|
||||
|
||||
let conditions = check_preconditions(&req.headers, &info);
|
||||
let conditions = check_preconditions(req.headers(), &info);
|
||||
if conditions.is_err() && !replication_check {
|
||||
let principal = SseKmsPrincipal::from_request(&req);
|
||||
crate::storage::sse::validate_conditional_read(&bucket, &key, &info.user_defined, &req.headers, principal.as_ref())
|
||||
crate::storage::sse::validate_conditional_read(&bucket, &key, &info.user_defined, req.headers(), principal.as_ref())
|
||||
.await?;
|
||||
}
|
||||
conditions?;
|
||||
@@ -535,21 +660,8 @@ impl DefaultObjectUsecase {
|
||||
// Clone ObjectInfo for event notification only when an event will
|
||||
// actually be built — the clone is expensive for multipart objects.
|
||||
let event_info = helper.wants_object_info().then(|| info.clone());
|
||||
let content_type = {
|
||||
if let Some(content_type) = &info.content_type {
|
||||
match ContentType::from_str(content_type) {
|
||||
Ok(res) => Some(res),
|
||||
Err(err) => {
|
||||
error!(content_type = %content_type, error = ?err, "Archive content-type parse failed");
|
||||
//
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let last_modified = info.mod_time.map(Timestamp::from);
|
||||
let content_type = info.content_type.clone();
|
||||
let last_modified = info.mod_time.map(timestamp);
|
||||
|
||||
let content_length = info.get_actual_size().map_err(|e| {
|
||||
error!(error = %e, "Failed to resolve actual object size");
|
||||
@@ -557,16 +669,14 @@ impl DefaultObjectUsecase {
|
||||
})?;
|
||||
|
||||
let metadata_map = info.user_defined.clone();
|
||||
let sse_customer_algorithm = metadata_map
|
||||
.get("x-amz-server-side-encryption-customer-algorithm")
|
||||
.map(|v| SSECustomerAlgorithm::from(v.clone()));
|
||||
let sse_customer_algorithm = metadata_map.get("x-amz-server-side-encryption-customer-algorithm").cloned();
|
||||
let server_side_encryption = metadata_map
|
||||
.get("x-amz-server-side-encryption")
|
||||
.filter(|_| sse_customer_algorithm.is_none())
|
||||
.map(|v| ServerSideEncryption::from(v.clone()));
|
||||
.map(|v| gateway_dto::ServerSideEncryption::custom(v.clone()));
|
||||
let sse_customer_key_md5 = metadata_map.get("x-amz-server-side-encryption-customer-key-md5").cloned();
|
||||
let sse_kms_key_id = metadata_map.get("x-amz-server-side-encryption-aws-kms-key-id").cloned();
|
||||
let storage_class = response_storage_class(&info, &metadata_map);
|
||||
let storage_class = response_storage_class_name(&info, &metadata_map);
|
||||
// checksum: classify once; additional algorithms (XXHash3/64/128, SHA-512, MD5)
|
||||
// land in `extra` and are emitted as raw headers below (s3s has no typed field).
|
||||
let ResponseChecksums {
|
||||
@@ -577,12 +687,12 @@ impl DefaultObjectUsecase {
|
||||
crc64nvme: checksum_crc64nvme,
|
||||
checksum_type,
|
||||
extra: extra_checksum_headers,
|
||||
} = if let Some(checksum_mode) = req.headers.get(AMZ_CHECKSUM_MODE)
|
||||
} = if let Some(checksum_mode) = req.headers().get(AMZ_CHECKSUM_MODE)
|
||||
&& checksum_mode.to_str().unwrap_or_default() == "ENABLED"
|
||||
&& rs.is_none()
|
||||
{
|
||||
let (checksums, is_multipart) = info
|
||||
.decrypt_checksums(opts.part_number.unwrap_or(0), &req.headers)
|
||||
.decrypt_checksums(opts.part_number.unwrap_or(0), req.headers())
|
||||
.map_err(ApiError::from)?;
|
||||
classify_response_checksums(checksums, is_multipart)
|
||||
} else {
|
||||
@@ -596,8 +706,7 @@ impl DefaultObjectUsecase {
|
||||
let website_redirect_location = metadata_map.get(AMZ_WEBSITE_REDIRECT_LOCATION).cloned();
|
||||
let expires = info
|
||||
.expires
|
||||
.map(Timestamp::from)
|
||||
.map(|expires| format_expires_header(&expires))
|
||||
.map(|expires| expires.format(RFC1123).map_err(S3Error::internal_error))
|
||||
.transpose()?;
|
||||
|
||||
// Calculate tag count from user_tags already in ObjectInfo
|
||||
@@ -608,7 +717,7 @@ impl DefaultObjectUsecase {
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let output = HeadObjectOutput {
|
||||
let dto = gateway_dto::HeadObjectOutput {
|
||||
content_length: Some(content_length),
|
||||
content_type,
|
||||
content_encoding: info.content_encoding.clone(),
|
||||
@@ -617,10 +726,12 @@ impl DefaultObjectUsecase {
|
||||
content_language,
|
||||
accept_ranges: Some(ACCEPT_RANGES_BYTES.to_string()),
|
||||
website_redirect_location,
|
||||
expires,
|
||||
expires: expires.map(Into::into),
|
||||
last_modified,
|
||||
e_tag: info.etag.map(|etag| to_s3s_etag(&etag)),
|
||||
metadata: filter_object_metadata(&metadata_map),
|
||||
metadata: filter_object_metadata(&metadata_map)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.collect(),
|
||||
version_id: s3_response_version_id(info.version_id),
|
||||
server_side_encryption,
|
||||
sse_customer_algorithm,
|
||||
@@ -631,20 +742,21 @@ impl DefaultObjectUsecase {
|
||||
checksum_sha1,
|
||||
checksum_sha256,
|
||||
checksum_crc64nvme,
|
||||
checksum_type,
|
||||
storage_class,
|
||||
checksum_type: checksum_type.map(gateway_dto::ChecksumType::custom),
|
||||
storage_class: storage_class.map(gateway_dto::StorageClass::custom),
|
||||
// x-amz-restore from object metadata
|
||||
restore: metadata_map.get(X_AMZ_RESTORE.as_str()).and_then(|v| {
|
||||
let rs = parse_restore_obj_status(v).ok()?;
|
||||
Some(rs.to_string2())
|
||||
}),
|
||||
restore: None,
|
||||
// x-amz-expiration from lifecycle prediction
|
||||
expiration: expiration_header,
|
||||
expiration: expiration_header.map(Into::into),
|
||||
// metadata: object_metadata,
|
||||
..Default::default()
|
||||
};
|
||||
let output = HeadObjectOutputFacts {
|
||||
dto,
|
||||
etag: info.etag.as_deref().map(ResponseEtag::from_stored),
|
||||
};
|
||||
|
||||
let version_id = req.input.version_id.clone().unwrap_or_default();
|
||||
let version_id = input.version_id.clone().unwrap_or_default();
|
||||
if let Some(event_info) = event_info {
|
||||
helper = helper.object(event_info);
|
||||
}
|
||||
@@ -656,7 +768,7 @@ impl DefaultObjectUsecase {
|
||||
// interact with objects (PUT/POST/DELETE/LIST, etc.) rely on the system-level
|
||||
// CORS layer instead. In case both are applicable, this bucket-level CORS logic
|
||||
// takes precedence for these read operations.
|
||||
let mut response = wrap_response_with_cors(&bucket, &req.method, &req.headers, output).await;
|
||||
let mut response = head_answer(&bucket, req.method(), req.headers(), output).await;
|
||||
|
||||
// Emit additional-checksum headers (XXHash3/64/128, SHA-512) that s3s cannot
|
||||
// carry on the typed HeadObjectOutput (#1257).
|
||||
@@ -664,7 +776,7 @@ impl DefaultObjectUsecase {
|
||||
|
||||
// Add x-amz-tagging-count header if object has tags
|
||||
// Per S3 API spec, this header should be present in HEAD object response when tags exist
|
||||
let tagging_action = if req.input.version_id.is_some() {
|
||||
let tagging_action = if input.version_id.is_some() {
|
||||
S3Action::GetObjectVersionTaggingAction
|
||||
} else {
|
||||
S3Action::GetObjectTaggingAction
|
||||
@@ -679,7 +791,7 @@ impl DefaultObjectUsecase {
|
||||
// MinIO `x-amz-tagging-directive: ACCESS`: a replication source
|
||||
// compares the replica's tag set, which the count cannot express.
|
||||
// Gated by the same authorization as the count above.
|
||||
if tagging_directive_is_access(&req.headers)
|
||||
if tagging_directive_is_access(req.headers())
|
||||
&& let Ok(header_value) = HeaderValue::from_str(&info.user_tags)
|
||||
{
|
||||
response
|
||||
@@ -766,7 +878,7 @@ impl DefaultObjectUsecase {
|
||||
}
|
||||
|
||||
let result = Ok(response);
|
||||
let _ = helper.complete(&result);
|
||||
complete_head(helper, &result);
|
||||
|
||||
result
|
||||
}
|
||||
@@ -776,6 +888,7 @@ impl DefaultObjectUsecase {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app::storage_api::s3::dto::Range;
|
||||
use crate::app::storage_api::s3::{S3Request, dto::HeadObjectInput};
|
||||
use crate::on_demand_migration::{
|
||||
BREAKER_FAILURE_THRESHOLD, BreakerState, FilterConfig, OdmStateError, OnDemandMigrationConfig, PathStyle, PolicyConfig,
|
||||
Provider, SourceConfig, SourceCredentials, SourceErrorPolicy, TlsConfig,
|
||||
@@ -905,34 +1018,45 @@ mod tests {
|
||||
#[test]
|
||||
fn odm_head_output_maps_source_fields_and_hides_local_only_headers() {
|
||||
let output = odm_head_output(source_head()).expect("source HEAD maps");
|
||||
assert_eq!(output.content_length, Some(1234));
|
||||
assert_eq!(output.content_type.as_ref().map(|v| v.to_string()), Some("text/plain".to_string()));
|
||||
assert_eq!(output.content_encoding.as_deref(), Some("gzip"));
|
||||
assert_eq!(output.content_disposition.as_deref(), Some("attachment; filename=\"a.txt\""));
|
||||
assert_eq!(output.content_language.as_deref(), Some("en"));
|
||||
assert_eq!(output.cache_control.as_deref(), Some("max-age=60"));
|
||||
assert_eq!(output.expires.as_deref(), Some("Thu, 01 Jan 2026 00:00:00 GMT"));
|
||||
assert_eq!(output.accept_ranges.as_deref(), Some("bytes"));
|
||||
assert_eq!(output.dto.content_length, Some(1234));
|
||||
assert_eq!(output.dto.content_type.as_ref().map(|v| v.to_string()), Some("text/plain".to_string()));
|
||||
assert_eq!(output.dto.content_encoding.as_deref(), Some("gzip"));
|
||||
assert_eq!(output.dto.content_disposition.as_deref(), Some("attachment; filename=\"a.txt\""));
|
||||
assert_eq!(output.dto.content_language.as_deref(), Some("en"));
|
||||
assert_eq!(output.dto.cache_control.as_deref(), Some("max-age=60"));
|
||||
assert_eq!(
|
||||
output.e_tag,
|
||||
Some(ETag::Strong("d41d8cd98f00b204e9800998ecf8427e-3".to_string())),
|
||||
output.dto.expires.as_ref().map(|value| value.as_str()),
|
||||
Some("Thu, 01 Jan 2026 00:00:00 GMT")
|
||||
);
|
||||
assert_eq!(output.dto.accept_ranges.as_deref(), Some("bytes"));
|
||||
assert_eq!(
|
||||
output.etag,
|
||||
Some(ResponseEtag {
|
||||
opaque: "d41d8cd98f00b204e9800998ecf8427e-3".to_owned(),
|
||||
weak: false
|
||||
}),
|
||||
"the source ETag is returned as-is"
|
||||
);
|
||||
let last_modified: OffsetDateTime = output.last_modified.expect("source Last-Modified is returned").into();
|
||||
let last_modified =
|
||||
OffsetDateTime::from_unix_timestamp(output.dto.last_modified.expect("source Last-Modified is returned").secs())
|
||||
.unwrap();
|
||||
assert_eq!(last_modified.unix_timestamp(), 1_445_412_480);
|
||||
assert_eq!(output.metadata, Some(HashMap::from([("owner".to_string(), "alice".to_string())])));
|
||||
assert_eq!(output.version_id, None, "no x-amz-version-id for a source answer");
|
||||
assert_eq!(output.server_side_encryption, None);
|
||||
assert_eq!(output.ssekms_key_id, None);
|
||||
assert_eq!(output.sse_customer_algorithm, None);
|
||||
assert_eq!(output.storage_class, None);
|
||||
assert_eq!(output.replication_status, None);
|
||||
assert_eq!(
|
||||
output.dto.metadata,
|
||||
std::collections::BTreeMap::from([("owner".to_string(), "alice".to_string())])
|
||||
);
|
||||
assert_eq!(output.dto.version_id, None, "no x-amz-version-id for a source answer");
|
||||
assert_eq!(output.dto.server_side_encryption, None);
|
||||
assert_eq!(output.dto.ssekms_key_id, None);
|
||||
assert_eq!(output.dto.sse_customer_algorithm, None);
|
||||
assert_eq!(output.dto.storage_class, None);
|
||||
assert_eq!(output.dto.replication_status, None);
|
||||
|
||||
let bare = odm_head_output(SourceHead::default()).expect("empty source HEAD maps");
|
||||
assert_eq!(bare.content_length, Some(0));
|
||||
assert_eq!(bare.e_tag, None);
|
||||
assert_eq!(bare.metadata, None, "no metadata header family for an empty map");
|
||||
assert_eq!(bare.last_modified, None);
|
||||
assert_eq!(bare.dto.content_length, Some(0));
|
||||
assert_eq!(bare.etag, None);
|
||||
assert!(bare.dto.metadata.is_empty(), "no metadata header family for an empty map");
|
||||
assert_eq!(bare.dto.last_modified, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -942,7 +1066,7 @@ mod tests {
|
||||
let source = ScriptedSource::new(vec![Ok(source_head())]);
|
||||
|
||||
let output = odm_head_from_source(&state, &source, "k").await.expect("source hit");
|
||||
assert_eq!(output.content_length, Some(1234));
|
||||
assert_eq!(output.dto.content_length, Some(1234));
|
||||
assert_eq!(source.calls(), 1);
|
||||
assert_eq!(head_count(&state, OdmOutcome::SourceHit), 1);
|
||||
let snapshot = state.stats().snapshot(state.breaker().state());
|
||||
@@ -964,12 +1088,12 @@ mod tests {
|
||||
let source = ScriptedSource::new(vec![Err(SourceError::NotFound)]);
|
||||
|
||||
let err = odm_head_from_source(&state, &source, "gone").await.expect_err("source 404");
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
assert_eq!(head_count(&state, OdmOutcome::SourceMiss), 1);
|
||||
|
||||
// The second HEAD stops at the negative cache: no source call.
|
||||
let err = fail(&sys, "b", "gone", OdmLocalMiss::NotFound);
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
assert_eq!(head_count(&state, OdmOutcome::NegativeCached), 1);
|
||||
assert_eq!(source.calls(), 1);
|
||||
assert!(
|
||||
@@ -1020,7 +1144,7 @@ mod tests {
|
||||
let hidden = consult(&hidden_sys, "h", "k");
|
||||
let source = ScriptedSource::new(vec![Err(SourceError::ServerError(503))]);
|
||||
let err = odm_head_from_source(&hidden, &source, "k").await.expect_err("503 hidden");
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
assert_eq!(head_count(&hidden, OdmOutcome::SourceError), 1);
|
||||
|
||||
// Consecutive scoring failures open the breaker; later HEADs stop
|
||||
@@ -1039,7 +1163,7 @@ mod tests {
|
||||
}
|
||||
assert_eq!(state.breaker().state(), BreakerState::Open);
|
||||
let err = fail(&breaker_sys, "c", "k", OdmLocalMiss::NotFound);
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
assert_eq!(head_count(&state, OdmOutcome::BreakerOpen), 1);
|
||||
assert_eq!(
|
||||
source.calls(),
|
||||
@@ -1080,7 +1204,7 @@ mod tests {
|
||||
)
|
||||
.await;
|
||||
let err = fail(&sys, "b", "k", OdmLocalMiss::NotFound);
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
let state = sys.state("b").expect("configured");
|
||||
assert_eq!(head_count(&state, OdmOutcome::Filtered), 1);
|
||||
assert_eq!(state.stats().snapshot(state.breaker().state()).source_latency.count, 0);
|
||||
@@ -1126,10 +1250,10 @@ mod tests {
|
||||
cfg.policy.source_error = SourceErrorPolicy::NotFound;
|
||||
sys.apply("b", Some(&cfg)).await;
|
||||
let err = fail(&sys, "b", "k", OdmLocalMiss::NotFound);
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
}
|
||||
|
||||
fn head_input(bucket: &str, key: &str, version_id: Option<String>) -> S3Request<HeadObjectInput> {
|
||||
pub(super) fn head_input(bucket: &str, key: &str, version_id: Option<String>) -> S3Request<HeadObjectInput> {
|
||||
let input = HeadObjectInput::builder()
|
||||
.bucket(bucket.to_string())
|
||||
.key(key.to_string())
|
||||
@@ -1221,7 +1345,9 @@ mod tests {
|
||||
.insert("x-rustfs-source-replication-check", HeaderValue::from_static("true"));
|
||||
}
|
||||
fs.head_object(&mut req).await.expect("ordinary HEAD read is permitted");
|
||||
let response = Box::pin(usecase.execute_head_object(req)).await.expect("HEAD succeeds");
|
||||
let response = Box::pin(crate::app::test_seams::head_object(&usecase, req))
|
||||
.await
|
||||
.expect("HEAD succeeds");
|
||||
assert_eq!(response.output.content_length, Some(4));
|
||||
for header in [
|
||||
AMZ_TAG_COUNT,
|
||||
@@ -1313,7 +1439,7 @@ mod tests {
|
||||
let state = sys.state(&bucket).expect("bucket runtime installed");
|
||||
|
||||
// Local hit: served locally, the runtime is never entered.
|
||||
let response = Box::pin(usecase.execute_head_object(head_input(&bucket, "present", None)))
|
||||
let response = Box::pin(usecase.execute_head_object_from_s3s(head_input(&bucket, "present", None)))
|
||||
.await
|
||||
.expect("local object is served");
|
||||
assert_eq!(response.output.content_length, Some(7));
|
||||
@@ -1321,25 +1447,28 @@ mod tests {
|
||||
assert_no_head_traffic(&state);
|
||||
|
||||
// HEAD ?versionId on a missing object never consults the runtime.
|
||||
let err = Box::pin(usecase.execute_head_object(head_input(&bucket, "missing", Some(Uuid::new_v4().to_string()))))
|
||||
.await
|
||||
.expect_err("missing version");
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
let err =
|
||||
Box::pin(usecase.execute_head_object_from_s3s(head_input(&bucket, "missing", Some(Uuid::new_v4().to_string()))))
|
||||
.await
|
||||
.expect_err("missing version");
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
assert_no_head_traffic(&state);
|
||||
|
||||
// The anti-loop marker (any value) keeps the answer local.
|
||||
let mut req = head_input(&bucket, "missing", None);
|
||||
req.headers
|
||||
.insert("x-minio-source-proxy-request", HeaderValue::from_static("false"));
|
||||
let err = Box::pin(usecase.execute_head_object(req)).await.expect_err("missing object");
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
let err = Box::pin(crate::app::test_seams::head_object(&usecase, req))
|
||||
.await
|
||||
.expect_err("missing object");
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
assert_no_head_traffic(&state);
|
||||
|
||||
// A plain miss reaches the runtime; local_only answers 404 there.
|
||||
let err = Box::pin(usecase.execute_head_object(head_input(&bucket, "missing", None)))
|
||||
let err = Box::pin(usecase.execute_head_object_from_s3s(head_input(&bucket, "missing", None)))
|
||||
.await
|
||||
.expect_err("missing object");
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
assert_eq!(head_count(&state, OdmOutcome::Filtered), 1);
|
||||
|
||||
// Latest delete marker: respected by default, a miss once overridden.
|
||||
@@ -1354,10 +1483,10 @@ mod tests {
|
||||
)
|
||||
.await
|
||||
.expect("write delete marker");
|
||||
let err = Box::pin(usecase.execute_head_object(head_input(&bucket, "present", None)))
|
||||
let err = Box::pin(usecase.execute_head_object_from_s3s(head_input(&bucket, "present", None)))
|
||||
.await
|
||||
.expect_err("delete marker hides the object");
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
assert_eq!(
|
||||
head_count(&state, OdmOutcome::Filtered),
|
||||
1,
|
||||
@@ -1371,10 +1500,10 @@ mod tests {
|
||||
Some(&cfg),
|
||||
)
|
||||
.await;
|
||||
let err = Box::pin(usecase.execute_head_object(head_input(&bucket, "present", None)))
|
||||
let err = Box::pin(usecase.execute_head_object_from_s3s(head_input(&bucket, "present", None)))
|
||||
.await
|
||||
.expect_err("local_only still answers 404");
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
assert_eq!(head_count(&state, OdmOutcome::Filtered), 2, "overridden delete marker is a miss");
|
||||
|
||||
// A bucket without a runtime keeps the plain 404.
|
||||
@@ -1384,10 +1513,10 @@ mod tests {
|
||||
.await
|
||||
.expect("create plain bucket");
|
||||
assert!(sys.state(&plain).is_none());
|
||||
let err = Box::pin(usecase.execute_head_object(head_input(&plain, "missing", None)))
|
||||
let err = Box::pin(usecase.execute_head_object_from_s3s(head_input(&plain, "missing", None)))
|
||||
.await
|
||||
.expect_err("missing object");
|
||||
assert_eq!(err.code(), &S3ErrorCode::NoSuchKey);
|
||||
assert_eq!(err.code().as_str(), "NoSuchKey");
|
||||
|
||||
sys.remove(&bucket);
|
||||
}
|
||||
@@ -1405,7 +1534,13 @@ mod tests {
|
||||
let req = build_request(input, Method::HEAD);
|
||||
let usecase = DefaultObjectUsecase::without_context();
|
||||
|
||||
let err = Box::pin(usecase.execute_head_object(req)).await.unwrap_err();
|
||||
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument);
|
||||
let err = Box::pin(crate::app::test_seams::head_object(&usecase, req))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code().as_str(), "InvalidArgument");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "head_response_test.rs"]
|
||||
mod response_tests;
|
||||
@@ -0,0 +1,516 @@
|
||||
// Copyright 2026 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.
|
||||
|
||||
//! Regression tests for the HeadObject response facts and their HTTP and legacy projections.
|
||||
//! The existing completion probe exposes the AuditEntry before asynchronous delivery.
|
||||
|
||||
use super::tests::head_input;
|
||||
use super::*;
|
||||
use http::Method;
|
||||
|
||||
#[test]
|
||||
fn head_stored_etag_facts_and_legacy_projection_preserve_spelling() {
|
||||
head_stored_etag_facts_preserve_spelling();
|
||||
head_legacy_etag_projection_preserves_spelling();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_stored_etag_facts_preserve_spelling() {
|
||||
for raw in [
|
||||
"abc",
|
||||
"\"abc\"",
|
||||
"W/\"abc\"",
|
||||
"W/\"\"",
|
||||
"\"\"",
|
||||
"",
|
||||
"*",
|
||||
" abc ",
|
||||
"abc_def",
|
||||
"a&b",
|
||||
"\"a&b\"",
|
||||
"\"a b\"",
|
||||
"\"a\\b\"",
|
||||
"\"a\"b\"",
|
||||
"w/\"abc\"",
|
||||
"\"abc",
|
||||
"W/abc",
|
||||
"a\rb",
|
||||
"a\nb",
|
||||
"a\0b",
|
||||
"é",
|
||||
] {
|
||||
let expected = to_s3s_etag(raw);
|
||||
let fact = ResponseEtag::from_stored(raw);
|
||||
assert_eq!(fact.opaque, expected.value(), "{raw:?}");
|
||||
assert_eq!(fact.weak, expected.as_weak().is_some(), "{raw:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_legacy_etag_projection_preserves_spelling() {
|
||||
for weak in [false, true] {
|
||||
for opaque in ["", "abc", "a\\b", "a\"b", "a\rb", "é"] {
|
||||
let fact = ResponseEtag {
|
||||
opaque: opaque.to_owned(),
|
||||
weak,
|
||||
};
|
||||
let output = HeadObjectOutputFacts {
|
||||
dto: gateway_dto::HeadObjectOutput::default(),
|
||||
etag: Some(fact),
|
||||
}
|
||||
.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_proxy_etag_mapping_matches_the_legacy_parser() {
|
||||
let mut inputs = vec![
|
||||
"abc".to_owned(),
|
||||
String::new(),
|
||||
"*".to_owned(),
|
||||
" abc ".to_owned(),
|
||||
"abc_def".to_owned(),
|
||||
"W/\"\"".to_owned(),
|
||||
"W/abc".to_owned(),
|
||||
"w/\"abc\"".to_owned(),
|
||||
"\"a\\b\"".to_owned(),
|
||||
"\"a\tb\"".to_owned(),
|
||||
"\"a\"b\"".to_owned(),
|
||||
];
|
||||
for byte in 0..=255u8 {
|
||||
inputs.push(format!("\"a{}b\"", char::from(byte)));
|
||||
inputs.push(format!("W/\"a{}b\"", char::from(byte)));
|
||||
inputs.push(char::from(byte).to_string());
|
||||
}
|
||||
for raw in inputs {
|
||||
let expected = crate::app::storage_api::s3::dto::ETag::from_str(&raw).ok();
|
||||
let sdk = aws_sdk_s3::operation::head_object::HeadObjectOutput::builder()
|
||||
.e_tag(&raw)
|
||||
.build();
|
||||
let facts = DefaultObjectUsecase::proxy_sdk_head_output(sdk);
|
||||
assert!(facts.dto.e_tag.is_none(), "ETag is carried as a response fact");
|
||||
assert_eq!(facts.into_s3s().unwrap().e_tag, expected, "{raw:?}");
|
||||
}
|
||||
let absent =
|
||||
DefaultObjectUsecase::proxy_sdk_head_output(aws_sdk_s3::operation::head_object::HeadObjectOutput::builder().build());
|
||||
assert!(absent.into_s3s().unwrap().e_tag.is_none());
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct HeadEtagRow {
|
||||
stored: &'static str,
|
||||
opaque: &'static str,
|
||||
weak: bool,
|
||||
status: u16,
|
||||
header: Option<&'static [u8]>,
|
||||
conditional_status: u16,
|
||||
conditional_header: Option<&'static [u8]>,
|
||||
}
|
||||
|
||||
const VALID_HEAD_ETAGS: &[HeadEtagRow] = &[
|
||||
HeadEtagRow {
|
||||
stored: "abc",
|
||||
opaque: "abc",
|
||||
weak: false,
|
||||
status: 200,
|
||||
header: Some(&[34, 97, 98, 99, 34]),
|
||||
conditional_status: 304,
|
||||
conditional_header: Some(&[34, 97, 98, 99, 34]),
|
||||
},
|
||||
HeadEtagRow {
|
||||
stored: "\"\"",
|
||||
opaque: "",
|
||||
weak: false,
|
||||
status: 200,
|
||||
header: Some(&[34, 34]),
|
||||
conditional_status: 500,
|
||||
conditional_header: None,
|
||||
},
|
||||
HeadEtagRow {
|
||||
stored: "W/\"\"",
|
||||
opaque: "",
|
||||
weak: true,
|
||||
status: 200,
|
||||
header: Some(&[87, 47, 34, 34]),
|
||||
conditional_status: 304,
|
||||
conditional_header: Some(&[34, 87, 47, 34]),
|
||||
},
|
||||
HeadEtagRow {
|
||||
stored: "\"a\\b\"",
|
||||
opaque: "a\\b",
|
||||
weak: false,
|
||||
status: 200,
|
||||
header: Some(&[34, 97, 92, 98, 34]),
|
||||
conditional_status: 304,
|
||||
conditional_header: Some(&[34, 97, 92, 98, 34]),
|
||||
},
|
||||
HeadEtagRow {
|
||||
stored: "\"a\"b\"",
|
||||
opaque: "a\"b",
|
||||
weak: false,
|
||||
status: 200,
|
||||
header: Some(&[34, 97, 34, 98, 34]),
|
||||
conditional_status: 304,
|
||||
conditional_header: Some(&[34, 97, 34, 98, 34]),
|
||||
},
|
||||
HeadEtagRow {
|
||||
stored: "é",
|
||||
opaque: "é",
|
||||
weak: false,
|
||||
status: 200,
|
||||
header: Some(&[34, 195, 169, 34]),
|
||||
conditional_status: 304,
|
||||
conditional_header: Some(&[34, 195, 169, 34]),
|
||||
},
|
||||
];
|
||||
|
||||
const INVALID_HEAD_ETAGS: &[HeadEtagRow] = &[
|
||||
VALID_HEAD_ETAGS[0],
|
||||
HeadEtagRow {
|
||||
stored: "a\rb",
|
||||
opaque: "a\rb",
|
||||
weak: false,
|
||||
status: 500,
|
||||
header: None,
|
||||
conditional_status: 500,
|
||||
conditional_header: None,
|
||||
},
|
||||
HeadEtagRow {
|
||||
stored: "a\nb",
|
||||
opaque: "a\nb",
|
||||
weak: false,
|
||||
status: 500,
|
||||
header: None,
|
||||
conditional_status: 500,
|
||||
conditional_header: None,
|
||||
},
|
||||
HeadEtagRow {
|
||||
stored: "a\0b",
|
||||
opaque: "a\0b",
|
||||
weak: false,
|
||||
status: 500,
|
||||
header: None,
|
||||
conditional_status: 500,
|
||||
conditional_header: None,
|
||||
},
|
||||
];
|
||||
|
||||
fn head_etag_wire_and_audit(stack: Option<&'static str>, rows: &'static [HeadEtagRow]) {
|
||||
temp_env::with_vars(
|
||||
[
|
||||
("RUSTFS_S3_STACK", stack),
|
||||
("RUSTFS_AUDIT_ENABLE", Some("true")),
|
||||
("RUSTFS_NOTIFY_ENABLE", Some("false")),
|
||||
],
|
||||
|| {
|
||||
crate::app::gating_test_env::run_large_stack_test("head-etag-wire-audit", move || async move {
|
||||
use crate::app::storage_api::object_usecase::helper::MutationCompletionProbe;
|
||||
use crate::app::storage_api::test::ReqInfo;
|
||||
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions};
|
||||
use crate::app::storage_api::test::contract::object::{ObjectIO as _, ObjectOperations as _};
|
||||
let server = head_test_server().await;
|
||||
crate::server::refresh_audit_module_enabled();
|
||||
let context = crate::app::runtime_sources::current_app_context().unwrap();
|
||||
let store = context.object_store();
|
||||
let bucket = "head-etag-values";
|
||||
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
|
||||
store.update_bucket_metadata_config(bucket, crate::app::storage_api::object_usecase::bucket::metadata::BUCKET_POLICY_CONFIG,
|
||||
serde_json::to_vec(&serde_json::json!({"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"*"},"Action":["s3:GetObject"],"Resource":format!("arn:aws:s3:::{bucket}/*")}]})).unwrap()).await.unwrap();
|
||||
let probe = MutationCompletionProbe::install(bucket);
|
||||
let usecase = DefaultObjectUsecase::with_context(Some(context.clone()));
|
||||
let mut wire = Vec::new();
|
||||
let mut expected_wire = Vec::new();
|
||||
let mut expected_audits = Vec::new();
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
let key = format!("etag-{index}");
|
||||
store
|
||||
.put_object(
|
||||
bucket,
|
||||
&key,
|
||||
&mut PutObjReader::from_vec(b"payload".to_vec()),
|
||||
&ObjectOptions {
|
||||
preserve_etag: Some(row.stored.to_owned()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("store the exact ETag fixture");
|
||||
let stored = store.get_object_info(bucket, &key, &ObjectOptions::default()).await.unwrap();
|
||||
assert_eq!(stored.etag.as_deref(), Some(row.stored), "fixture must reach HEAD unchanged");
|
||||
let mut request = head_input(bucket, &key, None);
|
||||
request.extensions.insert(ReqInfo {
|
||||
bucket: Some(bucket.to_owned()),
|
||||
object: Some(key.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
let internal = crate::app::test_seams::head_object(&usecase, request)
|
||||
.await
|
||||
.expect("unencoded legacy response");
|
||||
let typed = internal.output.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)));
|
||||
probe.wait_for(index * 3 + 1, 0).await;
|
||||
for conditional in [false, true] {
|
||||
let response = head_wire_response(&server, bucket, &key, conditional).await;
|
||||
let status = response.status().as_u16();
|
||||
let etag = response
|
||||
.headers()
|
||||
.get(http::header::ETAG)
|
||||
.map(|value| value.as_bytes().to_vec());
|
||||
let body = response.into_body();
|
||||
probe.wait_for(index * 3 + if conditional { 3 } else { 2 }, 0).await;
|
||||
wire.push((row.stored, conditional, status, etag, body.len()));
|
||||
let (status, header) = if conditional {
|
||||
(row.conditional_status, row.conditional_header)
|
||||
} else {
|
||||
(row.status, row.header)
|
||||
};
|
||||
expected_wire.push((row.stored, conditional, status, header.map(<[u8]>::to_vec), 0));
|
||||
expected_audits.push((
|
||||
Some("s3:HeadObject".to_owned()),
|
||||
Some(if conditional { "failure" } else { "success" }.to_owned()),
|
||||
Some(if conditional { 500 } else { 200 }),
|
||||
));
|
||||
}
|
||||
}
|
||||
let audits = probe
|
||||
.audits
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|entry| (entry.api.name.clone(), entry.api.status.clone(), entry.api.status_code))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(audits, expected_audits, "encoding does not rewrite the completed use-case audit");
|
||||
assert_eq!(wire, expected_wire, "HeadObject preserves its legacy status and ETag bytes");
|
||||
server.shutdown().await;
|
||||
})
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn legacy_head_etag_wire_preserves_typed_values_and_audit() {
|
||||
head_etag_wire_and_audit(None, VALID_HEAD_ETAGS);
|
||||
}
|
||||
|
||||
#[cfg(feature = "gateway-stack")]
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn gateway_head_etag_wire_preserves_typed_values_and_audit() {
|
||||
head_etag_wire_and_audit(Some("gateway"), VALID_HEAD_ETAGS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn legacy_head_invalid_etag_is_rejected_after_audit() {
|
||||
head_etag_wire_and_audit(None, INVALID_HEAD_ETAGS);
|
||||
}
|
||||
|
||||
#[cfg(feature = "gateway-stack")]
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn gateway_head_invalid_etag_is_rejected_after_audit() {
|
||||
head_etag_wire_and_audit(Some("gateway"), INVALID_HEAD_ETAGS);
|
||||
}
|
||||
|
||||
async fn head_test_server() -> crate::embedded::RustFSServer {
|
||||
use crate::embedded::{RustFSServerBuilder, find_available_port};
|
||||
RustFSServerBuilder::new()
|
||||
.address(format!("127.0.0.1:{}", find_available_port().unwrap()))
|
||||
.access_key("headfixture")
|
||||
.secret_key("head-fixture-test-secret")
|
||||
.build()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn head_wire_response(
|
||||
server: &crate::embedded::RustFSServer,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
conditional: bool,
|
||||
) -> http::Response<bytes::Bytes> {
|
||||
use http_body_util::BodyExt as _;
|
||||
use hyper_util::rt::TokioIo;
|
||||
let socket = tokio::net::TcpStream::connect(server.address()).await.unwrap();
|
||||
let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(socket)).await.unwrap();
|
||||
let transport = tokio::spawn(connection);
|
||||
let mut builder = http::Request::builder()
|
||||
.method(Method::HEAD)
|
||||
.uri(format!("/{bucket}/{key}"))
|
||||
.header(http::header::HOST, "localhost");
|
||||
if conditional {
|
||||
builder = builder.header(http::header::IF_NONE_MATCH, "*");
|
||||
}
|
||||
let response = sender
|
||||
.send_request(builder.body(http_body_util::Empty::<bytes::Bytes>::new()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = body.collect().await.unwrap().to_bytes();
|
||||
drop(sender);
|
||||
transport.abort();
|
||||
let _ = transport.await;
|
||||
http::Response::from_parts(parts, body)
|
||||
}
|
||||
|
||||
#[cfg(feature = "gateway-stack")]
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn gateway_head_authorization_uses_the_request_bound_context() {
|
||||
temp_env::with_var("RUSTFS_S3_STACK", Some("gateway"), || {
|
||||
crate::app::gating_test_env::run_large_stack_test("head-gateway-authorization", || async {
|
||||
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions};
|
||||
use crate::app::storage_api::test::contract::object::ObjectIO as _;
|
||||
use rustfs_io_metrics::s3_http_metrics::s3_http_metrics_snapshot;
|
||||
let server = head_test_server().await;
|
||||
let context = crate::app::runtime_sources::current_app_context().unwrap();
|
||||
let store = context.object_store();
|
||||
let bucket = "head-authorization";
|
||||
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
|
||||
store
|
||||
.put_object(
|
||||
bucket,
|
||||
"object",
|
||||
&mut PutObjReader::from_vec(b"payload".to_vec()),
|
||||
&ObjectOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for (allow, deny, expected) in [(false, false, 403), (true, true, 403), (true, false, 200)] {
|
||||
let mut statements = vec![
|
||||
serde_json::json!({"Effect":"Allow","Principal":{"AWS":"*"},"Action":"s3:GetObject","Resource":format!("arn:aws:s3:::{bucket}/another-object")}),
|
||||
];
|
||||
for (enabled, effect) in [(allow, "Allow"), (deny, "Deny")] {
|
||||
if enabled {
|
||||
statements.push(serde_json::json!({"Effect":effect,"Principal":{"AWS":"*"},"Action":"s3:GetObject","Resource":format!("arn:aws:s3:::{bucket}/*")}));
|
||||
}
|
||||
}
|
||||
store
|
||||
.update_bucket_metadata_config(
|
||||
bucket,
|
||||
crate::app::storage_api::object_usecase::bucket::metadata::BUCKET_POLICY_CONFIG,
|
||||
serde_json::to_vec(&serde_json::json!({"Version":"2012-10-17","Statement":statements})).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let before: u64 = s3_http_metrics_snapshot().iter().map(|series| series.total).sum();
|
||||
let response = head_wire_response(&server, bucket, "object", false).await;
|
||||
let status = response.status().as_u16();
|
||||
let length = response.headers().get(http::header::CONTENT_LENGTH).cloned();
|
||||
assert!(response.body().is_empty());
|
||||
assert_eq!(status, expected, "allow={allow}, deny={deny}");
|
||||
if status == 200 {
|
||||
assert_eq!(length.unwrap(), "7");
|
||||
}
|
||||
let after: u64 = s3_http_metrics_snapshot().iter().map(|series| series.total).sum();
|
||||
assert_eq!(after - before, 1, "one observed HEAD request");
|
||||
}
|
||||
server.shutdown().await;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn head_conditional_headers_preserve_stored_facts(stack: Option<&'static str>) {
|
||||
temp_env::with_var("RUSTFS_S3_STACK", stack, || {
|
||||
crate::app::gating_test_env::run_large_stack_test("head-conditional-headers", || async {
|
||||
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions};
|
||||
use crate::app::storage_api::test::contract::object::{ObjectIO as _, ObjectOperations as _};
|
||||
let server = head_test_server().await;
|
||||
let store = crate::app::runtime_sources::current_app_context().unwrap().object_store();
|
||||
let bucket = "head-cached-version";
|
||||
store
|
||||
.make_bucket(
|
||||
bucket,
|
||||
&MakeBucketOptions {
|
||||
versioning_enabled: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
store.update_bucket_metadata_config(bucket, crate::app::storage_api::object_usecase::bucket::metadata::BUCKET_POLICY_CONFIG,
|
||||
serde_json::to_vec(&serde_json::json!({"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"*"},"Action":["s3:GetObject","s3:GetObjectVersion"],"Resource":format!("arn:aws:s3:::{bucket}/*")}]})).unwrap()).await.unwrap();
|
||||
store
|
||||
.put_object(
|
||||
bucket,
|
||||
"object",
|
||||
&mut PutObjReader::from_vec(b"payload".to_vec()),
|
||||
&ObjectOptions {
|
||||
versioned: true,
|
||||
preserve_etag: Some("abc".to_owned()),
|
||||
user_defined: HashMap::from([
|
||||
("cache-control".to_owned(), "max-age=7".to_owned()),
|
||||
("content-location".to_owned(), "/snapshot".to_owned()),
|
||||
("expires".to_owned(), "Wed, 21 Oct 2037 07:28:00 GMT".to_owned()),
|
||||
("vary".to_owned(), "Origin, Accept-Encoding".to_owned()),
|
||||
]),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let stored = store
|
||||
.get_object_info(bucket, "object", &ObjectOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let version = stored.version_id.expect("versioned fixture").to_string();
|
||||
let modified = stored.mod_time.expect("stored modification time").format(RFC1123).unwrap();
|
||||
let ordinary = head_wire_response(&server, bucket, "object", false).await;
|
||||
assert_eq!(ordinary.status(), http::StatusCode::OK);
|
||||
assert_eq!(ordinary.headers()[http::header::CONTENT_LENGTH], "7");
|
||||
for key in ["object".to_owned(), format!("object?versionId={version}")] {
|
||||
let response = head_wire_response(&server, bucket, &key, true).await;
|
||||
assert_eq!(response.status(), http::StatusCode::NOT_MODIFIED, "{key}");
|
||||
for (name, expected) in [
|
||||
("etag", "\"abc\""),
|
||||
("last-modified", modified.as_str()),
|
||||
("cache-control", "max-age=7"),
|
||||
("content-location", "/snapshot"),
|
||||
("expires", "Wed, 21 Oct 2037 07:28:00 GMT"),
|
||||
("vary", "Origin, Accept-Encoding"),
|
||||
("x-amz-version-id", version.as_str()),
|
||||
] {
|
||||
assert_eq!(
|
||||
response.headers().get(name).map(http::HeaderValue::as_bytes),
|
||||
Some(expected.as_bytes()),
|
||||
"{key}: {name}"
|
||||
);
|
||||
}
|
||||
assert!(response.body().is_empty());
|
||||
}
|
||||
server.shutdown().await;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn legacy_head_conditional_headers_preserve_stored_facts() {
|
||||
head_conditional_headers_preserve_stored_facts(None);
|
||||
}
|
||||
|
||||
#[cfg(feature = "gateway-stack")]
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn gateway_head_conditional_headers_preserve_stored_facts() {
|
||||
head_conditional_headers_preserve_stored_facts(Some("gateway"));
|
||||
}
|
||||
@@ -208,6 +208,9 @@ mod delete;
|
||||
mod extract;
|
||||
mod get;
|
||||
mod head;
|
||||
#[cfg(feature = "gateway-stack")]
|
||||
pub(crate) use head::ResponseEtag;
|
||||
pub(crate) use head::{HeadObjectFields, HeadObjectOutputFacts};
|
||||
mod internal_put;
|
||||
mod on_demand_migration_put;
|
||||
mod put;
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
use super::*;
|
||||
use crate::app::storage_api::s3::dto::{
|
||||
ChecksumAlgorithm, ChecksumType, ObjectLockLegalHold, ObjectLockLegalHoldStatus, ObjectLockMode, ObjectLockRetention,
|
||||
ChecksumAlgorithm, ObjectLockLegalHold, ObjectLockLegalHoldStatus, ObjectLockMode, ObjectLockRetention,
|
||||
ObjectLockRetentionMode, Range, ServerSideEncryption, StorageClass, Timestamp, TimestampFormat,
|
||||
};
|
||||
use crate::app::storage_api::s3::header::{X_AMZ_DELETE_MARKER, X_AMZ_VERSION_ID};
|
||||
@@ -159,35 +159,32 @@ pub(super) fn decoded_content_length_from_headers(headers: &HeaderMap) -> S3Resu
|
||||
/// whole object, and [`HTTPRangeSpec::get_length`] clamps it to the real
|
||||
/// size once the object is known.
|
||||
pub(super) fn range_to_http_range_spec(range: Range) -> S3Result<HTTPRangeSpec> {
|
||||
match range {
|
||||
Range::Int { first, last } => {
|
||||
let start = i64::try_from(first).map_err(|_| s3_error!(InvalidRange, "The requested range is not satisfiable"))?;
|
||||
let end = match last {
|
||||
Some(last) => {
|
||||
i64::try_from(last).map_err(|_| s3_error!(InvalidRange, "The requested range is not satisfiable"))?
|
||||
}
|
||||
None => -1,
|
||||
};
|
||||
Ok(HTTPRangeSpec {
|
||||
is_suffix_length: false,
|
||||
start,
|
||||
end,
|
||||
})
|
||||
use rustfs_gateway_types::ByteRange;
|
||||
let 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 },
|
||||
};
|
||||
Ok(byte_range_to_http_range_spec(range)?)
|
||||
}
|
||||
|
||||
/// The range rules shared by native HEAD requests and the remaining legacy adapters.
|
||||
pub(super) fn byte_range_to_http_range_spec(range: rustfs_gateway_types::ByteRange) -> rustfs_s3_types::S3Result<HTTPRangeSpec> {
|
||||
use rustfs_gateway_types::ByteRange;
|
||||
let (start, end, suffix) = match range {
|
||||
ByteRange::FromTo { first, last } => (first, Some(last), false),
|
||||
ByteRange::From { first } => (first, None, false),
|
||||
ByteRange::Suffix { length: 0 } => {
|
||||
return Err(rustfs_s3_types::s3_error!(InvalidRange, "The requested range is not satisfiable"));
|
||||
}
|
||||
Range::Suffix { length } => {
|
||||
if length == 0 {
|
||||
return Err(s3_error!(InvalidRange, "The requested range is not satisfiable"));
|
||||
}
|
||||
// Clamp to i64::MAX: any suffix >= object size returns the whole
|
||||
// object, and object sizes never exceed i64::MAX.
|
||||
let start = i64::try_from(length).unwrap_or(i64::MAX);
|
||||
Ok(HTTPRangeSpec {
|
||||
is_suffix_length: true,
|
||||
start,
|
||||
end: -1,
|
||||
})
|
||||
}
|
||||
}
|
||||
ByteRange::Suffix { length } => (length.min(i64::MAX as u64), None, true),
|
||||
};
|
||||
let invalid = || rustfs_s3_types::s3_error!(InvalidRange, "The requested range is not satisfiable");
|
||||
Ok(HTTPRangeSpec {
|
||||
is_suffix_length: suffix,
|
||||
start: i64::try_from(start).map_err(|_| invalid())?,
|
||||
end: end.map(i64::try_from).transpose().map_err(|_| invalid())?.unwrap_or(-1),
|
||||
})
|
||||
}
|
||||
|
||||
/// True when the request body actually arrived chunk-framed on the wire, i.e. the payload was
|
||||
@@ -655,7 +652,7 @@ pub(crate) struct ResponseChecksums {
|
||||
pub(crate) sha1: Option<String>,
|
||||
pub(crate) sha256: Option<String>,
|
||||
pub(crate) crc64nvme: Option<String>,
|
||||
pub(crate) checksum_type: Option<ChecksumType>,
|
||||
pub(crate) checksum_type: Option<String>,
|
||||
pub(crate) extra: Vec<(&'static str, String)>,
|
||||
}
|
||||
|
||||
@@ -670,7 +667,7 @@ where
|
||||
let mut c = ResponseChecksums::default();
|
||||
for (key, checksum) in pairs {
|
||||
if key == AMZ_CHECKSUM_TYPE {
|
||||
c.checksum_type = Some(ChecksumType::from(checksum));
|
||||
c.checksum_type = Some(checksum);
|
||||
continue;
|
||||
}
|
||||
let ct = rustfs_rio::ChecksumType::from_string(key.as_str());
|
||||
@@ -688,7 +685,7 @@ where
|
||||
}
|
||||
}
|
||||
if is_multipart && c.checksum_type.is_none() {
|
||||
c.checksum_type = Some(ChecksumType::from("COMPOSITE".to_string()));
|
||||
c.checksum_type = Some("COMPOSITE".to_string());
|
||||
}
|
||||
c
|
||||
}
|
||||
@@ -804,7 +801,7 @@ pub(super) fn apply_standard_object_metadata(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn response_storage_class(info: &ObjectInfo, metadata: &HashMap<String, String>) -> Option<StorageClass> {
|
||||
pub(super) fn response_storage_class_name(info: &ObjectInfo, metadata: &HashMap<String, String>) -> Option<String> {
|
||||
let stored_class = info
|
||||
.storage_class
|
||||
.as_deref()
|
||||
@@ -814,7 +811,11 @@ pub(super) fn response_storage_class(info: &ObjectInfo, metadata: &HashMap<Strin
|
||||
.then_some(info.transitioned_object.tier.as_str());
|
||||
let effective_class = storageclass::effective_class(stored_class, transitioned_tier);
|
||||
|
||||
(effective_class != storageclass::STANDARD).then(|| StorageClass::from(effective_class.to_string()))
|
||||
(effective_class != storageclass::STANDARD).then(|| effective_class.to_string())
|
||||
}
|
||||
|
||||
pub(super) fn response_storage_class(info: &ObjectInfo, metadata: &HashMap<String, String>) -> Option<StorageClass> {
|
||||
response_storage_class_name(info, metadata).map(StorageClass::from)
|
||||
}
|
||||
|
||||
pub(super) fn response_storage_class_for_object_attributes(
|
||||
@@ -1356,7 +1357,7 @@ mod tests {
|
||||
}
|
||||
|
||||
// classify_response_checksums is the single point that splits decrypted checksum
|
||||
// pairs into the five s3s-typed fields and the additional-algorithm `extra`
|
||||
// pairs into the five named checksum fields and the additional-algorithm `extra`
|
||||
// headers, replacing five copies of the loop. Lock its behaviour (#1252).
|
||||
#[test]
|
||||
fn classify_response_checksums_splits_typed_and_extra() {
|
||||
@@ -1404,13 +1405,66 @@ mod tests {
|
||||
assert!(c.extra.is_empty() && c.crc32.is_none());
|
||||
|
||||
let c = classify_response_checksums(vec![("CRC32".to_string(), "AAAAAA==-2".to_string())], true);
|
||||
assert_eq!(c.checksum_type.as_ref().map(ChecksumType::as_str), Some("COMPOSITE"));
|
||||
assert_eq!(c.checksum_type.as_deref(), Some("COMPOSITE"));
|
||||
|
||||
// Empty input yields an all-default result.
|
||||
let c = classify_response_checksums(Vec::<(String, String)>::new(), false);
|
||||
assert!(c.crc32.is_none() && c.extra.is_empty() && c.checksum_type.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksum_type_metadata_keeps_unknown_and_empty_values() {
|
||||
for (value, multipart) in [("UNKNOWN-TYPE", false), ("", true), (" mIxEd ", true)] {
|
||||
let classified = classify_response_checksums(vec![(AMZ_CHECKSUM_TYPE.to_owned(), value.to_owned())], multipart);
|
||||
assert_eq!(classified.checksum_type.as_deref(), Some(value));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_range_core_preserves_boundaries() {
|
||||
use rustfs_gateway_types::ByteRange;
|
||||
for (range, expected) in [
|
||||
(ByteRange::From { first: 0 }, (false, 0, -1)),
|
||||
(
|
||||
ByteRange::FromTo {
|
||||
first: 0,
|
||||
last: i64::MAX as u64,
|
||||
},
|
||||
(false, 0, i64::MAX),
|
||||
),
|
||||
(ByteRange::Suffix { length: u64::MAX }, (true, i64::MAX, -1)),
|
||||
] {
|
||||
let actual = byte_range_to_http_range_spec(range).unwrap();
|
||||
assert_eq!((actual.is_suffix_length, actual.start, actual.end), expected);
|
||||
}
|
||||
native_range_core_rejects_invalid_boundaries();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_range_core_rejects_invalid_boundaries() {
|
||||
use rustfs_gateway_types::ByteRange;
|
||||
for range in [
|
||||
ByteRange::Suffix { length: 0 },
|
||||
ByteRange::From {
|
||||
first: i64::MAX as u64 + 1,
|
||||
},
|
||||
ByteRange::From { first: u64::MAX },
|
||||
ByteRange::FromTo {
|
||||
first: 0,
|
||||
last: i64::MAX as u64 + 1,
|
||||
},
|
||||
ByteRange::FromTo {
|
||||
first: 0,
|
||||
last: u64::MAX,
|
||||
},
|
||||
] {
|
||||
assert_eq!(
|
||||
byte_range_to_http_range_spec(range).unwrap_err().code(),
|
||||
&rustfs_s3_types::S3ErrorCode::InvalidRange
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// additional_checksum_echo_pairs derives the PutObject/UploadPart response echo for
|
||||
// additional algorithms from the server-computed checksum, and nothing for the
|
||||
// five typed ones (those go through typed output fields).
|
||||
|
||||
@@ -1751,6 +1751,18 @@ pub(crate) mod bucket_usecase {
|
||||
}
|
||||
|
||||
pub(crate) mod object_usecase {
|
||||
pub(crate) async fn head_cors_headers(
|
||||
bucket: &str,
|
||||
method: &http::Method,
|
||||
headers: &http::HeaderMap,
|
||||
) -> Option<http::HeaderMap> {
|
||||
crate::storage_api::server::layer::apply_cors_headers(
|
||||
bucket,
|
||||
method,
|
||||
&crate::server::cors::CorsRequest::from_headers(headers),
|
||||
)
|
||||
.await
|
||||
}
|
||||
pub(crate) use super::storage_contracts::object::DeleteObjectCondition;
|
||||
pub(crate) use crate::storage::storage_api::ecstore_object::{WriteCommitGuard, WriteCompletion};
|
||||
|
||||
|
||||
@@ -14,15 +14,24 @@
|
||||
|
||||
use crate::app::object_usecase::DefaultObjectUsecase;
|
||||
use crate::app::storage_api::s3::{HeadObjectInput, HeadObjectOutput, S3Request, S3Response, S3Result};
|
||||
use std::future::Future;
|
||||
|
||||
/// Calls `DefaultObjectUsecase::execute_head_object` with today's arguments.
|
||||
///
|
||||
/// Owned by the HeadObject 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) fn head_object(
|
||||
pub(crate) async fn head_object(
|
||||
usecase: &DefaultObjectUsecase,
|
||||
req: S3Request<HeadObjectInput>,
|
||||
) -> impl Future<Output = S3Result<S3Response<HeadObjectOutput>>> + '_ {
|
||||
usecase.execute_head_object(req)
|
||||
) -> S3Result<S3Response<HeadObjectOutput>> {
|
||||
use crate::app::object_usecase::HeadObjectFields;
|
||||
use crate::app::{Answered, RequestEnvelope};
|
||||
rustfs_io_metrics::record_s3_op(rustfs_s3_ops::S3Operation::HeadObject);
|
||||
let envelope = RequestEnvelope::from_s3s(&req);
|
||||
let Answered { output, status, headers } = usecase
|
||||
.execute_head_object_fields(envelope, HeadObjectFields::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)
|
||||
}
|
||||
@@ -94,10 +94,6 @@ pub(crate) trait Served: OperationCodec + Sized {
|
||||
|
||||
/// The gateway's answer for a use case's [`Answered`]: its status when it set one, and the headers
|
||||
/// its legacy body wrote. The gateway refuses a header it owns or its encoder wrote with a `500`.
|
||||
#[cfg_attr(
|
||||
not(test),
|
||||
expect(dead_code, reason = "HeadObject and GetObject of batch C are its first callers")
|
||||
)]
|
||||
fn resp<O: Served>(answered: Answered<O::Output>) -> Resp<O> {
|
||||
let Answered { output, status, headers } = answered;
|
||||
match status {
|
||||
@@ -235,4 +231,161 @@ mod tests {
|
||||
assert_eq!(default_status, 200);
|
||||
assert!(no_extra.is_empty());
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ExtraCase {
|
||||
Repeated,
|
||||
OwnedConflict,
|
||||
EncoderConflict,
|
||||
}
|
||||
|
||||
struct WireAnswer(ExtraCase);
|
||||
impl Handler<rustfs_gateway::dto::HeadObject> for WireAnswer {
|
||||
async fn call(&self, _request: Req<rustfs_gateway::dto::HeadObject>) -> HandlerResult<rustfs_gateway::dto::HeadObject> {
|
||||
let mut headers = http::HeaderMap::new();
|
||||
headers.append("vary", http::HeaderValue::from_static("Origin"));
|
||||
headers.append("vary", http::HeaderValue::from_static("Access-Control-Request-Method"));
|
||||
headers.insert(
|
||||
"x-amz-restore-request-date",
|
||||
http::HeaderValue::from_static("Fri, 02 Jan 2026 03:04:05 GMT"),
|
||||
);
|
||||
match self.0 {
|
||||
ExtraCase::Repeated => {}
|
||||
ExtraCase::OwnedConflict => {
|
||||
headers.insert("connection", http::HeaderValue::from_static("close"));
|
||||
}
|
||||
ExtraCase::EncoderConflict => {
|
||||
headers.insert("content-type", http::HeaderValue::from_static("text/html"));
|
||||
}
|
||||
}
|
||||
object_read::head_response(Answered {
|
||||
output: crate::app::object_usecase::HeadObjectOutputFacts {
|
||||
dto: rustfs_gateway::dto::HeadObjectOutput {
|
||||
content_type: Some("text/plain".to_owned()),
|
||||
content_length: Some(7),
|
||||
..Default::default()
|
||||
},
|
||||
etag: Some(crate::app::object_usecase::ResponseEtag {
|
||||
opaque: "a\\\"b".to_owned(),
|
||||
weak: true,
|
||||
}),
|
||||
},
|
||||
status: Some(http::StatusCode::PARTIAL_CONTENT),
|
||||
headers,
|
||||
})
|
||||
.map_err(handler_error)
|
||||
}
|
||||
}
|
||||
|
||||
async fn answered_over_socket(case: ExtraCase) -> http::Response<bytes::Bytes> {
|
||||
use http_body_util::BodyExt as _;
|
||||
use hyper_util::rt::TokioIo;
|
||||
use rustfs_gateway::{Credentials, RegionSet, SigV4Authenticator, StaticCredentials, allow_when};
|
||||
let credentials =
|
||||
Arc::new(StaticCredentials::new().with(Credentials::new("answeredkey", b"answered-fixture-secret").unwrap()));
|
||||
let service = Arc::new(
|
||||
ServiceBuilder::new()
|
||||
.authenticator(SigV4Authenticator::new(credentials, RegionSet::new(["us-east-1"]).unwrap()))
|
||||
.authorizer(allow_when(|_| true))
|
||||
.register::<rustfs_gateway::dto::HeadObject, _>(Arc::new(WireAnswer(case)))
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
|
||||
.await
|
||||
.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
hyper::server::conn::http1::Builder::new()
|
||||
.keep_alive(false)
|
||||
.serve_connection(
|
||||
TokioIo::new(socket),
|
||||
hyper::service::service_fn(move |request| {
|
||||
let service = Arc::clone(&service);
|
||||
async move { Ok::<_, std::convert::Infallible>(service.call(request).await) }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
let socket = tokio::net::TcpStream::connect(address).await.unwrap();
|
||||
let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(socket)).await.unwrap();
|
||||
let client = tokio::spawn(connection);
|
||||
let request = test_support::signed_request(
|
||||
test_support::Signed::Header,
|
||||
http::Method::HEAD,
|
||||
"/bucket/key",
|
||||
"",
|
||||
"answeredkey",
|
||||
"answered-fixture-secret",
|
||||
);
|
||||
let response = sender.send_request(request).await.unwrap();
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = body.collect().await.unwrap().to_bytes();
|
||||
drop(sender);
|
||||
server.await.unwrap();
|
||||
client.await.unwrap().unwrap();
|
||||
http::Response::from_parts(parts, body)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn answered_headers_and_conflicts_are_observed_on_the_socket() {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
for (case, status) in [
|
||||
(ExtraCase::Repeated, 206),
|
||||
(ExtraCase::OwnedConflict, 500),
|
||||
(ExtraCase::EncoderConflict, 500),
|
||||
] {
|
||||
assert_answered_case(case, status).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("socket exchange completes");
|
||||
}
|
||||
async fn assert_answered_case(case: ExtraCase, status: u16) {
|
||||
let response = answered_over_socket(case).await;
|
||||
assert_eq!(response.status().as_u16(), status);
|
||||
assert!(response.body().is_empty(), "HEAD never delivers an entity body");
|
||||
if status == 206 {
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get_all("vary")
|
||||
.iter()
|
||||
.map(|v| v.as_bytes())
|
||||
.collect::<Vec<_>>(),
|
||||
[b"Origin".as_slice(), b"Access-Control-Request-Method".as_slice()]
|
||||
);
|
||||
assert_eq!(response.headers()["x-amz-restore-request-date"], "Fri, 02 Jan 2026 03:04:05 GMT");
|
||||
assert_eq!(response.headers()["content-type"], "text/plain");
|
||||
assert_eq!(response.headers()["etag"].as_bytes(), b"W/\"a\\\"b\"");
|
||||
} else {
|
||||
assert!(
|
||||
response.headers().get("x-amz-restore-request-date").is_none(),
|
||||
"extras do not leak onto the refusal"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn answered_raw_headers_are_observed_on_the_socket() {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), assert_answered_case(ExtraCase::Repeated, 206))
|
||||
.await
|
||||
.expect("socket exchange completes");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn answered_transport_header_conflict_is_rejected_on_the_socket() {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), assert_answered_case(ExtraCase::OwnedConflict, 500))
|
||||
.await
|
||||
.expect("socket exchange completes");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn answered_encoder_header_conflict_is_rejected_on_the_socket() {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), assert_answered_case(ExtraCase::EncoderConflict, 500))
|
||||
.await
|
||||
.expect("socket exchange completes");
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,119 @@
|
||||
// limitations under the License.
|
||||
|
||||
//! The gateway operations of migration batch C (rustfs/backlog#2765): GetObject, HeadObject and GetObjectAttributes.
|
||||
//! None is served yet; the batch appends its rows here.
|
||||
//! HeadObject is served; the batch appends the remaining rows here.
|
||||
|
||||
pub(super) const ROWS: &[super::OpRow] = &[];
|
||||
use super::{OpRow, Served, resp, row};
|
||||
use crate::app::object_usecase::{DefaultObjectUsecase, HeadObjectOutputFacts, ResponseEtag};
|
||||
use crate::app::{Answered, RequestEnvelope};
|
||||
use crate::runtime_sources::AppContext;
|
||||
use crate::storage_api::server::http::access::access_owned::object_read::authorize_head_object;
|
||||
use rustfs_gateway::{Req, Resp, dto};
|
||||
use rustfs_s3_ops::S3Operation;
|
||||
use rustfs_s3_types::{S3ErrorCode, S3Result, s3_error};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) const ROWS: &[OpRow] = &[row::<dto::HeadObject>()];
|
||||
|
||||
impl Served for dto::HeadObject {
|
||||
const METRIC: S3Operation = S3Operation::HeadObject;
|
||||
async fn authorize(envelope: &mut RequestEnvelope, request: &Req<Self>) -> S3Result<()> {
|
||||
let input = request.input();
|
||||
let server_ctx = envelope
|
||||
.server_context()
|
||||
.cloned()
|
||||
.ok_or_else(|| s3_error!(InternalError, "server context is missing"))?;
|
||||
Ok(authorize_head_object(
|
||||
&server_ctx,
|
||||
envelope,
|
||||
input.bucket.as_str(),
|
||||
input.key.as_str(),
|
||||
input.version_id.as_deref(),
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
async fn execute(context: Option<Arc<AppContext>>, envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
|
||||
let result = DefaultObjectUsecase::with_context(context)
|
||||
.execute_head_object(envelope, request.into_input())
|
||||
.await;
|
||||
head_result(result)
|
||||
}
|
||||
}
|
||||
|
||||
/// The use case has already recorded this conditional refusal as an error. Preserve its
|
||||
/// completed response without re-parsing the stored headers through the generic error codec.
|
||||
fn head_result(result: S3Result<Answered<HeadObjectOutputFacts>>) -> S3Result<Resp<dto::HeadObject>> {
|
||||
match result {
|
||||
Ok(answered) => head_response(answered),
|
||||
Err(error)
|
||||
if error.code() == &S3ErrorCode::NotModified && error.status_code() == Some(http::StatusCode::NOT_MODIFIED) =>
|
||||
{
|
||||
let parts = error.into_parts();
|
||||
Ok(Resp::with_status(dto::HeadObjectOutput::default(), 304).with_extra_headers(parts.headers.unwrap_or_default()))
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Header encoding stays after use-case completion, just as on the legacy edge.
|
||||
pub(super) fn head_response(answered: Answered<HeadObjectOutputFacts>) -> S3Result<Resp<dto::HeadObject>> {
|
||||
let Answered {
|
||||
output,
|
||||
status,
|
||||
mut headers,
|
||||
} = answered;
|
||||
if let Some(ResponseEtag { opaque, weak }) = output.etag {
|
||||
let value = if weak {
|
||||
format!("W/\"{}\"", opaque)
|
||||
} else {
|
||||
format!("\"{}\"", opaque)
|
||||
};
|
||||
headers.insert(
|
||||
http::header::ETAG,
|
||||
http::HeaderValue::from_str(&value).map_err(|_| s3_error!(InternalError, "Invalid stored ETag header"))?,
|
||||
);
|
||||
}
|
||||
Ok(resp::<dto::HeadObject>(Answered {
|
||||
output: output.dto,
|
||||
status,
|
||||
headers,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn head_terminal_304_uses_the_resolved_status() {
|
||||
for status in [None, Some(http::StatusCode::NOT_MODIFIED)] {
|
||||
let mut error = rustfs_s3_types::S3Error::new(S3ErrorCode::NotModified);
|
||||
if let Some(status) = status {
|
||||
error.set_status_code(status);
|
||||
}
|
||||
let mut headers = http::HeaderMap::new();
|
||||
headers.insert(http::header::ETAG, http::HeaderValue::from_bytes(b"\"\xc3\xa9\"").unwrap());
|
||||
error.set_headers(headers.clone());
|
||||
let (_, status, actual) = head_result(Err(error)).unwrap().into_parts();
|
||||
assert_eq!(status, 304);
|
||||
assert_eq!(actual, headers);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_terminal_304_requires_both_code_and_status() {
|
||||
for (code, status) in [
|
||||
(S3ErrorCode::NotModified, http::StatusCode::BAD_REQUEST),
|
||||
(S3ErrorCode::AccessDenied, http::StatusCode::NOT_MODIFIED),
|
||||
(S3ErrorCode::InternalError, http::StatusCode::INTERNAL_SERVER_ERROR),
|
||||
] {
|
||||
let mut error = rustfs_s3_types::S3Error::new(code.clone());
|
||||
error.set_status_code(status);
|
||||
let Err(error) = head_result(Err(error)) else {
|
||||
panic!("unrelated refusal stays an error");
|
||||
};
|
||||
assert_eq!(error.code(), &code);
|
||||
assert_eq!(error.status_code(), Some(status));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3968,23 +3968,15 @@ impl S3Access for FS {
|
||||
///
|
||||
/// This method returns `Ok(())` by default.
|
||||
async fn head_object(&self, req: &mut S3Request<HeadObjectInput>) -> S3Result<()> {
|
||||
let bucket = req.input.bucket.clone();
|
||||
let source_generation = capture_odm_read_generation(self.server_ctx(), req, &bucket).await;
|
||||
let req_info = ext_req_info_mut(&mut req.extensions)?;
|
||||
req_info.bucket = Some(req.input.bucket.clone());
|
||||
req_info.object = Some(req.input.key.clone());
|
||||
req_info.version_id = req.input.version_id.clone();
|
||||
|
||||
authorize_request(req, versioned_read_action(req.input.version_id.as_deref())).await?;
|
||||
// Replication permission additionally unlocks the SSE-C convergence
|
||||
// check; it does not replace permission to read this version's metadata.
|
||||
if get_header(&req.headers, SUFFIX_SOURCE_REPLICATION_CHECK).as_deref() == Some("true") {
|
||||
authorize_request(req, Action::S3Action(S3Action::ReplicateObjectAction)).await?;
|
||||
req_info_mut(req)?.replication_request_authorized = true;
|
||||
}
|
||||
|
||||
req.install_odm_read_generation(source_generation);
|
||||
Ok(())
|
||||
let input = req.input.clone();
|
||||
access_owned::object_read::authorize_head_object(
|
||||
self.server_ctx(),
|
||||
req,
|
||||
&input.bucket,
|
||||
&input.key,
|
||||
input.version_id.as_deref(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Checks whether the ListBucketAnalyticsConfigurations request has accesses to the resources.
|
||||
|
||||
@@ -20,3 +20,36 @@
|
||||
//! policy evaluation itself (`authorize_request`), or the operation's use case.
|
||||
//! Upstream: the legacy hook in `storage/access.rs` and the batch's `server/gateway_handlers/object_read.rs`.
|
||||
//! Downstream: the shared shapes in `storage/access.rs`.
|
||||
|
||||
use crate::storage::access::{
|
||||
AuthorizationRequest, S3Result, ServerContextSlot, authorize_request, capture_odm_read_generation, req_info_mut,
|
||||
versioned_read_action,
|
||||
};
|
||||
use rustfs_policy::policy::action::{Action, S3Action};
|
||||
use rustfs_utils::http::{SUFFIX_SOURCE_REPLICATION_CHECK, get_header};
|
||||
|
||||
/// Both HEAD edges retain the captured ODM generation and the additional replication decision.
|
||||
pub(crate) async fn authorize_head_object<R: AuthorizationRequest + ?Sized>(
|
||||
server_ctx: &ServerContextSlot,
|
||||
req: &mut R,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
version_id: Option<&str>,
|
||||
) -> S3Result<()> {
|
||||
let source_generation = capture_odm_read_generation(server_ctx, req, bucket).await;
|
||||
let info = req_info_mut(req)?;
|
||||
info.bucket = Some(bucket.to_owned());
|
||||
info.object = Some(key.to_owned());
|
||||
info.version_id = version_id.map(str::to_owned);
|
||||
authorize_request(req, versioned_read_action(version_id)).await?;
|
||||
if get_header(req.headers(), SUFFIX_SOURCE_REPLICATION_CHECK).as_deref() == Some("true") {
|
||||
authorize_request(req, Action::S3Action(S3Action::ReplicateObjectAction)).await?;
|
||||
req_info_mut(req)?.replication_request_authorized = true;
|
||||
}
|
||||
req.install_odm_read_generation(source_generation);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "object_read_test.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,92 @@
|
||||
// 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.
|
||||
|
||||
//! Head authorization tests for the legacy request and owned envelope.
|
||||
|
||||
use super::authorize_head_object;
|
||||
use crate::app::RequestEnvelope;
|
||||
use crate::storage::access::{ReqInfo, S3ErrorCode, S3Request, ServerContextSlot};
|
||||
use crate::storage::storage_api::contract::bucket::{BucketOperations as _, MakeBucketOptions};
|
||||
use http::{Extensions, HeaderMap, HeaderValue, Method, Uri};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn head_replication_marker_requires_its_own_permission() {
|
||||
crate::app::gating_test_env::run_large_stack_test("head-replica-marker", || async {
|
||||
let context = crate::app::gating_test_env::shared_gating_ambient().await;
|
||||
let store = context.object_store();
|
||||
let bucket = format!("head-replica-marker-{}", uuid::Uuid::new_v4().simple());
|
||||
store.make_bucket(&bucket, &MakeBucketOptions::default()).await.unwrap();
|
||||
let slot = ServerContextSlot::new();
|
||||
assert!(slot.install(Arc::clone(&context)));
|
||||
for (allow, deny) in [(false, false), (true, true), (true, false)] {
|
||||
let mut statements = vec![
|
||||
serde_json::json!({"Effect":"Allow","Principal":{"AWS":"*"},"Action":"s3:GetObject","Resource":format!("arn:aws:s3:::{bucket}/*")}),
|
||||
];
|
||||
for (enabled, effect) in [(allow, "Allow"), (deny, "Deny")] {
|
||||
if enabled {
|
||||
statements.push(serde_json::json!({"Effect":effect,"Principal":{"AWS":"*"},"Action":"s3:ReplicateObject","Resource":format!("arn:aws:s3:::{bucket}/*")}));
|
||||
}
|
||||
}
|
||||
store
|
||||
.update_bucket_metadata_config(
|
||||
&bucket,
|
||||
crate::storage::storage_api::ecstore_bucket::metadata::BUCKET_POLICY_CONFIG,
|
||||
serde_json::to_vec(&serde_json::json!({"Version":"2012-10-17","Statement":statements})).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let headers = if !allow && !deny {
|
||||
vec![
|
||||
None,
|
||||
Some("x-rustfs-source-replication-check"),
|
||||
Some("x-minio-source-replication-check"),
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
Some("x-rustfs-source-replication-check"),
|
||||
Some("x-minio-source-replication-check"),
|
||||
]
|
||||
};
|
||||
for header in headers {
|
||||
let mut request = S3Request {
|
||||
input: (),
|
||||
method: Method::HEAD,
|
||||
uri: Uri::from_static("/bucket/key"),
|
||||
headers: HeaderMap::new(),
|
||||
extensions: Extensions::new(),
|
||||
credentials: None,
|
||||
region: None,
|
||||
service: None,
|
||||
trailing_headers: None,
|
||||
};
|
||||
request.extensions.insert(ReqInfo::default());
|
||||
request.extensions.insert(Arc::clone(&slot));
|
||||
if let Some(header) = header {
|
||||
request.headers.insert(header, HeaderValue::from_static("true"));
|
||||
}
|
||||
let mut envelope = RequestEnvelope::from_s3s(&request);
|
||||
let result = authorize_head_object(&slot, &mut envelope, &bucket, "key", None).await;
|
||||
let permitted = header.is_none() || (allow && !deny);
|
||||
if permitted {
|
||||
result.expect("read-only control or separately permitted replication");
|
||||
} else {
|
||||
assert_eq!(result.unwrap_err().code(), &S3ErrorCode::AccessDenied);
|
||||
}
|
||||
assert_eq!(envelope.req_info().unwrap().replication_request_authorized, header.is_some() && permitted);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -63,6 +63,46 @@ impl FS {
|
||||
) -> S3Result<S3Response<HeadObjectOutput>> {
|
||||
crate::hp_guard!("S3::head_object");
|
||||
let usecase = s3_api::object_usecase_for(self);
|
||||
usecase.execute_head_object(req).await
|
||||
record_s3_op(S3Operation::HeadObject);
|
||||
through_gateway_seam_answered(
|
||||
req,
|
||||
|input| Ok(s3_api::HeadObjectFields::from_s3s(input)),
|
||||
s3_api::HeadObjectOutputFacts::into_s3s,
|
||||
|envelope, input| usecase.execute_head_object_fields(envelope, input),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
impl s3_api::HeadObjectFields {
|
||||
pub(crate) fn from_s3s(input: HeadObjectInput) -> Self {
|
||||
use rustfs_gateway_types::ByteRange;
|
||||
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 s3_api::HeadObjectOutputFacts {
|
||||
pub(crate) fn into_s3s(self) -> Result<HeadObjectOutput, rustfs_gateway_types::compat::ConversionError> {
|
||||
let mut output = rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::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)
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@
|
||||
use crate::app::bucket_usecase::DefaultBucketUsecase;
|
||||
pub(crate) use crate::app::object::reject_veeam_sosapi_mutation;
|
||||
pub(crate) use crate::app::object::shared::mark_on_demand_migration_list_local_only;
|
||||
pub(crate) use crate::app::object_usecase::{HeadObjectFields, HeadObjectOutputFacts};
|
||||
use crate::app::{multipart_usecase::DefaultMultipartUsecase, object_usecase::DefaultObjectUsecase};
|
||||
|
||||
pub(crate) mod bucket;
|
||||
|
||||
@@ -353,6 +353,7 @@ async fn every_served_operation_serves_root_and_refuses_the_callers_it_cannot_ad
|
||||
create_bucket_in_the_store(MATRIX_BUCKET).await;
|
||||
create_bucket_in_the_store(object_meta::MATRIX_BUCKET).await;
|
||||
create_bucket_in_the_store(object_misc::MATRIX_BUCKET).await;
|
||||
create_bucket_in_the_store(object_read::MATRIX_BUCKET).await;
|
||||
create_user_without_a_policy(NO_POLICY_USER).await;
|
||||
let endpoint = server.endpoint();
|
||||
let root = s3_client(&endpoint, server.access_key(), server.secret_key());
|
||||
|
||||
@@ -12,6 +12,119 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Refusal-matrix rows of migration batch C (rustfs/backlog#2765). None is served yet.
|
||||
//! HeadObject wire checks and refusal-matrix row for migration batch C (rustfs/backlog#2767).
|
||||
|
||||
pub(crate) const MATRIX: &[super::MatrixRow] = &[];
|
||||
pub(crate) const MATRIX: &[super::MatrixRow] = &[super::MatrixRow {
|
||||
operation: "HeadObject",
|
||||
metric: rustfs_s3_ops::S3Operation::HeadObject,
|
||||
has_error_body: false,
|
||||
call: head_object,
|
||||
}];
|
||||
|
||||
pub(super) const MATRIX_BUCKET: &str = "object-read-matrix";
|
||||
|
||||
fn head_object<'a>(client: &'a aws_sdk_s3::Client, _bucket: &'a str) -> futures::future::BoxFuture<'a, super::Outcome> {
|
||||
Box::pin(async move {
|
||||
super::put_object_in_the_store(MATRIX_BUCKET, "head-matrix").await;
|
||||
super::outcome(client.head_object().bucket(MATRIX_BUCKET).key("head-matrix").send().await)
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn gateway_head_object_reports_missing_bucket_without_a_body() {
|
||||
super::with_stack(super::GATEWAY, |server| async move {
|
||||
let client = super::s3_client(&server.endpoint(), server.access_key(), server.secret_key());
|
||||
let error = client
|
||||
.head_object()
|
||||
.bucket("head-missing-bucket")
|
||||
.key("missing")
|
||||
.send()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.raw_response().unwrap().status().as_u16(), 404);
|
||||
assert!(
|
||||
error
|
||||
.raw_response()
|
||||
.unwrap()
|
||||
.body()
|
||||
.bytes()
|
||||
.expect("collected HEAD body")
|
||||
.is_empty()
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async fn head_answers(server: super::RustFSServer) {
|
||||
use rustfs::app::context::get_global_app_context;
|
||||
use rustfs_ecstore::api::object::{ObjectOptions, PutObjReader};
|
||||
use rustfs_storage_api::ObjectIO;
|
||||
use std::collections::HashMap;
|
||||
let client = super::s3_client(&server.endpoint(), server.access_key(), server.secret_key());
|
||||
for bucket in ["head-ordinary", "sthree-head", "head-s3alias"] {
|
||||
super::create_bucket_in_the_store(bucket).await;
|
||||
let store = get_global_app_context().unwrap().object_store();
|
||||
store
|
||||
.put_object(
|
||||
bucket,
|
||||
"object",
|
||||
&mut PutObjReader::from_vec(b"payload".to_vec()),
|
||||
&ObjectOptions {
|
||||
user_defined: HashMap::from([
|
||||
("cache-control".to_owned(), "max-age=7".to_owned()),
|
||||
("x-amz-restore".to_owned(), "ongoing-request=\"true\"".to_owned()),
|
||||
]),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let head = client
|
||||
.head_object()
|
||||
.bucket(bucket)
|
||||
.key("object")
|
||||
.send()
|
||||
.await
|
||||
.expect("stored object HEAD");
|
||||
assert_eq!(head.content_length(), Some(7));
|
||||
assert_eq!(head.cache_control(), Some("max-age=7"));
|
||||
assert_eq!(head.restore(), Some("ongoing-request=\"true\""));
|
||||
for (part, range, version, condition, status) in [
|
||||
(None, None, None, None, 404),
|
||||
(Some(0), None, None, None, 400),
|
||||
(Some(1), Some("bytes=0-1"), None, None, 400),
|
||||
(None, None, Some("not-a-version"), None, 400),
|
||||
(None, None, None, Some("*"), 304),
|
||||
] {
|
||||
let key = if status == 404 { "missing" } else { "object" };
|
||||
let error = client
|
||||
.head_object()
|
||||
.bucket(bucket)
|
||||
.key(key)
|
||||
.set_part_number(part)
|
||||
.set_range(range.map(str::to_owned))
|
||||
.set_version_id(version.map(str::to_owned))
|
||||
.set_if_none_match(condition.map(str::to_owned))
|
||||
.send()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.raw_response().expect("wire response").status().as_u16(),
|
||||
status,
|
||||
"{bucket} {part:?} {range:?} {version:?} {condition:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn legacy_head_preserves_stored_headers_and_refusal_order() {
|
||||
super::with_stack(super::LEGACY, head_answers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn gateway_head_preserves_stored_headers_and_refusal_order() {
|
||||
super::with_stack(super::GATEWAY, head_answers);
|
||||
}
|
||||
@@ -48,6 +48,7 @@ class Seam:
|
||||
seam_file: str
|
||||
owners: tuple[str, ...] # files that own the operation; each must exist
|
||||
owner_dirs: tuple[str, ...] = () # directories a split of an owner file may create
|
||||
entry_method: str | None = None # a raw-fields body shared by both production edges
|
||||
|
||||
|
||||
SEAMS = {
|
||||
@@ -64,6 +65,7 @@ SEAMS = {
|
||||
"execute_head_object": Seam(
|
||||
batch="C",
|
||||
seam_file="rustfs/src/app/test_seams/head_object.rs",
|
||||
entry_method="execute_head_object_fields",
|
||||
owners=(
|
||||
"rustfs/src/app/object/get.rs",
|
||||
"rustfs/src/app/object/head.rs",
|
||||
@@ -88,7 +90,8 @@ SEAMS = {
|
||||
|
||||
CFG_TEST = re.compile(r"#!?\[\s*cfg\s*\(\s*(?:all\s*\(\s*)?test\b")
|
||||
TEST_ATTR = re.compile(r"#\[\s*(?:tokio::)?test\b")
|
||||
CALL = re.compile(r"\.\s*(execute_get_object|execute_head_object|execute_list_objects_v2|execute_put_object)\s*\(")
|
||||
METHOD_SEAMS = {name: seam for method, seam in SEAMS.items() for name in {method, seam.entry_method or method}}
|
||||
CALL = re.compile(r"\.\s*(" + "|".join(re.escape(name) for name in sorted(METHOD_SEAMS)) + r")\s*\(")
|
||||
CHAR_LITERAL = re.compile(r"'(?:\\(?:[nrt\\0'\"]|x[0-9a-fA-F]{2}|u\{[0-9a-fA-F_]{1,6}\})|[^\\'\n])'")
|
||||
RAW_STRING = re.compile(r'b?r(#*)"')
|
||||
|
||||
@@ -328,9 +331,12 @@ def check(root: Path, files: list[str] | None = None) -> list[str]:
|
||||
else:
|
||||
text = seam_path.read_text()
|
||||
mask = code_mask(text)
|
||||
calls = [m for m in CALL.finditer(text) if mask[m.start()] and m.group(1) == method]
|
||||
entry = seam.entry_method or method
|
||||
calls = [m for m in CALL.finditer(text) if mask[m.start()] and m.group(1) == entry]
|
||||
if len(calls) != 1:
|
||||
errors.append(f"{seam.seam_file}: must call {method} exactly once, found {len(calls)}")
|
||||
errors.append(f"{seam.seam_file}: must call {entry} exactly once, found {len(calls)}")
|
||||
if entry != method and any(mask[m.start()] and m.group(1) == method for m in CALL.finditer(text)):
|
||||
errors.append(f"{seam.seam_file}: must not call {method}; call {entry} instead")
|
||||
for owner in seam.owners:
|
||||
if not (root / owner).is_file():
|
||||
errors.append(f"{owner}: owner file of {method} is missing; update SEAMS in {Path(__file__).name}")
|
||||
@@ -347,7 +353,7 @@ def check(root: Path, files: list[str] | None = None) -> list[str]:
|
||||
regions = test_regions(text, mask)
|
||||
for match in calls:
|
||||
method = match.group(1)
|
||||
seam = SEAMS[method]
|
||||
seam = METHOD_SEAMS[method]
|
||||
if path == seam.seam_file or path in seam.owners or path.startswith(seam.owner_dirs or ("\0",)):
|
||||
continue
|
||||
if whole_file or any(start <= match.start() < end for start, end in regions):
|
||||
@@ -387,7 +393,7 @@ def main(argv: list[str]) -> int:
|
||||
|
||||
SEAM_BODY = {
|
||||
"execute_get_object": "pub(crate) fn get_object(u: &U, r: R) -> F { u.execute_get_object(r) }\n",
|
||||
"execute_head_object": "pub(crate) fn head_object(u: &U, r: R) -> F { u.execute_head_object(r) }\n",
|
||||
"execute_head_object": "pub(crate) fn head_object(u: &U, r: R) -> F { u.execute_head_object_fields(r) }\n",
|
||||
"execute_list_objects_v2": "pub(crate) fn list_objects_v2(u: &U, r: R) -> F { u.execute_list_objects_v2(r) }\n",
|
||||
"execute_put_object": "pub(crate) fn put_object(u: &U, f: &Fs, r: R) -> F { u.execute_put_object(f, r) }\n",
|
||||
}
|
||||
@@ -426,6 +432,34 @@ class SelfTest(unittest.TestCase):
|
||||
def run_check(self) -> list[str]:
|
||||
return check(self.root, sorted(p for p in self.files if p.endswith(".rs")))
|
||||
|
||||
def test_external_head_fields_call_fails(self):
|
||||
self.write("rustfs/src/app/storage.rs", "#[cfg(test)] fn t() { u.execute_head_object_fields(r); }")
|
||||
self.assertRegex(" ".join(self.run_check()), "test calls execute_head_object_fields directly")
|
||||
|
||||
def test_head_fields_seam_missing_call_fails(self):
|
||||
self.write(SEAMS["execute_head_object"].seam_file, "fn head_object() {}")
|
||||
self.assertRegex(" ".join(self.run_check()), "must call execute_head_object_fields exactly once, found 0")
|
||||
|
||||
def test_head_fields_seam_duplicate_call_fails(self):
|
||||
self.write(SEAMS["execute_head_object"].seam_file, "fn head_object() { u.execute_head_object_fields(r); u.execute_head_object_fields(r); }")
|
||||
self.assertRegex(" ".join(self.run_check()), "must call execute_head_object_fields exactly once, found 2")
|
||||
|
||||
def test_head_seam_wrapper_instead_of_fields_fails(self):
|
||||
self.write(SEAMS["execute_head_object"].seam_file, "fn head_object() { u.execute_head_object(r); }")
|
||||
self.assertRegex(" ".join(self.run_check()), "must call execute_head_object_fields exactly once, found 0")
|
||||
|
||||
def test_head_seam_both_entries_fails(self):
|
||||
self.write(SEAMS["execute_head_object"].seam_file, "fn head_object() { u.execute_head_object_fields(r); u.execute_head_object(r); }")
|
||||
self.assertRegex(" ".join(self.run_check()), "must not call execute_head_object")
|
||||
|
||||
def test_commented_and_quoted_head_fields_calls_do_not_count(self):
|
||||
self.write(SEAMS["execute_head_object"].seam_file, 'fn head_object() { let s = "u.execute_head_object_fields(r)"; /* u.execute_head_object_fields(r); */ }')
|
||||
self.assertRegex(" ".join(self.run_check()), "must call execute_head_object_fields exactly once, found 0")
|
||||
|
||||
def test_head_owners_can_call_both_entries(self):
|
||||
self.write("rustfs/src/app/object/head.rs", "#[cfg(test)] fn t() { u.execute_head_object(r); u.execute_head_object_fields(r); }")
|
||||
self.assertEqual(self.run_check(), [])
|
||||
|
||||
# -- negative cases: each must fail --
|
||||
|
||||
def test_direct_call_in_cfg_test_module_of_non_owner_fails(self):
|
||||
|
||||
Reference in new issue
Block a user