diff --git a/Cargo.lock b/Cargo.lock index 36b191d6fd..d171127e80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10371,8 +10371,8 @@ dependencies = [ [[package]] name = "rustfs-gateway" -version = "0.67.0" -source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b" +version = "0.70.0" +source = "git+https://github.com/rustfs/gateway.git?rev=b6007d135c4b4285c9b2bccd915cb9a5814d8f24#b6007d135c4b4285c9b2bccd915cb9a5814d8f24" dependencies = [ "arc-swap", "bytes", @@ -10418,8 +10418,8 @@ dependencies = [ [[package]] name = "rustfs-gateway-core" -version = "0.64.0" -source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b" +version = "0.67.0" +source = "git+https://github.com/rustfs/gateway.git?rev=b6007d135c4b4285c9b2bccd915cb9a5814d8f24#b6007d135c4b4285c9b2bccd915cb9a5814d8f24" dependencies = [ "bytes", "futures-core", @@ -10439,8 +10439,8 @@ dependencies = [ [[package]] name = "rustfs-gateway-corpus" -version = "0.1.0" -source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b" +version = "0.2.0" +source = "git+https://github.com/rustfs/gateway.git?rev=b6007d135c4b4285c9b2bccd915cb9a5814d8f24#b6007d135c4b4285c9b2bccd915cb9a5814d8f24" dependencies = [ "serde", "serde_json", @@ -10450,7 +10450,7 @@ dependencies = [ [[package]] name = "rustfs-gateway-corpus-recorder" version = "0.1.0" -source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b" +source = "git+https://github.com/rustfs/gateway.git?rev=b6007d135c4b4285c9b2bccd915cb9a5814d8f24#b6007d135c4b4285c9b2bccd915cb9a5814d8f24" dependencies = [ "bytes", "http 1.5.0", @@ -10464,8 +10464,8 @@ dependencies = [ [[package]] name = "rustfs-gateway-dialect-rustfs-admin" -version = "0.13.0" -source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b" +version = "0.15.0" +source = "git+https://github.com/rustfs/gateway.git?rev=b6007d135c4b4285c9b2bccd915cb9a5814d8f24#b6007d135c4b4285c9b2bccd915cb9a5814d8f24" dependencies = [ "bytes", "form_urlencoded", @@ -10479,12 +10479,13 @@ dependencies = [ [[package]] name = "rustfs-gateway-http" version = "0.1.4" -source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b" +source = "git+https://github.com/rustfs/gateway.git?rev=b6007d135c4b4285c9b2bccd915cb9a5814d8f24#b6007d135c4b4285c9b2bccd915cb9a5814d8f24" dependencies = [ "hmac 0.13.0", "http 1.5.0", "httparse", "memchr", + "p256", "phf 0.14.0", "rustfs-gateway-stream", "rustfs-gateway-types", @@ -10497,7 +10498,7 @@ dependencies = [ [[package]] name = "rustfs-gateway-macros" version = "0.1.4" -source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b" +source = "git+https://github.com/rustfs/gateway.git?rev=b6007d135c4b4285c9b2bccd915cb9a5814d8f24#b6007d135c4b4285c9b2bccd915cb9a5814d8f24" dependencies = [ "proc-macro2", "quote", @@ -10506,11 +10507,12 @@ dependencies = [ [[package]] name = "rustfs-gateway-sig" -version = "0.16.0" -source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b" +version = "0.18.0" +source = "git+https://github.com/rustfs/gateway.git?rev=b6007d135c4b4285c9b2bccd915cb9a5814d8f24#b6007d135c4b4285c9b2bccd915cb9a5814d8f24" dependencies = [ "hmac 0.13.0", "http 1.5.0", + "p256", "rustfs-gateway-http", "sha1 0.11.0", "sha2 0.11.1", @@ -10522,7 +10524,7 @@ dependencies = [ [[package]] name = "rustfs-gateway-stream" version = "0.2.0" -source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b" +source = "git+https://github.com/rustfs/gateway.git?rev=b6007d135c4b4285c9b2bccd915cb9a5814d8f24#b6007d135c4b4285c9b2bccd915cb9a5814d8f24" dependencies = [ "bitflags 2.13.2", "bytes", @@ -10532,8 +10534,8 @@ dependencies = [ [[package]] name = "rustfs-gateway-types" -version = "0.42.0+aws.2026-10-02" -source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b" +version = "0.44.0+aws.2026-10-02" +source = "git+https://github.com/rustfs/gateway.git?rev=b6007d135c4b4285c9b2bccd915cb9a5814d8f24#b6007d135c4b4285c9b2bccd915cb9a5814d8f24" dependencies = [ "bytes", "crc-fast", @@ -10555,7 +10557,7 @@ dependencies = [ [[package]] name = "rustfs-gateway-xml" version = "0.4.0" -source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b" +source = "git+https://github.com/rustfs/gateway.git?rev=b6007d135c4b4285c9b2bccd915cb9a5814d8f24#b6007d135c4b4285c9b2bccd915cb9a5814d8f24" dependencies = [ "quick-xml 0.41.0", ] diff --git a/Cargo.toml b/Cargo.toml index 58b11f0565..581be6ccb7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -153,17 +153,17 @@ rustfs-utils = { path = "crates/utils", version = "1.0.5" } rustfs-zip = { path = "./crates/zip", version = "1.0.5" } # Pin the gateway and its protocol crates to the same revision. -rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.42.0", default-features = false } -rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.2.0", default-features = false } +rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "b6007d135c4b4285c9b2bccd915cb9a5814d8f24", version = "0.44.0", default-features = false } +rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "b6007d135c4b4285c9b2bccd915cb9a5814d8f24", 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 = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.67.0", default-features = false } +rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "b6007d135c4b4285c9b2bccd915cb9a5814d8f24", version = "0.70.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 = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", default-features = false } -rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.64.0", default-features = false } -rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.1.0", default-features = false } -rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.13.0", default-features = false } +rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "b6007d135c4b4285c9b2bccd915cb9a5814d8f24", default-features = false } +rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "b6007d135c4b4285c9b2bccd915cb9a5814d8f24", version = "0.67.0", default-features = false } +rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "b6007d135c4b4285c9b2bccd915cb9a5814d8f24", version = "0.1.0", default-features = false } +rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "b6007d135c4b4285c9b2bccd915cb9a5814d8f24", version = "0.15.0", default-features = false } # Async Runtime and Networking async-channel = "2.5.0" diff --git a/crates/gateway-adapter/src/bucket_owner.rs b/crates/gateway-adapter/src/bucket_owner.rs index 31d43efda9..2660885b08 100644 --- a/crates/gateway-adapter/src/bucket_owner.rs +++ b/crates/gateway-adapter/src/bucket_owner.rs @@ -15,8 +15,9 @@ //! The gateway's [`BucketOwnerSource`]: the one owner RustFS reports, for a bucket that exists. //! //! Responsible for: confirming through a [`BucketLookup`] that a bucket exists, answering the -//! single owner id the deployment reports ([`RustfsBucketOwners::new`]) for it, and turning every -//! outcome that is not a usable owner into the gateway's one refusal, [`BucketOwnerError`]. +//! single owner id the deployment reports ([`RustfsBucketOwners::new`]) for it, and translating +//! missing buckets, metadata backend faults, and unusable owner configuration into the matching +//! [`BucketOwnerError`] classes. //! NOT responsible for: choosing the owner id (the binary passes the constant it already reports //! as the owner in listings), comparing it with `x-amz-expected-bucket-owner` (the gateway does, //! byte for byte), or authorizing anything. @@ -37,10 +38,11 @@ //! //! Legacy RustFS ignores `x-amz-expected-bucket-owner` entirely. On the gateway stack a request //! carrying it is served only when the value equals the reported owner id; otherwise it is `403 -//! AccessDenied`. A missing bucket and a backend failure with the header present are also `403` -//! at the pinned gateway, where legacy answers `404` and `5xx`: [`BucketOwnerError`] has one value, -//! so it cannot express either. [`RustfsBucketOwners::resolve`] keeps the two apart at this -//! adapter's boundary so the gateway can surface them once it grows the classes. +//! AccessDenied`. Once authorized, a missing bucket yields [`BucketOwnerError::not_found`] (`404 +//! NoSuchBucket`, or bodyless `404` on `HEAD`), a metadata lookup fault yields +//! [`BucketOwnerError::backend_failure`] (retryable `500 InternalError`), and an empty configured +//! owner fails closed with [`BucketOwnerError::unavailable`] (`403 AccessDenied`) without probing +//! bucket existence. use std::sync::Arc; @@ -91,10 +93,10 @@ impl RustfsBucketOwners { /// [`OwnerLookupError::NoSuchBucket`] when the bucket does not exist; /// [`OwnerLookupError::Backend`] on any lookup failure or when the configured owner is empty. pub async fn resolve(&self, bucket: &str) -> Result, OwnerLookupError> { - self.lookup.check(bucket).await?; if self.owner.is_empty() { return Err(OwnerLookupError::Backend); } + self.lookup.check(bucket).await?; Ok(Arc::clone(&self.owner)) } } @@ -102,10 +104,14 @@ impl RustfsBucketOwners { impl BucketOwnerSource for RustfsBucketOwners { fn owner<'a>(&'a self, bucket: &'a BucketName) -> BoxFuture<'a, Result, BucketOwnerError>> { Box::pin(async move { - // The pinned gateway collapses both classes (R-071), so both are the one refusal. - self.resolve(bucket.as_str()) - .await - .map_err(|_: OwnerLookupError| BucketOwnerError::unavailable()) + if self.owner.is_empty() { + return Err(BucketOwnerError::unavailable()); + } + match self.lookup.check(bucket.as_str()).await { + Ok(()) => Ok(Arc::clone(&self.owner)), + Err(OwnerLookupError::NoSuchBucket) => Err(BucketOwnerError::not_found()), + Err(OwnerLookupError::Backend) => Err(BucketOwnerError::backend_failure()), + } }) } } @@ -192,24 +198,111 @@ mod tests { ); } - /// Negative: the pinned gateway sees one refusal for both, and never an owner. + /// Negative: the gateway distinguishes a missing bucket (`404 NoSuchBucket`) from a metadata + /// backend failure (`500 InternalError`), and never treats either as an owner. #[tokio::test] - async fn the_gateway_is_refused_in_both_cases() { + async fn the_gateway_distinguishes_missing_bucket_from_backend_failure() { assert_eq!( gateway_answer(Err(OwnerLookupError::NoSuchBucket)).await, - Err(BucketOwnerError::unavailable()) + Err(BucketOwnerError::not_found()) + ); + assert_eq!( + gateway_answer(Err(OwnerLookupError::Backend)).await, + Err(BucketOwnerError::backend_failure()) ); - assert_eq!(gateway_answer(Err(OwnerLookupError::Backend)).await, Err(BucketOwnerError::unavailable())); } - /// Negative: an empty configured owner is no owner; it must not equal an empty assertion. + /// Negative: an empty configured owner is no owner; it must fail closed as `unavailable` + /// without probing bucket existence, even when the lookup would report `NoSuchBucket`. #[tokio::test] async fn an_empty_owner_is_refused() { - let source = RustfsBucketOwners::new(Fake::answering(Ok(())), ""); - assert_eq!(source.resolve("photos").await, Err(OwnerLookupError::Backend)); - assert_eq!( - source.owner(&BucketName::new("photos").expect("a bucket name")).await, - Err(BucketOwnerError::unavailable()) - ); + for answer in [Ok(()), Err(OwnerLookupError::NoSuchBucket), Err(OwnerLookupError::Backend)] { + let source = RustfsBucketOwners::new(Fake::answering(answer), ""); + assert_eq!(source.resolve("photos").await, Err(OwnerLookupError::Backend)); + assert_eq!( + source.owner(&BucketName::new("photos").expect("a bucket name")).await, + Err(BucketOwnerError::unavailable()) + ); + assert!( + source.lookup.asked.lock().expect("lock").is_empty(), + "empty configured owner must not probe bucket existence" + ); + } + } + + /// Assembled service: `RustfsBucketOwners` surfaces `200`, `403 AccessDenied`, + /// `404 NoSuchBucket` (and bodyless `404` on `HEAD`), `500 InternalError`, and empty-owner + /// fail-closed `403 AccessDenied` through the real gateway pipeline. + #[tokio::test] + async fn assembled_service_surfaces_distinct_bucket_owner_outcomes() { + use bytes::Bytes; + use rustfs_gateway::dto::{GetBucketLocation, GetBucketLocationOutput, HeadBucket, HeadBucketOutput}; + use rustfs_gateway::{ + Decision, Handler, HandlerResult, RegionSet, Req, Resp, SecurityFloor, ServiceBuilder, SigV4Authenticator, + StaticCredentials, decide_with, + }; + + struct OkHandler; + impl Handler for OkHandler { + async fn call(&self, _request: Req) -> HandlerResult { + Ok(Resp::new(HeadBucketOutput::default())) + } + } + impl Handler for OkHandler { + async fn call(&self, _request: Req) -> HandlerResult { + Ok(Resp::new(GetBucketLocationOutput::default())) + } + } + + let build = |answer: Result<(), OwnerLookupError>, owner: &'static str| { + let handler = Arc::new(OkHandler); + let regions = RegionSet::new(["us-east-1"]).expect("a region"); + ServiceBuilder::new() + .authenticator(SigV4Authenticator::new(Arc::new(StaticCredentials::new()), regions)) + .security_floor(SecurityFloor::new().delegate_anonymous_to_authorizer_after_listing_in_the_posture_report()) + .authorizer(decide_with(|_| Decision::Allow)) + .bucket_owner_source(RustfsBucketOwners::new(Fake::answering(answer), owner)) + .register::(Arc::clone(&handler)) + .register::(handler) + .build() + .expect("assemble gateway service") + }; + let send = async |service: &rustfs_gateway::S3Service, method: http::Method, uri: &str, expected_owner: &str| { + let req = http::Request::builder() + .method(method) + .uri(uri) + .header(http::header::HOST, "s3.example.com") + .header("x-amz-expected-bucket-owner", expected_owner) + .body(Bytes::new()) + .expect("request"); + rustfs_gateway::collect(service.call_bytes(req).await) + .await + .expect("collect response") + }; + + let existing = build(Ok(()), OWNER); + let ok = send(&existing, http::Method::GET, "/photos?location", OWNER).await; + assert_eq!(ok.status(), http::StatusCode::OK); + let wrong = send(&existing, http::Method::GET, "/photos?location", "wrong-owner").await; + assert_eq!(wrong.status(), http::StatusCode::FORBIDDEN); + assert!(String::from_utf8_lossy(wrong.body()).contains("AccessDenied")); + + let missing = build(Err(OwnerLookupError::NoSuchBucket), OWNER); + let missing_get = send(&missing, http::Method::GET, "/photos?location", OWNER).await; + assert_eq!(missing_get.status(), http::StatusCode::NOT_FOUND); + assert!(String::from_utf8_lossy(missing_get.body()).contains("NoSuchBucket")); + let missing_head = send(&missing, http::Method::HEAD, "/photos", OWNER).await; + assert_eq!(missing_head.status(), http::StatusCode::NOT_FOUND); + assert!(missing_head.body().is_empty(), "HEAD 404 must be bodyless"); + + let fault = build(Err(OwnerLookupError::Backend), OWNER); + let backend_err = send(&fault, http::Method::GET, "/photos?location", OWNER).await; + assert_eq!(backend_err.status(), http::StatusCode::INTERNAL_SERVER_ERROR); + assert!(String::from_utf8_lossy(backend_err.body()).contains("InternalError")); + + let unconfigured = build(Err(OwnerLookupError::NoSuchBucket), ""); + let refused = send(&unconfigured, http::Method::GET, "/photos?location", OWNER).await; + assert_eq!(refused.status(), http::StatusCode::FORBIDDEN); + assert!(String::from_utf8_lossy(refused.body()).contains("AccessDenied")); } } diff --git a/crates/gateway-adapter/src/keystone.rs b/crates/gateway-adapter/src/keystone.rs index 20ab774b60..1e14100316 100644 --- a/crates/gateway-adapter/src/keystone.rs +++ b/crates/gateway-adapter/src/keystone.rs @@ -13,7 +13,8 @@ // limitations under the License. //! RustFS's side of the gateway's host-verified header token claim for OpenStack Keystone -//! (gateway ADR-0054): the claim, the value a validated token establishes, and the verifier. +//! (gateway ADR-0054 / ADR-0056): the claim, the value a validated token establishes, and the +//! verifier installed exclusively through `ServiceBuilder::host_verified_header_token`. //! //! NOT responsible for: validating tokens (`rustfs-keystone`), wiring any of this into the //! server, or authorising a Keystone principal. @@ -88,6 +89,15 @@ pub fn establish_keystone_identity( /// The gateway's `HeaderTokenVerifier` for Keystone: answers from its two arguments alone. /// +/// Under gateway ADR-0056, header-token admission and verdict construction are sealed behind the +/// gateway facade, so host code installs [`KeystoneVerifier`] exclusively via +/// `ServiceBuilder::host_verified_header_token` and cannot mint header-token verdicts directly: +/// +/// ```compile_fail +/// use rustfs_gateway::HeaderTokenAdmission; +/// fn forge(_admission: HeaderTokenAdmission) {} +/// ``` +/// /// NOT responsible for: revocation after validation, or authorisation. pub struct KeystoneVerifier; diff --git a/docs/operations/s3-stack-rollback.md b/docs/operations/s3-stack-rollback.md index ebdd65712f..1b4dd96d83 100644 --- a/docs/operations/s3-stack-rollback.md +++ b/docs/operations/s3-stack-rollback.md @@ -16,4 +16,4 @@ The gateway release serves S3 with rustfs/gateway. Remove `RUSTFS_S3_STACK` from | `PutBucketPolicy` (`#2684`, `8f81762a6`) | For a malformed JSON policy body, both versions return HTTP 400. The gateway returns the XML error code `MalformedPolicy` (matching AWS S3). RustFS `1.0.5` returns `InvalidArgument`. Clients that classify bucket-policy validation errors by code need to handle both during a rollout. | | `CreateBucket` (`#2684`, `8676d2f3b`) | For a successful default-region `CreateBucket` (`200 OK`), the gateway returns HTTP `Location: /` (matching AWS S3 and `c-bkt-0001`). RustFS `1.0.5` omits the `Location` header. Clients that inspect `Location` on bucket creation need to handle its presence on gateway nodes and absence on `1.0.5` nodes during a rollout. | -`c-sig-0598` is recorded in the [pinned gateway conformance rulings](https://github.com/rustfs/gateway/blob/b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b/conformance/rulings/rustfs-profile.toml); host-assembled conformance rulings are tracked in [`.config/conformance-rulings.toml`](../../.config/conformance-rulings.toml), and the signed `PutBucketPolicy` and `CreateBucket` `accepted-change` rulings are recorded in `rustfs/backlog#2684`. +`c-sig-0598` is recorded in the [pinned gateway conformance rulings](https://github.com/rustfs/gateway/blob/b6007d135c4b4285c9b2bccd915cb9a5814d8f24/conformance/rulings/rustfs-profile.toml); host-assembled conformance rulings are tracked in [`.config/conformance-rulings.toml`](../../.config/conformance-rulings.toml), and the signed `PutBucketPolicy` and `CreateBucket` `accepted-change` rulings are recorded in `rustfs/backlog#2684`. diff --git a/rustfs/src/auth.rs b/rustfs/src/auth.rs index b60e4d5fa7..30a8a35117 100644 --- a/rustfs/src/auth.rs +++ b/rustfs/src/auth.rs @@ -100,8 +100,11 @@ pub fn constant_time_eq(a: &str, b: &str) -> bool { const JWT_ALGORITHM: &str = "Bearer "; const SIGN_V2_ALGORITHM: &str = "AWS "; const SIGN_V4_ALGORITHM: &str = "AWS4-HMAC-SHA256"; +const SIGN_V4A_ALGORITHM: &str = "AWS4-ECDSA-P256-SHA256"; const STREAMING_CONTENT_SHA256: &str = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"; const STREAMING_CONTENT_SHA256_TRAILER: &str = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"; +const STREAMING_V4A_CONTENT_SHA256: &str = "STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD"; +const STREAMING_V4A_CONTENT_SHA256_TRAILER: &str = "STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD-TRAILER"; pub(crate) const UNSIGNED_PAYLOAD_TRAILER: &str = "STREAMING-UNSIGNED-PAYLOAD-TRAILER"; const ACTION_HEADER: &str = "Action"; pub const UNSIGNED_PAYLOAD: &str = "UNSIGNED-PAYLOAD"; @@ -113,17 +116,22 @@ pub enum AuthType { Unknown, Anonymous, Presigned, + PresignedV4a, PresignedV2, PostPolicy, StreamingSigned, + StreamingSignedV4a, Signed, + SignedV4a, SignedV2, #[allow(clippy::upper_case_acronyms)] JWT, #[allow(clippy::upper_case_acronyms)] STS, StreamingSignedTrailer, + StreamingSignedTrailerV4a, StreamingUnsignedTrailer, + StreamingUnsignedTrailerV4a, } /// Owner status of a validated Keystone identity, shared by both request edges. @@ -558,6 +566,8 @@ pub(crate) fn get_request_auth_type_with_method_and_query( AuthType::PostPolicy } else if is_request_presigned_signature_v2(query) { AuthType::PresignedV2 + } else if is_request_presigned_signature_v4a_with_query(query) { + AuthType::PresignedV4a } else if is_request_presigned_signature_v4_with_query(query) { AuthType::Presigned } else if is_request_signature_v2(header) { @@ -572,6 +582,16 @@ pub(crate) fn get_request_auth_type_with_method_and_query( } else { AuthType::Signed } + } else if is_request_signature_v4a(header) { + if is_request_sign_streaming_v4a(header) { + AuthType::StreamingSignedV4a + } else if is_request_sign_streaming_trailer_v4a(header) { + AuthType::StreamingSignedTrailerV4a + } else if is_request_unsigned_trailer_v4(header) { + AuthType::StreamingUnsignedTrailerV4a + } else { + AuthType::SignedV4a + } } else if is_request_jwt(header) { AuthType::JWT } else if method.is_none() && is_request_post_policy_signature_v4(header) { @@ -622,6 +642,13 @@ fn is_request_signature_v4(header: &HeaderMap) -> bool { get_unique_header_str(header, "authorization").is_some_and(|auth| auth.starts_with(SIGN_V4_ALGORITHM)) } +/// Verify if request has AWS Signature Version '4a' (`AWS4-ECDSA-P256-SHA256`). +fn is_request_signature_v4a(header: &HeaderMap) -> bool { + get_unique_header_str(header, "authorization") + .and_then(|auth| auth.strip_prefix(SIGN_V4A_ALGORITHM)) + .is_some_and(|rest| rest.starts_with(' ')) +} + /// Verify if request has AWS Signature Version '2' /// /// # Arguments @@ -681,13 +708,22 @@ pub fn hoist_signed_query_params(headers: &mut HeaderMap, query: Option<&str>) - return Ok(()); } - // One pass over the query: recognize the presigned-SigV4 marker set and + #[derive(Clone, Copy, PartialEq, Eq)] + enum PresignedAlgorithm { + None, + V4, + V4a, + } + + // One pass over the query: recognize the presigned-SigV4/SigV4a marker set and // stage user metadata parameters. Nothing is validated // or applied until the gate below passes, so a request whose query is not // signature-covered is never rejected here. - let mut algorithm = false; + let mut algorithm = PresignedAlgorithm::None; + let mut algorithm_seen = false; let mut credential = false; let mut signature = false; + let mut region_set = false; let mut staged: Vec<(String, String)> = Vec::new(); let mut seen = std::collections::HashSet::new(); let mut duplicate = false; @@ -702,7 +738,16 @@ pub fn hoist_signed_query_params(headers: &mut HeaderMap, query: Option<&str>) - continue; } if name.eq_ignore_ascii_case("x-amz-algorithm") { - algorithm = value == SIGN_V4_ALGORITHM; + if algorithm_seen { + algorithm = PresignedAlgorithm::None; + } else { + algorithm_seen = true; + algorithm = match value.as_ref() { + SIGN_V4_ALGORITHM => PresignedAlgorithm::V4, + SIGN_V4A_ALGORITHM => PresignedAlgorithm::V4a, + _ => PresignedAlgorithm::None, + }; + } continue; } if name.eq_ignore_ascii_case("x-amz-credential") { @@ -713,6 +758,10 @@ pub fn hoist_signed_query_params(headers: &mut HeaderMap, query: Option<&str>) - signature = !value.is_empty(); continue; } + if name.eq_ignore_ascii_case("x-amz-region-set") { + region_set = !value.is_empty(); + continue; + } // Parameter names keep whatever case the signer used (`X-Amz-Meta-User-Id` // is what a hoist produces), so match the prefix the way `HeaderName` would. if !starts_with_ignore_ascii_case(&name, "x-amz-meta-") { @@ -723,7 +772,12 @@ pub fn hoist_signed_query_params(headers: &mut HeaderMap, query: Option<&str>) - staged.push((stored_name, value.into_owned())); } - if !is_request_signature_v4(headers) && !(algorithm && credential && signature) { + let presigned_covered = match algorithm { + PresignedAlgorithm::V4 => credential && signature, + PresignedAlgorithm::V4a => credential && signature && region_set, + PresignedAlgorithm::None => false, + }; + if !is_request_signature_v4(headers) && !is_request_signature_v4a(headers) && !presigned_covered { return Ok(()); } if duplicate { @@ -749,6 +803,26 @@ pub fn hoist_signed_query_params(headers: &mut HeaderMap, query: Option<&str>) - Ok(()) } +/// Verify request has AWS PreSign Version '4a' (`AWS4-ECDSA-P256-SHA256`) from the decoded query string. +fn is_request_presigned_signature_v4a_with_query(query: Option<&str>) -> bool { + query.is_some_and(|query| { + let mut has_signature = false; + let mut algorithm: Option = None; + let mut duplicate_algorithm = false; + for (name, value) in form_urlencoded::parse(query.as_bytes()) { + if name == "X-Amz-Signature" { + has_signature = true; + } else if name == "X-Amz-Algorithm" { + if algorithm.is_some() { + duplicate_algorithm = true; + } + algorithm = Some(value.into_owned()); + } + } + has_signature && !duplicate_algorithm && algorithm.as_deref() == Some(SIGN_V4A_ALGORITHM) + }) +} + /// Verify request has AWS PreSign Version '4' from the decoded query string. pub(crate) fn is_request_presigned_signature_v4_with_query(query: Option<&str>) -> bool { query_has_param(query, "X-Amz-Signature") @@ -782,6 +856,16 @@ fn is_request_sign_streaming_v4(header: &HeaderMap) -> bool { false } +/// Verify if the request has AWS Streaming Signature Version '4a' +fn is_request_sign_streaming_v4a(header: &HeaderMap) -> bool { + if let Some(content_sha256) = header.get("x-amz-content-sha256") + && let Ok(sha256_str) = content_sha256.to_str() + { + return sha256_str == STREAMING_V4A_CONTENT_SHA256; + } + false +} + // Verify if the request has AWS Streaming Signature Version '4' with trailer fn is_request_sign_streaming_trailer_v4(header: &HeaderMap) -> bool { if let Some(content_sha256) = header.get("x-amz-content-sha256") @@ -792,6 +876,16 @@ fn is_request_sign_streaming_trailer_v4(header: &HeaderMap) -> bool { false } +/// Verify if the request has AWS Streaming Signature Version '4a' with trailer +fn is_request_sign_streaming_trailer_v4a(header: &HeaderMap) -> bool { + if let Some(content_sha256) = header.get("x-amz-content-sha256") + && let Ok(sha256_str) = content_sha256.to_str() + { + return sha256_str == STREAMING_V4A_CONTENT_SHA256_TRAILER; + } + false +} + // Verify if the request has AWS Streaming Signature Version '4' with unsigned content and trailer fn is_request_unsigned_trailer_v4(header: &HeaderMap) -> bool { if let Some(content_sha256) = header.get("x-amz-content-sha256") @@ -915,52 +1009,72 @@ fn reject_unsigned_headers_matching(header: &HeaderMap, query: Option<&str>, che let Ok(value) = value.to_str() else { continue; }; - let authorization = match rustfs_gateway::sig::SigV4HeaderCoverage::parse(value) { - Some(authorization) => authorization, - None if value.starts_with(SIGN_V4_ALGORITHM) => { + if let Some(authorization) = rustfs_gateway::sig::SigV4HeaderCoverage::parse(value) { + if authorization.algorithm() != SIGN_V4_ALGORITHM { + warn!( + event = EVENT_SIGV4_UNSUPPORTED_ALGORITHM, + component = LOG_COMPONENT_AUTH, + subsystem = LOG_SUBSYSTEM_REQUEST, + reason = "unsupported_algorithm", + "SigV4 request rejected" + ); + return Err(owned_error!(AccessDenied, "{UNSUPPORTED_SIGV4_ALGORITHM_MESSAGE}")); + } + reject_uncovered_signed_headers(header, check_header, |name| authorization.covers_header(name))?; + continue; + } + if value.starts_with(SIGN_V4_ALGORITHM) { + return Err(owned_error!(AccessDenied, "Invalid SigV4 authorization header")); + } + if value.starts_with(SIGN_V4A_ALGORITHM) { + let Ok(v4a) = + rustfs_gateway::sig::SigV4aAuthorization::parse_with(value, rustfs_gateway::sig::ServiceReading::AnyName) + else { return Err(owned_error!(AccessDenied, "Invalid SigV4 authorization header")); - } - None if value.trim_start().starts_with(SIGN_V2_ALGORITHM) => { - reject_extension_headers_on_sigv2_request(header)?; - continue; - } - None => continue, - }; - if authorization.algorithm() != SIGN_V4_ALGORITHM { - warn!( - event = EVENT_SIGV4_UNSUPPORTED_ALGORITHM, - component = LOG_COMPONENT_AUTH, - subsystem = LOG_SUBSYSTEM_REQUEST, - reason = "unsupported_algorithm", - "SigV4 request rejected" - ); - return Err(owned_error!(AccessDenied, "{UNSUPPORTED_SIGV4_ALGORITHM_MESSAGE}")); + }; + reject_uncovered_signed_headers(header, check_header, |name| { + v4a.signed_headers() + .split(';') + .any(|signed| signed.eq_ignore_ascii_case(name)) + })?; + continue; } - for name in header.keys() { - // `HeaderName` is already lowercase; the verifier looks signed - // names up case-insensitively, so compare them the same way. - let name = name.as_str(); - if !check_header(name) - || SIGV4_UNSIGNED_ENVELOPE_HEADERS.contains(&name) - || PRESIGNED_UNSIGNED_AMZ_HEADER_ALLOWLIST.contains(&name) - || authorization.covers_header(name) - { - continue; - } - warn!( - event = EVENT_SIGV4_UNSIGNED_AMZ_HEADER, - component = LOG_COMPONENT_AUTH, - subsystem = LOG_SUBSYSTEM_REQUEST, - reason = "unsigned_amz_header", - header = name, - "SigV4 request rejected" - ); - return Err(owned_error!(AccessDenied, "{UNSIGNED_HEADERS_MESSAGE}")); + if value.trim_start().starts_with(SIGN_V2_ALGORITHM) { + reject_extension_headers_on_sigv2_request(header)?; } } Ok(()) } +fn reject_uncovered_signed_headers( + header: &HeaderMap, + check_header: fn(&str) -> bool, + covers_header: impl Fn(&str) -> bool, +) -> OwnedResult<()> { + for name in header.keys() { + // `HeaderName` is already lowercase; the verifier looks signed + // names up case-insensitively, so compare them the same way. + let name = name.as_str(); + if !check_header(name) + || SIGV4_UNSIGNED_ENVELOPE_HEADERS.contains(&name) + || PRESIGNED_UNSIGNED_AMZ_HEADER_ALLOWLIST.contains(&name) + || covers_header(name) + { + continue; + } + warn!( + event = EVENT_SIGV4_UNSIGNED_AMZ_HEADER, + component = LOG_COMPONENT_AUTH, + subsystem = LOG_SUBSYSTEM_REQUEST, + reason = "unsigned_amz_header", + header = name, + "SigV4 request rejected" + ); + return Err(owned_error!(AccessDenied, "{UNSIGNED_HEADERS_MESSAGE}")); + } + Ok(()) +} + /// `x-amz-*` request headers a SigV4 presigned request may carry without /// listing them in `X-Amz-SignedHeaders`. /// @@ -1102,11 +1216,37 @@ fn header_as_signed_query_value(header: &HeaderMap, query: &str, name: &str) -> .any(|(param, param_value)| param.eq_ignore_ascii_case(name) && param_value.as_bytes() == value.as_bytes()) } +/// Returns whether `decoded_query` carries all required presigned SigV4 or SigV4a parameters +/// (requiring `X-Amz-Region-Set` for SigV4a). +fn is_complete_presigned_v4_or_v4a_query(decoded_query: &[(String, String)]) -> bool { + let query_value = |wanted: &str| { + decoded_query + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case(wanted)) + .map(|(_, value)| value.as_str()) + }; + let is_v4a = match query_value("x-amz-algorithm") { + Some(SIGN_V4_ALGORITHM) => false, + Some(SIGN_V4A_ALGORITHM) => true, + _ => return false, + }; + let common_present = [ + "x-amz-date", + "x-amz-expires", + "x-amz-signedheaders", + "x-amz-credential", + "x-amz-signature", + ] + .into_iter() + .all(|name| query_value(name).is_some_and(|value| !value.is_empty())); + common_present && (!is_v4a || query_value("x-amz-region-set").is_some_and(|value| !value.is_empty())) +} + /// Parse the RustFS presigned PutObject size capability after authentication. /// -/// The query value is covered by SigV4 when it is present before presigning, but +/// The query value is covered by SigV4/SigV4a when it is present before presigning, but /// the signature does not assign any semantics to the extension. Keep parsing -/// strict and only enable the capability for a verified SigV4 presigned request. +/// strict and only enable the capability for a verified SigV4 or SigV4a presigned request. pub(crate) fn parse_presigned_put_max_content_length( header: &HeaderMap, query: Option<&str>, @@ -1137,27 +1277,13 @@ pub(crate) fn parse_presigned_put_max_content_length( return Ok(None); }; - let query_value = |wanted: &str| { - decoded_query - .iter() - .find(|(name, _)| name.eq_ignore_ascii_case(wanted)) - .map(|(_, value)| value.as_str()) - }; - let is_complete_sigv4_query = [ - ("x-amz-algorithm", "AWS4-HMAC-SHA256"), - ("x-amz-date", ""), - ("x-amz-expires", ""), - ("x-amz-signedheaders", ""), - ("x-amz-credential", ""), - ("x-amz-signature", ""), - ] - .into_iter() - .all(|(name, expected)| { - query_value(name).is_some_and(|value| !value.is_empty() && (expected.is_empty() || value == expected)) - }); + let is_complete_sigv4_query = is_complete_presigned_v4_or_v4a_query(&decoded_query); if !verified_presigned || !is_complete_sigv4_query - || !matches!(get_request_auth_type_with_query(header, Some(query)), AuthType::Presigned) + || !matches!( + get_request_auth_type_with_query(header, Some(query)), + AuthType::Presigned | AuthType::PresignedV4a + ) { return Err(owned_error!( InvalidRequest, @@ -1188,9 +1314,9 @@ pub(crate) fn reject_presigned_put_max_content_length_for_other_operation( Ok(()) } -/// Parse the V2 multipart total-size capability after SigV4 authentication. +/// Parse the V2 multipart total-size capability after SigV4/SigV4a authentication. /// Header-authenticated CreateMultipartUpload requests are accepted because the -/// custom query is covered by the SigV4 canonical request; later multipart +/// custom query is covered by the SigV4/SigV4a canonical request; later multipart /// operations read the immutable value from the upload session metadata. pub(crate) fn parse_presigned_multipart_max_total_object_size( header: &HeaderMap, @@ -1226,23 +1352,9 @@ pub(crate) fn parse_presigned_multipart_max_total_object_size( }; let auth_type = get_request_auth_type_with_query(header, Some(query)); - let is_presigned = matches!(auth_type, AuthType::Presigned); - let is_header_signed = matches!(auth_type, AuthType::Signed); - let complete_presigned_query = [ - ("x-amz-algorithm", "AWS4-HMAC-SHA256"), - ("x-amz-date", ""), - ("x-amz-expires", ""), - ("x-amz-signedheaders", ""), - ("x-amz-credential", ""), - ("x-amz-signature", ""), - ] - .into_iter() - .all(|(name, expected)| { - decoded_query - .iter() - .find(|(candidate, _)| candidate.eq_ignore_ascii_case(name)) - .is_some_and(|(_, candidate)| !candidate.is_empty() && (expected.is_empty() || candidate == expected)) - }); + let is_presigned = matches!(auth_type, AuthType::Presigned | AuthType::PresignedV4a); + let is_header_signed = matches!(auth_type, AuthType::Signed | AuthType::SignedV4a); + let complete_presigned_query = is_complete_presigned_v4_or_v4a_query(&decoded_query); let authenticated = verified_sigv4 && (is_header_signed || (is_presigned && complete_presigned_query)); if !authenticated { @@ -2692,6 +2804,195 @@ mod tests { } } + #[test] + fn header_and_presigned_sigv4a_reject_unsigned_amz_and_extension_headers() { + use rustfs_gateway::sig::{AmzDate, PayloadMode, SigService, SigV4aSigner, SigningCredentials, SigningRequest}; + use rustfs_gateway::{Limits, WireRequest}; + + let build_v4a = |extra: &[(&str, &str)]| { + let mut headers = HeaderMap::new(); + headers.insert(http::header::HOST, HeaderValue::from_static("localhost")); + for &(name, value) in extra { + headers.insert( + HeaderName::from_bytes(name.as_bytes()).expect("header name"), + HeaderValue::from_str(value).expect("header value"), + ); + } + let probe = http::Request::builder() + .method(Method::GET) + .uri("/bucket/key") + .header(http::header::HOST, "localhost") + .body(bytes::Bytes::new()) + .expect("request"); + let accepted = WireRequest::accept(probe, &Limits::default()).expect("host"); + let stamp = AmzDate::parse("20260827T000000Z").expect("stamp"); + let creds = SigningCredentials::new("AKIAV4ATEST", b"secret-key-for-sigv4a-test").expect("creds"); + let signer = SigV4aSigner::new(creds, stamp.day(), SigService::S3, "*").expect("signer"); + let req = SigningRequest::new( + &Method::GET, + "/bucket/key", + "", + &headers, + accepted.host().raw_for_signing(), + PayloadMode::Empty, + stamp, + ); + ( + signer.sign_headers(&req).expect("header sign"), + signer.presign(&req, 300).expect("presign"), + ) + }; + + let (signed_header, signed_query) = build_v4a(&[]); + reject_unsigned_amz_headers_on_sigv4_request(signed_header.headers(), None).expect("clean SigV4a header passes"); + reject_unsigned_extension_headers_on_signed_request(signed_header.headers(), None) + .expect("clean SigV4a header passes extension guard"); + + let mut with_unsigned_copy = signed_header.headers().clone(); + with_unsigned_copy.insert("x-amz-copy-source", HeaderValue::from_static("/src/secret")); + assert_unsigned_headers_denied(reject_unsigned_amz_headers_on_sigv4_request(&with_unsigned_copy, None)); + + for name in EXTENSION_HEADERS { + let mut with_unsigned_ext = signed_header.headers().clone(); + with_unsigned_ext.insert(name, HeaderValue::from_static("true")); + assert_unsigned_headers_denied(reject_unsigned_amz_headers_on_sigv4_request(&with_unsigned_ext, None)); + assert_unsigned_headers_denied(reject_unsigned_extension_headers_on_signed_request(&with_unsigned_ext, None)); + + let (signed_with_ext, presigned_with_ext) = build_v4a(&[(name, "true")]); + reject_unsigned_amz_headers_on_sigv4_request(signed_with_ext.headers(), None) + .expect("signed SigV4a extension header passes"); + reject_unsigned_extension_headers_on_signed_request(signed_with_ext.headers(), None) + .expect("signed SigV4a extension header passes gateway guard"); + + let signed_target = signed_query.target(); + let (_, raw_query) = signed_target.split_once('?').expect("presigned query"); + let mut presigned_unsigned_ext = HeaderMap::new(); + presigned_unsigned_ext.insert(name, HeaderValue::from_static("true")); + assert_unsigned_headers_denied(reject_unsigned_extension_headers_on_signed_request( + &presigned_unsigned_ext, + Some(raw_query), + )); + + let ext_target = presigned_with_ext.target(); + let (_, ext_query) = ext_target.split_once('?').expect("presigned ext query"); + reject_unsigned_extension_headers_on_signed_request(&presigned_unsigned_ext, Some(ext_query)) + .expect("signed presigned SigV4a extension header passes"); + } + + let mut malformed_v4a = HeaderMap::new(); + malformed_v4a.insert("x-rustfs-force-delete", HeaderValue::from_static("true")); + malformed_v4a.insert("authorization", HeaderValue::from_static("AWS4-ECDSA-P256-SHA256 invalid")); + let err = reject_unsigned_extension_headers_on_signed_request(&malformed_v4a, None) + .expect_err("malformed SigV4a header must fail closed"); + assert_eq!(err.code(), &S3ErrorCode::AccessDenied); + } + + #[test] + fn sigv4a_classification_conditions_hoisting_and_size_caps() { + use crate::auth::facts::{AuthzFacts, AuthzPrincipal, AuthzTarget, build_conditions}; + use rustfs_policy::policy::action::{Action, S3Action}; + + const V4A_AUTH: &str = "AWS4-ECDSA-P256-SHA256 Credential=AKIAV4A/20260827/s3/aws4_request, SignedHeaders=host;x-amz-date;x-amz-region-set, Signature=30440220"; + const V4A_PRESIGNED: &str = "X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256&X-Amz-Credential=AKIAV4A%2F20260827%2Fs3%2Faws4_request&X-Amz-Date=20260827T000000Z&X-Amz-Expires=300&X-Amz-Region-Set=%2A&X-Amz-SignedHeaders=host&X-Amz-Signature=30440220"; + const V4A_PRESIGNED_NO_REGION: &str = "X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256&X-Amz-Credential=AKIAV4A%2F20260827%2Fs3%2Faws4_request&X-Amz-Date=20260827T000000Z&X-Amz-Expires=300&X-Amz-SignedHeaders=host&X-Amz-Signature=30440220"; + + let cred = Credentials { + access_key: "AKIAV4A".to_owned(), + ..Default::default() + }; + let principal = AuthzPrincipal::new(&cred, ""); + let target = || AuthzTarget { + action: Action::S3Action(S3Action::GetObjectAction), + bucket: "bucket", + object: "key", + version_id: None, + location_constraint: None, + }; + + // 1. Header and streaming SigV4a classify cleanly and emit REST-HEADER + AWS4-ECDSA-P256-SHA256. + for (content_sha256, expected_type) in [ + (None, AuthType::SignedV4a), + (Some(STREAMING_V4A_CONTENT_SHA256), AuthType::StreamingSignedV4a), + (Some(STREAMING_V4A_CONTENT_SHA256_TRAILER), AuthType::StreamingSignedTrailerV4a), + (Some(UNSIGNED_PAYLOAD_TRAILER), AuthType::StreamingUnsignedTrailerV4a), + ] { + let mut headers = HeaderMap::new(); + headers.insert(http::header::AUTHORIZATION, HeaderValue::from_static(V4A_AUTH)); + if let Some(sha) = content_sha256 { + headers.insert("x-amz-content-sha256", HeaderValue::from_static(sha)); + } + assert_eq!(get_request_auth_type_with_query(&headers, None), expected_type, "{content_sha256:?}"); + let facts = AuthzFacts::from_request_parts(&headers, None, None, None, target(), time::OffsetDateTime::now_utc()); + let conditions = build_conditions(&principal, &facts); + assert_eq!(conditions.get("authType"), Some(&vec!["REST-HEADER".to_owned()])); + assert_eq!(conditions.get("signatureversion"), Some(&vec![SIGN_V4A_ALGORITHM.to_owned()])); + } + + // 2. Presigned SigV4a emits REST-QUERY-STRING + AWS4-ECDSA-P256-SHA256 (never AWS4-HMAC-SHA256). + let empty = HeaderMap::new(); + assert_eq!(get_request_auth_type_with_query(&empty, Some(V4A_PRESIGNED)), AuthType::PresignedV4a); + let facts = + AuthzFacts::from_request_parts(&empty, Some(V4A_PRESIGNED), None, None, target(), time::OffsetDateTime::now_utc()); + let conditions = build_conditions(&principal, &facts); + assert_eq!(conditions.get("authType"), Some(&vec!["REST-QUERY-STRING".to_owned()])); + assert_eq!(conditions.get("signatureversion"), Some(&vec![SIGN_V4A_ALGORITHM.to_owned()])); + + // 3. hoist_signed_query_params supports header SigV4a and complete presigned SigV4a, + // and refuses to hoist presigned SigV4a missing X-Amz-Region-Set. + let mut v4a_header_req = HeaderMap::new(); + v4a_header_req.insert(http::header::AUTHORIZATION, HeaderValue::from_static(V4A_AUTH)); + hoist_signed_query_params(&mut v4a_header_req, Some("X-Amz-Meta-Tag=alpha")) + .expect("header SigV4a hoists query metadata"); + assert_eq!(v4a_header_req.get("x-amz-meta-tag"), Some(&HeaderValue::from_static("alpha"))); + + let mut v4a_presigned_req = HeaderMap::new(); + let presigned_meta_query = format!("{V4A_PRESIGNED}&X-Amz-Meta-Tag=beta"); + hoist_signed_query_params(&mut v4a_presigned_req, Some(&presigned_meta_query)) + .expect("presigned SigV4a with region-set hoists query metadata"); + assert_eq!(v4a_presigned_req.get("x-amz-meta-tag"), Some(&HeaderValue::from_static("beta"))); + + let mut missing_region_req = HeaderMap::new(); + let missing_region_query = format!("{V4A_PRESIGNED_NO_REGION}&X-Amz-Meta-Tag=gamma"); + hoist_signed_query_params(&mut missing_region_req, Some(&missing_region_query)) + .expect("incomplete presigned SigV4a ignores metadata"); + assert!(!missing_region_req.contains_key("x-amz-meta-tag")); + + // 4. Upload size-cap parsers accept verified SigV4a (requiring X-Amz-Region-Set when presigned) + // and reject incomplete presigned SigV4a. + let put_cap_query = format!("{V4A_PRESIGNED}&{RUSTFS_MAX_CONTENT_LENGTH_QUERY}=4096"); + assert_eq!( + parse_presigned_put_max_content_length(&empty, Some(&put_cap_query), true).expect("presigned SigV4a put cap"), + Some(4096) + ); + let incomplete_put_cap = format!("{V4A_PRESIGNED_NO_REGION}&{RUSTFS_MAX_CONTENT_LENGTH_QUERY}=4096"); + assert_eq!( + parse_presigned_put_max_content_length(&empty, Some(&incomplete_put_cap), true) + .expect_err("presigned SigV4a without region-set must fail") + .code(), + &S3ErrorCode::InvalidRequest + ); + + let mpu_cap_query = format!("{V4A_PRESIGNED}&{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY}=8192"); + assert_eq!( + parse_presigned_multipart_max_total_object_size(&empty, Some(&mpu_cap_query), true) + .expect("presigned SigV4a mpu cap"), + Some(8192) + ); + let incomplete_mpu_cap = format!("{V4A_PRESIGNED_NO_REGION}&{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY}=8192"); + assert_eq!( + parse_presigned_multipart_max_total_object_size(&empty, Some(&incomplete_mpu_cap), true) + .expect_err("presigned SigV4a mpu cap without region-set must fail") + .code(), + &S3ErrorCode::InvalidRequest + ); + let header_mpu_cap_query = format!("{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY}=16384"); + assert_eq!( + parse_presigned_multipart_max_total_object_size(&v4a_header_req, Some(&header_mpu_cap_query), true) + .expect("header SigV4a mpu cap"), + Some(16384) + ); + } + #[test] fn sigv2_request_rejects_extension_headers() { let sigv2_query = "AWSAccessKeyId=test&Expires=1893456000&Signature=abc"; @@ -3937,6 +4238,11 @@ pub(crate) mod legacy_condition_oracle { } AuthType::Signed => ("REST-HEADER".to_string(), "AWS4-HMAC-SHA256".to_string()), AuthType::Presigned => ("REST-QUERY-STRING".to_string(), "AWS4-HMAC-SHA256".to_string()), + AuthType::StreamingSignedV4a + | AuthType::StreamingSignedTrailerV4a + | AuthType::StreamingUnsignedTrailerV4a + | AuthType::SignedV4a => ("REST-HEADER".to_string(), "AWS4-ECDSA-P256-SHA256".to_string()), + AuthType::PresignedV4a => ("REST-QUERY-STRING".to_string(), "AWS4-ECDSA-P256-SHA256".to_string()), AuthType::PostPolicy => ("POST".to_string(), String::new()), AuthType::STS => ("STS".to_string(), String::new()), AuthType::Anonymous => ("Anonymous".to_string(), String::new()), diff --git a/rustfs/src/auth/facts.rs b/rustfs/src/auth/facts.rs index 0aeb85ab10..78657d6ed0 100644 --- a/rustfs/src/auth/facts.rs +++ b/rustfs/src/auth/facts.rs @@ -132,6 +132,7 @@ impl AuthTypeCondition { pub(crate) enum SignatureVersionCondition { V2, V4, + V4a, } impl SignatureVersionCondition { @@ -139,6 +140,7 @@ impl SignatureVersionCondition { match self { Self::V2 => "AWS2", Self::V4 => "AWS4-HMAC-SHA256", + Self::V4a => "AWS4-ECDSA-P256-SHA256", } } } @@ -147,7 +149,7 @@ impl SignatureVersionCondition { /// edge classified; `None` is a key the condition values leave out. fn scheme_conditions(auth_type: &AuthType) -> (Option, Option) { use AuthTypeCondition::{Anonymous, Jwt, Post, RestHeader, RestQueryString, Sts}; - use SignatureVersionCondition::{V2, V4}; + use SignatureVersionCondition::{V2, V4, V4a}; match auth_type { AuthType::JWT => (Some(Jwt), None), AuthType::SignedV2 => (Some(RestHeader), Some(V2)), @@ -156,6 +158,11 @@ fn scheme_conditions(auth_type: &AuthType) -> (Option, Option (Some(RestHeader), Some(V4)) } AuthType::Presigned => (Some(RestQueryString), Some(V4)), + AuthType::StreamingSignedV4a + | AuthType::StreamingSignedTrailerV4a + | AuthType::StreamingUnsignedTrailerV4a + | AuthType::SignedV4a => (Some(RestHeader), Some(V4a)), + AuthType::PresignedV4a => (Some(RestQueryString), Some(V4a)), AuthType::PostPolicy => (Some(Post), None), AuthType::STS => (Some(Sts), None), AuthType::Anonymous => (Some(Anonymous), None), diff --git a/rustfs/src/auth/facts/legacy_conditions.tsv b/rustfs/src/auth/facts/legacy_conditions.tsv index b0092c5643..ba7df17647 100644 --- a/rustfs/src/auth/facts/legacy_conditions.tsv +++ b/rustfs/src/auth/facts/legacy_conditions.tsv @@ -162,12 +162,36 @@ SourceIp [""] action ["AssumeRoleWithWebIdentity"] authType ["STS"] principaltype ["Anonymous"] +== sigv4a_header +CurrentTime [""] +EpochTime [""] +SecureTransport ["false"] +SourceIp [""] +authType ["REST-HEADER"] +authorization ["AWS4-ECDSA-P256-SHA256 Credential=facts-user/20261009/s3/aws4_request, SignedHeaders=host;x-amz-date;x-amz-region-set, Signature=30440220"] +principaltype ["User"] +signatureversion ["AWS4-ECDSA-P256-SHA256"] +userid ["facts-user"] +username ["facts-user"] +x-amz-date ["20261009T101500Z"] +x-amz-region-set ["*"] +== sigv4a_presigned_query +CurrentTime [""] +EpochTime [""] +SecureTransport ["false"] +SourceIp [""] +authType ["REST-QUERY-STRING"] +principaltype ["User"] +signatureAge [""] +signatureversion ["AWS4-ECDSA-P256-SHA256"] +userid ["facts-user"] +username ["facts-user"] == unknown_authorization_scheme CurrentTime [""] EpochTime [""] SecureTransport ["false"] SourceIp [""] -authorization ["AWS4-ECDSA-P256-SHA256 Credential=facts-user/20261009/s3/aws4_request"] +authorization ["AWS4-UNKNOWN-SCHEME Credential=facts-user/20261009/s3/aws4_request"] principaltype ["User"] userid ["facts-user"] username ["facts-user"] diff --git a/rustfs/src/auth/facts/tests.rs b/rustfs/src/auth/facts/tests.rs index 2f2fa13f7b..78dced73a1 100644 --- a/rustfs/src/auth/facts/tests.rs +++ b/rustfs/src/auth/facts/tests.rs @@ -396,8 +396,20 @@ fn cases() -> Vec { .sigv4() .header("Content-Type", "multipart/form-data; boundary=facts"), Case::new("sts_action_header", Anonymous).header("Action", "AssumeRoleWithWebIdentity"), + Case::new("sigv4a_header", User) + .header( + "Authorization", + "AWS4-ECDSA-P256-SHA256 Credential=facts-user/20261009/s3/aws4_request, SignedHeaders=host;x-amz-date;x-amz-region-set, Signature=30440220", + ) + .header("X-Amz-Date", "20261009T101500Z") + .header("X-Amz-Region-Set", "*"), + Case::new("sigv4a_presigned_query", User).query( + "X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256&X-Amz-Credential=facts-user%2F20261009%2Fs3%2Faws4_request\ + &X-Amz-Date=20261009T101500Z&X-Amz-Expires=300&X-Amz-Region-Set=%2A&X-Amz-SignedHeaders=host\ + &X-Amz-Signature=30440220", + ), Case::new("unknown_authorization_scheme", User) - .header("Authorization", "AWS4-ECDSA-P256-SHA256 Credential=facts-user/20261009/s3/aws4_request"), + .header("Authorization", "AWS4-UNKNOWN-SCHEME Credential=facts-user/20261009/s3/aws4_request"), // Who is asking: `aws:userid`, `aws:username`, `aws:principaltype` and claims. Case::new("sts_principal_with_token_header", Sts) .sigv4() @@ -716,8 +728,8 @@ fn version_id_matches_legacy() { #[test] fn signature_version_matches_legacy() { - assert_key_matches_legacy("signatureversion", 2, 1); - assert_legacy_values_seen("signatureversion", &["AWS2", "AWS4-HMAC-SHA256"]); + assert_key_matches_legacy("signatureversion", 3, 1); + assert_legacy_values_seen("signatureversion", &["AWS2", "AWS4-ECDSA-P256-SHA256", "AWS4-HMAC-SHA256"]); } #[test] @@ -894,7 +906,7 @@ fn absent_request_facts_leave_their_keys_absent() { let conditions = build_conditions( &AuthzPrincipal::new(&credentials(Who::User), ""), &Case::new("bare", Who::User) - .header("Authorization", "AWS4-ECDSA-P256-SHA256 Credential=unknown") + .header("Authorization", "AWS4-UNKNOWN-SCHEME Credential=unknown") .facts(OffsetDateTime::now_utc()), ); for key in [ diff --git a/rustfs/src/server/gateway_authorizer.rs b/rustfs/src/server/gateway_authorizer.rs index 7bdfb47e95..d9d1814fd4 100644 --- a/rustfs/src/server/gateway_authorizer.rs +++ b/rustfs/src/server/gateway_authorizer.rs @@ -208,7 +208,8 @@ fn prepare_request( copy_extension::(context, &mut extensions); copy_extension::(context, &mut extensions); extensions.insert(Arc::clone(server_ctx)); - AccessMarkers::new(request.operation, verified_signature(context.auth_scheme())).install(&mut extensions); + AccessMarkers::new(request.operation, verified_signature(context.auth_scheme(), &headers, raw_query)) + .install(&mut extensions); let scope = context.verified_scope(); let head = RequestHead { method: Method::GET, @@ -284,7 +285,7 @@ async fn install_caller(prepared: &mut PreparedRequest, server_ctx: &Arc VerifiedSignature { +fn verified_signature(scheme: AuthSchemeRef, headers: &HeaderMap, raw_query: &str) -> VerifiedSignature { match scheme { AuthSchemeRef::SigV4Header => VerifiedSignature { sigv4: true, @@ -294,6 +295,23 @@ fn verified_signature(scheme: AuthSchemeRef) -> VerifiedSignature { sigv4: true, presigned: true, }, + AuthSchemeRef::OtherSigned => { + let query = (!raw_query.is_empty()).then_some(raw_query); + match crate::auth::get_request_auth_type_with_query(headers, query) { + crate::auth::AuthType::PresignedV4a => VerifiedSignature { + sigv4: true, + presigned: true, + }, + crate::auth::AuthType::SignedV4a + | crate::auth::AuthType::StreamingSignedV4a + | crate::auth::AuthType::StreamingSignedTrailerV4a + | crate::auth::AuthType::StreamingUnsignedTrailerV4a => VerifiedSignature { + sigv4: true, + presigned: false, + }, + _ => VerifiedSignature::default(), + } + } _ => VerifiedSignature::default(), } } diff --git a/rustfs/src/server/gateway_handlers/access.rs b/rustfs/src/server/gateway_handlers/access.rs index 02c3ac3590..500b6288a0 100644 --- a/rustfs/src/server/gateway_handlers/access.rs +++ b/rustfs/src/server/gateway_handlers/access.rs @@ -156,11 +156,11 @@ fn require_server_context(envelope: &RequestEnvelope) -> S3Result VerifiedSignature { match context.principal().map(RequestPrincipal::scheme) { - Some(scheme) if scheme.family() == SigFamily::V4 => VerifiedSignature { + Some(scheme) if matches!(scheme.family(), SigFamily::V4 | SigFamily::V4a) => VerifiedSignature { sigv4: matches!(scheme.location(), SigLocation::Header | SigLocation::Query), presigned: scheme.location() == SigLocation::Query, }, diff --git a/rustfs/src/server/gateway_handlers/envelope.rs b/rustfs/src/server/gateway_handlers/envelope.rs index d9ef924afd..6cd5a90b8c 100644 --- a/rustfs/src/server/gateway_handlers/envelope.rs +++ b/rustfs/src/server/gateway_handlers/envelope.rs @@ -384,6 +384,78 @@ mod tests { assert!(envelope.verified_presigned().is_some(), "verified_presigned"); } + #[tokio::test] + async fn sigv4a_header_and_query_signatures_mark_verified_and_emit_v4a_conditions() { + use crate::app::storage_api::owned_parity::parity_test_support::request_authz_facts; + use crate::auth::facts::{AuthzPrincipal, AuthzTarget, build_conditions}; + use rustfs_gateway::sig::{AmzDate, PayloadMode, SigService, SigV4aSigner, SigningCredentials, SigningRequest}; + use rustfs_gateway::{Limits, WireRequest}; + use rustfs_policy::policy::action::{Action, S3Action}; + + let sign_v4a = |form: Signed| { + let mut headers = HeaderMap::new(); + headers.insert(http::header::HOST, HeaderValue::from_static("localhost")); + let probe = Request::builder() + .method(Method::GET) + .uri("/") + .header(http::header::HOST, "localhost") + .body(Bytes::new()) + .expect("probe"); + let accepted = WireRequest::accept(probe, &Limits::default()).expect("host"); + let stamp = AmzDate::parse(&chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string()).expect("stamp"); + let creds = SigningCredentials::new(SIGNER_ACCESS_KEY, SIGNER_SECRET_KEY.as_bytes()).expect("creds"); + let signer = SigV4aSigner::new(creds, stamp.day(), SigService::S3, "*").expect("signer"); + let req = SigningRequest::new( + &Method::GET, + "/", + "", + &headers, + accepted.host().raw_for_signing(), + PayloadMode::Unsigned, + stamp, + ); + let signed = match form { + Signed::Header => signer.sign_headers(&req), + Signed::Query => signer.presign(&req, 300), + } + .expect("signed SigV4a"); + let mut builder = Request::builder().method(Method::GET).uri(signed.target()); + for (name, value) in signed.headers() { + builder = builder.header(name, value); + } + builder.body(Empty::new()).expect("request") + }; + + let cred = rustfs_credentials::Credentials { + access_key: SIGNER_ACCESS_KEY.to_owned(), + ..Default::default() + }; + let target = || AuthzTarget { + action: Action::S3Action(S3Action::ListAllMyBucketsAction), + bucket: "", + object: "", + version_id: None, + location_constraint: None, + }; + + let header_env = envelope_of::(sign_v4a(Signed::Header), &ServerContextSlot::new()).await; + assert!(header_env.verified_sigv4().is_some(), "header SigV4a verified_sigv4"); + assert!(header_env.verified_presigned().is_none(), "header SigV4a verified_presigned"); + let header_conditions = build_conditions(&AuthzPrincipal::new(&cred, ""), &request_authz_facts(&header_env, target())); + assert_eq!(header_conditions.get("authType"), Some(&vec!["REST-HEADER".to_owned()])); + assert_eq!( + header_conditions.get("signatureversion"), + Some(&vec!["AWS4-ECDSA-P256-SHA256".to_owned()]) + ); + + let query_env = envelope_of::(sign_v4a(Signed::Query), &ServerContextSlot::new()).await; + assert!(query_env.verified_sigv4().is_some(), "presigned SigV4a verified_sigv4"); + assert!(query_env.verified_presigned().is_some(), "presigned SigV4a verified_presigned"); + let query_conditions = build_conditions(&AuthzPrincipal::new(&cred, ""), &request_authz_facts(&query_env, target())); + assert_eq!(query_conditions.get("authType"), Some(&vec!["REST-QUERY-STRING".to_owned()])); + assert_eq!(query_conditions.get("signatureversion"), Some(&vec!["AWS4-ECDSA-P256-SHA256".to_owned()])); + } + #[tokio::test] async fn presigned_and_anonymous_gateway_envelopes_ignore_unsigned_auth_type_headers() { use crate::app::storage_api::owned_parity::parity_test_support::request_authz_facts; diff --git a/rustfs/src/server/gateway_stack/tests.rs b/rustfs/src/server/gateway_stack/tests.rs index 11e0024214..92169c9c3e 100644 --- a/rustfs/src/server/gateway_stack/tests.rs +++ b/rustfs/src/server/gateway_stack/tests.rs @@ -1151,3 +1151,223 @@ fn assemble_initializes_s3_and_list_objects_metrics() { "GatewayStack::assemble must initialize ListObjects metrics" ); } + +/// Signs `method path?query` for `access_key`/`secret_key` with AWS SigV4a +/// (`AWS4-ECDSA-P256-SHA256`), either in the `Authorization` header or as a presigned query string. +fn sigv4a_request( + form: Signed, + method: Method, + path: &str, + query: &str, + headers: HeaderMap, + access_key: &str, + secret_key: &str, +) -> Request> { + use rustfs_gateway::sig::{AmzDate, PayloadMode, SigService, SigV4aSigner, SigningCredentials, SigningRequest}; + use rustfs_gateway::{Limits, WireRequest}; + + let mut headers = headers; + headers + .entry(http::header::HOST) + .or_insert(http::HeaderValue::from_static("localhost")); + let probe = Request::builder() + .method(method.clone()) + .uri(path) + .header(http::header::HOST, headers.get(http::header::HOST).expect("a host")) + .body(Bytes::new()) + .expect("static request"); + let accepted = WireRequest::accept(probe, &Limits::default()).expect("an acceptable host"); + let stamp = AmzDate::parse(&chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string()).expect("a stamp"); + let credentials = SigningCredentials::new(access_key, secret_key.as_bytes()).expect("credentials"); + let signer = SigV4aSigner::new(credentials, stamp.day(), SigService::S3, "*").expect("a SigV4a signer"); + let signing = SigningRequest::new( + &method, + path, + query, + &headers, + accepted.host().raw_for_signing(), + PayloadMode::Unsigned, + stamp, + ); + let signed = match form { + Signed::Header => signer.sign_headers(&signing), + Signed::Query => signer.presign(&signing, 300), + } + .expect("a signable SigV4a request"); + let mut builder = Request::builder().method(method).uri(signed.target()); + for (name, value) in signed.headers() { + builder = builder.header(name, value); + } + builder.body(Empty::new()).expect("a built SigV4a request") +} + +struct SigV4aProbe(std::sync::atomic::AtomicUsize); + +impl rustfs_gateway::Handler for SigV4aProbe { + async fn call( + &self, + request: rustfs_gateway::Req, + ) -> rustfs_gateway::HandlerResult { + assert_eq!( + request.context().principal().map(|principal| principal.access_key_id()), + Some(ROOT_ACCESS_KEY) + ); + self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(rustfs_gateway::Resp::new(rustfs_gateway::dto::ListBucketsOutput::default())) + } +} + +/// SigV4a header and presigned requests verify through `GatewayStack`, enforce signed +/// `x-rustfs-*` extension headers before reaching handlers, and reject tampered signatures. +#[tokio::test] +async fn sigv4a_requests_verify_and_enforce_signed_extension_headers() { + let probe = Arc::new(SigV4aProbe(std::sync::atomic::AtomicUsize::new(0))); + let a = assembly(); + let builder = GatewayStack::configured_builder( + &a, + Arc::new(ScriptedIam { ready: true }), + root().source(), + decide_with(|request| { + if request.operation == "ListBuckets" && request.identity.is_some() { + Decision::Allow + } else { + Decision::Deny + } + }), + std::convert::identity, + ) + .expect("the production builder assembles"); + let stack = GatewayStack { + service: builder + .register::(Arc::clone(&probe)) + .build() + .expect("probe registration"), + keystone_auth: None, + control_plane: false, + object_lambda_fallback: None, + }; + + for form in [Signed::Header, Signed::Query] { + let req = sigv4a_request(form, Method::GET, "/", "", HeaderMap::new(), ROOT_ACCESS_KEY, ROOT_SECRET_KEY); + let (status, _, body) = answer_request(&stack, req).await; + assert_eq!(status, StatusCode::OK, "{body}"); + + let mut signed_ext = HeaderMap::new(); + signed_ext.insert("x-rustfs-meta-probe", http::HeaderValue::from_static("ok")); + let req = sigv4a_request(form, Method::GET, "/", "", signed_ext, ROOT_ACCESS_KEY, ROOT_SECRET_KEY); + let (status, _, body) = answer_request(&stack, req).await; + assert_eq!(status, StatusCode::OK, "signed extension header must pass: {body}"); + + let mut unsigned_ext = sigv4a_request(form, Method::GET, "/", "", HeaderMap::new(), ROOT_ACCESS_KEY, ROOT_SECRET_KEY); + unsigned_ext + .headers_mut() + .insert("x-rustfs-force-delete", http::HeaderValue::from_static("true")); + let before = probe.0.load(std::sync::atomic::Ordering::SeqCst); + let (status, _, body) = answer_request(&stack, unsigned_ext).await; + assert_eq!(status, StatusCode::FORBIDDEN, "unsigned extension header must fail: {body}"); + assert!(body.contains("AccessDenied"), "{body}"); + assert_eq!( + probe.0.load(std::sync::atomic::Ordering::SeqCst), + before, + "unsigned extension header must never reach the handler" + ); + } + + let mut tampered = sigv4a_request(Signed::Header, Method::GET, "/", "", HeaderMap::new(), ROOT_ACCESS_KEY, ROOT_SECRET_KEY); + let auth = tampered + .headers() + .get(http::header::AUTHORIZATION) + .expect("authorization") + .to_str() + .expect("utf-8") + .to_owned(); + let last = auth.as_bytes().last().copied().expect("non-empty signature"); + let flipped = if last == b'0' { '1' } else { '0' }; + let mut broken = auth[..auth.len() - 1].to_owned(); + broken.push(flipped); + tampered + .headers_mut() + .insert(http::header::AUTHORIZATION, broken.parse().expect("header value")); + let before = probe.0.load(std::sync::atomic::Ordering::SeqCst); + let (status, _, body) = answer_request(&stack, tampered).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{body}"); + assert!(body.contains("SignatureDoesNotMatch"), "{body}"); + assert_eq!(probe.0.load(std::sync::atomic::Ordering::SeqCst), before); + assert_eq!(probe.0.load(std::sync::atomic::Ordering::SeqCst), 4); +} + +/// Real `GatewayStack::assemble` (real `EarlyAuthorizer` + real `GatewayBackend` handlers) serves +/// header SigV4a `ListBuckets`, allows a clean presigned SigV4a `UploadPart` to reach storage +/// (`404 NoSuchUpload`), and denies a presigned SigV4a `UploadPart` carrying a signed +/// `x-rustfs-replication-part-actual-size` header (`403 AccessDenied`). +#[tokio::test] +#[serial_test::serial] +async fn production_gateway_stack_blocks_presigned_sigv4a_upload_part_replication_headers() { + use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions}; + + let store = crate::app::gating_test_env::shared_gating_ecstore().await; + if crate::runtime_sources::current_app_context().is_none() { + crate::runtime_sources::install_test_app_context(Arc::clone(&store)).await; + } + let ambient = crate::runtime_sources::current_app_context().expect("ambient AppContext"); + let context = Arc::new(crate::runtime_sources::AppContext::new(Arc::clone(&store), ambient.iam(), ambient.kms())); + let bucket = format!("sigv4a-upload-part-{}", uuid::Uuid::new_v4()); + store + .make_bucket(&bucket, &MakeBucketOptions::default()) + .await + .expect("create SigV4a test bucket"); + let slot = ServerContextSlot::new(); + assert!(slot.install(Arc::clone(&context))); + let gateway = TestGateway::over(&context, slot); + + // Header SigV4a passes real EarlyAuthorizer and ListBuckets handler. + let list_req = sigv4a_request( + Signed::Header, + Method::GET, + "/", + "", + HeaderMap::new(), + TestGateway::ACCESS_KEY, + TestGateway::SECRET_KEY, + ); + let (status, _, body) = answer_request(&gateway.0, list_req).await; + assert_eq!(status, StatusCode::OK, "header SigV4a ListBuckets must succeed: {body}"); + + // Positive control: presigned SigV4a UploadPart without replication headers passes auth, + // EarlyAuthorizer, and admit_operation, reaching storage (404 NoSuchUpload). + let path = format!("/{bucket}/obj"); + let query = "partNumber=1&uploadId=nonexistent-upload"; + let control_req = sigv4a_request( + Signed::Query, + Method::PUT, + &path, + query, + HeaderMap::new(), + TestGateway::ACCESS_KEY, + TestGateway::SECRET_KEY, + ); + let (status, _, body) = answer_request(&gateway.0, control_req).await; + assert_eq!(status, StatusCode::NOT_FOUND, "control UploadPart must reach storage: {body}"); + assert!(body.contains("NoSuchUpload"), "{body}"); + + // Negative regression: the identical presigned SigV4a UploadPart carrying a *signed* + // `x-rustfs-replication-part-actual-size` header must be denied 403 AccessDenied. + let mut repl_headers = HeaderMap::new(); + repl_headers.insert("x-rustfs-replication-part-actual-size", http::HeaderValue::from_static("128")); + let repl_req = sigv4a_request( + Signed::Query, + Method::PUT, + &path, + query, + repl_headers, + TestGateway::ACCESS_KEY, + TestGateway::SECRET_KEY, + ); + let (status, _, body) = answer_request(&gateway.0, repl_req).await; + assert_eq!( + status, + StatusCode::FORBIDDEN, + "presigned SigV4a UploadPart with signed replication header must be denied: {body}" + ); + assert!(body.contains("AccessDenied"), "{body}"); +} diff --git a/rustfs/src/storage/authorization/admission.rs b/rustfs/src/storage/authorization/admission.rs index 9300aba62c..43523f67d1 100644 --- a/rustfs/src/storage/authorization/admission.rs +++ b/rustfs/src/storage/authorization/admission.rs @@ -56,8 +56,11 @@ impl VerifiedSignature { /// The legacy edge's reading: s3s verified the signature form these headers name. pub(crate) fn from_auth_type(auth_type: AuthType) -> Self { Self { - sigv4: matches!(auth_type, AuthType::Presigned | AuthType::Signed), - presigned: matches!(auth_type, AuthType::Presigned), + sigv4: matches!( + auth_type, + AuthType::Presigned | AuthType::PresignedV4a | AuthType::Signed | AuthType::SignedV4a + ), + presigned: matches!(auth_type, AuthType::Presigned | AuthType::PresignedV4a), } } } @@ -177,7 +180,9 @@ pub(crate) fn admit_operation( request_validation::RequestViolation::DeleteAcl => S3Error::new(S3ErrorCode::MethodNotAllowed), })?; crate::auth::reject_unsigned_amz_headers_on_sigv4_request(headers, raw_query)?; - if (signature.presigned || operation == "PostObject") && super::decision::has_replication_only_put_headers(headers) { + if (signature.presigned || crate::auth::is_presigned_request_head(headers, raw_query) || operation == "PostObject") + && super::decision::has_replication_only_put_headers(headers) + { return Err(s3_error!(AccessDenied, "Access Denied")); } if operation == "PostObject" { @@ -289,9 +294,12 @@ mod access_phase_tests { for (auth_type, expected) in [ (AuthType::Signed, (true, false)), (AuthType::Presigned, (true, true)), + (AuthType::SignedV4a, (true, false)), + (AuthType::PresignedV4a, (true, true)), (AuthType::SignedV2, (false, false)), (AuthType::PresignedV2, (false, false)), (AuthType::StreamingSigned, (false, false)), + (AuthType::StreamingSignedV4a, (false, false)), (AuthType::PostPolicy, (false, false)), (AuthType::Anonymous, (false, false)), ] { @@ -371,6 +379,26 @@ mod access_phase_tests { assert_eq!(err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied, "{operation} {header_name}"); } + // Defense in depth: presigned SigV4a replication headers on UploadPart/PutObject are + // denied both when `signature.presigned` is set and even if a caller passes default markers. + let presigned_v4a_host_only = "X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-Region-Set=*&X-Amz-SignedHeaders=host&X-Amz-Credential=test/20260827/s3/aws4_request&X-Amz-Signature=deadbeef"; + for signature in [ + VerifiedSignature { + sigv4: true, + presigned: true, + }, + VerifiedSignature::default(), + ] { + let signed_v4a_replication = presigned_v4a_host_only + .replace("SignedHeaders=host", "SignedHeaders=host%3Bx-rustfs-replication-part-actual-size"); + let mut headers = http::HeaderMap::new(); + headers.insert("x-rustfs-replication-part-actual-size", "1024".parse().unwrap()); + let err = + super::admit_operation(&http::Method::PUT, &headers, Some(&signed_v4a_replication), "UploadPart", signature) + .expect_err("presigned SigV4a UploadPart must never pass replication-only headers"); + assert_eq!(err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied, "{signature:?}"); + } + // Browser POST policy requests do not sign HTTP headers, so replication-only headers are rejected too. let mut post_headers = http::HeaderMap::new(); post_headers.insert("x-rustfs-source-version-id", "v1".parse().unwrap()); diff --git a/rustfs/src/storage/options.rs b/rustfs/src/storage/options.rs index 127f9209aa..f8872b9a16 100644 --- a/rustfs/src/storage/options.rs +++ b/rustfs/src/storage/options.rs @@ -1148,7 +1148,7 @@ pub fn parse_copy_source_range(range_str: &str) -> S3Result { /// manufactures the header this checks for. pub(crate) fn get_content_sha256_with_query(headers: &HeaderMap, query: Option<&str>) -> Option { match get_request_auth_type_with_query(headers, query) { - AuthType::Presigned if !headers.contains_key(AMZ_CONTENT_SHA256) => { + AuthType::Presigned | AuthType::PresignedV4a if !headers.contains_key(AMZ_CONTENT_SHA256) => { if skip_content_sha256_cksum_with_query(headers, query) { None } else { @@ -1159,7 +1159,10 @@ pub(crate) fn get_content_sha256_with_query(headers: &HeaderMap, qu } } fn skip_content_sha256_cksum_with_query(headers: &HeaderMap, query: Option<&str>) -> bool { - let include_query_values = matches!(get_request_auth_type_with_query(headers, query), AuthType::Presigned); + let include_query_values = matches!( + get_request_auth_type_with_query(headers, query), + AuthType::Presigned | AuthType::PresignedV4a + ); let content_sha256 = get_content_sha256_value(headers, query, include_query_values); // Skip if no checksum value was set in header/query for query-presigned requests. @@ -3249,6 +3252,15 @@ mod tests { let query = format!("{PRESIGNED_QUERY}&x-amz-content-sha256=UNSIGNED-PAYLOAD"); assert_eq!(super::get_content_sha256_with_query(&headers, Some(&query)), None); + + let presigned_v4a = "X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256&X-Amz-Region-Set=*&X-Amz-Credential=ak%2F20260916%2Fs3%2Faws4_request&X-Amz-Signature=deadbeef"; + let v4a_query = format!("{presigned_v4a}&x-amz-content-sha256={PAYLOAD_SHA256}"); + assert_eq!( + super::get_content_sha256_with_query(&headers, Some(&v4a_query)), + Some(PAYLOAD_SHA256.to_string()) + ); + let v4a_unsigned = format!("{presigned_v4a}&x-amz-content-sha256=UNSIGNED-PAYLOAD"); + assert_eq!(super::get_content_sha256_with_query(&headers, Some(&v4a_unsigned)), None); } #[test] diff --git a/rustfs/tests/embedded_gateway_stack_test/listing_multipart/parts.rs b/rustfs/tests/embedded_gateway_stack_test/listing_multipart/parts.rs index d115664010..18a39c6678 100644 --- a/rustfs/tests/embedded_gateway_stack_test/listing_multipart/parts.rs +++ b/rustfs/tests/embedded_gateway_stack_test/listing_multipart/parts.rs @@ -175,7 +175,15 @@ async fn list_parts_wire(server: RustFSServer, legacy: bool) { (Some("invalid"), None, "invalid query: part-number-marker: invalid"), (Some(""), None, "invalid query: part-number-marker: "), (Some("2147483648"), None, "invalid query: part-number-marker: 2147483648"), - (None, Some(-1), "max-parts must be between 1 and 1000"), + ( + None, + Some(-1), + if legacy { + "max-parts must be between 1 and 1000" + } else { + "the request carries a value this member cannot hold" + }, + ), (None, Some(0), "max-parts must be between 1 and 1000"), (None, Some(1001), "max-parts must be between 1 and 1000"), (Some("-1"), Some(0), "part-number-marker must be non-negative"),