fix(admin): harden admin authz context, scoping, and input validation (#9677)

Propagate verified proxy transport/client context and request-scoped
server context slots across admin authentication and authorization,
including task-scoped IAM root credential lookup so multi-instance
embedded servers do not leak ambient credentials across server domains.

Fail closed with InvalidArgument on non-empty AddOrUpdateUserReq.policy
in both the add-user admin handler and IamSys::create_user, normalizing
empty policy strings to None before persistence and site-replication
hooks.

Wrap GetKmsStatusHandler authorization denials in KmsAdminAudit::gate_admin
using KmsAdminOperation::Status, apply bucket-scoped authorization
symmetrically across bucket quota write and read handlers, and restore the
guardrail comment documenting direct is_allowed evaluation in
service_account.rs.

Enable bucket and object resource matching for scoped admin actions
(SetBucketQuota, GetBucketTarget, SetBucketTarget, InspectData) in the
policy evaluator and wire resource-scoped authorization into replication
remote-target and inspect-data handlers. Align bulk access-key routes on
ListUsersAdminAction for cross-user queries and enforce strict S3 bucket
name validation on quota and table-catalog warehouse parameters.

Refs: rustfs/backlog#1469, rustfs/backlog#1246, rustfs/backlog#1886, rustfs/backlog#2526
This commit is contained in:
Chris An
2026-11-27 20:20:08 +08:00
committed by GitHub
parent f9a9aa75d5
commit 2e5e99a994
36 changed files with 2267 additions and 245 deletions
+104 -4
View File
@@ -173,6 +173,7 @@ enum PreparedServicePolicyMode {
tokio::task_local! {
static BUCKET_TAG_DELETION: ();
static SCOPED_ROOT_CREDENTIALS: Option<Credentials>;
}
/// Scope authorization to the server's DeleteBucketTagging operation. The IAM action is shared
@@ -181,6 +182,22 @@ pub async fn with_bucket_tag_deletion<F: std::future::Future>(operation: F) -> F
BUCKET_TAG_DELETION.scope((), operation).await
}
/// Scope IAM root-credential lookup for the duration of `operation` to the
/// caller's request-scoped server context rather than the process-ambient root
/// credentials (rustfs/backlog#1469).
pub async fn with_scoped_root_credentials<F: std::future::Future>(
root_credentials: Option<Credentials>,
operation: F,
) -> F::Output {
SCOPED_ROOT_CREDENTIALS.scope(root_credentials, operation).await
}
fn effective_root_credentials() -> Option<Credentials> {
SCOPED_ROOT_CREDENTIALS
.try_with(Clone::clone)
.unwrap_or_else(|_| crate::root_credentials::credentials())
}
#[derive(Clone)]
enum PreparedIamMode {
TerminalDeny,
@@ -1439,6 +1456,10 @@ impl<T: Store> IamSys<T> {
return Err(IamError::InvalidSecretKeyLength);
}
if args.policy.as_deref().is_some_and(|policy| !policy.is_empty()) {
return Err(IamError::InvalidArgument);
}
let (updated_at, secret_changed, parent_guard) = self
.store
.add_user_at_with_secret_change(access_key, args, updated_at, allow_status_change)
@@ -1578,8 +1599,8 @@ impl<T: Store> IamSys<T> {
}
pub async fn check_key(&self, access_key: &str) -> Result<(Option<UserIdentity>, bool)> {
if let Some(sys_cred) = crate::root_credentials::credentials()
&& sys_cred.access_key == access_key
if let Some(sys_cred) = effective_root_credentials()
&& bool::from(sys_cred.access_key.as_bytes().ct_eq(access_key.as_bytes()))
{
return Ok((Some(UserIdentity::new(sys_cred)), true));
}
@@ -1607,12 +1628,17 @@ impl<T: Store> IamSys<T> {
return Ok(true);
}
if identity.sts_generation.is_none() {
if cred.is_service_account() || crate::is_root_access_key(&cred.parent_user) {
let root_cred = effective_root_credentials();
if cred.is_service_account()
|| root_cred
.as_ref()
.is_some_and(|root| bool::from(root.access_key.as_bytes().ct_eq(cred.parent_user.as_bytes())))
{
return Ok(true);
}
// OIDC and broker-issued plugin attempts have separate parent authorities.
// A freshly published identity may not yet have its decoded claims cached.
if let Some(key) = crate::root_credentials::token_signing_key()
if let Some(key) = root_cred.map(|root| root.secret_key)
&& let Ok(claims) = get_claims_from_token_with_secret(&cred.session_token, &key)
&& claims.get("parent").and_then(Value::as_str) == Some(cred.parent_user.as_str())
&& (is_verified_or_legacy_federated_session(&claims, &cred.parent_user)
@@ -8789,4 +8815,78 @@ mod tests {
assert!(matches!(result, Err(IamError::InvalidArgument)));
}
#[tokio::test]
async fn create_user_rejects_non_empty_policy_field_fail_closed() {
let iam_sys = IamSys::new(
IamCache::new(StsTestMockStore::new(true))
.await
.expect("IAM cache should initialize"),
);
let err = iam_sys
.create_user(
"alice-policy-reject",
&AddOrUpdateUserReq {
secret_key: "secret-key-123456".to_string(),
policy: Some("readwrite".to_string()),
status: rustfs_madmin::AccountStatus::Enabled,
},
)
.await
.expect_err("non-empty AddOrUpdateUserReq.policy must fail closed");
assert!(matches!(err, IamError::InvalidArgument), "unexpected error: {err:?}");
assert!(
iam_sys.get_user("alice-policy-reject").await.is_none(),
"rejected user creation must not leave a user in cache"
);
}
#[tokio::test]
async fn check_key_respects_scoped_root_credentials() {
let _ = rustfs_credentials::init_global_action_credentials(
Some("ambient-root".to_string()),
Some("ambient-root-secret".to_string()),
);
let ambient_root = crate::root_credentials::credentials().expect("global action credentials should be initialized");
let iam_sys = IamSys::new(
IamCache::new(StsTestMockStore::new(true))
.await
.expect("IAM cache should initialize"),
);
let scoped_root = Credentials {
access_key: "scoped-server-b-root".to_string(),
secret_key: "scoped-server-b-secret".to_string(),
status: "on".to_string(),
..Default::default()
};
let (ambient_in_b, ambient_valid) =
with_scoped_root_credentials(Some(scoped_root.clone()), iam_sys.check_key(&ambient_root.access_key))
.await
.expect("check_key should succeed cleanly");
assert!(
ambient_in_b.is_none() && !ambient_valid,
"process-ambient root key must not authenticate inside a different scoped root context"
);
let (scoped_in_b, scoped_valid) =
with_scoped_root_credentials(Some(scoped_root.clone()), iam_sys.check_key(&scoped_root.access_key))
.await
.expect("check_key should succeed cleanly");
assert!(scoped_valid);
assert_eq!(
scoped_in_b.expect("scoped root must resolve").credentials.access_key,
scoped_root.access_key
);
let (none_in_b, none_valid) = with_scoped_root_credentials(None, iam_sys.check_key(&ambient_root.access_key))
.await
.expect("check_key should succeed cleanly");
assert!(
none_in_b.is_none() && !none_valid,
"empty scoped root credentials must fail closed instead of falling back to ambient root"
);
}
}
+4
View File
@@ -99,6 +99,10 @@ pub struct AddOrUpdateUserReq {
#[serde(rename = "secretKey")]
pub secret_key: String,
/// Deprecated legacy field from older admin payloads. `/admin/v3/add-user`
/// manages user credentials and status only and rejects non-empty values
/// with `InvalidArgument`; callers must attach policies via the dedicated
/// policy-attachment endpoints.
#[serde(rename = "policy", skip_serializing_if = "Option::is_none")]
pub policy: Option<String>,
+11
View File
@@ -668,6 +668,17 @@ pub enum AdminAction {
}
impl AdminAction {
pub(crate) fn is_resource_scoped(&self) -> bool {
self.is_table_resource_scoped()
|| matches!(
self,
AdminAction::SetBucketQuotaAdminAction
| AdminAction::SetBucketTargetAction
| AdminAction::GetBucketTargetAction
| AdminAction::InspectDataAction
)
}
pub(crate) fn is_table_resource_scoped(&self) -> bool {
matches!(
self,
+101
View File
@@ -2337,6 +2337,107 @@ mod test {
Ok(())
}
#[tokio::test]
async fn test_bucket_and_object_scoped_admin_actions_enforce_resource_bounds() -> Result<()> {
use crate::policy::action::{Action, AdminAction};
let conditions = HashMap::new();
let claims = HashMap::new();
let groups = None;
for (action_name, action) in [
("admin:SetBucketQuota", AdminAction::SetBucketQuotaAdminAction),
("admin:GetBucketTarget", AdminAction::GetBucketTargetAction),
("admin:SetBucketTarget", AdminAction::SetBucketTargetAction),
] {
let scoped_doc = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Action":["{action_name}"],"Resource":["arn:aws:s3:::allowed-bucket"]}}]}}"#
);
let scoped = Policy::parse_config(scoped_doc.as_bytes())?;
let allowed_args = Args {
account: "testuser",
groups: &groups,
action: Action::AdminAction(action),
bucket: "allowed-bucket",
conditions: &conditions,
is_owner: false,
object: "",
claims: &claims,
deny_only: false,
};
assert!(
scoped.is_allowed(&allowed_args).await,
"{action_name} must allow the bucket named in Resource"
);
for denied_bucket in ["other-bucket", ""] {
let denied_args = Args {
bucket: denied_bucket,
..allowed_args
};
assert!(
!scoped.is_allowed(&denied_args).await,
"{action_name} scoped to allowed-bucket must deny bucket `{denied_bucket}`"
);
}
let unscoped_doc =
format!(r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Action":["{action_name}"]}}]}}"#);
let unscoped = Policy::parse_config(unscoped_doc.as_bytes())?;
for bucket in ["allowed-bucket", "other-bucket", ""] {
let args = Args { bucket, ..allowed_args };
assert!(
unscoped.is_allowed(&args).await,
"resource-less {action_name} statement must keep authorizing `{bucket}`"
);
}
}
let inspect_doc = r#"{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["admin:InspectData"],
"Resource": ["arn:aws:s3:::allowed-bucket/public/*"]
}
]
}"#;
let inspect_policy = Policy::parse_config(inspect_doc.as_bytes())?;
let base_inspect = Args {
account: "testuser",
groups: &groups,
action: Action::AdminAction(AdminAction::InspectDataAction),
bucket: "allowed-bucket",
conditions: &conditions,
is_owner: false,
object: "public/report.txt",
claims: &claims,
deny_only: false,
};
assert!(
inspect_policy.is_allowed(&base_inspect).await,
"InspectData must allow objects under the granted prefix"
);
for (bucket, object) in [
("allowed-bucket", "private/secret.txt"),
("other-bucket", "public/report.txt"),
("", ""),
] {
let denied = Args {
bucket,
object,
..base_inspect
};
assert!(
!inspect_policy.is_allowed(&denied).await,
"InspectData must deny `{bucket}/{object}` outside the granted resource"
);
}
Ok(())
}
#[test]
fn test_sts_statement_without_resource_is_valid() {
let data = r#"
+1 -1
View File
@@ -144,7 +144,7 @@ impl Statement {
return false;
}
!matches!(args.action, Action::AdminAction(action) if action.is_table_resource_scoped())
!matches!(args.action, Action::AdminAction(action) if action.is_resource_scoped())
}
fn is_kms(&self) -> bool {
+700 -39
View File
@@ -13,8 +13,9 @@
// limitations under the License.
use crate::admin::operation::AdminRequest;
use crate::admin::runtime_sources::AppContext;
use crate::app::{RequestCredentials, RequestEnvelope};
use crate::auth::get_condition_values;
use crate::auth::get_condition_values_with_client_info;
use http::HeaderMap;
use rustfs_credentials::Credentials;
use rustfs_iam::store::Store;
@@ -24,6 +25,7 @@ use rustfs_policy::policy::{
action::{Action, AdminAction},
};
use rustfs_s3_types::{S3Result, s3_error};
use rustfs_trusted_proxies::ClientInfo;
use std::sync::Arc;
use tracing::debug;
@@ -34,6 +36,90 @@ struct AuthContext<'a> {
is_owner: bool,
deny_only: bool,
remote_addr: Option<std::net::SocketAddr>,
client_info: Option<&'a ClientInfo>,
}
/// Network and optional per-server context facts for an admin authorization check.
///
/// Converting `&RequestEnvelope` via `From` threads only the verified proxy
/// [`ClientInfo`] and policy source address (`aws:SourceIp` and
/// `aws:SecureTransport`) while keeping IAM resolution ambient so ambient-store
/// admin handlers never split-brain auth/authz against a different server
/// domain. Handlers whose authentication, authorization, and execution all
/// resolve from the request's `ServerContextSlot` opt in explicitly via
/// [`Self::with_server_context`]. Callers outside `admin` that hold only a
/// resolved `Option<SocketAddr>` can keep passing it directly.
#[derive(Clone, Copy)]
pub struct AdminRequestOrigin<'a> {
remote_addr: Option<std::net::SocketAddr>,
client_info: Option<&'a ClientInfo>,
server_context_envelope: Option<&'a RequestEnvelope>,
}
impl<'a> AdminRequestOrigin<'a> {
/// Thread both verified proxy [`ClientInfo`] and the request's
/// `ServerContextSlot` for handlers that authenticate and execute against
/// the same request-scoped server context.
pub(crate) fn with_server_context(envelope: &'a RequestEnvelope) -> Self {
Self {
remote_addr: envelope.policy_source_addr(),
client_info: envelope.client_info(),
server_context_envelope: Some(envelope),
}
}
}
impl From<Option<std::net::SocketAddr>> for AdminRequestOrigin<'_> {
fn from(remote_addr: Option<std::net::SocketAddr>) -> Self {
Self {
remote_addr,
client_info: None,
server_context_envelope: None,
}
}
}
impl<'a> From<&'a RequestEnvelope> for AdminRequestOrigin<'a> {
fn from(envelope: &'a RequestEnvelope) -> Self {
Self {
remote_addr: envelope.policy_source_addr(),
client_info: envelope.client_info(),
server_context_envelope: None,
}
}
}
pub(crate) fn ready_iam_handle_from_envelope(
envelope: Option<&RequestEnvelope>,
) -> S3Result<Arc<IamSys<rustfs_iam::store::object::ObjectStore>>> {
if let Some(slot) = envelope.and_then(RequestEnvelope::server_context) {
let Some(context) = slot.installed_app_context() else {
return Err(s3_error!(ServiceUnavailable, "server context is not ready"));
};
if !context.iam().is_ready() {
return Err(s3_error!(InternalError, "iam not init"));
}
return Ok(context.iam().handle());
}
crate::admin::runtime_sources::current_ready_iam_handle().map_err(|_| s3_error!(InternalError, "iam not init"))
}
pub(crate) fn action_credentials_from_envelope(envelope: &RequestEnvelope) -> Option<Credentials> {
match envelope.server_context() {
Some(slot) => slot.installed_app_context().and_then(|ctx| ctx.action_credentials().get()),
None => crate::admin::runtime_sources::current_action_credentials(),
}
}
fn scoped_app_context_for_auth(envelope: &RequestEnvelope) -> S3Result<Option<Arc<AppContext>>> {
match envelope.server_context() {
Some(slot) => slot
.installed_app_context()
.map(Some)
.ok_or_else(|| s3_error!(ServiceUnavailable, "server context is not ready")),
None => Ok(None),
}
}
#[derive(Clone, Copy, Debug)]
@@ -66,23 +152,23 @@ impl<'a> AdminResourceScope<'a> {
}
}
pub async fn validate_admin_request(
pub async fn validate_admin_request<'a>(
headers: &HeaderMap,
cred: &Credentials,
is_owner: bool,
deny_only: bool,
actions: Vec<Action>,
remote_addr: Option<std::net::SocketAddr>,
origin: impl Into<AdminRequestOrigin<'a>>,
) -> S3Result<()> {
let Ok(iam_store) = crate::admin::runtime_sources::current_ready_iam_handle() else {
return Err(s3_error!(InternalError, "iam not init"));
};
let origin = origin.into();
let iam_store = ready_iam_handle_from_envelope(origin.server_context_envelope)?;
let ctx = AuthContext {
headers,
cred,
is_owner,
deny_only,
remote_addr,
remote_addr: origin.remote_addr,
client_info: origin.client_info,
};
evaluate_admin_actions(iam_store, &ctx, &actions, "", "").await
@@ -95,10 +181,22 @@ pub(crate) enum SelfServiceMutation {
impl SelfServiceMutation {
pub(crate) async fn check(&self, req: &AdminRequest, cred: &Credentials, is_owner: bool) -> S3Result<()> {
let context = crate::admin::runtime_sources::app_context_from_envelope(req.envelope())
.filter(|ctx| ctx.iam().is_ready())
.ok_or_else(|| s3_error!(ServiceUnavailable, "iam unavailable"))?;
self.check_for_iam(context.iam().handle(), req, cred, is_owner).await
let iam = match self {
// Password self-service handlers (`account.rs`, `user.rs::AddUser`)
// authenticate and mutate against the process-ambient IAM domain.
Self::Password => crate::admin::runtime_sources::current_ready_iam_handle()
.map_err(|_| s3_error!(ServiceUnavailable, "iam unavailable"))?,
// MFA self-service handlers (`mfa.rs`) resolve auth, IAM, and store
// strictly from the request envelope's `ServerContextSlot`.
Self::Mfa => ready_iam_handle_from_envelope(Some(req.envelope())).map_err(|err| {
if err.code() == &rustfs_s3_types::S3ErrorCode::ServiceUnavailable {
err
} else {
s3_error!(ServiceUnavailable, "iam unavailable")
}
})?,
};
self.check_for_iam(iam, req, cred, is_owner).await
}
async fn check_for_iam<S: Store>(
@@ -115,6 +213,7 @@ impl SelfServiceMutation {
is_owner: is_owner && cred.session_token.is_empty() && !cred.is_service_account(),
deny_only: true,
remote_addr: req.policy_source_addr(),
client_info: req.client_info(),
};
// Password rotation also honors the existing add-user self-rotation deny.
// The ordinary multi-action admin gate is any-of; here every check must pass.
@@ -158,7 +257,7 @@ async fn check_admin_request_auth<S: Store>(
bucket: &str,
object: &str,
) -> S3Result<()> {
let conditions = get_condition_values(ctx.headers, ctx.cred, None, None, ctx.remote_addr);
let conditions = get_condition_values_with_client_info(ctx.headers, ctx.cred, None, None, ctx.remote_addr, ctx.client_info);
let allowed = iam_store
.is_allowed(&Args {
@@ -189,13 +288,13 @@ async fn check_admin_request_auth<S: Store>(
Ok(())
}
pub async fn validate_admin_request_with_bucket(
pub async fn validate_admin_request_with_bucket<'a>(
headers: &HeaderMap,
cred: &Credentials,
is_owner: bool,
deny_only: bool,
actions: Vec<Action>,
remote_addr: Option<std::net::SocketAddr>,
origin: impl Into<AdminRequestOrigin<'a>>,
bucket: &str,
) -> S3Result<()> {
validate_admin_request_with_bucket_object(
@@ -204,50 +303,52 @@ pub async fn validate_admin_request_with_bucket(
is_owner,
deny_only,
actions,
remote_addr,
origin,
AdminResourceScope::bucket(bucket),
)
.await
}
pub async fn validate_admin_request_with_bucket_object(
pub async fn validate_admin_request_with_bucket_object<'a>(
headers: &HeaderMap,
cred: &Credentials,
is_owner: bool,
deny_only: bool,
actions: Vec<Action>,
remote_addr: Option<std::net::SocketAddr>,
origin: impl Into<AdminRequestOrigin<'a>>,
resource: AdminResourceScope<'_>,
) -> S3Result<()> {
let Ok(iam_store) = crate::admin::runtime_sources::current_ready_iam_handle() else {
return Err(s3_error!(InternalError, "iam not init"));
};
let origin = origin.into();
let iam_store = ready_iam_handle_from_envelope(origin.server_context_envelope)?;
let ctx = AuthContext {
headers,
cred,
is_owner,
deny_only,
remote_addr,
remote_addr: origin.remote_addr,
client_info: origin.client_info,
};
evaluate_admin_actions(iam_store, &ctx, &actions, resource.bucket, resource.object).await
}
pub(crate) async fn validate_admin_action_with_bucket_object_for_iam<S: Store>(
pub(crate) async fn validate_admin_action_with_bucket_object_for_iam<'a, S: Store>(
iam_store: Arc<IamSys<S>>,
headers: &HeaderMap,
cred: &Credentials,
is_owner: bool,
action: Action,
remote_addr: Option<std::net::SocketAddr>,
origin: impl Into<AdminRequestOrigin<'a>>,
resource: AdminResourceScope<'_>,
) -> S3Result<()> {
let origin = origin.into();
let ctx = AuthContext {
headers,
cred,
is_owner,
deny_only: false,
remote_addr,
remote_addr: origin.remote_addr,
client_info: origin.client_info,
};
evaluate_admin_actions(iam_store, &ctx, &[action], resource.bucket, resource.object).await
}
@@ -259,13 +360,13 @@ pub(crate) async fn validate_admin_action_with_bucket_object_for_iam<S: Store>(
/// without a target key pass `""` and stay unscoped, which is also what a
/// malformed request resolves to: the request is rejected on its own parse error
/// right after the gate, so no key is ever touched under an unscoped decision.
pub async fn validate_admin_request_with_kms_key(
pub async fn validate_admin_request_with_kms_key<'a>(
headers: &HeaderMap,
cred: &Credentials,
is_owner: bool,
deny_only: bool,
actions: Vec<Action>,
remote_addr: Option<std::net::SocketAddr>,
origin: impl Into<AdminRequestOrigin<'a>>,
key_id: &str,
) -> S3Result<()> {
validate_admin_request_with_bucket_object(
@@ -274,7 +375,7 @@ pub async fn validate_admin_request_with_kms_key(
is_owner,
deny_only,
actions,
remote_addr,
origin,
AdminResourceScope::kms_key(key_id),
)
.await
@@ -284,12 +385,53 @@ pub async fn validate_admin_request_with_kms_key(
/// envelope carries: the presented access key and the session token the edge
/// decoded.
pub(crate) async fn authenticate_envelope_credentials(credentials: &RequestCredentials) -> S3Result<(Credentials, bool)> {
authenticate_request_facts(credentials.access_key(), credentials.session_token().unwrap_or_default()).await
authenticate_request_facts_with_context(credentials.access_key(), credentials.session_token().unwrap_or_default(), None).await
}
async fn authenticate_request_facts(access_key: &str, session_token: &str) -> S3Result<(Credentials, bool)> {
/// Authenticate the caller of an owned admin request against the request's
/// server context slot when present, falling back to the ambient process
/// context only when no slot was attached.
pub(crate) async fn authenticate_envelope_credentials_with_context(
credentials: &RequestCredentials,
envelope: &RequestEnvelope,
) -> S3Result<(Credentials, bool)> {
let context = scoped_app_context_for_auth(envelope)?;
authenticate_request_facts_with_context(
credentials.access_key(),
credentials.session_token().unwrap_or_default(),
context.as_deref(),
)
.await
}
/// Validate an access key against an explicit application context while also
/// scoping IAM root-credential lookup to that context's own root credentials
/// so another embedded server's process-ambient root key cannot leak through
/// `IamSys::check_key` (rustfs/backlog#1469).
pub(crate) async fn check_admin_key_valid_with_context(
session_token: &str,
access_key: &str,
ctx: Option<&AppContext>,
) -> S3Result<(Credentials, bool)> {
use crate::auth::check_key_valid_with_context;
match ctx {
Some(context) => {
rustfs_iam::sys::with_scoped_root_credentials(
context.action_credentials().get(),
check_key_valid_with_context(session_token, access_key, Some(context)),
)
.await
}
None => check_key_valid_with_context(session_token, access_key, None).await,
}
}
async fn authenticate_request_facts_with_context(
access_key: &str,
session_token: &str,
ctx: Option<&AppContext>,
) -> S3Result<(Credentials, bool)> {
// Log authentication attempt for debugging
debug!(
"authenticate_request: processing authentication - access_key={}, has_session_token={}",
@@ -297,8 +439,7 @@ async fn authenticate_request_facts(access_key: &str, session_token: &str) -> S3
!session_token.is_empty()
);
// Validate credentials using the core authentication function
let result = check_key_valid_with_context(session_token, access_key, None).await;
let result = check_admin_key_valid_with_context(session_token, access_key, ctx).await;
match &result {
Ok((cred, is_owner)) => {
@@ -317,18 +458,59 @@ async fn authenticate_request_facts(access_key: &str, session_token: &str) -> S3
/// Full admin gate over RustFS-owned request facts: authenticate the
/// presented credentials, then authorize the caller for `actions`
/// ([`validate_admin_request`], allowing on the first permitted action).
/// Returns the authenticated credentials for handlers that need the caller
/// identity. `deny_only` stays `false`: every caller performs a full allow
/// check.
/// ([`validate_admin_request`], allowing on the first permitted action) against
/// the process-ambient IAM domain while propagating verified proxy
/// `ClientInfo`. Returns the authenticated credentials for handlers that need
/// the caller identity. `deny_only` stays `false`: every caller performs a full
/// allow check.
pub async fn authorize_admin_envelope(req: &RequestEnvelope, actions: Vec<Action>) -> S3Result<Credentials> {
authorize_admin_envelope_with_scope(req, actions, AdminResourceScope::bucket_object("", "")).await
}
/// Full admin gate over RustFS-owned request facts scoped to a bucket/object
/// resource against the process-ambient IAM domain (matching ambient-store
/// admin handlers).
pub(crate) async fn authorize_admin_envelope_with_scope(
req: &RequestEnvelope,
actions: Vec<Action>,
resource: AdminResourceScope<'_>,
) -> S3Result<Credentials> {
let Some(input_cred) = req.credentials() else {
return Err(s3_error!(InvalidRequest, "get cred failed"));
};
let (cred, owner) = authenticate_envelope_credentials(input_cred).await?;
// Policy conditions see the verified proxy client, never the raw peer.
validate_admin_request(req.headers(), &cred, owner, false, actions, req.policy_source_addr()).await?;
validate_admin_request_with_bucket_object(req.headers(), &cred, owner, false, actions, req, resource).await?;
Ok(cred)
}
/// Full admin gate over RustFS-owned request facts scoped to both the request's
/// `ServerContextSlot` (when present) and a bucket/object resource. Use this
/// ONLY for handlers whose downstream execution also resolves from
/// `req.envelope()`.
pub(crate) async fn authorize_admin_envelope_with_context_and_scope(
req: &RequestEnvelope,
actions: Vec<Action>,
resource: AdminResourceScope<'_>,
) -> S3Result<Credentials> {
let Some(input_cred) = req.credentials() else {
return Err(s3_error!(InvalidRequest, "get cred failed"));
};
let (cred, owner) = authenticate_envelope_credentials_with_context(input_cred, req).await?;
// Policy conditions see the verified proxy client, never the raw peer.
validate_admin_request_with_bucket_object(
req.headers(),
&cred,
owner,
false,
actions,
AdminRequestOrigin::with_server_context(req),
resource,
)
.await?;
Ok(cred)
}
@@ -350,7 +532,7 @@ pub(crate) async fn resolve_admin_object_read_sse_kms_principal(
let Some(input_cred) = req.credentials() else {
return Err(s3_error!(AccessDenied, "Access Denied"));
};
let (cred, is_owner) = authenticate_envelope_credentials(input_cred).await?;
let (cred, is_owner) = authenticate_envelope_credentials_with_context(input_cred, req).await?;
let request_context = req.request_context().cloned();
req.install_req_info(ReqInfo {
cred: Some(cred),
@@ -586,6 +768,7 @@ mod tests {
is_owner,
deny_only: false,
remote_addr: None,
client_info: None,
}
}
@@ -679,13 +862,13 @@ mod tests {
..Default::default()
}));
publish_test_app_context(context);
let (root, is_owner) = authenticate_request_facts("proxy-test-root", "")
let (root, is_owner) = authenticate_request_facts_with_context("proxy-test-root", "", None)
.await
.expect("root credentials");
assert_eq!(root.access_key, "proxy-test-root");
assert!(is_owner);
let error = authenticate_request_facts("proxy-test-root", "unexpected-token")
let error = authenticate_request_facts_with_context("proxy-test-root", "unexpected-token", None)
.await
.expect_err("the root has no session token");
assert_eq!(error.code(), &rustfs_s3_types::S3ErrorCode::InvalidRequest);
@@ -1095,4 +1278,482 @@ mod tests {
.expect_err("unauthenticated envelope must fail closed");
assert_eq!(err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied);
}
#[test]
#[serial_test::serial]
fn admin_auth_evaluates_aws_secure_transport_from_verified_client_info() {
crate::app::gating_test_env::run_large_stack_test("admin-secure-transport", || async {
use crate::admin::operation::Operation;
use crate::admin::operation::test_support::TestRequest;
use crate::admin::runtime_sources::{AppContext, IamInterface, KmsInterface, publish_test_app_context};
use crate::shared_types::RemoteAddr;
use rustfs_iam::store::object::ObjectStore;
use rustfs_madmin::{AccountStatus, AddOrUpdateUserReq};
use rustfs_trusted_proxies::{ClientInfo, ValidationMode};
use std::sync::Arc;
struct ReadyIam(Arc<rustfs_iam::sys::IamSys<ObjectStore>>);
impl IamInterface for ReadyIam {
fn handle(&self) -> Arc<rustfs_iam::sys::IamSys<ObjectStore>> {
Arc::clone(&self.0)
}
fn is_ready(&self) -> bool {
true
}
}
struct TestKms;
impl KmsInterface for TestKms {
fn handle(&self) -> Arc<rustfs_kms::KmsServiceManager> {
Arc::new(rustfs_kms::KmsServiceManager::new())
}
}
let previous = crate::runtime_sources::current_app_context();
let (_dir, _paths, store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
ObjectStore::new(Arc::clone(&store))
.save_iam_config(
serde_json::json!({"version": 1}),
format!("{}/format.json", *rustfs_iam::store::object::IAM_CONFIG_PREFIX),
)
.await
.expect("seed IAM format");
let iam = rustfs_iam::build_iam_sys(Arc::clone(&store)).await.expect("init IAM");
let user = "tls-only-admin";
let secret = "tls-admin-secret-1234";
iam.create_user(
user,
&AddOrUpdateUserReq {
secret_key: secret.to_owned(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create user");
let doc = serde_json::json!({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["admin:*"],
"Condition": {"Bool": {"aws:SecureTransport": "true"}}
},
{
"Effect": "Allow",
"Action": ["sts:AssumeRole"]
},
{
"Effect": "Deny",
"Action": ["sts:AssumeRole"],
"Condition": {"Bool": {"aws:SecureTransport": "false"}}
}
]
});
iam.set_policy(
"tls-only",
Policy::parse_config(&serde_json::to_vec(&doc).expect("encode policy")).expect("parse policy"),
)
.await
.expect("store policy");
iam.policy_db_set(user, UserType::Reg, false, "tls-only")
.await
.expect("attach policy");
let context = Arc::new(AppContext::new(store, Arc::new(ReadyIam(iam)), Arc::new(TestKms)));
assert!(context.publish_action_credentials(Credentials {
access_key: "tls-test-root".to_owned(),
secret_key: "tls-root-secret".to_owned(),
status: "on".to_owned(),
..Default::default()
}));
publish_test_app_context(context);
let proxy_peer: std::net::SocketAddr = "10.0.0.2:4430".parse().expect("proxy socket");
let client_ip: std::net::IpAddr = "198.51.100.42".parse().expect("client ip");
let build_req = |proto: Option<&str>, trusted: bool, method: http::Method, body: &str| {
let mut builder = TestRequest::new(method, "/")
.extension(Some(RemoteAddr(proxy_peer)))
// Spoofed header must never satisfy aws:SecureTransport without verified ClientInfo.
.header("x-forwarded-proto", "https")
.credentials(user, secret, None)
.body(body.to_owned());
if trusted {
builder = builder.extension(ClientInfo::from_trusted_proxy(
client_ip,
None,
proto.map(str::to_owned),
proxy_peer.ip(),
1,
ValidationMode::Strict,
Vec::new(),
));
} else if proto.is_some() {
builder = builder.extension(ClientInfo::direct(proxy_peer));
}
builder.build()
};
for (label, proto, trusted, allowed) in [
("trusted-https", Some("https"), true, true),
("trusted-http", Some("http"), true, false),
("trusted-missing-proto", None, true, false),
("spoofed-direct-header", Some("https"), false, false),
("spoofed-no-client-info", None, false, false),
] {
let req = build_req(proto, trusted, http::Method::GET, "");
let gate = authorize_admin_envelope(req.envelope(), vec![admin_action()]).await;
if allowed {
gate.unwrap_or_else(|err| panic!("{label}: trusted https must satisfy aws:SecureTransport=true: {err}"));
} else {
assert_access_denied(gate.map(|_| ()));
}
let is_admin_resp = crate::admin::handlers::is_admin::IsAdminHandler {}
.call(build_req(proto, trusted, http::Method::GET, ""), matchit::Params::new())
.await
.expect("is_admin responds 200");
let (_status, _headers, mut body) = is_admin_resp.into_parts();
let json: serde_json::Value =
serde_json::from_slice(&body.store_all_limited(4096).await.expect("read body")).expect("parse json");
assert_eq!(json["is_admin"], allowed, "{label}");
let sts_err = crate::admin::handlers::sts::AssumeRoleHandle {}
.call(
build_req(proto, trusted, http::Method::POST, "Action=AssumeRole&Version=invalid"),
matchit::Params::new(),
)
.await
.expect_err("invalid STS version or denied");
if allowed {
assert_eq!(sts_err.code(), &rustfs_s3_types::S3ErrorCode::InvalidArgument, "{label}");
} else {
assert_eq!(sts_err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied, "{label}");
}
}
if let Some(previous) = previous {
publish_test_app_context(previous);
}
});
}
#[test]
#[serial_test::serial]
fn admin_auth_uses_request_server_context_slot_for_accountinfo_and_heal() {
crate::app::gating_test_env::run_large_stack_test("admin-multi-instance-context", || async {
use crate::admin::operation::Operation;
use crate::admin::operation::test_support::TestRequest;
use crate::admin::runtime_sources::{
AppContext, IamInterface, KmsInterface, ServerContextSlot, publish_test_app_context,
};
use rustfs_iam::store::object::ObjectStore;
use rustfs_madmin::{AccountStatus, AddOrUpdateUserReq};
use std::sync::Arc;
struct ReadyIam(Arc<rustfs_iam::sys::IamSys<ObjectStore>>);
impl IamInterface for ReadyIam {
fn handle(&self) -> Arc<rustfs_iam::sys::IamSys<ObjectStore>> {
Arc::clone(&self.0)
}
fn is_ready(&self) -> bool {
true
}
}
struct TestKms;
impl KmsInterface for TestKms {
fn handle(&self) -> Arc<rustfs_kms::KmsServiceManager> {
Arc::new(rustfs_kms::KmsServiceManager::new())
}
}
let previous = crate::runtime_sources::current_app_context();
let (_dir_a, _paths_a, store_a) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
let (_dir_b, _paths_b, store_b) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
for store in [&store_a, &store_b] {
ObjectStore::new(Arc::clone(store))
.save_iam_config(
serde_json::json!({"version": 1}),
format!("{}/format.json", *rustfs_iam::store::object::IAM_CONFIG_PREFIX),
)
.await
.expect("seed IAM format");
}
let iam_a = rustfs_iam::build_iam_sys(Arc::clone(&store_a)).await.expect("init IAM A");
let iam_b = rustfs_iam::build_iam_sys(Arc::clone(&store_b)).await.expect("init IAM B");
iam_a
.create_user(
"alice-server-a",
&AddOrUpdateUserReq {
secret_key: "alice-secret-1234".to_owned(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create alice on server A");
iam_a
.set_policy(
"a-all",
Policy::parse_config(br#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:*"]}]}"#)
.expect("parse policy A"),
)
.await
.expect("save policy A");
iam_a
.policy_db_set("alice-server-a", UserType::Reg, false, "a-all")
.await
.expect("attach policy A");
iam_a
.create_user(
"split-brain-user",
&AddOrUpdateUserReq {
secret_key: "split-secret-a-1234".to_owned(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create unprivileged split-brain-user on server A");
iam_b
.create_user(
"bob-server-b",
&AddOrUpdateUserReq {
secret_key: "bob-secret-1234".to_owned(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create bob on server B");
iam_b
.create_user(
"split-brain-user",
&AddOrUpdateUserReq {
secret_key: "split-secret-b-1234".to_owned(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create privileged split-brain-user on server B");
iam_b
.set_policy(
"b-heal",
Policy::parse_config(br#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:Heal"]}]}"#)
.expect("parse policy B"),
)
.await
.expect("save policy B");
iam_b
.policy_db_set("bob-server-b", UserType::Reg, false, "b-heal")
.await
.expect("attach policy B");
iam_b
.set_policy(
"b-create-user",
Policy::parse_config(
br#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:CreateUser"]}]}"#,
)
.expect("parse create-user policy B"),
)
.await
.expect("save create-user policy B");
iam_b
.policy_db_set("split-brain-user", UserType::Reg, false, "b-create-user")
.await
.expect("attach create-user policy B");
// Server A is the process-ambient global context.
let context_a = Arc::new(AppContext::new(store_a, Arc::new(ReadyIam(iam_a)), Arc::new(TestKms)));
assert!(context_a.publish_action_credentials(Credentials {
access_key: "root-server-a".to_owned(),
secret_key: "root-a-secret-1234".to_owned(),
status: "on".to_owned(),
..Default::default()
}));
publish_test_app_context(context_a);
// Server B runs in the same process with its own ServerContextSlot and root credentials.
let context_b = Arc::new(AppContext::new(store_b, Arc::new(ReadyIam(iam_b)), Arc::new(TestKms)));
assert!(context_b.publish_action_credentials(Credentials {
access_key: "root-server-b".to_owned(),
secret_key: "root-b-secret-1234".to_owned(),
status: "on".to_owned(),
..Default::default()
}));
let slot_b = ServerContextSlot::new();
assert!(slot_b.install(Arc::clone(&context_b)));
// 1. Server A's root and IAM user must NEVER authenticate against Server B's slot
// or direct `check_admin_key_valid_with_context` (used by table_catalog/plugin/listen).
for (access_key, secret_key) in [
("root-server-a", "root-a-secret-1234"),
("alice-server-a", "alice-secret-1234"),
] {
let direct_err = check_admin_key_valid_with_context("", access_key, Some(context_b.as_ref()))
.await
.expect_err("direct context-scoped key check must reject server A identity on server B");
assert_eq!(direct_err.code(), &rustfs_s3_types::S3ErrorCode::InvalidAccessKeyId, "{access_key}");
let req = TestRequest::new(http::Method::GET, "/rustfs/admin/v3/accountinfo")
.extension(slot_b.clone())
.credentials(access_key, secret_key, None)
.build();
let auth_err =
authenticate_envelope_credentials_with_context(req.credentials().expect("test cred"), req.envelope())
.await
.expect_err("server A identity must not authenticate on server B");
assert_eq!(auth_err.code(), &rustfs_s3_types::S3ErrorCode::InvalidAccessKeyId, "{access_key}");
let acct_err = crate::admin::handlers::account_info::AccountInfoHandler {}
.call(req, matchit::Params::new())
.await
.expect_err("AccountInfoHandler must reject server A identity on server B");
assert_eq!(acct_err.code(), &rustfs_s3_types::S3ErrorCode::InvalidAccessKeyId, "{access_key}");
let heal_req = TestRequest::new(http::Method::POST, "/rustfs/admin/v3/heal")
.extension(slot_b.clone())
.credentials(access_key, secret_key, None)
.build();
let heal_err = crate::admin::handlers::heal::HealHandler {}
.call(heal_req, matchit::Params::new())
.await
.expect_err("HealHandler must reject server A identity on server B");
assert_eq!(heal_err.code(), &rustfs_s3_types::S3ErrorCode::InvalidAccessKeyId, "{access_key}");
}
// 2. An empty ServerContextSlot fails closed on slot-scoped paths rather than falling back to Server A.
let empty_slot = ServerContextSlot::new();
let empty_req = TestRequest::new(http::Method::GET, "/rustfs/admin/v3/accountinfo")
.extension(empty_slot)
.credentials("root-server-a", "root-a-secret-1234", None)
.build();
let empty_err = authorize_admin_envelope_with_context_and_scope(
empty_req.envelope(),
vec![admin_action()],
AdminResourceScope::bucket_object("", ""),
)
.await
.expect_err("uninstalled server slot must fail closed");
assert_eq!(empty_err.code(), &rustfs_s3_types::S3ErrorCode::ServiceUnavailable);
// 3. Server B's own root and IAM user authenticate and authorize against Server B's slot.
let (direct_root_b, direct_root_b_owner) =
check_admin_key_valid_with_context("", "root-server-b", Some(context_b.as_ref()))
.await
.expect("direct context-scoped key check must authenticate server B root");
assert_eq!(direct_root_b.access_key, "root-server-b");
assert!(direct_root_b_owner);
let root_b_req = TestRequest::new(http::Method::GET, "/rustfs/admin/v3/accountinfo")
.extension(slot_b.clone())
.credentials("root-server-b", "root-b-secret-1234", None)
.build();
let (cred_b, is_owner_b) = authenticate_envelope_credentials_with_context(
root_b_req.credentials().expect("test cred"),
root_b_req.envelope(),
)
.await
.expect("server B root must authenticate on server B");
assert_eq!(cred_b.access_key, "root-server-b");
assert!(is_owner_b);
let acct_resp = crate::admin::handlers::account_info::AccountInfoHandler {}
.call(root_b_req, matchit::Params::new())
.await
.expect("server B root must succeed on AccountInfoHandler");
let (status, _headers, mut body) = acct_resp.into_parts();
assert_eq!(status, http::StatusCode::OK);
let payload: serde_json::Value =
serde_json::from_slice(&body.store_all_limited(65_536).await.expect("read body")).expect("parse json");
assert_eq!(payload["account_name"], "root-server-b");
// Server B's user with admin:Heal clears HealHandler authentication & authorization.
let bob_heal_req = TestRequest::new(http::Method::POST, "/rustfs/admin/v3/heal")
.extension(slot_b.clone())
.credentials("bob-server-b", "bob-secret-1234", None)
.body("{invalid-json")
.build();
let bob_heal_err = crate::admin::handlers::heal::HealHandler {}
.call(bob_heal_req, matchit::Params::new())
.await
.expect_err("malformed heal body should fail after authz");
assert_ne!(bob_heal_err.code(), &rustfs_s3_types::S3ErrorCode::InvalidAccessKeyId);
assert_ne!(bob_heal_err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied);
// Server B's user without admin:ServerInfo is denied by Server B's IAM on slot-scoped gate.
let bob_info_req = TestRequest::new(http::Method::GET, "/rustfs/admin/v3/info")
.extension(slot_b.clone())
.credentials("bob-server-b", "bob-secret-1234", None)
.build();
assert_access_denied(
authorize_admin_envelope_with_context_and_scope(
bob_info_req.envelope(),
vec![admin_action()],
AdminResourceScope::bucket_object("", ""),
)
.await
.map(|_| ()),
);
// 4. Zero split-brain on ambient-store admin gates:
// (a) `validate_admin_request(..., req.envelope())` keeps IAM ambient (Server A), so
// an unprivileged Server A user whose name holds `admin:CreateUser` on Server B
// must NOT pass authz against Server A's ambient IAM.
let split_req = TestRequest::new(http::Method::PUT, "/rustfs/admin/v3/add-user?accessKey=victim")
.extension(slot_b.clone())
.credentials("split-brain-user", "split-secret-a-1234", None)
.build();
let split_cred = Credentials {
access_key: "split-brain-user".to_owned(),
secret_key: "split-secret-a-1234".to_owned(),
status: "on".to_owned(),
..Default::default()
};
assert_access_denied(
validate_admin_request(
split_req.headers(),
&split_cred,
false,
false,
vec![Action::AdminAction(AdminAction::CreateUserAdminAction)],
split_req.envelope(),
)
.await,
);
// (b) `authorize_admin_envelope(req.envelope(), ...)` stays ambient across both auth
// and authz, so a Server B-only admin cannot authenticate on Server B and mutate
// Server A's ambient IAM/stores.
let bob_ambient_req = TestRequest::new(http::Method::GET, "/rustfs/admin/v3/list-groups")
.extension(slot_b.clone())
.credentials("bob-server-b", "bob-secret-1234", None)
.build();
let bob_ambient_err =
authorize_admin_envelope(bob_ambient_req.envelope(), vec![Action::AdminAction(AdminAction::HealAdminAction)])
.await
.expect_err("Server B identity must not pass ambient authorize_admin_envelope");
assert_eq!(bob_ambient_err.code(), &rustfs_s3_types::S3ErrorCode::InvalidAccessKeyId);
// (c) Ambient `CallerIdentity::resolve_envelope` rejects Server B identities while
// slot-scoped `CallerIdentity::resolve_envelope_with_context` resolves them.
let caller_ambient_err =
crate::admin::service::caller_identity::CallerIdentity::resolve_envelope(bob_ambient_req.envelope())
.await
.expect_err("ambient CallerIdentity must stay in Server A");
assert_eq!(caller_ambient_err.code(), &rustfs_s3_types::S3ErrorCode::InvalidAccessKeyId);
let caller_scoped =
crate::admin::service::caller_identity::CallerIdentity::resolve_envelope_with_context(bob_ambient_req.envelope())
.await
.expect("slot-scoped CallerIdentity must resolve Server B identity");
assert_eq!(caller_scoped.access_key, "bob-server-b");
if let Some(previous) = previous {
publish_test_app_context(previous);
}
});
}
}
+1 -1
View File
@@ -380,7 +380,7 @@ impl Operation for SetUserSecretKeyHandler {
caller.is_owner,
false,
vec![Action::AdminAction(AdminAction::CreateUserAdminAction)],
req.policy_source_addr(),
req.envelope(),
)
.await
.inspect_err(|_| {
+16 -9
View File
@@ -12,17 +12,19 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::admin::auth::authenticate_envelope_credentials;
use crate::admin::auth::{
action_credentials_from_envelope, authenticate_envelope_credentials_with_context, ready_iam_handle_from_envelope,
};
use crate::admin::operation::{AdminRequest, AdminResponse, Operation};
use crate::admin::router::{AdminOperation, S3Router};
use crate::admin::runtime_sources::{current_action_credentials, object_store_from_envelope};
use crate::admin::runtime_sources::object_store_from_envelope;
use crate::admin::service::caller_identity::{OidcProfileFields, oidc_profile_fields};
use crate::admin::storage_api::bucket::versioning_sys::BucketVersioningSys;
use crate::admin::storage_api::contract::admin::StorageAdminApi;
use crate::admin::storage_api::contract::bucket::{BucketOperations, BucketOptions};
use crate::admin::storage_api::data_usage::{load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin};
use crate::admin::storage_api::metadata_sys;
use crate::auth::get_condition_values;
use crate::auth::get_condition_values_with_client_info;
use crate::server::ADMIN_PREFIX;
use http::header::CONTENT_TYPE;
use http::{HeaderMap, HeaderValue};
@@ -173,18 +175,23 @@ impl Operation for AccountInfoHandler {
return Err(s3_error!(InvalidRequest, "get cred failed"));
};
let (cred, owner) = authenticate_envelope_credentials(input_cred).await?;
let (cred, owner) = authenticate_envelope_credentials_with_context(input_cred, req.envelope()).await?;
let Ok(iam_store) = crate::admin::runtime_sources::current_ready_iam_handle() else {
return Err(s3_error!(InvalidRequest, "iam not init"));
};
let iam_store = ready_iam_handle_from_envelope(Some(req.envelope())).map_err(|err| {
if err.code() == &S3ErrorCode::ServiceUnavailable {
err
} else {
s3_error!(InvalidRequest, "iam not init")
}
})?;
let default_claims = HashMap::new();
let claims = cred.claims.as_ref().unwrap_or(&default_claims);
let cred_clone = cred.clone();
let remote_addr = req.policy_source_addr();
let conditions = get_condition_values(req.headers(), &cred_clone, None, None, remote_addr);
let conditions =
get_condition_values_with_client_info(req.headers(), &cred_clone, None, None, remote_addr, req.client_info());
let cred_clone = Arc::new(cred_clone);
let conditions = Arc::new(conditions);
@@ -250,7 +257,7 @@ impl Operation for AccountInfoHandler {
cred.access_key.clone()
};
let Some(admin_cred) = current_action_credentials() else {
let Some(admin_cred) = action_credentials_from_envelope(req.envelope()) else {
return Err(S3Error::with_message(
S3ErrorCode::InternalError,
"action credentials are not initialized".to_string(),
@@ -19,13 +19,13 @@
//! use an empty object; table/view creation checks use their parent namespace resource.
use crate::admin::auth::{
AdminResourceScope, authenticate_envelope_credentials, validate_admin_action_with_bucket_object_for_iam,
AdminResourceScope, authenticate_envelope_credentials_with_context, validate_admin_action_with_bucket_object_for_iam,
};
use crate::admin::operation::{AdminRequest, AdminResponse, Operation};
use crate::admin::router::{AdminOperation, S3Router};
use crate::admin::runtime_sources::current_ready_iam_handle;
use crate::app::RequestEnvelope;
use crate::auth::get_condition_values;
use crate::auth::get_condition_values_with_client_info;
use crate::server::ADMIN_PREFIX;
use crate::storage::authorization::AuthorizationRequest;
use crate::storage::authorization::{authorize_request_core, query_list_buckets_permission, s3_action_potential};
@@ -561,7 +561,14 @@ async fn evaluate_check(
potential: None,
});
};
let conditions = get_condition_values(probe.headers(), cred, None, None, envelope.policy_source_addr());
let conditions = get_condition_values_with_client_info(
probe.headers(),
cred,
None,
None,
envelope.policy_source_addr(),
envelope.client_info(),
);
let bucket = bucket.unwrap_or_default();
let object = check.key_id.as_deref().or(object).unwrap_or_default();
let args = Args {
@@ -584,16 +591,8 @@ async fn evaluate_check(
let scope = AdminResourceScope::bucket_object(bucket, object);
(
classify(
validate_admin_action_with_bucket_object_for_iam(
iam,
probe.headers(),
cred,
owner,
action,
envelope.policy_source_addr(),
scope,
)
.await,
validate_admin_action_with_bucket_object_for_iam(iam, probe.headers(), cred, owner, action, envelope, scope)
.await,
),
None,
)
@@ -614,7 +613,7 @@ impl Operation for AccountPermissionsHandler {
let credentials = req
.credentials()
.ok_or_else(|| s3_error!(AccessDenied, "authentication required"))?;
let (cred, owner) = authenticate_envelope_credentials(credentials).await?;
let (cred, owner) = authenticate_envelope_credentials_with_context(credentials, req.envelope()).await?;
let body = req
.take_body()
.store_all_limited(MAX_BODY_SIZE)
+1 -2
View File
@@ -128,14 +128,13 @@ async fn authenticate_admin(req: &AdminRequest) -> S3Result<()> {
let (cred, owner) =
check_key_valid(get_session_token(req.uri(), req.headers()).unwrap_or_default(), cred.access_key()).await?;
let remote_addr = req.policy_source_addr();
validate_admin_request(
req.headers(),
&cred,
owner,
false,
vec![Action::AdminAction(AdminAction::ConfigUpdateAdminAction)],
remote_addr,
req.envelope(),
)
.await?;
+1 -2
View File
@@ -125,14 +125,13 @@ async fn authenticate_admin(req: &AdminRequest) -> S3Result<()> {
let (cred, owner) =
check_key_valid(get_session_token(req.uri(), req.headers()).unwrap_or_default(), cred.access_key()).await?;
let remote_addr = req.policy_source_addr();
validate_admin_request(
req.headers(),
&cred,
owner,
false,
vec![Action::AdminAction(AdminAction::ConfigUpdateAdminAction)],
remote_addr,
req.envelope(),
)
.await?;
+3 -3
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::admin::auth::{authenticate_envelope_credentials, validate_admin_request};
use crate::admin::auth::{AdminRequestOrigin, authenticate_envelope_credentials_with_context, validate_admin_request};
use crate::admin::operation::{AdminRequest, AdminResponse, Operation};
use crate::admin::router::{AdminOperation, S3Router};
use crate::admin::runtime_sources::app_context_from_envelope;
@@ -1471,7 +1471,7 @@ async fn authenticate_heal_admin_request(req: &AdminRequest) -> S3Result<String>
return Err(s3_error!(InvalidRequest, "authentication required"));
};
let (cred, owner) = authenticate_envelope_credentials(input_cred).await?;
let (cred, owner) = authenticate_envelope_credentials_with_context(input_cred, req.envelope()).await?;
validate_admin_request(
req.headers(),
@@ -1479,7 +1479,7 @@ async fn authenticate_heal_admin_request(req: &AdminRequest) -> S3Result<String>
owner,
false,
vec![Action::AdminAction(AdminAction::HealAdminAction)],
req.policy_source_addr(),
AdminRequestOrigin::with_server_context(req.envelope()),
)
.await?;
Ok(cred.access_key)
+126 -9
View File
@@ -976,15 +976,7 @@ async fn authorize(req: &AdminRequest, action: AdminAction) -> S3Result<(StoredC
}
async fn authorize_action(req: &AdminRequest, cred: &StoredCredentials, owner: bool, action: AdminAction) -> S3Result<()> {
validate_admin_request(
req.headers(),
cred,
owner,
false,
vec![Action::AdminAction(action)],
req.policy_source_addr(),
)
.await
validate_admin_request(req.headers(), cred, owner, false, vec![Action::AdminAction(action)], req.envelope()).await
}
fn json_response<T: Serialize>(path: &str, secret_key: &str, status: StatusCode, payload: &T) -> S3Result<AdminResponse> {
@@ -1198,4 +1190,129 @@ mod tests {
);
assert_eq!(expiration_for_admin_path("/rustfs/admin/v3/idp/ldap/list-access-keys", None), None);
}
#[test]
#[serial_test::serial]
fn provider_bulk_access_keys_requires_list_users_for_cross_user_queries() {
crate::app::gating_test_env::run_large_stack_test("idp-bulk-list-users", || async {
use crate::admin::operation::test_support::TestRequest;
use crate::admin::runtime_sources::{AppContext, IamInterface, KmsInterface, publish_test_app_context};
use rustfs_iam::store::{Store as _, UserType};
use rustfs_madmin::{AccountStatus, AddOrUpdateUserReq};
use rustfs_policy::policy::Policy;
use std::sync::Arc;
struct ReadyIam(Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>>);
impl IamInterface for ReadyIam {
fn handle(&self) -> Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>> {
Arc::clone(&self.0)
}
fn is_ready(&self) -> bool {
true
}
}
struct TestKms;
impl KmsInterface for TestKms {
fn handle(&self) -> Arc<rustfs_kms::KmsServiceManager> {
Arc::new(rustfs_kms::KmsServiceManager::new())
}
}
let previous = crate::runtime_sources::current_app_context();
let (_dir, _paths, store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
rustfs_iam::store::object::ObjectStore::new(Arc::clone(&store))
.save_iam_config(
serde_json::json!({"version": 1}),
format!("{}/format.json", *rustfs_iam::store::object::IAM_CONFIG_PREFIX),
)
.await
.expect("seed IAM format");
let iam = rustfs_iam::build_iam_sys(Arc::clone(&store)).await.expect("init IAM");
let secret = "idp-bulk-secret-1234";
for (user, doc) in [
(
"idp-sa-only",
Some(r#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:ListServiceAccounts"]}]}"#),
),
(
"idp-sa-and-users",
Some(
r#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:ListServiceAccounts","admin:ListUsers"]}]}"#,
),
),
("other-user", None),
] {
iam.create_user(
user,
&AddOrUpdateUserReq {
secret_key: secret.to_owned(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create user");
if let Some(doc) = doc {
iam.set_policy(user, Policy::parse_config(doc.as_bytes()).expect("parse policy"))
.await
.expect("save policy");
iam.policy_db_set(user, UserType::Reg, false, user)
.await
.expect("attach policy");
}
}
let context = Arc::new(AppContext::new(store, Arc::new(ReadyIam(iam)), Arc::new(TestKms)));
assert!(context.publish_action_credentials(StoredCredentials {
access_key: "idp-bulk-root".to_owned(),
secret_key: "idp-bulk-root-secret".to_owned(),
status: "on".to_owned(),
..Default::default()
}));
publish_test_app_context(context);
for (handler, prefix) in [
(ListAccessKeysProviderBulk::ldap(), "/rustfs/admin/v3/idp/ldap/list-access-keys-bulk"),
(ListAccessKeysProviderBulk::openid(), "/rustfs/admin/v3/idp/openid/list-access-keys-bulk"),
] {
let self_ok = handler
.call(
TestRequest::new(Method::GET, format!("{prefix}?users=idp-sa-only").as_str())
.credentials("idp-sa-only", secret, None)
.build(),
Params::new(),
)
.await
.expect("self provider bulk list with ListServiceAccounts should succeed");
assert_eq!(self_ok.into_parts().0, StatusCode::OK);
for suffix in ["?users=other-user", "?all=true"] {
let denied = handler
.call(
TestRequest::new(Method::GET, format!("{prefix}{suffix}").as_str())
.credentials("idp-sa-only", secret, None)
.build(),
Params::new(),
)
.await
.expect_err("cross-user or all=true provider bulk list must require ListUsers");
assert_eq!(denied.code(), &S3ErrorCode::AccessDenied, "{prefix}{suffix}");
let allowed = handler
.call(
TestRequest::new(Method::GET, format!("{prefix}{suffix}").as_str())
.credentials("idp-sa-and-users", secret, None)
.build(),
Params::new(),
)
.await
.expect("caller with ListServiceAccounts + ListUsers should succeed");
assert_eq!(allowed.into_parts().0, StatusCode::OK, "{prefix}{suffix}");
}
}
if let Some(previous) = previous {
publish_test_app_context(previous);
}
});
}
}
+9 -2
View File
@@ -14,7 +14,7 @@
use crate::admin::operation::{AdminRequest, AdminResponse, Operation};
use crate::admin::runtime_sources::current_action_credentials;
use crate::auth::{check_key_valid, constant_time_eq, get_condition_values, get_session_token};
use crate::auth::{check_key_valid, constant_time_eq, get_condition_values_with_client_info, get_session_token};
use http::header::CONTENT_TYPE;
use http::{HeaderMap, HeaderValue};
use hyper::StatusCode;
@@ -66,7 +66,14 @@ impl Operation for IsAdminHandler {
let empty_claims = HashMap::new();
let iam_store = crate::admin::runtime_sources::current_ready_iam_handle()
.map_err(|_| s3_error!(InternalError, "iam not init"))?;
let conditions = get_condition_values(req.headers(), &cred, None, None, req.policy_source_addr());
let conditions = get_condition_values_with_client_info(
req.headers(),
&cred,
None,
None,
req.policy_source_addr(),
req.client_info(),
);
iam_store
.is_allowed(&Args {
account: &cred.access_key,
+6 -1
View File
@@ -102,6 +102,8 @@ pub(super) enum KmsAdminOperation {
Reconfigure,
/// Reload of the persisted configuration.
Reload,
/// Read-only status query for the KMS service.
Status,
/// Start or restart of the KMS service.
Start,
/// Stop of the KMS service.
@@ -129,6 +131,7 @@ impl KmsAdminOperation {
Self::Configure => "Configure",
Self::Reconfigure => "Reconfigure",
Self::Reload => "Reload",
Self::Status => "Status",
Self::Start => "Start",
Self::Stop => "Stop",
Self::Backup => "Backup",
@@ -158,7 +161,7 @@ impl KmsAdminOperation {
// event-name space is a fixed 64-bit mask that is nearly full, so
// these reuse the existing access event rather than claiming two
// more bits of it.
Self::Backup | Self::BackupStatus | Self::RestoreDryRun => EventName::KmsKeyAccessed,
Self::Backup | Self::BackupStatus | Self::RestoreDryRun | Self::Status => EventName::KmsKeyAccessed,
// A restore publishes key material into the target directory.
Self::Restore => EventName::KmsKeyCreated,
// Aborting an interrupted restore removes the material a partial
@@ -665,6 +668,8 @@ mod tests {
KmsAdminOperation::UntagResource,
KmsAdminOperation::Configure,
KmsAdminOperation::Reconfigure,
KmsAdminOperation::Reload,
KmsAdminOperation::Status,
KmsAdminOperation::Start,
KmsAdminOperation::Stop,
KmsAdminOperation::Backup,
+1 -1
View File
@@ -919,7 +919,7 @@ async fn authorize(
let audit = KmsAdminAudit::from_envelope(req.envelope(), &cred);
audit.gate_admin(
validate_admin_request(req.headers(), &cred, owner, false, actions, req.policy_source_addr()).await,
validate_admin_request(req.headers(), &cred, owner, false, actions, req.envelope()).await,
operation,
None,
)?;
+42 -38
View File
@@ -854,7 +854,7 @@ impl Operation for ConfigureKmsHandler {
let audit = KmsAdminAudit::from_envelope(req.envelope(), &cred);
audit.gate_admin(
validate_admin_request(req.headers(), &cred, owner, false, kms_configure_actions(), req.policy_source_addr()).await,
validate_admin_request(req.headers(), &cred, owner, false, kms_configure_actions(), req.envelope()).await,
KmsAdminOperation::Configure,
None,
)?;
@@ -999,15 +999,7 @@ impl Operation for StartKmsHandler {
let audit = KmsAdminAudit::from_envelope(req.envelope(), &cred);
audit.gate_admin(
validate_admin_request(
req.headers(),
&cred,
owner,
false,
kms_service_control_actions(),
req.policy_source_addr(),
)
.await,
validate_admin_request(req.headers(), &cred, owner, false, kms_service_control_actions(), req.envelope()).await,
KmsAdminOperation::Start,
None,
)?;
@@ -1156,15 +1148,7 @@ impl Operation for StopKmsHandler {
let audit = KmsAdminAudit::from_envelope(req.envelope(), &cred);
audit.gate_admin(
validate_admin_request(
req.headers(),
&cred,
owner,
false,
kms_service_control_actions(),
req.policy_source_addr(),
)
.await,
validate_admin_request(req.headers(), &cred, owner, false, kms_service_control_actions(), req.envelope()).await,
KmsAdminOperation::Stop,
None,
)?;
@@ -1258,15 +1242,7 @@ impl Operation for ReloadKmsHandler {
let audit = KmsAdminAudit::from_envelope(req.envelope(), &cred);
audit.gate_admin(
validate_admin_request(
req.headers(),
&cred,
owner,
false,
kms_service_control_actions(),
req.policy_source_addr(),
)
.await,
validate_admin_request(req.headers(), &cred, owner, false, kms_service_control_actions(), req.envelope()).await,
KmsAdminOperation::Reload,
None,
)?;
@@ -1352,15 +1328,17 @@ impl Operation for GetKmsStatusHandler {
let (cred, owner) =
check_key_valid(get_session_token(req.uri(), req.headers()).unwrap_or_default(), cred.access_key()).await?;
validate_admin_request(
req.headers(),
&cred,
owner,
false,
kms_service_control_actions(),
req.policy_source_addr(),
)
.await?;
let audit = KmsAdminAudit::from_envelope(req.envelope(), &cred);
// Audit authorization denials through `gate_admin` to match the rest of
// the KMS dynamic handler family (rustfs/backlog#1886). Successful
// status reads intentionally skip `audit.finish` so polling does not
// flood the audit trail.
audit.gate_admin(
validate_admin_request(req.headers(), &cred, owner, false, kms_service_control_actions(), req.envelope()).await,
KmsAdminOperation::Status,
None,
)?;
info!(
component = LOG_COMPONENT_ADMIN,
@@ -1446,7 +1424,7 @@ impl Operation for ReconfigureKmsHandler {
let audit = KmsAdminAudit::from_envelope(req.envelope(), &cred);
audit.gate_admin(
validate_admin_request(req.headers(), &cred, owner, false, kms_configure_actions(), req.policy_source_addr()).await,
validate_admin_request(req.headers(), &cred, owner, false, kms_configure_actions(), req.envelope()).await,
KmsAdminOperation::Reconfigure,
None,
)?;
@@ -2252,4 +2230,30 @@ mod tests {
assert!(message.contains("10.0.0.2:9000"));
assert!(message.contains("10.0.0.3:9000"));
}
#[test]
fn get_kms_status_handler_audits_denials_via_gate_admin_without_polling_finish_noise() {
let production = include_str!("kms_dynamic.rs")
.split("\n#[cfg(test)]\n")
.next()
.expect("production source must precede tests");
let status_block = production
.split_once("impl Operation for GetKmsStatusHandler")
.and_then(|(_, rest)| rest.split_once("/// Reconfigure KMS service handler"))
.map(|(block, _)| block)
.expect("GetKmsStatusHandler block should exist");
assert!(
status_block.contains("KmsAdminAudit::from_envelope(req.envelope(), &cred)"),
"GetKmsStatusHandler must construct KmsAdminAudit from the request envelope"
);
assert!(
status_block.contains("audit.gate_admin(") && status_block.contains("KmsAdminOperation::Status"),
"GetKmsStatusHandler must wrap validate_admin_request in audit.gate_admin for KmsAdminOperation::Status"
);
assert!(
!status_block.contains("audit.finish("),
"GetKmsStatusHandler should only audit authorization denials via gate_admin to avoid polling noise"
);
}
}
@@ -272,7 +272,7 @@ async fn handle_lifecycle_request(
owner,
false,
actions,
req.policy_source_addr(),
req.envelope(),
scoped.as_deref().unwrap_or_default(),
)
.await,
@@ -329,7 +329,7 @@ async fn handle_metadata_request(
owner,
false,
actions,
req.policy_source_addr(),
req.envelope(),
scoped.as_deref().unwrap_or_default(),
)
.await,
+9 -9
View File
@@ -321,7 +321,7 @@ impl Operation for CreateKeyHandler {
let audit = KmsAdminAudit::from_envelope(req.envelope(), &cred);
audit.gate(
validate_admin_request(req.headers(), &cred, owner, false, kms_create_key_actions(), req.policy_source_addr()).await,
validate_admin_request(req.headers(), &cred, owner, false, kms_create_key_actions(), req.envelope()).await,
KmsAuditOperation::CreateKey,
None,
)?;
@@ -412,7 +412,7 @@ impl Operation for DescribeKeyHandler {
owner,
false,
kms_describe_key_actions(),
req.policy_source_addr(),
req.envelope(),
requested_key_id.as_deref().unwrap_or_default(),
)
.await,
@@ -1517,7 +1517,7 @@ impl Operation for ListKeysHandler {
let audit = KmsAdminAudit::from_envelope(req.envelope(), &cred);
audit.gate(
validate_admin_request(req.headers(), &cred, owner, false, kms_list_keys_actions(), req.policy_source_addr()).await,
validate_admin_request(req.headers(), &cred, owner, false, kms_list_keys_actions(), req.envelope()).await,
KmsAuditOperation::ListKeys,
None,
)?;
@@ -1610,7 +1610,7 @@ impl Operation for GenerateDataKeyHandler {
owner,
false,
kms_generate_data_key_actions(),
req.policy_source_addr(),
req.envelope(),
parsed.as_ref().map(|request| request.key_id.as_str()).unwrap_or_default(),
)
.await,
@@ -1685,7 +1685,7 @@ impl Operation for CreateKmsKeyHandler {
let audit = KmsAdminAudit::from_envelope(req.envelope(), &cred);
audit.gate(
validate_admin_request(req.headers(), &cred, owner, false, kms_create_key_actions(), req.policy_source_addr()).await,
validate_admin_request(req.headers(), &cred, owner, false, kms_create_key_actions(), req.envelope()).await,
KmsAuditOperation::CreateKey,
None,
)?;
@@ -1962,7 +1962,7 @@ impl Operation for DeleteKmsKeyHandler {
owner,
false,
kms_delete_key_actions(),
req.policy_source_addr(),
req.envelope(),
scoped.as_deref().unwrap_or_default(),
)
.await,
@@ -2130,7 +2130,7 @@ impl Operation for CancelKmsKeyDeletionHandler {
owner,
false,
kms_delete_key_actions(),
req.policy_source_addr(),
req.envelope(),
scoped.as_deref().unwrap_or_default(),
)
.await,
@@ -2276,7 +2276,7 @@ impl Operation for ListKmsKeysHandler {
let audit = KmsAdminAudit::from_envelope(req.envelope(), &cred);
audit.gate(
validate_admin_request(req.headers(), &cred, owner, false, kms_list_keys_actions(), req.policy_source_addr()).await,
validate_admin_request(req.headers(), &cred, owner, false, kms_list_keys_actions(), req.envelope()).await,
KmsAuditOperation::ListKeys,
None,
)?;
@@ -2489,7 +2489,7 @@ impl Operation for DescribeKmsKeyHandler {
owner,
false,
kms_describe_key_actions(),
req.policy_source_addr(),
req.envelope(),
path_key_id.as_deref().unwrap_or_default(),
)
.await,
+9 -9
View File
@@ -43,7 +43,7 @@ use super::account_audit::{
AccountAuditContext, AccountAuditFailure, AccountAuditOperation, AccountAuditRecord, MfaMethod, emit as emit_audit,
};
use super::owned_admin_json_response;
use crate::admin::auth::{SelfServiceMutation, validate_admin_request};
use crate::admin::auth::{AdminRequestOrigin, SelfServiceMutation, action_credentials_from_envelope, validate_admin_request};
use crate::admin::operation::{AdminRequest, AdminResponse, Operation};
use crate::admin::router::{AdminOperation, S3Router};
use crate::admin::runtime_sources::{current_token_signing_key, object_store_from_envelope};
@@ -151,7 +151,7 @@ fn store_from_req(req: &AdminRequest) -> S3Result<Arc<ECStore>> {
/// Resolve the caller and confirm this credential kind may manage a second
/// factor for its identity.
async fn resolve_self_service_caller(req: &AdminRequest) -> S3Result<CallerIdentity> {
let caller = CallerIdentity::resolve_envelope(req.envelope()).await?;
let caller = CallerIdentity::resolve_envelope_with_context(req.envelope()).await?;
// The MFA capability, not the password one: a root identity may enroll a
// second factor even though its secret key is fixed for the life of the
// process.
@@ -230,7 +230,7 @@ impl Operation for AccountMfaStatusHandler {
// Reading state is allowed for every credential kind: a service account
// may need to know whether its parent is protected, even though it may
// not change that.
let caller = CallerIdentity::resolve_envelope(req.envelope()).await?;
let caller = CallerIdentity::resolve_envelope_with_context(req.envelope()).await?;
let store = store_from_req(&req)?;
let status = mfa_service::status(store, &caller.access_key, OffsetDateTime::now_utc())
@@ -500,7 +500,7 @@ pub struct MfaChallengeHandler {}
#[async_trait::async_trait]
impl Operation for MfaChallengeHandler {
async fn call(&self, req: AdminRequest, _params: Params<'_, '_>) -> S3Result<AdminResponse> {
let caller = CallerIdentity::resolve_envelope(req.envelope()).await?;
let caller = CallerIdentity::resolve_envelope_with_context(req.envelope()).await?;
let audit = AccountAuditContext::from_envelope(req.envelope());
let store = store_from_req(&req)?;
let now = OffsetDateTime::now_utc();
@@ -510,7 +510,7 @@ impl Operation for MfaChallengeHandler {
.map_err(map_service_error)?;
let response = if required {
let Some(signing_key) = current_token_signing_key() else {
let Some(signing_key) = action_credentials_from_envelope(req.envelope()).map(|cred| cred.secret_key) else {
return Err(s3::error(S3ErrorCode::InternalError, "the session signing key is not initialized"));
};
let challenge = mfa_service::issue_challenge(&caller.access_key, now, signing_key.as_bytes());
@@ -566,7 +566,7 @@ pub struct UserMfaStatusHandler {}
impl Operation for UserMfaStatusHandler {
async fn call(&self, req: AdminRequest, _params: Params<'_, '_>) -> S3Result<AdminResponse> {
let target = parse_user_mfa_query(&req)?;
let caller = CallerIdentity::resolve_envelope(req.envelope()).await?;
let caller = CallerIdentity::resolve_envelope_with_context(req.envelope()).await?;
validate_admin_request(
req.headers(),
@@ -574,7 +574,7 @@ impl Operation for UserMfaStatusHandler {
caller.is_owner,
false,
vec![Action::AdminAction(AdminAction::GetUserAdminAction)],
req.policy_source_addr(),
AdminRequestOrigin::with_server_context(req.envelope()),
)
.await?;
@@ -602,7 +602,7 @@ pub struct UserMfaResetHandler {}
impl Operation for UserMfaResetHandler {
async fn call(&self, req: AdminRequest, _params: Params<'_, '_>) -> S3Result<AdminResponse> {
let target = parse_user_mfa_query(&req)?;
let caller = CallerIdentity::resolve_envelope(req.envelope()).await?;
let caller = CallerIdentity::resolve_envelope_with_context(req.envelope()).await?;
let audit = AccountAuditContext::from_envelope(req.envelope());
validate_admin_request(
@@ -611,7 +611,7 @@ impl Operation for UserMfaResetHandler {
caller.is_owner,
false,
vec![Action::AdminAction(AdminAction::EnableUserAdminAction)],
req.policy_source_addr(),
AdminRequestOrigin::with_server_context(req.envelope()),
)
.await
.inspect_err(|_| {
+3 -3
View File
@@ -5,11 +5,11 @@ use super::plugin_delegation::{owner, response, storage_error};
use crate::admin::operation::{AdminRequest, AdminResponse, Operation};
use crate::{
admin::{
auth::check_admin_key_valid_with_context,
router::{AdminOperation, S3Router},
runtime_sources,
storage_api::s3::{self, S3Error, S3ErrorCode, S3Result},
},
auth::check_key_valid_with_context,
server::ADMIN_PREFIX,
};
use http::{Method, StatusCode};
@@ -205,7 +205,7 @@ impl Operation for Issue {
.await
.map_err(storage_error)?;
let policy = session_policy(&record, &attempt)?;
let (principal, root) = check_key_valid_with_context("", &record.owner_access_key, Some(context.as_ref())).await?;
let (principal, root) = check_admin_key_valid_with_context("", &record.owner_access_key, Some(context.as_ref())).await?;
if root || principal.is_temp() || principal.is_service_account() {
return Err(s3::error(S3ErrorCode::AccessDenied, "original user required"));
}
@@ -285,7 +285,7 @@ impl Operation for Issue {
.await
.map_err(storage_error)?;
let (current, current_root) =
check_key_valid_with_context("", &record.owner_access_key, Some(context.as_ref())).await?;
check_admin_key_valid_with_context("", &record.owner_access_key, Some(context.as_ref())).await?;
let names = iam
.policy_db_get(&current.access_key, &current.groups)
.await
@@ -434,7 +434,7 @@ async fn delegation_v2_persists_and_vends_with_real_parent_intersection() {
assert_eq!(headers[http::header::CACHE_CONTROL], "no-store");
let issued: Value =
serde_json::from_slice(&issued_body.store_all_limited(1 << 20).await.expect("issued body")).expect("issued JSON");
let (credential, root) = check_key_valid_with_context(
let (credential, root) = check_admin_key_valid_with_context(
issued["session_token"].as_str().expect("token"),
issued["access_key_id"].as_str().expect("access key"),
Some(fixture.context.as_ref()),
@@ -4,16 +4,13 @@
//! Restriction registration only. These endpoints do not vend credentials.
use crate::admin::operation::{AdminRequest, AdminResponse, Operation};
use crate::admin::{
auth::{AdminResourceScope, validate_admin_action_with_bucket_object_for_iam},
auth::{AdminResourceScope, check_admin_key_valid_with_context, validate_admin_action_with_bucket_object_for_iam},
plugin_runner::{self, ObjectReference, SubmitRequest},
router::{AdminOperation, S3Router},
runtime_sources,
storage_api::s3::{self, S3Error, S3ErrorCode, S3Result},
};
use crate::{
auth::{check_key_valid_with_context, get_session_token},
server::ADMIN_PREFIX,
};
use crate::{auth::get_session_token, server::ADMIN_PREFIX};
use http::{HeaderMap, HeaderValue, Method, StatusCode};
use matchit::Params;
use rustfs_iam::delegation::{DelegationError, Restrictions};
@@ -84,7 +81,7 @@ pub(super) async fn owner(
}
let context = runtime_sources::app_context_from_envelope(req.envelope())
.ok_or_else(|| s3::error(S3ErrorCode::InternalError, "application context unavailable"))?;
let (credentials, root) = check_key_valid_with_context("", signed.access_key(), Some(context.as_ref())).await?;
let (credentials, root) = check_admin_key_valid_with_context("", signed.access_key(), Some(context.as_ref())).await?;
if root || credentials.is_temp() || credentials.is_service_account() {
return Err(s3::error(S3ErrorCode::AccessDenied, "original user required"));
}
@@ -98,7 +95,7 @@ pub(super) async fn owner(
&credentials,
false,
Action::AdminAction(action),
req.policy_source_addr(),
req.envelope(),
AdminResourceScope::bucket_object("", ""),
)
.await?;
+264 -31
View File
@@ -179,6 +179,14 @@ fn bucket_from_params_or_query(params: &Params<'_, '_>, uri: &hyper::Uri) -> Str
String::new()
}
fn validate_quota_bucket_name(bucket: &str) -> S3Result<()> {
if bucket.is_empty() {
return Err(s3_error!(InvalidRequest, "bucket name is required"));
}
crate::admin::storage_api::bucket::utils::check_valid_bucket_name_strict(bucket)
.map_err(|_| s3_error!(InvalidArgument, "invalid bucket name"))
}
fn parse_set_bucket_quota_request(body: &[u8]) -> Result<SetBucketQuotaRequest, rustfs_s3_types::S3Error> {
if body.is_empty() {
return Ok(SetBucketQuotaRequest {
@@ -486,21 +494,20 @@ impl Operation for SetBucketQuotaHandler {
let (cred, owner) =
check_key_valid(get_session_token(req.uri(), req.headers()).unwrap_or_default(), cred.access_key()).await?;
let remote_addr = req.policy_source_addr();
validate_admin_request(
let bucket = bucket_from_params_or_query(&params, req.uri());
validate_quota_bucket_name(&bucket)?;
validate_admin_request_with_bucket(
req.headers(),
&cred,
owner,
false,
vec![Action::AdminAction(AdminAction::SetBucketQuotaAdminAction)],
remote_addr,
req.envelope(),
&bucket,
)
.await?;
let bucket = bucket_from_params_or_query(&params, req.uri());
if bucket.is_empty() {
return Err(s3_error!(InvalidRequest, "bucket name is required"));
}
let expected_incarnation_id = metadata_sys::capture_bucket_metadata_incarnation(&bucket)
.await
.map_err(|e| s3_error!(InternalError, "failed to capture bucket incarnation: {}", e))?;
@@ -630,17 +637,14 @@ impl Operation for GetBucketQuotaHandler {
check_key_valid(get_session_token(req.uri(), req.headers()).unwrap_or_default(), cred.access_key()).await?;
let bucket = bucket_from_params_or_query(&params, req.uri());
if bucket.is_empty() {
return Err(s3_error!(InvalidRequest, "bucket name is required"));
}
let remote_addr = req.policy_source_addr();
validate_quota_bucket_name(&bucket)?;
validate_admin_request_with_bucket(
req.headers(),
&cred,
owner,
false,
vec![Action::S3Action(S3Action::GetBucketQuotaAction)],
remote_addr,
req.envelope(),
&bucket,
)
.await?;
@@ -702,21 +706,20 @@ impl Operation for ClearBucketQuotaHandler {
let (cred, owner) =
check_key_valid(get_session_token(req.uri(), req.headers()).unwrap_or_default(), cred.access_key()).await?;
let remote_addr = req.policy_source_addr();
validate_admin_request(
let bucket = params.get("bucket").unwrap_or("").to_string();
validate_quota_bucket_name(&bucket)?;
validate_admin_request_with_bucket(
req.headers(),
&cred,
owner,
false,
vec![Action::AdminAction(AdminAction::SetBucketQuotaAdminAction)],
remote_addr,
req.envelope(),
&bucket,
)
.await?;
let bucket = params.get("bucket").unwrap_or("").to_string();
if bucket.is_empty() {
return Err(s3_error!(InvalidRequest, "bucket name is required"));
}
let expected_incarnation_id = metadata_sys::capture_bucket_metadata_incarnation(&bucket)
.await
.map_err(|e| s3_error!(InternalError, "failed to capture bucket incarnation: {}", e))?;
@@ -821,18 +824,15 @@ impl Operation for GetBucketQuotaStatsHandler {
check_key_valid(get_session_token(req.uri(), req.headers()).unwrap_or_default(), cred.access_key()).await?;
let bucket = params.get("bucket").unwrap_or("").to_string();
if bucket.is_empty() {
return Err(s3_error!(InvalidRequest, "bucket name is required"));
}
validate_quota_bucket_name(&bucket)?;
let remote_addr = req.policy_source_addr();
validate_admin_request_with_bucket(
req.headers(),
&cred,
owner,
false,
vec![Action::S3Action(S3Action::GetBucketQuotaAction)],
remote_addr,
req.envelope(),
&bucket,
)
.await?;
@@ -890,18 +890,15 @@ impl Operation for CheckBucketQuotaHandler {
check_key_valid(get_session_token(req.uri(), req.headers()).unwrap_or_default(), cred.access_key()).await?;
let bucket = params.get("bucket").unwrap_or("").to_string();
if bucket.is_empty() {
return Err(s3_error!(InvalidRequest, "bucket name is required"));
}
validate_quota_bucket_name(&bucket)?;
let remote_addr = req.policy_source_addr();
validate_admin_request_with_bucket(
req.headers(),
&cred,
owner,
false,
vec![Action::S3Action(S3Action::GetBucketQuotaAction)],
remote_addr,
req.envelope(),
&bucket,
)
.await?;
@@ -989,14 +986,15 @@ impl Operation for MigrateBucketQuotaProtocolHandler {
let (cred, owner) =
check_key_valid(get_session_token(req.uri(), req.headers()).unwrap_or_default(), cred.access_key()).await?;
let remote_addr = req.policy_source_addr();
// Protocol migration iterates every bucket in the cluster, so it requires
// unscoped `admin:SetBucketQuota` authority rather than a single bucket.
validate_admin_request(
req.headers(),
&cred,
owner,
false,
vec![Action::AdminAction(AdminAction::SetBucketQuotaAdminAction)],
remote_addr,
req.envelope(),
)
.await?;
@@ -1360,4 +1358,239 @@ mod tests {
assert_eq!(stats["remaining_quota"], 2048);
assert_eq!(stats["usage_percentage"], 0.0);
}
#[test]
fn quota_bucket_validation_enforces_strict_s3_bucket_naming() {
let empty_err = validate_quota_bucket_name("").expect_err("empty bucket must fail");
assert_eq!(empty_err.code(), &rustfs_s3_types::S3ErrorCode::InvalidRequest);
for invalid in [
".rustfs.sys",
".minio.sys",
"../escape",
"UPPERCASE",
"bad_bucket",
"ab",
"192.168.1.1",
] {
let err = validate_quota_bucket_name(invalid).expect_err("invalid bucket name must fail");
assert_eq!(err.code(), &rustfs_s3_types::S3ErrorCode::InvalidArgument, "invalid bucket `{invalid}`");
}
for valid in ["allowed-bucket", "data.2026", "abc"] {
validate_quota_bucket_name(valid).unwrap_or_else(|err| panic!("valid bucket `{valid}` failed: {err}"));
}
}
#[test]
#[serial_test::serial]
fn quota_write_and_read_handlers_enforce_bucket_scope_and_strict_names() {
crate::app::gating_test_env::run_large_stack_test("quota-bucket-scope", || async {
use crate::admin::operation::test_support::TestRequest;
use crate::admin::runtime_sources::{AppContext, IamInterface, KmsInterface, publish_test_app_context};
use rustfs_iam::store::{Store as _, UserType};
use rustfs_madmin::{AccountStatus, AddOrUpdateUserReq};
use rustfs_policy::policy::Policy;
use std::sync::Arc;
struct ReadyIam(Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>>);
impl IamInterface for ReadyIam {
fn handle(&self) -> Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>> {
Arc::clone(&self.0)
}
fn is_ready(&self) -> bool {
true
}
}
struct TestKms;
impl KmsInterface for TestKms {
fn handle(&self) -> Arc<rustfs_kms::KmsServiceManager> {
Arc::new(rustfs_kms::KmsServiceManager::new())
}
}
let previous = crate::runtime_sources::current_app_context();
let (_dir, _paths, store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
rustfs_iam::store::object::ObjectStore::new(Arc::clone(&store))
.save_iam_config(
serde_json::json!({"version": 1}),
format!("{}/format.json", *rustfs_iam::store::object::IAM_CONFIG_PREFIX),
)
.await
.expect("seed IAM format");
let iam = rustfs_iam::build_iam_sys(Arc::clone(&store)).await.expect("init IAM");
let scoped_user = "quota-scoped-user";
let secret = "quota-secret-1234";
iam.create_user(
scoped_user,
&AddOrUpdateUserReq {
secret_key: secret.to_owned(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create quota user");
iam.set_policy(
"quota-allowed-only",
Policy::parse_config(
br#"{
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": ["admin:SetBucketQuota"], "Resource": ["arn:aws:s3:::allowed-bucket"]},
{"Effect": "Allow", "Action": ["s3:GetBucketQuota"], "Resource": ["arn:aws:s3:::allowed-bucket"]}
]
}"#,
)
.expect("parse quota policy"),
)
.await
.expect("save quota policy");
iam.policy_db_set(scoped_user, UserType::Reg, false, "quota-allowed-only")
.await
.expect("attach quota policy");
let context = Arc::new(AppContext::new(store, Arc::new(ReadyIam(iam)), Arc::new(TestKms)));
assert!(context.publish_action_credentials(rustfs_credentials::Credentials {
access_key: "quota-test-root".to_owned(),
secret_key: "quota-root-secret".to_owned(),
status: "on".to_owned(),
..Default::default()
}));
publish_test_app_context(context);
let mut routes = matchit::Router::new();
routes.insert("/quota/{bucket}", ()).expect("quota route");
// Write & read handlers must deny buckets outside the granted resource scope.
let forbidden = routes.at("/quota/forbidden-bucket").expect("match forbidden");
let set_err = SetBucketQuotaHandler
.call(
TestRequest::new(Method::PUT, "/rustfs/admin/v3/quota/forbidden-bucket")
.credentials(scoped_user, secret, None)
.body(r#"{"quota":1024}"#)
.build(),
forbidden.params.clone(),
)
.await
.expect_err("SetBucketQuotaHandler must deny forbidden-bucket");
assert_eq!(set_err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied);
let compat_set_err = SetBucketQuotaHandler
.call(
TestRequest::new(Method::PUT, "/rustfs/admin/v3/set-bucket-quota?bucket=forbidden-bucket")
.credentials(scoped_user, secret, None)
.body(r#"{"quota":1024}"#)
.build(),
Params::new(),
)
.await
.expect_err("compat set-bucket-quota must deny forbidden-bucket");
assert_eq!(compat_set_err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied);
let clear_err = ClearBucketQuotaHandler
.call(
TestRequest::new(Method::DELETE, "/rustfs/admin/v3/quota/forbidden-bucket")
.credentials(scoped_user, secret, None)
.build(),
forbidden.params.clone(),
)
.await
.expect_err("ClearBucketQuotaHandler must deny forbidden-bucket");
assert_eq!(clear_err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied);
let get_err = GetBucketQuotaHandler
.call(
TestRequest::new(Method::GET, "/rustfs/admin/v3/quota/forbidden-bucket")
.credentials(scoped_user, secret, None)
.build(),
forbidden.params.clone(),
)
.await
.expect_err("GetBucketQuotaHandler must deny forbidden-bucket");
assert_eq!(get_err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied);
// Bucket-scoped SetBucketQuota must not authorize cluster-wide quota migration.
let migrate_err = MigrateBucketQuotaProtocolHandler
.call(
TestRequest::new(Method::POST, "/rustfs/admin/v3/quota-migration")
.credentials(scoped_user, secret, None)
.build(),
Params::new(),
)
.await
.expect_err("single-bucket SetBucketQuota must not authorize cluster-wide migration");
assert_eq!(migrate_err.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied);
// The granted bucket clears the authorization gate (fails later on malformed JSON, not AccessDenied).
let allowed = routes.at("/quota/allowed-bucket").expect("match allowed");
let allowed_res = SetBucketQuotaHandler
.call(
TestRequest::new(Method::PUT, "/rustfs/admin/v3/quota/allowed-bucket")
.credentials(scoped_user, secret, None)
.body("{invalid-json")
.build(),
allowed.params.clone(),
)
.await
.expect_err("malformed body should fail after authorization");
assert_ne!(allowed_res.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied);
// Reserved/invalid bucket names are rejected with InvalidArgument across all 5 bucket handlers.
let invalid = routes.at("/quota/.rustfs.sys").expect("match invalid");
for err in [
SetBucketQuotaHandler
.call(
TestRequest::new(Method::PUT, "/rustfs/admin/v3/quota/.rustfs.sys")
.credentials("quota-test-root", "quota-root-secret", None)
.build(),
invalid.params.clone(),
)
.await
.expect_err("Set must reject .rustfs.sys"),
GetBucketQuotaHandler
.call(
TestRequest::new(Method::GET, "/rustfs/admin/v3/quota/.rustfs.sys")
.credentials("quota-test-root", "quota-root-secret", None)
.build(),
invalid.params.clone(),
)
.await
.expect_err("Get must reject .rustfs.sys"),
ClearBucketQuotaHandler
.call(
TestRequest::new(Method::DELETE, "/rustfs/admin/v3/quota/.rustfs.sys")
.credentials("quota-test-root", "quota-root-secret", None)
.build(),
invalid.params.clone(),
)
.await
.expect_err("Clear must reject .rustfs.sys"),
GetBucketQuotaStatsHandler
.call(
TestRequest::new(Method::GET, "/rustfs/admin/v3/quota-stats/.rustfs.sys")
.credentials("quota-test-root", "quota-root-secret", None)
.build(),
invalid.params.clone(),
)
.await
.expect_err("Stats must reject .rustfs.sys"),
CheckBucketQuotaHandler
.call(
TestRequest::new(Method::POST, "/rustfs/admin/v3/quota-check/.rustfs.sys")
.credentials("quota-test-root", "quota-root-secret", None)
.build(),
invalid.params.clone(),
)
.await
.expect_err("Check must reject .rustfs.sys"),
] {
assert_eq!(err.code(), &rustfs_s3_types::S3ErrorCode::InvalidArgument);
}
if let Some(previous) = previous {
publish_test_app_context(previous);
}
});
}
}
+196 -8
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::admin::auth::authorize_admin_envelope;
use crate::admin::auth::{AdminResourceScope, authorize_admin_envelope, authorize_admin_envelope_with_scope};
use crate::admin::handlers::site_replication::site_replication_peer_deployment_id_for_endpoint;
use crate::admin::operation::{AdminRequest, AdminResponse, Operation};
use crate::admin::router::{AdminOperation, S3Router};
@@ -634,6 +634,15 @@ pub fn register_replication_route(r: &mut S3Router<AdminOperation>) -> std::io::
async fn validate_replication_admin_request(req: &AdminRequest, action: AdminAction) -> S3Result<Credentials> {
authorize_admin_envelope(req.envelope(), vec![Action::AdminAction(action)]).await
}
async fn validate_replication_admin_request_with_bucket(
req: &AdminRequest,
action: AdminAction,
bucket: &str,
) -> S3Result<Credentials> {
authorize_admin_envelope_with_scope(req.envelope(), vec![Action::AdminAction(action)], AdminResourceScope::bucket(bucket))
.await
}
pub(crate) async fn cluster_replication_stats(bucket: &str, context: Option<Arc<AppContext>>) -> BucketStats {
let Some(stats) = current_replication_stats_handle_for_context(context.clone()) else {
return BucketStats::default();
@@ -752,10 +761,14 @@ pub struct SetRemoteTargetHandler {}
#[async_trait::async_trait]
impl Operation for SetRemoteTargetHandler {
async fn call(&self, mut req: AdminRequest, _params: Params<'_, '_>) -> S3Result<AdminResponse> {
let cred = validate_replication_admin_request(&req, AdminAction::SetBucketTargetAction).await?;
let app_context = app_context_from_envelope(req.envelope());
let queries = extract_query_params(req.uri());
let cred = validate_replication_admin_request_with_bucket(
&req,
AdminAction::SetBucketTargetAction,
queries.get("bucket").map(String::as_str).unwrap_or(""),
)
.await?;
let app_context = app_context_from_envelope(req.envelope());
let Some(bucket) = queries.get("bucket") else {
return Err(s3_error!(InvalidRequest, "bucket is required"));
@@ -998,9 +1011,13 @@ pub struct ListRemoteTargetHandler {}
#[async_trait::async_trait]
impl Operation for ListRemoteTargetHandler {
async fn call(&self, req: AdminRequest, _params: Params<'_, '_>) -> S3Result<AdminResponse> {
validate_replication_admin_request(&req, AdminAction::GetBucketTargetAction).await?;
let queries = extract_query_params(req.uri());
validate_replication_admin_request_with_bucket(
&req,
AdminAction::GetBucketTargetAction,
queries.get("bucket").map(String::as_str).unwrap_or(""),
)
.await?;
if let Some(bucket) = queries.get("bucket") {
if bucket.is_empty() {
@@ -1063,11 +1080,16 @@ pub struct RemoveRemoteTargetHandler {}
#[async_trait::async_trait]
impl Operation for RemoveRemoteTargetHandler {
async fn call(&self, req: AdminRequest, _params: Params<'_, '_>) -> S3Result<AdminResponse> {
validate_replication_admin_request(&req, AdminAction::SetBucketTargetAction).await?;
let queries = extract_query_params(req.uri());
validate_replication_admin_request_with_bucket(
&req,
AdminAction::SetBucketTargetAction,
queries.get("bucket").map(String::as_str).unwrap_or(""),
)
.await?;
let app_context = app_context_from_envelope(req.envelope());
debug!("remove remote target called");
let queries = extract_query_params(req.uri());
let Some(bucket) = queries.get("bucket") else {
return Err(s3_error!(InvalidRequest, "bucket is required"));
};
@@ -4051,4 +4073,170 @@ mod target_repair_tests {
async fn ordinary_target_remove_rejects_malformed_persisted_replication_rules() {
assert_target_remove_checks_persisted_rules(true).await;
}
#[test]
#[serial_test::serial]
fn remote_target_handlers_enforce_query_bucket_scope() {
crate::app::gating_test_env::run_large_stack_test("remote-target-bucket-scope", || async {
use crate::admin::operation::test_support::TestRequest;
use crate::admin::runtime_sources::{AppContext, IamInterface, KmsInterface, publish_test_app_context};
use crate::admin::storage_api::contract::bucket::{BucketOperations as _, MakeBucketOptions};
use rustfs_iam::store::{Store as _, UserType};
use rustfs_madmin::{AccountStatus, AddOrUpdateUserReq};
use rustfs_policy::policy::Policy;
use std::sync::Arc;
struct ReadyIam(Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>>);
impl IamInterface for ReadyIam {
fn handle(&self) -> Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>> {
Arc::clone(&self.0)
}
fn is_ready(&self) -> bool {
true
}
}
struct TestKms;
impl KmsInterface for TestKms {
fn handle(&self) -> Arc<rustfs_kms::KmsServiceManager> {
Arc::new(rustfs_kms::KmsServiceManager::new())
}
}
let previous = crate::runtime_sources::current_app_context();
let (_dir, _paths, store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
rustfs_iam::store::object::ObjectStore::new(Arc::clone(&store))
.save_iam_config(
serde_json::json!({"version": 1}),
format!("{}/format.json", *rustfs_iam::store::object::IAM_CONFIG_PREFIX),
)
.await
.expect("seed IAM format");
store
.make_bucket("allowed-bucket", &MakeBucketOptions::default())
.await
.expect("create allowed bucket");
let iam = rustfs_iam::build_iam_sys(Arc::clone(&store)).await.expect("init IAM");
for (user, secret, doc) in [
(
"target-scoped",
"target-secret-1234",
r#"{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["admin:GetBucketTarget", "admin:SetBucketTarget"],
"Resource": ["arn:aws:s3:::allowed-bucket"]
}]
}"#,
),
(
"target-unscoped",
"target-secret-1234",
r#"{
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": ["admin:GetBucketTarget"]}]
}"#,
),
] {
iam.create_user(
user,
&AddOrUpdateUserReq {
secret_key: secret.to_owned(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create test user");
iam.set_policy(user, Policy::parse_config(doc.as_bytes()).expect("parse policy"))
.await
.expect("store policy");
iam.policy_db_set(user, UserType::Reg, false, user)
.await
.expect("attach policy");
}
let context = Arc::new(AppContext::new(store, Arc::new(ReadyIam(iam)), Arc::new(TestKms)));
assert!(context.publish_action_credentials(Credentials {
access_key: "repl-scope-root".to_owned(),
secret_key: "repl-scope-secret".to_owned(),
status: "on".to_owned(),
..Default::default()
}));
publish_test_app_context(context);
// Bucket-scoped caller is denied for another bucket and for unscoped listing.
for uri in [
"/rustfs/admin/v3/list-remote-targets?bucket=forbidden-bucket",
"/rustfs/admin/v3/list-remote-targets",
] {
let err = ListRemoteTargetHandler {}
.call(
TestRequest::new(Method::GET, uri)
.credentials("target-scoped", "target-secret-1234", None)
.build(),
Params::new(),
)
.await
.expect_err("scoped list-remote-targets must reject out-of-scope bucket");
assert_eq!(err.code(), &S3ErrorCode::AccessDenied, "{uri}");
}
// Set and remove target handlers also reject out-of-scope buckets.
let set_err = SetRemoteTargetHandler {}
.call(
TestRequest::new(Method::PUT, "/rustfs/admin/v3/set-remote-target?bucket=forbidden-bucket")
.credentials("target-scoped", "target-secret-1234", None)
.build(),
Params::new(),
)
.await
.expect_err("set-remote-target must deny forbidden-bucket");
assert_eq!(set_err.code(), &S3ErrorCode::AccessDenied);
let remove_err = RemoveRemoteTargetHandler {}
.call(
TestRequest::new(
Method::DELETE,
"/rustfs/admin/v3/remove-remote-target?bucket=forbidden-bucket&arn=arn:rustfs:replication:us-east-1:dep:target",
)
.credentials("target-scoped", "target-secret-1234", None)
.build(),
Params::new(),
)
.await
.expect_err("remove-remote-target must deny forbidden-bucket");
assert_eq!(remove_err.code(), &S3ErrorCode::AccessDenied);
// The granted bucket passes authorization on list-remote-targets.
let allowed_res = ListRemoteTargetHandler {}
.call(
TestRequest::new(Method::GET, "/rustfs/admin/v3/list-remote-targets?bucket=allowed-bucket")
.credentials("target-scoped", "target-secret-1234", None)
.build(),
Params::new(),
)
.await;
if let Err(err) = allowed_res {
assert_ne!(err.code(), &S3ErrorCode::AccessDenied, "allowed-bucket must clear the authorization gate");
}
// Unscoped policy still allows bucket-less list-remote-targets (returns []).
let unscoped_resp = ListRemoteTargetHandler {}
.call(
TestRequest::new(Method::GET, "/rustfs/admin/v3/list-remote-targets")
.credentials("target-unscoped", "target-secret-1234", None)
.build(),
Params::new(),
)
.await
.expect("unscoped GetBucketTarget must still succeed without bucket query");
assert_eq!(unscoped_resp.into_parts().0, StatusCode::OK);
if let Some(previous) = previous {
publish_test_app_context(previous);
}
});
}
}
@@ -335,7 +335,7 @@ impl ListenNotificationAuthorization {
.ok_or_else(|| S3Error::new(S3ErrorCode::AccessDenied))?;
rustfs_keystone::KEYSTONE_CREDENTIALS
.scope(keystone, async {
let (cred, is_owner) = crate::auth::check_key_valid_with_context(
let (cred, is_owner) = crate::admin::auth::check_admin_key_valid_with_context(
get_session_token(self.envelope.uri(), self.envelope.headers()).unwrap_or_default(),
&access_key,
context.as_deref(),
@@ -31,7 +31,7 @@
mod listen;
mod replication;
use crate::admin::auth::authenticate_envelope_credentials;
use crate::admin::auth::authenticate_envelope_credentials_with_context;
use crate::admin::operation::AdminRequest;
use crate::admin::route_table;
use crate::admin::router::{AdminOperation, EVENT_ADMIN_ROUTER_STATE, LOG_COMPONENT_ADMIN, S3Router};
@@ -104,7 +104,7 @@ async fn authorize(req: &mut AdminRequest, bucket: Option<&str>, action: Action)
let Some(credentials) = req.credentials() else {
return Err(S3Error::with_message(S3ErrorCode::AccessDenied, "Signature is required"));
};
let (cred, is_owner) = authenticate_envelope_credentials(credentials).await?;
let (cred, is_owner) = authenticate_envelope_credentials_with_context(credentials, req.envelope()).await?;
req.install_req_info(ReqInfo {
cred: Some(cred),
is_owner,
+179 -12
View File
@@ -18,7 +18,7 @@ use crate::admin::handlers::site_replication::{encode_service_account_replicatio
use crate::admin::operation::{AdminRequest, AdminResponse, Operation};
use crate::admin::runtime_sources::current_action_credentials;
use crate::admin::utils::{encode_compatible_admin_payload, has_space_be, is_compat_admin_request, read_compatible_admin_body};
use crate::auth::{constant_time_eq, get_condition_values, get_session_token};
use crate::auth::{constant_time_eq, get_condition_values_with_client_info, get_session_token};
use crate::server::ADMIN_PREFIX;
use crate::{
admin::router::{AdminOperation, S3Router},
@@ -514,13 +514,21 @@ impl Operation for AddServiceAccount {
};
create_req.expiration = bounded_service_account_expiration(&cred, create_req.expiration);
let mut conditions = get_condition_values(req.headers(), &cred, None, None, req.policy_source_addr());
let mut conditions =
get_condition_values_with_client_info(req.headers(), &cred, None, None, req.policy_source_addr(), req.client_info());
set_service_account_duration_condition(&mut conditions, create_req.expiration, OffsetDateTime::now_utc());
// The policy and the write must see the same resolved parent, including
// when a derived credential names itself. OPA receives this map too.
conditions.retain(|key, _| !key.eq_ignore_ascii_case(SVC_TARGET_USER));
conditions.insert(SVC_TARGET_USER.to_owned(), vec![target_user.to_owned()]);
// This family deliberately calls `is_allowed` directly instead of going
// through `validate_admin_request`, and must keep doing so
// (backlog#1886). The shared helper returns as soon as *any* candidate
// action is allowed — an OR. The checks here are an AND: each one must
// pass, and later stages additionally need `owner` for the GHSA-5354
// parent-scope guard and drive `deny_only` dynamically. Replacing these
// with the shared gate would widen authorization.
if self_scoped {
if !iam_store
.is_allowed(&Args {
@@ -712,7 +720,8 @@ impl Operation for UpdateServiceAccount {
if update_req.new_expiration.is_some() {
update_req.new_expiration = bounded_service_account_expiration(&cred, update_req.new_expiration);
}
let mut conditions = get_condition_values(req.headers(), &cred, None, None, req.policy_source_addr());
let mut conditions =
get_condition_values_with_client_info(req.headers(), &cred, None, None, req.policy_source_addr(), req.client_info());
set_service_account_duration_condition(
&mut conditions,
update_req
@@ -834,7 +843,8 @@ impl Operation for InfoServiceAccount {
// Keep lookup errors behind authorization so unauthorized callers cannot
// distinguish missing service accounts from forbidden ones.
let existing_account = iam_store.get_service_account(&access_key).await;
let conditions = get_condition_values(req.headers(), &cred, None, None, req.policy_source_addr());
let conditions =
get_condition_values_with_client_info(req.headers(), &cred, None, None, req.policy_source_addr(), req.client_info());
let claims = cred.claims_or_empty();
if !iam_store
@@ -927,7 +937,14 @@ impl Operation for TemporaryAccountInfo {
groups: &cred.groups,
action: Action::AdminAction(AdminAction::ListTemporaryAccountsAdminAction),
bucket: "",
conditions: &get_condition_values(req.headers(), &cred, None, None, req.policy_source_addr()),
conditions: &get_condition_values_with_client_info(
req.headers(),
&cred,
None,
None,
req.policy_source_addr(),
req.client_info(),
),
is_owner: owner,
object: "",
claims: cred.claims_or_empty(),
@@ -987,7 +1004,8 @@ impl Operation for InfoAccessKey {
let target_cred = iam_store.get_user(&access_key).await.map(|identity| identity.credentials);
let conditions = get_condition_values(req.headers(), &cred, None, None, req.policy_source_addr());
let conditions =
get_condition_values_with_client_info(req.headers(), &cred, None, None, req.policy_source_addr(), req.client_info());
let claims = cred.claims_or_empty();
if !iam_store
@@ -1118,7 +1136,14 @@ impl Operation for ListServiceAccount {
groups: &cred.groups,
action: Action::AdminAction(AdminAction::ListServiceAccountsAdminAction),
bucket: "",
conditions: &get_condition_values(req.headers(), &cred, None, None, req.policy_source_addr()),
conditions: &get_condition_values_with_client_info(
req.headers(),
&cred,
None,
None,
req.policy_source_addr(),
req.client_info(),
),
is_owner: owner,
object: "",
claims: cred.claims_or_empty(),
@@ -1243,19 +1268,24 @@ impl Operation for ListAccessKeysBulk {
let mut self_only = !query.all && requested_users.is_empty();
if !query.all && requested_users.len() == 1 {
let requested_user = &requested_users[0];
if requested_user == &cred.access_key || requested_user == &cred.parent_user {
if requested_user == &cred.access_key || (!cred.parent_user.is_empty() && requested_user == &cred.parent_user) {
self_only = true;
}
}
if query.all
let conditions =
get_condition_values_with_client_info(req.headers(), &cred, None, None, req.policy_source_addr(), req.client_info());
// Listing all users or any other named user requires ListUsers in addition
// to ListServiceAccounts, matching `/v3/idp/{ldap,openid}/list-access-keys-bulk`.
if (query.all || !self_only)
&& !iam_store
.is_allowed(&Args {
account: &cred.access_key,
groups: &cred.groups,
action: Action::AdminAction(AdminAction::ListUsersAdminAction),
bucket: "",
conditions: &get_condition_values(req.headers(), &cred, None, None, req.policy_source_addr()),
conditions: &conditions,
is_owner: owner,
object: "",
claims: cred.claims_or_empty(),
@@ -1272,7 +1302,7 @@ impl Operation for ListAccessKeysBulk {
groups: &cred.groups,
action: Action::AdminAction(AdminAction::ListServiceAccountsAdminAction),
bucket: "",
conditions: &get_condition_values(req.headers(), &cred, None, None, req.policy_source_addr()),
conditions: &conditions,
is_owner: owner,
object: "",
claims: cred.claims_or_empty(),
@@ -1448,7 +1478,8 @@ impl Operation for DeleteServiceAccount {
return Err(s3_error!(InvalidRequest, "iam not init"));
};
let conditions = get_condition_values(req.headers(), &cred, None, None, req.policy_source_addr());
let conditions =
get_condition_values_with_client_info(req.headers(), &cred, None, None, req.policy_source_addr(), req.client_info());
let claims = cred.claims_or_empty();
let deleted_at = if iam_store
@@ -3917,4 +3948,140 @@ mod tests {
}
});
}
#[test]
#[serial_test::serial]
fn list_access_keys_bulk_requires_list_users_for_cross_user_queries() {
crate::app::gating_test_env::run_large_stack_test("bulk-access-keys-list-users-parity", || async {
use crate::admin::operation::test_support::TestRequest;
use crate::admin::runtime_sources::{AppContext, IamInterface, KmsInterface, publish_test_app_context};
use rustfs_iam::store::{Store as _, UserType};
use rustfs_madmin::{AccountStatus, AddOrUpdateUserReq};
use rustfs_policy::policy::Policy;
use std::sync::Arc;
struct ReadyIam(Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>>);
impl IamInterface for ReadyIam {
fn handle(&self) -> Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>> {
Arc::clone(&self.0)
}
fn is_ready(&self) -> bool {
true
}
}
struct TestKms;
impl KmsInterface for TestKms {
fn handle(&self) -> Arc<rustfs_kms::KmsServiceManager> {
Arc::new(rustfs_kms::KmsServiceManager::new())
}
}
let previous = crate::runtime_sources::current_app_context();
let (_dir, _paths, store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
rustfs_iam::store::object::ObjectStore::new(Arc::clone(&store))
.save_iam_config(
serde_json::json!({"version": 1}),
format!("{}/format.json", *rustfs_iam::store::object::IAM_CONFIG_PREFIX),
)
.await
.expect("seed IAM format");
let iam = rustfs_iam::build_iam_sys(Arc::clone(&store)).await.expect("init IAM");
let secret = "bulk-parity-secret-1234";
for (user, doc) in [
(
"sa-only-user",
Some(r#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:ListServiceAccounts"]}]}"#),
),
(
"sa-and-users",
Some(
r#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:ListServiceAccounts","admin:ListUsers"]}]}"#,
),
),
("bob-target", None),
] {
iam.create_user(
user,
&AddOrUpdateUserReq {
secret_key: secret.to_owned(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create user");
if let Some(doc) = doc {
iam.set_policy(user, Policy::parse_config(doc.as_bytes()).expect("parse policy"))
.await
.expect("save policy");
iam.policy_db_set(user, UserType::Reg, false, user)
.await
.expect("attach policy");
}
}
let context = Arc::new(AppContext::new(store, Arc::new(ReadyIam(iam)), Arc::new(TestKms)));
assert!(context.publish_action_credentials(rustfs_credentials::Credentials {
access_key: "bulk-parity-root".to_owned(),
secret_key: "bulk-parity-root-secret".to_owned(),
status: "on".to_owned(),
..Default::default()
}));
publish_test_app_context(context);
// Caller with only ListServiceAccounts may list self, but is denied for other users or all=true.
for uri in [
"/rustfs/admin/v3/list-access-keys-bulk",
"/rustfs/admin/v3/list-access-keys-bulk?users=sa-only-user",
] {
let resp = ListAccessKeysBulk {}
.call(
TestRequest::new(http::Method::GET, uri)
.credentials("sa-only-user", secret, None)
.build(),
Params::new(),
)
.await
.unwrap_or_else(|err| panic!("self bulk list `{uri}` must succeed: {err}"));
assert_eq!(resp.into_parts().0, StatusCode::OK, "{uri}");
}
for uri in [
"/rustfs/admin/v3/list-access-keys-bulk?users=bob-target",
"/rustfs/admin/v3/list-access-keys-bulk?users=sa-only-user&users=bob-target",
"/rustfs/admin/v3/list-access-keys-bulk?all=true",
] {
let err = ListAccessKeysBulk {}
.call(
TestRequest::new(http::Method::GET, uri)
.credentials("sa-only-user", secret, None)
.build(),
Params::new(),
)
.await
.expect_err("cross-user or all=true bulk list must require ListUsersAdminAction");
assert_eq!(err.code(), &S3ErrorCode::AccessDenied, "{uri}");
}
// Caller holding both ListServiceAccounts and ListUsers succeeds for cross-user and all=true queries.
for uri in [
"/rustfs/admin/v3/list-access-keys-bulk?users=bob-target",
"/rustfs/admin/v3/list-access-keys-bulk?all=true",
] {
let resp = ListAccessKeysBulk {}
.call(
TestRequest::new(http::Method::GET, uri)
.credentials("sa-and-users", secret, None)
.build(),
Params::new(),
)
.await
.unwrap_or_else(|err| panic!("authorized bulk list `{uri}` must succeed: {err}"));
assert_eq!(resp.into_parts().0, StatusCode::OK, "{uri}");
}
if let Some(previous) = previous {
publish_test_app_context(previous);
}
});
}
}
+14 -2
View File
@@ -235,7 +235,17 @@ impl Operation for AssumeRoleHandle {
match body.action.as_str() {
ASSUME_ROLE_ACTION => {
let remote_addr = req.policy_source_addr();
handle_assume_role(req.credentials(), req.uri(), req.headers(), remote_addr, body, store, &audit).await
handle_assume_role(
req.credentials(),
req.uri(),
req.headers(),
remote_addr,
req.client_info(),
body,
store,
&audit,
)
.await
}
ASSUME_ROLE_WITH_WEB_IDENTITY_ACTION => handle_assume_role_with_web_identity(body).await,
_ => Err(s3_error!(InvalidArgument, "unsupported Action")),
@@ -244,11 +254,13 @@ impl Operation for AssumeRoleHandle {
}
/// Handle the standard AssumeRole action (requires SigV4 credentials).
#[allow(clippy::too_many_arguments)]
async fn handle_assume_role(
credentials: Option<&RequestCredentials>,
uri: &http::Uri,
headers: &http::HeaderMap,
remote_addr: Option<std::net::SocketAddr>,
client_info: Option<&rustfs_trusted_proxies::ClientInfo>,
body: AssumeRoleRequest,
store: Option<std::sync::Arc<crate::admin::storage_api::runtime::ECStore>>,
audit: &AccountAuditContext,
@@ -277,7 +289,7 @@ async fn handle_assume_role(
let Ok(iam_store) = crate::admin::runtime_sources::current_ready_iam_handle() else {
return Err(s3_error!(InvalidRequest, "iam not init"));
};
let mut conditions = crate::auth::get_condition_values(headers, &cred, None, None, remote_addr);
let mut conditions = crate::auth::get_condition_values_with_client_info(headers, &cred, None, None, remote_addr, client_info);
let exp = set_assume_role_duration_condition(&mut conditions, body.duration_seconds);
if !iam_store
.is_allowed(&Args {
+176 -14
View File
@@ -13,7 +13,10 @@
// limitations under the License.
use super::{cluster_snapshot, realtime};
use crate::admin::auth::{authorize_admin_envelope, resolve_admin_object_read_sse_kms_principal};
use crate::admin::auth::{
AdminResourceScope, authorize_admin_envelope, authorize_admin_envelope_with_context_and_scope,
resolve_admin_object_read_sse_kms_principal,
};
use crate::admin::handlers::account::{ACCOUNT_INFO_ROUTE, ACCOUNT_PASSWORD_ROUTE};
use crate::admin::handlers::mfa::{ACCOUNT_MFA_ROUTE, MFA_CHALLENGE_ROUTE, USER_MFA_ROUTE};
use crate::admin::operation::{AdminRequest, AdminResponse, Operation};
@@ -560,7 +563,6 @@ impl Operation for InspectDataHandler {
log_system_request_rejected!("inspect_data", "missing_credentials");
return Err(s3_error!(InvalidRequest, "get cred failed"));
}
authorize_admin_envelope(req.envelope(), vec![Action::AdminAction(AdminAction::InspectDataAction)]).await?;
// MinIO's inspect-data exports a signed archive of raw drive files for a
// `volume`/`file` glob. RustFS erasure-codes and (optionally) encrypts
@@ -568,7 +570,19 @@ impl Operation for InspectDataHandler {
// back; instead we return the reconstructed raw object bytes for the
// requested `volume` (bucket) + `file` (object), which is the honest,
// usable form of "inspect this object's data" against an EC store.
let Some((bucket, object)) = inspect_data_target(req.uri()) else {
let target = inspect_data_target(req.uri());
let scope = match target.as_ref() {
Some((bucket, object)) => AdminResourceScope::bucket_object(bucket, object),
None => AdminResourceScope::bucket_object("", ""),
};
authorize_admin_envelope_with_context_and_scope(
req.envelope(),
vec![Action::AdminAction(AdminAction::InspectDataAction)],
scope,
)
.await?;
let Some((bucket, object)) = target else {
return Err(s3_error!(
InvalidRequest,
"inspect-data requires `volume` (bucket) and `file` (object) query parameters"
@@ -2485,20 +2499,30 @@ mod tests {
let runtime_capabilities_tokens = ["runtime_capabilities_gate_actions()"];
let data_usage_info_tokens = ["data_usage_info_gate_actions()"];
for (handler, inline_admin_actions, tokens) in [
("ServiceHandle", 1usize, service_tokens.as_slice()),
("UpdateHandler", 1, update_tokens.as_slice()),
("ServerInfoHandler", 1, server_info_tokens.as_slice()),
("InspectDataHandler", 1, inspect_data_tokens.as_slice()),
("StorageInfoHandler", 1, storage_info_tokens.as_slice()),
("RuntimeCapabilitiesHandler", 0, runtime_capabilities_tokens.as_slice()),
("DataUsageInfoHandler", 0, data_usage_info_tokens.as_slice()),
for (handler, gate_fn, inline_admin_actions, tokens) in [
("ServiceHandle", "authorize_admin_envelope(", 1usize, service_tokens.as_slice()),
("UpdateHandler", "authorize_admin_envelope(", 1, update_tokens.as_slice()),
("ServerInfoHandler", "authorize_admin_envelope(", 1, server_info_tokens.as_slice()),
(
"InspectDataHandler",
"authorize_admin_envelope_with_context_and_scope(",
1,
inspect_data_tokens.as_slice(),
),
("StorageInfoHandler", "authorize_admin_envelope(", 1, storage_info_tokens.as_slice()),
(
"RuntimeCapabilitiesHandler",
"authorize_admin_envelope(",
0,
runtime_capabilities_tokens.as_slice(),
),
("DataUsageInfoHandler", "authorize_admin_envelope(", 0, data_usage_info_tokens.as_slice()),
] {
let block = source_block(production, &format!("impl Operation for {handler}"));
assert_eq!(
block.matches("authorize_admin_envelope(").count(),
block.matches(gate_fn).count(),
1,
"{handler} must use exactly one shared gate"
"{handler} must use exactly one shared gate ({gate_fn})"
);
assert_eq!(
block.matches("Action::AdminAction(").count(),
@@ -2509,11 +2533,17 @@ mod tests {
assert!(block.contains(token), "{handler} must authorize with {token}");
}
assert!(
!block.contains("let cred = authorize_admin_envelope("),
!block.contains("let cred = authorize_admin_envelope"),
"{handler} does not consume the authenticated credentials"
);
}
let inspect_data = source_block(production, "impl Operation for InspectDataHandler");
assert!(
inspect_data.contains("AdminResourceScope::bucket_object(bucket, object)"),
"InspectDataHandler must scope InspectDataAction to the requested bucket and object"
);
assert!(!production.contains("check_key_valid(get_session_token"));
assert!(!production.contains("validate_admin_request("));
@@ -2528,4 +2558,136 @@ mod tests {
"InspectDataHandler must authorize kms:Decrypt on the opened reader before returning bytes"
);
}
#[test]
#[serial_test::serial]
fn inspect_data_handler_enforces_bucket_and_object_resource_scope() {
crate::app::gating_test_env::run_large_stack_test("inspect-data-resource-scope", || async {
use crate::admin::operation::test_support::TestRequest;
use crate::admin::runtime_sources::{AppContext, IamInterface, KmsInterface, publish_test_app_context};
use crate::admin::storage_api::contract::bucket::{BucketOperations as _, MakeBucketOptions};
use crate::admin::storage_api::contract::object::ObjectIO as _;
use crate::admin::storage_api::object::{StorageObjectOptions, StoragePutObjReader};
use rustfs_iam::store::{Store as _, UserType};
use rustfs_madmin::{AccountStatus, AddOrUpdateUserReq};
use rustfs_policy::policy::Policy;
use std::sync::Arc;
struct ReadyIam(Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>>);
impl IamInterface for ReadyIam {
fn handle(&self) -> Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>> {
Arc::clone(&self.0)
}
fn is_ready(&self) -> bool {
true
}
}
struct TestKms;
impl KmsInterface for TestKms {
fn handle(&self) -> Arc<rustfs_kms::KmsServiceManager> {
Arc::new(rustfs_kms::KmsServiceManager::new())
}
}
let previous = crate::runtime_sources::current_app_context();
let (_dir, _paths, store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
rustfs_iam::store::object::ObjectStore::new(Arc::clone(&store))
.save_iam_config(
serde_json::json!({"version": 1}),
format!("{}/format.json", *rustfs_iam::store::object::IAM_CONFIG_PREFIX),
)
.await
.expect("seed IAM format");
for (bucket, key, payload) in [
("app-data", "public/ok.txt", b"public bytes".as_slice()),
("app-data", "private/secret.txt", b"private bytes".as_slice()),
("other-bucket", "public/ok.txt", b"other bytes".as_slice()),
] {
let _ = store.make_bucket(bucket, &MakeBucketOptions::default()).await;
store
.put_object(
bucket,
key,
&mut StoragePutObjReader::from_vec(payload.to_vec()),
&StorageObjectOptions::default(),
)
.await
.expect("seed test object");
}
let iam = rustfs_iam::build_iam_sys(Arc::clone(&store)).await.expect("init IAM");
let user = "scoped-inspector";
let secret = "inspector-secret-1234";
iam.create_user(
user,
&AddOrUpdateUserReq {
secret_key: secret.to_owned(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create inspector user");
iam.set_policy(
"inspect-public-only",
Policy::parse_config(
br#"{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["admin:InspectData"],
"Resource": ["arn:aws:s3:::app-data/public/*"]
}]
}"#,
)
.expect("parse policy"),
)
.await
.expect("store policy");
iam.policy_db_set(user, UserType::Reg, false, "inspect-public-only")
.await
.expect("attach policy");
let context = Arc::new(AppContext::new(store, Arc::new(ReadyIam(iam)), Arc::new(TestKms)));
assert!(context.publish_action_credentials(rustfs_credentials::Credentials {
access_key: "inspect-scope-root".to_owned(),
secret_key: "inspect-scope-secret".to_owned(),
status: "on".to_owned(),
..Default::default()
}));
publish_test_app_context(context);
// In-scope bucket + prefix succeeds.
let ok_resp = InspectDataHandler {}
.call(
TestRequest::new(Method::GET, "/rustfs/admin/v3/inspect-data?volume=app-data&file=public/ok.txt")
.credentials(user, secret, None)
.build(),
Params::new(),
)
.await
.expect("in-scope object must be readable");
let (status, _headers, mut body) = ok_resp.into_parts();
assert_eq!(status, http::StatusCode::OK);
assert_eq!(body.store_all_limited(4096).await.expect("read body").as_ref(), b"public bytes");
// Out-of-scope prefix, out-of-scope bucket, reserved bucket, and missing query params are denied.
for uri in [
"/rustfs/admin/v3/inspect-data?volume=app-data&file=private/secret.txt",
"/rustfs/admin/v3/inspect-data?volume=other-bucket&file=public/ok.txt",
"/rustfs/admin/v3/inspect-data?volume=.rustfs.sys&file=config/iam/format.json",
"/rustfs/admin/v3/inspect-data",
] {
let err = InspectDataHandler {}
.call(TestRequest::new(Method::GET, uri).credentials(user, secret, None).build(), Params::new())
.await
.expect_err("out-of-scope inspect-data must be denied");
assert_eq!(err.code(), &S3ErrorCode::AccessDenied, "{uri}");
}
if let Some(previous) = previous {
publish_test_app_context(previous);
}
});
}
}
@@ -20,11 +20,11 @@ use crate::admin::storage_api::bucket::metadata::table_catalog_path_hash;
use crate::admin::storage_api::runtime::ECStore;
use crate::admin::utils::owned_empty_response;
use crate::admin::{
auth::{AdminResourceScope, validate_admin_action_with_bucket_object_for_iam},
auth::{AdminResourceScope, check_admin_key_valid_with_context, validate_admin_action_with_bucket_object_for_iam},
router::{AdminOperation, S3Router},
};
use crate::app::RequestEnvelope;
use crate::auth::{check_key_valid_with_context, get_session_token};
use crate::auth::get_session_token;
use crate::error::ApiError;
use crate::server::{TABLE_CATALOG_COMPAT_PREFIX, TABLE_CATALOG_PREFIX};
use crate::table_catalog::{DEFAULT_WAREHOUSE_ID, TableCatalogStore};
@@ -1157,7 +1157,7 @@ async fn authorize_table_catalog_request(req: &AdminRequest, action: AdminAction
&principal.credentials,
principal.owner,
Action::AdminAction(action),
req.policy_source_addr(),
req.envelope(),
AdminResourceScope::bucket(""),
)
.await
@@ -1271,7 +1271,7 @@ async fn authorize_table_catalog_object_for_principal(
&principal.credentials,
principal.owner,
Action::AdminAction(action),
req.policy_source_addr(),
req.envelope(),
AdminResourceScope::bucket_object(bucket, object),
)
.await
@@ -1338,7 +1338,7 @@ async fn table_catalog_request_principal(req: &AdminRequest) -> S3Result<TableCa
};
let context = runtime_sources::app_context_from_envelope(req.envelope())
.ok_or_else(|| table_catalog_internal_error("request application context is not initialized"))?;
let (credentials, owner) = check_key_valid_with_context(
let (credentials, owner) = check_admin_key_valid_with_context(
get_session_token(req.uri(), req.headers()).unwrap_or_default(),
input_cred.access_key(),
Some(context.as_ref()),
@@ -2242,6 +2242,8 @@ fn warehouse_from_params(params: &Params<'_, '_>) -> S3Result<String> {
if warehouse.is_empty() {
return Err(S3Error::from(ApiError::invalid_request("warehouse is required")));
}
crate::admin::storage_api::bucket::utils::check_valid_bucket_name_strict(warehouse)
.map_err(|_| s3_error!(InvalidArgument, "invalid warehouse bucket name"))?;
Ok(warehouse.to_string())
}
@@ -2260,6 +2262,8 @@ fn warehouse_from_config_query(uri: &http::Uri) -> S3Result<Option<String>> {
if value.is_empty() {
return Err(s3_error!(InvalidRequest, "warehouse query parameter must not be empty"));
}
crate::admin::storage_api::bucket::utils::check_valid_bucket_name_strict(&value)
.map_err(|_| s3_error!(InvalidArgument, "invalid warehouse bucket name"))?;
warehouse = Some(value.into_owned());
}
Ok(warehouse)
@@ -2100,6 +2100,44 @@ fn warehouse_config_query_rejects_empty_and_repeated_values() {
assert!(warehouse_from_config_query(&uri).is_err());
}
#[test]
fn warehouse_parsers_enforce_strict_s3_bucket_naming() {
let mut router = matchit::Router::new();
router.insert("/iceberg/v1/{warehouse}", ()).expect("warehouse test route");
for valid in ["analytics", "warehouse-2026", "data.lake"] {
let path = format!("/iceberg/v1/{valid}");
let matched = router.at(&path).expect("valid route match");
assert_eq!(
warehouse_from_params(&matched.params).expect("valid S3 bucket name must pass params check"),
valid
);
let uri = format!("/iceberg/v1/config?warehouse={valid}").parse().expect("valid URI");
assert_eq!(
warehouse_from_config_query(&uri).expect("valid S3 bucket name must pass query check"),
Some(valid.to_string())
);
}
for invalid in [".rustfs.sys", ".minio.sys", "UPPERCASE", "bad_warehouse", "ab", "192.168.1.1"] {
let path = format!("/iceberg/v1/{invalid}");
let matched = router.at(&path).expect("invalid route match");
let err = warehouse_from_params(&matched.params).expect_err("invalid S3 bucket name must be rejected in params");
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument, "params rejected `{invalid}`");
let uri = format!("/iceberg/v1/config?warehouse={invalid}")
.parse()
.expect("invalid URI");
let err = warehouse_from_config_query(&uri).expect_err("invalid S3 bucket name must be rejected in query");
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument, "query rejected `{invalid}`");
}
let traversal_uri = "/iceberg/v1/config?warehouse=..%2Fescape".parse().expect("traversal URI");
let err = warehouse_from_config_query(&traversal_uri).expect_err("path traversal warehouse must be rejected");
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument);
}
#[test]
fn drop_table_purge_query_is_explicit_and_strict() {
for (uri, expected) in [
+1 -1
View File
@@ -83,7 +83,7 @@ impl Operation for BucketPrefixUsageHandler {
owner,
false,
data_usage_info_gate_actions(),
req.policy_source_addr(),
req.envelope(),
&bucket,
)
.await?;
+189 -6
View File
@@ -339,11 +339,23 @@ impl Operation for AddUser {
owner,
false,
vec![Action::AdminAction(AdminAction::CreateUserAdminAction)],
req.policy_source_addr(),
req.envelope(),
)
.await?;
}
// `/admin/v3/add-user` manages user credentials and status only (matching
// MinIO semantics); policy attachment requires `admin:AttachUserOrGroupPolicy`
// via the dedicated policy-attachment endpoints. Fail closed rather than
// silently ignoring a caller-supplied policy (rustfs/backlog#1246).
if args.policy.as_deref().is_some_and(|policy| !policy.is_empty()) {
return Err(s3_error!(
InvalidArgument,
"policy attachment is not supported by add-user; use policy attachment endpoints"
));
}
args.policy = None;
let rotation_secret = self_rotation_secret(check_deny_only, input_secret.as_deref())?;
let updated_at = if let Some(current_secret) = rotation_secret {
let (updated_at, status, _) = iam_store
@@ -351,8 +363,6 @@ impl Operation for AddUser {
.await
.map_err(map_add_user_create_error)?;
args.status = status;
// A self-service secret rotation does not change policy attachment.
args.policy = None;
updated_at
} else {
if validate_admin_request(
@@ -361,7 +371,7 @@ impl Operation for AddUser {
owner,
false,
vec![Action::AdminAction(AdminAction::EnableUserAdminAction)],
req.policy_source_addr(),
req.envelope(),
)
.await
.is_ok()
@@ -681,7 +691,7 @@ impl Operation for GetUserInfo {
owner,
check_deny_only,
vec![Action::AdminAction(AdminAction::GetUserAdminAction)],
req.policy_source_addr(),
req.envelope(),
)
.await?;
@@ -970,7 +980,7 @@ impl Operation for ImportIam {
owner,
false,
vec![Action::AdminAction(AdminAction::ImportIAMAction)],
req.policy_source_addr(),
req.envelope(),
)
.await?;
@@ -2140,4 +2150,177 @@ mod tests {
);
}
}
#[test]
#[serial_test::serial]
fn add_user_fails_closed_on_non_empty_policy_and_allows_empty_or_omitted() {
crate::app::gating_test_env::run_large_stack_test("add-user-policy-fail-closed", || async {
use super::AddUser;
use crate::admin::operation::test_support::TestRequest;
use crate::admin::runtime_sources::{AppContext, IamInterface, KmsInterface, publish_test_app_context};
use http::StatusCode;
use rustfs_iam::store::{Store as _, UserType};
use rustfs_madmin::{AccountStatus, AddOrUpdateUserReq};
use rustfs_policy::policy::Policy;
use std::sync::Arc;
struct ReadyIam(Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>>);
impl IamInterface for ReadyIam {
fn handle(&self) -> Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>> {
Arc::clone(&self.0)
}
fn is_ready(&self) -> bool {
true
}
}
struct TestKms;
impl KmsInterface for TestKms {
fn handle(&self) -> Arc<rustfs_kms::KmsServiceManager> {
Arc::new(rustfs_kms::KmsServiceManager::new())
}
}
let previous = crate::runtime_sources::current_app_context();
let (_dir, _paths, store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
rustfs_iam::store::object::ObjectStore::new(Arc::clone(&store))
.save_iam_config(
serde_json::json!({"version": 1}),
format!("{}/format.json", *rustfs_iam::store::object::IAM_CONFIG_PREFIX),
)
.await
.expect("seed IAM format");
let iam = rustfs_iam::build_iam_sys(Arc::clone(&store)).await.expect("init IAM");
for (user, secret, policy_doc) in [
(
"creator-only",
"creator-secret-1234",
Some(r#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:CreateUser"]}]}"#),
),
("unprivileged", "unpriv-secret-1234", None),
] {
iam.create_user(
user,
&AddOrUpdateUserReq {
secret_key: secret.to_owned(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("seed user");
if let Some(doc) = policy_doc {
iam.set_policy(user, Policy::parse_config(doc.as_bytes()).expect("parse policy"))
.await
.expect("save policy");
iam.policy_db_set(user, UserType::Reg, false, user)
.await
.expect("attach policy");
}
}
let context = Arc::new(AppContext::new(store, Arc::new(ReadyIam(Arc::clone(&iam))), Arc::new(TestKms)));
assert!(context.publish_action_credentials(Credentials {
access_key: "add-user-test-root".to_owned(),
secret_key: "add-user-root-secret".to_owned(),
status: "on".to_owned(),
..Default::default()
}));
publish_test_app_context(context);
// 1. Unauthorized caller sending policy still gets AccessDenied.
let unauth_req = TestRequest::new(Method::PUT, "/rustfs/admin/v3/add-user?accessKey=victim-unauth")
.credentials("unprivileged", "unpriv-secret-1234", None)
.body(
serde_json::to_vec(&serde_json::json!({
"secretKey": "new-secret-123456",
"policy": "consoleAdmin",
"status": "enabled"
}))
.expect("serialize payload"),
)
.build();
let err = AddUser {}
.call(unauth_req, Params::new())
.await
.expect_err("unprivileged caller must be denied");
assert_eq!(err.code(), &S3ErrorCode::AccessDenied);
assert!(iam.get_user("victim-unauth").await.is_none());
// 2. Authorized creator (and root) sending non-empty policy must fail closed with InvalidArgument.
for (caller, secret, target) in [
("creator-only", "creator-secret-1234", "victim-creator"),
("add-user-test-root", "add-user-root-secret", "victim-root"),
] {
let req = TestRequest::new(Method::PUT, format!("/rustfs/admin/v3/add-user?accessKey={target}").as_str())
.credentials(caller, secret, None)
.body(
serde_json::to_vec(&serde_json::json!({
"secretKey": "new-secret-123456",
"policy": "readwrite",
"status": "enabled"
}))
.expect("serialize payload"),
)
.build();
let err = AddUser {}
.call(req, Params::new())
.await
.expect_err("non-empty policy in add-user must fail closed");
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument, "caller={caller}");
assert!(iam.get_user(target).await.is_none(), "rejected add-user must not create `{target}`");
}
// 3. Self-rotation with a non-empty policy must also fail closed without changing secret.
let self_req = TestRequest::new(Method::PUT, "/rustfs/admin/v3/add-user?accessKey=unprivileged")
.credentials("unprivileged", "unpriv-secret-1234", None)
.body(
serde_json::to_vec(&serde_json::json!({
"secretKey": "rotated-secret-123456",
"policy": "consoleAdmin",
"status": "enabled"
}))
.expect("serialize payload"),
)
.build();
let err = AddUser {}
.call(self_req, Params::new())
.await
.expect_err("self-rotation with policy must fail closed");
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument);
assert_eq!(
iam.get_user("unprivileged")
.await
.expect("user still exists")
.credentials
.secret_key,
"unpriv-secret-1234"
);
// 4. Omitted or empty policy continues creating and updating users normally.
for (target, body) in [
(
"valid-omitted",
serde_json::json!({"secretKey": "valid-secret-123456", "status": "enabled"}),
),
(
"valid-empty",
serde_json::json!({"secretKey": "valid-secret-123456", "policy": "", "status": "enabled"}),
),
] {
let req = TestRequest::new(Method::PUT, format!("/rustfs/admin/v3/add-user?accessKey={target}").as_str())
.credentials("creator-only", "creator-secret-1234", None)
.body(serde_json::to_vec(&body).expect("serialize payload"))
.build();
let resp = AddUser {}
.call(req, Params::new())
.await
.expect("add-user without policy should succeed");
assert_eq!(resp.into_parts().0, StatusCode::OK);
assert!(iam.get_user(target).await.is_some(), "`{target}` must be created");
}
if let Some(previous) = previous {
publish_test_app_context(previous);
}
});
}
}
+30 -6
View File
@@ -25,7 +25,9 @@
//! credentials but must *not* be allowed to rewrite the parent's secret. This
//! module is the single place those distinctions are made.
use crate::admin::auth::authenticate_envelope_credentials;
use crate::admin::auth::{
action_credentials_from_envelope, authenticate_envelope_credentials, authenticate_envelope_credentials_with_context,
};
use crate::admin::runtime_sources::current_action_credentials;
use crate::admin::storage_api::s3::{self, S3ErrorCode, S3Result};
use crate::app::RequestEnvelope;
@@ -168,20 +170,42 @@ pub(crate) struct CallerIdentity {
}
impl CallerIdentity {
/// Authenticate the request and resolve who it acts as.
/// Authenticate the request against the process-ambient IAM domain and
/// resolve who it acts as.
///
/// Authentication only: callers that need an authorization decision must
/// still enforce their action policy and credential eligibility checks.
/// Use this for ambient-store handlers (such as `account.rs`) so auth,
/// authz, and IAM mutation share the same server domain. Handlers that
/// execute against the request's `ServerContextSlot` must call
/// [`Self::resolve_envelope_with_context`] instead.
pub(crate) async fn resolve_envelope(envelope: &RequestEnvelope) -> S3Result<Self> {
let Some(input_cred) = envelope.credentials() else {
return Err(s3::error(S3ErrorCode::InvalidRequest, "authentication required"));
};
let (credentials, is_owner) = authenticate_envelope_credentials(input_cred).await?;
Ok(Self::from_credentials(credentials, is_owner))
let root_cred = current_action_credentials();
Ok(Self::from_credentials_with_root(credentials, is_owner, root_cred.as_ref()))
}
/// Authenticate the request against its `ServerContextSlot` (when present)
/// and resolve who it acts as against that server context's root identity.
pub(crate) async fn resolve_envelope_with_context(envelope: &RequestEnvelope) -> S3Result<Self> {
let Some(input_cred) = envelope.credentials() else {
return Err(s3::error(S3ErrorCode::InvalidRequest, "authentication required"));
};
let (credentials, is_owner) = authenticate_envelope_credentials_with_context(input_cred, envelope).await?;
let root_cred = action_credentials_from_envelope(envelope);
Ok(Self::from_credentials_with_root(credentials, is_owner, root_cred.as_ref()))
}
#[cfg(test)]
fn from_credentials(credentials: Credentials, is_owner: bool) -> Self {
let root_cred = current_action_credentials();
Self::from_credentials_with_root(credentials, is_owner, root_cred.as_ref())
}
fn from_credentials_with_root(credentials: Credentials, is_owner: bool, root_cred: Option<&Credentials>) -> Self {
let presented_access_key = credentials.access_key.clone();
let is_service_account = credentials.is_service_account();
let is_temp = credentials.is_temp();
@@ -209,7 +233,7 @@ impl CallerIdentity {
(IdentityType::Iam, presented_access_key.clone(), false)
};
let is_root = current_action_credentials().is_some_and(|root| constant_time_eq(&root.access_key, &access_key));
let is_root = root_cred.is_some_and(|root| constant_time_eq(&root.access_key, &access_key));
let identity_type = if is_root && matches!(identity_type, IdentityType::Iam) {
IdentityType::Root