fix(security): harden RPC, proxies, egress DNS, and OIDC (#9682)

* fix(security): harden RPC, proxies, egress DNS, and OIDC

Harden internode RPC authentication/quotas, trusted-proxy allowlisting,
protocol IAM policy conditions, outbound DNS egress pinning, and OIDC
redirect and HTTPS enforcement:

- Trusted proxies: replace broad private/link-local peer trust in simple
  mode with the configured trusted-proxy allowlist (defaulting to
  loopback-only) and update proxy integration coverage.
- Protocol gateways & FTPS: populate standard IAM condition keys
  (SourceIp, SecureTransport, CurrentTime, EpochTime, UserAgent,
  Referer, principal metadata) in gateway authorization and replace the
  unchecked FTPS fallback IP parse with explicit connection context.
- Bucket listing RPC: fail closed with entry index diagnostics instead
  of silently dropping malformed BucketInfo entries on encode/decode.
- Internode RPC streams & replay cache: add framed HMAC-SHA256 response
  authentication with sequence/digest/EOF verification and
  post-verification endpoint pinning for read_file_stream and walk_dir,
  plus canonicalized per-peer entry and memory-budget replay cache
  isolation.
- Outbound DNS egress: unify storage/tier, remote S3 replication
  targets, on-demand migration HTTP, Azure Blob, GCS, Keystone, and OIDC
  outbound checks onto OutboundPolicy and connection-time
  OutboundDnsResolver (with redirect blocking on Keystone) to stop DNS
  rebinding to loopback/link-local/metadata targets.
- OIDC redirects & transport security: trust forwarded scheme/host only
  from verified trusted proxies, never reflect untrusted request headers
  into STS credential or logout redirects, and reject plaintext http://
  OIDC URLs for non-loopback hosts unless explicitly opted in via
  RUSTFS_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT.

Refs: rustfs/backlog#1470, rustfs/backlog#1473, rustfs/backlog#1472, rustfs/backlog#1506

* fix(egress): restrict GCS endpoints and restore tier compatibility

* ci: tighten the GCS error-format baseline

* fix(ci): stop sending deprecated policy field in s3-tests add-user

rustfs/rustfs#9677 hardened /rustfs/admin/v3/add-user to fail closed when a non-empty deprecated policy field is provided. scripts/s3-tests/run.sh was still passing policy=readwrite in the add-user body even though it immediately calls set-user-or-group-policy right after, and awscurl returned exit 0 on XML <Error> responses so provisioning silently failed and broke all alt-user s3-tests.

Remove the deprecated policy field from the add-user payload, check awscurl responses for XML <Error> elements in provisioning, and add a regression unit test in scripts/s3-tests/test_runner_tools.py.

Refs: rustfs/backlog#1246

* fix(ci): fail S3 user provisioning on HTTP errors without logging responses

* fix(iceberg): reject repeated warehouses before validating bucket names

* test(ecstore): wait for relaxed writes on the foreground lane

* test(quota): isolate concurrent real-disk probes in CI

* test(ecstore): scope upload lock identity helper to its Linux test

* fix(oidc): preserve HTTPS in dynamic callbacks

* ci: allow cold builds to finish all fuzz binaries
This commit is contained in:
Chris An
2026-11-29 10:23:40 +08:00
committed by GitHub
parent 21fc821938
commit 5a0bdfcf1c
68 changed files with 4250 additions and 565 deletions
+12
View File
@@ -187,6 +187,18 @@ pub const DEFAULT_INTERNODE_RPC_REPLAY_SCOPE_STRICT: bool = false;
// observed fallback counter an explicit strictness decision.
const _: () = assert!(!DEFAULT_INTERNODE_RPC_REPLAY_SCOPE_STRICT);
/// Require authenticated response framing (`framed-v1`) on internode HTTP read and walk-dir
/// streams, rejecting unauthenticated legacy streams during plaintext transport.
///
/// Defaults to `false` so mixed-version clusters survive rolling upgrades; once a peer responds
/// with authenticated framing it is pinned for this process, and enabling this flag enforces
/// authenticated framing unconditionally on both client and server.
pub const ENV_INTERNODE_RPC_STREAM_AUTH_STRICT: &str = "RUSTFS_INTERNODE_RPC_STREAM_AUTH_STRICT";
pub const DEFAULT_INTERNODE_RPC_STREAM_AUTH_STRICT: bool = false;
// Compile-time invariant: mixed-version clusters must remain available during rolling upgrades.
const _: () = assert!(!DEFAULT_INTERNODE_RPC_STREAM_AUTH_STRICT);
/// Capacity (distinct nonces) of the process-local internode RPC replay cache that enforces
/// one-time consumption of authenticated RPC signatures.
///
+3
View File
@@ -50,6 +50,9 @@ pub const ENV_IDENTITY_OPENID_ROLES_CLAIM: &str = "RUSTFS_IDENTITY_OPENID_ROLES_
pub const ENV_IDENTITY_OPENID_EMAIL_CLAIM: &str = "RUSTFS_IDENTITY_OPENID_EMAIL_CLAIM";
pub const ENV_IDENTITY_OPENID_USERNAME_CLAIM: &str = "RUSTFS_IDENTITY_OPENID_USERNAME_CLAIM";
pub const ENV_IDENTITY_OPENID_HIDE_FROM_UI: &str = "RUSTFS_IDENTITY_OPENID_HIDE_FROM_UI";
/// Explicit opt-in allowing plaintext `http://` OIDC provider URLs for non-loopback hosts.
/// Defaults to off; loopback hosts remain subject to the shared outbound egress policy.
pub const ENV_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT: &str = "RUSTFS_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT";
/// List of all environment variable keys for an OIDC provider.
pub const ENV_IDENTITY_OPENID_KEYS: &[&str; 18] = &[
+23 -19
View File
@@ -291,8 +291,9 @@ pub mod bucket {
pub mod remote_s3_client {
pub use crate::bucket::remote_s3_client::{
PathStyle, RemoteCredentials, RemoteS3ClientError, RemoteS3EndpointSpec, RemoteS3RetryPolicy, build_remote_s3_client,
build_remote_s3_config, validate_remote_endpoint, validate_target_ca_pem,
PathStyle, RemoteCredentials, RemoteS3ClientError, RemoteS3EndpointSpec, RemoteS3RetryPolicy,
build_remote_endpoint_dns_resolver, build_remote_s3_client, build_remote_s3_config, validate_remote_endpoint,
validate_target_ca_pem,
};
}
@@ -711,23 +712,26 @@ pub mod rpc {
PEER_RESTSIGNAL, PEER_RESTSUB_SYS, PeerRestClient, PeerS3Client, RpcReplayCacheAdmissionError, S3PeerSys,
SERVICE_SIGNAL_REFRESH_CONFIG, SERVICE_SIGNAL_RELOAD_DYNAMIC, ScannerBucketListing, ScannerDirtyUsageAcknowledgement,
ScannerPeerActivity, ScannerPeerDirtyUsageBucket, ScannerPeerDirtyUsageSnapshot, ScannerPublicationLease,
ScannerScopedDirtyUsageAckEntry, TONIC_RPC_PREFIX, TonicInterceptor, build_put_file_auth_trailer,
check_and_record_signed_rpc_nonce, decode_heal_bucket_rpc_options, encode_heal_bucket_rpc_options, gen_signature_headers,
gen_tonic_replay_scope_headers, gen_tonic_signature_headers, gen_tonic_signature_interceptor,
node_service_time_out_client, node_service_time_out_client_no_auth, normalize_tonic_rpc_audience,
rpc_auth_is_resource_exhausted, rpc_background_admission, set_tonic_canonical_body_digest, sign_ns_scanner_capability,
sign_ns_scanner_capability_with_checkpoint_coverage, sign_ns_scanner_capability_with_durable_progress,
sign_ns_scanner_capability_with_tier_registry_generation, sign_ns_scanner_capability_with_usage_capabilities,
sign_ns_scanner_tier_registry_preflight_capability, sign_ns_scanner_usage_watch_capability, sign_put_file_capability,
sign_tonic_rpc_response_proof, tonic_boot_epoch_challenge, tonic_boot_epoch_response_headers,
tonic_boot_epoch_response_headers_with_msgpack_capability, tonic_msgpack_manifest_capability_requested,
tonic_rpc_auth_failure_reason, verify_ns_scanner_capability, verify_ns_scanner_capability_with_checkpoint_coverage,
verify_ns_scanner_capability_with_durable_progress, verify_ns_scanner_capability_with_tier_registry_generation,
verify_ns_scanner_capability_with_usage_capabilities, verify_ns_scanner_tier_registry_preflight_capability,
verify_ns_scanner_usage_watch_capability, verify_put_file_auth_trailer, verify_put_file_capability, verify_rpc_signature,
verify_tonic_boot_epoch_response, verify_tonic_canonical_body_digest, verify_tonic_mutation_body_digest,
verify_tonic_mutation_body_digest_reject_unsigned, verify_tonic_rpc_response_proof, verify_tonic_rpc_signature,
verify_tonic_rpc_signature_with_bootstrap,
ScannerScopedDirtyUsageAckEntry, StreamResponseAuthDomain, TONIC_RPC_PREFIX, TonicInterceptor,
build_put_file_auth_trailer, check_and_record_signed_rpc_nonce, check_and_record_signed_rpc_nonce_for_peer,
decode_heal_bucket_rpc_options, encode_heal_bucket_rpc_options, encode_stream_auth_data_frame,
encode_stream_auth_eof_frame, gen_signature_headers, gen_tonic_replay_scope_headers, gen_tonic_signature_headers,
gen_tonic_signature_interceptor, node_service_time_out_client, node_service_time_out_client_no_auth,
normalize_tonic_rpc_audience, rpc_auth_is_resource_exhausted, rpc_background_admission, set_tonic_canonical_body_digest,
sign_ns_scanner_capability, sign_ns_scanner_capability_with_checkpoint_coverage,
sign_ns_scanner_capability_with_durable_progress, sign_ns_scanner_capability_with_tier_registry_generation,
sign_ns_scanner_capability_with_usage_capabilities, sign_ns_scanner_tier_registry_preflight_capability,
sign_ns_scanner_usage_watch_capability, sign_put_file_capability, sign_tonic_rpc_response_proof,
tonic_boot_epoch_challenge, tonic_boot_epoch_response_headers, tonic_boot_epoch_response_headers_with_msgpack_capability,
tonic_msgpack_manifest_capability_requested, tonic_rpc_auth_failure_reason, verify_ns_scanner_capability,
verify_ns_scanner_capability_with_checkpoint_coverage, verify_ns_scanner_capability_with_durable_progress,
verify_ns_scanner_capability_with_tier_registry_generation, verify_ns_scanner_capability_with_usage_capabilities,
verify_ns_scanner_tier_registry_preflight_capability, verify_ns_scanner_usage_watch_capability,
verify_put_file_auth_trailer, verify_put_file_capability, verify_rpc_signature, verify_stream_auth_data_frame,
verify_stream_auth_eof_frame, verify_tonic_boot_epoch_response, verify_tonic_canonical_body_digest,
verify_tonic_mutation_body_digest, verify_tonic_mutation_body_digest_reject_unsigned, verify_tonic_rpc_response_proof,
verify_tonic_rpc_signature, verify_tonic_rpc_signature_with_bootstrap,
verify_tonic_rpc_signature_with_bootstrap_and_peer,
};
}
+343 -25
View File
@@ -36,6 +36,7 @@ use aws_sdk_s3::config::retry::RetryConfig;
use aws_sdk_s3::{Client as S3Client, Config as S3Config};
use aws_smithy_http_client::{Builder as SmithyHttpClientBuilder, tls as smithy_tls};
use aws_smithy_runtime_api::box_error::BoxError;
use aws_smithy_runtime_api::client::dns::{DnsFuture, ResolveDns, ResolveDnsError};
use aws_smithy_runtime_api::client::http::{
HttpConnector as SmithyHttpConnector, HttpConnectorFuture, SharedHttpConnector, http_client_fn,
};
@@ -51,13 +52,19 @@ use aws_smithy_types::config_bag::ConfigBag;
use aws_smithy_types::timeout::TimeoutConfig;
use http::Uri;
use hyper_util::client::legacy::Client as HyperClient;
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::client::legacy::connect::dns::Name as HyperDnsName;
use hyper_util::rt::{TokioExecutor, TokioTimer};
use rustfs_config::{DEFAULT_TRUST_LEAF_CERT_AS_CA, ENV_TRUST_LEAF_CERT_AS_CA, RUSTFS_CA_CERT, RUSTFS_TLS_CERT};
use rustfs_utils::egress::{OutboundUrlError, validate_outbound_url};
use rustfs_utils::egress::{OutboundDnsResolver, OutboundPolicy, OutboundPolicyError, OutboundUrlError, validate_outbound_url};
use rustls_pki_types::pem::PemObject;
use std::fmt;
use std::future::Future;
use std::net::SocketAddr;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, SystemTime};
use tower::Service;
use tracing::warn;
@@ -426,6 +433,29 @@ pub async fn build_remote_s3_config(spec: &RemoteS3EndpointSpec) -> Result<aws_s
let endpoint = spec.endpoint_url();
let parsed_endpoint = Url::parse(&endpoint).map_err(|err| RemoteS3ClientError::InvalidEndpoint(err.to_string()))?;
validate_remote_endpoint(&parsed_endpoint).map_err(RemoteS3ClientError::EndpointNotAllowed)?;
let dns_resolver = build_remote_endpoint_dns_resolver(&parsed_endpoint)?;
build_remote_s3_config_with_creds_and_resolver(spec, creds, dns_resolver).await
}
#[cfg(test)]
async fn build_remote_s3_config_with_resolver(
spec: &RemoteS3EndpointSpec,
dns_resolver: OutboundDnsResolver,
) -> Result<aws_sdk_s3::config::Builder, RemoteS3ClientError> {
let Some(credentials) = &spec.credentials else {
return Err(RemoteS3ClientError::MissingCredentials);
};
let creds = remote_sdk_credentials(credentials, SystemTime::now()).map_err(RemoteS3ClientError::Credentials)?;
build_remote_s3_config_with_creds_and_resolver(spec, creds, dns_resolver).await
}
async fn build_remote_s3_config_with_creds_and_resolver(
spec: &RemoteS3EndpointSpec,
creds: SdkCredentials,
dns_resolver: OutboundDnsResolver,
) -> Result<aws_sdk_s3::config::Builder, RemoteS3ClientError> {
let endpoint = spec.endpoint_url();
let http_client = build_aws_s3_http_client_for_spec_with_resolver(spec, dns_resolver).await?;
let mut config_builder = S3Config::builder()
.endpoint_url(endpoint)
@@ -435,16 +465,13 @@ pub async fn build_remote_s3_config(spec: &RemoteS3EndpointSpec) -> Result<aws_s
.request_checksum_calculation(replication_request_checksum_calculation())
.interceptor(ControlResponseLimit(16 * 1024 * 1024))
.retry_classifier(OversizedResponseRetryClassifier)
.retry_config(spec.retry.retry_config());
.retry_config(spec.retry.retry_config())
.http_client(http_client);
if spec.path_style.force_path_style() {
config_builder = config_builder.force_path_style(true);
}
if let Some(http_client) = build_aws_s3_http_client_for_spec(spec).await? {
config_builder = config_builder.http_client(http_client);
}
if spec.connect_timeout.is_some() || spec.read_timeout.is_some() || spec.operation_timeout.is_some() {
let mut timeouts = TimeoutConfig::builder();
if let Some(connect_timeout) = spec.connect_timeout {
@@ -617,6 +644,61 @@ pub(crate) fn validate_remote_endpoint_inner(url: &Url, allow_loopback: bool) ->
}
}
#[derive(Clone, Debug)]
struct OutboundSmithyDnsResolver(OutboundDnsResolver);
impl ResolveDns for OutboundSmithyDnsResolver {
fn resolve_dns<'a>(&'a self, name: &'a str) -> DnsFuture<'a> {
let resolver = self.0.clone();
let host = name.to_owned();
DnsFuture::new(async move {
let addrs = resolver.resolve_host(&host).await.map_err(ResolveDnsError::new)?;
Ok(addrs.into_iter().map(|addr| addr.ip()).collect())
})
}
}
#[derive(Clone)]
struct OutboundHyperDnsResolver(OutboundDnsResolver);
impl Service<HyperDnsName> for OutboundHyperDnsResolver {
type Response = std::vec::IntoIter<SocketAddr>;
type Error = std::io::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, name: HyperDnsName) -> Self::Future {
let resolver = self.0.clone();
let host = name.as_str().to_owned();
Box::pin(async move {
let addrs = resolver.resolve_host(&host).await?;
Ok(addrs.into_iter())
})
}
}
fn outbound_policy_error_to_remote_client_error(err: OutboundPolicyError) -> RemoteS3ClientError {
match err {
OutboundPolicyError::MissingHost => RemoteS3ClientError::EndpointNotAllowed(OutboundUrlError::MissingHost),
OutboundPolicyError::ForbiddenHost { host, reason } => {
RemoteS3ClientError::EndpointNotAllowed(OutboundUrlError::ForbiddenHost { host, reason })
}
other => RemoteS3ClientError::InvalidEndpoint(other.to_string()),
}
}
/// Build a connection-time DNS egress resolver for an operator-configured remote
/// storage endpoint (replication target or on-demand migration source).
pub fn build_remote_endpoint_dns_resolver(url: &Url) -> Result<OutboundDnsResolver, RemoteS3ClientError> {
OutboundPolicy::default()
.resolver_for_storage_endpoint(url, true, loopback_replication_targets_allowed())
.map_err(outbound_policy_error_to_remote_client_error)
}
#[cfg(test)]
pub(crate) fn build_insecure_aws_s3_http_client() -> SharedHttpClient {
ensure_rustls_crypto_provider();
@@ -639,6 +721,30 @@ pub(crate) fn build_insecure_aws_s3_http_client() -> SharedHttpClient {
http_client_fn(move |_settings, _components| connector.clone())
}
fn build_insecure_aws_s3_http_client_with_resolver(dns_resolver: OutboundDnsResolver) -> SharedHttpClient {
ensure_rustls_crypto_provider();
let tls_config = rustls::ClientConfig::builder()
.dangerous()
.with_custom_certificate_verifier(Arc::new(AcceptAnyServerCertVerifier))
.with_no_client_auth();
let mut http = HttpConnector::new_with_resolver(OutboundHyperDnsResolver(dns_resolver));
http.enforce_http(false);
let https = hyper_rustls::HttpsConnectorBuilder::new()
.with_tls_config(tls_config)
.https_or_http()
.enable_http1()
.enable_http2()
.wrap_connector(http);
let mut client_builder = HyperClient::builder(TokioExecutor::new());
client_builder.pool_timer(TokioTimer::new());
let client = client_builder.build(https);
let connector = SharedHttpConnector::new(TargetHyperHttpConnector { client });
http_client_fn(move |_settings, _components| connector.clone())
}
fn validate_ca_pem_bundle(ca_cert_pem: &[u8]) -> Result<(), String> {
let certs = rustls_pki_types::CertificateDer::pem_slice_iter(ca_cert_pem)
.collect::<Result<Vec<_>, _>>()
@@ -682,6 +788,7 @@ pub(crate) fn compose_replication_trust_store(
(trust_store, custom_bundle_count)
}
#[cfg(test)]
pub(crate) fn build_aws_s3_http_client_with_trust_store(
trust_store: smithy_tls::TrustStore,
) -> Result<SharedHttpClient, RemoteS3ClientError> {
@@ -696,6 +803,21 @@ pub(crate) fn build_aws_s3_http_client_with_trust_store(
.build_https())
}
fn build_aws_s3_http_client_with_trust_store_and_resolver(
trust_store: smithy_tls::TrustStore,
dns_resolver: OutboundDnsResolver,
) -> Result<SharedHttpClient, RemoteS3ClientError> {
let tls_context = smithy_tls::TlsContext::builder()
.with_trust_store(trust_store)
.build()
.map_err(|err| RemoteS3ClientError::InvalidCaPem(err.to_string()))?;
Ok(SmithyHttpClientBuilder::new()
.tls_provider(smithy_tls::Provider::rustls(smithy_tls::rustls_provider::CryptoMode::AwsLc))
.tls_context(tls_context)
.build_with_resolver(OutboundSmithyDnsResolver(dns_resolver)))
}
pub(crate) async fn load_tls_path_ca_bundles(tls_dir: &Path, trust_leaf_cert_as_ca: bool) -> Vec<Vec<u8>> {
let mut certificate_bundles = Vec::new();
@@ -740,6 +862,7 @@ async fn load_configured_tls_ca_bundles() -> Vec<Vec<u8>> {
.await
}
#[cfg(test)]
pub(crate) async fn build_aws_s3_http_client_from_target_ca_pem(
ca_cert_pem: &str,
) -> Result<SharedHttpClient, RemoteS3ClientError> {
@@ -752,40 +875,68 @@ pub(crate) async fn build_aws_s3_http_client_from_target_ca_pem(
build_aws_s3_http_client_with_trust_store(trust_store)
}
/// Selects the HTTP client for `spec`: `None` keeps the SDK default (plain
/// HTTP, or HTTPS with platform roots when no custom trust is configured).
async fn build_aws_s3_http_client_from_target_ca_pem_with_resolver(
ca_cert_pem: &str,
dns_resolver: OutboundDnsResolver,
) -> Result<SharedHttpClient, RemoteS3ClientError> {
validate_target_ca_pem(ca_cert_pem)?;
let mut certificate_bundles = load_configured_tls_ca_bundles().await;
certificate_bundles.push(ca_cert_pem.as_bytes().to_vec());
let (trust_store, _) = compose_replication_trust_store(certificate_bundles);
build_aws_s3_http_client_with_trust_store_and_resolver(trust_store, dns_resolver)
}
#[cfg(test)]
pub(crate) async fn build_aws_s3_http_client_for_spec(
spec: &RemoteS3EndpointSpec,
) -> Result<Option<SharedHttpClient>, RemoteS3ClientError> {
let fallback_url = Url::parse("https://remote-target.invalid").expect("static URL should parse");
let dns_resolver = match Url::parse(&spec.endpoint_url())
.ok()
.and_then(|url| build_remote_endpoint_dns_resolver(&url).ok())
{
Some(resolver) => resolver,
None => OutboundPolicy::default()
.resolver_for_storage_endpoint(&fallback_url, true, loopback_replication_targets_allowed())
.map_err(outbound_policy_error_to_remote_client_error)?,
};
build_aws_s3_http_client_for_spec_with_resolver(spec, dns_resolver)
.await
.map(Some)
}
/// Builds the DNS-pinned HTTP client for `spec`, covering plain HTTP, default
/// HTTPS, `RUSTFS_TLS_PATH` / custom CA PEM, and `skip_tls_verify` uniformly.
async fn build_aws_s3_http_client_for_spec_with_resolver(
spec: &RemoteS3EndpointSpec,
dns_resolver: OutboundDnsResolver,
) -> Result<SharedHttpClient, RemoteS3ClientError> {
if !spec.secure {
return Ok(None);
return build_aws_s3_http_client_with_trust_store_and_resolver(smithy_tls::TrustStore::default(), dns_resolver);
}
if spec.skip_tls_verify {
return Ok(Some(build_insecure_aws_s3_http_client()));
return Ok(build_insecure_aws_s3_http_client_with_resolver(dns_resolver));
}
if let Some(ca_cert_pem) = spec.custom_ca_pem() {
return build_aws_s3_http_client_from_target_ca_pem(ca_cert_pem).await.map(Some);
return build_aws_s3_http_client_from_target_ca_pem_with_resolver(ca_cert_pem, dns_resolver).await;
}
Ok(build_aws_s3_http_client_from_tls_path().await)
}
async fn build_aws_s3_http_client_from_tls_path() -> Option<SharedHttpClient> {
let certificate_bundles = load_configured_tls_ca_bundles().await;
if certificate_bundles.is_empty() {
return None;
}
let (trust_store, _) = compose_replication_trust_store(certificate_bundles);
match build_aws_s3_http_client_with_trust_store(trust_store) {
Ok(client) => Some(client),
Err(e) => {
warn!("failed to build AWS SDK TLS context for replication client: {}", e);
None
if !certificate_bundles.is_empty() {
let (trust_store, _) = compose_replication_trust_store(certificate_bundles);
match build_aws_s3_http_client_with_trust_store_and_resolver(trust_store, dns_resolver.clone()) {
Ok(client) => return Ok(client),
Err(e) => {
warn!("failed to build AWS SDK TLS context for replication client: {}", e);
}
}
}
build_aws_s3_http_client_with_trust_store_and_resolver(smithy_tls::TrustStore::default(), dns_resolver)
}
#[cfg(test)]
@@ -1279,4 +1430,171 @@ mod tests {
"request must still be signed"
);
}
#[test]
fn storage_dns_keeps_the_replication_loopback_setting_independent() {
let host = "storage.example.test";
let origin = "https://storage.example.test";
temp_env::with_vars(
[
("RUSTFS_OUTBOUND_ALLOW_ORIGINS", Some(origin)),
(ALLOW_LOOPBACK_REPLICATION_TARGET_ENV, Some("false")),
],
|| {
let url = Url::parse(origin).expect("storage origin");
let resolver = build_remote_endpoint_dns_resolver(&url).expect("valid storage hostname");
let loopback = "127.0.0.1:443".parse().expect("loopback socket address");
assert_eq!(
resolver
.filter_resolved_addresses(host, vec![loopback])
.expect_err("replication loopback is disabled")
.kind(),
std::io::ErrorKind::PermissionDenied
);
},
);
}
#[tokio::test]
async fn remote_s3_client_blocks_dns_rebinding_across_http_and_skip_tls_verify() {
use rustfs_utils::egress::find_outbound_dns_policy_rejection;
use std::collections::VecDeque;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
let listener = match TcpListener::bind("127.0.0.1:0").await {
Ok(listener) => listener,
Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => return,
Err(err) => panic!("test listener should bind: {err}"),
};
let address = listener.local_addr().expect("listener address");
let endpoint = format!("rebind-remote.test:{}", address.port());
let endpoint_url = Url::parse(&format!("http://{endpoint}")).expect("endpoint URL");
// 1. Without loopback opt-in, a hostname resolving to 127.0.0.1 fails closed at connect time
// (and private RFC1918 answers remain allowed by the resolver).
let no_loopback_resolver = OutboundPolicy::default()
.resolver_for_storage_endpoint(&endpoint_url, true, false)
.expect("hostname should pass URL check")
.with_resolve_override(move |host| {
if host == "rebind-remote.test" {
Some(vec![SocketAddr::new(address.ip(), 0)])
} else {
None
}
});
assert!(
no_loopback_resolver
.filter_resolved_addresses(
"rebind-remote.test",
vec![
SocketAddr::new("10.0.0.5".parse().expect("private ip"), 0),
SocketAddr::new("169.254.169.254".parse().expect("metadata ip"), 0),
SocketAddr::new("fe80::1".parse().expect("link-local"), 0),
SocketAddr::new("127.0.0.1".parse().expect("loopback"), 0),
],
)
.expect("private IP must survive filtering")
== vec![SocketAddr::new("10.0.0.5".parse().expect("private ip"), 0)]
);
let no_loopback_client = S3Client::from_conf(
build_remote_s3_config_with_resolver(&spec(&endpoint, false), no_loopback_resolver)
.await
.expect("config should build")
.build(),
);
let err = no_loopback_client
.head_bucket()
.bucket("bucket")
.send()
.await
.expect_err("loopback DNS answer must be rejected when loopback opt-in is disabled");
assert!(
find_outbound_dns_policy_rejection(&err).is_some(),
"DNS policy rejection must remain in error chain: {err:?}"
);
// 2. With loopback opt-in enabled, first connect reaches local listener, then DNS rebinding
// to metadata (169.254.169.254) fails closed on the second connect.
let answers = Arc::new(Mutex::new(VecDeque::from([
vec![SocketAddr::new(address.ip(), 0)],
vec![SocketAddr::new("169.254.169.254".parse().expect("metadata ip"), 0)],
])));
let rebinding_resolver = OutboundPolicy::default()
.resolver_for_storage_endpoint(&endpoint_url, true, true)
.expect("loopback opt-in should allow hostname")
.with_resolve_override(move |host| {
if host != "rebind-remote.test" {
return None;
}
let mut guard = answers.lock().expect("override lock");
if guard.len() > 1 {
guard.pop_front()
} else {
guard.front().cloned()
}
});
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.expect("first connection should succeed");
let mut buf = [0_u8; 1024];
let _ = stream.read(&mut buf).await.expect("read request");
stream
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.await
.expect("write response");
});
let rebinding_client = S3Client::from_conf(
build_remote_s3_config_with_resolver(&spec(&endpoint, false), rebinding_resolver)
.await
.expect("rebinding config should build")
.build(),
);
rebinding_client
.head_bucket()
.bucket("bucket")
.send()
.await
.expect("first request to local listener should succeed");
server.await.expect("server should finish");
let rebind_err = rebinding_client
.head_bucket()
.bucket("bucket")
.send()
.await
.expect_err("rebound metadata DNS answer must fail closed");
assert!(
find_outbound_dns_policy_rejection(&rebind_err).is_some(),
"rebound metadata rejection must remain in error chain: {rebind_err:?}"
);
// 3. `skip_tls_verify` HTTPS client also enforces connection-time DNS egress policy.
let mut insecure_spec = spec(&endpoint, true);
insecure_spec.skip_tls_verify = true;
let insecure_url = Url::parse(&insecure_spec.endpoint_url()).expect("https endpoint URL");
let metadata_resolver = OutboundPolicy::default()
.resolver_for_storage_endpoint(&insecure_url, true, true)
.expect("https hostname should pass URL check")
.with_resolve_override(|host| {
(host == "rebind-remote.test").then(|| vec![SocketAddr::new("169.254.169.254".parse().expect("metadata ip"), 0)])
});
let insecure_client = S3Client::from_conf(
build_remote_s3_config_with_resolver(&insecure_spec, metadata_resolver)
.await
.expect("skip_tls_verify config should build")
.build(),
);
let insecure_err = insecure_client
.head_bucket()
.bucket("bucket")
.send()
.await
.expect_err("skip_tls_verify client must still reject metadata DNS answers");
assert!(
find_outbound_dns_policy_rejection(&insecure_err).is_some(),
"skip_tls_verify DNS rejection must remain in error chain: {insecure_err:?}"
);
}
}
+558 -21
View File
@@ -29,7 +29,9 @@
use crate::cluster::rpc::context_propagation::{inject_request_id_into_http_headers, inject_trace_context_into_http_headers};
use crate::storage_api_contracts::internode::{
NS_SCANNER_PROTOCOL_VERSION, PUT_FILE_AUTH_TRAILER_DIGEST_LEN, PUT_FILE_AUTH_TRAILER_LEN, PUT_FILE_AUTH_TRAILER_MAC_LEN,
PUT_FILE_AUTH_TRAILER_MAGIC, PUT_FILE_CAPABILITY_VERSION,
PUT_FILE_AUTH_TRAILER_MAGIC, PUT_FILE_CAPABILITY_VERSION, STREAM_RESPONSE_DATA_HEADER_LEN, STREAM_RESPONSE_EOF_FRAME_LEN,
STREAM_RESPONSE_FRAME_KIND_DATA, STREAM_RESPONSE_FRAME_KIND_EOF, STREAM_RESPONSE_FRAME_MAGIC,
STREAM_RESPONSE_FRAME_MAX_PAYLOAD,
};
use hashbrown::HashSet;
@@ -51,7 +53,8 @@ use rustfs_utils::crypto::{HmacSha256, KeyInit, Mac};
use rustfs_utils::get_env_bool;
use sha2::Digest as _;
use sha2::Sha256;
use std::collections::{BTreeMap, hash_map::RandomState};
use std::collections::{BTreeMap, HashMap, hash_map::RandomState};
use std::net::IpAddr;
use std::sync::{LazyLock, Mutex, Once};
use std::thread;
#[cfg(test)]
@@ -368,6 +371,9 @@ pub enum RpcReplayCacheAdmissionError {
/// The next allocation would exceed the automatic byte budget.
#[error("RPC replay cache memory budget exceeded")]
MemoryBudget,
/// One peer reached its isolated share of the replay cache.
#[error("RPC replay cache peer quota exceeded")]
PeerQuota,
}
/// Whether an RPC verifier failed because replay admission exhausted resources.
@@ -388,6 +394,7 @@ pub fn rpc_auth_is_resource_exhausted(error: &std::io::Error) -> bool {
struct RpcNonceBucket {
nonces: HashSet<Uuid, RandomState>,
charged_bytes: u64,
peer_counts: HashMap<IpAddr, usize>,
}
struct RpcNonceCache {
@@ -395,6 +402,7 @@ struct RpcNonceCache {
entries: usize,
table_bytes: u64,
max_wall_time: i64,
peer_entries: HashMap<IpAddr, usize>,
}
impl Default for RpcNonceCache {
@@ -404,6 +412,7 @@ impl Default for RpcNonceCache {
entries: 0,
table_bytes: 0,
max_wall_time: i64::MIN,
peer_entries: HashMap::new(),
}
}
}
@@ -423,6 +432,7 @@ struct RpcNonceRecord<'a> {
wall_time: i64,
capacity: usize,
memory_budget_bytes: Option<u64>,
peer: Option<IpAddr>,
metric_scope: RpcReplayCacheMetricScope<'a>,
}
@@ -475,15 +485,63 @@ impl RpcNonceCache {
.first_key_value()
.is_some_and(|(signed, _)| *signed < first_valid)
{
if let Some((_, nonces)) = self.signed_times.pop_first() {
removed += nonces.nonces.len();
self.table_bytes -= nonces.charged_bytes;
if let Some((_, bucket)) = self.signed_times.pop_first() {
removed += bucket.nonces.len();
self.table_bytes -= bucket.charged_bytes;
for (peer, count) in bucket.peer_counts {
if let Some(total) = self.peer_entries.get_mut(&peer) {
*total = total.saturating_sub(count);
if *total == 0 {
self.peer_entries.remove(&peer);
}
}
}
}
}
self.entries -= removed;
removed
}
fn check_peer_quota(&self, record: &RpcNonceRecord<'_>, additional: usize, growth: u64) -> std::io::Result<()> {
let Some(peer) = record.peer.map(|ip| ip.to_canonical()) else {
return Ok(());
};
let current_peer_entries = self.peer_entries.get(&peer).copied().unwrap_or(0);
// Reserve at least half the cache headroom even when only one peer is active so a
// noisy peer cannot starve healthy peers that arrive later.
let active_peers = self.peer_entries.len() + usize::from(current_peer_entries == 0);
let peer_divisor = active_peers.max(2);
let peer_capacity_limit = (record.capacity / peer_divisor).max(1);
let projected_peer_entries = current_peer_entries
.checked_add(additional)
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::WouldBlock, RpcReplayCacheAdmissionError::PeerQuota))?;
if projected_peer_entries > peer_capacity_limit {
return Err(std::io::Error::new(
std::io::ErrorKind::WouldBlock,
RpcReplayCacheAdmissionError::PeerQuota,
));
}
if let Some(budget) = record.memory_budget_bytes
&& current_peer_entries > 0
{
let usable_budget = budget.saturating_sub(REPLAY_CACHE_METADATA_BYTES);
let peer_budget_limit = usable_budget / (peer_divisor as u64);
let projected_total_entries = self.entries.saturating_add(additional).max(1);
let projected_total_bytes = self.table_bytes.saturating_add(growth);
let projected_peer_bytes = u128::from(projected_total_bytes).saturating_mul(projected_peer_entries as u128)
/ (projected_total_entries as u128);
if projected_peer_bytes > u128::from(peer_budget_limit) {
return Err(std::io::Error::new(
std::io::ErrorKind::WouldBlock,
RpcReplayCacheAdmissionError::PeerQuota,
));
}
}
Ok(())
}
fn reserve_nonces(&mut self, record: &RpcNonceRecord<'_>) -> std::io::Result<()> {
let bucket = self.signed_times.get(&record.signed_at);
let (len, capacity) = bucket.map_or((0, 0), |bucket| (bucket.nonces.len(), bucket.nonces.capacity()));
@@ -491,10 +549,15 @@ impl RpcNonceCache {
let needed = len
.checked_add(additional)
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::OutOfMemory, hashbrown::TryReserveError::CapacityOverflow))?;
if needed > capacity {
let growth = replay_cache_table_growth_bytes(needed).ok_or_else(|| {
let growth = if needed > capacity {
replay_cache_table_growth_bytes(needed).ok_or_else(|| {
std::io::Error::new(std::io::ErrorKind::OutOfMemory, hashbrown::TryReserveError::CapacityOverflow)
})?;
})?
} else {
0
};
self.check_peer_quota(record, additional, growth)?;
if needed > capacity {
// The old table stays live until growth completes. Do not subtract
// it here, even though it will be replaced immediately afterwards.
let peak = self
@@ -526,6 +589,10 @@ impl RpcNonceCache {
if let Some(nonce) = record.compatibility_nonce {
bucket.nonces.insert(nonce);
}
if let Some(peer) = record.peer.map(|ip| ip.to_canonical()) {
*bucket.peer_counts.entry(peer).or_default() += additional;
*self.peer_entries.entry(peer).or_default() += additional;
}
self.entries += additional;
debug_assert!(self.signed_times.len() <= REPLAY_CACHE_CAPACITY_WINDOW_SECS);
Ok(())
@@ -766,6 +833,222 @@ pub fn verify_put_file_auth_trailer(url: &str, method: &Method, nonce: Uuid, tra
Ok(body_sha256.to_string())
}
/// Cryptographic domain separator for framed internode HTTP response streams.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StreamResponseAuthDomain {
ReadFileStream,
WalkDir,
}
impl StreamResponseAuthDomain {
const fn domain_bytes(self) -> &'static [u8] {
match self {
Self::ReadFileStream => b"rustfs-http-read-stream-auth-v1\0",
Self::WalkDir => b"rustfs-http-walk-dir-auth-v1\0",
}
}
}
fn stream_auth_data_frame_mac(
domain: StreamResponseAuthDomain,
url: &str,
method: &Method,
nonce: Uuid,
seq: u64,
payload: &[u8],
) -> std::io::Result<HmacSha256> {
if nonce.is_nil() {
return Err(std::io::Error::other("Invalid stream response auth nonce"));
}
if payload.is_empty() || payload.len() > STREAM_RESPONSE_FRAME_MAX_PAYLOAD {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"stream response auth frame payload size is out of bounds",
));
}
let payload_len = u32::try_from(payload.len())
.map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "stream response frame length overflow"))?;
let path_and_query = canonical_path_and_query(url)?;
let mut mac = <HmacSha256 as KeyInit>::new_from_slice(get_shared_secret()?.as_bytes())
.map_err(|_| std::io::Error::other("Invalid RPC HMAC key"))?;
mac.update(domain.domain_bytes());
mac.update(b"data\0");
mac.update(path_and_query.as_bytes());
mac.update(b"|");
mac.update(method.as_str().as_bytes());
mac.update(b"|");
mac.update(nonce.as_bytes());
mac.update(b"|");
mac.update(&seq.to_be_bytes());
mac.update(&payload_len.to_be_bytes());
mac.update(payload);
Ok(mac)
}
pub fn encode_stream_auth_data_frame(
domain: StreamResponseAuthDomain,
url: &str,
method: &Method,
nonce: Uuid,
seq: u64,
payload: &[u8],
) -> std::io::Result<Vec<u8>> {
let payload_len = u32::try_from(payload.len())
.map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "stream response frame length overflow"))?;
let mac = stream_auth_data_frame_mac(domain, url, method, nonce, seq, payload)?
.finalize()
.into_bytes();
let mut frame = Vec::with_capacity(STREAM_RESPONSE_DATA_HEADER_LEN + payload.len());
frame.extend_from_slice(STREAM_RESPONSE_FRAME_MAGIC);
frame.push(STREAM_RESPONSE_FRAME_KIND_DATA);
frame.extend_from_slice(&seq.to_be_bytes());
frame.extend_from_slice(&payload_len.to_be_bytes());
frame.extend_from_slice(&mac);
frame.extend_from_slice(payload);
Ok(frame)
}
pub fn verify_stream_auth_data_frame(
domain: StreamResponseAuthDomain,
url: &str,
method: &Method,
nonce: Uuid,
expected_seq: u64,
header: &[u8; STREAM_RESPONSE_DATA_HEADER_LEN],
payload: &[u8],
) -> std::io::Result<()> {
if &header[..8] != STREAM_RESPONSE_FRAME_MAGIC || header[8] != STREAM_RESPONSE_FRAME_KIND_DATA {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"invalid authenticated internode stream data frame header",
));
}
let seq = u64::from_be_bytes(
header[9..17]
.try_into()
.map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid stream frame sequence"))?,
);
if seq != expected_seq {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"authenticated internode stream frame sequence mismatch",
));
}
let declared_len = u32::from_be_bytes(
header[17..21]
.try_into()
.map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid stream frame length"))?,
) as usize;
if declared_len == 0 || declared_len != payload.len() || declared_len > STREAM_RESPONSE_FRAME_MAX_PAYLOAD {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"authenticated internode stream frame length mismatch",
));
}
stream_auth_data_frame_mac(domain, url, method, nonce, expected_seq, payload)?
.verify_slice(&header[21..53])
.map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"invalid authenticated internode stream data frame MAC",
)
})
}
fn stream_auth_eof_frame_mac(
domain: StreamResponseAuthDomain,
url: &str,
method: &Method,
nonce: Uuid,
seq: u64,
total_bytes: u64,
running_sha256: &[u8; 32],
) -> std::io::Result<HmacSha256> {
if nonce.is_nil() {
return Err(std::io::Error::other("Invalid stream response auth nonce"));
}
let path_and_query = canonical_path_and_query(url)?;
let mut mac = <HmacSha256 as KeyInit>::new_from_slice(get_shared_secret()?.as_bytes())
.map_err(|_| std::io::Error::other("Invalid RPC HMAC key"))?;
mac.update(domain.domain_bytes());
mac.update(b"eof\0");
mac.update(path_and_query.as_bytes());
mac.update(b"|");
mac.update(method.as_str().as_bytes());
mac.update(b"|");
mac.update(nonce.as_bytes());
mac.update(b"|");
mac.update(&seq.to_be_bytes());
mac.update(&total_bytes.to_be_bytes());
mac.update(running_sha256);
Ok(mac)
}
pub fn encode_stream_auth_eof_frame(
domain: StreamResponseAuthDomain,
url: &str,
method: &Method,
nonce: Uuid,
seq: u64,
total_bytes: u64,
running_sha256: &[u8; 32],
) -> std::io::Result<[u8; STREAM_RESPONSE_EOF_FRAME_LEN]> {
let mac = stream_auth_eof_frame_mac(domain, url, method, nonce, seq, total_bytes, running_sha256)?
.finalize()
.into_bytes();
let mut frame = [0u8; STREAM_RESPONSE_EOF_FRAME_LEN];
frame[..8].copy_from_slice(STREAM_RESPONSE_FRAME_MAGIC);
frame[8] = STREAM_RESPONSE_FRAME_KIND_EOF;
frame[9..17].copy_from_slice(&seq.to_be_bytes());
frame[17..25].copy_from_slice(&total_bytes.to_be_bytes());
frame[25..57].copy_from_slice(running_sha256);
frame[57..89].copy_from_slice(&mac);
Ok(frame)
}
#[allow(clippy::too_many_arguments)]
pub fn verify_stream_auth_eof_frame(
domain: StreamResponseAuthDomain,
url: &str,
method: &Method,
nonce: Uuid,
expected_seq: u64,
expected_total_bytes: u64,
expected_sha256: &[u8; 32],
frame: &[u8; STREAM_RESPONSE_EOF_FRAME_LEN],
) -> std::io::Result<()> {
if &frame[..8] != STREAM_RESPONSE_FRAME_MAGIC || frame[8] != STREAM_RESPONSE_FRAME_KIND_EOF {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"invalid authenticated internode stream EOF frame header",
));
}
let seq = u64::from_be_bytes(
frame[9..17]
.try_into()
.map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid stream EOF sequence"))?,
);
let total_bytes = u64::from_be_bytes(
frame[17..25]
.try_into()
.map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid stream EOF byte count"))?,
);
if seq != expected_seq || total_bytes != expected_total_bytes || &frame[25..57] != expected_sha256 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"authenticated internode stream EOF summary mismatch",
));
}
stream_auth_eof_frame_mac(domain, url, method, nonce, expected_seq, expected_total_bytes, expected_sha256)?
.verify_slice(&frame[57..89])
.map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"invalid authenticated internode stream EOF frame MAC",
)
})
}
fn update_put_file_capability_mac(mac: &mut HmacSha256, challenge: Uuid, server_epoch: Uuid, version: u16) {
mac.update(HTTP_PUT_FILE_CAPABILITY_AUTH_DOMAIN);
mac.update(challenge.as_bytes());
@@ -1631,6 +1914,7 @@ fn check_and_record_nonce_with_scope(
rpc_path: &str,
operation: &'static str,
backend: &'static str,
peer: Option<IpAddr>,
) -> std::io::Result<()> {
let wall_time = OffsetDateTime::now_utc().unix_timestamp();
let (result, metrics) = {
@@ -1644,6 +1928,7 @@ fn check_and_record_nonce_with_scope(
wall_time,
capacity: REPLAY_CACHE_CAPACITY.capacity,
memory_budget_bytes: REPLAY_CACHE_CAPACITY.memory_budget_bytes,
peer,
metric_scope: RpcReplayCacheMetricScope {
operation,
backend,
@@ -1660,6 +1945,7 @@ fn check_and_record_tonic_nonce(
compatibility_nonce: Option<Uuid>,
signed_at: i64,
rpc_path: &str,
peer: Option<IpAddr>,
) -> std::io::Result<()> {
check_and_record_nonce_with_scope(
nonce,
@@ -1668,6 +1954,7 @@ fn check_and_record_tonic_nonce(
rpc_path,
tonic_rpc_metric_operation(rpc_path),
INTERNODE_TRANSPORT_BACKEND_GRPC,
peer,
)
}
@@ -1677,6 +1964,17 @@ pub fn check_and_record_signed_rpc_nonce(
rpc_path: &str,
operation: &'static str,
backend: &'static str,
) -> std::io::Result<()> {
check_and_record_signed_rpc_nonce_for_peer(headers, nonce, rpc_path, operation, backend, None)
}
pub fn check_and_record_signed_rpc_nonce_for_peer(
headers: &HeaderMap,
nonce: Uuid,
rpc_path: &str,
operation: &'static str,
backend: &'static str,
peer: Option<IpAddr>,
) -> std::io::Result<()> {
if nonce.is_nil() {
return Err(std::io::Error::other("Invalid RPC nonce"));
@@ -1689,7 +1987,7 @@ pub fn check_and_record_signed_rpc_nonce(
.parse::<i64>()
.map_err(|_| std::io::Error::other("Invalid timestamp format"))?;
check_timestamp(timestamp)?;
check_and_record_nonce_with_scope(nonce, None, timestamp, rpc_path, operation, backend)
check_and_record_nonce_with_scope(nonce, None, timestamp, rpc_path, operation, backend, peer)
}
/// Build headers with authentication signature
@@ -2006,7 +2304,12 @@ fn internode_rpc_replay_scope_strict() -> bool {
*INTERNODE_RPC_REPLAY_SCOPE_STRICT
}
fn verify_tonic_replay_scope_signature(audience: &str, path: &str, headers: &HeaderMap) -> std::io::Result<()> {
fn verify_tonic_replay_scope_signature(
audience: &str,
path: &str,
headers: &HeaderMap,
peer: Option<IpAddr>,
) -> std::io::Result<()> {
if audience.is_empty() {
return Err(std::io::Error::other("Missing RPC audience"));
}
@@ -2078,18 +2381,19 @@ fn verify_tonic_replay_scope_signature(audience: &str, path: &str, headers: &Hea
} else {
None
};
check_and_record_tonic_nonce(nonce, compatibility_nonce, signed_at, path)
check_and_record_tonic_nonce(nonce, compatibility_nonce, signed_at, path, peer)
}
/// Verify gRPC authentication, preferring v2 without downgrade on malformed v2 metadata.
pub fn verify_tonic_rpc_signature(audience: &str, path: &str, headers: &HeaderMap) -> std::io::Result<()> {
verify_tonic_rpc_signature_with_policy(
verify_tonic_rpc_signature_with_policy_and_peer(
audience,
path,
headers,
internode_rpc_signature_strict(),
internode_rpc_replay_scope_strict(),
false,
None,
)
}
@@ -2101,13 +2405,25 @@ pub fn verify_tonic_rpc_signature_with_bootstrap(
headers: &HeaderMap,
allow_replay_scope_bootstrap: bool,
) -> std::io::Result<()> {
verify_tonic_rpc_signature_with_policy(
verify_tonic_rpc_signature_with_bootstrap_and_peer(audience, path, headers, allow_replay_scope_bootstrap, None)
}
/// Verify gRPC authentication while isolating replay-cache quota per peer address.
pub fn verify_tonic_rpc_signature_with_bootstrap_and_peer(
audience: &str,
path: &str,
headers: &HeaderMap,
allow_replay_scope_bootstrap: bool,
peer: Option<IpAddr>,
) -> std::io::Result<()> {
verify_tonic_rpc_signature_with_policy_and_peer(
audience,
path,
headers,
internode_rpc_signature_strict(),
internode_rpc_replay_scope_strict(),
allow_replay_scope_bootstrap,
peer,
)
}
@@ -2131,6 +2447,7 @@ pub fn tonic_rpc_auth_failure_reason(error: &std::io::Error) -> &'static str {
"RPC request replay detected" => "replay_detected",
"RPC replay cache capacity exceeded" => "replay_cache_capacity",
"RPC replay cache memory budget exceeded" => "replay_cache_memory",
"RPC replay cache peer quota exceeded" => "replay_cache_peer_quota",
"RPC replay cache unavailable" => "replay_cache_unavailable",
"RPC replay expiry overflow" => "replay_expiry_overflow",
"RPC request timestamp expired after clock regression" => "timestamp_expired_after_clock_regression",
@@ -2157,6 +2474,7 @@ pub fn tonic_rpc_auth_failure_reason(error: &std::io::Error) -> &'static str {
}
}
#[cfg(test)]
fn verify_tonic_rpc_signature_with_policy(
audience: &str,
path: &str,
@@ -2164,9 +2482,29 @@ fn verify_tonic_rpc_signature_with_policy(
signature_strict: bool,
replay_scope_strict: bool,
allow_replay_scope_bootstrap: bool,
) -> std::io::Result<()> {
verify_tonic_rpc_signature_with_policy_and_peer(
audience,
path,
headers,
signature_strict,
replay_scope_strict,
allow_replay_scope_bootstrap,
None,
)
}
fn verify_tonic_rpc_signature_with_policy_and_peer(
audience: &str,
path: &str,
headers: &HeaderMap,
signature_strict: bool,
replay_scope_strict: bool,
allow_replay_scope_bootstrap: bool,
peer: Option<IpAddr>,
) -> std::io::Result<()> {
if has_replay_scope_headers(headers) {
return verify_tonic_replay_scope_signature(audience, path, headers);
return verify_tonic_replay_scope_signature(audience, path, headers, peer);
}
// Only a method-bound v2 Ping with a syntactically valid challenge may bootstrap a strict
@@ -2182,21 +2520,32 @@ fn verify_tonic_rpc_signature_with_policy(
return Err(std::io::Error::other("RPC replay-scoped authentication required"));
}
verify_tonic_rpc_signature_with_strictness(audience, path, headers, signature_strict)?;
verify_tonic_rpc_signature_with_strictness_and_peer(audience, path, headers, signature_strict, peer)?;
global_internode_metrics().record_replay_scope_fallback();
Ok(())
}
/// [`verify_tonic_rpc_signature`] with the strict gate injected as a parameter, so both rollout
/// postures are unit-testable without racing on process-global environment variables.
#[cfg(test)]
fn verify_tonic_rpc_signature_with_strictness(
audience: &str,
path: &str,
headers: &HeaderMap,
strict: bool,
) -> std::io::Result<()> {
verify_tonic_rpc_signature_with_strictness_and_peer(audience, path, headers, strict, None)
}
fn verify_tonic_rpc_signature_with_strictness_and_peer(
audience: &str,
path: &str,
headers: &HeaderMap,
strict: bool,
peer: Option<IpAddr>,
) -> std::io::Result<()> {
if let Some((nonce, signed_at)) = verified_tonic_rpc_nonce(audience, path, headers, strict)? {
check_and_record_tonic_nonce(nonce, None, signed_at, path)?;
check_and_record_tonic_nonce(nonce, None, signed_at, path, peer)?;
}
Ok(())
}
@@ -2484,11 +2833,11 @@ mod tests {
};
assert!(verify_rpc_signature("/rustfs/rpc/read?disk=a", &Method::GET, &alter(&http)).is_err());
assert!(verify_tonic_rpc_signature_with_strictness("node-a:9000", path, &alter(&tonic), true).is_err());
assert!(verify_tonic_replay_scope_signature("node-a:9000", path, &alter(&replay)).is_err());
assert!(verify_tonic_replay_scope_signature("node-a:9000", path, &alter(&replay), None).is_err());
}
verify_tonic_replay_scope_signature("node-a:9000", path, &replay).expect("v3 authentication");
verify_tonic_replay_scope_signature("node-a:9000", path, &replay, None).expect("v3 authentication");
assert!(
verify_tonic_replay_scope_signature("node-a:9000", path, &replay).is_err(),
verify_tonic_replay_scope_signature("node-a:9000", path, &replay, None).is_err(),
"replay rejected"
);
@@ -3201,8 +3550,9 @@ mod tests {
.expect_err("the random replay-scope nonce must be single-use");
assert_eq!(replay.to_string(), "RPC request replay detected");
let path_error = verify_tonic_replay_scope_signature("node-a:9000", "/node_service.NodeService/SignalService", &headers)
.expect_err("a replay-scoped signature must not move to another method");
let path_error =
verify_tonic_replay_scope_signature("node-a:9000", "/node_service.NodeService/SignalService", &headers, None)
.expect_err("a replay-scoped signature must not move to another method");
assert_eq!(path_error.to_string(), "Invalid RPC replay scope signature");
}
@@ -3870,6 +4220,7 @@ mod tests {
wall_time,
capacity,
memory_budget_bytes: None,
peer: None,
metric_scope: RpcReplayCacheMetricScope {
operation: INTERNODE_OPERATION_GRPC_READ_ALL,
backend: INTERNODE_TRANSPORT_BACKEND_GRPC,
@@ -4765,4 +5116,190 @@ mod tests {
.expect_err("the monotonic wall-clock high-water mark must fail closed");
assert_eq!(stale.to_string(), "RPC request timestamp expired after clock regression");
}
#[test]
fn nonce_cache_isolates_noisy_peer_by_entry_and_memory_quota() {
let now = Instant::now();
let peer_a: IpAddr = "10.0.0.10".parse().expect("peer a");
let peer_b: IpAddr = "10.0.0.20".parse().expect("peer b");
// 1. Entry capacity quota: with capacity=10, a single peer cannot consume more than
// half the slots (5), leaving headroom for an honest peer.
let mut cache = RpcNonceCache::default();
for i in 1..=5_u128 {
let mut rec = test_nonce_record(Uuid::from_u128(i), 1_000, now, 1_000, now, 10);
rec.peer = Some(peer_a);
cache.check_and_record(rec).0.expect("peer A within isolated share");
}
let mut overflow = test_nonce_record(Uuid::from_u128(6), 1_000, now, 1_000, now, 10);
overflow.peer = Some(peer_a);
let err = cache
.check_and_record(overflow)
.0
.expect_err("peer A must hit PeerQuota before exhausting global capacity");
assert!(rpc_auth_is_resource_exhausted(&err));
assert_eq!(tonic_rpc_auth_failure_reason(&err), "replay_cache_peer_quota");
// IPv4-mapped IPv6 for the same peer shares the canonical peer quota bucket.
let mut mapped_overflow = test_nonce_record(Uuid::from_u128(100), 1_000, now, 1_000, now, 10);
mapped_overflow.peer = Some("::ffff:10.0.0.10".parse().expect("mapped peer a"));
let mapped_err = cache
.check_and_record(mapped_overflow)
.0
.expect_err("IPv4-mapped IPv6 peer must share the canonical IPv4 quota");
assert_eq!(tonic_rpc_auth_failure_reason(&mapped_err), "replay_cache_peer_quota");
// Honest peer B must still be admitted into the remaining slots.
for i in 101..=105_u128 {
let mut rec = test_nonce_record(Uuid::from_u128(i), 1_000, now, 1_000, now, 10);
rec.peer = Some(peer_b);
cache
.check_and_record(rec)
.0
.expect("honest peer B must succeed despite peer A flood");
}
// After expiration, peer A's tracked entry count is reclaimed so it can send again.
let mut after_expiry = test_nonce_record(Uuid::from_u128(200), 1_400, now, 1_400, now, 10);
after_expiry.peer = Some(peer_a);
cache
.check_and_record(after_expiry)
.0
.expect("expired entries must free peer A quota");
assert_eq!(cache.peer_entries.get(&peer_a), Some(&1));
assert!(!cache.peer_entries.contains_key(&peer_b));
// 2. Memory budget quota: peer A flooding distinct timestamps hits PeerQuota before
// exhausting the memory budget so peer B can still register its request.
let mut mem_cache = RpcNonceCache::default();
let budget = REPLAY_CACHE_METADATA_BYTES + 12_000;
let mut peer_a_hit_quota = false;
for ts in 0..64_i64 {
let mut rec = test_nonce_record(Uuid::from_u128((ts + 1) as u128), 2_000 + ts, now, 2_000 + ts, now, 10_000);
rec.memory_budget_bytes = Some(budget);
rec.peer = Some(peer_a);
match mem_cache.check_and_record(rec).0 {
Ok(()) => {}
Err(err) => {
assert_eq!(tonic_rpc_auth_failure_reason(&err), "replay_cache_peer_quota");
peer_a_hit_quota = true;
break;
}
}
}
assert!(peer_a_hit_quota, "flooding peer must hit per-peer memory quota before global exhaustion");
let mut honest = test_nonce_record(Uuid::from_u128(9_999), 2_000, now, 2_000, now, 10_000);
honest.memory_budget_bytes = Some(budget);
honest.peer = Some(peer_b);
mem_cache
.check_and_record(honest)
.0
.expect("honest peer must succeed when noisy peer hit memory quota");
}
#[test]
fn stream_auth_frames_verify_and_reject_tamper_reorder_and_cross_domain_replay() {
crate::runtime::sources::ensure_test_rpc_secret();
let nonce = Uuid::new_v4();
let url =
format!("http://127.0.0.1:9000/rustfs/rpc/read_file_stream?disk=d1&stream_auth=framed-v1&stream_auth_nonce={nonce}");
let payload = b"erasure-shard-bytes";
let frame =
encode_stream_auth_data_frame(StreamResponseAuthDomain::ReadFileStream, &url, &Method::GET, nonce, 0, payload)
.expect("data frame should encode");
let header: [u8; STREAM_RESPONSE_DATA_HEADER_LEN] =
frame[..STREAM_RESPONSE_DATA_HEADER_LEN].try_into().expect("header length");
verify_stream_auth_data_frame(StreamResponseAuthDomain::ReadFileStream, &url, &Method::GET, nonce, 0, &header, payload)
.expect("valid data frame must verify");
// Payload bit flip rejected.
let mut tampered_payload = payload.to_vec();
tampered_payload[0] ^= 0x01;
assert!(
verify_stream_auth_data_frame(
StreamResponseAuthDomain::ReadFileStream,
&url,
&Method::GET,
nonce,
0,
&header,
&tampered_payload,
)
.is_err()
);
// Sequence reorder rejected.
assert!(
verify_stream_auth_data_frame(
StreamResponseAuthDomain::ReadFileStream,
&url,
&Method::GET,
nonce,
1,
&header,
payload,
)
.is_err()
);
// Cross-domain replay (ReadFileStream frame verified as WalkDir) rejected.
assert!(
verify_stream_auth_data_frame(StreamResponseAuthDomain::WalkDir, &url, &Method::GET, nonce, 0, &header, payload,)
.is_err()
);
// Cross-request replay (different nonce) rejected.
assert!(
verify_stream_auth_data_frame(
StreamResponseAuthDomain::ReadFileStream,
&url,
&Method::GET,
Uuid::new_v4(),
0,
&header,
payload,
)
.is_err()
);
// EOF frame verification and digest/length mismatch rejection.
let digest: [u8; 32] = Sha256::digest(payload).into();
let eof = encode_stream_auth_eof_frame(
StreamResponseAuthDomain::ReadFileStream,
&url,
&Method::GET,
nonce,
1,
payload.len() as u64,
&digest,
)
.expect("eof frame should encode");
verify_stream_auth_eof_frame(
StreamResponseAuthDomain::ReadFileStream,
&url,
&Method::GET,
nonce,
1,
payload.len() as u64,
&digest,
&eof,
)
.expect("valid EOF frame must verify");
assert!(
verify_stream_auth_eof_frame(
StreamResponseAuthDomain::ReadFileStream,
&url,
&Method::GET,
nonce,
1,
payload.len() as u64 + 1,
&digest,
&eof,
)
.is_err()
);
}
}
@@ -13,9 +13,10 @@
// limitations under the License.
use crate::cluster::rpc::{
build_auth_headers, build_put_file_auth_trailer, verify_ns_scanner_capability_with_checkpoint_coverage,
verify_ns_scanner_capability_with_durable_progress, verify_ns_scanner_capability_with_tier_registry_generation,
verify_ns_scanner_capability_with_usage_capabilities, verify_put_file_capability,
StreamResponseAuthDomain, build_auth_headers, build_put_file_auth_trailer,
verify_ns_scanner_capability_with_checkpoint_coverage, verify_ns_scanner_capability_with_durable_progress,
verify_ns_scanner_capability_with_tier_registry_generation, verify_ns_scanner_capability_with_usage_capabilities,
verify_put_file_capability, verify_stream_auth_data_frame, verify_stream_auth_eof_frame,
};
use crate::disk::error::{Error, Result};
use crate::disk::{FileReader, FileWriter};
@@ -27,26 +28,31 @@ use crate::storage_api_contracts::internode::{
NS_SCANNER_TIER_REGISTRY_GENERATION_QUERY, NS_SCANNER_TIER_REGISTRY_PREFLIGHT_QUERY, NsScannerCapabilityResponse,
PUT_FILE_AUTH_QUERY, PUT_FILE_AUTH_V1, PUT_FILE_CAPABILITY_CHALLENGE_QUERY, PUT_FILE_CAPABILITY_QUERY,
PUT_FILE_CAPABILITY_VERSION, PUT_FILE_NONCE_QUERY, PUT_FILE_SERVER_EPOCH_QUERY, PutFileCapabilityResponse,
WALK_DIR_BODY_SHA256_QUERY, WALK_DIR_STREAM_COMPLETION_QUERY, WALK_DIR_STREAM_COMPLETION_V1,
STREAM_RESPONSE_AUTH_HEADER, STREAM_RESPONSE_AUTH_NONCE_QUERY, STREAM_RESPONSE_AUTH_QUERY, STREAM_RESPONSE_AUTH_V1,
STREAM_RESPONSE_DATA_HEADER_LEN, STREAM_RESPONSE_EOF_FRAME_LEN, STREAM_RESPONSE_FRAME_KIND_DATA,
STREAM_RESPONSE_FRAME_KIND_EOF, STREAM_RESPONSE_FRAME_MAGIC, STREAM_RESPONSE_FRAME_MAX_PAYLOAD, WALK_DIR_BODY_SHA256_QUERY,
WALK_DIR_STREAM_COMPLETION_QUERY, WALK_DIR_STREAM_COMPLETION_V1,
};
use async_trait::async_trait;
use bytes::Bytes;
use http::{HeaderMap, HeaderValue, Method, header::CONTENT_TYPE};
use rustfs_config::{
DEFAULT_INTERNODE_DATA_TRANSPORT, ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, INTERNODE_DATA_TRANSPORT_NIXL,
INTERNODE_DATA_TRANSPORT_TCP, KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS,
DEFAULT_INTERNODE_DATA_TRANSPORT, DEFAULT_INTERNODE_RPC_STREAM_AUTH_STRICT, ENV_INTERNODE_RPC_STREAM_AUTH_STRICT,
ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, INTERNODE_DATA_TRANSPORT_NIXL, INTERNODE_DATA_TRANSPORT_TCP,
KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS,
};
use rustfs_rio::{
ChunkReaderBox, HttpChunkReader, HttpReader, HttpWriter, HttpWriterMemoryReservation, HttpWriterMemoryReserver,
ChunkReader, ChunkReaderBox, HttpChunkReader, HttpReader, HttpWriter, HttpWriterMemoryReservation, HttpWriterMemoryReserver,
};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::{Arc, LazyLock, OnceLock};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWrite};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf};
use tokio::sync::OnceCell;
use uuid::Uuid;
@@ -135,6 +141,271 @@ pub(super) type PutFileCapabilityCacheEntry = Arc<parking_lot::RwLock<PutFileCap
static PUT_FILE_CAPABILITY_CACHE: LazyLock<parking_lot::RwLock<HashMap<String, PutFileCapabilityCacheEntry>>> =
LazyLock::new(|| parking_lot::RwLock::new(HashMap::new()));
static STREAM_RESPONSE_AUTH_STRICT: LazyLock<bool> =
LazyLock::new(|| rustfs_utils::get_env_bool(ENV_INTERNODE_RPC_STREAM_AUTH_STRICT, DEFAULT_INTERNODE_RPC_STREAM_AUTH_STRICT));
// Once a peer proves cryptographic support for authenticated framed response streams,
// pin it so an on-path attacker cannot strip the header and downgrade subsequent responses.
static STREAM_AUTH_PINNED_ENDPOINTS: LazyLock<parking_lot::RwLock<HashSet<String>>> =
LazyLock::new(|| parking_lot::RwLock::new(HashSet::new()));
fn normalize_stream_auth_endpoint(endpoint: &str) -> String {
endpoint.trim().trim_end_matches('/').to_ascii_lowercase()
}
fn pin_stream_auth_endpoint(endpoint: &str) {
let key = normalize_stream_auth_endpoint(endpoint);
if !key.is_empty() && !STREAM_AUTH_PINNED_ENDPOINTS.read().contains(&key) {
STREAM_AUTH_PINNED_ENDPOINTS.write().insert(key);
}
}
fn should_authenticate_response_stream(endpoint: &str, response_headers: &HeaderMap, strict: bool) -> Result<bool> {
let mut values = response_headers.get_all(STREAM_RESPONSE_AUTH_HEADER).iter();
match (values.next(), values.next()) {
(Some(value), None) if value == STREAM_RESPONSE_AUTH_V1 => Ok(true),
(Some(_), _) => Err(Error::other("unsupported or duplicate internode stream response auth header")),
(None, _) => {
let key = normalize_stream_auth_endpoint(endpoint);
if strict || STREAM_AUTH_PINNED_ENDPOINTS.read().contains(&key) {
return Err(Error::other("internode stream response auth missing or downgraded"));
}
Ok(false)
}
}
}
struct AuthenticatedStreamReader<R> {
inner: R,
endpoint: String,
pinned: bool,
domain: StreamResponseAuthDomain,
url: String,
method: Method,
nonce: Uuid,
seq: u64,
total_bytes: u64,
hasher: Sha256,
raw_buf: Vec<u8>,
raw_pos: usize,
decoded: Bytes,
eof_verified: bool,
failed: Option<String>,
}
impl<R> AuthenticatedStreamReader<R> {
fn new(inner: R, endpoint: String, domain: StreamResponseAuthDomain, url: String, method: Method, nonce: Uuid) -> Self {
Self {
inner,
endpoint,
pinned: false,
domain,
url,
method,
nonce,
seq: 0,
total_bytes: 0,
hasher: Sha256::new(),
raw_buf: Vec::new(),
raw_pos: 0,
decoded: Bytes::new(),
eof_verified: false,
failed: None,
}
}
fn note_authenticated_peer(&mut self) {
if !self.pinned {
pin_stream_auth_endpoint(&self.endpoint);
self.pinned = true;
}
}
fn compact_raw_buf(&mut self) {
if self.raw_pos == self.raw_buf.len() {
self.raw_buf.clear();
self.raw_pos = 0;
} else if self.raw_pos >= 64 * 1024 {
self.raw_buf.drain(..self.raw_pos);
self.raw_pos = 0;
}
}
fn record_failure(&mut self, err: io::Error) -> io::Error {
self.failed = Some(err.to_string());
err
}
fn try_decode_buffered_frame(&mut self) -> io::Result<bool> {
let avail = &self.raw_buf[self.raw_pos..];
if avail.len() >= 8 && &avail[..8] != STREAM_RESPONSE_FRAME_MAGIC {
return Err(self.record_failure(io::Error::new(
io::ErrorKind::InvalidData,
"invalid authenticated internode stream frame magic",
)));
}
if avail.len() < 9 {
return Ok(false);
}
match avail[8] {
STREAM_RESPONSE_FRAME_KIND_DATA => {
if avail.len() < STREAM_RESPONSE_DATA_HEADER_LEN {
return Ok(false);
}
let declared_len = u32::from_be_bytes(
avail[17..21]
.try_into()
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid stream frame length"))?,
) as usize;
if declared_len == 0 || declared_len > STREAM_RESPONSE_FRAME_MAX_PAYLOAD {
return Err(self.record_failure(io::Error::new(
io::ErrorKind::InvalidData,
"authenticated internode stream frame payload size is out of bounds",
)));
}
let frame_len = STREAM_RESPONSE_DATA_HEADER_LEN + declared_len;
if avail.len() < frame_len {
return Ok(false);
}
let header: [u8; STREAM_RESPONSE_DATA_HEADER_LEN] = avail[..STREAM_RESPONSE_DATA_HEADER_LEN]
.try_into()
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid stream header"))?;
let payload = &avail[STREAM_RESPONSE_DATA_HEADER_LEN..frame_len];
if let Err(err) =
verify_stream_auth_data_frame(self.domain, &self.url, &self.method, self.nonce, self.seq, &header, payload)
{
return Err(self.record_failure(err));
}
self.hasher.update(payload);
self.total_bytes = self.total_bytes.saturating_add(payload.len() as u64);
self.seq = self.seq.saturating_add(1);
self.decoded = Bytes::copy_from_slice(payload);
self.raw_pos += frame_len;
self.compact_raw_buf();
self.note_authenticated_peer();
Ok(true)
}
STREAM_RESPONSE_FRAME_KIND_EOF => {
if avail.len() < STREAM_RESPONSE_EOF_FRAME_LEN {
return Ok(false);
}
let frame: [u8; STREAM_RESPONSE_EOF_FRAME_LEN] = avail[..STREAM_RESPONSE_EOF_FRAME_LEN]
.try_into()
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid stream EOF frame"))?;
let digest: [u8; 32] = self.hasher.clone().finalize().into();
if let Err(err) = verify_stream_auth_eof_frame(
self.domain,
&self.url,
&self.method,
self.nonce,
self.seq,
self.total_bytes,
&digest,
&frame,
) {
return Err(self.record_failure(err));
}
self.note_authenticated_peer();
self.raw_pos += STREAM_RESPONSE_EOF_FRAME_LEN;
if self.raw_pos < self.raw_buf.len() {
return Err(self.record_failure(io::Error::new(
io::ErrorKind::InvalidData,
"unexpected trailing bytes after authenticated internode stream EOF",
)));
}
self.raw_buf.clear();
self.raw_pos = 0;
self.eof_verified = true;
Ok(true)
}
_ => Err(self.record_failure(io::Error::new(
io::ErrorKind::InvalidData,
"invalid authenticated internode stream frame kind",
))),
}
}
fn poll_next_verified_bytes(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<bool>>
where
R: AsyncRead + Unpin,
{
loop {
if !self.decoded.is_empty() {
return Poll::Ready(Ok(true));
}
if let Some(msg) = &self.failed {
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, msg.clone())));
}
if !self.eof_verified && self.try_decode_buffered_frame()? {
continue;
}
let mut scratch = [0u8; 8192];
let mut read_buf = ReadBuf::new(&mut scratch);
match Pin::new(&mut self.inner).poll_read(cx, &mut read_buf) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(err)) => return Poll::Ready(Err(self.record_failure(err))),
Poll::Ready(Ok(())) => {
let n = read_buf.filled().len();
if n == 0 {
if self.eof_verified {
return Poll::Ready(Ok(false));
}
return Poll::Ready(Err(self.record_failure(io::Error::new(
io::ErrorKind::UnexpectedEof,
"truncated authenticated internode stream before EOF frame",
))));
}
if self.eof_verified {
return Poll::Ready(Err(self.record_failure(io::Error::new(
io::ErrorKind::InvalidData,
"unexpected trailing bytes after authenticated internode stream EOF",
))));
}
self.raw_buf.extend_from_slice(read_buf.filled());
}
}
}
}
}
impl<R> AsyncRead for AuthenticatedStreamReader<R>
where
R: AsyncRead + Unpin,
{
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
if buf.remaining() == 0 {
return Poll::Ready(Ok(()));
}
let this = self.as_mut().get_mut();
match std::task::ready!(this.poll_next_verified_bytes(cx)) {
Ok(false) => Poll::Ready(Ok(())),
Ok(true) => {
let take = buf.remaining().min(this.decoded.len());
buf.put_slice(&this.decoded.split_to(take));
Poll::Ready(Ok(()))
}
Err(err) => Poll::Ready(Err(err)),
}
}
}
impl<R> ChunkReader for AuthenticatedStreamReader<R>
where
R: AsyncRead + Send + Sync + Unpin,
{
fn poll_read_chunk(mut self: Pin<&mut Self>, cx: &mut Context<'_>, max: usize) -> Poll<io::Result<Option<Bytes>>> {
let this = self.as_mut().get_mut();
match std::task::ready!(this.poll_next_verified_bytes(cx)) {
Ok(false) => Poll::Ready(Ok(None)),
Ok(true) => {
let take = max.min(this.decoded.len());
Poll::Ready(Ok(Some(this.decoded.split_to(take))))
}
Err(err) => Poll::Ready(Err(err)),
}
}
}
pub(super) fn put_file_capability_cache_entry(endpoint: &str) -> PutFileCapabilityCacheEntry {
if let Some(entry) = PUT_FILE_CAPABILITY_CACHE.read().get(endpoint).cloned() {
return entry;
@@ -349,40 +620,93 @@ pub struct TcpHttpInternodeDataTransport;
#[async_trait]
impl InternodeDataTransport for TcpHttpInternodeDataTransport {
async fn open_read(&self, request: ReadStreamRequest) -> Result<FileReader> {
let url = build_read_file_stream_url(&request);
let auth_nonce = Uuid::new_v4();
let url = build_authenticated_read_file_stream_url(&request, auth_nonce);
let mut headers = json_headers();
build_auth_headers(&url, &Method::GET, &mut headers)?;
Ok(Box::new(
HttpReader::new_with_stall_timeout(url, Method::GET, headers, None, request.stall_timeout).await?,
))
let reader = HttpReader::new_with_stall_timeout(url.clone(), Method::GET, headers, None, request.stall_timeout).await?;
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
Ok(Box::new(AuthenticatedStreamReader::new(
reader,
request.endpoint,
StreamResponseAuthDomain::ReadFileStream,
url,
Method::GET,
auth_nonce,
)))
} else {
Ok(Box::new(reader))
}
}
async fn open_read_fresh(&self, request: ReadStreamRequest) -> Result<FileReader> {
let url = build_read_file_stream_url(&request);
let auth_nonce = Uuid::new_v4();
let url = build_authenticated_read_file_stream_url(&request, auth_nonce);
let mut headers = json_headers();
build_auth_headers(&url, &Method::GET, &mut headers)?;
Ok(Box::new(
HttpReader::new_fresh_connection_with_stall_timeout(url, Method::GET, headers, None, request.stall_timeout).await?,
))
let reader =
HttpReader::new_fresh_connection_with_stall_timeout(url.clone(), Method::GET, headers, None, request.stall_timeout)
.await?;
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
Ok(Box::new(AuthenticatedStreamReader::new(
reader,
request.endpoint,
StreamResponseAuthDomain::ReadFileStream,
url,
Method::GET,
auth_nonce,
)))
} else {
Ok(Box::new(reader))
}
}
async fn open_read_chunks(&self, request: ReadStreamRequest) -> Result<Option<ChunkReaderBox>> {
let url = build_read_file_stream_url(&request);
let auth_nonce = Uuid::new_v4();
let url = build_authenticated_read_file_stream_url(&request, auth_nonce);
let mut headers = json_headers();
build_auth_headers(&url, &Method::GET, &mut headers)?;
Ok(Some(Box::new(
HttpChunkReader::new_with_stall_timeout(url, Method::GET, headers, None, request.stall_timeout).await?,
)))
let reader =
HttpChunkReader::new_with_stall_timeout(url.clone(), Method::GET, headers, None, request.stall_timeout).await?;
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
Ok(Some(Box::new(AuthenticatedStreamReader::new(
reader,
request.endpoint,
StreamResponseAuthDomain::ReadFileStream,
url,
Method::GET,
auth_nonce,
))))
} else {
Ok(Some(Box::new(reader)))
}
}
async fn open_read_chunks_fresh(&self, request: ReadStreamRequest) -> Result<Option<ChunkReaderBox>> {
let url = build_read_file_stream_url(&request);
let auth_nonce = Uuid::new_v4();
let url = build_authenticated_read_file_stream_url(&request, auth_nonce);
let mut headers = json_headers();
build_auth_headers(&url, &Method::GET, &mut headers)?;
Ok(Some(Box::new(
HttpChunkReader::new_fresh_connection_with_stall_timeout(url, Method::GET, headers, None, request.stall_timeout)
.await?,
)))
let reader = HttpChunkReader::new_fresh_connection_with_stall_timeout(
url.clone(),
Method::GET,
headers,
None,
request.stall_timeout,
)
.await?;
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
Ok(Some(Box::new(AuthenticatedStreamReader::new(
reader,
request.endpoint,
StreamResponseAuthDomain::ReadFileStream,
url,
Method::GET,
auth_nonce,
))))
} else {
Ok(Some(Box::new(reader)))
}
}
async fn open_write(&self, request: WriteStreamRequest) -> Result<FileWriter> {
@@ -404,12 +728,25 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
}
async fn open_walk_dir(&self, request: WalkDirStreamRequest) -> Result<FileReader> {
let url = build_walk_dir_url(&request);
let auth_nonce = Uuid::new_v4();
let url = build_authenticated_walk_dir_url(&request, auth_nonce);
let mut headers = json_headers();
build_auth_headers(&url, &Method::GET, &mut headers)?;
Ok(Box::new(
HttpReader::new_with_stall_timeout(url, Method::GET, headers, Some(request.body), request.stall_timeout).await?,
))
let reader =
HttpReader::new_with_stall_timeout(url.clone(), Method::GET, headers, Some(request.body), request.stall_timeout)
.await?;
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
Ok(Box::new(AuthenticatedStreamReader::new(
reader,
request.endpoint,
StreamResponseAuthDomain::WalkDir,
url,
Method::GET,
auth_nonce,
)))
} else {
Ok(Box::new(reader))
}
}
async fn open_ns_scanner(&self, request: NsScannerStreamRequest) -> Result<FileReader> {
@@ -825,6 +1162,17 @@ pub(super) fn build_read_file_stream_url(request: &ReadStreamRequest) -> String
)
}
fn build_authenticated_read_file_stream_url(request: &ReadStreamRequest, auth_nonce: Uuid) -> String {
format!(
"{}&{}={}&{}={}",
build_read_file_stream_url(request),
STREAM_RESPONSE_AUTH_QUERY,
STREAM_RESPONSE_AUTH_V1,
STREAM_RESPONSE_AUTH_NONCE_QUERY,
auth_nonce
)
}
fn build_put_file_stream_url(request: &WriteStreamRequest, auth_scope: Option<(Uuid, Uuid)>) -> String {
let stream_path = if auth_scope.is_some() {
PUT_FILE_AUTH_STREAM_PATH
@@ -994,17 +1342,21 @@ where
}
}
fn build_walk_dir_url(request: &WalkDirStreamRequest) -> String {
fn build_authenticated_walk_dir_url(request: &WalkDirStreamRequest, auth_nonce: Uuid) -> String {
let body_sha256 = hex_simd::encode_to_string(Sha256::digest(&request.body), hex_simd::AsciiCase::Lower);
format!(
"{}{}?disk={}&{}={}&{}={}",
"{}{}?disk={}&{}={}&{}={}&{}={}&{}={}",
request.endpoint,
WALK_DIR_PATH,
urlencoding::encode(&request.disk),
WALK_DIR_STREAM_COMPLETION_QUERY,
WALK_DIR_STREAM_COMPLETION_V1,
WALK_DIR_BODY_SHA256_QUERY,
body_sha256
body_sha256,
STREAM_RESPONSE_AUTH_QUERY,
STREAM_RESPONSE_AUTH_V1,
STREAM_RESPONSE_AUTH_NONCE_QUERY,
auth_nonce
)
}
@@ -2634,19 +2986,25 @@ mod tests {
#[test]
fn walk_dir_url_encodes_disk_ref() {
let url = build_walk_dir_url(&WalkDirStreamRequest {
endpoint: "http://node1:9000".to_string(),
disk: "http://node1:9000/data/rustfs0".to_string(),
body: Vec::new(),
stall_timeout: None,
});
let auth_nonce = Uuid::parse_str("22222222-3333-4444-8555-666666666666").expect("auth nonce");
let url = build_authenticated_walk_dir_url(
&WalkDirStreamRequest {
endpoint: "http://node1:9000".to_string(),
disk: "http://node1:9000/data/rustfs0".to_string(),
body: Vec::new(),
stall_timeout: None,
},
auth_nonce,
);
assert_eq!(
url,
concat!(
"http://node1:9000/rustfs/rpc/walk_dir?disk=http%3A%2F%2Fnode1%3A9000%2Fdata%2Frustfs0",
"&walk_dir_stream_completion=error-v1",
"&walk_dir_body_sha256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
"&walk_dir_body_sha256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"&stream_auth=framed-v1",
"&stream_auth_nonce=22222222-3333-4444-8555-666666666666"
)
);
}
@@ -2871,4 +3229,297 @@ mod tests {
assert!(err.contains(ENV_RUSTFS_INTERNODE_DATA_TRANSPORT));
assert!(err.contains("unsupported-backend"));
}
#[tokio::test]
async fn authenticated_stream_reader_verifies_roundtrip_and_rejects_tamper_truncation_and_trailing() {
use crate::cluster::rpc::{encode_stream_auth_data_frame, encode_stream_auth_eof_frame};
use std::io::Cursor;
crate::runtime::sources::ensure_test_rpc_secret();
let nonce = Uuid::new_v4();
let url =
format!("http://127.0.0.1:9000/rustfs/rpc/read_file_stream?disk=d1&stream_auth=framed-v1&stream_auth_nonce={nonce}");
let part1 = b"chunk-one-";
let part2 = b"chunk-two";
let mut combined = Vec::new();
combined.extend_from_slice(part1);
combined.extend_from_slice(part2);
let frame0 = encode_stream_auth_data_frame(StreamResponseAuthDomain::ReadFileStream, &url, &Method::GET, nonce, 0, part1)
.expect("frame 0");
let frame1 = encode_stream_auth_data_frame(StreamResponseAuthDomain::ReadFileStream, &url, &Method::GET, nonce, 1, part2)
.expect("frame 1");
let digest: [u8; 32] = Sha256::digest(&combined).into();
let eof = encode_stream_auth_eof_frame(
StreamResponseAuthDomain::ReadFileStream,
&url,
&Method::GET,
nonce,
2,
combined.len() as u64,
&digest,
)
.expect("eof");
let mut wire = Vec::new();
wire.extend_from_slice(&frame0);
wire.extend_from_slice(&frame1);
wire.extend_from_slice(&eof);
let test_endpoint = format!("http://auth-reader-test-{}.invalid:9000", Uuid::new_v4());
// 1. Valid multi-frame stream succeeds via AsyncRead.
let mut reader = AuthenticatedStreamReader::new(
Cursor::new(wire.clone()),
test_endpoint.clone(),
StreamResponseAuthDomain::ReadFileStream,
url.clone(),
Method::GET,
nonce,
);
let mut out = Vec::new();
reader.read_to_end(&mut out).await.expect("valid stream should read");
assert_eq!(out, combined);
// 2. Valid multi-frame stream succeeds via ChunkReader.
let mut chunk_reader = AuthenticatedStreamReader::new(
Cursor::new(wire.clone()),
test_endpoint.clone(),
StreamResponseAuthDomain::ReadFileStream,
url.clone(),
Method::GET,
nonce,
);
let mut chunked = Vec::new();
while let Some(chunk) = std::future::poll_fn(|cx| Pin::new(&mut chunk_reader).poll_read_chunk(cx, 5))
.await
.expect("valid chunk read")
{
chunked.extend_from_slice(&chunk);
}
assert_eq!(chunked, combined);
// 3. Single flipped payload byte fails closed BEFORE returning tampered bytes.
let mut tampered = wire.clone();
tampered[STREAM_RESPONSE_DATA_HEADER_LEN] ^= 0xff;
let mut bad_reader = AuthenticatedStreamReader::new(
Cursor::new(tampered),
test_endpoint.clone(),
StreamResponseAuthDomain::ReadFileStream,
url.clone(),
Method::GET,
nonce,
);
let mut bad_out = Vec::new();
let err = bad_reader
.read_to_end(&mut bad_out)
.await
.expect_err("tampered payload must fail closed");
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
assert!(bad_out.is_empty(), "tampered frame must not emit unverified bytes");
// 4. Truncated stream (missing EOF frame) fails closed with UnexpectedEof.
let truncated = wire[..frame0.len() + frame1.len()].to_vec();
let mut trunc_reader = AuthenticatedStreamReader::new(
Cursor::new(truncated),
test_endpoint.clone(),
StreamResponseAuthDomain::ReadFileStream,
url.clone(),
Method::GET,
nonce,
);
let mut trunc_out = Vec::new();
let err = trunc_reader
.read_to_end(&mut trunc_out)
.await
.expect_err("missing EOF frame must fail closed");
assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
// 5. Trailing garbage after EOF frame fails closed.
let mut trailing = wire.clone();
trailing.extend_from_slice(b"junk");
let mut trail_reader = AuthenticatedStreamReader::new(
Cursor::new(trailing),
test_endpoint.clone(),
StreamResponseAuthDomain::ReadFileStream,
url.clone(),
Method::GET,
nonce,
);
let mut trail_out = Vec::new();
let err = trail_reader
.read_to_end(&mut trail_out)
.await
.expect_err("trailing bytes after EOF frame must fail closed");
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
STREAM_AUTH_PINNED_ENDPOINTS
.write()
.remove(&normalize_stream_auth_endpoint(&test_endpoint));
}
#[tokio::test]
async fn rolling_back_one_peer_requires_the_pinned_caller_to_restart() {
use bytes::Bytes;
use http_body_util::Full;
use hyper::{server::conn::http1, service::service_fn};
use hyper_util::rt::TokioIo;
crate::runtime::sources::ensure_test_rpc_secret();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let endpoint = format!("http://{}", listener.local_addr().unwrap());
let peer = endpoint.clone();
let server = tokio::spawn(async move {
for signed in [false, true, false, false, false] {
let (socket, _) = listener.accept().await.unwrap();
let peer = peer.clone();
let service = service_fn(move |request: http::Request<hyper::body::Incoming>| {
let mut response = http::Response::builder();
let body = if signed {
let url = format!("{peer}{}", request.uri());
let parsed = url::Url::parse(&url).unwrap();
let nonce = parsed
.query_pairs()
.find(|(key, _)| key == STREAM_RESPONSE_AUTH_NONCE_QUERY)
.unwrap()
.1
.parse()
.unwrap();
response = response.header(STREAM_RESPONSE_AUTH_HEADER, STREAM_RESPONSE_AUTH_V1);
let digest = Sha256::digest([]).into();
Bytes::copy_from_slice(
&crate::cluster::rpc::encode_stream_auth_eof_frame(
StreamResponseAuthDomain::ReadFileStream,
&url,
request.method(),
nonce,
0,
0,
&digest,
)
.unwrap(),
)
} else {
Bytes::new()
};
async move { Ok::<_, std::convert::Infallible>(response.body(Full::new(body)).unwrap()) }
});
http1::Builder::new()
.keep_alive(false)
.serve_connection(TokioIo::new(socket), service)
.await
.unwrap();
}
});
let transport = TcpHttpInternodeDataTransport;
let read = || ReadStreamRequest {
endpoint: endpoint.clone(),
disk: "disk-a".into(),
volume: "bucket".into(),
path: "part.1".into(),
offset: 0,
length: 0,
stall_timeout: Some(Duration::from_secs(2)),
};
let walk = || WalkDirStreamRequest {
endpoint: endpoint.clone(),
disk: "disk-a".into(),
body: b"{}".to_vec(),
stall_timeout: Some(Duration::from_secs(2)),
};
tokio::time::timeout(Duration::from_secs(10), async {
for _ in 0..2 {
let mut reader = transport.open_read(read()).await.unwrap();
assert_eq!(reader.read_to_end(&mut Vec::new()).await.unwrap(), 0);
}
let read_error = transport
.open_read(read())
.await
.err()
.expect("rolled-back reads must fail on the pinned caller");
let walk_error = transport
.open_walk_dir(walk())
.await
.err()
.expect("rolled-back walks must fail on the pinned caller");
for error in [read_error, walk_error] {
assert!(error.to_string().contains("downgraded"), "{error}");
}
// A caller restart clears its in-memory peer pins.
assert!(
STREAM_AUTH_PINNED_ENDPOINTS
.write()
.remove(&normalize_stream_auth_endpoint(&endpoint))
);
let mut reader = transport.open_walk_dir(walk()).await.unwrap();
assert_eq!(reader.read_to_end(&mut Vec::new()).await.unwrap(), 0);
server.await.unwrap();
})
.await
.expect("rolling peer fixture must finish");
}
#[tokio::test]
async fn stream_response_auth_pins_peer_only_after_crypto_verification_and_blocks_downgrade() {
use crate::cluster::rpc::encode_stream_auth_eof_frame;
use std::io::Cursor;
crate::runtime::sources::ensure_test_rpc_secret();
let endpoint = format!("http://pin-stream-test-{}.invalid:9000", Uuid::new_v4());
let empty = HeaderMap::new();
assert!(
!should_authenticate_response_stream(&endpoint, &empty, false)
.expect("unpinned legacy peer allowed when strict is off")
);
assert!(
should_authenticate_response_stream(&endpoint, &empty, true).is_err(),
"strict mode must reject missing stream auth header"
);
// Header alone must NOT pin the endpoint before a frame cryptographically verifies
// (prevents an unauthenticated on-path attacker from DoS-pinning a legacy peer).
let mut valid_headers = HeaderMap::new();
valid_headers.insert(STREAM_RESPONSE_AUTH_HEADER, HeaderValue::from_static(STREAM_RESPONSE_AUTH_V1));
assert!(should_authenticate_response_stream(&endpoint, &valid_headers, false).expect("valid header should enable auth"));
assert!(
!should_authenticate_response_stream(&endpoint, &empty, false)
.expect("header without verified MAC must not pin legacy peer")
);
// Duplicate or unknown header values fail closed.
let mut dup_headers = valid_headers.clone();
dup_headers.append(STREAM_RESPONSE_AUTH_HEADER, HeaderValue::from_static(STREAM_RESPONSE_AUTH_V1));
assert!(should_authenticate_response_stream(&endpoint, &dup_headers, false).is_err());
let mut unknown_headers = HeaderMap::new();
unknown_headers.insert(STREAM_RESPONSE_AUTH_HEADER, HeaderValue::from_static("framed-v99"));
assert!(should_authenticate_response_stream(&endpoint, &unknown_headers, false).is_err());
// Once a peer proves possession of the RPC secret with a valid authenticated stream,
// it is pinned (case/trailing-slash normalized) and header stripping is rejected.
let nonce = Uuid::new_v4();
let url = format!("{endpoint}/rustfs/rpc/walk_dir?disk=d1&stream_auth=framed-v1&stream_auth_nonce={nonce}");
let empty_digest: [u8; 32] = Sha256::digest([]).into();
let eof = encode_stream_auth_eof_frame(StreamResponseAuthDomain::WalkDir, &url, &Method::GET, nonce, 0, 0, &empty_digest)
.expect("empty EOF");
let mut reader = AuthenticatedStreamReader::new(
Cursor::new(eof.to_vec()),
endpoint.clone(),
StreamResponseAuthDomain::WalkDir,
url,
Method::GET,
nonce,
);
let mut out = Vec::new();
reader.read_to_end(&mut out).await.expect("verified empty stream");
assert!(out.is_empty());
let variant = format!("{}/", endpoint.to_ascii_uppercase());
assert!(
should_authenticate_response_stream(&variant, &empty, false).is_err(),
"stripping auth header from a cryptographically pinned peer must be rejected as a downgrade"
);
STREAM_AUTH_PINNED_ENDPOINTS
.write()
.remove(&normalize_stream_auth_endpoint(&endpoint));
}
}
+19 -16
View File
@@ -36,22 +36,25 @@ pub use client::{
// Re-exported through `api::rpc`; not every item is consumed inside this crate.
#[allow(unused_imports)]
pub use http_auth::{
RPC_BACKGROUND_ADMISSION_HEADER, RpcReplayCacheAdmissionError, TONIC_RPC_PREFIX, build_auth_headers,
build_put_file_auth_trailer, check_and_record_signed_rpc_nonce, gen_signature_headers, gen_tonic_replay_scope_headers,
gen_tonic_signature_headers, normalize_tonic_rpc_audience, rpc_auth_is_resource_exhausted, rpc_background_admission,
set_tonic_canonical_body_digest, set_tonic_mutation_body_digest, set_tonic_rolling_canonical_body_digest,
set_tonic_rolling_mutation_body_digest, sign_ns_scanner_capability, sign_ns_scanner_capability_with_checkpoint_coverage,
sign_ns_scanner_capability_with_durable_progress, sign_ns_scanner_capability_with_tier_registry_generation,
sign_ns_scanner_capability_with_usage_capabilities, sign_ns_scanner_tier_registry_preflight_capability,
sign_ns_scanner_usage_watch_capability, sign_put_file_capability, sign_tonic_rpc_response_proof, tonic_boot_epoch_challenge,
tonic_boot_epoch_response_headers, tonic_boot_epoch_response_headers_with_msgpack_capability,
tonic_msgpack_manifest_capability_requested, tonic_rpc_auth_failure_reason, verify_ns_scanner_capability,
verify_ns_scanner_capability_with_checkpoint_coverage, verify_ns_scanner_capability_with_durable_progress,
verify_ns_scanner_capability_with_tier_registry_generation, verify_ns_scanner_capability_with_usage_capabilities,
verify_ns_scanner_tier_registry_preflight_capability, verify_ns_scanner_usage_watch_capability, verify_put_file_auth_trailer,
verify_put_file_capability, verify_rpc_signature, verify_tonic_boot_epoch_response, verify_tonic_canonical_body_digest,
verify_tonic_mutation_body_digest, verify_tonic_mutation_body_digest_reject_unsigned, verify_tonic_rpc_response_proof,
verify_tonic_rpc_signature, verify_tonic_rpc_signature_with_bootstrap,
RPC_BACKGROUND_ADMISSION_HEADER, RpcReplayCacheAdmissionError, StreamResponseAuthDomain, TONIC_RPC_PREFIX,
build_auth_headers, build_put_file_auth_trailer, check_and_record_signed_rpc_nonce,
check_and_record_signed_rpc_nonce_for_peer, encode_stream_auth_data_frame, encode_stream_auth_eof_frame,
gen_signature_headers, gen_tonic_replay_scope_headers, gen_tonic_signature_headers, normalize_tonic_rpc_audience,
rpc_auth_is_resource_exhausted, rpc_background_admission, set_tonic_canonical_body_digest, set_tonic_mutation_body_digest,
set_tonic_rolling_canonical_body_digest, set_tonic_rolling_mutation_body_digest, sign_ns_scanner_capability,
sign_ns_scanner_capability_with_checkpoint_coverage, sign_ns_scanner_capability_with_durable_progress,
sign_ns_scanner_capability_with_tier_registry_generation, sign_ns_scanner_capability_with_usage_capabilities,
sign_ns_scanner_tier_registry_preflight_capability, sign_ns_scanner_usage_watch_capability, sign_put_file_capability,
sign_tonic_rpc_response_proof, tonic_boot_epoch_challenge, tonic_boot_epoch_response_headers,
tonic_boot_epoch_response_headers_with_msgpack_capability, tonic_msgpack_manifest_capability_requested,
tonic_rpc_auth_failure_reason, verify_ns_scanner_capability, verify_ns_scanner_capability_with_checkpoint_coverage,
verify_ns_scanner_capability_with_durable_progress, verify_ns_scanner_capability_with_tier_registry_generation,
verify_ns_scanner_capability_with_usage_capabilities, verify_ns_scanner_tier_registry_preflight_capability,
verify_ns_scanner_usage_watch_capability, verify_put_file_auth_trailer, verify_put_file_capability, verify_rpc_signature,
verify_stream_auth_data_frame, verify_stream_auth_eof_frame, verify_tonic_boot_epoch_response,
verify_tonic_canonical_body_digest, verify_tonic_mutation_body_digest, verify_tonic_mutation_body_digest_reject_unsigned,
verify_tonic_rpc_response_proof, verify_tonic_rpc_signature, verify_tonic_rpc_signature_with_bootstrap,
verify_tonic_rpc_signature_with_bootstrap_and_peer,
};
#[cfg(test)]
pub(crate) use internode_data_transport::TcpHttpInternodeDataTransport;
@@ -254,6 +254,21 @@ fn pool_write_quorum(participant_count: usize) -> usize {
/// dominant error into `ErasureWriteQuorum`.
///
/// `peer_rest_client` carries the same helper over `StorageError` for the same response shape.
fn decode_bucket_infos(bucket_infos: Vec<String>) -> Result<Vec<BucketInfo>> {
bucket_infos
.into_iter()
.enumerate()
.map(|(index, json_str)| {
serde_json::from_str::<BucketInfo>(&json_str).map_err(|err| {
Error::Io(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("decode BucketInfo entry {index} failed: {err}"),
))
})
})
.collect()
}
fn peer_failure_without_details(op: &str, bucket: Option<&str>) -> Error {
match bucket {
Some(bucket) => Error::other(format!("{op}({bucket}): peer returned failure without error details")),
@@ -1329,11 +1344,7 @@ impl PeerS3Client for RemotePeerS3Client {
Err(peer_failure_without_details("list_bucket", None))
};
}
let bucket_infos = response
.bucket_infos
.into_iter()
.filter_map(|json_str| serde_json::from_str::<BucketInfo>(&json_str).ok())
.collect();
let bucket_infos = decode_bucket_infos(response.bucket_infos)?;
Ok(bucket_infos)
},
@@ -3067,4 +3078,25 @@ mod tests {
peer_failure_without_details("get_bucket_info", Some("shared"))
);
}
#[test]
fn decode_bucket_infos_rejects_malformed_entry_instead_of_dropping() {
let valid = BucketInfo {
name: "alpha".to_string(),
created: None,
deleted: None,
versioning: false,
object_locking: false,
};
let encoded = serde_json::to_string(&valid).expect("valid bucket info should serialize");
let decoded = decode_bucket_infos(vec![encoded.clone()]).expect("valid list should decode");
assert_eq!(decoded.len(), 1);
assert_eq!(decoded[0].name, "alpha");
let err = decode_bucket_infos(vec![encoded, "{not-valid-json".to_string()])
.expect_err("malformed BucketInfo entry must fail closed");
let msg = err.to_string();
assert!(msg.contains("entry 1"), "error must identify failing index: {msg}");
}
}
@@ -48,7 +48,7 @@ use rustfs_s3_client::{
transition_api::{ReadCloser, ReaderImpl},
};
use rustfs_scanner_metrics::metrics::{TierRequestOperation, TierRequestOutcome, global_metrics};
use rustfs_utils::egress::validate_outbound_url;
use rustfs_utils::egress::OutboundPolicy;
use rustfs_utils::http::headers::{
CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_TYPE, EXPIRES, HeaderExt as _,
};
@@ -309,6 +309,42 @@ pub fn build_transition_put_options(storage_class: String, mut metadata: HashMap
opts
}
/// Outbound address policy enforced at both URL validation and connection-time DNS resolution
/// for S3-compatible warm backends.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TierEndpointPolicy {
/// Cloud object stores: public destinations only unless explicitly allowlisted via
/// `RUSTFS_OUTBOUND_ALLOW_ORIGINS`.
PublicOnly,
/// Self-hosted S3-compatible tiers (MinIO, S3): public and non-metadata RFC1918/ULA
/// private destinations allowed; loopback, link-local, metadata, and special-use blocked.
AllowPrivate,
/// RustFS tier: private destinations allowed plus debug-only env-gated loopback for tests.
AllowPrivateAndDebugLoopback { allow_loopback: bool },
}
impl TierEndpointPolicy {
pub(crate) fn build_resolver(
self,
url: &url::Url,
virtual_bucket: Option<&str>,
) -> Result<rustfs_utils::egress::OutboundDnsResolver, rustfs_utils::egress::OutboundPolicyError> {
match self {
Self::PublicOnly => {
let policy = OutboundPolicy::from_env_cached()?;
match virtual_bucket {
Some(bucket) => policy.resolver_for_virtual_bucket(url, bucket),
None => policy.resolver_for(url),
}
}
Self::AllowPrivate => OutboundPolicy::default().resolver_for_allow_private(url),
Self::AllowPrivateAndDebugLoopback { allow_loopback } => {
OutboundPolicy::default().resolver_for_storage_endpoint(url, true, allow_loopback)
}
}
}
}
/// Connection parameters every S3-compatible warm backend provider supplies.
///
/// The Aliyun, legacy Azure, Huaweicloud, Tencent, MinIO, R2, and RustFS backends all
@@ -328,11 +364,8 @@ pub(crate) struct S3CompatibleWarmBackendParams<'a> {
/// Tag handed to [`TransitionClient::new`] so per-provider client behavior
/// and metrics stay attributable.
pub provider_tag: &'a str,
/// SSRF guard run against the parsed endpoint once it's known to have a
/// host. Cloud providers use [`rustfs_utils::egress::validate_outbound_url`];
/// MinIO allows private storage endpoints, and RustFS additionally wraps
/// that policy with its debug-only, env-gated loopback exception.
pub validate_endpoint: fn(&url::Url) -> Result<(), rustfs_utils::egress::OutboundUrlError>,
/// Connection-time DNS and URL SSRF policy for this tier provider.
pub endpoint_policy: TierEndpointPolicy,
}
/// A bucket can become a host prefix or the first path segment. Keep legacy
@@ -420,6 +453,13 @@ pub(crate) async fn new_s3_compatible_warm_backend(
..Default::default()
}));
let timeouts = transition_client_timeouts_from_env();
let endpoint = endpoint_authority(&u)?;
// Run the SSRF guard after the host-presence check so a host-less endpoint
// keeps this constructor's stable error text.
let dns_resolver = params
.endpoint_policy
.build_resolver(&u, (params.bucket_lookup == BucketLookupType::BucketLookupDNS).then_some(params.bucket))
.map_err(|err| std::io::Error::other(format!("tier endpoint is not allowed: {err}")))?;
let opts = Options {
creds,
secure: u.scheme() == "https",
@@ -428,11 +468,7 @@ pub(crate) async fn new_s3_compatible_warm_backend(
bucket_lookup: params.bucket_lookup,
..Default::default()
};
let endpoint = endpoint_authority(&u)?;
// Run the SSRF guard after the host-presence check so a host-less endpoint
// keeps this constructor's stable error text.
(params.validate_endpoint)(&u).map_err(|err| std::io::Error::other(format!("tier endpoint is not allowed: {err}")))?;
let client = TransitionClient::new_with_timeouts(&endpoint, opts, params.provider_tag, timeouts).await?;
let client = TransitionClient::new_with_dns_resolver(&endpoint, opts, params.provider_tag, timeouts, dns_resolver).await?;
let client = Arc::new(client);
let core = TransitionCore(Arc::clone(&client));
@@ -445,6 +481,19 @@ pub(crate) async fn new_s3_compatible_warm_backend(
})
}
#[cfg(test)]
pub(super) async fn fixture_transition_client(
endpoint: &str,
options: Options,
provider: &str,
) -> std::io::Result<TransitionClient<rustfs_s3_client::transition_api::TierConnector>> {
let url = url::Url::parse(&format!("http://{endpoint}")).unwrap();
let resolver = OutboundPolicy::default()
.resolver_for_storage_endpoint(&url, true, true)
.unwrap();
TransitionClient::new_with_dns_resolver(endpoint, options, provider, TransitionClientTimeouts::default(), resolver).await
}
/// Round the multipart part size up to a whole multiple of `min_part_size` that
/// keeps the upload within [`MAX_PARTS_COUNT`] parts.
///
@@ -2001,7 +2050,7 @@ mod tests {
region: "us-east-1",
bucket_lookup: BucketLookupType::BucketLookupDNS,
provider_tag: "aliyun",
validate_endpoint: validate_outbound_url,
endpoint_policy: TierEndpointPolicy::PublicOnly,
}
}
@@ -21,13 +21,12 @@ use std::collections::HashMap;
use crate::services::tier::{
tier_config::TierAliyun,
warm_backend::{
S3CompatibleWarmBackendParams, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts, build_transition_put_options,
new_s3_compatible_warm_backend, optimal_part_size,
S3CompatibleWarmBackendParams, TierEndpointPolicy, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts,
build_transition_put_options, new_s3_compatible_warm_backend, optimal_part_size,
},
warm_backend_s3::WarmBackendS3,
};
use rustfs_s3_client::transition_api::{BucketLookupType, ReadCloser, ReaderImpl};
use rustfs_utils::egress::validate_outbound_url;
const MIN_PART_SIZE: i64 = 1024 * 1024 * 128;
@@ -45,7 +44,7 @@ impl WarmBackendAliyun {
region: &conf.region,
bucket_lookup: BucketLookupType::BucketLookupDNS,
provider_tag: "aliyun",
validate_endpoint: validate_outbound_url,
endpoint_policy: TierEndpointPolicy::PublicOnly,
})
.await?,
))
@@ -21,13 +21,12 @@ use std::collections::HashMap;
use crate::services::tier::{
tier_config::TierAzure,
warm_backend::{
S3CompatibleWarmBackendParams, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts, build_transition_put_options,
new_s3_compatible_warm_backend, optimal_part_size,
S3CompatibleWarmBackendParams, TierEndpointPolicy, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts,
build_transition_put_options, new_s3_compatible_warm_backend, optimal_part_size,
},
warm_backend_s3::WarmBackendS3,
};
use rustfs_s3_client::transition_api::{BucketLookupType, ReadCloser, ReaderImpl};
use rustfs_utils::egress::validate_outbound_url;
const MIN_PART_SIZE: i64 = 1024 * 1024 * 128;
@@ -45,7 +44,7 @@ impl WarmBackendAzure {
region: &conf.region,
bucket_lookup: BucketLookupType::BucketLookupDNS,
provider_tag: "azure",
validate_endpoint: validate_outbound_url,
endpoint_policy: TierEndpointPolicy::PublicOnly,
})
.await?,
))
@@ -108,7 +107,7 @@ mod tests {
use crate::services::tier::tier_config::TierAzure;
use rustfs_s3_client::{
credentials::{Credentials, SignatureType, Static, Value},
transition_api::{Options, TransitionClient, TransitionCore},
transition_api::{Options, TransitionCore},
};
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -175,7 +174,7 @@ mod tests {
(get_request, delete_request)
});
let client = Arc::new(
TransitionClient::new(
super::super::warm_backend::fixture_transition_client(
&endpoint,
Options {
creds: Credentials::new(Static(Value {
@@ -37,7 +37,7 @@ use quick_xml::{Reader, events::Event};
use rustfs_s3_client::transition_api::{ReadCloser, ReaderImpl};
use rustfs_signer::azure_shared_key_signature;
use rustfs_utils::crypto::hex;
use rustfs_utils::egress::validate_outbound_url;
use rustfs_utils::egress::OutboundPolicy;
use rustfs_utils::hash::FastMd5;
use rustfs_utils::http::metadata_compat::{
MINIO_INTERNAL_PREFIX, SUFFIX_TRANSITION_TIER_DESTINATION_ID, SUFFIX_TRANSITION_TRANSACTION_ID, internal_key_rustfs,
@@ -119,13 +119,19 @@ impl WarmBackendAzureBlob {
"Azure Blob endpoint must be an HTTP(S) origin without credentials, path or query",
));
}
validate_outbound_url(&endpoint).map_err(|_| invalid_input("Azure Blob endpoint is not allowed"))?;
let outbound_policy =
OutboundPolicy::from_env_cached().map_err(|_| invalid_input("Azure Blob outbound policy is invalid"))?;
let dns_resolver = outbound_policy
.resolver_for(&endpoint)
.map_err(|_| invalid_input("Azure Blob endpoint is not allowed"))?;
let key = decode_key(&conf.secret_key)?;
rustfs_tls_runtime::ensure_crypto_provider().map_err(io::Error::other)?;
let timeouts = transition_client_timeouts_from_env();
let client = reqwest::Client::builder()
.connect_timeout(timeouts.connect_timeout)
.read_timeout(timeouts.response_body_idle_timeout)
.no_proxy()
.dns_resolver(dns_resolver)
.redirect(reqwest::redirect::Policy::none())
.retry(reqwest::retry::never())
.no_gzip()
@@ -37,7 +37,6 @@ use rustfs_s3_client::{
api_put_object::PutObjectOptions,
transition_api::{Options, ReadCloser, ReaderImpl},
};
use rustfs_utils::egress::validate_outbound_url;
use tracing::warn;
const _MAX_PART_SIZE: i64 = 1024 * 1024 * 1024 * 5;
@@ -135,6 +134,21 @@ where
})
}
const GCS_SERVICE_ENDPOINT: &str = "https://storage.googleapis.com";
fn gcs_service_endpoint(configured: &str) -> std::io::Result<&'static str> {
// Both SDK clients resolve hosts internally. Only pass the fixed Google origin to them.
if configured.is_empty()
|| url::Url::parse(configured).is_ok_and(|url| url.as_str().strip_suffix('/') == Some(GCS_SERVICE_ENDPOINT))
{
return Ok(GCS_SERVICE_ENDPOINT);
}
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"custom GCS tier endpoint is not allowed; omit the endpoint or use https://storage.googleapis.com",
))
}
pub struct WarmBackendGCS {
pub client: Arc<Storage>,
pub control: Arc<StorageControl>,
@@ -152,11 +166,7 @@ impl WarmBackendGCS {
return Err(std::io::Error::other("no bucket name was provided"));
}
if !conf.endpoint.is_empty() {
let endpoint_url = url::Url::parse(&conf.endpoint).map_err(|e| std::io::Error::other(e.to_string()))?;
validate_outbound_url(&endpoint_url)
.map_err(|err| std::io::Error::other(format!("tier endpoint is not allowed: {err}")))?;
}
let endpoint = gcs_service_endpoint(&conf.endpoint)?;
let service_account = serde_json::from_str(&conf.creds)?;
let credentials = Builder::new(service_account)
@@ -165,21 +175,16 @@ impl WarmBackendGCS {
.build()
.map_err(|e| std::io::Error::other(format!("Invalid credentials JSON: {}", e)))?;
let Ok(client) = Storage::builder()
.with_endpoint(conf.endpoint.clone())
let data_builder = Storage::builder()
.with_credentials(credentials.clone())
.build()
.await
else {
.with_endpoint(endpoint);
let control_builder = StorageControl::builder()
.with_credentials(credentials)
.with_endpoint(endpoint);
let Ok(client) = data_builder.build().await else {
return Err(std::io::Error::other("Storage::builder error"));
};
let client = Arc::new(client);
// Control-plane client: the data-plane `Storage` client cannot delete or list objects;
// delete_object/list_objects live on StorageControl.
let mut control_builder = StorageControl::builder().with_credentials(credentials);
if !conf.endpoint.is_empty() {
control_builder = control_builder.with_endpoint(conf.endpoint.clone());
}
let Ok(control) = control_builder.build().await else {
return Err(std::io::Error::other("StorageControl::builder error"));
};
@@ -718,6 +723,27 @@ mod tests {
);
}
#[test]
fn native_gcs_tier_uses_only_the_google_storage_origin() {
for configured in ["", "https://storage.googleapis.com", "https://STORAGE.GOOGLEAPIS.COM:443/"] {
assert_eq!(super::gcs_service_endpoint(configured).unwrap(), super::GCS_SERVICE_ENDPOINT);
}
for configured in [
"https://storage.gcs.example.test",
"http://storage.googleapis.com",
"https://storage.googleapis.com:8443",
"https://storage.googleapis.com/other",
"https://storage.googleapis.com/?endpoint=other",
"https://user@storage.googleapis.com",
] {
assert_eq!(
super::gcs_service_endpoint(configured).unwrap_err().kind(),
std::io::ErrorKind::InvalidInput,
"{configured}"
);
}
}
#[tokio::test]
async fn new_rejects_loopback_endpoint_before_credential_setup() {
let conf = TierGCS {
@@ -21,13 +21,12 @@ use std::collections::HashMap;
use crate::services::tier::{
tier_config::TierHuaweicloud,
warm_backend::{
S3CompatibleWarmBackendParams, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts, build_transition_put_options,
new_s3_compatible_warm_backend, optimal_part_size,
S3CompatibleWarmBackendParams, TierEndpointPolicy, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts,
build_transition_put_options, new_s3_compatible_warm_backend, optimal_part_size,
},
warm_backend_s3::WarmBackendS3,
};
use rustfs_s3_client::transition_api::{BucketLookupType, ReadCloser, ReaderImpl};
use rustfs_utils::egress::validate_outbound_url;
const MIN_PART_SIZE: i64 = 1024 * 1024 * 128;
@@ -45,7 +44,7 @@ impl WarmBackendHuaweicloud {
region: &conf.region,
bucket_lookup: BucketLookupType::BucketLookupDNS,
provider_tag: "huaweicloud",
validate_endpoint: validate_outbound_url,
endpoint_policy: TierEndpointPolicy::PublicOnly,
})
.await?,
))
@@ -21,13 +21,12 @@ use std::collections::HashMap;
use crate::services::tier::{
tier_config::TierMinIO,
warm_backend::{
S3CompatibleWarmBackendParams, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts, build_transition_put_options,
new_s3_compatible_warm_backend, optimal_part_size,
S3CompatibleWarmBackendParams, TierEndpointPolicy, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts,
build_transition_put_options, new_s3_compatible_warm_backend, optimal_part_size,
},
warm_backend_s3::WarmBackendS3,
};
use rustfs_s3_client::transition_api::{BucketLookupType, ReadCloser, ReaderImpl};
use rustfs_utils::egress::validate_outbound_url_allow_private;
const _MAX_PART_SIZE: i64 = 1024 * 1024 * 1024 * 5;
const MIN_PART_SIZE: i64 = 1024 * 1024 * 128;
@@ -48,7 +47,7 @@ impl WarmBackendMinIO {
// `BucketLookupAuto`; pinning DNS here would break those deployments.
bucket_lookup: BucketLookupType::BucketLookupAuto,
provider_tag: "minio",
validate_endpoint: validate_outbound_url_allow_private,
endpoint_policy: TierEndpointPolicy::AllowPrivate,
})
.await?,
))
@@ -21,13 +21,12 @@ use std::collections::HashMap;
use crate::services::tier::{
tier_config::TierR2,
warm_backend::{
S3CompatibleWarmBackendParams, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts, build_transition_put_options,
new_s3_compatible_warm_backend, optimal_part_size,
S3CompatibleWarmBackendParams, TierEndpointPolicy, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts,
build_transition_put_options, new_s3_compatible_warm_backend, optimal_part_size,
},
warm_backend_s3::WarmBackendS3,
};
use rustfs_s3_client::transition_api::{BucketLookupType, ReadCloser, ReaderImpl};
use rustfs_utils::egress::validate_outbound_url;
const _MAX_PART_SIZE: i64 = 1024 * 1024 * 1024 * 5;
const MIN_PART_SIZE: i64 = 1024 * 1024 * 128;
@@ -48,7 +47,7 @@ impl WarmBackendR2 {
// `BucketLookupAuto`; pinning DNS here would break those deployments.
bucket_lookup: BucketLookupType::BucketLookupAuto,
provider_tag: "r2",
validate_endpoint: validate_outbound_url,
endpoint_policy: TierEndpointPolicy::PublicOnly,
})
.await?,
))
@@ -21,35 +21,30 @@ use std::collections::HashMap;
use crate::services::tier::{
tier_config::TierRustFS,
warm_backend::{
S3CompatibleWarmBackendParams, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts, build_transition_put_options,
new_s3_compatible_warm_backend, optimal_part_size,
S3CompatibleWarmBackendParams, TierEndpointPolicy, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts,
build_transition_put_options, new_s3_compatible_warm_backend, optimal_part_size,
},
warm_backend_s3::WarmBackendS3,
};
use rustfs_s3_client::transition_api::{BucketLookupType, ReadCloser, ReaderImpl};
use rustfs_utils::egress::{OutboundUrlError, validate_outbound_url_allow_private};
#[cfg(test)]
use rustfs_utils::egress::{OutboundPolicy, OutboundPolicyError};
const _MAX_PART_SIZE: i64 = 1024 * 1024 * 1024 * 5;
const MIN_PART_SIZE: i64 = 1024 * 1024 * 128;
// Debug-only opt-in for single-host test/dev setups; release builds always reject loopback.
const ALLOW_LOOPBACK_TIER_ENDPOINT_ENV: &str = "RUSTFS_TIER_RUSTFS_ALLOW_LOOPBACK_ENDPOINT";
fn validate_rustfs_tier_endpoint(url: &url::Url) -> Result<(), OutboundUrlError> {
let allow_loopback = cfg!(debug_assertions)
fn allow_loopback_rustfs_tier_endpoint() -> bool {
cfg!(debug_assertions)
&& std::env::var(ALLOW_LOOPBACK_TIER_ENDPOINT_ENV)
.map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
.unwrap_or(false);
validate_rustfs_tier_endpoint_inner(url, allow_loopback)
.unwrap_or(false)
}
fn validate_rustfs_tier_endpoint_inner(url: &url::Url, allow_loopback: bool) -> Result<(), OutboundUrlError> {
match validate_outbound_url_allow_private(url) {
Err(OutboundUrlError::ForbiddenHost {
reason: "loopback address" | "loopback host",
..
}) if allow_loopback => Ok(()),
result => result,
}
#[cfg(test)]
fn validate_rustfs_tier_endpoint_inner(url: &url::Url, allow_loopback: bool) -> Result<(), OutboundPolicyError> {
OutboundPolicy::default().validate_storage_url(url, true, allow_loopback)
}
pub struct WarmBackendRustFS(WarmBackendS3);
@@ -92,7 +87,9 @@ impl WarmBackendRustFS {
provider_tag: "rustfs",
// Private storage endpoints are allowed; loopback remains a debug-only,
// env-gated exception for this provider's own e2e tier tests.
validate_endpoint: validate_rustfs_tier_endpoint,
endpoint_policy: TierEndpointPolicy::AllowPrivateAndDebugLoopback {
allow_loopback: allow_loopback_rustfs_tier_endpoint(),
},
})
.await?,
))
@@ -42,12 +42,12 @@ use rustfs_s3_client::{
transition_api::{BucketLookupType, ObjectInfo, Options, TransitionClient, TransitionCore},
transition_api::{ReadCloser, ReaderImpl},
};
use rustfs_utils::egress::validate_outbound_url_allow_private;
use rustfs_utils::egress::OutboundPolicy;
use rustfs_utils::path::SLASH_SEPARATOR;
pub struct WarmBackendS3 {
pub client: Arc<TransitionClient>,
pub core: TransitionCore,
pub client: Arc<TransitionClient<rustfs_s3_client::transition_api::TierConnector>>,
pub core: TransitionCore<rustfs_s3_client::transition_api::TierConnector>,
pub bucket: String,
pub prefix: String,
pub storage_class: String,
@@ -103,7 +103,8 @@ impl WarmBackendS3 {
return Err(std::io::Error::other(err.to_string()));
}
};
validate_outbound_url_allow_private(&u)
let dns_resolver = OutboundPolicy::default()
.resolver_for_allow_private(&u)
.map_err(|err| std::io::Error::other(format!("tier endpoint is not allowed: {err}")))?;
let has_web_identity_token_file = !conf.aws_role_web_identity_token_file.is_empty();
@@ -143,7 +144,7 @@ impl WarmBackendS3 {
..Default::default()
};
let endpoint = endpoint_authority(&u)?;
let client = TransitionClient::new_with_timeouts(&endpoint, opts, tier_type, timeouts).await?;
let client = TransitionClient::new_with_dns_resolver(&endpoint, opts, tier_type, timeouts, dns_resolver).await?;
let client = Arc::new(client);
let core = TransitionCore(Arc::clone(&client));
@@ -518,7 +519,7 @@ mod tests {
.expect("listener local address should be available")
.to_string();
let client = Arc::new(
TransitionClient::new(
super::super::warm_backend::fixture_transition_client(
&endpoint,
Options {
creds: Credentials::new(Static(Value {
@@ -619,7 +620,7 @@ mod tests {
requests
});
let client = Arc::new(
TransitionClient::new(
super::super::warm_backend::fixture_transition_client(
&endpoint,
Options {
creds: Credentials::new(Static(Value {
@@ -21,13 +21,12 @@ use std::collections::HashMap;
use crate::services::tier::{
tier_config::TierTencent,
warm_backend::{
S3CompatibleWarmBackendParams, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts, build_transition_put_options,
new_s3_compatible_warm_backend, optimal_part_size,
S3CompatibleWarmBackendParams, TierEndpointPolicy, TransitionCandidateProbe, WarmBackend, WarmBackendGetOpts,
build_transition_put_options, new_s3_compatible_warm_backend, optimal_part_size,
},
warm_backend_s3::WarmBackendS3,
};
use rustfs_s3_client::transition_api::{BucketLookupType, ReadCloser, ReaderImpl};
use rustfs_utils::egress::validate_outbound_url;
const MIN_PART_SIZE: i64 = 1024 * 1024 * 128;
@@ -45,7 +44,7 @@ impl WarmBackendTencent {
region: &conf.region,
bucket_lookup: BucketLookupType::BucketLookupDNS,
provider_tag: "tencent",
validate_endpoint: validate_outbound_url,
endpoint_policy: TierEndpointPolicy::PublicOnly,
})
.await?,
))
@@ -222,7 +222,7 @@ mod tests {
async fn backend_for_endpoint(endpoint: &str, max_retries: i64) -> WarmBackendWasabi {
let client = Arc::new(
rustfs_s3_client::transition_api::TransitionClient::new(
super::super::warm_backend::fixture_transition_client(
endpoint,
Options {
creds: Credentials::new(Static(Value {
@@ -36,6 +36,9 @@ pub(crate) mod internode {
SCANNER_ACTIVITY_PREVIOUS_PROTOCOL_VERSION, SCANNER_ACTIVITY_PROTOCOL_VERSION, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION,
SCANNER_ACTIVITY_V7_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_MAX_ENTRIES,
SCANNER_DIRTY_USAGE_SNAPSHOT_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_RPC_MAX_MESSAGE_SIZE,
STREAM_RESPONSE_AUTH_HEADER, STREAM_RESPONSE_AUTH_NONCE_QUERY, STREAM_RESPONSE_AUTH_QUERY, STREAM_RESPONSE_AUTH_V1,
STREAM_RESPONSE_DATA_HEADER_LEN, STREAM_RESPONSE_EOF_FRAME_LEN, STREAM_RESPONSE_FRAME_KIND_DATA,
STREAM_RESPONSE_FRAME_KIND_EOF, STREAM_RESPONSE_FRAME_MAGIC, STREAM_RESPONSE_FRAME_MAX_PAYLOAD,
WALK_DIR_BODY_SHA256_QUERY, WALK_DIR_STREAM_COMPLETION_QUERY, WALK_DIR_STREAM_COMPLETION_V1,
};
}
+16 -7
View File
@@ -137,15 +137,20 @@ impl VerifiedFederatedIdentity {
pub(crate) struct OpaqueLogoutContinuation {
provider: FederatedProviderRef,
id_token: String,
callback_origin: url::Origin,
}
impl OpaqueLogoutContinuation {
pub(crate) fn new(provider: FederatedProviderRef, id_token: String) -> Self {
Self { provider, id_token }
pub(crate) fn new(provider: FederatedProviderRef, id_token: String, callback_origin: url::Origin) -> Self {
Self {
provider,
id_token,
callback_origin,
}
}
pub(crate) fn into_parts(self) -> (FederatedProviderRef, String) {
(self.provider, self.id_token)
pub(crate) fn into_parts(self) -> (FederatedProviderRef, String, url::Origin) {
(self.provider, self.id_token, self.callback_origin)
}
}
@@ -237,10 +242,14 @@ mod tests {
#[test]
fn logout_continuation_binds_provider_and_redacts_token() {
let continuation =
OpaqueLogoutContinuation::new(FederatedProviderRef::new("standard_oidc".to_string()), "secret-id-token".to_string());
let continuation = OpaqueLogoutContinuation::new(
FederatedProviderRef::new("standard_oidc".to_string()),
"secret-id-token".to_string(),
url::Url::parse("https://console.example.test/callback").unwrap().origin(),
);
let continuation_debug = format!("{continuation:?}");
let (provider, id_token) = continuation.into_parts();
let (provider, id_token, origin) = continuation.into_parts();
assert_eq!(origin.ascii_serialization(), "https://console.example.test");
assert_eq!(provider.as_str(), "standard_oidc");
assert_eq!(id_token, "secret-id-token");
+2 -2
View File
@@ -317,7 +317,7 @@ mod tests {
Ok(VerifiedFederatedCodeExchange::new(
self.identity(self.browser_provider_id),
Some("/browser".to_string()),
OpaqueLogoutContinuation::new(provider, "id-token".to_string()),
OpaqueLogoutContinuation::new(provider, "id-token".to_string(), url::Url::parse(redirect_uri).unwrap().origin()),
))
}
@@ -331,7 +331,7 @@ mod tests {
async fn create_logout_token(&self, continuation: OpaqueLogoutContinuation) -> Result<String> {
self.record("logout");
let (provider, id_token) = continuation.into_parts();
let (provider, id_token, _) = continuation.into_parts();
assert_eq!((provider.as_str(), id_token.as_str()), self.expected_logout);
if self.failure == ProviderFailure::Logout {
return Err(FederationError::Logout("logout failed".to_string()));
+40 -3
View File
@@ -19,7 +19,7 @@ use rustfs_config::{
CONSOLE_OIDC_SESSION_DURATION_MAX_SECS, DEFAULT_CONSOLE_OIDC_SESSION_DURATION_SECS, DEFAULT_DELIMITER, ENABLE_KEY,
ENV_CONSOLE_OIDC_SESSION_DURATION, EnableState,
};
use rustfs_utils::egress::{OutboundUrlError, validate_outbound_url};
use rustfs_utils::egress::{OutboundPolicy, OutboundPolicyError};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
@@ -205,11 +205,15 @@ pub enum OidcConfigError {
OpenidScopeRequired,
#[error("{0} must be an absolute http/https URL")]
InvalidAbsoluteUrl(&'static str),
#[error(
"{field} must use https:// for non-loopback hosts (set {ENV_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT}=true to opt in for development)"
)]
InsecureHttpNotAllowed { field: &'static str },
#[error("{field} is not allowed: {source}")]
ForbiddenOutbound {
field: &'static str,
#[source]
source: OutboundUrlError,
source: OutboundPolicyError,
},
}
@@ -379,13 +383,46 @@ fn or_default(value: &str, default: &str) -> String {
}
}
/// Returns true when the operator explicitly opted into plaintext `http://` OIDC URLs
/// for non-loopback hosts via `RUSTFS_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT`.
pub(super) fn oidc_insecure_transport_allowed() -> bool {
rustfs_utils::get_env_bool(ENV_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT, false)
}
/// True only for canonical loopback hosts (`localhost`, `127.0.0.0/8`, `::1`).
pub(super) fn is_loopback_oidc_url(url: &Url) -> bool {
match url.host() {
Some(url::Host::Domain(host)) => host.trim_end_matches('.').eq_ignore_ascii_case("localhost"),
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
None => false,
}
}
/// Enforce HTTPS for non-loopback OIDC URLs unless `RUSTFS_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT`
/// is explicitly enabled.
pub(super) fn ensure_oidc_url_transport_security(url: &Url) -> Result<(), String> {
if url.scheme().eq_ignore_ascii_case("https") || is_loopback_oidc_url(url) || oidc_insecure_transport_allowed() {
return Ok(());
}
Err(format!(
"plaintext http:// OIDC URLs are forbidden for non-loopback hosts; use https:// or set {ENV_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT}=true for development"
))
}
fn validate_absolute_http_url(value: &str, field: &'static str, check_outbound: bool) -> Result<(), OidcConfigError> {
let parsed = Url::parse(value).map_err(|_| OidcConfigError::InvalidAbsoluteUrl(field))?;
if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
return Err(OidcConfigError::InvalidAbsoluteUrl(field));
}
if check_outbound {
validate_outbound_url(&parsed).map_err(|source| OidcConfigError::ForbiddenOutbound { field, source })?;
let policy = OutboundPolicy::from_env_cached().map_err(|source| OidcConfigError::ForbiddenOutbound { field, source })?;
policy
.validate_url(&parsed)
.map_err(|source| OidcConfigError::ForbiddenOutbound { field, source })?;
}
if ensure_oidc_url_transport_security(&parsed).is_err() {
return Err(OidcConfigError::InsecureHttpNotAllowed { field });
}
Ok(())
}
+52
View File
@@ -419,6 +419,58 @@ fn config_input_rejects_invalid_fields() {
));
}
#[test]
#[serial_test::serial]
fn config_input_rejects_plaintext_http_for_non_loopback_unless_opted_in() {
temp_env::with_var(ENV_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT, None::<&str>, || {
let http_config = OidcProviderConfigInput {
config_url: "http://idp.example.com/.well-known/openid-configuration".to_string(),
client_id: "client".to_string(),
..Default::default()
};
assert!(matches!(
build_upsert_provider_config("default", http_config, None),
Err(OidcConfigError::InsecureHttpNotAllowed { field: "config_url" })
));
let http_issuer = OidcProviderConfigInput {
config_url: "https://idp.example.com/.well-known/openid-configuration".to_string(),
issuer: Some("http://issuer.example.com".to_string()),
client_id: "client".to_string(),
..Default::default()
};
assert!(matches!(
build_upsert_provider_config("default", http_issuer, None),
Err(OidcConfigError::InsecureHttpNotAllowed { field: "issuer" })
));
let http_redirect = OidcProviderConfigInput {
config_url: "https://idp.example.com/.well-known/openid-configuration".to_string(),
redirect_uri: Some("http://console.example.com/rustfs/admin/v3/oidc/callback/default".to_string()),
redirect_uri_dynamic: false,
client_id: "client".to_string(),
..Default::default()
};
assert!(matches!(
build_upsert_provider_config("default", http_redirect, None),
Err(OidcConfigError::InsecureHttpNotAllowed { field: "redirect_uri" })
));
});
temp_env::with_var(ENV_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT, Some("true"), || {
let opted_in = OidcProviderConfigInput {
config_url: "http://idp.example.com/.well-known/openid-configuration".to_string(),
issuer: Some("http://issuer.example.com".to_string()),
redirect_uri: Some("http://console.example.com/rustfs/admin/v3/oidc/callback/default".to_string()),
redirect_uri_dynamic: false,
client_id: "client".to_string(),
..Default::default()
};
build_upsert_provider_config("default", opted_in, None)
.expect("explicit insecure transport opt-in should allow http:// URLs");
});
}
#[test]
fn validation_input_defaults_to_default_provider() {
let input = OidcProviderValidationInput {
+32 -6
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use super::{
config::{OidcProviderConfig, OidcProviderValidationResult, SourcedOidcProviderConfig},
config::{OidcProviderConfig, OidcProviderValidationResult, SourcedOidcProviderConfig, ensure_oidc_url_transport_security},
transport::{DiscoveryRequest, OidcHttpError, ReqwestHttpClient, oidc_extra_root_certs, oidc_http_error_diagnostics},
};
use crate::{EVENT_OIDC_DIAGNOSTICS, LOG_COMPONENT_IAM, LOG_SUBSYSTEM_OIDC};
@@ -204,6 +204,24 @@ impl DiscoveredProviderMetadata {
}
}
pub(super) fn validate_transport_security(&self) -> Result<(), String> {
ensure_oidc_url_transport_security(self.issuer().url())?;
ensure_oidc_url_transport_security(self.jwks_uri().url())?;
if let Some(token_endpoint) = self.token_endpoint() {
ensure_oidc_url_transport_security(token_endpoint.url())?;
}
if let Self::Console(metadata) = self {
ensure_oidc_url_transport_security(metadata.authorization_endpoint().url())?;
if let Some(userinfo) = metadata.userinfo_endpoint() {
ensure_oidc_url_transport_security(userinfo.url())?;
}
if let Some(end_session) = metadata.additional_metadata().end_session_endpoint.as_ref() {
ensure_oidc_url_transport_security(end_session.url())?;
}
}
Ok(())
}
pub(super) fn verifier(&self, config: &OidcProviderConfig) -> CoreIdTokenVerifier<'static> {
let client_id = ClientId::new(config.client_id.clone());
let (issuer, jwks, algorithms) = match self {
@@ -474,11 +492,17 @@ pub(super) async fn discover_provider_for_recovery(
};
ProviderMetadataWithLogout::discover_async(issuer_url.clone(), &client)
.await
.map(|metadata| ProviderState {
metadata: DiscoveredProviderMetadata::Console(Box::new(metadata)),
discovered_at: Instant::now(),
})
.map_err(|err| discovery_failure(err, "discovery failed", OIDC_DISCOVERY_BLOCKED_BY_OUTBOUND_POLICY))
.and_then(|metadata| {
let metadata = DiscoveredProviderMetadata::Console(Box::new(metadata));
metadata.validate_transport_security().map_err(|reason| {
DiscoveryFailure::from(format!("{OIDC_DISCOVERY_BLOCKED_BY_OUTBOUND_POLICY}: {reason}"))
})?;
Ok(ProviderState {
metadata,
discovered_at: Instant::now(),
})
})
};
match discovered {
Ok(state) => return Ok(state),
@@ -637,7 +661,6 @@ async fn discover_provider_from_config_url(
)
.into());
}
let jwks_url = if explicit_issuer {
jwks_url_from_config_url(&config.config_url, &issuer_url, provider_metadata.jwks_uri())?
} else {
@@ -655,6 +678,9 @@ async fn discover_provider_from_config_url(
Ok(jwks) => jwks,
Err(err) => return Err(discovery_failure(err, "failed to fetch JWKS", OIDC_JWKS_BLOCKED_BY_OUTBOUND_POLICY)),
};
provider_metadata
.validate_transport_security()
.map_err(|reason| DiscoveryFailure::from(format!("{OIDC_DISCOVERY_BLOCKED_BY_OUTBOUND_POLICY}: {reason}")))?;
Ok(ProviderState {
metadata: provider_metadata.set_jwks(jwks),
+19 -4
View File
@@ -626,7 +626,7 @@ async fn oidc_reqwest_dns_policy_rejection_stays_typed() {
let calls = Arc::new(AtomicUsize::new(0));
let config = build_mocked_oidc_provider_config(
"default",
"http://keycloak.internal:8080/realms/rustfs/.well-known/openid-configuration",
"https://keycloak.internal:8443/realms/rustfs/.well-known/openid-configuration",
);
let http_client = ReqwestHttpClient::with_policy_and_dns_resolver(
OutboundPolicy::default(),
@@ -642,7 +642,7 @@ async fn oidc_reqwest_dns_policy_rejection_stays_typed() {
};
assert!(error.contains("OIDC provider discovery blocked by outbound policy"));
assert!(error.contains(&format!("add http://keycloak.internal:8080 to {ENV_OUTBOUND_ALLOW_ORIGINS}")));
assert!(error.contains(&format!("add https://keycloak.internal:8443 to {ENV_OUTBOUND_ALLOW_ORIGINS}")));
assert_eq!(calls.load(Ordering::Relaxed), 1, "policy rejection must not be retried");
}
#[tokio::test]
@@ -650,7 +650,7 @@ async fn oidc_explicit_issuer_preserves_dns_policy_rejection() {
let calls = Arc::new(AtomicUsize::new(0));
let mut config = build_mocked_oidc_provider_config(
"default",
"http://keycloak.internal:8080/realms/rustfs/.well-known/openid-configuration",
"https://keycloak.internal:8443/realms/rustfs/.well-known/openid-configuration",
);
config.issuer = Some("https://idp.example.com/realms/rustfs".to_string());
let http_client = ReqwestHttpClient::with_policy_and_dns_resolver(
@@ -667,10 +667,25 @@ async fn oidc_explicit_issuer_preserves_dns_policy_rejection() {
};
assert!(error.contains("OIDC provider discovery blocked by outbound policy"));
assert!(error.contains(&format!("add http://keycloak.internal:8080 to {ENV_OUTBOUND_ALLOW_ORIGINS}")));
assert!(error.contains(&format!("add https://keycloak.internal:8443 to {ENV_OUTBOUND_ALLOW_ORIGINS}")));
assert_eq!(calls.load(Ordering::Relaxed), 1, "policy rejection must not be retried");
}
#[tokio::test]
#[serial_test::serial]
async fn oidc_discovery_rejects_plaintext_http_for_non_loopback_hosts() {
let config = build_mocked_oidc_provider_config("default", "http://idp.example.com/.well-known/openid-configuration");
let http_client = ReqwestHttpClient::with_policy(OutboundPolicy::default());
let error = match discover_provider(&config, &http_client).await {
Ok(_) => panic!("plaintext http:// non-loopback OIDC provider must fail closed"),
Err(error) => error,
};
assert!(error.contains("OIDC provider discovery blocked by outbound policy"));
assert!(error.contains("plaintext http://"));
}
#[tokio::test]
async fn workload_config_validation_reports_absent_console_endpoints() {
let (base, handle) = start_mock_oidc_discovery_server_with_jwks(
+5 -1
View File
@@ -288,7 +288,11 @@ async fn recovery_preserves_ready_provider_and_inflight_sessions() {
.into_owned()
.collect();
let logout = sys
.create_logout_token("ready", "verified-id-token")
.create_logout_token(
"ready",
"verified-id-token",
url::Url::parse("https://console.example.com/callback").unwrap().origin(),
)
.await
.expect("retain logout continuation");
let discovered_at = sys
+41 -12
View File
@@ -695,7 +695,12 @@ impl OidcSys {
/// Store a one-time logout session keyed by an opaque token so the console can
/// trigger browser logout without persisting the raw ID token.
pub(crate) async fn create_logout_token(&self, provider_id: &str, id_token: &str) -> Result<String, String> {
pub(crate) async fn create_logout_token(
&self,
provider_id: &str,
id_token: &str,
callback_origin: url::Origin,
) -> Result<String, String> {
if !self.configs.contains_key(provider_id) {
return Err(format!("unknown OIDC provider: {provider_id}"));
}
@@ -707,6 +712,7 @@ impl OidcSys {
OidcLogoutSession {
provider_id: provider_id.to_string(),
id_token: id_token.to_string(),
callback_origin,
},
)
.await;
@@ -742,15 +748,17 @@ impl OidcSys {
.id_token
.parse()
.map_err(|e: serde_json::Error| format!("failed to parse ID token for logout: {e}"))?;
let post_logout_redirect_uri = PostLogoutRedirectUrl::new(post_logout_redirect_uri.to_string())
.map_err(|e| format!("invalid post logout redirect URI: {e}"))?;
let logout_url = LogoutRequest::from(end_session_endpoint)
let mut logout_request = LogoutRequest::from(end_session_endpoint)
.set_id_token_hint(&id_token)
.set_client_id(ClientId::new(config.client_id.clone()))
.set_post_logout_redirect_uri(post_logout_redirect_uri)
.http_get_url()
.to_string();
.set_client_id(ClientId::new(config.client_id.clone()));
if let Some(post_logout_uri) = resolve_post_logout_redirect_uri(&session.callback_origin, post_logout_redirect_uri) {
let post_logout_redirect_uri =
PostLogoutRedirectUrl::new(post_logout_uri).map_err(|e| format!("invalid post logout redirect URI: {e}"))?;
logout_request = logout_request.set_post_logout_redirect_uri(post_logout_redirect_uri);
}
let logout_url = logout_request.http_get_url().to_string();
Ok(Some(logout_url))
}
@@ -869,6 +877,21 @@ impl OidcSys {
}
}
/// Resolve the console's login path against the callback origin accepted during the code exchange.
pub(super) fn resolve_post_logout_redirect_uri(callback_origin: &url::Origin, post_logout_redirect_uri: &str) -> Option<String> {
let trimmed = post_logout_redirect_uri.trim();
if trimmed.is_empty() || trimmed.starts_with("//") {
return None;
}
if trimmed.starts_with('/') {
if !matches!(callback_origin, url::Origin::Tuple(scheme, ..) if matches!(scheme.as_str(), "http" | "https")) {
return None;
}
return Some(format!("{}{trimmed}", callback_origin.ascii_serialization()));
}
Some(trimmed.to_string())
}
/// Fetch display profile claims from the provider's UserInfo endpoint.
///
/// Only called after the ID token was verified, and only for display metadata:
@@ -1052,7 +1075,13 @@ impl StandardOidcAuthentication for StandardOidcAdapter {
Ok(VerifiedFederatedCodeExchange::new(
verified_identity(provider.clone(), claims),
session.redirect_after,
OpaqueLogoutContinuation::new(provider, id_token),
OpaqueLogoutContinuation::new(
provider,
id_token,
url::Url::parse(redirect_uri)
.map_err(|_| FederationError::CodeExchange("invalid OIDC callback URI".into()))?
.origin(),
),
))
}
@@ -1066,9 +1095,9 @@ impl StandardOidcAuthentication for StandardOidcAdapter {
}
async fn create_logout_token(&self, continuation: OpaqueLogoutContinuation) -> FederationResult<String> {
let (provider, id_token) = continuation.into_parts();
let (provider, id_token, callback_origin) = continuation.into_parts();
self.oidc
.create_logout_token(provider.as_str(), &id_token)
.create_logout_token(provider.as_str(), &id_token, callback_origin)
.await
.map_err(FederationError::Logout)
}
+46 -1
View File
@@ -231,6 +231,8 @@ async fn assert_complete_console_login(initially_unavailable: bool) {
};
let mut config = build_mocked_oidc_provider_config("console", &format!("{base}/.well-known/openid-configuration"));
config.hide_from_ui = hidden;
config.redirect_uri = None;
config.redirect_uri_dynamic = true;
config.claim_name = "groups".into();
config.claim_prefix = "team/".into();
config.issuer = explicit.then(|| issuer.clone());
@@ -288,6 +290,7 @@ async fn assert_complete_console_login(initially_unavailable: bool) {
serde_json::json!({
"issuer": issuer, "authorization_endpoint": format!("{server_base}/authorize"),
"token_endpoint": format!("{server_base}/token"), "jwks_uri": format!("{server_base}/jwks"),
"end_session_endpoint": format!("{server_base}/logout"),
"response_types_supported": ["code"], "subject_types_supported": ["public"],
"id_token_signing_alg_values_supported": ["ES256"]
})
@@ -395,7 +398,16 @@ async fn assert_complete_console_login(initially_unavailable: bool) {
.exchange_identity("console", &state, "test-authorization-code", redirect)
.await
.unwrap_or_else(|err| panic!("hidden={hidden}, explicit={explicit}: {err}"));
let (identity, redirect_after, _) = exchange.into_parts();
let (identity, redirect_after, continuation) = exchange.into_parts();
let logout_token = adapter.create_logout_token(continuation).await.expect("logout token");
let logout = adapter
.build_logout_url(&logout_token, "/console/login")
.await
.unwrap()
.expect("end-session URL");
let logout = Url::parse(&logout).unwrap();
let logout_params: HashMap<_, _> = logout.query_pairs().into_owned().collect();
assert_eq!(logout_params["post_logout_redirect_uri"], "https://console.example.com/console/login");
assert_eq!(identity.source_groups(), ["readwrite"]);
let authorization = mapper.map(identity);
assert_eq!(authorization.provider_id(), "console");
@@ -1044,3 +1056,36 @@ async fn userinfo_request_is_bound_by_outbound_policy() {
.unwrap_err();
assert!(error.starts_with("userinfo request failed:"), "{error}");
}
#[test]
fn resolve_post_logout_redirect_uri_uses_login_origin_and_rejects_protocol_relative_paths() {
let origin = Url::parse("https://console.example.test/callback").unwrap().origin();
assert_eq!(
resolve_post_logout_redirect_uri(&origin, "/console/login").as_deref(),
Some("https://console.example.test/console/login")
);
assert_eq!(resolve_post_logout_redirect_uri(&origin, "//other.example.test/login"), None);
assert_eq!(resolve_post_logout_redirect_uri(&origin, " "), None);
assert_eq!(
resolve_post_logout_redirect_uri(&origin, "https://browser.example.test/login").as_deref(),
Some("https://browser.example.test/login")
);
}
#[tokio::test]
async fn userinfo_request_rejects_plaintext_http_for_non_loopback_host() {
let http_client = ReqwestHttpClient::with_policy(OutboundPolicy::default());
let error = fetch_userinfo_profile(
&http_client,
"http://idp.example.com/userinfo",
"test-access-token",
"existing-user",
&test_config("console"),
)
.await
.unwrap_err();
assert!(
error.contains("plaintext http:// OIDC URLs are forbidden"),
"expected plaintext HTTP rejection, got: {error}"
);
}
+3
View File
@@ -41,6 +41,7 @@ pub(super) struct OidcAuthSession {
pub(super) struct OidcLogoutSession {
pub(super) provider_id: String,
pub(super) id_token: String,
pub(super) callback_origin: url::Origin,
}
/// TTL cache for OIDC auth state (PKCE verifiers + nonces) during the authorization flow.
@@ -252,6 +253,7 @@ mod tests {
let session = OidcLogoutSession {
provider_id: "corp".to_string(),
id_token: "jwt-token".to_string(),
callback_origin: url::Url::parse("https://console.example.test/callback").unwrap().origin(),
};
for i in 0..OIDC_STATE_CAPACITY {
@@ -366,6 +368,7 @@ mod tests {
let session = OidcLogoutSession {
provider_id: "okta".to_string(),
id_token: "jwt-token".to_string(),
callback_origin: url::Url::parse("https://console.example.test/callback").unwrap().origin(),
};
store.insert_logout("logout_abc".to_string(), session.clone()).await;
+1
View File
@@ -422,6 +422,7 @@ pub(super) fn build_oidc_http_client(
}
};
super::config::ensure_oidc_url_transport_security(&url).map_err(OidcHttpError::ForbiddenOutbound)?;
if !extra_root_certs.is_empty() {
builder = builder.tls_certs_merge(extra_root_certs.iter().cloned());
}
+64 -8
View File
@@ -125,6 +125,32 @@ fn build_oidc_http_client_rejects_forbidden_targets_without_allowlist() {
);
}
#[tokio::test]
async fn oidc_resolves_the_provider_directly_when_no_proxy_matches() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind proxy listener");
let proxy = format!("http://{}", listener.local_addr().expect("proxy address"));
temp_env::async_with_vars(
[
("HTTPS_PROXY", Some(proxy.as_str())),
("https_proxy", Some(proxy.as_str())),
("NO_PROXY", Some("provider.invalid")),
("no_proxy", Some("provider.invalid")),
],
async {
let proxy_override = OidcTransportTestOverrides::with_proxy_matcher(OutboundProxyMatcher::from_env());
let (client, url) =
build_oidc_http_client("https://provider.invalid", Some(&OutboundPolicy::default()), &[], Some(&proxy_override))
.expect("build the provider client");
tokio::select! {
result = client.get(url).send() => assert!(result.expect_err("reserved .invalid domain").is_connect()),
_ = listener.accept() => panic!("OIDC connected to the environment proxy"),
}
},
)
.await;
}
#[test]
fn build_oidc_http_client_honors_explicit_allowlist_for_loopback() {
let no_proxy = OidcTransportTestOverrides::with_proxy_matcher(OutboundProxyMatcher::none());
@@ -151,7 +177,7 @@ fn build_oidc_http_client_honors_explicit_allowlist_for_loopback() {
#[tokio::test]
async fn oidc_nonrecoverable_dns_policy_rejection_omits_allowlist_hint() {
let uri = "http://metadata.internal/latest/meta-data";
let uri = "https://metadata.internal/latest/meta-data";
let http_client = ReqwestHttpClient::with_policy_and_dns_resolver(
OutboundPolicy::default(),
Arc::new(RejectingDnsResolver {
@@ -172,7 +198,30 @@ async fn oidc_nonrecoverable_dns_policy_rejection_omits_allowlist_hint() {
assert!(matches!(error, OidcHttpError::ForbiddenOutbound(_)));
assert!(message.contains("metadata.internal"));
assert!(!message.contains(&format!("add http://metadata.internal to {ENV_OUTBOUND_ALLOW_ORIGINS}")));
assert!(!message.contains(&format!("add https://metadata.internal to {ENV_OUTBOUND_ALLOW_ORIGINS}")));
}
#[test]
#[serial_test::serial]
fn build_oidc_http_client_rejects_plaintext_http_for_non_loopback_by_default() {
temp_env::with_var(rustfs_config::oidc::ENV_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT, None::<&str>, || {
let err = build_oidc_http_client("http://idp.example.com/.well-known/openid-configuration", None, &[], None)
.expect_err("non-loopback plaintext http:// OIDC URL must be rejected");
assert!(matches!(err, OidcHttpError::ForbiddenOutbound(ref msg) if msg.contains("plaintext http://")));
// Loopback http:// stays allowed when explicitly allowlisted in OutboundPolicy.
let policy = OutboundPolicy::from_allowed_origins("http://127.0.0.1:8080").expect("origin should parse");
assert!(
build_oidc_http_client("http://127.0.0.1:8080/.well-known/openid-configuration", Some(&policy), &[], None).is_ok()
);
});
temp_env::with_var(rustfs_config::oidc::ENV_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT, Some("true"), || {
assert!(
build_oidc_http_client("http://idp.example.com/.well-known/openid-configuration", None, &[], None).is_ok(),
"explicit opt-in must permit plaintext http:// OIDC URLs"
);
});
}
#[test]
@@ -359,6 +408,7 @@ async fn oidc_https_discovery_tunnels_through_private_proxy_hostname_without_all
}
#[tokio::test]
#[serial_test::serial]
async fn oidc_http_request_forwards_through_authenticated_private_proxy_without_leaking_credentials() {
const PROXY_SECRET: &str = "proxy-secret-9611";
// base64("oidc-proxy:proxy-secret-9611")
@@ -413,8 +463,7 @@ async fn oidc_http_request_forwards_through_authenticated_private_proxy_without_
.uri("http://sso-sit.intra.kommunale.it/realms/rustfs/certs")
.body(Vec::new())
.expect("build proxied HTTP request");
let response = http_client
.call(request)
let response = with_plaintext_oidc_fixture(http_client.call(request))
.await
.expect("HTTP forward-proxied OIDC request should succeed");
assert_eq!(response.status(), http::StatusCode::OK);
@@ -529,7 +578,16 @@ async fn oidc_rejected_proxy_names_proxy_and_omits_target_allowlist_hint() {
);
}
async fn with_plaintext_oidc_fixture<F: std::future::Future>(request: F) -> F::Output {
temp_env::async_with_vars(
[(rustfs_config::oidc::ENV_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT, Some("true"))],
request,
)
.await
}
#[tokio::test]
#[serial_test::serial]
async fn oidc_no_proxy_bypasses_proxy_and_enforces_direct_target_dns_policy() {
let proxy_listener = match TcpListener::bind("127.0.0.1:0").await {
Ok(listener) => listener,
@@ -573,8 +631,7 @@ async fn oidc_no_proxy_bypasses_proxy_and_enforces_direct_target_dns_policy() {
.uri(&target_uri)
.body(Vec::new())
.expect("build unallowlisted NO_PROXY request");
let blocked_err = unallowlisted_client
.call(blocked_req)
let blocked_err = with_plaintext_oidc_fixture(unallowlisted_client.call(blocked_req))
.await
.expect_err("NO_PROXY direct target with private/loopback DNS must be blocked when unallowlisted");
assert!(matches!(blocked_err, OidcHttpError::ForbiddenOutbound(_)));
@@ -595,8 +652,7 @@ async fn oidc_no_proxy_bypasses_proxy_and_enforces_direct_target_dns_policy() {
.uri(&target_uri)
.body(Vec::new())
.expect("build allowlisted NO_PROXY request");
let response = allowlisted_client
.call(allowed_req)
let response = with_plaintext_oidc_fixture(allowlisted_client.call(allowed_req))
.await
.expect("allowlisted NO_PROXY target should connect directly");
assert_eq!(response.status(), http::StatusCode::OK);
+11 -5
View File
@@ -32,20 +32,23 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = KeystoneConfig::from_env()?;
// Create Keystone client
let client = KeystoneClient::new(
let client = KeystoneClient::try_new(
config.auth_url.clone(),
config.get_version()?,
config.admin_user.clone(),
config.admin_password.clone(),
config.admin_project.clone(),
config.get_admin_domain(),
config.verify_ssl,
);
config.get_timeout(),
)?;
// Create authentication provider
let auth_provider = KeystoneAuthProvider::new(
client,
config.cache_size,
config.get_cache_ttl(),
config.enable_cache,
);
// Authenticate with Keystone token
@@ -53,7 +56,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let credentials = auth_provider.authenticate_with_token(token).await?;
println!("Authenticated user: {}", credentials.parent_user);
println!("Project: {:?}", credentials.claims);
Ok(())
}
@@ -67,6 +69,7 @@ Configure via environment variables:
# Enable Keystone
export RUSTFS_KEYSTONE_ENABLE=true
export RUSTFS_KEYSTONE_AUTH_URL=http://keystone:5000
export RUSTFS_OUTBOUND_ALLOW_ORIGINS=http://keystone:5000
export RUSTFS_KEYSTONE_VERSION=v3
# Admin credentials (optional, for privileged operations)
@@ -93,14 +96,16 @@ MITM attacks against the Keystone connection and emits a startup warning.
The `KeystoneClient` provides low-level API access to Keystone services:
```rust
let client = KeystoneClient::new(
let client = KeystoneClient::try_new(
"http://keystone:5000".to_string(),
KeystoneVersion::V3,
Some("admin".to_string()),
Some("secret".to_string()),
Some("admin".to_string()),
"Default".to_string(),
true, // verify SSL
);
std::time::Duration::from_secs(30),
)?;
// Validate a token
let token_info = client.validate_token("token123").await?;
@@ -358,6 +363,7 @@ To enable Keystone authentication in RustFS:
```bash
export RUSTFS_KEYSTONE_ENABLE=true
export RUSTFS_KEYSTONE_AUTH_URL=http://keystone:5000
export RUSTFS_OUTBOUND_ALLOW_ORIGINS=http://keystone:5000
export RUSTFS_KEYSTONE_VERSION=v3
export RUSTFS_KEYSTONE_ADMIN_USER=admin
export RUSTFS_KEYSTONE_ADMIN_PASSWORD=secret
+203 -1
View File
@@ -14,11 +14,13 @@
use crate::{EC2Credential, KeystoneError, KeystoneToken, KeystoneVersion, Result};
use reqwest::{Client, StatusCode};
use rustfs_utils::egress::{OutboundDnsResolver, OutboundPolicy};
use serde_json::json;
use std::sync::Arc;
use time::OffsetDateTime;
use tokio::sync::RwLock;
use tracing::{debug, error, info, warn};
use url::Url;
/// Keystone client for API interactions
#[derive(Clone)]
@@ -74,9 +76,10 @@ impl KeystoneClient {
let client = Client::builder()
.danger_accept_invalid_certs(!verify_ssl)
.redirect(reqwest::redirect::Policy::none())
.timeout(timeout)
.build()
.unwrap();
.expect("Keystone reqwest client builder should succeed");
Self {
client,
@@ -92,6 +95,106 @@ impl KeystoneClient {
}
}
/// Create a Keystone client bound to the process outbound DNS egress policy and
/// disabling automatic HTTP redirects.
#[allow(clippy::too_many_arguments)]
pub fn try_new(
auth_url: String,
version: KeystoneVersion,
admin_user: Option<String>,
admin_password: Option<String>,
admin_project: Option<String>,
admin_domain: String,
verify_ssl: bool,
timeout: std::time::Duration,
) -> Result<Self> {
let outbound_policy = OutboundPolicy::from_env_cached()
.map_err(|err| KeystoneError::ConfigError(format!("invalid outbound policy: {err}")))?;
Self::try_new_with_policy(
auth_url,
version,
admin_user,
admin_password,
admin_project,
admin_domain,
verify_ssl,
timeout,
outbound_policy,
)
}
/// Create a Keystone client bound to an explicit [`OutboundPolicy`].
#[allow(clippy::too_many_arguments)]
pub fn try_new_with_policy(
auth_url: String,
version: KeystoneVersion,
admin_user: Option<String>,
admin_password: Option<String>,
admin_project: Option<String>,
admin_domain: String,
verify_ssl: bool,
timeout: std::time::Duration,
outbound_policy: &OutboundPolicy,
) -> Result<Self> {
let parsed = Url::parse(&auth_url).map_err(|err| KeystoneError::ConfigError(format!("invalid auth_url: {err}")))?;
let dns_resolver = outbound_policy
.resolver_for(&parsed)
.map_err(|err| KeystoneError::ConfigError(format!("auth_url is not allowed: {err}")))?;
Self::try_new_with_resolver(
auth_url,
version,
admin_user,
admin_password,
admin_project,
admin_domain,
verify_ssl,
timeout,
dns_resolver,
)
}
#[allow(clippy::too_many_arguments)]
fn try_new_with_resolver(
auth_url: String,
version: KeystoneVersion,
admin_user: Option<String>,
admin_password: Option<String>,
admin_project: Option<String>,
admin_domain: String,
verify_ssl: bool,
timeout: std::time::Duration,
dns_resolver: OutboundDnsResolver,
) -> Result<Self> {
if !verify_ssl {
warn!(
"Keystone client for '{}' is configured to skip TLS certificate verification. This permits MITM attacks and should not be used in production.",
auth_url
);
}
let client = Client::builder()
.danger_accept_invalid_certs(!verify_ssl)
.redirect(reqwest::redirect::Policy::none())
.no_proxy()
.dns_resolver(dns_resolver)
.timeout(timeout)
.build()
.map_err(|err| KeystoneError::HttpError(format!("failed to build Keystone HTTP client: {err}")))?;
Ok(Self {
client,
auth_url,
version,
admin_token: Arc::new(RwLock::new(None)),
admin_user,
admin_password,
admin_project,
admin_domain,
verify_ssl,
timeout,
})
}
/// Request timeout applied to the underlying HTTP client.
pub fn timeout(&self) -> std::time::Duration {
self.timeout
@@ -562,4 +665,103 @@ mod tests {
assert_eq!(client.auth_url, "http://keystone:5000");
assert_eq!(client.version, KeystoneVersion::V3);
}
#[tokio::test]
async fn try_new_with_policy_rejects_dns_rebind_and_redirects() {
use std::collections::VecDeque;
use std::io::{Read, Write};
use std::net::SocketAddr;
use std::sync::Mutex;
// 1. Literal loopback rejected by default policy.
let err = match KeystoneClient::try_new_with_policy(
"http://127.0.0.1:5000".to_string(),
KeystoneVersion::V3,
None,
None,
None,
"Default".to_string(),
true,
std::time::Duration::from_secs(2),
&OutboundPolicy::default(),
) {
Ok(_) => panic!("loopback auth_url must fail closed"),
Err(err) => err,
};
assert!(err.to_string().contains("not allowed"), "unexpected error: {err}");
// 2. Hostname DNS rebinding to metadata address fails closed at connection time.
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind redirect listener");
let addr = listener.local_addr().expect("listener addr");
let endpoint = format!("http://keystone-rebind.test:{}", addr.port());
let parsed = Url::parse(&endpoint).expect("endpoint URL");
let policy = OutboundPolicy::from_allowed_origins(&parsed.origin().ascii_serialization())
.expect("allowlisted test origin should parse");
let answers = Arc::new(Mutex::new(VecDeque::from([
vec![SocketAddr::new(addr.ip(), 0)],
vec![SocketAddr::new("169.254.169.254".parse().expect("metadata ip"), 0)],
])));
let resolver = policy
.resolver_for(&parsed)
.expect("resolver should construct")
.with_resolve_override(move |host| {
if host != "keystone-rebind.test" {
return None;
}
let mut guard = answers.lock().expect("override lock");
if guard.len() > 1 {
guard.pop_front()
} else {
guard.front().cloned()
}
});
// First connection receives a 302 redirect to metadata endpoint; redirects must NOT be followed.
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("accept request");
stream.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
let mut req = [0_u8; 2048];
let _ = stream.read(&mut req).expect("read request");
stream
.write_all(
b"HTTP/1.1 302 Found\r\nLocation: http://169.254.169.254/latest/meta-data/\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
)
.expect("write redirect");
});
let client = KeystoneClient::try_new_with_resolver(
endpoint,
KeystoneVersion::V3,
None,
None,
None,
"Default".to_string(),
true,
std::time::Duration::from_secs(2),
resolver,
)
.expect("keystone client should build");
// Redirect response must be treated as non-success auth failure, never followed.
let redirect_err = client
.validate_token("token-1")
.await
.expect_err("302 redirect must not be followed");
assert!(
matches!(redirect_err, KeystoneError::AuthenticationFailed(ref msg) if msg.contains("302")),
"expected non-followed 302 failure, got: {redirect_err:?}"
);
server.join().expect("redirect server finished");
// Second request rebinds DNS to 169.254.169.254 and must be blocked at DNS policy layer.
let rebind_err = client
.validate_token("token-2")
.await
.expect_err("rebound metadata DNS answer must fail closed");
assert!(
matches!(rebind_err, KeystoneError::HttpError(_)),
"expected HTTP transport policy error, got: {rebind_err:?}"
);
}
}
+6 -2
View File
@@ -13,7 +13,7 @@
// limitations under the License.
use crate::{KeystoneError, KeystoneVersion, Result};
use rustfs_utils::egress::validate_outbound_url;
use rustfs_utils::egress::OutboundPolicy;
use rustfs_utils::{get_env_bool, get_env_opt_str, get_env_str, get_env_u64};
use serde::{Deserialize, Serialize};
use std::time::Duration;
@@ -167,7 +167,11 @@ impl KeystoneConfig {
}
let parsed = Url::parse(&self.auth_url).map_err(|err| KeystoneError::ConfigError(format!("invalid auth_url: {err}")))?;
validate_outbound_url(&parsed).map_err(|err| KeystoneError::ConfigError(format!("auth_url is not allowed: {err}")))?;
let outbound_policy = OutboundPolicy::from_env_cached()
.map_err(|err| KeystoneError::ConfigError(format!("invalid outbound policy: {err}")))?;
outbound_policy
.validate_url(&parsed)
.map_err(|err| KeystoneError::ConfigError(format!("auth_url is not allowed: {err}")))?;
// Validate version
self.get_version()?;
+2 -2
View File
@@ -32,7 +32,7 @@
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let config = KeystoneConfig::from_env()?;
//! let client = KeystoneClient::new(
//! let client = KeystoneClient::try_new(
//! config.auth_url.clone(),
//! config.get_version()?,
//! config.admin_user.clone(),
@@ -41,7 +41,7 @@
//! config.get_admin_domain(),
//! config.verify_ssl,
//! config.get_timeout(),
//! );
//! )?;
//!
//! let auth_provider = KeystoneAuthProvider::new(
//! client,
+163 -1
View File
@@ -16,6 +16,8 @@ use rustfs_policy::policy::action::S3Action as PolicyS3Action;
use serde_json;
use std::collections::HashMap;
use thiserror::Error;
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use tracing::error;
use super::session::SessionContext;
@@ -294,13 +296,14 @@ pub async fn is_authorized(
// Check if user is the owner (admin)
let is_owner = rustfs_iam::is_root_access_key(session_context.principal.access_key());
let conditions = policy_conditions_for_session(session_context, is_owner);
let args = rustfs_policy::policy::Args {
account: session_context.principal.access_key(),
groups: &session_context.principal.user_identity.credentials.groups,
action: policy_action,
bucket,
conditions: &HashMap::new(),
conditions: &conditions,
is_owner,
object: object.unwrap_or(""),
claims: &claims,
@@ -310,6 +313,63 @@ pub async fn is_authorized(
Ok(iam_sys.is_allowed(&args).await)
}
/// Build IAM policy condition values from the authenticated protocol session context.
///
/// Server-derived transport and identity facts (`SourceIp`, `SecureTransport`, `CurrentTime`,
/// `EpochTime`, `userid`, `username`, `principaltype`) are always authoritative and cannot be
/// shadowed by caller-controlled request headers.
pub(crate) fn policy_conditions_for_session(session_context: &SessionContext, is_owner: bool) -> HashMap<String, Vec<String>> {
policy_conditions_for_session_at(session_context, is_owner, OffsetDateTime::now_utc())
}
fn policy_conditions_for_session_at(
session_context: &SessionContext,
is_owner: bool,
now: OffsetDateTime,
) -> HashMap<String, Vec<String>> {
let mut conditions = HashMap::new();
conditions.insert("CurrentTime".to_owned(), vec![now.format(&Rfc3339).unwrap_or_default()]);
conditions.insert("EpochTime".to_owned(), vec![now.unix_timestamp().to_string()]);
conditions.insert("SecureTransport".to_owned(), vec![session_context.secure_transport.to_string()]);
// An unspecified source address renders as the empty string so IpAddress / NotIpAddress
// conditions evaluate deterministically without matching 0.0.0.0/0 as a concrete peer.
let source_ip = if session_context.source_ip.is_unspecified() {
String::new()
} else {
session_context.source_ip.to_string()
};
conditions.insert("SourceIp".to_owned(), vec![source_ip]);
if let Some(user_agent) = session_context.request_headers.get(http::header::USER_AGENT)
&& let Ok(value) = user_agent.to_str()
{
conditions.insert("UserAgent".to_owned(), vec![value.to_owned()]);
}
if let Some(referer) = session_context.request_headers.get(http::header::REFERER)
&& let Ok(value) = referer.to_str()
{
conditions.insert("Referer".to_owned(), vec![value.to_owned()]);
}
let username = session_context.principal.access_key();
if !username.is_empty() {
conditions.insert("userid".to_owned(), vec![username.to_owned()]);
conditions.insert("username".to_owned(), vec![username.to_owned()]);
}
let creds = session_context.credentials();
let principal_type = if is_owner {
"Account"
} else if creds.is_temp() && !creds.is_service_account() {
"AssumedRole"
} else {
"User"
};
conditions.insert("principaltype".to_owned(), vec![principal_type.to_owned()]);
conditions
}
fn policy_claims_for_session(session_context: &SessionContext) -> HashMap<String, serde_json::Value> {
let mut claims = session_context
.principal
@@ -631,4 +691,106 @@ mod tests {
.await;
assert!(matches!(result, Err(AuthorizationError::IamUnavailable)));
}
#[tokio::test]
async fn policy_conditions_enforce_source_ip_and_secure_transport() {
use rustfs_policy::policy::{Args, Policy, action::Action};
use std::net::{IpAddr, Ipv4Addr};
let policy: Policy = serde_json::from_str(
r#"{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::restricted/*"],
"Condition": {
"IpAddress": {"aws:SourceIp": ["203.0.113.0/24"]},
"Bool": {"aws:SecureTransport": ["true"]}
}
},
{
"Effect": "Deny",
"Action": ["s3:*"],
"Resource": ["arn:aws:s3:::restricted/*"],
"Condition": {
"Bool": {"aws:SecureTransport": ["false"]}
}
}
]
}"#,
)
.expect("policy JSON should parse");
let mut allowed_session = test_session();
allowed_session.source_ip = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 42));
allowed_session.secure_transport = true;
allowed_session
.request_headers
.insert(http::header::USER_AGENT, http::HeaderValue::from_static("proto-client/1.0"));
allowed_session
.request_headers
.insert("x-forwarded-for", http::HeaderValue::from_static("198.51.100.1"));
let allowed_conditions = policy_conditions_for_session(&allowed_session, false);
assert_eq!(allowed_conditions.get("SourceIp"), Some(&vec!["203.0.113.42".to_string()]));
assert_eq!(allowed_conditions.get("SecureTransport"), Some(&vec!["true".to_string()]));
assert_eq!(allowed_conditions.get("UserAgent"), Some(&vec!["proto-client/1.0".to_string()]));
assert!(!allowed_conditions.contains_key("x-forwarded-for"));
let claims = policy_claims_for_session(&allowed_session);
let allowed_args = Args {
account: "alice",
groups: &None,
action: Action::from(S3Action::GetObject),
bucket: "restricted",
conditions: &allowed_conditions,
is_owner: false,
object: "secret.txt",
claims: &claims,
deny_only: false,
};
assert!(
policy.is_allowed(&allowed_args).await,
"matching SourceIp and SecureTransport=true must be allowed"
);
// Plaintext transport must be denied even from an allowed IP.
let mut insecure_session = allowed_session.clone();
insecure_session.secure_transport = false;
let insecure_conditions = policy_conditions_for_session(&insecure_session, false);
let insecure_args = Args {
conditions: &insecure_conditions,
..allowed_args
};
assert!(
!policy.is_allowed(&insecure_args).await,
"SecureTransport=false must fail the policy condition and match explicit Deny"
);
// Disallowed source IP must fail closed even over TLS.
let mut wrong_ip_session = allowed_session.clone();
wrong_ip_session.source_ip = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 9));
let wrong_ip_conditions = policy_conditions_for_session(&wrong_ip_session, false);
let wrong_ip_args = Args {
conditions: &wrong_ip_conditions,
..allowed_args
};
assert!(!policy.is_allowed(&wrong_ip_args).await, "non-matching SourceIp must be denied");
// Unspecified source IP renders empty string and must not match the CIDR.
let mut unspecified_session = allowed_session;
unspecified_session.source_ip = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
let unspecified_conditions = policy_conditions_for_session(&unspecified_session, false);
assert_eq!(unspecified_conditions.get("SourceIp"), Some(&vec![String::new()]));
let unspecified_args = Args {
conditions: &unspecified_conditions,
..allowed_args
};
assert!(
!policy.is_allowed(&unspecified_args).await,
"unspecified SourceIp must never satisfy an IpAddress allow condition"
);
}
}
+41 -18
View File
@@ -16,13 +16,13 @@ use super::config::{FtpsConfig, FtpsInitError};
use super::driver::FtpsDriver;
use crate::common::client::s3::StorageBackend;
use crate::common::session::{Protocol, ProtocolPrincipal, SessionContext, is_temporary_credential};
use crate::constants::{network::DEFAULT_SOURCE_IP, paths::ROOT_PATH};
use crate::constants::paths::ROOT_PATH;
use libunftp::options::FtpsRequired;
use rustfs_config::{DEFAULT_TLS_RELOAD_ENABLE, DEFAULT_TLS_RELOAD_INTERVAL, ENV_TLS_RELOAD_ENABLE, ENV_TLS_RELOAD_INTERVAL};
use rustfs_tls_runtime::{ReloadableServerCertResolver, TlsReloadOptions, spawn_server_cert_reload_loop};
use rustfs_utils::MaskedAccessKey;
use std::fmt::{Debug, Display, Formatter};
use std::net::IpAddr;
use std::net::{IpAddr, Ipv4Addr};
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
@@ -329,13 +329,15 @@ where
#[derive(Debug)]
pub struct FtpsUserDetailProvider;
#[async_trait::async_trait]
impl UserDetailProvider for FtpsUserDetailProvider {
type User = FtpsUser;
async fn provide_user_detail(&self, principal: &Principal) -> Result<Self::User, UserDetailError> {
impl FtpsUserDetailProvider {
async fn provide_user_detail_with_context(
&self,
username: &str,
source_ip: IpAddr,
secure_transport: bool,
) -> Result<FtpsUser, UserDetailError> {
use rustfs_iam::get;
let masked_username = MaskedAccessKey(&principal.username);
let masked_username = MaskedAccessKey(username);
// Access IAM system
let iam_sys = get().map_err(|e| {
@@ -351,7 +353,7 @@ impl UserDetailProvider for FtpsUserDetailProvider {
UserDetailError::ImplPropagated("Internal authentication service unavailable".to_string(), Some(Box::new(e)))
})?;
let (user_identity, _is_valid) = iam_sys.check_key(&principal.username).await.map_err(|e| {
let (user_identity, _is_valid) = iam_sys.check_key(username).await.map_err(|e| {
error!(
event = EVENT_FTPS_AUTH_STATE,
component = LOG_COMPONENT_PROTOCOLS,
@@ -376,16 +378,16 @@ impl UserDetailProvider for FtpsUserDetailProvider {
"FTPS user-detail identity missing"
);
UserDetailError::UserNotFound {
username: principal.username.clone(),
username: username.to_string(),
}
})?;
let source_ip: IpAddr = DEFAULT_SOURCE_IP.parse().unwrap();
let session_context = SessionContext::new(ProtocolPrincipal::new(Arc::new(identity.clone())), Protocol::Ftps, source_ip);
let mut session_context =
SessionContext::new(ProtocolPrincipal::new(Arc::new(identity.clone())), Protocol::Ftps, source_ip);
session_context.secure_transport = secure_transport;
let ftps_user = FtpsUser {
username: principal.username.clone(),
username: username.to_string(),
name: identity.credentials.name,
session_context,
};
@@ -394,6 +396,16 @@ impl UserDetailProvider for FtpsUserDetailProvider {
}
}
#[async_trait::async_trait]
impl UserDetailProvider for FtpsUserDetailProvider {
type User = FtpsUser;
async fn provide_user_detail(&self, principal: &Principal) -> Result<Self::User, UserDetailError> {
self.provide_user_detail_with_context(&principal.username, IpAddr::V4(Ipv4Addr::UNSPECIFIED), false)
.await
}
}
// libunftp passes only Principal between authentication and user construction.
// Encode the verified connection attributes in that private handoff so concurrent
// logins for the same account cannot overwrite each other's source address.
@@ -425,10 +437,9 @@ impl UserDetailProvider for ConnectionUserDetailProvider {
async fn provide_user_detail(&self, principal: &Principal) -> Result<Self::User, UserDetailError> {
let (username, source_ip, secure_transport): (String, IpAddr, bool) = serde_json::from_str(&principal.username)
.map_err(|error| UserDetailError::with_source("Invalid connection context", error))?;
let mut user = FtpsUserDetailProvider.provide_user_detail(&Principal { username }).await?;
user.session_context.source_ip = source_ip;
user.session_context.secure_transport = secure_transport;
Ok(user)
FtpsUserDetailProvider
.provide_user_detail_with_context(&username, source_ip, secure_transport)
.await
}
}
@@ -685,4 +696,16 @@ mod tests {
shutdown_tx.send(()).expect("signal shutdown");
server_task.await.expect("server task").expect("clean server exit");
}
#[tokio::test]
async fn connection_user_detail_provider_rejects_malformed_context_without_panicking() {
let provider = ConnectionUserDetailProvider;
let err = provider
.provide_user_detail(&Principal {
username: "not-valid-connection-context".to_string(),
})
.await
.expect_err("malformed connection context must fail closed");
assert!(matches!(err, UserDetailError::ImplPropagated(_, _)), "unexpected error: {err:?}");
}
}
+16
View File
@@ -1004,6 +1004,7 @@ pub type ChunkReaderBox = Box<dyn ChunkReader>;
struct HttpReaderInit {
stream: HttpByteStream,
response_headers: HeaderMap,
track_internode_metrics: bool,
internode_operation: Option<&'static str>,
stall_timeout: Option<Duration>,
@@ -1015,6 +1016,7 @@ pin_project! {
url:String,
method: Method,
headers: HeaderMap,
response_headers: HeaderMap,
track_internode_metrics: bool,
internode_operation: Option<&'static str>,
stall_timeout: Option<Duration>,
@@ -1028,6 +1030,7 @@ pin_project! {
pin_project! {
pub struct HttpChunkReader {
response_headers: HeaderMap,
track_internode_metrics: bool,
internode_operation: Option<&'static str>,
stall_timeout: Option<Duration>,
@@ -1085,6 +1088,7 @@ impl HttpReader {
url,
method,
headers,
response_headers: init.response_headers,
track_internode_metrics: init.track_internode_metrics,
internode_operation: init.internode_operation,
stall_timer: None,
@@ -1191,6 +1195,7 @@ impl HttpReader {
record_internode_outgoing_request(track_internode_metrics, internode_operation);
let response_headers = resp.headers().clone();
let stream_error_url = url.to_owned();
let stream_error_method = method.clone();
let stream = resp.bytes_stream().map_err(move |e| {
@@ -1202,6 +1207,7 @@ impl HttpReader {
Ok(HttpReaderInit {
stream: Box::pin(stream),
response_headers,
track_internode_metrics,
internode_operation,
stall_timeout,
@@ -1217,6 +1223,9 @@ impl HttpReader {
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
pub fn response_headers(&self) -> &HeaderMap {
&self.response_headers
}
}
impl AsyncRead for HttpReader {
@@ -1282,6 +1291,7 @@ impl HttpChunkReader {
let init = HttpReader::open(&url, &method, &headers, body, stall_timeout, ReaderConnection::Pooled).await?;
Ok(Self {
inner: init.stream,
response_headers: init.response_headers,
current: None,
track_internode_metrics: init.track_internode_metrics,
internode_operation: init.internode_operation,
@@ -1303,6 +1313,7 @@ impl HttpChunkReader {
let init = HttpReader::open(&url, &method, &headers, body, stall_timeout, ReaderConnection::Fresh).await?;
Ok(Self {
inner: init.stream,
response_headers: init.response_headers,
current: None,
track_internode_metrics: init.track_internode_metrics,
internode_operation: init.internode_operation,
@@ -1313,6 +1324,10 @@ impl HttpChunkReader {
consecutive_empty_chunks: 0,
})
}
pub fn response_headers(&self) -> &HeaderMap {
&self.response_headers
}
}
fn excessive_empty_chunks_error() -> Error {
@@ -2846,6 +2861,7 @@ mod tests {
request_started: Instant::now(),
duration_recorded: false,
consecutive_empty_chunks: 0,
response_headers: HeaderMap::new(),
inner,
current: None,
};
+1 -1
View File
@@ -77,7 +77,7 @@ fn response_limit_from_range(opts: &GetObjectOptions) -> Result<Option<usize>, s
Ok(Some(limit))
}
impl TransitionClient {
impl<C: crate::transition_api::TransitionConnector> TransitionClient<C> {
pub fn get_object(&self, bucket_name: &str, object_name: &str, opts: &GetObjectOptions) -> Result<Object, std::io::Error> {
let _ = opts;
Err(std::io::Error::new(
+1 -1
View File
@@ -35,7 +35,7 @@ use rustfs_utils::hash::EMPTY_STRING_SHA256_HASH;
use std::collections::HashMap;
use std::io::ErrorKind;
impl TransitionClient {
impl<C: crate::transition_api::TransitionConnector> TransitionClient<C> {
pub fn list_buckets(&self) -> Result<Vec<BucketInfo>, std::io::Error> {
Err(std::io::Error::new(
ErrorKind::Unsupported,
+1 -1
View File
@@ -275,7 +275,7 @@ impl PutObjectOptions {
}
}
impl TransitionClient {
impl<C: crate::transition_api::TransitionConnector> TransitionClient<C> {
pub async fn put_object(
self: Arc<Self>,
bucket_name: &str,
@@ -95,7 +95,7 @@ pub fn optimal_part_info(object_size: i64, configured_part_size: u64) -> Result<
Ok((total_parts_count, part_size, last_part_size))
}
impl TransitionClient {
impl<C: crate::transition_api::TransitionConnector> TransitionClient<C> {
pub async fn new_upload_id(
&self,
bucket_name: &str,
@@ -42,7 +42,7 @@ use crate::{
};
use rustfs_utils::path::trim_etag;
impl TransitionClient {
impl<C: crate::transition_api::TransitionConnector> TransitionClient<C> {
pub async fn put_object_multipart(
&self,
bucket_name: &str,
@@ -81,7 +81,7 @@ async fn read_multipart_part(reader: &mut ReaderImpl, want: usize) -> Result<Vec
}
}
impl TransitionClient {
impl<C: crate::transition_api::TransitionConnector> TransitionClient<C> {
pub async fn put_object_multipart_stream(
self: Arc<Self>,
bucket_name: &str,
+1 -1
View File
@@ -79,7 +79,7 @@ pub struct RemoveObjectOptions {
pub internal: AdvancedRemoveOptions,
}
impl TransitionClient {
impl<C: crate::transition_api::TransitionConnector> TransitionClient<C> {
pub async fn remove_bucket_with_options(&self, bucket_name: &str, opts: &RemoveBucketOptions) -> Result<(), std::io::Error> {
let headers = HeaderMap::new();
+1 -1
View File
@@ -85,7 +85,7 @@ fn parse_bucket_versioning_response(
})
}
impl TransitionClient {
impl<C: crate::transition_api::TransitionConnector> TransitionClient<C> {
pub async fn bucket_exists(&self, bucket_name: &str) -> Result<bool, std::io::Error> {
let resp = self
.execute_method(
+3 -3
View File
@@ -62,7 +62,7 @@ impl BucketLocationCache {
}
}
impl TransitionClient {
impl<C: crate::transition_api::TransitionConnector> TransitionClient<C> {
pub async fn get_bucket_location(&self, bucket_name: &str) -> Result<String, std::io::Error> {
Ok(self.get_bucket_location_inner(bucket_name).await?)
}
@@ -196,8 +196,8 @@ impl TransitionClient {
}
}
async fn process_bucket_location_response(
client: &TransitionClient,
async fn process_bucket_location_response<C: crate::transition_api::TransitionConnector>(
client: &TransitionClient<C>,
mut resp: http::Response<Incoming>,
bucket_name: &str,
tier_type: &str,
+154 -9
View File
@@ -46,7 +46,11 @@ use http_body_util::BodyExt;
use hyper::body::Bytes;
use hyper::body::Incoming;
use hyper_rustls::{ConfigBuilderExt, HttpsConnector};
use hyper_util::{client::legacy::Client, client::legacy::connect::HttpConnector, rt::TokioExecutor};
use hyper_util::{
client::legacy::Client,
client::legacy::connect::{HttpConnector, dns::Name as HyperDnsName},
rt::TokioExecutor,
};
use md5::Digest;
use md5::Md5;
use rand::{Rng, RngExt};
@@ -54,6 +58,7 @@ use rustfs_config::MAX_S3_CLIENT_RESPONSE_SIZE;
use rustfs_gateway_types::dto::{Owner, ReplicationStatus};
use rustfs_rio::HashReader;
use rustfs_utils::HashAlgorithm;
use rustfs_utils::egress::{OutboundDnsResolver, find_outbound_dns_policy_rejection};
use rustfs_utils::{
http::headers::{
AMZ_CHECKSUM_CRC32, AMZ_CHECKSUM_CRC32C, AMZ_CHECKSUM_CRC64NVME, AMZ_CHECKSUM_MODE, AMZ_CHECKSUM_SHA1,
@@ -118,9 +123,35 @@ fn transition_transport_error(err: hyper_util::client::legacy::Error) -> std::io
if source_chain_has_io_kind(&err, std::io::ErrorKind::TimedOut) {
return remote_tier_timeout_error("remote tier connection timed out");
}
if find_outbound_dns_policy_rejection(&err).is_some() {
return std::io::Error::new(std::io::ErrorKind::PermissionDenied, err);
}
std::io::Error::other(err)
}
#[derive(Clone, Debug)]
pub struct OutboundHyperDnsResolver(OutboundDnsResolver);
impl tower::Service<HyperDnsName> for OutboundHyperDnsResolver {
type Response = std::vec::IntoIter<std::net::SocketAddr>;
type Error = std::io::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, name: HyperDnsName) -> Self::Future {
let resolver = self.0.clone();
Box::pin(async move { Ok(resolver.resolve_host(name.as_str()).await?.into_iter()) })
}
}
pub type TierConnector = HttpsConnector<HttpConnector<OutboundHyperDnsResolver>>;
pub trait TransitionConnector: hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static {}
impl<C: hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static> TransitionConnector for C {}
fn is_retryable_transport_error(error: &std::io::Error) -> bool {
// Hyper wraps connection and body errors; the outer io::Error is often Other.
let mut current: Option<&(dyn StdError + 'static)> = Some(error);
@@ -300,12 +331,12 @@ pub enum ReaderImpl {
pub type ReadCloser = ObjectReader;
#[derive(Debug)]
pub struct TransitionClient {
pub struct TransitionClient<C = HttpsConnector<HttpConnector>> {
pub endpoint_url: Url,
pub creds_provider: Arc<Mutex<Credentials<Static>>>,
pub override_signer_type: SignatureType,
pub secure: bool,
pub http_client: Client<HttpsConnector<HttpConnector>, rustfs_s3_types::Body>,
pub http_client: Client<C, rustfs_s3_types::Body>,
pub bucket_loc_cache: Arc<Mutex<BucketLocationCache>>,
pub is_trace_enabled: Arc<Mutex<bool>>,
pub trace_errors_only: Arc<Mutex<bool>>,
@@ -468,7 +499,7 @@ async fn build_tls_config() -> Result<rustls::ClientConfig, std::io::Error> {
impl TransitionClient {
pub async fn new(endpoint: &str, opts: Options, tier_type: &str) -> Result<TransitionClient, std::io::Error> {
Self::private_new(endpoint, opts, tier_type, TransitionClientTimeouts::default()).await
Self::new_with_timeouts(endpoint, opts, tier_type, TransitionClientTimeouts::default()).await
}
/// Builds a transition client with explicit transport timeout budgets.
@@ -481,15 +512,39 @@ impl TransitionClient {
tier_type: &str,
timeouts: TransitionClientTimeouts,
) -> Result<TransitionClient, std::io::Error> {
Self::private_new(endpoint, opts, tier_type, timeouts).await
Self::from_connector(endpoint, opts, tier_type, timeouts, HttpConnector::new()).await
}
async fn private_new(
/// Build a tier client whose connector filters DNS answers on every connection.
pub async fn new_with_dns_resolver(
endpoint: &str,
opts: Options,
tier_type: &str,
timeouts: TransitionClientTimeouts,
) -> Result<TransitionClient, std::io::Error> {
resolver: OutboundDnsResolver,
) -> std::io::Result<TransitionClient<TierConnector>> {
TransitionClient::from_connector(
endpoint,
opts,
tier_type,
timeouts,
HttpConnector::new_with_resolver(OutboundHyperDnsResolver(resolver)),
)
.await
}
}
impl<R> TransitionClient<HttpsConnector<HttpConnector<R>>>
where
HttpsConnector<HttpConnector<R>>: TransitionConnector,
{
async fn from_connector(
endpoint: &str,
opts: Options,
tier_type: &str,
timeouts: TransitionClientTimeouts,
mut http: HttpConnector<R>,
) -> Result<Self, std::io::Error> {
rustfs_tls_runtime::ensure_crypto_provider().map_err(std::io::Error::other)?;
let endpoint_url = get_endpoint_url(endpoint, opts.secure)?;
@@ -497,7 +552,6 @@ impl TransitionClient {
let tls = build_tls_config().await?;
let mut http = HttpConnector::new();
http.enforce_http(false);
http.set_connect_timeout(Some(timeouts.connect_timeout));
let https = hyper_rustls::HttpsConnectorBuilder::new()
@@ -551,7 +605,9 @@ impl TransitionClient {
Ok(client)
}
}
impl<C: TransitionConnector> TransitionClient<C> {
#[allow(
dead_code,
reason = "MinIO-parity transition client surface with no caller in this port (backlog#1823)"
@@ -1150,14 +1206,16 @@ pub struct RequestMetadata {
pub trailer: HeaderMap,
}
pub struct TransitionCore(pub Arc<TransitionClient>);
pub struct TransitionCore<C = HttpsConnector<HttpConnector>>(pub Arc<TransitionClient<C>>);
impl TransitionCore {
pub async fn new(endpoint: &str, opts: Options) -> Result<Self, std::io::Error> {
let client = TransitionClient::new(endpoint, opts, "").await?;
Ok(Self(Arc::new(client)))
}
}
impl<C: TransitionConnector> TransitionCore<C> {
pub fn list_objects(
&self,
bucket: &str,
@@ -2044,4 +2102,91 @@ mod tests {
.expect("nil s3 uuid version should parse");
assert_eq!(info.version_id, None);
}
#[tokio::test]
async fn transition_client_rechecks_outbound_dns_policy_on_rebinding() {
use super::find_outbound_dns_policy_rejection;
use http::StatusCode;
use rustfs_utils::egress::OutboundPolicy;
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use url::Url;
let listener = match TcpListener::bind("127.0.0.1:0").await {
Ok(listener) => listener,
Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => return,
Err(err) => panic!("test listener should bind: {err}"),
};
let address = listener.local_addr().expect("listener address");
let endpoint = format!("rebind-tier.test:{}", address.port());
let endpoint_url = Url::parse(&format!("http://{endpoint}")).expect("endpoint URL");
let policy = OutboundPolicy::from_allowed_origins(&endpoint_url.origin().ascii_serialization())
.expect("allowlisted test origin should parse");
let answers = Arc::new(Mutex::new(VecDeque::from([
vec![SocketAddr::new(address.ip(), 0)],
vec![SocketAddr::new("169.254.169.254".parse().expect("metadata ip"), 0)],
])));
let resolver = policy
.resolver_for_allow_private(&endpoint_url)
.expect("resolver should construct")
.with_resolve_override(move |host| {
if host != "rebind-tier.test" {
return None;
}
let mut guard = answers.lock().expect("override lock");
if guard.len() > 1 {
guard.pop_front()
} else {
guard.front().cloned()
}
});
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.expect("first connection should succeed");
let mut buf = [0_u8; 1024];
let _ = stream.read(&mut buf).await.expect("read request");
stream
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.await
.expect("write response");
});
let client = super::TransitionClient::new_with_dns_resolver(
&endpoint,
super::Options {
secure: false,
..Default::default()
},
"s3",
super::TransitionClientTimeouts::new(StdDuration::from_secs(2), StdDuration::from_secs(2), StdDuration::from_secs(2)),
resolver,
)
.await
.expect("transition client should build");
let req1 = Request::builder()
.uri(format!("http://{endpoint}/probe"))
.body(rustfs_s3_types::Body::empty())
.expect("first request");
let resp = client.doit(req1).await.expect("first connection should succeed");
assert_eq!(resp.status(), StatusCode::OK);
server.await.expect("server should finish");
let req2 = Request::builder()
.uri(format!("http://{endpoint}/probe"))
.body(rustfs_s3_types::Body::empty())
.expect("second request");
let err = client
.doit(req2)
.await
.expect_err("rebound metadata DNS answer must fail closed");
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied);
assert!(
find_outbound_dns_policy_rejection(&err).is_some(),
"DNS policy rejection must remain typed in error chain: {err}"
);
}
}
+8 -1
View File
@@ -143,13 +143,20 @@ async fn run_case(
region: "us-east-1".into(),
bucket_lookup: BucketLookupType::BucketLookupPath,
max_retries: attempts,
..Default::default()
secure: false,
trailing_headers: false,
custom_md5: None,
custom_sha256: None,
},
"s3",
TransitionClientTimeouts::new(Duration::from_secs(1), Duration::from_secs(1), Duration::from_secs(1)),
)
.await
.expect("build real transition client");
let _: &hyper_util::client::legacy::Client<
hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>,
rustfs_s3_types::Body,
> = &client.http_client;
let result = tokio::time::timeout(Duration::from_secs(5), client.execute_method(method, metadata)).await;
let _ = stop.send(());
let requests = tokio::time::timeout(Duration::from_secs(2), server)
+10
View File
@@ -17,6 +17,16 @@
pub const WALK_DIR_STREAM_COMPLETION_QUERY: &str = "walk_dir_stream_completion";
pub const WALK_DIR_STREAM_COMPLETION_V1: &str = "error-v1";
pub const WALK_DIR_BODY_SHA256_QUERY: &str = "walk_dir_body_sha256";
pub const STREAM_RESPONSE_AUTH_QUERY: &str = "stream_auth";
pub const STREAM_RESPONSE_AUTH_V1: &str = "framed-v1";
pub const STREAM_RESPONSE_AUTH_NONCE_QUERY: &str = "stream_auth_nonce";
pub const STREAM_RESPONSE_AUTH_HEADER: &str = "x-rustfs-rpc-stream-auth";
pub const STREAM_RESPONSE_FRAME_MAGIC: &[u8; 8] = b"RFS-SF1\0";
pub const STREAM_RESPONSE_FRAME_KIND_DATA: u8 = 1;
pub const STREAM_RESPONSE_FRAME_KIND_EOF: u8 = 2;
pub const STREAM_RESPONSE_FRAME_MAX_PAYLOAD: usize = 4 * 1024 * 1024;
pub const STREAM_RESPONSE_DATA_HEADER_LEN: usize = STREAM_RESPONSE_FRAME_MAGIC.len() + 1 + 8 + 4 + 32;
pub const STREAM_RESPONSE_EOF_FRAME_LEN: usize = STREAM_RESPONSE_FRAME_MAGIC.len() + 1 + 8 + 8 + 32 + 32;
pub const PUT_FILE_AUTH_QUERY: &str = "put_file_auth";
pub const PUT_FILE_AUTH_V1: &str = "digest-trailer-v1";
pub const PUT_FILE_NONCE_QUERY: &str = "put_file_nonce";
+222 -49
View File
@@ -18,7 +18,9 @@
//! runtime path uses the simplified rule set, and an environment variable can
//! switch the global entrypoints to the legacy chain validator.
use crate::{ClientInfo, LegacyTrustedProxyLayer, LegacyTrustedProxyMiddleware, ValidationMode, global};
use crate::{
ClientInfo, ConfigLoader, LegacyTrustedProxyLayer, LegacyTrustedProxyMiddleware, TrustedProxy, ValidationMode, global,
};
use axum::http::{HeaderMap, Request, Response, StatusCode};
use futures::future::{Either, Ready, ready};
use rustfs_config::{
@@ -28,13 +30,17 @@ use rustfs_config::{
use std::fmt;
use std::net::{IpAddr, SocketAddr};
use std::str::FromStr;
use std::sync::OnceLock;
use std::sync::{Arc, OnceLock};
use std::task::{Context, Poll};
use tower::{Layer, Service};
use tracing::debug;
/// Constant switch for the crate's default integration path.
pub const SIMPLE_INTERNAL_ONLY_DEFAULT: bool = true;
///
/// Simple mode now honors the configured trusted-proxy allowlist
/// (`RUSTFS_TRUSTED_PROXY_NETWORKS`, defaulting to loopback-only) rather than
/// trusting every private/internal IP range.
pub const SIMPLE_INTERNAL_ONLY_DEFAULT: bool = false;
#[cfg(test)]
const HEADER_FORWARDED: &str = "forwarded";
@@ -128,6 +134,10 @@ impl TrustedProxyLayer {
Self::Simple(SimpleTrustedProxyLayer::enabled())
}
pub fn with_trusted_proxies(trusted_proxies: Vec<TrustedProxy>) -> Self {
Self::Simple(SimpleTrustedProxyLayer::with_trusted_proxies(trusted_proxies))
}
pub fn disabled() -> Self {
Self::Simple(SimpleTrustedProxyLayer::disabled())
}
@@ -195,20 +205,43 @@ where
#[derive(Clone, Debug, Default)]
pub struct SimpleTrustedProxyLayer {
enabled: bool,
trusted_proxies: Arc<Vec<TrustedProxy>>,
}
impl SimpleTrustedProxyLayer {
/// Creates an enabled simple layer using the operator-configured trusted proxy list
/// (`RUSTFS_TRUSTED_PROXY_NETWORKS`, `RUSTFS_TRUSTED_PROXY_EXTRA_NETWORKS`,
/// `RUSTFS_TRUSTED_PROXY_IPS`), falling back to loopback-only (`127.0.0.1`, `::1`).
pub fn enabled() -> Self {
Self { enabled: true }
Self {
enabled: true,
trusted_proxies: Arc::new(ConfigLoader::from_env_or_default().proxy.proxies),
}
}
/// Creates an enabled simple layer trusting only the explicitly supplied proxy entries.
pub fn with_trusted_proxies(trusted_proxies: Vec<TrustedProxy>) -> Self {
Self {
enabled: true,
trusted_proxies: Arc::new(trusted_proxies),
}
}
pub fn disabled() -> Self {
Self { enabled: false }
Self {
enabled: false,
trusted_proxies: Arc::new(Vec::new()),
}
}
pub fn is_enabled(&self) -> bool {
self.enabled
}
/// Returns the configured trusted proxy entries enforced by this layer.
pub fn trusted_proxies(&self) -> &[TrustedProxy] {
&self.trusted_proxies
}
}
impl<S> Layer<S> for SimpleTrustedProxyLayer {
@@ -218,6 +251,7 @@ impl<S> Layer<S> for SimpleTrustedProxyLayer {
SimpleTrustedProxyMiddleware {
inner,
enabled: self.enabled,
trusted_proxies: Arc::clone(&self.trusted_proxies),
}
}
}
@@ -227,6 +261,7 @@ impl<S> Layer<S> for SimpleTrustedProxyLayer {
pub struct SimpleTrustedProxyMiddleware<S> {
inner: S,
enabled: bool,
trusted_proxies: Arc<Vec<TrustedProxy>>,
}
impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for SimpleTrustedProxyMiddleware<S>
@@ -246,7 +281,7 @@ where
fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
if self.enabled {
let peer_addr = req.extensions().get::<SocketAddr>().copied();
if peer_addr.is_some_and(|peer| is_internal_ip(peer.ip()))
if peer_addr.is_some_and(|peer| is_trusted_proxy_ip(peer.ip(), &self.trusted_proxies))
&& (req.headers().contains_key(HEADER_X_FORWARDED_FOR)
|| req.headers().contains_key("forwarded")
|| req.headers().contains_key("x-real-ip"))
@@ -256,7 +291,7 @@ where
*response.status_mut() = StatusCode::BAD_REQUEST;
return Either::Right(ready(Ok(response)));
}
let client_info = resolve_client_info(peer_addr, req.headers());
let client_info = resolve_client_info_with_proxies(peer_addr, req.headers(), &self.trusted_proxies);
req.extensions_mut().insert(client_info);
} else {
debug!("Simple trusted proxy middleware is disabled");
@@ -266,27 +301,28 @@ where
}
}
fn resolve_client_info(peer_addr: Option<SocketAddr>, headers: &HeaderMap) -> ClientInfo {
fn resolve_client_info_with_proxies(
peer_addr: Option<SocketAddr>,
headers: &HeaderMap,
trusted_proxies: &[TrustedProxy],
) -> ClientInfo {
let Some(peer_addr) = peer_addr else {
return ClientInfo::direct(SocketAddr::new(IpAddr::from([0, 0, 0, 0]), 0));
};
if !is_internal_ip(peer_addr.ip()) {
if !is_trusted_proxy_ip(peer_addr.ip(), trusted_proxies) {
return ClientInfo::direct(peer_addr);
}
match forwarded_client_ip(headers) {
Some(real_ip) if is_usable_ip(real_ip) && real_ip != peer_addr.ip() => ClientInfo::from_trusted_proxy(
real_ip,
forwarded_host(headers),
forwarded_proto(headers),
peer_addr.ip(),
1,
ValidationMode::Lenient,
Vec::new(),
),
_ => ClientInfo::direct(peer_addr),
let real_ip = forwarded_client_ip(headers)
.filter(|ip| is_usable_ip(*ip))
.unwrap_or(peer_addr.ip());
let host = forwarded_host(headers);
let proto = forwarded_proto(headers);
if real_ip == peer_addr.ip() && host.is_none() && proto.is_none() {
return ClientInfo::direct(peer_addr);
}
ClientInfo::from_trusted_proxy(real_ip, host, proto, peer_addr.ip(), 1, ValidationMode::Lenient, Vec::new())
}
fn forwarded_client_ip(headers: &HeaderMap) -> Option<IpAddr> {
@@ -367,11 +403,9 @@ fn parse_ip_token(value: &str) -> Option<IpAddr> {
None
}
fn is_internal_ip(ip: IpAddr) -> bool {
match ip.to_canonical() {
IpAddr::V4(ip) => ip.is_private() || ip.is_loopback() || ip.is_link_local(),
IpAddr::V6(ip) => ip.is_loopback() || ip.is_unique_local() || ip.is_unicast_link_local(),
}
fn is_trusted_proxy_ip(ip: IpAddr, trusted_proxies: &[TrustedProxy]) -> bool {
let canonical = ip.to_canonical();
trusted_proxies.iter().any(|proxy| proxy.contains(&canonical))
}
fn is_usable_ip(ip: IpAddr) -> bool {
@@ -393,14 +427,22 @@ fn parse_implementation(value: Option<&str>) -> TrustedProxyImplementation {
mod tests {
use super::{
ENV_TRUSTED_PROXY_IMPLEMENTATION, HEADER_FORWARDED, HEADER_X_FORWARDED_FOR, HEADER_X_FORWARDED_HOST,
HEADER_X_FORWARDED_PROTO, HEADER_X_FORWARDED_SCHEME, HEADER_X_REAL_IP, TrustedProxyImplementation, TrustedProxyLayer,
forwarded_client_ip, forwarded_host, forwarded_proto, is_internal_ip, parse_implementation, parse_ip_token,
resolve_client_info,
HEADER_X_FORWARDED_PROTO, HEADER_X_FORWARDED_SCHEME, HEADER_X_REAL_IP, SimpleTrustedProxyLayer,
TrustedProxyImplementation, TrustedProxyLayer, forwarded_client_ip, forwarded_host, forwarded_proto, is_trusted_proxy_ip,
parse_implementation, parse_ip_token, resolve_client_info_with_proxies,
};
use crate::ClientInfo;
use axum::http::{HeaderMap, HeaderValue};
use crate::{ClientInfo, ConfigLoader, TrustedProxy};
use axum::http::{HeaderMap, HeaderValue, Request, Response, StatusCode};
use ipnetwork::IpNetwork;
use rustfs_config::{ENV_TRUSTED_PROXY_EXTRA_PROXIES, ENV_TRUSTED_PROXY_IPS, ENV_TRUSTED_PROXY_PROXIES};
use serial_test::serial;
use std::convert::Infallible;
use std::net::{IpAddr, SocketAddr};
use tower::{Layer, Service, service_fn};
fn default_loopback_proxies() -> Vec<TrustedProxy> {
ConfigLoader::default_config().proxy.proxies
}
#[test]
fn test_simple_mode_is_default() {
@@ -442,36 +484,100 @@ mod tests {
}
#[test]
fn test_internal_peer_can_override_real_ip() {
fn test_default_loopback_peer_can_override_real_ip() {
let mut headers = HeaderMap::new();
headers.insert(HEADER_X_FORWARDED_FOR, HeaderValue::from_static("203.0.113.10"));
let client_info = resolve_client_info(Some(SocketAddr::from(([10, 0, 0, 5], 9000))), &headers);
let proxies = default_loopback_proxies();
let client_info = resolve_client_info_with_proxies(Some(SocketAddr::from(([127, 0, 0, 1], 9000))), &headers, &proxies);
assert_eq!(client_info.real_ip, IpAddr::from([203, 0, 113, 10]));
assert!(client_info.is_from_trusted_proxy);
assert_eq!(client_info.proxy_ip, Some(IpAddr::from([10, 0, 0, 5])));
assert_eq!(client_info.proxy_ip, Some(IpAddr::from([127, 0, 0, 1])));
let ipv6_loopback: SocketAddr = "[::1]:9000".parse().expect("IPv6 loopback should parse");
let ipv6_info = resolve_client_info_with_proxies(Some(ipv6_loopback), &headers, &proxies);
assert_eq!(ipv6_info.real_ip, IpAddr::from([203, 0, 113, 10]));
assert!(ipv6_info.is_from_trusted_proxy);
}
#[test]
fn test_internal_peer_preserves_forwarded_proto_and_host() {
fn test_untrusted_private_and_link_local_peers_cannot_spoof_forwarding_headers_by_default() {
let mut headers = HeaderMap::new();
headers.insert(HEADER_X_FORWARDED_FOR, HeaderValue::from_static("203.0.113.10"));
headers.insert(HEADER_X_FORWARDED_HOST, HeaderValue::from_static("spoofed.example.test"));
headers.insert(HEADER_X_FORWARDED_PROTO, HeaderValue::from_static("https"));
let proxies = default_loopback_proxies();
for peer_ip in [
IpAddr::from([10, 0, 0, 5]),
IpAddr::from([172, 16, 0, 5]),
IpAddr::from([192, 168, 1, 20]),
IpAddr::from([169, 254, 1, 10]),
"fd00::1".parse().expect("ULA IPv6"),
"fe80::1".parse().expect("link-local IPv6"),
"::ffff:10.0.0.5".parse().expect("IPv4-mapped RFC1918"),
] {
let peer_addr = SocketAddr::new(peer_ip, 9000);
let client_info = resolve_client_info_with_proxies(Some(peer_addr), &headers, &proxies);
assert_eq!(
client_info.real_ip,
peer_ip.to_canonical(),
"untrusted internal peer {peer_ip} must not spoof real_ip"
);
assert!(!client_info.is_from_trusted_proxy, "peer {peer_ip} must not be trusted by default");
assert_eq!(client_info.forwarded_host, None, "peer {peer_ip} must not spoof forwarded_host");
assert_eq!(client_info.forwarded_proto, None, "peer {peer_ip} must not spoof forwarded_proto");
}
}
#[test]
fn test_explicitly_configured_proxy_cidr_is_honored_and_bounded() {
let mut headers = HeaderMap::new();
headers.insert(HEADER_X_FORWARDED_FOR, HeaderValue::from_static("198.51.100.7, 203.0.113.10"));
headers.insert(HEADER_X_FORWARDED_HOST, HeaderValue::from_static("s3.example.test"));
headers.insert(HEADER_X_FORWARDED_PROTO, HeaderValue::from_static("https"));
let client_info = resolve_client_info(Some(SocketAddr::from(([10, 0, 0, 5], 9000))), &headers);
let proxies = vec![TrustedProxy::Cidr("10.0.0.0/24".parse::<IpNetwork>().expect("CIDR"))];
assert_eq!(client_info.forwarded_host.as_deref(), Some("s3.example.test"));
assert_eq!(client_info.forwarded_proto.as_deref(), Some("https"));
let allowed = resolve_client_info_with_proxies(Some(SocketAddr::from(([10, 0, 0, 5], 9000))), &headers, &proxies);
assert_eq!(allowed.real_ip, IpAddr::from([203, 0, 113, 10]));
assert!(allowed.is_from_trusted_proxy);
assert_eq!(allowed.proxy_ip, Some(IpAddr::from([10, 0, 0, 5])));
assert_eq!(allowed.forwarded_host.as_deref(), Some("s3.example.test"));
assert_eq!(allowed.forwarded_proto.as_deref(), Some("https"));
// An adjacent RFC1918 peer outside the configured CIDR must not be trusted.
let outside = resolve_client_info_with_proxies(Some(SocketAddr::from(([10, 0, 1, 5], 9000))), &headers, &proxies);
assert_eq!(outside.real_ip, IpAddr::from([10, 0, 1, 5]));
assert!(!outside.is_from_trusted_proxy);
assert_eq!(outside.forwarded_host, None);
assert_eq!(outside.forwarded_proto, None);
}
#[test]
fn test_internal_peer_ignores_unselected_forwarded_scheme() {
fn trusted_tls_terminator_can_forward_origin_without_client_ip() {
let mut headers = HeaderMap::new();
headers.insert(HEADER_X_FORWARDED_PROTO, HeaderValue::from_static("https"));
headers.insert(HEADER_X_FORWARDED_HOST, HeaderValue::from_static("console.example.test"));
let proxies = vec![TrustedProxy::Single(IpAddr::from([10, 0, 0, 5]))];
for (last, trusted) in [(5, true), (6, false)] {
let peer = SocketAddr::from(([10, 0, 0, last], 9000));
let info = resolve_client_info_with_proxies(Some(peer), &headers, &proxies);
assert_eq!(info.real_ip, peer.ip());
assert_eq!(info.is_from_trusted_proxy, trusted);
assert_eq!(info.forwarded_proto.as_deref(), trusted.then_some("https"));
assert_eq!(info.forwarded_host.as_deref(), trusted.then_some("console.example.test"));
}
}
#[test]
fn test_trusted_peer_ignores_unselected_forwarded_scheme() {
let mut headers = HeaderMap::new();
headers.insert(HEADER_X_FORWARDED_FOR, HeaderValue::from_static("203.0.113.10"));
headers.insert(HEADER_X_FORWARDED_SCHEME, HeaderValue::from_static("https"));
let client_info = resolve_client_info(Some(SocketAddr::from(([10, 0, 0, 5], 9000))), &headers);
let proxies = vec![TrustedProxy::Single(IpAddr::from([10, 0, 0, 5]))];
let client_info = resolve_client_info_with_proxies(Some(SocketAddr::from(([10, 0, 0, 5], 9000))), &headers, &proxies);
assert_eq!(client_info.forwarded_proto, None);
}
@@ -484,7 +590,8 @@ mod tests {
HeaderValue::from_static("for=203.0.113.10;proto=https;host=s3.example.test"),
);
let client_info = resolve_client_info(Some(SocketAddr::from(([10, 0, 0, 5], 9000))), &headers);
let proxies = vec![TrustedProxy::Single(IpAddr::from([10, 0, 0, 5]))];
let client_info = resolve_client_info_with_proxies(Some(SocketAddr::from(([10, 0, 0, 5], 9000))), &headers, &proxies);
assert_eq!(client_info.real_ip, IpAddr::from([10, 0, 0, 5]));
assert_eq!(client_info.forwarded_host, None);
@@ -507,22 +614,22 @@ mod tests {
headers.insert(HEADER_X_FORWARDED_FOR, HeaderValue::from_static("203.0.113.10"));
let peer_addr = SocketAddr::from(([8, 8, 8, 8], 9000));
let client_info = resolve_client_info(Some(peer_addr), &headers);
let client_info = resolve_client_info_with_proxies(Some(peer_addr), &headers, &default_loopback_proxies());
assert_eq!(client_info.real_ip, peer_addr.ip());
assert!(!client_info.is_from_trusted_proxy);
}
#[test]
fn test_missing_headers_keep_direct_ip() {
let peer_addr = SocketAddr::from(([192, 168, 1, 20], 9000));
let client_info = resolve_client_info(Some(peer_addr), &HeaderMap::new());
let peer_addr = SocketAddr::from(([127, 0, 0, 1], 9000));
let client_info = resolve_client_info_with_proxies(Some(peer_addr), &HeaderMap::new(), &default_loopback_proxies());
assert_eq!(client_info.real_ip, peer_addr.ip());
assert!(!client_info.is_from_trusted_proxy);
}
#[test]
fn test_missing_peer_addr_uses_direct_placeholder() {
let client_info = resolve_client_info(None, &HeaderMap::new());
let client_info = resolve_client_info_with_proxies(None, &HeaderMap::new(), &default_loopback_proxies());
assert_eq!(
client_info.real_ip,
ClientInfo::direct(SocketAddr::new(IpAddr::from([0, 0, 0, 0]), 0)).real_ip
@@ -546,11 +653,77 @@ mod tests {
}
#[test]
fn test_internal_ip_detection() {
assert!(is_internal_ip(IpAddr::from([10, 0, 0, 1])));
assert!(is_internal_ip(IpAddr::from([127, 0, 0, 1])));
assert!(is_internal_ip("fd00::1".parse().unwrap()));
assert!(!is_internal_ip(IpAddr::from([203, 0, 113, 10])));
fn test_trusted_proxy_ip_matching() {
let proxies = vec![
TrustedProxy::Single(IpAddr::from([127, 0, 0, 1])),
TrustedProxy::Cidr("10.20.0.0/24".parse::<IpNetwork>().expect("CIDR")),
];
assert!(is_trusted_proxy_ip(IpAddr::from([127, 0, 0, 1]), &proxies));
assert!(is_trusted_proxy_ip("::ffff:127.0.0.1".parse().expect("mapped loopback"), &proxies));
assert!(is_trusted_proxy_ip(IpAddr::from([10, 20, 0, 42]), &proxies));
assert!(!is_trusted_proxy_ip(IpAddr::from([10, 20, 1, 1]), &proxies));
assert!(!is_trusted_proxy_ip(IpAddr::from([192, 168, 1, 1]), &proxies));
assert!(!is_trusted_proxy_ip("fd00::1".parse().expect("ULA"), &proxies));
assert!(!is_trusted_proxy_ip(IpAddr::from([203, 0, 113, 10]), &proxies));
}
#[tokio::test]
async fn test_middleware_rejects_malformed_forwarded_from_trusted_proxy_but_ignores_untrusted_private_peer() {
let layer = SimpleTrustedProxyLayer::with_trusted_proxies(default_loopback_proxies());
let mut svc = layer.layer(service_fn(|req: Request<()>| async move {
let info = req
.extensions()
.get::<ClientInfo>()
.cloned()
.expect("middleware must attach ClientInfo");
let mut resp = Response::new(String::new());
resp.headers_mut()
.insert("x-observed-real-ip", HeaderValue::from_str(&info.real_ip.to_string()).expect("header"));
resp.headers_mut().insert(
"x-observed-trusted",
HeaderValue::from_static(if info.is_from_trusted_proxy { "true" } else { "false" }),
);
Ok::<_, Infallible>(resp)
}));
// Untrusted private peer sending malformed X-Forwarded-For is treated as direct (not trusted, not 400).
let mut untrusted_req = Request::builder()
.header(HEADER_X_FORWARDED_FOR, "not-an-ip")
.body(())
.expect("request");
untrusted_req.extensions_mut().insert(SocketAddr::from(([10, 0, 0, 9], 4321)));
let untrusted_resp = svc.call(untrusted_req).await.expect("infallible");
assert_eq!(untrusted_resp.status(), StatusCode::OK);
assert_eq!(untrusted_resp.headers().get("x-observed-real-ip").unwrap(), "10.0.0.9");
assert_eq!(untrusted_resp.headers().get("x-observed-trusted").unwrap(), "false");
// Trusted loopback proxy sending malformed X-Forwarded-For fails closed with 400.
let mut trusted_req = Request::builder()
.header(HEADER_X_FORWARDED_FOR, "not-an-ip")
.body(())
.expect("request");
trusted_req.extensions_mut().insert(SocketAddr::from(([127, 0, 0, 1], 4321)));
let trusted_resp = svc.call(trusted_req).await.expect("infallible");
assert_eq!(trusted_resp.status(), StatusCode::BAD_REQUEST);
}
#[test]
#[serial]
fn test_simple_layer_loads_configured_networks_from_env() {
temp_env::with_vars(
[
(ENV_TRUSTED_PROXY_PROXIES, Some("10.42.0.0/24")),
(ENV_TRUSTED_PROXY_EXTRA_PROXIES, Some("")),
(ENV_TRUSTED_PROXY_IPS, Some("198.51.100.5")),
],
|| {
let layer = SimpleTrustedProxyLayer::enabled();
assert!(is_trusted_proxy_ip(IpAddr::from([10, 42, 0, 9]), layer.trusted_proxies()));
assert!(is_trusted_proxy_ip(IpAddr::from([198, 51, 100, 5]), layer.trusted_proxies()));
assert!(!is_trusted_proxy_ip(IpAddr::from([10, 42, 1, 9]), layer.trusted_proxies()));
assert!(!is_trusted_proxy_ip(IpAddr::from([192, 168, 1, 1]), layer.trusted_proxies()));
},
);
}
#[test]
+26 -12
View File
@@ -16,13 +16,14 @@ use axum::{
body::{self, Body},
http::{Request, Response},
};
use rustfs_trusted_proxies::{ClientInfo, TrustedProxyLayer};
use rustfs_trusted_proxies::{ClientInfo, TrustedProxy, TrustedProxyLayer};
use std::convert::Infallible;
use std::net::SocketAddr;
use tower::{Layer, ServiceExt, service_fn};
#[tokio::test]
async fn simple_proxy_uses_only_the_rightmost_observed_peer() {
let trusted_peer: SocketAddr = "[::ffff:10.0.0.5]:9000".parse().expect("peer");
for (chain, expected) in [
("203.0.113.7, 198.51.100.9", "198.51.100.9"),
("203.0.113.7, 10.20.0.9", "10.20.0.9"),
@@ -34,11 +35,9 @@ async fn simple_proxy_uses_only_the_rightmost_observed_peer() {
assert_eq!(info.forwarded_proto.as_deref(), Some("http"));
Ok::<_, Infallible>(Response::new(Body::from(info.real_ip.to_string())))
});
let service = TrustedProxyLayer::enabled().layer(service);
let service = TrustedProxyLayer::with_trusted_proxies(vec![TrustedProxy::Single(trusted_peer.ip())]).layer(service);
let mut request = Request::builder().body(Body::empty()).expect("request");
request
.extensions_mut()
.insert("[::ffff:10.0.0.5]:9000".parse::<SocketAddr>().expect("peer"));
request.extensions_mut().insert(trusted_peer);
request
.headers_mut()
.append("x-forwarded-for", "203.0.113.1".parse().expect("forged line"));
@@ -84,7 +83,7 @@ async fn invalid_proxy_chains_never_reach_the_inner_service() {
async { Ok::<_, Infallible>(Response::new(Body::empty())) }
});
let layer = match mode {
None => TrustedProxyLayer::enabled(),
None => TrustedProxyLayer::with_trusted_proxies(vec![TrustedProxy::Single(peer.ip())]),
Some(mode) => TrustedProxyLayer::legacy(LegacyTrustedProxyLayer::enabled(
TrustedProxyConfig::new(vec![TrustedProxy::Single(peer.ip())], mode, false, 3, false, vec![]),
None,
@@ -185,21 +184,36 @@ async fn legacy_proxy_selects_one_family_and_preserves_repeated_lines() {
#[tokio::test]
async fn test_layer_inserts_client_info_for_internal_proxy() {
let peer_addr = SocketAddr::from(([10, 0, 0, 5], 9000));
let service = service_fn(|request: Request<Body>| async move {
// Unconfigured RFC1918 peer is NOT trusted by default; forwarding headers are ignored.
let default_service = TrustedProxyLayer::enabled().layer(service_fn(|request: Request<Body>| async move {
let client_info = request.extensions().get::<ClientInfo>().cloned().unwrap();
Ok::<_, Infallible>(Response::new(Body::from(client_info.real_ip.to_string())))
});
let service = TrustedProxyLayer::enabled().layer(service);
}));
let mut untrusted_request = Request::builder()
.uri("/")
.header("x-forwarded-for", "203.0.113.10")
.body(Body::empty())
.unwrap();
untrusted_request.extensions_mut().insert(peer_addr);
let untrusted_response = default_service.oneshot(untrusted_request).await.unwrap();
let untrusted_body = body::to_bytes(untrusted_response.into_body(), usize::MAX).await.unwrap();
assert_eq!(std::str::from_utf8(&untrusted_body).unwrap(), "10.0.0.5");
// Explicitly configured proxy peer IS trusted and resolves the forwarded client IP.
let configured_service = TrustedProxyLayer::with_trusted_proxies(vec![TrustedProxy::Single(peer_addr.ip())]).layer(
service_fn(|request: Request<Body>| async move {
let client_info = request.extensions().get::<ClientInfo>().cloned().unwrap();
Ok::<_, Infallible>(Response::new(Body::from(client_info.real_ip.to_string())))
}),
);
let mut request = Request::builder()
.uri("/")
.header("x-forwarded-for", "203.0.113.10")
.body(Body::empty())
.unwrap();
request.extensions_mut().insert(peer_addr);
let response = service.oneshot(request).await.unwrap();
let response = configured_service.oneshot(request).await.unwrap();
let body = body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
assert_eq!(std::str::from_utf8(&body).unwrap(), "203.0.113.10");
}
+315 -56
View File
@@ -450,14 +450,90 @@ impl OutboundPolicy {
}
pub fn validate_url(&self, url: &Url) -> Result<(), OutboundPolicyError> {
self.validate_target(url).map(|_| ())
self.validate_target(url, false, false).map(|_| ())
}
pub fn resolver_for(&self, url: &Url) -> Result<OutboundDnsResolver, OutboundPolicyError> {
let target = self.validate_target(url)?;
let target = self.validate_target(url, false, false)?;
Ok(OutboundDnsResolver::new(target.host, target.allow_restricted))
}
/// Validate an outbound URL while allowing non-metadata private storage endpoints
/// (RFC1918 and IPv6 ULA excluding cloud metadata addresses).
pub fn validate_url_allow_private(&self, url: &Url) -> Result<(), OutboundPolicyError> {
self.validate_storage_url(url, true, false)
}
/// Validate an outbound storage endpoint URL with explicit private-network and
/// loopback opt-ins. Link-local, metadata, unspecified, and translation ranges
/// remain unconditionally forbidden.
pub fn validate_storage_url(&self, url: &Url, allow_private: bool, allow_loopback: bool) -> Result<(), OutboundPolicyError> {
self.validate_target(url, allow_private, allow_loopback).map(|_| ())
}
/// Virtual-hosted S3 requests may connect to the endpoint or its bucket subdomain.
/// Each needs its own exact origin allowance to use restricted addresses.
pub fn resolver_for_virtual_bucket(&self, endpoint: &Url, bucket: &str) -> Result<OutboundDnsResolver, OutboundPolicyError> {
let mut resolver = self.resolver_for(endpoint)?;
let host = format!("{bucket}.{}", endpoint.host_str().ok_or(OutboundPolicyError::MissingHost)?);
let mut target = endpoint.clone();
target.set_host(Some(&host)).map_err(|_| OutboundPolicyError::ForbiddenHost {
host,
reason: "invalid tier bucket hostname",
})?;
let target = self.validate_target(&target, false, false)?;
if target.allow_restricted {
resolver.allowed_restricted_hosts.push(target.host);
}
Ok(resolver)
}
/// Validate an outbound URL and construct a connection-time DNS resolver that allows
/// non-metadata private storage endpoints while still blocking loopback, link-local,
/// metadata, unspecified, shared, and special-use addresses (including via DNS rebinding).
pub fn resolver_for_allow_private(&self, url: &Url) -> Result<OutboundDnsResolver, OutboundPolicyError> {
self.resolver_for_storage_endpoint(url, true, false)
}
/// Validate a storage endpoint URL and construct a connection-time DNS resolver with
/// explicit private-network and loopback opt-ins.
pub fn resolver_for_storage_endpoint(
&self,
url: &Url,
allow_private: bool,
allow_loopback: bool,
) -> Result<OutboundDnsResolver, OutboundPolicyError> {
let target = self.validate_target(url, allow_private, allow_loopback)?;
Ok(OutboundDnsResolver::with_options(
target.host,
target.allow_restricted,
allow_private,
allow_loopback,
))
}
/// Validate a URL and resolve + filter its current DNS addresses against this policy.
///
/// Prefer binding [`Self::resolver_for`] (or [`Self::resolver_for_allow_private`]) directly
/// to the HTTP client's connection-time DNS resolver whenever the transport supports it, so
/// DNS rebinding between validation and connection is also prevented.
pub async fn resolve_and_validate_url(&self, url: &Url) -> std::io::Result<Vec<SocketAddr>> {
let resolver = self
.resolver_for(url)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::PermissionDenied, err))?;
let host = normalized_host(url)
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, OutboundPolicyError::MissingHost))?;
let port = url.port_or_known_default().unwrap_or(0);
if let Ok(ip) = host.parse::<IpAddr>() {
return Ok(vec![SocketAddr::new(ip, port)]);
}
let mut addrs = resolver.resolve_host(&host).await?;
for addr in &mut addrs {
addr.set_port(port);
}
Ok(addrs)
}
/// Configures `builder` for a single outbound request to `url` using system proxy settings.
///
/// # Errors
@@ -505,7 +581,7 @@ impl OutboundPolicy {
dns_override: Option<OutboundDnsLookup>,
builder: reqwest::ClientBuilder,
) -> Result<reqwest::ClientBuilder, OutboundClientError> {
let target = self.validate_target(url)?;
let target = self.validate_target(url, false, false)?;
if !target.bypass_proxy
&& let Some(matched_proxy) = proxy_matcher.match_target(&target, url)?
@@ -530,7 +606,12 @@ impl OutboundPolicy {
Ok(builder.no_proxy().dns_resolver(target_resolver))
}
fn validate_target(&self, url: &Url) -> Result<ValidatedTarget, OutboundPolicyError> {
fn validate_target(
&self,
url: &Url,
allow_private: bool,
allow_loopback: bool,
) -> Result<ValidatedTarget, OutboundPolicyError> {
validate_http_url_shape(url)?;
let raw_host = url.host_str().ok_or(OutboundPolicyError::MissingHost)?;
let normalized = normalize_host_str(raw_host);
@@ -542,9 +623,9 @@ impl OutboundPolicy {
let is_ipv6 = parsed_ip.is_some_and(|ip| ip.is_ipv6());
let bypass_proxy = host == "localhost" || parsed_ip.is_some_and(is_loopback_ip);
let classification = if host == "localhost" {
Err("loopback host")
if allow_loopback { Ok(()) } else { Err("loopback host") }
} else if let Some(ip) = parsed_ip {
validate_policy_ip(ip)
validate_policy_ip_with_options(ip, allow_private, allow_loopback)
} else {
Ok(())
};
@@ -578,7 +659,9 @@ impl OutboundPolicy {
#[derive(Clone)]
pub struct OutboundDnsResolver {
peer_kind: OutboundPeerKind,
allowed_restricted_host: Option<String>,
allowed_restricted_hosts: Vec<String>,
allow_private: bool,
allow_loopback_host: Option<String>,
lookup_override: Option<OutboundDnsLookup>,
}
@@ -586,7 +669,9 @@ impl fmt::Debug for OutboundDnsResolver {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OutboundDnsResolver")
.field("peer_kind", &self.peer_kind)
.field("allowed_restricted_host", &self.allowed_restricted_host)
.field("allowed_restricted_hosts", &self.allowed_restricted_hosts)
.field("allow_private", &self.allow_private)
.field("allow_loopback_host", &self.allow_loopback_host)
.field("has_lookup_override", &self.lookup_override.is_some())
.finish()
}
@@ -594,9 +679,15 @@ impl fmt::Debug for OutboundDnsResolver {
impl OutboundDnsResolver {
fn new(host: String, allow_restricted: bool) -> Self {
Self::with_options(host, allow_restricted, false, false)
}
fn with_options(host: String, allow_restricted: bool, allow_private: bool, allow_loopback: bool) -> Self {
Self {
peer_kind: OutboundPeerKind::Target,
allowed_restricted_host: allow_restricted.then_some(host),
allowed_restricted_hosts: if allow_restricted { vec![host.clone()] } else { Vec::new() },
allow_private,
allow_loopback_host: allow_loopback.then_some(host),
lookup_override: None,
}
}
@@ -609,7 +700,9 @@ impl OutboundDnsResolver {
pub fn for_proxy() -> Self {
Self {
peer_kind: OutboundPeerKind::Proxy,
allowed_restricted_host: None,
allowed_restricted_hosts: Vec::new(),
allow_private: false,
allow_loopback_host: None,
lookup_override: None,
}
}
@@ -646,62 +739,94 @@ impl OutboundDnsResolver {
}
}))
}
/// Inject a DNS lookup for a caller while applying the same address policy.
#[doc(hidden)]
pub fn with_resolve_override<F>(self, lookup: F) -> Self
where
F: Fn(&str) -> Option<Vec<SocketAddr>> + Send + Sync + 'static,
{
self.with_lookup_override(Arc::new(lookup))
}
/// Filter resolved addresses for `host` according to this resolver's outbound policy.
pub fn filter_resolved_addresses(&self, host: &str, addresses: Vec<SocketAddr>) -> std::io::Result<Vec<SocketAddr>> {
let normalized_host = host.trim_end_matches('.').trim_matches(['[', ']']).to_ascii_lowercase();
if addresses.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("DNS resolution for '{normalized_host}' returned no addresses"),
));
}
let allow_restricted = self.allowed_restricted_hosts.contains(&normalized_host);
let allow_loopback = self.allow_loopback_host.as_deref() == Some(normalized_host.as_str());
let mut recoverable = false;
let addrs = addresses
.into_iter()
.filter(|address| match self.peer_kind {
OutboundPeerKind::Proxy => validate_policy_ip(address.ip())
.err()
.is_none_or(proxy_restricted_reason_allowed),
OutboundPeerKind::Target => {
match validate_policy_ip_with_options(address.ip(), self.allow_private, allow_loopback) {
Ok(()) => true,
Err(reason) => {
let can_override = restricted_reason_can_be_overridden(reason);
recoverable |= can_override;
allow_restricted && can_override
}
}
}
})
.collect::<Vec<_>>();
if addrs.is_empty() {
let rejection = match self.peer_kind {
OutboundPeerKind::Target => OutboundDnsPolicyRejection::new(normalized_host, recoverable),
OutboundPeerKind::Proxy => OutboundDnsPolicyRejection::new_proxy(normalized_host),
};
return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, rejection));
}
Ok(addrs)
}
/// Perform a fresh uncached DNS lookup for `host` and filter every returned address
/// against this resolver's outbound policy.
pub async fn resolve_host(&self, host: &str) -> std::io::Result<Vec<SocketAddr>> {
let normalized_host = host.trim_end_matches('.').trim_matches(['[', ']']).to_ascii_lowercase();
let overridden = self.lookup_override.as_ref().and_then(|lookup| lookup(&normalized_host));
let addresses = if let Some(addresses) = overridden {
addresses
} else {
// Do not use the cached resolver in `crate::net`: every new connection must
// classify the addresses returned at that boundary so DNS rebinding fails closed.
tokio::net::lookup_host((normalized_host.as_str(), 0))
.await
.map_err(|err| std::io::Error::new(std::io::ErrorKind::NotFound, err))?
.collect()
};
self.filter_resolved_addresses(&normalized_host, addresses)
}
}
impl reqwest::dns::Resolve for OutboundDnsResolver {
fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
let host = name.as_str().trim_end_matches('.').to_ascii_lowercase();
let peer_kind = self.peer_kind;
let allow_restricted =
peer_kind == OutboundPeerKind::Target && self.allowed_restricted_host.as_deref() == Some(host.as_str());
let lookup_override = self.lookup_override.clone();
let resolver = self.clone();
let host = name.as_str().to_string();
Box::pin(async move {
let overridden = lookup_override.as_ref().and_then(|lookup| lookup(&host));
let addresses = if let Some(addresses) = overridden {
addresses
} else {
// Do not use the cached resolver in `crate::net`: every new connection must
// classify the addresses returned at that boundary so DNS rebinding fails closed.
tokio::net::lookup_host((host.as_str(), 0))
.await
.map_err(|err| std::io::Error::new(std::io::ErrorKind::NotFound, err))?
.collect()
};
if addresses.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("DNS resolution for '{host}' returned no addresses"),
)
.into());
}
let mut allow_origin_can_recover = false;
let addrs = addresses
.into_iter()
.filter(|address| match validate_policy_ip(address.ip()) {
Ok(()) => true,
Err(reason) => match peer_kind {
OutboundPeerKind::Target => {
let recoverable = restricted_reason_can_be_overridden(reason);
allow_origin_can_recover |= recoverable;
allow_restricted && recoverable
}
OutboundPeerKind::Proxy => proxy_restricted_reason_allowed(reason),
},
})
.collect::<Vec<_>>();
if addrs.is_empty() {
let rejection = match peer_kind {
OutboundPeerKind::Target => OutboundDnsPolicyRejection::new(host, allow_origin_can_recover),
OutboundPeerKind::Proxy => OutboundDnsPolicyRejection::new_proxy(host),
};
return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, rejection).into());
}
let addrs = resolver.resolve_host(&host).await?;
Ok(Box::new(addrs.into_iter()) as reqwest::dns::Addrs)
})
}
}
/// Syntax and literal-IP preflight check for outbound URLs.
///
/// This helper rejects `localhost` and forbidden literal IP addresses, but does not
/// resolve hostnames or prevent DNS rebinding. Callers making outbound HTTP requests to
/// hostname-bearing URLs must pair URL validation with [`OutboundPolicy::resolver_for`]
/// at the connection boundary.
pub fn validate_outbound_url(url: &Url) -> Result<(), OutboundUrlError> {
let Some(raw_host) = url.host_str() else {
return Err(OutboundUrlError::MissingHost);
@@ -806,6 +931,41 @@ fn proxy_restricted_reason_allowed(reason: &str) -> bool {
matches!(reason, "loopback host" | "loopback address" | "private address" | "shared address")
}
fn validate_policy_ip_with_options(ip: IpAddr, allow_private: bool, allow_loopback: bool) -> Result<(), &'static str> {
match validate_policy_ip(ip) {
Ok(()) => Ok(()),
Err("private address") if allow_private && is_storage_private_ip(ip) => Ok(()),
Err("loopback address") if allow_loopback && is_direct_loopback_ip(ip) => Ok(()),
Err(reason) => Err(reason),
}
}
fn is_storage_private_ip(ip: IpAddr) -> bool {
if is_metadata_endpoint(ip) {
return false;
}
let ip = match ip {
IpAddr::V6(v6) => {
if v6.is_unique_local() {
return true;
}
match embedded_ipv4(v6) {
Some(v4) => IpAddr::V4(v4),
None => return false,
}
}
IpAddr::V4(v4) => IpAddr::V4(v4),
};
!is_metadata_endpoint(ip) && matches!(ip, IpAddr::V4(v4) if v4.is_private())
}
fn is_direct_loopback_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => v4.is_loopback(),
IpAddr::V6(v6) => v6.is_loopback() || embedded_ipv4(v6).is_some_and(|v4| v4.is_loopback()),
}
}
fn validate_policy_ip(ip: IpAddr) -> Result<(), &'static str> {
if is_metadata_endpoint(ip) {
return Err("metadata endpoint");
@@ -995,6 +1155,36 @@ mod tests {
use std::sync::{Arc, Mutex};
use url::Url;
#[test]
fn virtual_bucket_dns_checks_the_exact_origin_for_private_addresses() {
let endpoint = Url::parse("https://oss.example.test:8443").unwrap();
let policy = OutboundPolicy::from_allowed_origins(
"https://oss.example.test:8443,https://archive.oss.example.test:8443,https://other.oss.example.test:443",
)
.unwrap();
let private = vec!["10.10.0.8:0".parse::<SocketAddr>().unwrap()];
for (bucket, allowed) in [("archive", true), ("other", false)] {
let resolver = policy.resolver_for_virtual_bucket(&endpoint, bucket).unwrap();
assert_eq!(
resolver
.filter_resolved_addresses("oss.example.test", private.clone())
.unwrap(),
private
);
assert_eq!(
resolver
.filter_resolved_addresses(&format!("{bucket}.oss.example.test"), private.clone())
.is_ok(),
allowed
);
assert!(
resolver
.filter_resolved_addresses("unlisted.oss.example.test", private.clone())
.is_err()
);
}
}
#[test]
fn validate_outbound_url_allows_public_hostname() {
let url = Url::parse("https://example.com/webhook").expect("public URL should parse");
@@ -2234,4 +2424,73 @@ mod tests {
);
}
}
#[tokio::test]
async fn resolver_for_allow_private_permits_private_storage_but_blocks_loopback_and_metadata() {
let policy = OutboundPolicy::default();
let endpoint = Url::parse("https://private-tier.internal:9443").expect("endpoint should parse");
let resolver = policy
.resolver_for_allow_private(&endpoint)
.expect("private-storage policy should accept hostname")
.with_resolve_override(|host| match host {
"private-tier.internal" => Some(vec![
SocketAddr::new("10.20.30.40".parse().expect("RFC1918"), 0),
SocketAddr::new("fd12:3456::1".parse().expect("ULA"), 0),
SocketAddr::new("127.0.0.1".parse().expect("loopback"), 0),
SocketAddr::new("169.254.169.254".parse().expect("metadata"), 0),
SocketAddr::new("fd00:ec2::254".parse().expect("ipv6 metadata"), 0),
SocketAddr::new("64:ff9b::a00:1".parse().expect("nat64 private"), 0),
SocketAddr::new("2002:a00:1::".parse().expect("6to4 private"), 0),
]),
"rebound-loopback.internal" => Some(vec![SocketAddr::new("127.0.0.1".parse().expect("loopback"), 0)]),
"rebound-metadata.internal" => Some(vec![SocketAddr::new("169.254.169.254".parse().expect("metadata"), 0)]),
_ => None,
});
let resolved = resolver
.resolve_host("private-tier.internal")
.await
.expect("RFC1918 and non-metadata ULA answers should remain");
let ips = resolved.into_iter().map(|addr| addr.ip()).collect::<Vec<_>>();
assert_eq!(
ips,
vec![
"10.20.30.40".parse::<std::net::IpAddr>().expect("RFC1918"),
"fd12:3456::1".parse::<std::net::IpAddr>().expect("ULA"),
]
);
let loopback_err = resolver
.resolve_host("rebound-loopback.internal")
.await
.expect_err("loopback DNS rebind must fail closed even in private-storage mode");
assert_eq!(loopback_err.kind(), std::io::ErrorKind::PermissionDenied);
assert!(find_outbound_dns_policy_rejection(&loopback_err).is_some());
let metadata_err = resolver
.resolve_host("rebound-metadata.internal")
.await
.expect_err("metadata DNS rebind must fail closed even in private-storage mode");
assert_eq!(metadata_err.kind(), std::io::ErrorKind::PermissionDenied);
let rejection = find_outbound_dns_policy_rejection(&metadata_err).expect("typed metadata rejection");
assert!(!rejection.allow_origin_can_recover());
}
#[tokio::test]
async fn resolve_and_validate_url_blocks_literal_and_hostname_forbidden_targets() {
let policy = OutboundPolicy::default();
let loopback = Url::parse("http://127.0.0.1:9000/test").expect("loopback URL");
let err = policy
.resolve_and_validate_url(&loopback)
.await
.expect_err("literal loopback must be rejected");
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied);
let public_ip = Url::parse("https://8.8.8.8:8443/test").expect("public IP URL");
let addrs = policy
.resolve_and_validate_url(&public_ip)
.await
.expect("public literal IP should resolve without DNS");
assert_eq!(addrs, vec![SocketAddr::new("8.8.8.8".parse().expect("ip"), 8443)]);
}
}
+5 -2
View File
@@ -2,7 +2,7 @@
**Use this when:** large distributed reads stall, or you need to select the node-to-node HTTP protocol while retaining TLS and connection reuse.
The internode HTTP data plane defaults to pooled HTTP/1.1. Each active response has its own connection, so a paused shard body cannot exhaust HTTP/2 receive credit shared by other shard bodies. Bounded shard responses advertise their exact positive Content-Length so consuming the requested bytes completes HTTP framing without waiting for a chunked terminator. Requests with length zero retain the existing stream-to-EOF semantics. Completed responses can return their connections to the idle pool. TLS certificate verification, client identities, proxy policy, and certificate rotation use the existing client configuration.
The internode HTTP data plane defaults to pooled HTTP/1.1. Each active response has its own connection, so a paused shard body cannot exhaust HTTP/2 receive credit shared by other shard bodies. Legacy unframed responses for bounded shard reads advertise their exact positive Content-Length so consuming the requested bytes completes HTTP framing without waiting for a chunked terminator. Requests with length zero retain the existing stream-to-EOF semantics. Completed responses can return their connections to the idle pool. TLS certificate verification, client identities, proxy policy, and certificate rotation use the existing client configuration.
This setting covers internode shard reads, writes, and directory walks. It does not change the public S3 listener, gRPC control channels, or outbound replication and tier S3 clients.
@@ -11,14 +11,17 @@ This setting covers internode shard reads, writes, and directory walks. It does
| `RUSTFS_INTERNODE_HTTP_PROTOCOL` | `http1` | `http1` restricts the client to HTTP/1.1, including over TLS. `auto` restores the previous protocol negotiation: TLS ALPN can select HTTP/2; plaintext uses HTTP/1.1. Values are case insensitive and trimmed; missing or unknown values select `http1`. |
| `RUSTFS_INTERNODE_HTTP_POOL_MAX_IDLE_PER_HOST` | Existing tuning profile | Limits idle connections. `0` disables pooling entirely, including shared HTTP/2 connections. |
| `RUSTFS_INTERNODE_HTTP_POOL_IDLE_TIMEOUT_SECS` | Existing tuning profile | Evicts idle connections. It does not isolate concurrent HTTP/2 streams on an active connection. |
| `RUSTFS_INTERNODE_RPC_STREAM_AUTH_STRICT` | `false` | Require authenticated response frames for shard reads and directory walks on both client and server. Enable after every node supports framing. |
Set the protocol on every node and restart the processes. The node initiating a read, scan, or heal chooses the outbound protocol. With `http1`, retain the normal connection-pool settings; there is no need to set the maximum idle count to zero to isolate active bodies.
During a rolling upgrade, keep `RUSTFS_INTERNODE_HTTP_POOL_MAX_IDLE_PER_HOST=0` on older nodes that lack the protocol selector. Their coordinators, scanner and heal workers still choose the older outbound policy. After a node runs a release with the selector, use `http1` and restore its normal idle-pool setting. New response framing alone does not isolate streams initiated by an older HTTP/2 client.
Upgraded peers authenticate each data frame and the terminal frame. A client that verifies a frame requires framing from that endpoint until the client process restarts. Leave strict mode off during a mixed-version upgrade. For a rollback, disable strict mode, roll the peer back, then restart every RustFS node that read a signed shard or directory stream from that endpoint. Until restarted, those callers reject legacy reads and directory walks from the rolled-back peer. Schedule the caller restarts within the cluster’s quorum budget.
HTTP/2 window and adaptive-window settings apply only with `auto` and a TLS connection that negotiates HTTP/2. The `legacy`, `balanced`, and `throughput` tuning profiles continue to control their existing pool and window settings; none overrides the protocol policy.
HTTP/1.1 uses more concurrent connections than multiplexed HTTP/2. Size file-descriptor and connection budgets for the workload. For bounded reads, consuming the full advertised byte count completes HTTP framing and permits reuse without an additional EOF poll. Unknown-length reads still require EOF. Cancelled or partially consumed responses can close their connections. A bounded response that ends early is a transport error; the server retains its existing read cap and never pads or shrinks a short response into success. Disabling pooling also adds TCP/TLS setup and connection churn to subsequent requests. No universal throughput improvement is implied by the protocol default.
HTTP/1.1 uses more concurrent connections than multiplexed HTTP/2. Size file-descriptor and connection budgets for the workload. For legacy bounded reads, consuming the full advertised byte count completes HTTP framing and permits reuse without an additional EOF poll. Unknown-length reads still require EOF. Cancelled or partially consumed responses can close their connections. A bounded response that ends early is a transport error; the server retains its existing read cap and never pads or shrinks a short response into success. Disabling pooling also adds TCP/TLS setup and connection churn to subsequent requests. No universal throughput improvement is implied by the protocol default.
For validation, compare complete 100 MiB and 1 GiB GETs through every coordinator, verify lengths and hashes, and include concurrent GET, scanner, and heal activity. Record latency, stall errors, CPU, connection counts, and file descriptors. Include small objects and uploads when assessing a deployment's performance. Local transport tests exercise TLS ALPN, shared HTTP/2 backpressure, full-body delivery, and HTTP/1.1 idle reuse; they do not replace a distributed cluster run.
@@ -36,5 +36,7 @@ Workload-only providers cannot perform Console authorization-code login. Hiding
Operators who add, edit or remove OIDC providers through the admin API need both `admin:ConfigUpdate` and `admin:ManageOpenIDConfig`. Grant the latter only to administrators trusted to choose identity providers and their policy mappings. This also applies when a configuration import or history restore changes or removes a provider. Existing policies that grant only `admin:ConfigUpdate` can still update unrelated settings.
OIDC endpoints outside loopback require HTTPS by default. For an HTTP development provider, set `RUSTFS_IDENTITY_OPENID_ALLOW_INSECURE_TRANSPORT=true`. A private or loopback provider also needs its exact origin in `RUSTFS_OUTBOUND_ALLOW_ORIGINS`. The node must be able to reach the provider directly for discovery, key retrieval and token exchange.
- Behind a load balancer, authorize and callback requests must reach the same RustFS node while the `state` is in flight, or set `RUSTFS_BROWSER_REDIRECT_URL` so the callback URL is stable; the callback error text names both remedies.
- Provider-specific setup (client registration, claim mappers, redirect-URL priority) is covered by the console integration guide for the provider in use; this page states only what any provider must offer.
+10 -6
View File
@@ -18,19 +18,23 @@ RustFS validates every operator-configured outbound destination to close a serve
| Target configuration validation (startup and admin API) | Full policy | `crates/targets/src/config/common.rs` `validate_outbound_http_url`; `rustfs/src/admin/handlers/target_descriptor.rs` |
| OIDC discovery, JWKS, and token requests | Full policy | Direct requests enforce target DNS filtering; requests routed via `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` validate the target URL up front and enforce proxy-hop egress rules (see below). Startup logs `OIDC provider discovery blocked by outbound policy` naming either the origin to allowlist or the rejected proxy (`crates/iam/src/oidc/provider.rs`, `crates/iam/src/oidc/transport.rs`) |
| Object Lambda targets | Full policy | `rustfs/src/admin/router.rs` `outbound_policy` |
| Bucket replication targets | Literal check, relaxed | Private addresses are always allowed; loopback only with `RUSTFS_REPLICATION_ALLOW_LOOPBACK_TARGET=true` (`crates/ecstore/src/bucket/remote_s3_client.rs` `validate_remote_endpoint`, shared with on-demand migration sources) |
| On-demand migration sources | Literal check, relaxed | Same guard and same escape hatch as replication targets (see below) |
| Bucket replication targets and on-demand migration sources | Storage endpoint policy | Filters the configured URL and DNS answers. Private storage addresses are supported. Loopback requires `RUSTFS_REPLICATION_ALLOW_LOOPBACK_TARGET=true`. |
| Site replication peers | Literal check | `rustfs/src/site_replication/mod.rs` |
| Self-hosted tiering warm backends (S3, MinIO, RustFS) | Literal check, relaxed | `validate_outbound_url_allow_private` allows private storage addresses except known IPv6 metadata addresses; RustFS retains its own debug-only loopback exception |
| Cloud tiering warm backends (Azure, GCS, Aliyun, Tencent, Huawei, R2) | Literal check | `crates/ecstore/src/services/tier/warm_backend.rs` `validate_endpoint`, or the direct literal check in `warm_backend_azure_blob.rs` for native Azure; Wasabi additionally requires its canonical provider endpoint before using the S3 constructor |
| Keystone `auth_url` | Literal check | `crates/keystone/src/config.rs` |
| Self-hosted S3, MinIO and RustFS tiers | Storage endpoint policy | Checks DNS answers on each connection. RustFS also has a debug-only loopback setting. |
| Azure Blob, Aliyun, legacy Azure, Tencent, Huawei and R2 tiers | Full policy | Filters DNS on direct connections. Private virtual-hosted tiers need exact origins for both the endpoint and the bucket hostname, including any non-default port. Wasabi requires its canonical provider endpoint. |
| Native GCS tier | Fixed service endpoint | Both data and control clients use `https://storage.googleapis.com`. Omit the tier endpoint or specify that HTTPS origin. The Google SDK manages DNS for this origin. |
| Keystone identity service | Full policy | Connects directly to the configured identity endpoint and disables redirects. |
The allowlist affects only the "Full policy" rows. A literal-check subsystem rejects a hostname that is itself a restricted IP literal, does not re-check what a hostname resolves to, and cannot be widened by `RUSTFS_OUTBOUND_ALLOW_ORIGINS`.
S3, MinIO and RustFS tiers accept RFC 1918 and ordinary IPv6 ULA addresses. Known metadata addresses remain forbidden. The RustFS tier supports `RUSTFS_TIER_RUSTFS_ALLOW_LOOPBACK_ENDPOINT` in debug builds. Replication, migration and self-hosted storage tiers keep their own loopback rules independently of `RUSTFS_OUTBOUND_ALLOW_ORIGINS`.
OIDC requests honor standard HTTP(S) forward-proxy environment variables while keeping redirects disabled: direct connections (including hosts matched by `NO_PROXY` and loopback OIDC URLs, which always bypass proxies) re-validate target DNS answers on every connection and use `RUSTFS_OUTBOUND_ALLOW_ORIGINS` for private or loopback OIDC origins; when `HTTP_PROXY`, `HTTPS_PROXY`, or `ALL_PROXY` routes an OIDC request through an HTTP(S) forward proxy (SOCKS proxy schemes are rejected), RustFS validates the target URL shape and literals up front, permits private, shared, and loopback addresses on the operator-configured proxy hop (still blocking metadata, link-local, unspecified, translation, and reserved addresses), and delegates remote target DNS resolution and egress filtering to the proxy. Multi-node clusters using process-wide proxy variables should list cluster peers in `NO_PROXY` or set `RUSTFS_INTERNODE_HTTP_PROXY=off`.
S3, MinIO, and RustFS tiers accept RFC 1918 and ordinary IPv6 ULA addresses without an environment switch. The private-address exception retains the literal guard's other rejections and does not allow the known IPv6 metadata endpoints `fd00:ec2::254`, `fd00:ec2::23`, or `fd20:ce::254`. It does not add DNS filtering or change the other subsystems' policies. `RUSTFS_REPLICATION_ALLOW_LOOPBACK_TARGET` has no effect on tiers. RustFS's `RUSTFS_TIER_RUSTFS_ALLOW_LOOPBACK_ENDPOINT` remains a debug-build-only exception; release builds reject literal loopback endpoints.
Before upgrading a cluster with native GCS tiers, check each tier’s endpoint. A custom hostname, IP address or emulator endpoint will prevent the tier from opening, including reads of objects already transitioned there. Verify that the same objects and generations are available through Google’s service endpoint before switching. If the backing store requires its custom endpoint, migrate the data while the previous release can still read it. `RUSTFS_OUTBOUND_ALLOW_ORIGINS` cannot enable a custom native GCS tier endpoint.
Keystone, native Azure Blob tiering and native Azure/GCS migration connect directly so RustFS can filter the destination at connection time. Nodes that previously used an HTTP forward proxy for these services need direct egress to the configured endpoints. For a Keystone installation at `http://keystone:5000` on a private network, include that exact origin in `RUSTFS_OUTBOUND_ALLOW_ORIGINS` before upgrading.
The same tier endpoint check runs when constructing a driver from an existing configuration. Keep the original tier name and endpoint when recovering an upgrade that blocked a private IP; changing them can break existing destination bindings. Restoring the connection does not repair missing legacy cleanup metadata. See [tier free-version recovery](tier-ilm-debugging.md#free-version-recovery-controls).
On-demand migration sources share the replication egress guard exactly: the source endpoint an operator saves through `PUT /rustfs/admin/v3/on-demand-migration/{bucket}` goes through the same `validate_remote_endpoint` in `crates/ecstore/src/bucket/remote_s3_client.rs`, so private addresses are accepted (a source on the same private network is the normal migration case), loopback is refused unless `RUSTFS_REPLICATION_ALLOW_LOOPBACK_TARGET=true`, and metadata, link-local and unspecified addresses stay blocked. The variable is named for replication because it is one switch over one shared guard; setting it for a single-host migration also relaxes loopback for replication targets, so prefer a real hostname or private address for the source and keep the switch for lab and e2e hosts. `RUSTFS_OUTBOUND_ALLOW_ORIGINS` does not apply here. Two migration-specific rules sit on top of the endpoint guard and are enforced by the config validator, not by the egress layer: a source that names this bucket on this deployment is rejected as a self-reference, and a source matching one of the bucket's own replication targets is rejected as a replication loop. See [on-demand-migration.md](on-demand-migration.md).
+2
View File
@@ -14,6 +14,8 @@ The external request stack is shared with TCP, including readiness, Keystone aut
## What RustFS requires from the proxy
Simple trusted-proxy mode trusts loopback by default. For a reverse proxy on another host, put its address or CIDR in `RUSTFS_TRUSTED_PROXY_NETWORKS` so RustFS can use its forwarded client address and scheme.
S3 clients sign requests with AWS SigV4. RustFS (via `s3s`) re-derives the signature from the forwarded request and streams the request body to storage, so the proxy must forward the signed material and the body byte-for-byte:
| Requirement | Why |
+233 -58
View File
@@ -604,10 +604,11 @@ impl Operation for OidcCallbackHandler {
);
let new_cred = &login.session.credentials;
let redirect_policy = federation.redirect_policy(actual_provider_id);
// Build redirect URL to console with credentials in the fragment
let console_redirect = build_console_redirect(
&req,
let console_redirect = build_console_redirect_with_policy(
redirect_policy.as_ref(),
&new_cred.access_key,
&new_cred.secret_key,
&new_cred.session_token,
@@ -637,7 +638,7 @@ pub struct OidcLogoutHandler {}
#[async_trait::async_trait]
impl Operation for OidcLogoutHandler {
async fn call(&self, req: AdminRequest, _params: Params<'_, '_>) -> S3Result<AdminResponse> {
let fallback_location = build_console_login_redirect(&req)?;
let fallback_location = build_console_login_redirect()?;
let Some(logout_token) = extract_query_param(req.uri(), "logout_token") else {
return redirect_response(&fallback_location);
};
@@ -835,9 +836,19 @@ fn build_console_callback_fragment(
fragment
}
/// Build the console redirect URL with STS credentials in the hash fragment.
fn build_console_redirect(
req: &AdminRequest,
fn configured_redirect_origin(policy: Option<&rustfs_iam::federation::FederatedRedirectPolicy>) -> S3Result<Option<String>> {
let Some(uri) = policy.and_then(|policy| policy.redirect_uri.as_deref()) else {
return Ok(None);
};
let parsed = Url::parse(uri).map_err(|_| s3_error!(InvalidRequest, "invalid configured redirect_uri"))?;
if !is_valid_scheme(parsed.scheme()) || parsed.host_str().is_none() {
return Err(s3_error!(InvalidRequest, "configured redirect_uri must be absolute http/https URL"));
}
Ok(Some(parsed.origin().ascii_serialization()))
}
fn build_console_redirect_with_policy(
policy: Option<&rustfs_iam::federation::FederatedRedirectPolicy>,
access_key: &str,
secret_key: &str,
session_token: &str,
@@ -854,22 +865,31 @@ fn build_console_redirect(
return Ok(format!("{base_url}#{fragment}"));
}
let scheme = extract_request_scheme(req)?;
let host = extract_request_host(req)?;
if let Some(origin) = configured_redirect_origin(policy)? {
return Ok(format!("{origin}{callback_path}#{fragment}"));
}
Ok(format!("{scheme}://{host}{callback_path}#{fragment}"))
if policy.is_some_and(|policy| !policy.allow_request_origin) {
return Err(s3_error!(
InvalidRequest,
"provider requires explicit redirect_uri or RUSTFS_BROWSER_REDIRECT_URL because redirect_uri_dynamic is disabled"
));
}
// Never reflect untrusted Host or X-Forwarded-Proto headers into a redirect that carries
// STS credentials in its fragment. A same-origin relative Location stays bound to the
// origin the browser already navigated to for the callback.
Ok(format!("{callback_path}#{fragment}"))
}
fn build_console_login_redirect(req: &AdminRequest) -> S3Result<String> {
fn build_console_login_redirect() -> S3Result<String> {
let console_prefix = console_prefix();
let login_path = format!("{console_prefix}{CONSOLE_LOGIN_SUFFIX}");
if let Some(url) = browser_redirect_url(&login_path)? {
return Ok(url);
}
let scheme = extract_request_scheme(req)?;
let host = extract_request_host(req)?;
Ok(format!("{scheme}://{host}{login_path}"))
Ok(login_path)
}
fn redirect_response(location: &str) -> S3Result<AdminResponse> {
@@ -909,16 +929,22 @@ async fn parse_json_body<T: DeserializeOwned>(req: &mut AdminRequest) -> S3Resul
}
fn extract_request_scheme(req: &AdminRequest) -> S3Result<String> {
let raw_scheme = req
.headers()
.get("x-forwarded-proto")
.and_then(|v| v.to_str().ok())
.map(|v| v.split(',').next().map(str::trim).unwrap_or(""))
.filter(|v| !v.is_empty())
.map(ToOwned::to_owned)
.or_else(|| req.uri().scheme_str().map(str::to_owned))
.unwrap_or_else(|| "http".to_owned())
.to_ascii_lowercase();
// Only trust X-Forwarded-Proto when validated by the trusted-proxy middleware.
let trusted_proto = req
.client_info()
.filter(|info| info.is_from_trusted_proxy)
.and_then(|info| info.forwarded_proto.as_deref())
.map(str::trim)
.filter(|value| !value.is_empty());
let scheme = if let Some(proto) = trusted_proto {
proto
} else if req.envelope().native_tls_transport() == Some(true) {
"https"
} else {
req.uri().scheme_str().unwrap_or("http")
};
let raw_scheme = scheme.to_ascii_lowercase();
if !is_valid_scheme(&raw_scheme) {
return Err(s3_error!(InvalidRequest, "invalid scheme in request"));
@@ -928,13 +954,23 @@ fn extract_request_scheme(req: &AdminRequest) -> S3Result<String> {
}
fn extract_request_host(req: &AdminRequest) -> S3Result<String> {
let host = req
.headers()
.get(http::header::HOST)
.and_then(|v| v.to_str().ok())
.and_then(|v| {
let v = v.trim();
if v.is_empty() { None } else { Some(v.to_owned()) }
let trusted_host = req
.client_info()
.filter(|info| info.is_from_trusted_proxy)
.and_then(|info| info.forwarded_host.as_deref())
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned);
let host = trusted_host
.or_else(|| {
req.headers()
.get(http::header::HOST)
.and_then(|v| v.to_str().ok())
.and_then(|v| {
let v = v.trim();
if v.is_empty() { None } else { Some(v.to_owned()) }
})
})
.or_else(|| req.uri().authority().map(|a| a.as_str().to_owned()))
.ok_or_else(|| s3_error!(InvalidRequest, "cannot determine host for redirect URI"))?;
@@ -1011,8 +1047,18 @@ mod tests {
use http::{Extensions, HeaderMap, HeaderValue, Uri};
use temp_env::with_var;
fn build_console_redirect(
access_key: &str,
secret_key: &str,
session_token: &str,
expiration: Option<OffsetDateTime>,
redirect_after: Option<&str>,
logout_token: Option<&str>,
) -> S3Result<String> {
build_console_redirect_with_policy(None, access_key, secret_key, session_token, expiration, redirect_after, logout_token)
}
#[tokio::test]
#[serial_test::serial]
async fn validate_handler_preserves_workload_null_and_console_endpoints() {
use crate::admin::runtime_sources::{AppContext, publish_test_app_context};
use http_body_util::BodyExt as _;
@@ -1020,16 +1066,32 @@ mod tests {
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
// The outbound policy and IAM are initialized once per process.
const CHILD_ENV: &str = "RUSTFS_TEST_OIDC_VALIDATE_HANDLER_CHILD";
if std::env::var_os(CHILD_ENV).is_none() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"admin::handlers::oidc::tests::validate_handler_preserves_workload_null_and_console_endpoints",
"--nocapture",
])
.env(CHILD_ENV, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"{stdout}{}",
String::from_utf8_lossy(&output.stderr)
);
return;
}
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
// The admin URL boundary rejects literal loopback hosts. A local proxy
// serves the public-shaped test origin without external DNS or traffic.
let proxy = format!("http://{}", listener.local_addr().unwrap());
let base = "http://oidc-handler.example.invalid".to_string();
let address = listener.local_addr().unwrap();
let base = format!("http://{address}");
temp_env::async_with_vars(
[("RUSTFS_OUTBOUND_ALLOW_ORIGINS", Some(base.as_str())),
("HTTP_PROXY", Some(proxy.as_str())), ("http_proxy", Some(proxy.as_str())),
("HTTPS_PROXY", None), ("https_proxy", None), ("ALL_PROXY", None), ("all_proxy", None),
("NO_PROXY", Some("")), ("no_proxy", Some(""))],
[(rustfs_utils::egress::ENV_OUTBOUND_ALLOW_ORIGINS, Some(base.as_str()))],
async {
let _ = rustfs_credentials::init_global_action_credentials(Some("OIDCVALIDATEROOT".into()), Some("oidcValidateRootSecret123".into()));
let env = rustfs_test_utils::TestECStoreEnv::builder().prefix("oidc_validate_handler")
@@ -1042,6 +1104,7 @@ mod tests {
)));
let server_base = base.clone();
let server = tokio::spawn(async move {
let host = format!("host: {address}");
for path in ["/.well-known/openid-configuration", "/jwks", "/.well-known/openid-configuration", "/complete/.well-known/openid-configuration", "/complete/jwks"] {
let (mut stream, _) = tokio::time::timeout(std::time::Duration::from_secs(15), listener.accept()).await.unwrap().unwrap();
let mut request = Vec::new();
@@ -1050,9 +1113,8 @@ mod tests {
assert!(request.len() < 8192);
}
let request = String::from_utf8(request).unwrap();
let target = Url::parse(request.lines().next().unwrap().split_whitespace().nth(1).unwrap()).unwrap();
assert_eq!(target.origin().ascii_serialization(), server_base);
assert_eq!(target.path(), path);
assert_eq!(request.lines().next().unwrap(), format!("GET {path} HTTP/1.1"));
assert!(request.lines().any(|line| line.eq_ignore_ascii_case(&host)));
let mut body = if path.ends_with("/jwks") { serde_json::json!({"keys": []}) } else {
serde_json::json!({"issuer": server_base, "jwks_uri": format!("{server_base}/jwks"), "id_token_signing_alg_values_supported": ["RS256"]})
};
@@ -1333,7 +1395,7 @@ mod tests {
}
#[test]
fn test_derive_callback_uri_missing_provider_falls_back_to_request_headers() {
fn test_derive_callback_uri_missing_provider_ignores_untrusted_forwarded_proto() {
let req = build_oidc_request(
"http://internal/rustfs/admin/v3/oidc/authorize/default",
Some("internal:9000"),
@@ -1342,10 +1404,10 @@ mod tests {
let callback = with_var(ENV_RUSTFS_BROWSER_REDIRECT_URL, None::<&str>, || {
derive_callback_uri_with_redirect_policy(&req, "missing", None)
.expect("a missing provider should keep the request-header fallback")
.expect("a missing provider should keep the request-origin fallback without trusting raw X-Forwarded-Proto")
});
assert_eq!(callback, "https://internal:9000/rustfs/admin/v3/oidc/callback/missing");
assert_eq!(callback, "http://internal:9000/rustfs/admin/v3/oidc/callback/missing");
}
#[test]
@@ -1388,8 +1450,8 @@ mod tests {
}
#[test]
fn test_derive_callback_uri_dynamic_provider_falls_back_to_request_headers() {
let req = build_oidc_request(
fn test_derive_callback_uri_dynamic_provider_honors_only_trusted_proxy_headers() {
let untrusted_req = build_oidc_request(
"http://internal/rustfs/admin/v3/oidc/authorize/default",
Some("internal:9000"),
Some("https"),
@@ -1397,11 +1459,128 @@ mod tests {
let policy = test_redirect_policy(None, true);
let callback = with_var(ENV_RUSTFS_BROWSER_REDIRECT_URL, None::<&str>, || {
derive_callback_uri_with_redirect_policy(&req, "default", Some(&policy))
.expect("dynamic provider should fall back to request headers")
derive_callback_uri_with_redirect_policy(&untrusted_req, "default", Some(&policy))
.expect("dynamic provider should ignore untrusted X-Forwarded-Proto")
});
assert_eq!(callback, "http://internal:9000/rustfs/admin/v3/oidc/callback/default");
assert_eq!(callback, "https://internal:9000/rustfs/admin/v3/oidc/callback/default");
let mut headers = HeaderMap::new();
headers.insert(http::header::HOST, HeaderValue::from_static("internal:9000"));
headers.insert("x-forwarded-proto", HeaderValue::from_static("https"));
headers.insert("x-forwarded-host", HeaderValue::from_static("public.example.com"));
let trusted_req = crate::admin::operation::test_support::TestRequest::new(
Method::GET,
Uri::from_static("http://internal/rustfs/admin/v3/oidc/authorize/default"),
)
.headers(headers)
.extension(rustfs_trusted_proxies::ClientInfo::from_trusted_proxy(
"203.0.113.10".parse().expect("valid client IP"),
Some("public.example.com".to_string()),
Some("https".to_string()),
"127.0.0.1".parse().expect("valid proxy IP"),
1,
rustfs_trusted_proxies::ValidationMode::Strict,
Vec::new(),
))
.body(Body::empty())
.build();
let trusted_callback = with_var(ENV_RUSTFS_BROWSER_REDIRECT_URL, None::<&str>, || {
derive_callback_uri_with_redirect_policy(&trusted_req, "default", Some(&policy))
.expect("trusted proxy headers should be honored for dynamic provider")
});
assert_eq!(trusted_callback, "https://public.example.com/rustfs/admin/v3/oidc/callback/default");
}
#[tokio::test]
async fn dynamic_callback_uses_the_listener_scheme_unless_the_trusted_proxy_supplies_one() {
use crate::admin::operation::test_support::TestRequest;
use crate::shared_types::NativeTlsTransport;
use rustfs_trusted_proxies::{TrustedProxy, TrustedProxyLayer};
use std::net::SocketAddr;
use tower::{Layer, ServiceExt, service_fn};
let trusted_peer = SocketAddr::from(([10, 0, 0, 5], 9000));
let direct_peer = SocketAddr::from(([10, 0, 0, 6], 9000));
let layer = TrustedProxyLayer::with_trusted_proxies(vec![TrustedProxy::Single(trusted_peer.ip())]);
let service = layer.layer(service_fn(|request: http::Request<()>| async move {
let (parts, ()) = request.into_parts();
let req = TestRequest::new(parts.method, parts.uri)
.headers(parts.headers)
.extensions(parts.extensions)
.build();
let policy = test_redirect_policy(None, true);
let callback = with_var(ENV_RUSTFS_BROWSER_REDIRECT_URL, None::<&str>, || {
derive_callback_uri_with_redirect_policy(&req, "default", Some(&policy)).unwrap()
});
Ok::<_, std::convert::Infallible>(http::Response::new(callback))
}));
for (peer, tls, proto, expected_origin) in [
(direct_peer, false, Some("https"), "http://console.example:9000"),
(direct_peer, true, Some("http"), "https://console.example:9000"),
(trusted_peer, true, None, "https://public.example"),
(trusted_peer, true, Some("http"), "http://public.example"),
(trusted_peer, false, Some("https"), "https://public.example"),
] {
let mut request = http::Request::get("/rustfs/admin/v3/oidc/authorize/default")
.extension(peer)
.extension(NativeTlsTransport(tls))
.header("host", "console.example:9000")
.header("x-forwarded-host", "public.example");
if let Some(proto) = proto {
request = request.header("x-forwarded-proto", proto);
}
let response = service.clone().oneshot(request.body(()).unwrap()).await.unwrap();
assert_eq!(response.into_body(), format!("{expected_origin}/rustfs/admin/v3/oidc/callback/default"));
}
}
#[test]
fn test_console_redirects_never_reflect_spoofed_host_or_forwarded_proto() {
// 1. When provider has a configured redirect_uri, callback redirects to that origin,
// never reflecting untrusted request headers.
let static_policy =
test_redirect_policy(Some("https://console.example.com/rustfs/admin/v3/oidc/callback/default"), false);
let configured_redirect = with_var(ENV_RUSTFS_BROWSER_REDIRECT_URL, None::<&str>, || {
build_console_redirect_with_policy(Some(&static_policy), "ak", "sk", "st", None, Some("/buckets"), Some("logout-tok"))
.expect("configured provider origin should be used")
});
assert!(
configured_redirect.starts_with(&format!("https://console.example.com{}/auth/oidc-callback/#", console_prefix())),
"unexpected redirect: {configured_redirect}"
);
assert!(!configured_redirect.contains("attacker.example"));
// 2. When no explicit redirect URL is configured and dynamic mode is enabled,
// emit a same-origin relative Location so credentials never leave the browser's origin.
let dynamic_policy = test_redirect_policy(None, true);
let relative_redirect = with_var(ENV_RUSTFS_BROWSER_REDIRECT_URL, None::<&str>, || {
build_console_redirect_with_policy(Some(&dynamic_policy), "ak", "sk", "st", None, None, None)
.expect("dynamic provider should emit same-origin relative redirect")
});
assert!(
relative_redirect.starts_with(&format!("{}/auth/oidc-callback/#", console_prefix())),
"expected same-origin relative redirect, got: {relative_redirect}"
);
assert!(!relative_redirect.contains("attacker.example"));
assert!(!relative_redirect.starts_with("http://"));
assert!(!relative_redirect.starts_with("https://"));
// 3. Static provider without redirect_uri or RUSTFS_BROWSER_REDIRECT_URL fails closed.
let incomplete_static = test_redirect_policy(None, false);
let err = with_var(ENV_RUSTFS_BROWSER_REDIRECT_URL, None::<&str>, || {
build_console_redirect_with_policy(Some(&incomplete_static), "ak", "sk", "st", None, None, None)
.expect_err("static provider without configured origin must fail closed")
});
assert_eq!(err.code(), &S3ErrorCode::InvalidRequest);
// 4. Login redirect fallback also uses a relative path and ignores spoofed Host/proto.
let login_redirect = with_var(ENV_RUSTFS_BROWSER_REDIRECT_URL, None::<&str>, || {
build_console_login_redirect().expect("login redirect should be relative")
});
assert_eq!(login_redirect, format!("{}/auth/login", console_prefix()));
assert!(!login_redirect.contains("attacker.example"));
}
#[test]
@@ -1413,10 +1592,10 @@ mod tests {
let prefix = console_prefix();
let req = build_oidc_request("http://internal/rustfs/admin/v3/oidc/callback/default", Some("internal:9000"), None);
assert_eq!(
build_console_login_redirect(&req).expect("login URL"),
build_console_login_redirect().expect("login URL"),
format!("https://console.example.com{prefix}/auth/login")
);
let redirect = build_console_redirect(&req, "access", "secret", "token", None, None, None).expect("console callback URL");
let redirect = build_console_redirect("access", "secret", "token", None, None, None).expect("console callback URL");
assert!(redirect.starts_with(&format!("https://console.example.com{prefix}/auth/oidc-callback/#")));
assert_eq!(
derive_callback_uri(&req, "default").expect("admin callback URL"),
@@ -1426,10 +1605,8 @@ mod tests {
#[test]
fn test_build_console_redirect_uses_browser_redirect_url() {
let req = build_oidc_request("http://internal/rustfs/admin/v3/oidc/callback/default", Some("internal:9000"), None);
let redirect = with_var(ENV_RUSTFS_BROWSER_REDIRECT_URL, Some("https://console.example.com/"), || {
build_console_redirect(&req, "access", "secret", "token", None, Some("/buckets"), Some("logout-token"))
build_console_redirect("access", "secret", "token", None, Some("/buckets"), Some("logout-token"))
.expect("console redirect should use browser redirect URL")
});
@@ -1440,10 +1617,8 @@ mod tests {
#[test]
fn test_build_console_login_redirect_uses_browser_redirect_url() {
let req = build_oidc_request("http://internal/rustfs/admin/v3/oidc/logout", Some("internal:9000"), None);
let redirect = with_var(ENV_RUSTFS_BROWSER_REDIRECT_URL, Some("https://console.example.com"), || {
build_console_login_redirect(&req).expect("login redirect should use browser redirect URL")
build_console_login_redirect().expect("login redirect should use browser redirect URL")
});
assert_eq!(redirect, format!("https://console.example.com{}/auth/login", console_prefix()));
+2 -2
View File
@@ -54,7 +54,7 @@ pub async fn init_keystone_auth(config: KeystoneConfig) -> Result<(), Box<dyn st
config.validate()?;
let version = config.get_version()?;
let client = KeystoneClient::new(
let client = KeystoneClient::try_new(
config.auth_url.clone(),
version,
config.admin_user.clone(),
@@ -63,7 +63,7 @@ pub async fn init_keystone_auth(config: KeystoneConfig) -> Result<(), Box<dyn st
config.get_admin_domain(),
config.verify_ssl,
config.get_timeout(),
);
)?;
let auth_provider = KeystoneAuthProvider::new(client.clone(), config.cache_size, config.get_cache_ttl(), config.enable_cache);
+110 -1
View File
@@ -26,11 +26,14 @@
//! the log line and the admin response.
use super::source_client::{SourceError, SourceHead, SourceTimeouts, USER_AGENT_SUFFIX, classify_status, is_multipart_etag};
use super::storage_api::remote_s3_client::{RemoteS3ClientError, validate_remote_endpoint, validate_target_ca_pem};
use super::storage_api::remote_s3_client::{
RemoteS3ClientError, build_remote_endpoint_dns_resolver, validate_remote_endpoint, validate_target_ca_pem,
};
use aws_sdk_s3::primitives::ByteStream;
use aws_smithy_types::body::SdkBody;
use futures::StreamExt;
use http::HeaderMap;
use rustfs_utils::egress::OutboundDnsResolver;
use std::collections::HashMap;
use std::time::SystemTime;
use time::OffsetDateTime;
@@ -72,10 +75,22 @@ impl NativeHttp {
));
}
validate_remote_endpoint(&endpoint).map_err(RemoteS3ClientError::EndpointNotAllowed)?;
let dns_resolver = build_remote_endpoint_dns_resolver(&endpoint)?;
Self::new_with_resolver(endpoint, timeouts, skip_tls_verify, ca_cert_pem, dns_resolver)
}
fn new_with_resolver(
endpoint: Url,
timeouts: SourceTimeouts,
skip_tls_verify: bool,
ca_cert_pem: Option<&str>,
dns_resolver: OutboundDnsResolver,
) -> Result<Self, RemoteS3ClientError> {
let mut builder = reqwest::Client::builder()
.connect_timeout(timeouts.connect)
.read_timeout(timeouts.read)
.no_proxy()
.dns_resolver(dns_resolver)
.redirect(reqwest::redirect::Policy::none())
.user_agent(USER_AGENT_SUFFIX);
if skip_tls_verify {
@@ -497,4 +512,98 @@ mod tests {
assert!(url.fragment().is_none());
}
}
#[tokio::test]
async fn native_http_enforces_outbound_dns_policy_on_rebinding_and_loopback() {
use rustfs_utils::egress::OutboundPolicy;
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
// Literal policy checks: private IP is allowed; loopback/metadata rejected by default.
assert!(NativeHttp::new("http://10.0.0.5:9000", SourceTimeouts::default(), false, None).is_ok());
assert!(NativeHttp::new("http://169.254.169.254", SourceTimeouts::default(), false, None).is_err());
let listener = match TcpListener::bind("127.0.0.1:0").await {
Ok(listener) => listener,
Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => return,
Err(err) => panic!("test listener should bind: {err}"),
};
let address = listener.local_addr().expect("listener address");
let endpoint = Url::parse(&format!("http://rebind-native.test:{}", address.port())).expect("endpoint URL");
// 1. Without loopback opt-in, a hostname resolving to 127.0.0.1 fails closed at connect time.
let no_loopback_resolver = OutboundPolicy::default()
.resolver_for_storage_endpoint(&endpoint, true, false)
.expect("hostname should pass URL validation")
.with_resolve_override(move |host| (host == "rebind-native.test").then(|| vec![SocketAddr::new(address.ip(), 0)]));
let no_loopback_http =
NativeHttp::new_with_resolver(endpoint.clone(), SourceTimeouts::default(), false, None, no_loopback_resolver)
.expect("native http client should build");
let req = no_loopback_http
.client
.get(no_loopback_http.url(["probe"]).expect("probe url"))
.build()
.expect("request");
let err = no_loopback_http
.execute(req)
.await
.expect_err("loopback DNS answer must fail closed without loopback opt-in");
assert!(matches!(err, SourceError::Connect(_)), "unexpected error: {err:?}");
// 2. With loopback opt-in enabled, first request hits local listener, then DNS rebinding to
// cloud metadata (169.254.169.254) fails closed on the next connection.
let answers = Arc::new(Mutex::new(VecDeque::from([
vec![SocketAddr::new(address.ip(), 0)],
vec![SocketAddr::new("169.254.169.254".parse().expect("metadata ip"), 0)],
])));
let rebinding_resolver = OutboundPolicy::default()
.resolver_for_storage_endpoint(&endpoint, true, true)
.expect("loopback opt-in should allow hostname")
.with_resolve_override(move |host| {
if host != "rebind-native.test" {
return None;
}
let mut guard = answers.lock().expect("override lock");
if guard.len() > 1 {
guard.pop_front()
} else {
guard.front().cloned()
}
});
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.expect("first connection should succeed");
let mut buf = [0_u8; 1024];
let _ = stream.read(&mut buf).await.expect("read request");
stream
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.await
.expect("write response");
});
let rebinding_http = NativeHttp::new_with_resolver(endpoint, SourceTimeouts::default(), false, None, rebinding_resolver)
.expect("rebinding native http client should build");
let req1 = rebinding_http
.client
.get(rebinding_http.url(["probe"]).expect("probe url"))
.build()
.expect("first request");
let resp1 = rebinding_http.execute(req1).await.expect("first request should succeed");
assert_eq!(resp1.status(), reqwest::StatusCode::OK);
server.await.expect("server should finish");
let req2 = rebinding_http
.client
.get(rebinding_http.url(["probe"]).expect("probe url"))
.build()
.expect("second request");
let err2 = rebinding_http
.execute(req2)
.await
.expect_err("rebound metadata DNS answer must fail closed");
assert!(matches!(err2, SourceError::Connect(_)), "unexpected error: {err2:?}");
}
}
+11 -8
View File
@@ -49,7 +49,7 @@ use crate::storage_api::server::http::tonic_service::make_server;
use crate::storage_api::server::http::tonic_service::make_server_for_slot;
use crate::storage_api::server::http::{
ServerContextSlot, TONIC_RPC_PREFIX, normalize_tonic_rpc_audience, tonic_boot_epoch_challenge,
verify_tonic_rpc_signature_with_bootstrap,
verify_tonic_rpc_signature_with_bootstrap_and_peer,
};
use bytes::Bytes;
use futures::stream::FuturesUnordered;
@@ -3424,13 +3424,21 @@ fn check_auth(req: Request<()>) -> std::result::Result<Request<()>, Status> {
.filter(|method| !method.is_empty() && !method.contains('/'))
.ok_or_else(|| Status::unauthenticated("Invalid RPC request path"))?;
debug_assert!(!rpc_method.is_empty());
let peer_remote_addr = req
.extensions()
.get::<Option<RemoteAddr>>()
.copied()
.flatten()
.or_else(|| req.extensions().get::<RemoteAddr>().copied());
let peer_ip = peer_remote_addr.map(|addr| addr.0.ip());
let allow_replay_scope_bootstrap = target.uri.path() == "/node_service.NodeService/Ping"
&& tonic_boot_epoch_challenge(req.metadata().as_ref()).is_ok_and(|challenge| challenge.is_some());
verify_tonic_rpc_signature_with_bootstrap(
verify_tonic_rpc_signature_with_bootstrap_and_peer(
&audience,
target.uri.path(),
req.metadata().as_ref(),
allow_replay_scope_bootstrap,
peer_ip,
)
.map_err(|e| {
let rpc_path = target.uri.path();
@@ -3439,12 +3447,7 @@ fn check_auth(req: Request<()>) -> std::result::Result<Request<()>, Status> {
.and_then(|path| path.split_once('/'))
.map(|(service, _)| service)
.unwrap_or("unknown");
let peer_addr = req
.extensions()
.get::<Option<RemoteAddr>>()
.copied()
.flatten()
.or_else(|| req.extensions().get::<RemoteAddr>().copied())
let peer_addr = peer_remote_addr
.map(|addr| addr.0.to_string())
.unwrap_or_else(|| "unknown".to_string());
let failure_reason = storage::tonic_rpc_auth_failure_reason(&e);
+407 -52
View File
@@ -17,19 +17,21 @@ use crate::storage::request_context::spawn_traced;
use crate::storage::storage_api::rpc_consumer::http_service::{
BackgroundPipeWriter, BackgroundReaderStream, DEFAULT_READ_BUFFER_SIZE, DeleteOptions, DiskStore,
NS_SCANNER_PROTOCOL_VERSION, NsScannerCapabilityResponse, PUT_FILE_AUTH_TRAILER_LEN, PUT_FILE_AUTH_V1,
PUT_FILE_CAPABILITY_VERSION, PutFileCapabilityResponse, RemoteBackgroundIo, StorageDiskRpcExt as _,
WALK_DIR_STREAM_COMPLETION_V1, WalkDirOptions, background_pipe, check_and_record_signed_rpc_nonce,
find_local_disk_by_ref_for_rpc, find_local_disk_by_ref_for_scanner_rpc, rpc_background_admission,
sign_ns_scanner_capability_with_usage_capabilities, sign_ns_scanner_tier_registry_preflight_capability,
sign_ns_scanner_usage_watch_capability, sign_put_file_capability, verify_put_file_auth_trailer, verify_rpc_signature,
with_remote_background_io, with_rpc_background_request,
PUT_FILE_CAPABILITY_VERSION, PutFileCapabilityResponse, RemoteBackgroundIo, STREAM_RESPONSE_AUTH_HEADER,
STREAM_RESPONSE_AUTH_V1, STREAM_RESPONSE_FRAME_MAX_PAYLOAD, StorageDiskRpcExt as _, StreamResponseAuthDomain,
WALK_DIR_STREAM_COMPLETION_V1, WalkDirOptions, background_pipe, check_and_record_signed_rpc_nonce_for_peer,
encode_stream_auth_data_frame, encode_stream_auth_eof_frame, find_local_disk_by_ref_for_rpc,
find_local_disk_by_ref_for_scanner_rpc, rpc_background_admission, sign_ns_scanner_capability_with_usage_capabilities,
sign_ns_scanner_tier_registry_preflight_capability, sign_ns_scanner_usage_watch_capability, sign_put_file_capability,
verify_put_file_auth_trailer, verify_rpc_signature, with_remote_background_io, with_rpc_background_request,
};
#[cfg(test)]
use crate::storage::storage_api::rpc_consumer::http_service::{
NS_SCANNER_BODY_SHA256_QUERY, NS_SCANNER_CAPABILITY_CHALLENGE_QUERY, NS_SCANNER_CYCLE_QUERY, NS_SCANNER_LEADER_EPOCH_QUERY,
NS_SCANNER_REQUEST_ID_QUERY, NS_SCANNER_SERVER_EPOCH_QUERY, NS_SCANNER_SESSION_ID_QUERY, NS_SCANNER_SESSION_SEQUENCE_QUERY,
NS_SCANNER_TIER_REGISTRY_GENERATION_QUERY, PUT_FILE_CAPABILITY_CHALLENGE_QUERY, PUT_FILE_CAPABILITY_QUERY,
WALK_DIR_BODY_SHA256_QUERY,
STREAM_RESPONSE_AUTH_NONCE_QUERY, STREAM_RESPONSE_AUTH_QUERY, STREAM_RESPONSE_DATA_HEADER_LEN, STREAM_RESPONSE_EOF_FRAME_LEN,
WALK_DIR_BODY_SHA256_QUERY, verify_stream_auth_data_frame, verify_stream_auth_eof_frame,
};
use crate::storage::storage_api::runtime_sources_consumer::runtime_sources;
use crate::storage::storage_api::tonic_rpc_auth_failure_reason;
@@ -93,6 +95,12 @@ pub(super) static PUT_FILE_AUTH_STRICT: LazyLock<bool> = LazyLock::new(|| {
rustfs_config::DEFAULT_INTERNODE_RPC_BODY_DIGEST_STRICT,
)
});
static STREAM_RESPONSE_AUTH_STRICT: LazyLock<bool> = LazyLock::new(|| {
rustfs_utils::get_env_bool(
rustfs_config::ENV_INTERNODE_RPC_STREAM_AUTH_STRICT,
rustfs_config::DEFAULT_INTERNODE_RPC_STREAM_AUTH_STRICT,
)
});
const PUT_FILE_TARGET_LOCK_SHARDS: usize = 64;
const PUT_FILE_TARGET_LOCK_INITIAL_GC_THRESHOLD: usize = 64;
@@ -365,6 +373,8 @@ struct ReadFileQuery {
path: String,
offset: usize,
length: usize,
stream_auth: Option<String>,
stream_auth_nonce: Option<uuid::Uuid>,
}
#[derive(Debug, Default, serde::Deserialize)]
@@ -372,6 +382,138 @@ struct WalkDirQuery {
disk: String,
walk_dir_stream_completion: Option<String>,
walk_dir_body_sha256: Option<String>,
stream_auth: Option<String>,
stream_auth_nonce: Option<uuid::Uuid>,
}
#[derive(Clone, Debug)]
struct StreamResponseAuthContext {
domain: StreamResponseAuthDomain,
url: String,
method: Method,
nonce: uuid::Uuid,
}
fn parse_stream_response_auth(
stream_auth: Option<&str>,
stream_auth_nonce: Option<uuid::Uuid>,
strict: bool,
) -> io::Result<Option<uuid::Uuid>> {
match stream_auth {
None => {
if stream_auth_nonce.is_some() {
return Err(io::Error::other("unexpected stream_auth_nonce without stream_auth"));
}
if strict {
return Err(io::Error::other("internode stream response auth required"));
}
Ok(None)
}
Some(STREAM_RESPONSE_AUTH_V1) => {
let nonce = stream_auth_nonce
.filter(|nonce| !nonce.is_nil())
.ok_or_else(|| io::Error::other("Invalid stream response auth nonce"))?;
Ok(Some(nonce))
}
Some(_) => Err(io::Error::other("Unsupported stream response auth version")),
}
}
struct AuthenticatedResponseStream<S> {
inner: Pin<Box<S>>,
auth: StreamResponseAuthContext,
seq: u64,
total_bytes: u64,
hasher: Sha256,
pending_frames: std::collections::VecDeque<Bytes>,
done: bool,
}
impl<S> AuthenticatedResponseStream<S> {
fn new(inner: S, auth: StreamResponseAuthContext) -> Self {
Self {
inner: Box::pin(inner),
auth,
seq: 0,
total_bytes: 0,
hasher: Sha256::new(),
pending_frames: std::collections::VecDeque::new(),
done: false,
}
}
}
impl<S> Stream for AuthenticatedResponseStream<S>
where
S: Stream<Item = io::Result<Bytes>>,
{
type Item = io::Result<Bytes>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.as_mut().get_mut();
if let Some(frame) = this.pending_frames.pop_front() {
return Poll::Ready(Some(Ok(frame)));
}
if this.done {
return Poll::Ready(None);
}
loop {
match this.inner.as_mut().poll_next(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Some(Ok(bytes))) => {
if bytes.is_empty() {
continue;
}
for chunk in bytes.chunks(STREAM_RESPONSE_FRAME_MAX_PAYLOAD) {
let frame = match encode_stream_auth_data_frame(
this.auth.domain,
&this.auth.url,
&this.auth.method,
this.auth.nonce,
this.seq,
chunk,
) {
Ok(frame) => frame,
Err(err) => {
this.done = true;
return Poll::Ready(Some(Err(err)));
}
};
this.hasher.update(chunk);
this.total_bytes = this.total_bytes.saturating_add(chunk.len() as u64);
this.seq = this.seq.saturating_add(1);
this.pending_frames.push_back(Bytes::from(frame));
}
if let Some(frame) = this.pending_frames.pop_front() {
return Poll::Ready(Some(Ok(frame)));
}
}
Poll::Ready(Some(Err(err))) => {
// Never emit a signed EOF frame when the producer fails.
this.done = true;
return Poll::Ready(Some(Err(err)));
}
Poll::Ready(None) => {
this.done = true;
let digest: [u8; 32] = this.hasher.clone().finalize().into();
let eof = match encode_stream_auth_eof_frame(
this.auth.domain,
&this.auth.url,
&this.auth.method,
this.auth.nonce,
this.seq,
this.total_bytes,
&digest,
) {
Ok(eof) => eof,
Err(err) => return Poll::Ready(Some(Err(err))),
};
return Poll::Ready(Some(Ok(Bytes::copy_from_slice(&eof))));
}
}
}
}
}
#[derive(Debug, Default, serde::Deserialize)]
@@ -827,10 +969,29 @@ async fn handle_read_file(req: Request<Incoming>) -> Response<Body> {
return empty_ok();
}
let request_url = req.uri().to_string();
let request_method = req.method().clone();
let query = match parse_query::<ReadFileQuery>(&req) {
Ok(query) => query,
Err(response) => return *response,
};
let stream_auth_nonce =
match parse_stream_response_auth(query.stream_auth.as_deref(), query.stream_auth_nonce, *STREAM_RESPONSE_AUTH_STRICT) {
Ok(nonce) => nonce,
Err(err) => {
log_internode_rpc_response_failure!(
StatusCode::FORBIDDEN,
req.uri().path(),
&request_method,
Some(INTERNODE_OPERATION_READ_FILE_STREAM),
"stream_response_auth_invalid",
"rejected",
Some(("disk", query.disk.as_str())),
Some(&err)
);
return response_with_status(StatusCode::FORBIDDEN, format!("invalid stream response auth: {err}"));
}
};
let disk = match find_local_disk_by_ref_for_rpc(&query.disk).await {
Ok(disk) => disk,
@@ -888,14 +1049,36 @@ async fn handle_read_file(req: Request<Incoming>) -> Response<Body> {
INTERNODE_OPERATION_READ_FILE_STREAM,
INTERNODE_TRANSPORT_BACKEND_TCP_HTTP,
);
read_file_response(file, query.length)
let stream_auth = stream_auth_nonce.map(|nonce| StreamResponseAuthContext {
domain: StreamResponseAuthDomain::ReadFileStream,
url: request_url,
method: request_method,
nonce,
});
read_file_response_with_auth(file, query.length, stream_auth)
}
#[cfg(test)]
fn read_file_response<R>(reader: R, length: usize) -> Response<Body>
where
R: tokio::io::AsyncRead + Unpin + Send + Sync + 'static,
{
read_file_response_with_auth(reader, length, None)
}
fn read_file_response_with_auth<R>(reader: R, length: usize, stream_auth: Option<StreamResponseAuthContext>) -> Response<Body>
where
R: tokio::io::AsyncRead + Unpin + Send + Sync + 'static,
{
let stream = read_file_body_stream(reader, length, INTERNODE_OPERATION_READ_FILE_STREAM);
if let Some(auth) = stream_auth {
let auth_stream = AuthenticatedResponseStream::new(stream, auth);
let mut response = Response::new(Body::from_stream(auth_stream));
response
.headers_mut()
.insert(STREAM_RESPONSE_AUTH_HEADER, HeaderValue::from_static(STREAM_RESPONSE_AUTH_V1));
return response;
}
let mut response = Response::new(Body::from_stream(stream));
if length != 0 {
// Bounded shard readers stop at the requested byte count. Exact framing
@@ -1060,10 +1243,29 @@ async fn handle_walk_dir(req: Request<Incoming>) -> Response<Body> {
return empty_ok();
}
let request_url = req.uri().to_string();
let request_method = req.method().clone();
let query = match parse_query::<WalkDirQuery>(&req) {
Ok(query) => query,
Err(response) => return *response,
};
let stream_auth_nonce =
match parse_stream_response_auth(query.stream_auth.as_deref(), query.stream_auth_nonce, *STREAM_RESPONSE_AUTH_STRICT) {
Ok(nonce) => nonce,
Err(err) => {
log_internode_rpc_response_failure!(
StatusCode::FORBIDDEN,
req.uri().path(),
&request_method,
Some(INTERNODE_OPERATION_WALK_DIR),
"stream_response_auth_invalid",
"rejected",
Some(("disk", query.disk.as_str())),
Some(&err)
);
return response_with_status(StatusCode::FORBIDDEN, format!("invalid stream response auth: {err}"));
}
};
let disk = match find_local_disk_by_ref_for_rpc(&query.disk).await {
Ok(disk) => disk,
Err(_) => return response_with_status(StatusCode::SERVICE_UNAVAILABLE, "background storage admission deferred"),
@@ -1159,32 +1361,44 @@ async fn handle_walk_dir(req: Request<Incoming>) -> Response<Body> {
runtime_sources::current_internode_metrics()
.record_incoming_request_for_operation_and_backend(INTERNODE_OPERATION_WALK_DIR, INTERNODE_TRANSPORT_BACKEND_TCP_HTTP);
let body = walk_dir_response_body(propagate_completion_errors, preflight_missing_path_error, move |mut writer| async move {
walk_dir_with_legacy_meta_fallback(&disk, args, &mut writer)
.await
.map_err(|e| {
warn!(
event = EVENT_RPC_BACKGROUND_TASK_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_DIRECTORY_WALK,
operation = INTERNODE_OPERATION_WALK_DIR,
result = "failed",
disk = %log_disk,
bucket = %log_bucket,
base_dir = %log_base_dir,
recursive = log_recursive,
report_notfound = log_report_notfound,
filter_prefix = ?log_filter_prefix,
forward_to = ?log_forward_to,
limit = log_limit,
disk_id = %log_disk_id,
skip_total_timeout = log_skip_total_timeout,
error = %e,
"internode rpc background task failed"
);
e
})
})
let stream_auth = stream_auth_nonce.map(|nonce| StreamResponseAuthContext {
domain: StreamResponseAuthDomain::WalkDir,
url: request_url,
method: request_method,
nonce,
});
let has_stream_auth = stream_auth.is_some();
let body = walk_dir_response_body_with_auth(
propagate_completion_errors,
preflight_missing_path_error,
stream_auth,
move |mut writer| async move {
walk_dir_with_legacy_meta_fallback(&disk, args, &mut writer)
.await
.map_err(|e| {
warn!(
event = EVENT_RPC_BACKGROUND_TASK_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_DIRECTORY_WALK,
operation = INTERNODE_OPERATION_WALK_DIR,
result = "failed",
disk = %log_disk,
bucket = %log_bucket,
base_dir = %log_base_dir,
recursive = log_recursive,
report_notfound = log_report_notfound,
filter_prefix = ?log_filter_prefix,
forward_to = ?log_forward_to,
limit = log_limit,
disk_id = %log_disk_id,
skip_total_timeout = log_skip_total_timeout,
error = %e,
"internode rpc background task failed"
);
e
})
},
)
.await;
let body = match body {
@@ -1192,10 +1406,11 @@ async fn handle_walk_dir(req: Request<Incoming>) -> Response<Body> {
Err(error) => return response_with_disk_error(&error, error.to_string()),
};
Response::builder()
.status(StatusCode::OK)
.body(body)
.expect("failed to build walk dir response")
let mut builder = Response::builder().status(StatusCode::OK);
if has_stream_auth {
builder = builder.header(STREAM_RESPONSE_AUTH_HEADER, STREAM_RESPONSE_AUTH_V1);
}
builder.body(body).expect("failed to build walk dir response")
}
fn legacy_meta_bucket_alias(volume: &str) -> Option<String> {
@@ -1556,11 +1771,35 @@ fn remote_scanner_claim_rejection(error: &rustfs_scanner::ScannerError) -> (Stat
}
}
#[cfg(test)]
async fn walk_dir_response_body<F, Fut>(
propagate_completion_errors: bool,
preflight_missing_path_error: bool,
producer: F,
) -> Result<Body, DiskError>
where
F: FnOnce(BackgroundPipeWriter) -> Fut + Send + 'static,
Fut: Future<Output = Result<(), DiskError>> + Send + 'static,
{
walk_dir_response_body_with_auth(propagate_completion_errors, preflight_missing_path_error, None, producer).await
}
fn wrap_walk_dir_body<S>(stream: S, stream_auth: Option<StreamResponseAuthContext>) -> Body
where
S: Stream<Item = io::Result<Bytes>> + Send + Sync + 'static,
{
match stream_auth {
Some(auth) => Body::from_stream(AuthenticatedResponseStream::new(stream, auth)),
None => Body::from_stream(stream),
}
}
async fn walk_dir_response_body_with_auth<F, Fut>(
propagate_completion_errors: bool,
preflight_missing_path_error: bool,
stream_auth: Option<StreamResponseAuthContext>,
producer: F,
) -> Result<Body, DiskError>
where
F: FnOnce(BackgroundPipeWriter) -> Fut + Send + 'static,
Fut: Future<Output = Result<(), DiskError>> + Send + 'static,
@@ -1594,7 +1833,7 @@ where
let mut stream = Box::pin(stream);
if !preflight_missing_path_error {
let stream = append_walk_dir_completion(stream, completion_rx, propagate_completion_errors);
return Ok(Body::from_stream(stream));
return Ok(wrap_walk_dir_body(stream, stream_auth));
}
// Keep the first chunk bounded in memory so a missing-path error can use
@@ -1603,15 +1842,23 @@ where
Some(Ok(first_bytes)) => {
let stream = stream::once(async move { Ok(first_bytes) }).chain(stream);
let stream = append_walk_dir_completion(stream, completion_rx, propagate_completion_errors);
Ok(Body::from_stream(stream))
Ok(wrap_walk_dir_body(stream, stream_auth))
}
Some(Err(first_error)) => {
let stream = stream::once(async move { Err(first_error) }).chain(stream);
let stream = append_walk_dir_completion(stream, completion_rx, propagate_completion_errors);
Ok(Body::from_stream(stream))
Ok(wrap_walk_dir_body(stream, stream_auth))
}
None => match completion_rx.await {
Ok(Ok(())) => Ok(Body::empty()),
Ok(Ok(())) => match stream_auth {
Some(auth) => {
let digest: [u8; 32] = Sha256::digest([]).into();
let eof = encode_stream_auth_eof_frame(auth.domain, &auth.url, &auth.method, auth.nonce, 0, 0, &digest)
.map_err(DiskError::other)?;
Ok(Body::from(Bytes::copy_from_slice(&eof)))
}
None => Ok(Body::empty()),
},
Ok(Err(error)) if propagate_completion_errors => match error {
DiskError::FileNotFound | DiskError::VolumeNotFound => Err(error),
_ => Ok(walk_dir_error_body("remote walk_dir failed")),
@@ -1918,13 +2165,15 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
if require_auth && !put_file_server_epoch_accepted(&query, *PUT_FILE_AUTH_STRICT) {
return response_with_status(StatusCode::CONFLICT, "put_file capability server epoch changed");
}
let peer_ip = req.extensions().get::<std::net::SocketAddr>().map(std::net::SocketAddr::ip);
if let Some(nonce) = auth_nonce
&& let Err(e) = check_and_record_signed_rpc_nonce(
&& let Err(e) = check_and_record_signed_rpc_nonce_for_peer(
req.headers(),
nonce,
&path,
INTERNODE_OPERATION_PUT_FILE_STREAM,
INTERNODE_TRANSPORT_BACKEND_TCP_HTTP,
peer_ip,
)
{
if crate::storage::storage_api::rpc_auth_is_resource_exhausted(&e) {
@@ -2267,14 +2516,16 @@ mod tests {
NS_SCANNER_REQUEST_ID_QUERY, NS_SCANNER_SERVER_EPOCH_QUERY, NS_SCANNER_SESSION_ID_QUERY,
NS_SCANNER_SESSION_SEQUENCE_QUERY, NS_SCANNER_TIER_REGISTRY_GENERATION_QUERY, NsScannerCapabilityResponse,
NsScannerQuery, PUT_FILE_AUTH_STREAM_PATH, PUT_FILE_CAPABILITY_PATH, PUT_FILE_STREAM_PATH, PutFileQuery,
READ_FILE_STREAM_PATH, WALK_DIR_BODY_SHA256_QUERY, WALK_DIR_PATH, WalkDirQuery, append_walk_dir_completion,
internode_http_operation, internode_rpc_subsystem, is_internode_rpc_path, legacy_meta_bucket_alias,
ns_scanner_response_body, ns_scanner_server_epoch_matches, put_body_size_mismatch, put_file_auth_nonce,
put_file_capability_response, put_file_server_epoch_accepted, put_file_server_epoch_matches,
put_file_stage_error_message, put_file_target_lock, read_file_body_stream, read_file_response,
read_file_stream_buffer_size, remote_scanner_claim_rejection, response_with_disk_error,
supports_walk_dir_stream_completion, validate_walk_dir_completion_request, verify_internode_rpc_signature,
verify_ns_scanner_body_digest, verify_walk_dir_body_digest, walk_dir_response_body, write_authenticated_put_file,
READ_FILE_STREAM_PATH, STREAM_RESPONSE_AUTH_HEADER, STREAM_RESPONSE_AUTH_NONCE_QUERY, STREAM_RESPONSE_AUTH_QUERY,
STREAM_RESPONSE_AUTH_V1, STREAM_RESPONSE_DATA_HEADER_LEN, STREAM_RESPONSE_EOF_FRAME_LEN, StreamResponseAuthDomain,
WALK_DIR_BODY_SHA256_QUERY, WALK_DIR_PATH, WalkDirQuery, append_walk_dir_completion, internode_http_operation,
internode_rpc_subsystem, is_internode_rpc_path, legacy_meta_bucket_alias, ns_scanner_response_body,
ns_scanner_server_epoch_matches, put_body_size_mismatch, put_file_auth_nonce, put_file_capability_response,
put_file_server_epoch_accepted, put_file_server_epoch_matches, put_file_stage_error_message, put_file_target_lock,
read_file_body_stream, read_file_response, read_file_stream_buffer_size, remote_scanner_claim_rejection,
response_with_disk_error, supports_walk_dir_stream_completion, validate_walk_dir_completion_request,
verify_internode_rpc_signature, verify_ns_scanner_body_digest, verify_stream_auth_data_frame,
verify_stream_auth_eof_frame, verify_walk_dir_body_digest, walk_dir_response_body, write_authenticated_put_file,
write_body_chunks_to_writer, write_put_file_body_chunks_to_writer,
};
use crate::storage::storage_api::ecstore_rpc::{build_put_file_auth_trailer, gen_signature_headers};
@@ -2291,7 +2542,7 @@ mod tests {
INTERNODE_OPERATION_READ_FILE_STREAM, INTERNODE_OPERATION_WALK_DIR, INTERNODE_TRANSPORT_BACKEND_TCP_HTTP,
global_internode_metrics,
};
use sha2::Digest as _;
use sha2::{Digest as _, Sha256};
use std::collections::HashMap;
use std::convert::Infallible;
use std::future::Future as _;
@@ -4574,4 +4825,108 @@ mod tests {
assert!(guard.entries.len() <= guard.next_gc_threshold);
}
}
#[tokio::test]
async fn read_file_and_walk_dir_responses_emit_verified_framed_auth_streams() {
let _ = rustfs_credentials::set_global_rpc_secret("stream-response-auth-test-secret".to_string());
let read_nonce = uuid::Uuid::new_v4();
let read_url = format!(
"/rustfs/rpc/read_file_stream?disk=d1&volume=b&path=p&offset=0&length=11&{STREAM_RESPONSE_AUTH_QUERY}={STREAM_RESPONSE_AUTH_V1}&{STREAM_RESPONSE_AUTH_NONCE_QUERY}={read_nonce}"
);
let read_ctx = super::StreamResponseAuthContext {
domain: StreamResponseAuthDomain::ReadFileStream,
url: read_url.clone(),
method: Method::GET,
nonce: read_nonce,
};
let response = super::read_file_response_with_auth(std::io::Cursor::new(b"hello world".to_vec()), 11, Some(read_ctx));
assert_eq!(
response
.headers()
.get(STREAM_RESPONSE_AUTH_HEADER)
.and_then(|v| v.to_str().ok()),
Some(STREAM_RESPONSE_AUTH_V1)
);
assert!(
response.headers().get(http::header::CONTENT_LENGTH).is_none(),
"authenticated framed response must omit raw payload Content-Length"
);
let wire = response.into_body().collect().await.expect("framed body").to_bytes();
assert_eq!(wire.len(), STREAM_RESPONSE_DATA_HEADER_LEN + 11 + STREAM_RESPONSE_EOF_FRAME_LEN);
let header: [u8; STREAM_RESPONSE_DATA_HEADER_LEN] = wire[..STREAM_RESPONSE_DATA_HEADER_LEN].try_into().unwrap();
let payload = &wire[STREAM_RESPONSE_DATA_HEADER_LEN..STREAM_RESPONSE_DATA_HEADER_LEN + 11];
assert_eq!(payload, b"hello world");
verify_stream_auth_data_frame(
StreamResponseAuthDomain::ReadFileStream,
&read_url,
&Method::GET,
read_nonce,
0,
&header,
payload,
)
.expect("read_file data frame must verify");
let eof: [u8; STREAM_RESPONSE_EOF_FRAME_LEN] = wire[STREAM_RESPONSE_DATA_HEADER_LEN + 11..].try_into().unwrap();
let digest: [u8; 32] = Sha256::digest(payload).into();
verify_stream_auth_eof_frame(
StreamResponseAuthDomain::ReadFileStream,
&read_url,
&Method::GET,
read_nonce,
1,
11,
&digest,
&eof,
)
.expect("read_file EOF frame must verify");
// Empty walk_dir still emits an authenticated EOF frame.
let walk_nonce = uuid::Uuid::new_v4();
let walk_url = format!(
"/rustfs/rpc/walk_dir?disk=d1&{STREAM_RESPONSE_AUTH_QUERY}={STREAM_RESPONSE_AUTH_V1}&{STREAM_RESPONSE_AUTH_NONCE_QUERY}={walk_nonce}"
);
let walk_ctx = super::StreamResponseAuthContext {
domain: StreamResponseAuthDomain::WalkDir,
url: walk_url.clone(),
method: Method::GET,
nonce: walk_nonce,
};
let empty_walk = super::walk_dir_response_body_with_auth(true, true, Some(walk_ctx.clone()), |_w| async { Ok(()) })
.await
.expect("empty authenticated walk_dir should succeed");
let empty_wire = empty_walk.collect().await.expect("empty walk wire").to_bytes();
assert_eq!(empty_wire.len(), STREAM_RESPONSE_EOF_FRAME_LEN);
let empty_eof: [u8; STREAM_RESPONSE_EOF_FRAME_LEN] = empty_wire[..].try_into().unwrap();
let empty_digest: [u8; 32] = Sha256::digest([]).into();
verify_stream_auth_eof_frame(
StreamResponseAuthDomain::WalkDir,
&walk_url,
&Method::GET,
walk_nonce,
0,
0,
&empty_digest,
&empty_eof,
)
.expect("empty walk_dir EOF frame must verify");
// Failed mid-stream walk_dir must abort without emitting a signed EOF frame.
let failed_walk = super::walk_dir_response_body_with_auth(true, false, Some(walk_ctx), |mut w| async move {
w.write_all(b"partial-entry").await.expect("write partial");
Err(DiskError::other("injected walk failure"))
})
.await
.expect("stream starts before producer error");
assert!(
failed_walk.collect().await.is_err(),
"failed walk_dir stream must error rather than emit an EOF frame"
);
// Strict query parsing rejects missing or unknown stream_auth.
assert!(super::parse_stream_response_auth(None, None, false).unwrap().is_none());
assert!(super::parse_stream_response_auth(None, None, true).is_err());
assert!(super::parse_stream_response_auth(Some(STREAM_RESPONSE_AUTH_V1), None, false).is_err());
assert!(super::parse_stream_response_auth(Some(STREAM_RESPONSE_AUTH_V1), Some(uuid::Uuid::nil()), false).is_err());
assert!(super::parse_stream_response_auth(Some("framed-v99"), Some(read_nonce), false).is_err());
}
}
+54 -8
View File
@@ -225,17 +225,18 @@ impl NodeService {
}
};
match self.local_peer.list_bucket(&options).await {
Ok(bucket_infos) => {
let bucket_infos = bucket_infos
.into_iter()
.filter_map(|bucket_info| serde_json::to_string(&bucket_info).ok())
.collect();
Ok(Response::new(ListBucketResponse {
Ok(bucket_infos) => match encode_bucket_infos(&bucket_infos) {
Ok(bucket_infos) => Ok(Response::new(ListBucketResponse {
success: true,
bucket_infos,
error: None,
}))
}
})),
Err(err) => Ok(Response::new(ListBucketResponse {
success: false,
bucket_infos: Vec::new(),
error: Some(err.into()),
})),
},
Err(err) => Ok(Response::new(ListBucketResponse {
success: false,
@@ -297,3 +298,48 @@ impl NodeService {
}
}
}
fn encode_bucket_infos<T: serde::Serialize>(bucket_infos: &[T]) -> Result<Vec<String>, DiskError> {
bucket_infos
.iter()
.enumerate()
.map(|(index, bucket_info)| {
serde_json::to_string(bucket_info)
.map_err(|err| DiskError::other(format!("encode BucketInfo entry {index} failed: {err}")))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::encode_bucket_infos;
use crate::storage::storage_api::rpc_consumer::node_service::contract::bucket::BucketInfo;
use serde::ser::{Error as SerError, Serializer};
struct FailingBucketInfo;
impl serde::Serialize for FailingBucketInfo {
fn serialize<S: Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
Err(S::Error::custom("injected serialization failure"))
}
}
#[test]
fn encode_bucket_infos_serializes_valid_entries_and_fails_closed_on_error() {
let valid = vec![BucketInfo {
name: "alpha".to_string(),
created: None,
deleted: None,
versioning: false,
object_locking: false,
}];
let encoded = encode_bucket_infos(&valid).expect("valid bucket list should serialize");
assert_eq!(encoded.len(), 1);
let roundtrip: BucketInfo = serde_json::from_str(&encoded[0]).expect("encoded entry must deserialize");
assert_eq!(roundtrip.name, "alpha");
let err = encode_bucket_infos(&[FailingBucketInfo]).expect_err("serialization error must fail closed");
let msg = err.to_string();
assert!(msg.contains("entry 0"), "error must identify failing index: {msg}");
}
}
+60 -8
View File
@@ -338,6 +338,9 @@ pub(crate) mod rpc_consumer {
pub(crate) use rustfs_ecstore::api::disk::{BackgroundPipeWriter, BackgroundReaderStream, background_pipe};
pub(crate) use rustfs_ecstore::api::rpc::with_rpc_background_request;
pub(crate) const DEFAULT_READ_BUFFER_SIZE: usize = super::super::DEFAULT_READ_BUFFER_SIZE;
pub(crate) use super::super::ecstore_rpc::StreamResponseAuthDomain;
#[cfg(test)]
pub(crate) use super::super::ecstore_rpc::{verify_stream_auth_data_frame, verify_stream_auth_eof_frame};
#[cfg(test)]
pub(crate) use super::super::storage_contracts::{
NS_SCANNER_BODY_SHA256_QUERY, NS_SCANNER_CAPABILITY_CHALLENGE_QUERY, NS_SCANNER_CYCLE_QUERY,
@@ -347,10 +350,17 @@ pub(crate) mod rpc_consumer {
};
pub(crate) use super::super::storage_contracts::{
NS_SCANNER_PROTOCOL_VERSION, NsScannerCapabilityResponse, PUT_FILE_AUTH_TRAILER_LEN, PUT_FILE_AUTH_V1,
PUT_FILE_CAPABILITY_VERSION, PutFileCapabilityResponse, WALK_DIR_STREAM_COMPLETION_V1,
PUT_FILE_CAPABILITY_VERSION, PutFileCapabilityResponse, STREAM_RESPONSE_AUTH_HEADER, STREAM_RESPONSE_AUTH_V1,
STREAM_RESPONSE_FRAME_MAX_PAYLOAD, WALK_DIR_STREAM_COMPLETION_V1,
};
#[cfg(test)]
pub(crate) use super::super::storage_contracts::{
STREAM_RESPONSE_AUTH_NONCE_QUERY, STREAM_RESPONSE_AUTH_QUERY, STREAM_RESPONSE_DATA_HEADER_LEN,
STREAM_RESPONSE_EOF_FRAME_LEN,
};
pub(crate) use super::super::{
DeleteOptions, DiskStore, RemoteBackgroundIo, StorageDiskRpcExt, WalkDirOptions, check_and_record_signed_rpc_nonce,
DeleteOptions, DiskStore, RemoteBackgroundIo, StorageDiskRpcExt, WalkDirOptions,
check_and_record_signed_rpc_nonce_for_peer, encode_stream_auth_data_frame, encode_stream_auth_eof_frame,
find_local_disk_by_ref_for_rpc, find_local_disk_by_ref_for_scanner_rpc, rpc_background_admission,
sign_ns_scanner_capability_with_usage_capabilities, sign_ns_scanner_tier_registry_preflight_capability,
sign_ns_scanner_usage_watch_capability, sign_put_file_capability, verify_put_file_auth_trailer, verify_rpc_signature,
@@ -401,6 +411,8 @@ pub(crate) mod rpc_consumer {
}
pub(crate) mod bucket {
#[cfg(test)]
pub(crate) use super::super::super::super::contract::bucket::BucketInfo;
pub(crate) use super::super::super::super::contract::bucket::{
BucketOptions, DeleteBucketOptions, MakeBucketOptions,
};
@@ -693,24 +705,28 @@ pub(crate) mod ecstore_internode {
}
pub(crate) mod ecstore_rpc {
#[cfg(any(feature = "internode-transport", all(feature = "nixl", target_os = "linux")))]
pub(crate) use rustfs_ecstore::api::rpc::check_and_record_signed_rpc_nonce;
pub(crate) use rustfs_ecstore::api::rpc::{
KMS_SIGNAL_SUBSYSTEM, LocalPeerS3Client, MAX_NETWORK_PROBE_BYTES, MAX_NETWORK_PROBE_DURATION, NetworkPeerProbeClient,
NetworkPeerProbeError, PEER_RESTDRY_RUN, PEER_RESTSIGNAL, PEER_RESTSUB_SYS, PeerRestClient, PeerS3Client,
SERVICE_SIGNAL_REFRESH_CONFIG, SERVICE_SIGNAL_RELOAD_DYNAMIC, TONIC_RPC_PREFIX, check_and_record_signed_rpc_nonce,
decode_heal_bucket_rpc_options, normalize_tonic_rpc_audience, rpc_auth_is_resource_exhausted, rpc_background_admission,
SERVICE_SIGNAL_REFRESH_CONFIG, SERVICE_SIGNAL_RELOAD_DYNAMIC, StreamResponseAuthDomain, TONIC_RPC_PREFIX,
check_and_record_signed_rpc_nonce_for_peer, decode_heal_bucket_rpc_options, encode_stream_auth_data_frame,
encode_stream_auth_eof_frame, normalize_tonic_rpc_audience, rpc_auth_is_resource_exhausted, rpc_background_admission,
sign_ns_scanner_capability_with_usage_capabilities, sign_ns_scanner_tier_registry_preflight_capability,
sign_ns_scanner_usage_watch_capability, sign_put_file_capability, sign_tonic_rpc_response_proof,
tonic_boot_epoch_challenge, tonic_boot_epoch_response_headers_with_msgpack_capability,
tonic_msgpack_manifest_capability_requested, tonic_rpc_auth_failure_reason, verify_put_file_auth_trailer,
verify_rpc_signature, verify_tonic_canonical_body_digest, verify_tonic_mutation_body_digest,
verify_tonic_mutation_body_digest_reject_unsigned, verify_tonic_rpc_signature_with_bootstrap,
verify_tonic_mutation_body_digest_reject_unsigned, verify_tonic_rpc_signature_with_bootstrap_and_peer,
};
#[cfg(test)]
pub(crate) use rustfs_ecstore::api::rpc::{
RpcReplayCacheAdmissionError, ScannerScopedDirtyUsageAckEntry, build_put_file_auth_trailer, gen_signature_headers,
gen_tonic_replay_scope_headers, gen_tonic_signature_headers, set_tonic_canonical_body_digest,
tonic_boot_epoch_response_headers, verify_ns_scanner_capability_with_usage_capabilities, verify_put_file_capability,
verify_tonic_boot_epoch_response, verify_tonic_rpc_response_proof,
verify_stream_auth_data_frame, verify_stream_auth_eof_frame, verify_tonic_boot_epoch_response,
verify_tonic_rpc_response_proof,
};
#[cfg(test)]
pub(crate) use rustfs_ecstore::api::rpc::{
@@ -2453,6 +2469,7 @@ pub(crate) fn verify_rpc_signature(url: &str, method: &http::Method, headers: &h
ecstore_rpc::verify_rpc_signature(url, method, headers)
}
#[cfg(any(feature = "internode-transport", all(feature = "nixl", target_os = "linux")))]
pub(crate) fn check_and_record_signed_rpc_nonce(
headers: &http::HeaderMap,
nonce: uuid::Uuid,
@@ -2463,6 +2480,40 @@ pub(crate) fn check_and_record_signed_rpc_nonce(
ecstore_rpc::check_and_record_signed_rpc_nonce(headers, nonce, rpc_path, operation, backend)
}
pub(crate) fn check_and_record_signed_rpc_nonce_for_peer(
headers: &http::HeaderMap,
nonce: uuid::Uuid,
rpc_path: &str,
operation: &'static str,
backend: &'static str,
peer: Option<std::net::IpAddr>,
) -> std::io::Result<()> {
ecstore_rpc::check_and_record_signed_rpc_nonce_for_peer(headers, nonce, rpc_path, operation, backend, peer)
}
pub(crate) fn encode_stream_auth_data_frame(
domain: ecstore_rpc::StreamResponseAuthDomain,
url: &str,
method: &http::Method,
nonce: uuid::Uuid,
seq: u64,
payload: &[u8],
) -> std::io::Result<Vec<u8>> {
ecstore_rpc::encode_stream_auth_data_frame(domain, url, method, nonce, seq, payload)
}
pub(crate) fn encode_stream_auth_eof_frame(
domain: ecstore_rpc::StreamResponseAuthDomain,
url: &str,
method: &http::Method,
nonce: uuid::Uuid,
seq: u64,
total_bytes: u64,
running_sha256: &[u8; 32],
) -> std::io::Result<[u8; 89]> {
ecstore_rpc::encode_stream_auth_eof_frame(domain, url, method, nonce, seq, total_bytes, running_sha256)
}
pub(crate) fn verify_put_file_auth_trailer(
url: &str,
method: &http::Method,
@@ -2512,13 +2563,14 @@ pub(crate) fn sign_put_file_capability(
ecstore_rpc::sign_put_file_capability(challenge, server_epoch, version)
}
pub(crate) fn verify_tonic_rpc_signature_with_bootstrap(
pub(crate) fn verify_tonic_rpc_signature_with_bootstrap_and_peer(
audience: &str,
path: &str,
headers: &http::HeaderMap,
allow_replay_scope_bootstrap: bool,
peer: Option<std::net::IpAddr>,
) -> std::io::Result<()> {
ecstore_rpc::verify_tonic_rpc_signature_with_bootstrap(audience, path, headers, allow_replay_scope_bootstrap)
ecstore_rpc::verify_tonic_rpc_signature_with_bootstrap_and_peer(audience, path, headers, allow_replay_scope_bootstrap, peer)
}
pub(crate) fn rpc_auth_is_resource_exhausted(error: &std::io::Error) -> bool {
+1 -1
View File
@@ -200,7 +200,7 @@ pub(crate) mod server {
RemoteBackgroundIo, ServerContextSlot, TONIC_RPC_PREFIX, normalize_tonic_rpc_audience,
rpc_auth_is_resource_exhausted, rpc_background_admission, tonic_boot_epoch_challenge,
tonic_boot_epoch_response_headers_with_msgpack_capability, tonic_msgpack_manifest_capability_requested,
tonic_rpc_auth_failure_reason, verify_tonic_rpc_signature_with_bootstrap, with_remote_background_io,
tonic_rpc_auth_failure_reason, verify_tonic_rpc_signature_with_bootstrap_and_peer, with_remote_background_io,
};
pub(crate) fn try_current_local_node_name() -> Option<String> {
+1 -1
View File
@@ -53,7 +53,7 @@
33|crates/ecstore/src/services/tier/tier.rs
1|crates/ecstore/src/services/tier/tier_config.rs
1|crates/ecstore/src/services/tier/warm_backend.rs
2|crates/ecstore/src/services/tier/warm_backend_gcs.rs
1|crates/ecstore/src/services/tier/warm_backend_gcs.rs
1|crates/ecstore/src/services/tier/warm_backend_s3.rs
1|crates/ecstore/src/services/tier/warm_backend_wasabi.rs
7|crates/ecstore/src/set_disk/core/io_primitives.rs