Compare commits

..

1 Commits

Author SHA1 Message Date
overtrue b25f27330d fix(gateway): harden post-cutover S3 auth, body limits, and context isolation
Address nine post-cutover parity and isolation regressions against rustfs/gateway:
- Keep expired STS sessions enabled in gateway-adapter so gateway returns 400 ExpiredToken (retiring c-cred-0020 ruling) while disabled/invalid STS and expired service accounts remain disabled.
- Remove pre-auth 20 MiB ControlBodyDigestService buffering from S3/gateway listeners, preserving console-listener route isolation via ConsoleListenerRouteService and post-auth SigV2 Content-MD5 checks on DeleteObjects and non-empty config PUTs.
- Stop copying unsigned wire x-amz-server-side-encryption* headers into PostObjectPolicyHeaders during preflight authorization.
- Source live_root() credentials and token signing key strictly from ServerContextSlot rather than process globals.
- Configure max_framed_upload_bytes(5 GiB) and upload_object_ceiling(5 GiB) on GatewayStack.
- Initialize S3 and ListObjects metrics on GatewayStack::assemble.
- Inject ServerContextSlot into NativeConsoleEdgeService request extensions.
- Scope ProtocolStorageClient is_owner and list_buckets IAM lookup to ServerContextSlot without breaking direct-write BucketGenerationGuard invariants.
- Wire verify_paths_double_encoded_under(TABLE_CATALOG_PREFIXES) in native admin, record 204 NO_CONTENT on PutBucketPolicy audit entries, and set explicit 500 status on HeadObject ErrMeta.
2026-11-27 06:46:52 +08:00
22 changed files with 1608 additions and 1090 deletions
-14
View File
@@ -59,20 +59,6 @@ failures = [
]
expires = 2027-02-01
# Tracked IAM gap (R-065): https://github.com/rustfs/backlog/issues/2684#issuecomment-7163283798
[[ruling]]
case = "c-cred-0020"
ledger = "R-065"
reason = "Tracked IAM gap (rustfs/rustfs#9559, rustfs/backlog#2684): expired STS session token returns 403 InvalidAccessKeyId instead of 400 ExpiredToken."
failures = [
"[expect/status] at /expect/status: exchange #1, attempt 1: expected status 400, observed 403",
"[expect/error.code] at /expect/error/code: exchange #1, attempt 1: expected <Code>ExpiredToken</Code>, the body carried <Code>InvalidAccessKeyId</Code>",
"[expect/body.exact_utf8] at /expect/body: exchange #1, attempt 1: bodies differ at byte 52 (expected 196 bytes, observed 200 bytes)\n expected: …F-8\\\"?>\\n<Error><Code>ExpiredToken</Code><Message>the session …\n observed: …F-8\\\"?>\\n<Error><Code>InvalidAccessKeyId</Code><Message>The Ac…",
"[expect/body.not_contains_utf8] at /expect/body: exchange #1, attempt 1: the body must not contain \"InvalidAccessKeyId\", found at byte 52",
]
expires = 2027-02-01
# Outer CORS middleware and HTTP/2 OPTIONS parity: https://github.com/rustfs/backlog/issues/2684#issuecomment-7163283798
[[ruling]]
+125 -4
View File
@@ -134,15 +134,18 @@ fn classify_iam_error(error: &IamError) -> Result<CredentialLookup, ProviderErro
}
/// Builds the gateway credential for one IAM identity. No authorization happens here: a
/// disabled or invalid principal still resolves, marked disabled, and the gateway refuses it
/// exactly as it refuses an unknown key.
/// disabled or otherwise invalid principal still resolves, marked disabled, and the gateway
/// refuses it identically to an unknown key. An expired STS session is the one exception: its
/// expiry is carried in [`SessionBinding`] without calling `.disable()` so the gateway checks the
/// signature and session token first and answers `400 ExpiredToken` to its holder.
fn to_gateway_credentials(access_key: &str, identity: &UserIdentity, valid: bool) -> Result<Credentials, ProviderError> {
let cred = &identity.credentials;
let mut credentials = Credentials::new(access_key, cred.secret_key.as_bytes()).map_err(|_| ProviderError::Backend)?;
// A service account carries a claims token internally, but its clients never present it, so
// it authenticates as a long-term credential (as `check_session_token` treats it in legacy).
if !cred.session_token.is_empty() && !cred.is_service_account() {
let is_sts_session = !cred.session_token.is_empty() && !cred.is_service_account();
if is_sts_session {
// A temporary credential without an expiry cannot become a gateway session, which always
// ends. Refusing it as a fault is the fail-closed answer; a never-ending session is not.
let expiration = cred.expiration.ok_or(ProviderError::Backend)?;
@@ -152,7 +155,16 @@ fn to_gateway_credentials(access_key: &str, identity: &UserIdentity, valid: bool
.map_err(|_| ProviderError::Backend)?;
}
if !valid || cred.status == ACCOUNT_OFF {
// Leave STS sessions enabled when expiration is the sole reason `valid` is false so the
// gateway evaluates `SessionBinding` against `RequestNow` and returns `400 ExpiredToken`.
// Disabled, structurally invalid, or non-expired invalid STS credentials, as well as expired
// service accounts and long-term users, remain disabled (`403`).
let expired_sts_only = is_sts_session
&& cred.status != ACCOUNT_OFF
&& cred.access_key.len() >= 3
&& cred.secret_key.len() >= 8
&& cred.is_expired();
if (!valid && !expired_sts_only) || cred.status == ACCOUNT_OFF {
credentials = credentials.disable();
}
Ok(credentials)
@@ -459,4 +471,113 @@ mod tests {
assert!(matches!(provider.lookup("rootadmin").await, Err(ProviderError::Unavailable)));
assert_eq!(iam.calls.load(Ordering::SeqCst), 0);
}
/// Positive — an expired STS credential keeps its session binding enabled so the gateway can
/// verify possession first and answer `400 ExpiredToken` via `SessionBinding`.
#[tokio::test]
async fn credentials_expired_sts_stays_enabled_for_gateway_expiry_refusal() {
let expires_at = (OffsetDateTime::now_utc() - time::Duration::hours(1)).unix_timestamp();
let iam = fake(true, move || {
let mut cred = user("on");
cred.session_token = "expired-sts-token".to_owned();
cred.parent_user = "parent".to_owned();
cred.expiration = Some(OffsetDateTime::from_unix_timestamp(expires_at).expect("valid timestamp"));
found(cred, false)
});
let credentials = expect_found(lookup(iam, ACCESS_KEY).await);
assert!(!credentials.is_disabled());
let binding = credentials
.session_binding()
.expect("expired STS retains its session binding");
assert_eq!(binding.expires_at_unix_seconds(), expires_at);
let now = RequestNow::from_unix_seconds(expires_at + 1);
assert_eq!(
credentials.admit(Some(b"expired-sts-token"), now),
Err(rustfs_gateway::CredentialRefusal::SessionExpired)
);
assert_eq!(
credentials.admit(Some(b"wrong-token"), now),
Err(rustfs_gateway::CredentialRefusal::SessionTokenMismatch)
);
assert_eq!(
credentials.admit(None, now),
Err(rustfs_gateway::CredentialRefusal::SessionCredentialWithoutToken)
);
}
/// Negative — disabled, structurally invalid, or non-expired invalid STS credentials, and
/// expired service accounts, must still be disabled so the gateway answers `403`.
#[tokio::test]
async fn credentials_non_expiry_invalid_sts_and_expired_service_account_stay_disabled() {
let past = OffsetDateTime::now_utc() - time::Duration::hours(1);
let future = OffsetDateTime::now_utc() + time::Duration::hours(1);
let disabled_expired_sts = expect_found(
lookup(
fake(true, move || {
let mut cred = user("off");
cred.session_token = "sts-token".to_owned();
cred.parent_user = "parent".to_owned();
cred.expiration = Some(past);
found(cred, false)
}),
ACCESS_KEY,
)
.await,
);
assert!(disabled_expired_sts.is_disabled());
assert_eq!(
disabled_expired_sts.admit(Some(b"sts-token"), RequestNow::from_unix_seconds(past.unix_timestamp() + 1)),
Err(rustfs_gateway::CredentialRefusal::Disabled)
);
let invalid_unexpired_sts = expect_found(
lookup(
fake(true, move || {
let mut cred = user("on");
cred.session_token = "sts-token".to_owned();
cred.parent_user = "parent".to_owned();
cred.expiration = Some(future);
found(cred, false)
}),
ACCESS_KEY,
)
.await,
);
assert!(invalid_unexpired_sts.is_disabled());
let short_key_expired_sts = expect_found(
lookup(
fake(true, move || {
let mut cred = user("on");
cred.access_key = "ab".to_owned();
cred.session_token = "sts-token".to_owned();
cred.parent_user = "parent".to_owned();
cred.expiration = Some(past);
found(cred, false)
}),
"ab",
)
.await,
);
assert!(short_key_expired_sts.is_disabled());
let expired_service_account = expect_found(
lookup(
fake(true, move || {
let mut cred = user("on");
cred.session_token = "service-account-claims-token".to_owned();
cred.parent_user = "parent".to_owned();
cred.expiration = Some(past);
cred.claims =
Some([(rustfs_credentials::IAM_POLICY_CLAIM_NAME_SA.to_owned(), "inherited-policy".into())].into());
found(cred, false)
}),
ACCESS_KEY,
)
.await,
);
assert!(expired_service_account.is_disabled());
assert!(expired_service_account.session_binding().is_none());
}
}
+56 -51
View File
@@ -171,73 +171,78 @@ impl DefaultBucketUsecase {
bucket: &str,
policy: &str,
) -> rustfs_s3_types::S3Result<()> {
RequestEnvelope::audit_only_operation(envelope, S3Operation::PutBucketPolicy, StatusCode::OK, |envelope| async move {
let expected_incarnation_id = bucket_config_mutation_incarnation(&envelope, bucket)?;
let request_context = envelope.request_context().cloned();
RequestEnvelope::audit_only_operation(
envelope,
S3Operation::PutBucketPolicy,
StatusCode::NO_CONTENT,
|envelope| async move {
let expected_incarnation_id = bucket_config_mutation_incarnation(&envelope, bucket)?;
let request_context = envelope.request_context().cloned();
let Some(store) = self.object_store() else {
return Err(s3_error!(InternalError, "Not init"));
};
let Some(store) = self.object_store() else {
return Err(s3_error!(InternalError, "Not init"));
};
store
.get_bucket_info(bucket, &BucketOptions::default())
.await
.map_err(ApiError::from)?;
store
.get_bucket_info(bucket, &BucketOptions::default())
.await
.map_err(ApiError::from)?;
let cfg: BucketPolicy = serde_json::from_str(policy).map_err(|_| s3_error!(MalformedPolicy))?;
let cfg: BucketPolicy = serde_json::from_str(policy).map_err(|_| s3_error!(MalformedPolicy))?;
if cfg.is_valid().is_err() {
return Err(s3_error!(MalformedPolicy));
}
if cfg.is_valid().is_err() {
return Err(s3_error!(MalformedPolicy));
}
let replication_policy = serde_json::from_str(policy)
.map(serde_json::Value::Object)
.map_err(|_| s3_error!(MalformedPolicy))?;
let replication_policy = serde_json::from_str(policy)
.map(serde_json::Value::Object)
.map_err(|_| s3_error!(MalformedPolicy))?;
let is_public_policy = cfg
.statements
.iter()
.any(|statement| matches!(statement.effect, Effect::Allow) && statement.principal.is_public());
let is_public_policy = cfg
.statements
.iter()
.any(|statement| matches!(statement.effect, Effect::Allow) && statement.principal.is_public());
if is_public_policy {
match metadata_sys::get_public_access_block_config(bucket).await {
Ok((config, _)) => {
if config.block_public_policy.unwrap_or(false) {
return Err(s3_error!(AccessDenied, "Access Denied"));
if is_public_policy {
match metadata_sys::get_public_access_block_config(bucket).await {
Ok((config, _)) => {
if config.block_public_policy.unwrap_or(false) {
return Err(s3_error!(AccessDenied, "Access Denied"));
}
}
}
Err(err) => {
if err != StorageError::ConfigNotFound {
warn!(
component = LOG_COMPONENT_APP,
subsystem = LOG_SUBSYSTEM_BUCKET,
event = "bucket_public_access_block_load_failed",
bucket = %bucket,
error = ?err,
"Failed to load bucket public access block configuration"
);
return Err(ApiError::from(err).into());
Err(err) => {
if err != StorageError::ConfigNotFound {
warn!(
component = LOG_COMPONENT_APP,
subsystem = LOG_SUBSYSTEM_BUCKET,
event = "bucket_public_access_block_load_failed",
bucket = %bucket,
error = ?err,
"Failed to load bucket public access block configuration"
);
return Err(ApiError::from(err).into());
}
}
}
}
}
let data = policy.as_bytes().to_vec();
let data = policy.as_bytes().to_vec();
update_bucket_config_for_incarnation(bucket, BUCKET_POLICY_CONFIG, data, expected_incarnation_id)
.await
.map_err(ApiError::from)?;
update_bucket_config_for_incarnation(bucket, BUCKET_POLICY_CONFIG, data, expected_incarnation_id)
.await
.map_err(ApiError::from)?;
notify_bucket_metadata_reload(bucket.to_owned(), "put bucket policy", request_context, false).await;
notify_bucket_metadata_reload(bucket.to_owned(), "put bucket policy", request_context, false).await;
let mut item = sr_bucket_meta_item(bucket.to_owned(), "policy");
item.policy = Some(replication_policy);
if let Err(err) = site_replication_bucket_meta_hook(item).await {
warn!(bucket = %bucket, error = ?err, "site replication bucket policy hook failed");
}
let mut item = sr_bucket_meta_item(bucket.to_owned(), "policy");
item.policy = Some(replication_policy);
if let Err(err) = site_replication_bucket_meta_hook(item).await {
warn!(bucket = %bucket, error = ?err, "site replication bucket policy hook failed");
}
Ok(())
})
Ok(())
},
)
.await
}
}
+15
View File
@@ -389,6 +389,21 @@ impl AppContext {
self.notification_system = notification_system;
self
}
pub(crate) fn with_empty_action_credentials(mut self) -> Self {
struct EmptyActionCredentials;
impl ActionCredentialInterface for EmptyActionCredentials {
fn get(&self) -> Option<rustfs_credentials::Credentials> {
None
}
fn publish(&self, _credentials: rustfs_credentials::Credentials) -> bool {
false
}
}
self.action_credentials = Arc::new(EmptyActionCredentials);
self
}
}
static APP_CONTEXT_SINGLETON: OnceLock<Arc<AppContext>> = OnceLock::new();
+17 -9
View File
@@ -29,6 +29,12 @@ use crate::on_demand_migration::{
BucketOdmState, HeadPolicy, OdmLookup, OdmOp, OdmOutcome, OnDemandMigrationSys, SourceClient, SourceError, SourceHead,
};
fn err_meta(message: &'static str) -> S3Error {
let mut err = S3Error::with_message(S3ErrorCode::Custom("ErrMeta".into()), message);
err.set_status_code(StatusCode::INTERNAL_SERVER_ERROR);
err
}
/// The DTO holds ordinary fields; ETag remains a native fact until either edge encodes it.
#[derive(Debug)]
pub(crate) struct HeadObjectOutputFacts {
@@ -817,7 +823,7 @@ impl DefaultObjectUsecase {
if let Some(amz_restore) = metadata_map.get(AMZ_RESTORE) {
let Ok(restore_status) = parse_restore_obj_status(amz_restore) else {
return Err(S3Error::with_message(S3ErrorCode::Custom("ErrMeta".into()), "parse amz_restore failed."));
return Err(err_meta("parse amz_restore failed."));
};
if let Ok(header_value) = HeaderValue::from_str(restore_status.to_string2().as_str()) {
response.headers.insert(AMZ_RESTORE, header_value);
@@ -827,16 +833,10 @@ impl DefaultObjectUsecase {
&& let Ok(header_name) = http::HeaderName::from_bytes(AMZ_RESTORE_REQUEST_DATE.as_bytes())
{
let Ok(amz_restore_request_date) = OffsetDateTime::parse(amz_restore_request_date, &Rfc3339) else {
return Err(S3Error::with_message(
S3ErrorCode::Custom("ErrMeta".into()),
"parse amz_restore_request_date failed.",
));
return Err(err_meta("parse amz_restore_request_date failed."));
};
let Ok(amz_restore_request_date) = amz_restore_request_date.format(&RFC1123) else {
return Err(S3Error::with_message(
S3ErrorCode::Custom("ErrMeta".into()),
"format amz_restore_request_date failed.",
));
return Err(err_meta("format amz_restore_request_date failed."));
};
if let Ok(header_value) = HeaderValue::from_str(&amz_restore_request_date) {
response.headers.insert(header_name, header_value);
@@ -1535,6 +1535,14 @@ mod tests {
.unwrap_err();
assert_eq!(err.code().as_str(), "InvalidArgument");
}
#[test]
fn err_meta_sets_internal_server_error_status() {
let err = err_meta("parse amz_restore failed.");
assert_eq!(err.code(), &S3ErrorCode::Custom("ErrMeta".into()));
assert_eq!(err.status_code(), Some(StatusCode::INTERNAL_SERVER_ERROR));
assert_eq!(err.message(), Some("parse amz_restore failed."));
}
}
#[cfg(test)]
+142 -21
View File
@@ -493,7 +493,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
}
let input = owned::put_input(input)?;
let envelope = Self::create_envelope_with_headers(
let envelope = self.create_envelope_with_headers(
Method::PUT,
uri,
RequestParams {
@@ -520,7 +520,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
trace_protocol_request("delete_object", Some(bucket), Some(key));
let uri = build_object_uri(bucket, key, &[])?;
let envelope = Self::create_envelope(
let envelope = self.create_envelope(
Method::DELETE,
uri,
RequestParams {
@@ -544,7 +544,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
trace_protocol_request("head_object", Some(bucket), Some(key));
let uri = build_object_uri(bucket, key, &[])?;
let envelope = Self::create_envelope(
let envelope = self.create_envelope(
Method::HEAD,
uri,
RequestParams {
@@ -634,15 +634,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
"Protocol storage client request"
);
let envelope = Self::create_envelope(
Method::GET,
http::Uri::from_static("/"),
RequestParams {
bucket: None,
object: None,
credentials,
},
);
let envelope = self.create_list_buckets_envelope(credentials);
rustfs_io_metrics::record_s3_op(rustfs_s3_ops::S3Operation::ListBuckets);
self.owned_bucket_usecase()
.execute_list_buckets(envelope, gateway_dto::ListBucketsInput::default())
@@ -762,7 +754,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
trace_protocol_request("create_bucket", Some(bucket), None);
let uri = build_bucket_uri(bucket, &[])?;
let envelope = Self::create_envelope(
let envelope = self.create_envelope(
Method::PUT,
uri,
RequestParams {
@@ -828,7 +820,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
let key = input.key.as_str().to_owned();
let uri = build_object_uri(&bucket, &key, &[])?;
let input = owned::copy_input(input)?;
let envelope = Self::create_envelope(
let envelope = self.create_envelope(
Method::PUT,
uri,
RequestParams {
@@ -857,7 +849,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
.map_err(|e| conversion_error("DeleteBucket bucket", e))?,
expected_bucket_owner: None,
};
let envelope = Self::create_envelope(
let envelope = self.create_envelope(
Method::DELETE,
uri,
RequestParams {
@@ -889,7 +881,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
let key = input.key.as_str().to_owned();
let uri = build_object_uri(&bucket, &key, &[("uploads", None)])?;
let input = multipart::create_multipart_input(input)?;
let envelope = Self::create_envelope(
let envelope = self.create_envelope(
Method::POST,
uri,
RequestParams {
@@ -939,7 +931,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
if let Ok(value) = content_length.to_string().parse() {
headers.insert("content-length", value);
}
let envelope = Self::create_envelope_with_headers(
let envelope = self.create_envelope_with_headers(
Method::PUT,
uri,
RequestParams {
@@ -985,7 +977,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
let key = input.key.as_str().to_owned();
let input = multipart::complete_multipart_input(input)?;
let uri = build_object_uri(&bucket, &key, &[("uploadId", Some(upload_id.as_str()))])?;
let envelope = Self::create_envelope(
let envelope = self.create_envelope(
Method::POST,
uri,
RequestParams {
@@ -1022,7 +1014,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
let key = input.key.as_str().to_owned();
multipart::abort_multipart_input(&input)?;
let uri = build_object_uri(&bucket, &key, &[("uploadId", Some(upload_id.as_str()))])?;
let envelope = Self::create_envelope(
let envelope = self.create_envelope(
Method::DELETE,
uri,
RequestParams {
@@ -1062,7 +1054,7 @@ impl rustfs_protocols::common::client::s3::StorageBackend for ProtocolStorageCli
let key = input.key.as_str().to_owned();
let (uri, input) = multipart::prepare_upload_part_copy(request)?;
let envelope = Self::create_envelope(
let envelope = self.create_envelope(
Method::PUT,
uri,
RequestParams {
@@ -1253,7 +1245,7 @@ mod tests {
..Default::default()
};
let envelope = ProtocolStorageClient::create_envelope(
let envelope = ProtocolStorageClient::new(crate::runtime_sources::ServerContextSlot::new()).create_envelope(
Method::GET,
http::Uri::from_static("/bucket?list-type=2"),
RequestParams {
@@ -2681,6 +2673,135 @@ mod listing_tests {
});
}
#[test]
#[serial_test::serial]
fn protocol_list_buckets_scopes_non_root_iam_and_is_owner_to_bound_server_context() {
crate::app::gating_test_env::run_large_stack_test("protocol-list-buckets-isolation", || async {
let (_temp, ambient_root, ambient_backend) = listing_client().await;
let other_root = rustfs_credentials::Credentials {
access_key: "other-server-root".to_owned(),
secret_key: "other-server-root-secret".to_owned(),
status: "on".to_owned(),
..Default::default()
};
let (_other_temp, other_context, other_iam) =
crate::protocols::policy_test::protocol_test_context(other_root.clone()).await;
for bucket in ["bound-allowed", "bound-denied"] {
other_context
.object_store()
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create bound server bucket");
}
let user_key = "bound-nonroot-user";
let user_secret = "bound-nonroot-secret";
let policy_name = "bound-list-only";
let policy_doc = rustfs_policy::policy::Policy::parse_config(
br#"{
"Version":"2012-10-17",
"Statement":[{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::bound-allowed"]}]
}"#,
)
.expect("parse bound user policy");
other_iam
.set_policy(policy_name, policy_doc)
.await
.expect("install policy on bound server IAM");
other_iam
.create_user(
user_key,
&rustfs_madmin::AddOrUpdateUserReq {
secret_key: user_secret.to_owned(),
policy: None,
status: rustfs_madmin::AccountStatus::Enabled,
},
)
.await
.expect("create non-root user on bound server IAM");
other_iam
.policy_db_set(user_key, rustfs_iam::store::UserType::Reg, false, policy_name)
.await
.expect("attach policy on bound server IAM");
let other_slot = ServerContextSlot::new();
assert!(other_slot.install(other_context));
let other = ProtocolStorageClient::new(other_slot);
// `is_owner` must reflect the bound server's root credentials, never the ambient/global root.
let ambient_root_envelope = other.create_envelope(
Method::GET,
http::Uri::from_static("/"),
RequestParams {
bucket: None,
object: None,
credentials: &ambient_root,
},
);
assert!(
!ambient_root_envelope.req_info().expect("req info").is_owner,
"ambient root must not be treated as owner on another server context"
);
let other_root_envelope = other.create_envelope(
Method::GET,
http::Uri::from_static("/"),
RequestParams {
bucket: None,
object: None,
credentials: &other_root,
},
);
assert!(
other_root_envelope.req_info().expect("req info").is_owner,
"bound server's own root must be treated as owner"
);
assert!(
other_root_envelope.server_context().is_none(),
"direct-write create_envelope keeps server_context unbound for BucketGenerationGuard compatibility"
);
// Ambient root has no IAM identity or policy on `other` and is not its owner -> AccessDenied.
let ambient_err = other
.list_buckets(&ambient_root)
.await
.expect_err("ambient root must not list buckets on another server");
assert_eq!(ambient_err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied);
// Non-root user defined ONLY in `other_iam` must see only `bound-allowed`.
let non_root_creds = rustfs_credentials::Credentials {
access_key: user_key.to_owned(),
secret_key: user_secret.to_owned(),
status: "on".to_owned(),
..Default::default()
};
let listed = other
.list_buckets(&non_root_creds)
.await
.expect("non-root user in bound server IAM should list its allowed bucket");
let names: Vec<_> = listed.buckets.iter().map(|b| b.name.as_str()).collect();
assert_eq!(names, ["bound-allowed"]);
// Bound server's own root lists both bound buckets.
let root_listed = other.list_buckets(&other_root).await.expect("bound root lists all buckets");
let mut root_names: Vec<_> = root_listed.buckets.iter().map(|b| b.name.as_str()).collect();
root_names.sort_unstable();
assert_eq!(root_names, ["bound-allowed", "bound-denied"]);
// Direct protocol writes remain unaffected by `list_buckets` context binding (no
// missing BucketGenerationGuard refusal on a bound ProtocolStorageClient).
let put_input = gateway_dto::PutObjectInput {
bucket: rustfs_gateway_types::BucketName::new("listing-runtime".to_owned()).expect("bucket"),
key: rustfs_gateway_types::ObjectKey::new("direct-write.txt".to_owned()).expect("key"),
content_length: 4,
body: Some(rustfs_gateway_stream::ByteStream::from_bytes(bytes::Bytes::from_static(b"data"))),
..Default::default()
};
ambient_backend
.put_object(put_input, &ambient_root)
.await
.expect("direct protocol write must remain unaffected by list_buckets context binding");
});
}
#[test]
fn protocol_listing_output_matches_legacy_projection() {
use rustfs_gateway_types::{ETag, ObjectKey, Timestamp};
+1 -1
View File
@@ -313,7 +313,7 @@ fn protocol_copy_request_head_matches_legacy() {
..Default::default()
};
let uri = build_object_uri("copy-target", "a ?&/%é", &[]).expect("request URI");
let envelope = ProtocolStorageClient::create_envelope(
let envelope = ProtocolStorageClient::new(crate::runtime_sources::ServerContextSlot::new()).create_envelope(
Method::PUT,
uri,
RequestParams {
@@ -348,7 +348,11 @@ fn multipart_envelopes_preserve_original_request_facts() {
object: Some("a ?#+%.txt".into()),
credentials: &credentials,
};
let envelope = ProtocolStorageClient::create_envelope(method.clone(), uri.clone(), params);
let envelope = ProtocolStorageClient::new(crate::runtime_sources::ServerContextSlot::new()).create_envelope(
method.clone(),
uri.clone(),
params,
);
assert_eq!((envelope.method(), envelope.uri(), envelope.headers().is_empty()), (&method, &uri, true));
let owned = envelope.req_info().expect("owned facts");
assert_eq!(
+37 -4
View File
@@ -37,7 +37,7 @@ impl ProtocolStorageClient {
range: Option<rustfs_gateway_types::ByteRange>,
) -> S3Result<dto::GetObjectOutput> {
let uri = super::build_object_uri(bucket, key, &[])?;
let envelope = Self::create_envelope(
let envelope = self.create_envelope(
Method::GET,
uri,
RequestParams {
@@ -72,21 +72,54 @@ impl ProtocolStorageClient {
DefaultObjectUsecase::with_context(self.server_ctx.app_context())
}
pub(super) fn create_envelope(method: Method, uri: Uri, params: RequestParams<'_>) -> RequestEnvelope {
Self::create_envelope_with_headers(method, uri, params, HeaderMap::new())
pub(super) fn create_envelope(&self, method: Method, uri: Uri, params: RequestParams<'_>) -> RequestEnvelope {
self.create_envelope_with_headers(method, uri, params, HeaderMap::new())
}
pub(super) fn create_envelope_with_headers(
&self,
method: Method,
uri: Uri,
params: RequestParams<'_>,
headers: HeaderMap,
) -> RequestEnvelope {
let is_owner = current_action_credentials().is_some_and(|root| params.credentials.access_key == root.access_key);
self.create_envelope_inner(method, uri, params, headers, false)
}
pub(super) fn create_list_buckets_envelope(&self, credentials: &rustfs_credentials::Credentials) -> RequestEnvelope {
self.create_envelope_inner(
Method::GET,
Uri::from_static("/"),
RequestParams {
bucket: None,
object: None,
credentials,
},
HeaderMap::new(),
self.server_ctx.installed_app_context().is_some(),
)
}
fn create_envelope_inner(
&self,
method: Method,
uri: Uri,
params: RequestParams<'_>,
headers: HeaderMap,
attach_server_ctx: bool,
) -> RequestEnvelope {
let root = match self.server_ctx.installed_app_context() {
Some(context) => context.action_credentials().get(),
None => current_action_credentials(),
};
let is_owner = root.is_some_and(|root| params.credentials.access_key == root.access_key);
let credentials =
RequestCredentials::new(params.credentials.access_key.clone(), params.credentials.secret_key.clone(), None)
.unwrap_or_else(|_| RequestCredentials::without_secret_key(params.credentials.access_key.clone(), None));
let mut extensions = http::Extensions::new();
if attach_server_ctx {
extensions.insert(self.server_ctx.clone());
}
extensions.insert(ReqInfo {
cred: Some(params.credentials.clone()),
keystone_session_present: None,
@@ -399,7 +399,7 @@ fn protocol_upload_copy_keeps_destination_generation_fence() {
&[("partNumber", Some("1")), ("uploadId", Some(&upload.upload_id))],
)
.expect("URI");
let mut envelope = ProtocolStorageClient::create_envelope(
let mut envelope = ProtocolStorageClient::new(crate::runtime_sources::ServerContextSlot::new()).create_envelope(
Method::PUT,
uri,
RequestParams {
@@ -729,7 +729,7 @@ async fn protocol_upload_copy_capabilities_precede_part_validation() {
),
] {
let uri: http::Uri = format!("/bucket/copy-target?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=fixture/20260827/us-east-1/s3/aws4_request&X-Amz-Signature=fixture{query}").parse().expect("URI");
let request = ProtocolStorageClient::create_envelope(
let request = ProtocolStorageClient::new(crate::runtime_sources::ServerContextSlot::new()).create_envelope(
Method::PUT,
uri.clone(),
RequestParams {
+91 -2
View File
@@ -31,7 +31,7 @@ use crate::storage_api::server::http::access::{
use rustfs_gateway::sig::{SigFamily, SigLocation};
use rustfs_gateway::{RequestContextView, RequestPrincipal};
use rustfs_policy::policy::action::Action;
use rustfs_s3_types::S3Result;
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result};
use std::future::Future;
use std::sync::Arc;
use zeroize::Zeroizing;
@@ -41,13 +41,18 @@ use zeroize::Zeroizing;
/// # Errors
///
/// Credential errors from the key lookup, `MethodNotAllowed` for ACL deletion,
/// `InvalidRequest` for a misplaced capability query, `AccessDenied` for a refused license, and
/// `InvalidRequest` for a misplaced capability query, `MissingContentMD5` for a SigV2
/// control-plane mutation without a digest, `AccessDenied` for a refused license, and
/// `InternalError` when IAM or the license cannot be read or the request cannot be read back.
pub(super) fn admit<'a>(
server_ctx: &'a Arc<ServerContextSlot>,
context: &RequestContextView,
) -> impl Future<Output = S3Result<RequestEnvelope>> + Send + use<'a> {
let signature = verified_signature(context);
let is_sigv2 = context
.principal()
.map(RequestPrincipal::scheme)
.is_some_and(|scheme| scheme.family() == SigFamily::V2);
let operation = context.operation();
let envelope = RequestEnvelope::from_gateway(context, server_ctx, signature);
let keystone = context.header_token_principal().map(|_| {
@@ -75,10 +80,54 @@ pub(super) fn admit<'a>(
};
envelope.install_req_info(req_info);
admit_operation(envelope.method(), envelope.headers(), envelope.uri().query(), operation, signature)?;
enforce_sigv2_body_digest_requirement(is_sigv2, envelope.method(), envelope.headers(), operation)?;
Ok(envelope)
}
}
/// SigV2 does not sign request bodies, and `rustfs_profile()` waives the AWS checksum-required
/// check globally for legacy clients. Require a signed `Content-MD5` post-auth on SigV2
/// `DeleteObjects` and non-empty configuration `PUT`s so a signed request cannot be replayed
/// with a tampered XML body; the gateway verifies the supplied `Content-MD5` post-auth.
fn enforce_sigv2_body_digest_requirement(
is_sigv2: bool,
method: &http::Method,
headers: &http::HeaderMap,
operation: &str,
) -> S3Result<()> {
if !is_sigv2 {
return Ok(());
}
let has_content_md5 = headers
.get("content-md5")
.is_some_and(|value| !value.as_bytes().iter().all(u8::is_ascii_whitespace));
if has_content_md5 {
return Ok(());
}
if operation == "DeleteObjects" {
return Err(missing_content_md5_error());
}
if method == http::Method::PUT && operation.starts_with("Put") && operation != "PutObject" {
let declared_empty = headers
.get(http::header::CONTENT_LENGTH)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value.trim() == "0");
if !declared_empty {
return Err(missing_content_md5_error());
}
}
Ok(())
}
fn missing_content_md5_error() -> S3Error {
let mut err = S3Error::with_message(
S3ErrorCode::Custom("MissingContentMD5".into()),
"A Content-MD5 header is required for this request.",
);
err.set_status_code(http::StatusCode::BAD_REQUEST);
err
}
/// The bucket-configuration mutation shape on the gateway edge: the shared function the legacy
/// hook calls, with the server context the envelope carries.
///
@@ -148,4 +197,44 @@ mod tests {
assert_eq!(refusal.code(), &rustfs_s3_types::S3ErrorCode::InternalError);
assert_eq!(refusal.message(), Some("the request carries no server context"));
}
#[test]
fn sigv2_body_digest_requirement_enforces_content_md5_on_delete_objects_and_config_puts() {
let empty_headers = HeaderMap::new();
let err = enforce_sigv2_body_digest_requirement(true, &Method::POST, &empty_headers, "DeleteObjects")
.expect_err("SigV2 DeleteObjects without Content-MD5 must fail");
assert_eq!(err.code().as_str(), "MissingContentMD5");
assert_eq!(err.status_code(), Some(http::StatusCode::BAD_REQUEST));
let mut blank_md5 = HeaderMap::new();
blank_md5.insert("content-md5", http::HeaderValue::from_static(" "));
let err = enforce_sigv2_body_digest_requirement(true, &Method::POST, &blank_md5, "DeleteObjects")
.expect_err("blank Content-MD5 must not satisfy SigV2 DeleteObjects");
assert_eq!(err.code().as_str(), "MissingContentMD5");
let mut checksum_only = HeaderMap::new();
checksum_only.insert("x-amz-checksum-sha256", http::HeaderValue::from_static("placeholder"));
let err = enforce_sigv2_body_digest_requirement(true, &Method::POST, &checksum_only, "DeleteObjects")
.expect_err("x-amz-checksum alone must not satisfy SigV2 DeleteObjects");
assert_eq!(err.code().as_str(), "MissingContentMD5");
let mut with_md5 = HeaderMap::new();
with_md5.insert("content-md5", http::HeaderValue::from_static("1B2M2Y8AsgTpgAmY7PhCfg=="));
assert!(enforce_sigv2_body_digest_requirement(true, &Method::POST, &with_md5, "DeleteObjects").is_ok());
let err = enforce_sigv2_body_digest_requirement(true, &Method::PUT, &empty_headers, "PutBucketVersioning")
.expect_err("non-empty SigV2 config PUT without Content-MD5 must fail");
assert_eq!(err.code().as_str(), "MissingContentMD5");
assert_eq!(err.status_code(), Some(http::StatusCode::BAD_REQUEST));
let mut declared_empty = HeaderMap::new();
declared_empty.insert(http::header::CONTENT_LENGTH, http::HeaderValue::from_static("0"));
assert!(enforce_sigv2_body_digest_requirement(true, &Method::PUT, &declared_empty, "PutBucketAcl").is_ok());
assert!(enforce_sigv2_body_digest_requirement(true, &Method::PUT, &with_md5, "PutBucketVersioning").is_ok());
// SigV2 PutObject streaming uploads and SigV4 operations remain unaffected.
assert!(enforce_sigv2_body_digest_requirement(true, &Method::PUT, &empty_headers, "PutObject").is_ok());
assert!(enforce_sigv2_body_digest_requirement(false, &Method::POST, &empty_headers, "DeleteObjects").is_ok());
assert!(enforce_sigv2_body_digest_requirement(false, &Method::PUT, &empty_headers, "PutBucketVersioning").is_ok());
}
}
@@ -70,6 +70,74 @@ pub(crate) fn signed_request_with_headers(
signed_session_request(form, method, path, query, access_key, secret_key, None, headers)
}
/// Signs an `aws-chunked` request using `STREAMING-UNSIGNED-PAYLOAD-TRAILER` and `trailer_name`.
pub(crate) fn signed_streaming_trailer_request(
method: Method,
path: &str,
query: &str,
access_key: &str,
secret_key: &str,
decoded_content_length: u64,
trailer_name: &str,
) -> Request<Empty<Bytes>> {
use hmac::{Hmac, KeyInit as _, Mac as _};
use sha2::{Digest as _, Sha256};
use std::collections::BTreeMap;
const PAYLOAD_TOKEN: &str = "STREAMING-UNSIGNED-PAYLOAD-TRAILER";
let mac = |key: &[u8], data: &str| -> Vec<u8> {
let mut h = Hmac::<Sha256>::new_from_slice(key).expect("HMAC key");
h.update(data.as_bytes());
h.finalize().into_bytes().to_vec()
};
let hex = |bytes: &[u8]| bytes.iter().map(|byte| format!("{byte:02x}")).collect::<String>();
let now = chrono::Utc::now();
let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
let day = now.format("%Y%m%d").to_string();
let scope = format!("{day}/us-east-1/s3/aws4_request");
let mut headers = BTreeMap::new();
headers.insert("content-encoding", "aws-chunked".to_owned());
headers.insert("host", "localhost".to_owned());
headers.insert("x-amz-content-sha256", PAYLOAD_TOKEN.to_owned());
headers.insert("x-amz-date", amz_date.clone());
headers.insert("x-amz-decoded-content-length", decoded_content_length.to_string());
headers.insert("x-amz-trailer", trailer_name.to_owned());
let canonical_headers = headers.iter().map(|(k, v)| format!("{k}:{v}\n")).collect::<String>();
let signed_headers = headers.keys().copied().collect::<Vec<_>>().join(";");
let canonical_request = format!(
"{}\n{path}\n{query}\n{canonical_headers}\n{signed_headers}\n{PAYLOAD_TOKEN}",
method.as_str()
);
let string_to_sign = format!(
"AWS4-HMAC-SHA256\n{amz_date}\n{scope}\n{}",
hex(&Sha256::digest(canonical_request.as_bytes()))
);
let mut key = format!("AWS4{secret_key}").into_bytes();
for part in [day.as_str(), "us-east-1", "s3", "aws4_request"] {
key = mac(&key, part);
}
let signature = hex(&mac(&key, &string_to_sign));
let authorization =
format!("AWS4-HMAC-SHA256 Credential={access_key}/{scope}, SignedHeaders={signed_headers}, Signature={signature}");
let target = if query.is_empty() {
path.to_owned()
} else {
format!("{path}?{query}")
};
let mut builder = Request::builder().method(method).uri(target);
for (name, value) in headers {
builder = builder.header(name, value);
}
builder
.header(http::header::AUTHORIZATION, authorization)
.body(Empty::new())
.expect("signed streaming trailer request")
}
/// As [`signed_request_with_headers`], for a session whose token the signer places where the
/// signature travels: the `X-Amz-Security-Token` header or query parameter.
#[allow(clippy::too_many_arguments)] // A test fixture naming every signing input.
+140 -16
View File
@@ -57,18 +57,18 @@ mod reserved_console;
pub(crate) static CONFIG_HANDLER_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
use crate::app::dto_values::owner;
use crate::runtime_sources::{ServerContextSlot, current_action_credentials};
use crate::runtime_sources::ServerContextSlot;
use crate::server::gateway_handlers::{GatewayBackend, OPERATIONS, OperationTable, metadata_listing, register};
use crate::server::ssec_transport::{carries_ssec_headers, is_secure_transport, report_plaintext_ssec, require_tls};
use crate::shared_types::{NativeTlsTransport, RemoteAddr};
use crate::storage_api::server::http::request_context::RequestContext;
use http::{Extensions, Request, Response};
use rustfs_config::RUSTFS_REGION;
use rustfs_config::{MAX_SINGLE_PUT_OBJECT_SIZE, RUSTFS_REGION};
use rustfs_gateway::{
AssemblyError, Authorizer, BoxFuture, BucketName, BucketOwnerError, BucketOwnerSource, ClientAddr, ConnectionIntent,
DEFAULT_MAX_BUFFERED_BODY_BYTES, HandlerDeadlineClass, HandlerDeadlineConfig, MintedTraces, PlaintextCustomerKeyAck,
DEFAULT_MAX_BUFFERED_BODY_BYTES, HandlerDeadlineClass, HandlerDeadlineConfig, Limits, MintedTraces, PlaintextCustomerKeyAck,
RegionSet, RequestBodyDeadlineConfig, ServiceBuilder, ServiceConfig, SigV4Authenticator, SseConfig, TransportSecurity,
connection_intent_of,
connection_intent_of, max_framed_upload_bytes,
};
#[cfg(test)]
use rustfs_gateway::{Decision, decide_with};
@@ -77,7 +77,6 @@ use rustfs_gateway_adapter::{
RootSource, establish_keystone_identity, host_request_id, keystone_header_token_claim, rustfs_host_resolver,
};
use rustfs_iam::error::Error as IamError;
use rustfs_iam::manager::get_token_signing_key;
use rustfs_iam::store::object::ObjectStore;
use rustfs_iam::sys::IamSys;
use rustfs_policy::auth::UserIdentity;
@@ -179,6 +178,10 @@ impl GatewayStack {
/// [`GatewayAssemblyError`] naming the input the gateway refused. The secret key is never
/// part of it.
pub(crate) fn assemble(assembly: GatewayAssembly) -> Result<Self, GatewayAssemblyError> {
// Ensure S3 operation and ListObjects metric descriptions are registered on S3-only
// servers, not only when optional protocol gateways (FTP/FTPS/WebDAV/SFTP) are enabled.
rustfs_io_metrics::init_s3_metrics();
rustfs_io_metrics::init_list_objects_metrics();
let iam = Arc::new(ServerIam {
server_ctx: Arc::clone(&assembly.server_ctx),
});
@@ -293,6 +296,12 @@ impl GatewayStack {
let credentials = Arc::new(IamCredentials::new(iam, root));
let builder = base
.rustfs_profile()
// Widen the wire-body limit for aws-chunked framing overhead while `service_config`
// enforces the 5 GiB single-request ceiling on the decoded object payload.
.limits(Limits {
max_body_bytes: max_framed_upload_bytes(MAX_SINGLE_PUT_OBJECT_SIZE),
..Limits::default()
})
// Shipped RustFS authorizes before it judges an SSE header; the handler entry answers
// the refusal once authorization succeeds.
.defer_encryption_header_refusals_to_handlers()
@@ -542,6 +551,7 @@ fn service_config(body_read_timeout: Duration, max_buffered_body_bytes: u64) ->
.without_deadline(HandlerDeadlineClass::Extended)
.without_commit_progress_deadline();
ServiceConfig::new(max_buffered_body_bytes)
.with_upload_object_ceiling(MAX_SINGLE_PUT_OBJECT_SIZE)
.with_handler_deadlines(handlers)
.with_request_body_deadlines(body_deadlines(body_read_timeout))
}
@@ -616,19 +626,16 @@ impl RequestIdCarrier for RequestContext {
}
}
/// The root credentials of one server as they are now, read on every call from where the legacy
/// stack reads them, so a root change reaches both stacks at once. `None` while they are not
/// initialized or cannot verify a signature, which the adapters answer as unavailable.
/// The root credentials of one server as they are now, read strictly from this server's installed
/// `AppContext` (never falling back to process-global credentials or token-signing keys). `None`
/// while this server context is uninstalled, lacks root credentials, or cannot verify a signature,
/// which the adapters answer as unavailable.
fn live_root(server_ctx: Arc<ServerContextSlot>) -> impl Fn() -> Option<Arc<RootCredentials>> + Send + Sync + 'static {
move || {
let root = match server_ctx.app_context() {
Some(context) => context.action_credentials().get(),
None => current_action_credentials(),
}?;
// IAM signs STS session tokens with its token-signing key, which is the root secret
// until IAM has published one of its own.
let signing_key = get_token_signing_key().unwrap_or_else(|| root.secret_key.clone());
RootCredentials::new(&root.access_key, &root.secret_key, &signing_key)
let root = server_ctx.installed_app_context()?.action_credentials().get()?;
// Match `check_claims_from_token_with_context`: STS session tokens are signed with this
// server context's root secret rather than a process-global key.
RootCredentials::new(&root.access_key, &root.secret_key, &root.secret_key)
.ok()
.map(Arc::new)
}
@@ -855,6 +862,123 @@ mod object_lock_tests {
assert_eq!(retention.days, Some(30));
assert_eq!(retention.years, None);
}
#[tokio::test]
#[serial_test::serial]
async fn sigv2_delete_objects_and_config_puts_enforce_content_md5_post_auth() {
let ambient = crate::app::gating_test_env::shared_gating_ambient().await;
let store = crate::app::gating_test_env::shared_gating_ecstore().await;
let context = Arc::new(crate::runtime_sources::AppContext::new(Arc::clone(&store), ambient.iam(), ambient.kms()));
let slot = ServerContextSlot::new();
assert!(slot.install(Arc::clone(&context)));
let gateway = TestGateway::over(&context, slot);
let bucket = format!("sigv2-digest-{}", Uuid::new_v4());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create sigv2 digest test bucket");
let delete_xml = "<Delete><Object><Key>missing-key</Key></Object></Delete>";
let sign_v2 = |method: Method, uri: String, body: &str, with_md5: bool, secret: &str| {
let mut builder = http::Request::builder()
.method(method)
.uri(uri)
.header(http::header::HOST, "localhost")
.header("date", chrono::Utc::now().format("%a, %d %b %Y %H:%M:%S GMT").to_string())
.header(http::header::CONTENT_TYPE, "application/xml")
.header(http::header::CONTENT_LENGTH, body.len());
if with_md5 {
let md5 = base64_simd::STANDARD.encode_to_string(md5::Md5::digest(body.as_bytes()));
builder = builder.header("content-md5", md5);
}
let req = builder
.body(rustfs_gateway::Body::from_bytes(Bytes::copy_from_slice(body.as_bytes())))
.expect("build sigv2 request");
rustfs_signer::try_sign_v2(req, body.len() as i64, TestGateway::ACCESS_KEY, secret, false)
.expect("sign sigv2 request")
};
// Missing Content-MD5 on valid SigV2 DeleteObjects -> 400 MissingContentMD5 post-auth.
let missing = gateway
.call(sign_v2(
Method::POST,
format!("http://localhost/{bucket}?delete"),
delete_xml,
false,
TestGateway::SECRET_KEY,
))
.await;
assert_eq!(missing.status(), StatusCode::BAD_REQUEST);
let missing_body = missing.into_body().collect().await.unwrap().to_bytes();
assert!(
String::from_utf8_lossy(&missing_body).contains("<Code>MissingContentMD5</Code>"),
"{}",
String::from_utf8_lossy(&missing_body)
);
// Wrong secret fails auth (403) rather than MissingContentMD5 (400).
let wrong_secret = gateway
.call(sign_v2(
Method::POST,
format!("http://localhost/{bucket}?delete"),
delete_xml,
false,
"wrong-sigv2-secret-key",
))
.await;
assert_eq!(wrong_secret.status(), StatusCode::FORBIDDEN);
// Valid SigV2 DeleteObjects with matching Content-MD5 -> 200 OK.
let ok = gateway
.call(sign_v2(
Method::POST,
format!("http://localhost/{bucket}?delete"),
delete_xml,
true,
TestGateway::SECRET_KEY,
))
.await;
let ok_status = ok.status();
let ok_body = ok.into_body().collect().await.unwrap().to_bytes();
assert_eq!(ok_status, StatusCode::OK, "{}", String::from_utf8_lossy(&ok_body));
// Tampered body after signing valid Content-MD5 -> 400 BadDigest.
let mut tampered = sign_v2(
Method::POST,
format!("http://localhost/{bucket}?delete"),
delete_xml,
true,
TestGateway::SECRET_KEY,
);
*tampered.body_mut() = rustfs_gateway::Body::from_bytes(Bytes::from(delete_xml.replace("missing-key", "other-key")));
let tampered_resp = gateway.call(tampered).await;
assert_eq!(tampered_resp.status(), StatusCode::BAD_REQUEST);
let tampered_body = tampered_resp.into_body().collect().await.unwrap().to_bytes();
assert!(
String::from_utf8_lossy(&tampered_body).contains("<Code>BadDigest</Code>"),
"{}",
String::from_utf8_lossy(&tampered_body)
);
// Non-empty SigV2 bucket config PUT without Content-MD5 -> 400 MissingContentMD5.
let versioning_xml = "<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>";
let cfg_missing = gateway
.call(sign_v2(
Method::PUT,
format!("http://localhost/{bucket}?versioning"),
versioning_xml,
false,
TestGateway::SECRET_KEY,
))
.await;
assert_eq!(cfg_missing.status(), StatusCode::BAD_REQUEST);
let cfg_body = cfg_missing.into_body().collect().await.unwrap().to_bytes();
assert!(
String::from_utf8_lossy(&cfg_body).contains("<Code>MissingContentMD5</Code>"),
"{}",
String::from_utf8_lossy(&cfg_body)
);
}
}
#[cfg(test)]
+11 -3
View File
@@ -31,7 +31,9 @@ use crate::runtime_sources::ServerContextSlot;
use crate::server::gateway_handlers::{handler_error, verified_signature};
use crate::storage_api::server::http::access::ReqInfo;
use http_body_util::BodyExt as _;
use rustfs_gateway::{Decision, Handler, HandlerResult, Operation, Req, RequestContextView, Resp, decide_with};
use rustfs_gateway::{
Decision, Handler, HandlerResult, Operation, Req, RequestContextView, Resp, SigV4Authenticator, decide_with,
};
use rustfs_gateway_adapter::{IamKeyLookup, RootSource};
use rustfs_gateway_core::dialect::{ClaimedRoute, Dialect, DialectBuilder, DialectOverlay, OverlayRow};
use rustfs_gateway_dialect_rustfs_admin::ops::{
@@ -41,7 +43,9 @@ use rustfs_gateway_dialect_rustfs_admin::ops::{
get_v4_extensions_catalog::GetV4ExtensionsCatalog, get_v4_plugins_catalog::GetV4PluginsCatalog,
get_v4_runtime_capabilities::GetV4RuntimeCapabilities,
};
use rustfs_gateway_dialect_rustfs_admin::{AdminOperation, AdminResponse as WireResponse, CLAIMS, OVERLAY};
use rustfs_gateway_dialect_rustfs_admin::{
AdminOperation, AdminResponse as WireResponse, CLAIMS, OVERLAY, TABLE_CATALOG_PREFIXES,
};
use rustfs_s3_types::{Body, S3Result, s3_error};
use std::sync::{Arc, OnceLock};
@@ -86,6 +90,10 @@ pub(super) fn dialect() -> Result<Dialect, GatewayAssemblyError> {
.map_err(GatewayAssemblyError::AdminDialect)
}
pub(super) fn configure_authenticator(authenticator: SigV4Authenticator) -> SigV4Authenticator {
authenticator.verify_paths_double_encoded_under(TABLE_CATALOG_PREFIXES)
}
pub(super) fn assemble(
assembly: GatewayAssembly,
iam: Arc<dyn IamKeyLookup>,
@@ -98,7 +106,7 @@ pub(super) fn assemble(
Decision::Deny
}
});
let builder = GatewayStack::configured_builder(&assembly, iam, root, gate, std::convert::identity)?;
let builder = GatewayStack::configured_builder(&assembly, iam, root, gate, configure_authenticator)?;
let service = builder
.dialect(&dialect()?)
.register::<GetIcebergConfig, _>(Arc::new(AdminBridge {
+101 -2
View File
@@ -19,7 +19,7 @@ use super::*;
use crate::admin::operation::AdminResponse;
use crate::server::gateway_handlers::handler_error;
use crate::server::gateway_handlers::test_support::{CLIENT, PEER, REQUEST_ID, Signed, request_context, signed_request};
use crate::server::gateway_stack::admin::{assemble, complete_response, dialect, envelope};
use crate::server::gateway_stack::admin::{assemble, complete_response, configure_authenticator, dialect, envelope};
use crate::server::stack::claims_native_admin_read;
use crate::shared_types::RemoteAddr;
use crate::storage_api::server::http::access::ReqInfo;
@@ -129,7 +129,7 @@ fn capturing_stack(captured: &Arc<Mutex<Vec<serde_json::Value>>>) -> GatewayStac
Arc::new(ScriptedIam { ready: true }),
root().source(),
decide_with(|_| Decision::Allow),
std::convert::identity,
configure_authenticator,
)
.unwrap();
GatewayStack {
@@ -279,3 +279,102 @@ async fn native_admin_refuses_an_unsigned_amz_header_before_any_handler() {
}
assert_eq!(captured.lock().unwrap().len(), 1, "a refused request reached a handler");
}
#[tokio::test]
async fn native_admin_verifies_double_encoded_paths_under_table_catalog_prefixes() {
use rustfs_gateway_dialect_rustfs_admin::ops::get_iceberg_by_warehouse_namespaces_by_namespace_tables_by_table::GetIcebergByWarehouseNamespacesByNamespaceTablesByTable as LoadTable;
use rustfs_gateway_dialect_rustfs_admin::rustfs_admin_dialect;
struct NamespaceCapture(Arc<Mutex<Vec<String>>>);
impl Handler<LoadTable> for NamespaceCapture {
async fn call(&self, request: Req<LoadTable>) -> HandlerResult<LoadTable> {
let namespace = request
.context()
.path_params()
.iter()
.find_map(|(name, value)| (name == "namespace").then(|| value.to_owned()))
.unwrap_or_default();
self.0.lock().unwrap().push(namespace);
Ok(Resp::new(WireResponse::json("{}")))
}
}
let build_stack = |captured: Arc<Mutex<Vec<String>>>, with_admin_auth: bool| {
let customizer: fn(rustfs_gateway::SigV4Authenticator) -> rustfs_gateway::SigV4Authenticator = if with_admin_auth {
configure_authenticator
} else {
std::convert::identity
};
let builder = GatewayStack::configured_builder(
&assembly(),
Arc::new(ScriptedIam { ready: true }),
root().source(),
decide_with(|_| Decision::Allow),
customizer,
)
.unwrap();
GatewayStack {
keystone_auth: None,
control_plane: false,
object_lambda_fallback: None,
service: builder
.dialect(&rustfs_admin_dialect().unwrap())
.register::<LoadTable, _>(Arc::new(NamespaceCapture(captured)))
.build()
.unwrap(),
}
};
let captured = Arc::new(Mutex::new(Vec::new()));
let configured = build_stack(Arc::clone(&captured), true);
let unconfigured = build_stack(Arc::clone(&captured), false);
// Botocore's generic SigV4 signer double-encodes percent-encoded segments under `/iceberg/v1`
// and `/_iceberg/v1`: a wire path containing `ods%1Fkfk_log_order` is signed over
// `ods%251Fkfk_log_order`. `admin::configure_authenticator` must accept the double-encoded
// signature and reject the single-encoded S3 spelling; without it, double-encoded fails auth.
for prefix in ["/iceberg/v1", "/_iceberg/v1"] {
let wire_path = format!("{prefix}/warehouse/namespaces/ods%1Fkfk_log_order/tables/files");
let double_encoded_path = format!("{prefix}/warehouse/namespaces/ods%251Fkfk_log_order/tables/files");
let wire_uri: http::Uri = wire_path.parse().expect("valid wire URI");
let mut double_signed =
signed_request(Signed::Header, Method::GET, &double_encoded_path, "", ROOT_ACCESS_KEY, ROOT_SECRET_KEY);
*double_signed.uri_mut() = wire_uri.clone();
let response = configured.call(double_signed).await;
let status = response.status();
let body = response.into_body().collect().await.unwrap().to_bytes();
assert_eq!(status, StatusCode::OK, "{prefix}: {}", String::from_utf8_lossy(&body));
let single_signed = signed_request(Signed::Header, Method::GET, &wire_path, "", ROOT_ACCESS_KEY, ROOT_SECRET_KEY);
let rejected = configured.call(single_signed).await;
let rejected_status = rejected.status();
let rejected_body = rejected.into_body().collect().await.unwrap().to_bytes();
assert_eq!(
rejected_status,
StatusCode::FORBIDDEN,
"{prefix}: {}",
String::from_utf8_lossy(&rejected_body)
);
assert!(
String::from_utf8_lossy(&rejected_body).contains("<Code>SignatureDoesNotMatch</Code>"),
"{prefix}: {}",
String::from_utf8_lossy(&rejected_body)
);
let mut without_switch =
signed_request(Signed::Header, Method::GET, &double_encoded_path, "", ROOT_ACCESS_KEY, ROOT_SECRET_KEY);
*without_switch.uri_mut() = wire_uri;
let unconfigured_resp = unconfigured.call(without_switch).await;
assert_eq!(
unconfigured_resp.status(),
StatusCode::FORBIDDEN,
"{prefix}: control must fail without switch"
);
}
assert_eq!(
*captured.lock().unwrap(),
vec!["ods\u{1f}kfk_log_order".to_owned(), "ods\u{1f}kfk_log_order".to_owned()]
);
}
+543
View File
@@ -309,6 +309,7 @@ fn no_handler_runs_under_a_total_deadline_and_the_body_keeps_the_rustfs_idle_bou
assert_eq!(config.request_body_deadlines().read_idle(), Duration::from_secs(300));
assert_eq!(config.request_body_deadlines().first_byte(), Duration::from_secs(300));
assert_eq!(config.request_body_deadlines().throughput_window(), NO_DEADLINE);
assert_eq!(config.upload_object_ceiling(), Some(MAX_SINGLE_PUT_OBJECT_SIZE));
}
#[test]
@@ -608,3 +609,545 @@ async fn the_reported_owner_is_every_bucket_s_owner_and_without_one_nothing_is()
);
assert_eq!(ReportedOwner(None).owner(&photos).await, Err(BucketOwnerError::unavailable()));
}
struct CountingStalledBody {
polled: Arc<std::sync::atomic::AtomicUsize>,
dropped: Arc<std::sync::atomic::AtomicBool>,
}
impl Drop for CountingStalledBody {
fn drop(&mut self) {
self.dropped.store(true, std::sync::atomic::Ordering::SeqCst);
}
}
impl http_body::Body for CountingStalledBody {
type Data = Bytes;
type Error = std::convert::Infallible;
fn poll_frame(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
self.polled.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
std::task::Poll::Pending
}
}
struct TableIam {
users: std::collections::HashMap<String, (UserIdentity, bool)>,
}
impl IamKeyLookup for TableIam {
fn is_ready(&self) -> bool {
true
}
fn check_key<'a>(&'a self, access_key: &'a str) -> BoxFuture<'a, Result<(Option<UserIdentity>, bool), IamError>> {
let answer = self
.users
.get(access_key)
.cloned()
.map_or((None, false), |(id, ok)| (Some(id), ok));
Box::pin(async move { Ok(answer) })
}
}
#[tokio::test]
async fn expired_sts_returns_400_expired_token_only_to_holder_and_keeps_disabled_403() {
use crate::server::gateway_handlers::test_support::signed_request_with_headers;
use rustfs_credentials::Credentials as IamCredential;
const EXPIRED_STS_AK: &str = "AKIAEXPIREDSTS01";
const EXPIRED_STS_SK: &str = "expired-sts-secret-key-01";
const EXPIRED_STS_TOKEN: &str = "expired-sts-session-token-01";
const DISABLED_STS_AK: &str = "AKIADISABLEDSTS1";
const DISABLED_STS_SK: &str = "disabled-sts-secret-key-01";
const DISABLED_STS_TOKEN: &str = "disabled-sts-session-token-01";
const EXPIRED_SA_AK: &str = "AKIAEXPIREDSA001";
const EXPIRED_SA_SK: &str = "expired-sa-secret-key-01";
let past = time::OffsetDateTime::now_utc() - time::Duration::hours(1);
let mut users = std::collections::HashMap::new();
users.insert(
EXPIRED_STS_AK.to_owned(),
(
UserIdentity::new(IamCredential {
access_key: EXPIRED_STS_AK.to_owned(),
secret_key: EXPIRED_STS_SK.to_owned(),
session_token: EXPIRED_STS_TOKEN.to_owned(),
parent_user: "parent".to_owned(),
status: "on".to_owned(),
expiration: Some(past),
..Default::default()
}),
false,
),
);
users.insert(
DISABLED_STS_AK.to_owned(),
(
UserIdentity::new(IamCredential {
access_key: DISABLED_STS_AK.to_owned(),
secret_key: DISABLED_STS_SK.to_owned(),
session_token: DISABLED_STS_TOKEN.to_owned(),
parent_user: "parent".to_owned(),
status: "off".to_owned(),
expiration: Some(past),
..Default::default()
}),
false,
),
);
users.insert(
EXPIRED_SA_AK.to_owned(),
(
UserIdentity::new(IamCredential {
access_key: EXPIRED_SA_AK.to_owned(),
secret_key: EXPIRED_SA_SK.to_owned(),
session_token: "sa-internal-claims-token".to_owned(),
parent_user: "parent".to_owned(),
status: "on".to_owned(),
expiration: Some(past),
claims: Some([(rustfs_credentials::IAM_POLICY_CLAIM_NAME_SA.to_owned(), "inherited-policy".into())].into()),
..Default::default()
}),
false,
),
);
let assembly = assembly();
let server_ctx = Arc::clone(&assembly.server_ctx);
let stack = GatewayStack::assemble_with(
assembly,
Arc::new(TableIam { users }),
root().source(),
early_gate(OPERATIONS, server_ctx),
)
.expect("stack assembles");
let sign_with_token = |ak: &str, sk: &str, token: Option<&str>| {
let mut headers = HeaderMap::new();
if let Some(token) = token {
headers.insert("x-amz-security-token", token.parse().expect("token header"));
}
signed_request_with_headers(Signed::Header, Method::GET, "/", "", ak, sk, headers)
};
// Holder proves possession with matching secret and token -> 400 ExpiredToken.
let (status, _, body) =
answer_request(&stack, sign_with_token(EXPIRED_STS_AK, EXPIRED_STS_SK, Some(EXPIRED_STS_TOKEN))).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
assert!(body.contains("<Code>ExpiredToken</Code>"), "{body}");
assert!(!body.contains("InvalidAccessKeyId"), "{body}");
// Wrong secret, wrong token, or missing token must never leak ExpiredToken -> 403.
for (label, req) in [
(
"wrong secret",
sign_with_token(EXPIRED_STS_AK, "wrong-secret-key-01", Some(EXPIRED_STS_TOKEN)),
),
("wrong token", sign_with_token(EXPIRED_STS_AK, EXPIRED_STS_SK, Some("other-token"))),
("missing token", sign_with_token(EXPIRED_STS_AK, EXPIRED_STS_SK, None)),
] {
let (status, _, body) = answer_request(&stack, req).await;
assert_eq!(status, StatusCode::FORBIDDEN, "{label}: {body}");
assert!(!body.contains("ExpiredToken"), "{label}: {body}");
}
// Disabled STS and expired service account stay disabled -> 403 InvalidAccessKeyId.
for (label, req) in [
(
"disabled expired STS",
sign_with_token(DISABLED_STS_AK, DISABLED_STS_SK, Some(DISABLED_STS_TOKEN)),
),
("expired service account", sign_with_token(EXPIRED_SA_AK, EXPIRED_SA_SK, None)),
] {
let (status, _, body) = answer_request(&stack, req).await;
assert_eq!(status, StatusCode::FORBIDDEN, "{label}: {body}");
assert!(body.contains("<Code>InvalidAccessKeyId</Code>"), "{label}: {body}");
}
}
#[tokio::test]
async fn delete_objects_fails_auth_before_body_read_and_verifies_digests_post_auth() {
use crate::server::gateway_handlers::test_support::{signed_request_with_headers, signed_streaming_trailer_request};
use md5::Digest as _;
use rustfs_gateway::{Handler, HandlerResult, Req, Resp, dto};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
const DELETE_XML: &str = "<Delete><Object><Key>safe-object</Key></Object></Delete>";
struct DeleteProbe(Arc<AtomicUsize>);
impl Handler<dto::DeleteObjects> for DeleteProbe {
async fn call(&self, request: Req<dto::DeleteObjects>) -> HandlerResult<dto::DeleteObjects> {
let keys: Vec<_> = request
.resources()
.resolve_objects(request.read_proof())
.expect("DeleteObjects resources")
.map(|object| object.key.as_str())
.collect();
assert_eq!(keys, ["safe-object"]);
self.0.fetch_add(1, Ordering::SeqCst);
Ok(Resp::new(dto::DeleteObjectsOutput::default()))
}
}
let calls = Arc::new(AtomicUsize::new(0));
let assembly = assembly();
let builder = GatewayStack::configured_builder(
&assembly,
Arc::new(ScriptedIam { ready: true }),
root().source(),
decide_with(|_| Decision::Allow),
std::convert::identity,
)
.expect("configured builder");
let stack = GatewayStack {
service: builder
.register::<dto::DeleteObjects, _>(Arc::new(DeleteProbe(Arc::clone(&calls))))
.build()
.expect("delete probe stack"),
keystone_auth: None,
control_plane: false,
object_lambda_fallback: None,
};
// 1. Unauthenticated / wrongly-signed POST /bucket?delete fails auth before polling a byte.
let polled = Arc::new(AtomicUsize::new(0));
let dropped = Arc::new(AtomicBool::new(false));
let bad_auth_req = signed_with_a_wrong_signature(request(Method::POST, "/bucket?delete"), ROOT_ACCESS_KEY)
.header(http::header::CONTENT_LENGTH, 20 * 1024 * 1024)
.header("content-md5", "not-valid-base64")
.body(CountingStalledBody {
polled: Arc::clone(&polled),
dropped: Arc::clone(&dropped),
})
.expect("bad auth delete request");
let response = stack.call(bad_auth_req).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(polled.load(Ordering::SeqCst), 0, "auth refusal must not read body bytes");
assert!(dropped.load(Ordering::SeqCst), "unread body must be released on auth refusal");
assert_eq!(calls.load(Ordering::SeqCst), 0);
// 2. Signed aws-chunked + x-amz-trailer DeleteObjects reaches gateway post-auth trailer
// verification (no pre-auth MissingContentMD5 from ControlBodyDigestService). A tampered
// trailer is rejected post-auth with 400 BadDigest; a valid trailer passes trailer checking
// and currently hits gateway's rustfs_profile() refuse_unsized_buffered_bodies_as_legacy_rustfs
// gate (400 IncompleteBody) until gateway drops that switch from rustfs_profile().
let crc32 = rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::CRC32, DELETE_XML.as_bytes())
.expect("crc32 checksum")
.encoded;
let chunked_request = |trailer_value: &str| {
let wire = format!(
"{:x}\r\n{DELETE_XML}\r\n0\r\nx-amz-checksum-crc32:{trailer_value}\r\n\r\n",
DELETE_XML.len()
);
let signed = signed_streaming_trailer_request(
Method::POST,
"/bucket",
"delete=",
ROOT_ACCESS_KEY,
ROOT_SECRET_KEY,
DELETE_XML.len() as u64,
"x-amz-checksum-crc32",
);
let wire_bytes = Bytes::from(wire);
let mut req = signed.map(|_| http_body_util::Full::new(wire_bytes.clone()));
req.headers_mut()
.insert(http::header::CONTENT_LENGTH, http::HeaderValue::from(wire_bytes.len()));
req
};
let tampered = stack.call(chunked_request("AAAAAA==")).await;
let tampered_status = tampered.status();
let tampered_body = tampered.into_body().collect().await.unwrap().to_bytes();
assert_eq!(tampered_status, StatusCode::BAD_REQUEST);
assert!(
String::from_utf8_lossy(&tampered_body).contains("<Code>BadDigest</Code>"),
"{}",
String::from_utf8_lossy(&tampered_body)
);
assert_eq!(calls.load(Ordering::SeqCst), 0);
let valid_chunked = stack.call(chunked_request(&crc32)).await;
let valid_chunked_status = valid_chunked.status();
let valid_chunked_body = valid_chunked.into_body().collect().await.unwrap().to_bytes();
let valid_chunked_text = String::from_utf8_lossy(&valid_chunked_body);
assert!(
!valid_chunked_text.contains("<Code>MissingContentMD5</Code>"),
"pre-auth ControlBodyDigestService must not reject trailer DeleteObjects: {valid_chunked_text}"
);
assert!(
valid_chunked_status == StatusCode::OK
|| (valid_chunked_status == StatusCode::BAD_REQUEST && valid_chunked_text.contains("<Code>IncompleteBody</Code>")),
"{valid_chunked_status}: {valid_chunked_text}"
);
let baseline_calls = calls.load(Ordering::SeqCst);
// 3. Supplied Content-MD5, head x-amz-checksum-*, and SigV4 without MD5/checksum are all
// verified post-auth by gateway.
let good_md5 = base64_simd::STANDARD.encode_to_string(md5::Md5::digest(DELETE_XML.as_bytes()));
for (header_pair, payload, expected_status, expected_code) in [
(Some(("content-md5", good_md5.as_str())), DELETE_XML, StatusCode::OK, None),
(
Some(("content-md5", good_md5.as_str())),
"<Delete><Object><Key>evil-object</Key></Object></Delete>",
StatusCode::BAD_REQUEST,
Some("BadDigest"),
),
(
Some(("content-md5", "invalid-md5")),
DELETE_XML,
StatusCode::BAD_REQUEST,
Some("InvalidDigest"),
),
(Some(("x-amz-checksum-crc32", crc32.as_str())), DELETE_XML, StatusCode::OK, None),
(
Some(("x-amz-checksum-crc32", "AAAAAA==")),
DELETE_XML,
StatusCode::BAD_REQUEST,
Some("BadDigest"),
),
(None, DELETE_XML, StatusCode::OK, None),
] {
let mut headers = HeaderMap::new();
if let Some((name, value)) = header_pair {
headers.insert(name, value.parse().unwrap());
}
let signed = signed_request_with_headers(
Signed::Header,
Method::POST,
"/bucket",
"delete=",
ROOT_ACCESS_KEY,
ROOT_SECRET_KEY,
headers,
);
let payload_bytes = Bytes::from_static(payload.as_bytes());
let mut req = signed.map(|_| http_body_util::Full::new(payload_bytes.clone()));
req.headers_mut()
.insert(http::header::CONTENT_LENGTH, http::HeaderValue::from(payload_bytes.len()));
let resp = stack.call(req).await;
let status = resp.status();
let body = resp.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8_lossy(&body);
assert_eq!(status, expected_status, "{header_pair:?}: {text}");
if let Some(code) = expected_code {
assert!(text.contains(&format!("<Code>{code}</Code>")), "{header_pair:?}: {text}");
}
}
assert_eq!(calls.load(Ordering::SeqCst), baseline_calls + 3);
}
#[tokio::test]
#[serial_test::serial]
async fn live_root_reads_strictly_from_server_context_and_ignores_global_signing_key() {
// Seed a weak process-global secret if not yet set in this process (in nextest each test runs
// in its own process, so `get_token_signing_key()` observes `"weak"`, which previously caused
// `RootCredentials::new` to fail with `WeakSigningKey` and return `None`).
let _ = rustfs_credentials::init_global_action_credentials(Some("global-weak-root".to_owned()), Some("weak".to_owned()));
// An uninstalled ServerContextSlot must never fall back to global action credentials.
let uninstalled = ServerContextSlot::new();
assert!(
live_root(uninstalled)().is_none(),
"uninstalled ServerContextSlot must not fall back to process-global action credentials"
);
let store = crate::app::gating_test_env::shared_gating_ecstore().await;
if crate::runtime_sources::current_app_context().is_none() {
crate::runtime_sources::install_test_app_context(Arc::clone(&store)).await;
}
let ambient = crate::runtime_sources::current_app_context().expect("ambient context");
let context = Arc::new(crate::runtime_sources::AppContext::new(Arc::clone(&store), ambient.iam(), ambient.kms()));
const SLOT_AK: &str = "slotisolatedroot";
const SLOT_SK: &str = "slot-isolated-root-secret";
assert!(context.publish_action_credentials(rustfs_credentials::Credentials {
access_key: SLOT_AK.to_owned(),
secret_key: SLOT_SK.to_owned(),
status: "on".to_owned(),
..Default::default()
}));
let slot = ServerContextSlot::new();
assert!(slot.install(context));
let root = live_root(Arc::clone(&slot))()
.expect("live_root must stay healthy despite a weak or unrelated process-global signing key");
assert_eq!(root.access_key(), SLOT_AK);
// End-to-end check: a GatewayStack assembled with `live_root(slot)` verifies the slot's root
// secret (returning SignatureDoesNotMatch rather than 500 InternalError or InvalidAccessKeyId).
let assembly = GatewayAssembly {
server_ctx: Arc::clone(&slot),
root_access_key: SLOT_AK.to_owned(),
root_secret_key: SLOT_SK.to_owned(),
..assembly()
};
let stack = GatewayStack::assemble(assembly).expect("stack assembles");
let (status, _, body) = answer(&stack, signed_with_a_wrong_signature(request(Method::GET, "/"), SLOT_AK)).await;
assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
assert!(body.contains("<Code>SignatureDoesNotMatch</Code>"), "{body}");
}
#[tokio::test]
async fn upload_ceilings_admit_5_gib_framed_upload_and_refuse_above_5_gib_before_body_read() {
use crate::server::gateway_handlers::test_support::signed_streaming_trailer_request;
use rustfs_gateway::{Handler, HandlerError, HandlerResult, Req, dto};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
struct PutProbe(Arc<AtomicUsize>);
impl Handler<dto::PutObject> for PutProbe {
async fn call(&self, _request: Req<dto::PutObject>) -> HandlerResult<dto::PutObject> {
self.0.fetch_add(1, Ordering::SeqCst);
// Return an explicit sentinel error so the test verifies handler admission for a 5 GiB
// declared upload without materializing 5 GiB of body bytes for BodyMonitor completion.
Err(HandlerError::not_implemented("admitted-5gib-probe"))
}
}
let calls = Arc::new(AtomicUsize::new(0));
let assembly = assembly();
let builder = GatewayStack::configured_builder(
&assembly,
Arc::new(ScriptedIam { ready: true }),
root().source(),
decide_with(|_| Decision::Allow),
std::convert::identity,
)
.expect("configured builder");
let stack = GatewayStack {
service: builder
.register::<dto::PutObject, _>(Arc::new(PutProbe(Arc::clone(&calls))))
.build()
.expect("put probe stack"),
keystone_auth: None,
control_plane: false,
object_lambda_fallback: None,
};
let wire_limit = max_framed_upload_bytes(MAX_SINGLE_PUT_OBJECT_SIZE);
assert_eq!(
stack.service.limits().max_body_bytes,
wire_limit,
"wire limit must accommodate aws-chunked framing for a 5 GiB object"
);
assert!(stack.service.limits().max_body_bytes > MAX_SINGLE_PUT_OBJECT_SIZE);
// 1. A 5 GiB + 1 byte decoded upload is refused with 400 EntityTooLarge before body read.
let polled = Arc::new(AtomicUsize::new(0));
let dropped = Arc::new(AtomicBool::new(false));
let mut oversized = signed_streaming_trailer_request(
Method::PUT,
"/bucket/oversized",
"",
ROOT_ACCESS_KEY,
ROOT_SECRET_KEY,
MAX_SINGLE_PUT_OBJECT_SIZE + 1,
"x-amz-checksum-crc32",
)
.map(|_| CountingStalledBody {
polled: Arc::clone(&polled),
dropped: Arc::clone(&dropped),
});
oversized.headers_mut().insert(
http::header::CONTENT_LENGTH,
(MAX_SINGLE_PUT_OBJECT_SIZE + 128).to_string().parse().unwrap(),
);
let resp = stack.call(oversized).await;
let status = resp.status();
let body = resp.into_body().collect().await.unwrap().to_bytes();
assert_eq!(status, StatusCode::BAD_REQUEST, "{}", String::from_utf8_lossy(&body));
assert!(
String::from_utf8_lossy(&body).contains("<Code>EntityTooLarge</Code>"),
"{}",
String::from_utf8_lossy(&body)
);
assert_eq!(polled.load(Ordering::SeqCst), 0, "oversized upload must fail before reading body");
assert!(dropped.load(Ordering::SeqCst));
assert_eq!(calls.load(Ordering::SeqCst), 0);
// 2. A wire Content-Length above `max_framed_upload_bytes(5 GiB)` is refused before body read.
let wire_polled = Arc::new(AtomicUsize::new(0));
let wire_dropped = Arc::new(AtomicBool::new(false));
let mut over_wire = signed_streaming_trailer_request(
Method::PUT,
"/bucket/over-wire",
"",
ROOT_ACCESS_KEY,
ROOT_SECRET_KEY,
MAX_SINGLE_PUT_OBJECT_SIZE,
"x-amz-checksum-crc32",
)
.map(|_| CountingStalledBody {
polled: Arc::clone(&wire_polled),
dropped: Arc::clone(&wire_dropped),
});
over_wire
.headers_mut()
.insert(http::header::CONTENT_LENGTH, (wire_limit + 1).to_string().parse().unwrap());
let resp = stack.call(over_wire).await;
let status = resp.status();
let body = resp.into_body().collect().await.unwrap().to_bytes();
assert!(
matches!(status, StatusCode::BAD_REQUEST | StatusCode::PAYLOAD_TOO_LARGE),
"{status}: {}",
String::from_utf8_lossy(&body)
);
assert_eq!(wire_polled.load(Ordering::SeqCst), 0, "over-wire upload must fail before reading body");
assert!(wire_dropped.load(Ordering::SeqCst));
assert_eq!(calls.load(Ordering::SeqCst), 0);
// 3. A 5 GiB decoded aws-chunked upload whose framed wire Content-Length exceeds 5 GiB passes
// both the wire limit and object ceiling gates and reaches the handler.
let mut framed_5gib = signed_streaming_trailer_request(
Method::PUT,
"/bucket/five-gib",
"",
ROOT_ACCESS_KEY,
ROOT_SECRET_KEY,
MAX_SINGLE_PUT_OBJECT_SIZE,
"x-amz-checksum-crc32",
);
framed_5gib.headers_mut().insert(
http::header::CONTENT_LENGTH,
(MAX_SINGLE_PUT_OBJECT_SIZE + 65_536).to_string().parse().unwrap(),
);
let resp = stack.call(framed_5gib).await;
let status = resp.status();
let body = resp.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8_lossy(&body);
assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{text}");
assert!(text.contains("admitted-5gib-probe"), "{text}");
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
#[test]
fn assemble_initializes_s3_and_list_objects_metrics() {
const S3_OPS_METRIC: &str = "rustfs_s3_operations_total";
const LIST_OBJECTS_GATHER_TOTAL: &str = "rustfs_s3_list_objects_gather_total";
let recorder = metrics_util::debugging::DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
let _stack = GatewayStack::assemble(assembly()).expect("stack assembles");
rustfs_io_metrics::record_s3_op(rustfs_s3_ops::S3Operation::ListBuckets);
metrics::counter!(LIST_OBJECTS_GATHER_TOTAL).increment(1);
});
let entries = snapshotter.snapshot().into_vec();
let description_for = |name: &str| {
entries
.iter()
.find(|(key, _, _, _)| key.key().name() == name)
.and_then(|(_, _, desc, _)| desc.as_deref())
.map(str::to_owned)
};
assert!(
description_for(S3_OPS_METRIC).is_some(),
"GatewayStack::assemble must initialize S3 operation metrics"
);
assert!(
description_for(LIST_OBJECTS_GATHER_TOTAL).is_some(),
"GatewayStack::assemble must initialize ListObjects metrics"
);
}
+123 -943
View File
File diff suppressed because it is too large Load Diff
@@ -704,12 +704,12 @@ async fn the_console_listener_isolates_its_routes_in_front_of_the_control_plane_
let reached = Arc::new(AtomicUsize::new(0));
let counted = {
let reached = Arc::clone(&reached);
tower::service_fn(move |request: HttpRequest<ControlRequestBody>| {
tower::service_fn(move |request: HttpRequest<Full<Bytes>>| {
reached.fetch_add(1, Ordering::SeqCst);
edge.clone().oneshot(request)
})
};
let console = ControlBodyDigestService::new(counted, Duration::from_secs(1)).with_console_listener(true);
let console = ConsoleListenerRouteService::new(counted, true);
let to_full = |request: HttpRequest<Empty<Bytes>>| request.map(|_| Full::new(Bytes::new()));
let signed = |path: &str, query: &str| to_full(signed_as(Method::GET, path, query, ROOT, ROOT_SECRET, Signed::Header));
for (label, request) in [
@@ -198,13 +198,11 @@ impl PostObjectFormPolicy {
}
pub(crate) fn install_gateway<R: AuthorizationRequest + ?Sized>(mut self, req: &mut R) {
// Execution (`app/object/put.rs`) rejects any wire `x-amz-server-side-encryption*` header
// on POST Object, so preflight authorization must project only form SSE fields.
for (name, value) in &mut self.0 {
match name.as_str() {
"if-match" | "if-none-match" => *value = req.headers().get(&*name).cloned(),
"x-amz-server-side-encryption" | "x-amz-server-side-encryption-customer-algorithm" if value.is_none() => {
*value = req.headers().get(&*name).cloned();
}
_ => {}
if matches!(name.as_str(), "if-match" | "if-none-match") {
*value = req.headers().get(&*name).cloned();
}
}
self.install(req);
@@ -363,12 +363,16 @@ fn post_object_policy_checks_form_fields_instead_of_headers() {
assert_eq!(conditions.get("object-lock-legal-hold"), Some(&vec!["ON".to_string()]));
}
#[test]
fn gateway_post_policy_projects_effective_write_conditions() {
#[tokio::test]
async fn gateway_post_policy_projects_effective_write_conditions() {
let mut req = request(Method::POST)
.header("if-none-match", "*")
.header("if-none-match", "\"second\"")
.header("x-amz-server-side-encryption", "wire")
.header("x-amz-server-side-encryption", "AES256")
.header(
"x-amz-server-side-encryption-aws-kms-key-id",
"arn:aws:kms:us-east-1:111122223333:key/wire",
)
.header("x-amz-server-side-encryption-customer-algorithm", "AES256")
.build();
PostObjectFormPolicy::new(PostObjectPolicyFields {
@@ -383,12 +387,58 @@ fn gateway_post_policy_projects_effective_write_conditions() {
assert!(!projected.contains_key("if-match"));
assert_eq!(projected.get("if-none-match"), Some(&HeaderValue::from_static("*")));
assert_eq!(projected.get("x-amz-server-side-encryption"), Some(&HeaderValue::from_static("form")));
assert_eq!(
projected.get("x-amz-server-side-encryption-customer-algorithm"),
Some(&HeaderValue::from_static("AES256"))
assert!(
!projected.contains_key("x-amz-server-side-encryption-aws-kms-key-id"),
"unsigned wire KMS key header must not bleed into PostObject policy headers"
);
assert!(
!projected.contains_key("x-amz-server-side-encryption-customer-algorithm"),
"unsigned wire SSE-C algorithm header must not bleed into PostObject policy headers"
);
assert_eq!(req.headers().get_all("if-none-match").iter().count(), 2);
assert_eq!(req.headers().get("x-amz-server-side-encryption"), Some(&HeaderValue::from_static("wire")));
assert_eq!(
req.headers().get("x-amz-server-side-encryption"),
Some(&HeaderValue::from_static("AES256"))
);
// Unsigned HTTP wire SSE headers must not satisfy a preflight policy requiring SSE when the
// POST form itself omits encryption fields.
let mut wire_only_sse = request(Method::POST)
.header("x-amz-server-side-encryption", "AES256")
.header("x-amz-server-side-encryption-customer-algorithm", "AES256")
.build();
PostObjectFormPolicy::new(PostObjectPolicyFields::default())
.expect("empty form policy")
.install_gateway(&mut wire_only_sse);
let projected = &wire_only_sse.post_object_policy_headers().expect("projected headers").0;
assert!(!projected.contains_key("x-amz-server-side-encryption"));
assert!(!projected.contains_key("x-amz-server-side-encryption-customer-algorithm"));
let action = Action::S3Action(S3Action::PutObjectAction);
let conditions = remaining_retention_days_conditions(&wire_only_sse, action);
assert!(!conditions.contains_key("x-amz-server-side-encryption"));
let require_sse_policy = Policy::parse_config(
br#"{
"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::bucket/*",
"Condition":{"StringEquals":{"s3:x-amz-server-side-encryption":"AES256"}}}]
}"#,
)
.expect("SSE condition policy should parse");
let args = Args {
account: "writer",
groups: &None,
action,
bucket: "bucket",
conditions: &conditions,
is_owner: false,
object: "object",
claims: &HashMap::new(),
deny_only: false,
};
assert!(
!require_sse_policy.is_allowed(&args).await,
"unsigned wire SSE headers must not satisfy a PostObject preflight encryption policy"
);
}
#[tokio::test]
@@ -737,3 +787,55 @@ fn replication_proxy_requires_authorization_independent_of_local_tags() {
));
assert!(!proxy_allowed(&req));
}
#[tokio::test]
#[serial_test::serial]
async fn discovery_root_access_key_stays_isolated_to_bound_server_context() {
use crate::runtime_sources::{
AppContext, ServerContextSlot, current_action_credentials, current_app_context, install_test_app_context,
};
use crate::storage::authorization::request_root_access_key;
use std::sync::Arc;
let store = crate::app::gating_test_env::shared_gating_ecstore().await;
if current_app_context().is_none() {
install_test_app_context(Arc::clone(&store)).await;
}
let _ = rustfs_credentials::init_global_action_credentials(
Some("global-server-a-root".to_owned()),
Some("global-server-a-secret".to_owned()),
);
let ambient = current_app_context().expect("ambient context");
let _ = ambient.publish_action_credentials(rustfs_credentials::Credentials {
access_key: "global-server-a-root".to_owned(),
secret_key: "global-server-a-secret".to_owned(),
status: "on".to_owned(),
..Default::default()
});
let global_root = current_action_credentials().map(|cred| cred.access_key).unwrap_or_default();
assert!(!global_root.is_empty());
assert_eq!(request_root_access_key(None), global_root);
let uninstalled = ServerContextSlot::new();
assert_eq!(request_root_access_key(Some(&uninstalled)), "");
let no_root_ctx = Arc::new(AppContext::new(Arc::clone(&store), ambient.iam(), ambient.kms()).with_empty_action_credentials());
let slot_without_root = ServerContextSlot::new();
assert!(slot_without_root.install(no_root_ctx));
assert_eq!(
request_root_access_key(Some(&slot_without_root)),
"",
"installed server context without published root credentials must never fall back to global root"
);
let isolated_ctx = Arc::new(AppContext::new(Arc::clone(&store), ambient.iam(), ambient.kms()));
assert!(isolated_ctx.publish_action_credentials(rustfs_credentials::Credentials {
access_key: "server-b-root".to_owned(),
secret_key: "server-b-secret".to_owned(),
status: "on".to_owned(),
..Default::default()
}));
let slot_with_root = ServerContextSlot::new();
assert!(slot_with_root.install(isolated_ctx));
assert_eq!(request_root_access_key(Some(&slot_with_root)), "server-b-root");
}
+14 -2
View File
@@ -29,6 +29,7 @@ use crate::auth::facts::{AuthzTarget, build_args};
use crate::error::ApiError;
use crate::storage::denial_audit::DenialAuditor;
use crate::storage::storage_api::contract::bucket::{BucketOperations, BucketOptions};
use crate::storage::storage_api::runtime_sources_consumer::ServerContextSlot;
use crate::storage::{StorageError, is_err_bucket_not_found};
use rustfs_iam::{
store::object::ObjectStore,
@@ -129,6 +130,17 @@ pub(crate) async fn query_list_buckets_permission<R: AuthorizationRequest + ?Siz
}
}
pub(crate) fn request_root_access_key(server_context: Option<&Arc<ServerContextSlot>>) -> String {
match server_context {
Some(slot) => slot
.installed_app_context()
.and_then(|context| context.action_credentials().get())
.map(|root| root.access_key)
.unwrap_or_default(),
None => root_access_key(),
}
}
/// Prepare the IAM-only authorization used to decide which buckets are visible in ListBuckets.
/// Bucket policies are intentionally excluded from this discovery decision, matching MinIO.
pub(crate) async fn prepare_list_buckets_iam_authorization<R: AuthorizationRequest + ?Sized>(
@@ -143,7 +155,7 @@ pub(crate) async fn prepare_list_buckets_iam_authorization<R: AuthorizationReque
let groups = cred.groups.clone();
let claims = cred.claims.clone().unwrap_or_default();
let action = Action::S3Action(S3Action::ListAllMyBucketsAction);
let root_access_key = root_access_key();
let root_access_key = request_root_access_key(req.server_context());
let principal = request_principal(req, cred, &root_access_key);
let facts = request_authz_facts(
req,
@@ -216,7 +228,7 @@ pub(crate) async fn s3_action_potential<R: AuthorizationRequest + ?Sized>(req: &
if is_reserved_meta_bucket(bucket) {
return Ok(false);
}
let root = root_access_key();
let root = request_root_access_key(req.server_context());
let principal = request_principal(req, cred, &root).with_owner(info.is_owner);
let facts = request_authz_facts(
req,
+2
View File
@@ -62,6 +62,8 @@ pub(crate) use decision::{
authorize_request_core, authorize_request_with_location_constraint, authorize_staged_multipart_part,
authorize_write_etag_condition, iam_authorization_error,
};
#[cfg(test)]
pub(crate) use discovery::request_root_access_key;
pub(crate) use discovery::{
log_list_buckets_iam_implicit_deny, prepare_list_buckets_iam_authorization, query_list_buckets_permission,
s3_action_potential,