feat(gateway): verify SigV4 on S3-port reserved console paths via gateway@095d4763

Bump the pinned rustfs/gateway revision to 095d4763a3f58a5e1d22fe7a231bf1c105473de8
(#1620, independent service-scoped dialects with single-segment path claims) and
add an independent SigService::S3 reserved-console host for console-disabled
listeners (such as the S3 port when a dedicated console listener is enabled).

Both default (/rustfs/console) and custom single-segment console prefixes (/ui,
/UI_assets) plus root icon paths now bypass S3 bucket-name parsing while keeping
original-URI SigV4 verification intact: anonymous and SigV2 requests receive
403 AccessDenied and validly signed SigV4 requests receive 501 NotImplemented,
matching RustFS 1.0.5 while preserving extension/Object Lambda precedence and
dedicated console listener 200 responses (rustfs/backlog#2771).
This commit is contained in:
overtrue
2026-11-26 11:12:46 +08:00
parent 2ddfd16d49
commit bdcb29c2aa
11 changed files with 721 additions and 36 deletions
Generated
+14 -14
View File
@@ -10433,8 +10433,8 @@ dependencies = [
[[package]]
name = "rustfs-gateway"
version = "0.66.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ecafc085de850e1be0c22ba173bf1accc68e75c5#ecafc085de850e1be0c22ba173bf1accc68e75c5"
version = "0.67.0"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"arc-swap",
"bytes",
@@ -10480,8 +10480,8 @@ dependencies = [
[[package]]
name = "rustfs-gateway-core"
version = "0.63.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ecafc085de850e1be0c22ba173bf1accc68e75c5#ecafc085de850e1be0c22ba173bf1accc68e75c5"
version = "0.64.0"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"bytes",
"futures-core",
@@ -10502,7 +10502,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-corpus"
version = "0.1.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ecafc085de850e1be0c22ba173bf1accc68e75c5#ecafc085de850e1be0c22ba173bf1accc68e75c5"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"serde",
"serde_json",
@@ -10512,7 +10512,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-corpus-recorder"
version = "0.1.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ecafc085de850e1be0c22ba173bf1accc68e75c5#ecafc085de850e1be0c22ba173bf1accc68e75c5"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"bytes",
"http 1.5.0",
@@ -10527,7 +10527,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-dialect-rustfs-admin"
version = "0.13.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ecafc085de850e1be0c22ba173bf1accc68e75c5#ecafc085de850e1be0c22ba173bf1accc68e75c5"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"bytes",
"form_urlencoded",
@@ -10541,7 +10541,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-http"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=ecafc085de850e1be0c22ba173bf1accc68e75c5#ecafc085de850e1be0c22ba173bf1accc68e75c5"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"hmac 0.13.0",
"http 1.5.0",
@@ -10559,7 +10559,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-macros"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=ecafc085de850e1be0c22ba173bf1accc68e75c5#ecafc085de850e1be0c22ba173bf1accc68e75c5"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"proc-macro2",
"quote",
@@ -10568,8 +10568,8 @@ dependencies = [
[[package]]
name = "rustfs-gateway-sig"
version = "0.15.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ecafc085de850e1be0c22ba173bf1accc68e75c5#ecafc085de850e1be0c22ba173bf1accc68e75c5"
version = "0.16.0"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"hmac 0.13.0",
"http 1.5.0",
@@ -10584,7 +10584,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-stream"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ecafc085de850e1be0c22ba173bf1accc68e75c5#ecafc085de850e1be0c22ba173bf1accc68e75c5"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"bitflags 2.13.2",
"bytes",
@@ -10595,7 +10595,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-types"
version = "0.42.0+aws.2026-10-02"
source = "git+https://github.com/rustfs/gateway.git?rev=ecafc085de850e1be0c22ba173bf1accc68e75c5#ecafc085de850e1be0c22ba173bf1accc68e75c5"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"bytes",
"crc-fast",
@@ -10617,7 +10617,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-xml"
version = "0.4.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ecafc085de850e1be0c22ba173bf1accc68e75c5#ecafc085de850e1be0c22ba173bf1accc68e75c5"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"quick-xml 0.41.0",
]
+7 -7
View File
@@ -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 = "ecafc085de850e1be0c22ba173bf1accc68e75c5", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "ecafc085de850e1be0c22ba173bf1accc68e75c5", version = "0.2.0", default-features = false }
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", 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 = "ecafc085de850e1be0c22ba173bf1accc68e75c5", version = "0.66.0", default-features = false }
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", version = "0.67.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 = "ecafc085de850e1be0c22ba173bf1accc68e75c5", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "ecafc085de850e1be0c22ba173bf1accc68e75c5", version = "0.63.0", default-features = false }
rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "ecafc085de850e1be0c22ba173bf1accc68e75c5", version = "0.1.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "ecafc085de850e1be0c22ba173bf1accc68e75c5", version = "0.13.0", default-features = false }
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", version = "0.64.0", default-features = false }
rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", version = "0.1.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", version = "0.13.0", default-features = false }
# Async Runtime and Networking
async-channel = "2.5.0"
+1 -1
View File
@@ -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: /<bucket>` (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/ecafc085de850e1be0c22ba173bf1accc68e75c5/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/095d4763a3f58a5e1d22fe7a231bf1c105473de8/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`.
+23
View File
@@ -1179,6 +1179,29 @@ impl<T> S3Router<T> {
}
}
/// Access rule for reserved console paths arriving on a listener where the native console is
/// disabled (for example, the S3 port when a dedicated console port is enabled).
pub(crate) fn admit_reserved_console(
server_ctx: Option<&crate::admin::runtime_sources::ServerContextSlot>,
method: &Method,
uri: &Uri,
headers: &HeaderMap,
signed: bool,
) -> rustfs_s3_types::S3Result<()> {
reject_unsigned_amz_headers_on_sigv4_request(headers, uri.query())?;
if let Some(server_ctx) = server_ctx
&& server_ctx.installed_app_context().is_none()
{
return Err(server_context_not_ready_error());
}
reject_unbound_custom_route_auth(method, uri, headers, signed)?;
if signed {
Ok(())
} else {
Err(access_denied("Signature is required"))
}
}
/// Answers a request `router` admitted from its route table: an extension route by its key,
/// every other route by its canonical path, an unknown v4 admin path `426`, and anything else
/// `NotImplemented`. Object Lambda and the console are each edge's own.
+23 -1
View File
@@ -51,6 +51,7 @@
mod admin;
mod control_plane;
pub(in crate::server) mod indeterminate_audit;
mod reserved_console;
#[cfg(test)]
pub(crate) static CONFIG_HANDLER_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
@@ -207,6 +208,16 @@ impl GatewayStack {
control_plane::assemble(assembly, iam, root, router)
}
/// Assembles the independent S3-signed host for reserved console paths when the native console
/// is not mounted on this listener.
pub(crate) fn assemble_reserved_console(assembly: GatewayAssembly) -> Result<Self, GatewayAssemblyError> {
let iam = Arc::new(ServerIam {
server_ctx: Arc::clone(&assembly.server_ctx),
});
let root = Arc::new(live_root(Arc::clone(&assembly.server_ctx)));
reserved_console::assemble(assembly, iam, root)
}
/// The stack as [`GatewayStack::assemble`] configures it, admitting every caller to the
/// handlers `register` adds instead of RustFS's: for tests of the host layers around it.
#[cfg(test)]
@@ -255,6 +266,17 @@ impl GatewayStack {
root: Arc<dyn RootSource>,
authorizer: impl Authorizer,
authenticator: impl FnOnce(SigV4Authenticator) -> SigV4Authenticator,
) -> Result<ServiceBuilder, GatewayAssemblyError> {
Self::configured_builder_on(ServiceBuilder::new(), assembly, iam, root, authorizer, authenticator)
}
fn configured_builder_on(
base: ServiceBuilder,
assembly: &GatewayAssembly,
iam: Arc<dyn IamKeyLookup>,
root: Arc<dyn RootSource>,
authorizer: impl Authorizer,
authenticator: impl FnOnce(SigV4Authenticator) -> SigV4Authenticator,
) -> Result<ServiceBuilder, GatewayAssemblyError> {
// A root the gateway could not verify a signature with is a startup error, never a
// server that silently has no root. Requests read the live root from `root`.
@@ -269,7 +291,7 @@ impl GatewayStack {
// Every legacy RustFS reading of a request, a credential scope and an answer, in the
// gateway's one reviewable preset; its other half is on the authenticator.
let credentials = Arc::new(IamCredentials::new(iam, root));
let builder = ServiceBuilder::new()
let builder = base
.rustfs_profile()
// Shipped RustFS authorizes before it judges an SSE header; the handler entry answers
// the refusal once authorization succeeds.
@@ -426,13 +426,13 @@ pub(super) fn assemble(
/// The head of a claimed request as the transport handed it over, which the access rule reads.
#[derive(Clone)]
struct ClaimedHead {
method: Method,
uri: Uri,
headers: HeaderMap,
pub(super) struct ClaimedHead {
pub(super) method: Method,
pub(super) uri: Uri,
pub(super) headers: HeaderMap,
/// Whether the request carried more than one `Authorization` line, which [`attach_head`]
/// removed before the gateway read the request.
repeated_authorization: bool,
pub(super) repeated_authorization: bool,
}
/// Attaches the head of `request` for the access rule, before the gateway reads anything.
@@ -0,0 +1,322 @@
// 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.
//! Independent S3-signed gateway host for reserved console paths when the console is disabled on
//! this listener (for example, the S3 listener while a dedicated console listener serves assets).
//!
//! Using `ServiceBuilder::for_service(SigService::S3)` with `Dialect::assemble_for_service` lets
//! both multi-segment defaults (`/rustfs/console`) and single-segment custom prefixes (`/ui`,
//! `/UI_assets`, `/favicon.ico`) bypass S3 bucket-name parsing while keeping original-URI SigV4
//! verification intact: anonymous requests receive `403 AccessDenied` and validly signed requests
//! receive `501 NotImplemented`, matching RustFS 1.0.5 (rustfs/backlog#2771).
use super::control_plane::ClaimedHead;
use super::{GatewayAssembly, GatewayAssemblyError, GatewayStack};
use crate::admin::router::admit_reserved_console;
use crate::runtime_sources::ServerContextSlot;
use crate::server::gateway_handlers::handler_error;
use crate::server::{APPLE_TOUCH_ICON_PATH, APPLE_TOUCH_ICON_PRECOMPOSED_PATH, FAVICON_PATH, console_prefix};
use bytes::Bytes;
use rustfs_gateway::sig::SigService;
use rustfs_gateway::{
Authorizer, AuthzRequest, BoxFuture, Decision, Handler, HandlerError, HandlerResult, InputAuthzRequest, InputDecisions,
Operation, OperationFloor, Req, RequestContext as AuthzContext, ServiceBuilder,
};
use rustfs_gateway_adapter::{IamKeyLookup, RootSource};
use rustfs_gateway_core::codec::{CodecError, EncodedResponse, MetaView, OperationCodec, RequestBody, RequestBodyMode};
use rustfs_gateway_core::dialect::{ClaimedRoute, ClaimedRow, Dialect, DialectOverlay, OverlayRow, render_claimed_route};
use rustfs_gateway_core::op::{AuthRequirement, ResourceShape};
use rustfs_gateway_core::registry::{HandlerDeadlineClass, OperationSpec};
use rustfs_gateway_core::route::PathClaim;
use rustfs_gateway_core::{DerivedResourceError, NoDerived};
use rustfs_gateway_dialect_rustfs_admin::{AdminResponse as WireResponse, OVERLAY, admin};
use rustfs_s3_types::s3_error;
use std::sync::{Arc, OnceLock};
const ROUTER: &str = "https://github.com/rustfs/rustfs/blob/main/rustfs/src/admin/router.rs";
const CLAIM_REASON: &str =
"Reserved console paths on a listener without the native console verify SigV4 before returning 501 NotImplemented.";
const NAME: &str = "rustfs:ReservedConsole";
const CLAIMED_ROUTE_BODY_BYTES: u64 = 1024 * 1024;
static SPEC: OperationSpec = OperationSpec::builder(NAME, 200, None)
.handler_deadline_class(HandlerDeadlineClass::Standard)
.required_params(&[])
.auth(AuthRequirement::new(NAME, ResourceShape::Service))
.build();
/// Header-signed or presigned SigV4 only: anonymous and SigV2 requests are refused at the floor
/// with `403 AccessDenied`, matching legacy RustFS `S3Router::admit` on a console-disabled port.
static FLOOR: OperationFloor = OperationFloor::builtin_presigned(NAME, SigService::S3).require_sigv4_under_every_policy();
#[derive(Debug)]
struct ReservedConsole;
impl Operation for ReservedConsole {
const NAME: &'static str = NAME;
type Input = Bytes;
type Output = WireResponse;
type DerivedResources = NoDerived;
fn derive_resources(_input: &Self::Input) -> Result<NoDerived, DerivedResourceError> {
Ok(NoDerived)
}
fn seal_derived_input(_input: &mut Self::Input) {}
fn spec() -> &'static OperationSpec {
&SPEC
}
fn floor() -> &'static OperationFloor {
&FLOOR
}
}
impl OperationCodec for ReservedConsole {
const REQUEST_BODY: RequestBodyMode = RequestBodyMode::Full;
fn decode(_request: &MetaView<'_>, body: RequestBody) -> Result<Bytes, CodecError> {
admin::buffered(body)
}
fn encode(output: WireResponse, _request: &MetaView<'_>, status: u16) -> Result<EncodedResponse, CodecError> {
admin::encode(output, status)
}
}
struct ReservedConsoleTable {
dialect: Dialect,
}
fn build_dialect(prefix: &'static str) -> Result<Dialect, GatewayAssemblyError> {
let slash: &'static str = Box::leak(format!("{prefix}/").into_boxed_str());
let remainder: &'static str = Box::leak(format!("{prefix}/{{*remainder}}").into_boxed_str());
let claims: &'static [PathClaim] = Box::leak(Box::new([
PathClaim {
prefix,
reason: CLAIM_REASON,
evidence: &[ROUTER],
},
PathClaim {
prefix: FAVICON_PATH,
reason: CLAIM_REASON,
evidence: &[ROUTER],
},
PathClaim {
prefix: APPLE_TOUCH_ICON_PATH,
reason: CLAIM_REASON,
evidence: &[ROUTER],
},
PathClaim {
prefix: APPLE_TOUCH_ICON_PRECOMPOSED_PATH,
reason: CLAIM_REASON,
evidence: &[ROUTER],
},
]));
let rows: &'static [ClaimedRow] = Box::leak(Box::new([
ClaimedRow {
template: prefix,
selector: &[],
},
ClaimedRow {
template: slash,
selector: &[],
},
ClaimedRow {
template: remainder,
selector: &[],
},
ClaimedRow {
template: FAVICON_PATH,
selector: &[],
},
ClaimedRow {
template: APPLE_TOUCH_ICON_PATH,
selector: &[],
},
ClaimedRow {
template: APPLE_TOUCH_ICON_PRECOMPOSED_PATH,
selector: &[],
},
]));
let route = ClaimedRoute {
precedence: 65535,
rows,
shadows: &[],
bucket_param: None,
};
let selector: &'static str = Box::leak(render_claimed_route(&route).into_boxed_str());
let action: &'static str = Box::leak(SPEC.auth.map(|auth| auth.render()).unwrap_or_default().into_boxed_str());
let operations: &'static [OverlayRow] = Box::leak(Box::new([OverlayRow {
name: NAME,
precedence: route.precedence,
selector,
action,
resource: ResourceShape::Service,
success_status: 200,
anonymous: false,
evidence: &[ROUTER],
}]));
let record: &'static DialectOverlay = Box::leak(Box::new(DialectOverlay {
name: "rustfs-reserved-console",
vendor: OVERLAY.vendor,
claims,
operations,
}));
Dialect::assemble_for_service(record, SigService::S3)
.declare_claimed::<ReservedConsole>(route)
.build()
.map_err(GatewayAssemblyError::AdminDialect)
}
fn production_dialect() -> Result<&'static Dialect, GatewayAssemblyError> {
static TABLE: OnceLock<Result<ReservedConsoleTable, GatewayAssemblyError>> = OnceLock::new();
match TABLE.get_or_init(|| build_dialect(console_prefix()).map(|dialect| ReservedConsoleTable { dialect })) {
Ok(table) => Ok(&table.dialect),
Err(err) => Err(GatewayAssemblyError::AdminDialect(match err {
GatewayAssemblyError::AdminDialect(errors) => errors.clone(),
_ => Vec::new(),
})),
}
}
#[cfg(test)]
fn test_dialect_for_prefix(prefix: &'static str) -> Result<Dialect, GatewayAssemblyError> {
use std::collections::HashMap;
use std::sync::Mutex;
static CACHE: OnceLock<Mutex<HashMap<&'static str, Dialect>>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let mut guard = cache.lock().expect("reserved console dialect cache lock");
if let Some(dialect) = guard.get(prefix) {
return Ok(dialect.clone());
}
let dialect = build_dialect(prefix)?;
guard.insert(prefix, dialect.clone());
Ok(dialect)
}
struct Admission {
server_ctx: Option<Arc<ServerContextSlot>>,
}
impl Admission {
fn route(&self, context: &AuthzContext<'_>, request: &AuthzRequest<'_>) -> Result<Decision, HandlerError> {
let head = context
.server_extensions()
.get::<ClaimedHead>()
.ok_or_else(|| handler_error(s3_error!(InternalError, "the claimed request head was not attached")))?;
let signed = request.identity.is_some() && !head.repeated_authorization;
admit_reserved_console(self.server_ctx.as_deref(), &head.method, &head.uri, &head.headers, signed)
.map_err(handler_error)?;
if head.repeated_authorization {
return Ok(Decision::Deny);
}
Ok(Decision::Allow)
}
}
impl Authorizer for Admission {
fn authorize_route<'a>(&'a self, context: &'a AuthzContext<'a>, request: &'a AuthzRequest<'a>) -> BoxFuture<'a, Decision> {
let decision = self.route(context, request).unwrap_or(Decision::Deny);
Box::pin(async move { decision })
}
fn authorize_route_result<'a>(
&'a self,
context: &'a AuthzContext<'a>,
request: &'a AuthzRequest<'a>,
) -> BoxFuture<'a, Result<Decision, HandlerError>> {
let result = self.route(context, request);
Box::pin(async move { result })
}
fn authorize_input<'a>(
&'a self,
_context: &'a AuthzContext<'a>,
request: &'a InputAuthzRequest<'a>,
) -> BoxFuture<'a, InputDecisions> {
let stage = if request.route().identity.is_some() {
Decision::Allow
} else {
Decision::Deny
};
let decisions = request.decide_all(stage, |_| stage);
Box::pin(async move { decisions })
}
}
struct NotImplementedHost;
impl Handler<ReservedConsole> for NotImplementedHost {
async fn call(&self, _request: Req<ReservedConsole>) -> HandlerResult<ReservedConsole> {
Err(handler_error(s3_error!(NotImplemented)))
}
}
pub(super) fn assemble(
assembly: GatewayAssembly,
iam: Arc<dyn IamKeyLookup>,
root: Arc<dyn RootSource>,
) -> Result<GatewayStack, GatewayAssemblyError> {
let server_ctx = Some(Arc::clone(&assembly.server_ctx));
let dialect = production_dialect()?;
assemble_with_dialect(assembly, iam, root, dialect, server_ctx)
}
#[cfg(test)]
pub(super) fn assemble_for_prefix(
assembly: GatewayAssembly,
iam: Arc<dyn IamKeyLookup>,
root: Arc<dyn RootSource>,
prefix: &'static str,
server_ctx: Option<Arc<ServerContextSlot>>,
) -> Result<GatewayStack, GatewayAssemblyError> {
let dialect = test_dialect_for_prefix(prefix)?;
assemble_with_dialect(assembly, iam, root, &dialect, server_ctx)
}
fn assemble_with_dialect(
mut assembly: GatewayAssembly,
iam: Arc<dyn IamKeyLookup>,
root: Arc<dyn RootSource>,
dialect: &Dialect,
server_ctx: Option<Arc<ServerContextSlot>>,
) -> Result<GatewayStack, GatewayAssemblyError> {
// Claimed console routes reject Keystone header tokens in `S3StackService` before reaching
// this host, and independent SigV4-only services do not accept header-token authentication.
assembly.keystone_auth = None;
let gate = Admission { server_ctx };
let (builder, _settings) = GatewayStack::configured_builder_on(
ServiceBuilder::for_service(SigService::S3),
&assembly,
iam,
root,
gate,
std::convert::identity,
)?
.config(super::service_config(assembly.body_read_timeout, CLAIMED_ROUTE_BODY_BYTES));
let service = builder
.dialect(dialect)
.register::<ReservedConsole, _>(Arc::new(NotImplementedHost))
.build()
.map_err(GatewayAssemblyError::Service)?;
Ok(GatewayStack {
service,
keystone_auth: None,
control_plane: true,
object_lambda_fallback: None,
})
}
+1
View File
@@ -19,6 +19,7 @@ mod admin;
mod control_plane;
mod keystone;
mod legacy_layers;
mod reserved_console;
mod ssec;
use super::*;
@@ -0,0 +1,197 @@
// 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.
//! Reserved console paths on a console-disabled listener (for example, the S3 listener while a
//! dedicated console port serves static assets): anonymous requests get `403 AccessDenied`, valid
//! SigV4 requests get `501 NotImplemented`, and custom single-segment prefixes like `/ui` and
//! `/UI_assets` verify over their original URI without tripping S3 bucket-name parsing
//! (rustfs/backlog#2771).
use super::*;
use crate::server::{APPLE_TOUCH_ICON_PATH, APPLE_TOUCH_ICON_PRECOMPOSED_PATH, FAVICON_PATH};
fn host_for(prefix: &'static str) -> GatewayStack {
super::super::reserved_console::assemble_for_prefix(
assembly(),
Arc::new(ScriptedIam { ready: true }),
root().source(),
prefix,
None,
)
.expect("reserved console host assembles")
}
fn not_ready_host_for(prefix: &'static str) -> GatewayStack {
let assembly = assembly();
let server_ctx = Some(Arc::clone(&assembly.server_ctx));
super::super::reserved_console::assemble_for_prefix(
assembly,
Arc::new(ScriptedIam { ready: true }),
root().source(),
prefix,
server_ctx,
)
.expect("reserved console host assembles")
}
#[tokio::test]
async fn default_and_single_segment_console_prefixes_return_403_anonymous_and_501_signed() {
for (prefix, targets) in [
(
"/rustfs/console",
[
("/rustfs/console", ""),
("/rustfs/console/", ""),
("/rustfs/console/index.html", ""),
("/rustfs/console/index.html", "v=1"),
(FAVICON_PATH, ""),
(APPLE_TOUCH_ICON_PATH, ""),
(APPLE_TOUCH_ICON_PRECOMPOSED_PATH, ""),
]
.as_slice(),
),
(
"/ui",
[("/ui", ""), ("/ui/", ""), ("/ui/index.html", ""), ("/ui/index.html", "v=1")].as_slice(),
),
(
"/UI_assets",
[
("/UI_assets", ""),
("/UI_assets/", ""),
("/UI_assets/index.html", ""),
("/UI_assets/index.html", "v=1"),
]
.as_slice(),
),
] {
let host = host_for(prefix);
for &(path, query) in targets {
let uri = if query.is_empty() {
path.to_owned()
} else {
format!("{path}?{query}")
};
// Anonymous request -> 403 AccessDenied (never 501 or 400 InvalidBucketName).
let anon_req = request(Method::GET, &uri).body(Empty::new()).expect("anon request");
let (status, _, body) = answer_request(&host, anon_req).await;
assert_eq!(status, StatusCode::FORBIDDEN, "anonymous {prefix} -> {uri}: {body}");
assert!(
body.contains("<Code>AccessDenied</Code>"),
"anonymous {prefix} -> {uri} expected AccessDenied XML, got: {body}"
);
// Valid SigV4 header-signed request over original URI -> 501 NotImplemented.
let signed_req = signed_request(Signed::Header, Method::GET, path, query, ROOT_ACCESS_KEY, ROOT_SECRET_KEY);
let (status, _, body) = answer_request(&host, signed_req).await;
assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "header-signed {prefix} -> {uri}: {body}");
assert!(
body.contains("<Code>NotImplemented</Code>"),
"header-signed {prefix} -> {uri} expected NotImplemented XML, got: {body}"
);
// Valid SigV4 presigned request over original URI -> 501 NotImplemented.
let presigned_req = signed_request(Signed::Query, Method::GET, path, query, ROOT_ACCESS_KEY, ROOT_SECRET_KEY);
let (status, _, body) = answer_request(&host, presigned_req).await;
assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "presigned {prefix} -> {uri}: {body}");
assert!(
body.contains("<Code>NotImplemented</Code>"),
"presigned {prefix} -> {uri} expected NotImplemented XML, got: {body}"
);
}
}
}
#[tokio::test]
async fn reserved_console_verifies_original_uri_and_enforces_sigv4_and_readiness() {
let host = host_for("/UI_assets");
// Wrong secret -> 403 SignatureDoesNotMatch (signature verified over original `/UI_assets/index.html?v=1`).
let bad_sig = signed_request(
Signed::Header,
Method::GET,
"/UI_assets/index.html",
"v=1",
ROOT_ACCESS_KEY,
"wrong-secret",
);
let (status, _, body) = answer_request(&host, bad_sig).await;
assert_eq!(status, StatusCode::FORBIDDEN, "bad sig: {body}");
assert!(
body.contains("<Code>SignatureDoesNotMatch</Code>"),
"bad sig expected SignatureDoesNotMatch, got: {body}"
);
// Tampered query after signing -> 403 SignatureDoesNotMatch.
let mut tampered = signed_request(
Signed::Header,
Method::GET,
"/UI_assets/index.html",
"v=1",
ROOT_ACCESS_KEY,
ROOT_SECRET_KEY,
);
*tampered.uri_mut() = "/UI_assets/index.html?v=2".parse().expect("tampered uri");
let (status, _, body) = answer_request(&host, tampered).await;
assert_eq!(status, StatusCode::FORBIDDEN, "tampered query: {body}");
assert!(
body.contains("<Code>SignatureDoesNotMatch</Code>"),
"tampered query expected SignatureDoesNotMatch, got: {body}"
);
// SigV2 Authorization -> refused at the SigV4-only floor with 403 AccessDenied.
let sigv2 = request(Method::GET, "/UI_assets/index.html")
.header(http::header::DATE, chrono::Utc::now().format("%a, %d %b %Y %H:%M:%S GMT").to_string())
.header(http::header::AUTHORIZATION, format!("AWS {ROOT_ACCESS_KEY}:invalid"))
.body(Empty::new())
.expect("sigv2 request");
let (status, _, body) = answer_request(&host, sigv2).await;
assert_eq!(status, StatusCode::FORBIDDEN, "sigv2: {body}");
assert!(body.contains("<Code>AccessDenied</Code>"), "sigv2 expected AccessDenied, got: {body}");
// Repeated Authorization headers -> 403 AccessDenied.
let mut repeated = signed_request(Signed::Header, Method::GET, "/UI_assets/index.html", "", ROOT_ACCESS_KEY, ROOT_SECRET_KEY);
let first = repeated
.headers()
.get(http::header::AUTHORIZATION)
.expect("authorization")
.clone();
repeated.headers_mut().append(http::header::AUTHORIZATION, first);
let (status, _, body) = answer_request(&host, repeated).await;
assert_eq!(status, StatusCode::FORBIDDEN, "repeated auth: {body}");
assert!(
body.contains("<Code>AccessDenied</Code>"),
"repeated auth expected AccessDenied, got: {body}"
);
// Unsigned x-amz-* header on a SigV4 request -> 403 AccessDenied (GHSA-g8w9).
let mut unsigned_amz =
signed_request(Signed::Header, Method::GET, "/UI_assets/index.html", "", ROOT_ACCESS_KEY, ROOT_SECRET_KEY);
unsigned_amz
.headers_mut()
.insert("x-amz-meta-unsigned", http::HeaderValue::from_static("injected"));
let (status, _, body) = answer_request(&host, unsigned_amz).await;
assert_eq!(status, StatusCode::FORBIDDEN, "unsigned x-amz header: {body}");
assert!(
body.contains("<Code>AccessDenied</Code>"),
"unsigned x-amz header expected AccessDenied, got: {body}"
);
// Signed request while server context is not installed -> 503 ServiceUnavailable.
let not_ready = not_ready_host_for("/ui");
let signed_req = signed_request(Signed::Header, Method::GET, "/ui/index.html", "v=1", ROOT_ACCESS_KEY, ROOT_SECRET_KEY);
let (status, _, body) = answer_request(&not_ready, signed_req).await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "not ready: {body}");
}
+57 -1
View File
@@ -1689,20 +1689,26 @@ fn assemble_s3_stack(
let router = admin::make_admin_router(config.console_enable, Arc::clone(&assembly.server_ctx))?;
let control_plane =
GatewayEdgeService(GatewayStack::assemble_control_plane(assembly.clone(), Arc::new(router)).map_err(Error::other)?);
let reserved_console = (!config.console_enable)
.then(|| GatewayStack::assemble_reserved_console(assembly.clone()).map(GatewayEdgeService))
.transpose()
.map_err(Error::other)?;
#[cfg(feature = "corpus-record")]
let recorder = corpus::recorder(config, &assembly.server_domains)?;
let s3 = GatewayEdgeService(GatewayStack::assemble(assembly).map_err(Error::other)?);
#[cfg(feature = "corpus-record")]
let (s3, native_admin, control_plane) = {
let (s3, native_admin, control_plane, reserved_console) = {
use tower::{Layer, util::Either};
(
Either::Left(recorder.layer(s3)),
Either::Right(native_admin),
Either::Right(control_plane),
reserved_console.map(Either::Right),
)
};
Ok(S3StackService::new(s3)
.with_native_console(NativeConsoleEdgeService::for_config(config))
.with_reserved_console(reserved_console)
.with_native_website(NativeWebsiteEdgeService::claiming(website))
.with_native_admin(Some(native_admin))
.with_control_plane(Some(control_plane)))
@@ -6328,6 +6334,56 @@ mod tests {
assert_eq!(console, 0);
assert_eq!(control_plane + gateway, cases.len() * 2);
}
#[tokio::test]
async fn production_s3_stack_reserved_console_contract() {
use http_body_util::BodyExt;
let prefix = crate::server::console_prefix();
let make_assembly = || GatewayAssembly {
server_ctx: ServerContextSlot::new(),
root_access_key: "rustfsadmin".to_owned(),
root_secret_key: "rustfsadmin-secret".to_owned(),
region: Some("us-east-1".to_owned()),
server_domains: Vec::new(),
body_read_timeout: Duration::from_secs(30),
keystone_auth: None,
};
let mut s3_port_config = config::Config::new("127.0.0.1:9000", Vec::new());
s3_port_config.console_enable = false;
let s3_port = assemble_s3_stack(&s3_port_config, None, make_assembly()).expect("s3 port stack assembles");
for target in [
format!("{prefix}/"),
format!("{prefix}/index.html?v=1"),
"/favicon.ico".to_owned(),
] {
let response = s3_port
.clone()
.oneshot(console_request(Method::GET, &target, false))
.await
.expect("s3 port response");
assert_eq!(response.status(), StatusCode::FORBIDDEN, "anonymous S3 port {target}");
let body = response.into_body().collect().await.unwrap().to_bytes();
let body = String::from_utf8_lossy(&body);
assert!(
body.contains("<Code>AccessDenied</Code>"),
"anonymous S3 port {target} expected AccessDenied XML, got: {body}"
);
}
let mut console_port_config = config::Config::new("127.0.0.1:9001", Vec::new());
console_port_config.console_enable = true;
let console_port =
assemble_s3_stack(&console_port_config, None, make_assembly()).expect("console port stack assembles");
let target = format!("{prefix}/index.html");
let response = console_port
.oneshot(console_request(Method::GET, &target, false))
.await
.expect("console port response");
static_response_body(response, &Method::GET, &target).await;
}
}
type RateLimitTestCore = tower::util::BoxCloneService<
+71 -7
View File
@@ -78,6 +78,7 @@ struct GatewayServices<G, C, W> {
s3: G,
native_website: Option<(HostClaim, W)>,
native_console: Option<C>,
reserved_console: Option<G>,
native_admin: Option<G>,
control_plane: Option<G>,
}
@@ -90,6 +91,7 @@ impl<G> S3StackService<G> {
s3,
native_website: None,
native_console: None,
reserved_console: None,
native_admin: None,
control_plane: None,
},
@@ -106,12 +108,20 @@ impl<G, C, W> S3StackService<G, C, W> {
s3: services.s3,
native_website: services.native_website,
native_console,
reserved_console: services.reserved_console,
native_admin: services.native_admin,
control_plane: services.control_plane,
},
}
}
/// Attaches the reserved-console SigV4 host used when the native console is disabled on this
/// listener (e.g. the S3 port while a dedicated console listener serves assets).
pub(crate) fn with_reserved_console(mut self, reserved_console: Option<G>) -> Self {
self.services.reserved_console = reserved_console;
self
}
/// Attaches the website service: every request `claim` selects goes to it before any other
/// routing.
pub(crate) fn with_native_website<N>(self, native_website: Option<(HostClaim, N)>) -> S3StackService<G, C, N> {
@@ -121,6 +131,7 @@ impl<G, C, W> S3StackService<G, C, W> {
s3: services.s3,
native_website,
native_console: services.native_console,
reserved_console: services.reserved_console,
native_admin: services.native_admin,
control_plane: services.control_plane,
},
@@ -171,10 +182,13 @@ impl<G, C, W> GatewayServices<G, C, W> {
if claimed && (request.headers().contains_key("x-auth-token") || request.headers().contains_key("x-storage-token")) {
return bare(http::StatusCode::FORBIDDEN);
}
if let Some(console) = &mut self.native_console
&& claims_native_console_route(request.method(), request.uri())
{
return Box::pin(console.call(request));
if claims_native_console_route(request.method(), request.uri()) {
if let Some(console) = &mut self.native_console {
return Box::pin(console.call(request));
}
if let Some(reserved_console) = &mut self.reserved_console {
return Box::pin(reserved_console.call(request));
}
}
if let Some(admin) = &mut self.native_admin
&& claims_native_admin_read(request.method(), request.uri())
@@ -213,9 +227,13 @@ where
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let services = &mut self.services;
ready!(services.s3.poll_ready(cx))?;
for host in [&mut services.native_admin, &mut services.control_plane]
.into_iter()
.flatten()
for host in [
&mut services.reserved_console,
&mut services.native_admin,
&mut services.control_plane,
]
.into_iter()
.flatten()
{
ready!(host.poll_ready(cx))?;
}
@@ -706,4 +724,50 @@ mod tests {
assert_eq!(answered_by(&mut service, request(method, target)).await, expected, "{target}");
}
}
#[tokio::test]
async fn reserved_console_handles_disabled_console_routes_while_preserving_extensions_and_native_console() {
let prefix = crate::server::console_prefix();
let console_root = prefix.to_owned();
let console_slash = format!("{prefix}/");
let console_index = format!("{prefix}/index.html?v=1");
let console_lambda = format!("{prefix}/index.html?lambdaArn=arn");
let neighbor = format!("{prefix}x/index.html");
let mut disabled_stack = S3StackService::new(Named("gateway"))
.with_reserved_console(Some(Named("reserved-console")))
.with_control_plane(Some(Named("control-plane")));
for (method, target, expected) in [
(Method::GET, console_root.as_str(), "reserved-console"),
(Method::GET, console_slash.as_str(), "reserved-console"),
(Method::GET, console_index.as_str(), "reserved-console"),
(Method::GET, "/favicon.ico", "reserved-console"),
(Method::GET, "/apple-touch-icon.png", "reserved-console"),
(Method::GET, "/apple-touch-icon-precomposed.png", "reserved-console"),
(Method::GET, console_lambda.as_str(), "control-plane"),
(Method::GET, "/favicon.ico?replication-metrics", "control-plane"),
(Method::GET, neighbor.as_str(), "gateway"),
(Method::GET, "/bucket/key", "gateway"),
] {
assert_eq!(
answered_by(&mut disabled_stack, request(method, target)).await,
expected,
"console-disabled S3 port: {target}"
);
}
// Dedicated console listener with native_console mounted keeps precedence over reserved_console.
let mut enabled_stack = S3StackService::new(Named("gateway"))
.with_native_console(Some(Named("native-console")))
.with_reserved_console(Some(Named("reserved-console")))
.with_control_plane(Some(Named("control-plane")));
assert_eq!(
answered_by(&mut enabled_stack, request(Method::GET, console_index.as_str())).await,
"native-console"
);
assert_eq!(
answered_by(&mut enabled_stack, request(Method::GET, console_lambda.as_str())).await,
"control-plane"
);
}
}