mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-30 20:57:35 +00:00
perf(gateway): avoid duplicate authz and stack cloning on object reads (#9761)
* perf(gateway): avoid duplicate authz and stack cloning on object reads * fix(gateway): capture ODM read generation before early policy evaluation * fix(server): keep exclusive edge dispatch shape via Arc::make_mut
This commit is contained in:
@@ -1743,6 +1743,13 @@ pub(crate) fn bucket_metadata_transaction_lock_key(bucket: &str) -> String {
|
||||
format!("bucket-targets/{bucket}/transaction.lock")
|
||||
}
|
||||
|
||||
/// Lightweight authorization snapshot derived from a single authoritative bucket metadata lookup.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct BucketAuthzSnapshot {
|
||||
pub has_policy: bool,
|
||||
pub table_bucket_enabled: bool,
|
||||
}
|
||||
|
||||
pub async fn get_bucket_policy(bucket: &str) -> Result<(BucketPolicy, OffsetDateTime)> {
|
||||
let bucket_meta_sys_lock = get_bucket_metadata_sys()?;
|
||||
let bucket_meta_sys = bucket_meta_sys_lock.read().await.clone();
|
||||
@@ -3484,18 +3491,22 @@ impl BucketMetadataSys {
|
||||
Ok(metadata.versioning_config.is_none() && metadata.versioning_config_xml.is_empty())
|
||||
}
|
||||
|
||||
pub async fn get_bucket_policy(&self, bucket: &str) -> Result<(BucketPolicy, OffsetDateTime)> {
|
||||
let bm = match self.get_metadata_authority(bucket).await? {
|
||||
BucketMetadataAuthority::Authoritative(bm) => bm,
|
||||
async fn get_authoritative_policy_metadata(&self, bucket: &str) -> Result<Arc<BucketMetadata>> {
|
||||
match self.get_metadata_authority(bucket).await? {
|
||||
BucketMetadataAuthority::Authoritative(bm) => Ok(bm),
|
||||
BucketMetadataAuthority::Fabricated => match self.migrate_legacy_metadata(bucket).await? {
|
||||
BucketMetadataAuthority::Authoritative(bm) => bm,
|
||||
BucketMetadataAuthority::Authoritative(bm) => Ok(bm),
|
||||
BucketMetadataAuthority::Fabricated => {
|
||||
return Err(Error::other(format!("bucket policy metadata is not authoritative: {bucket}")));
|
||||
Err(Error::other(format!("bucket policy metadata is not authoritative: {bucket}")))
|
||||
}
|
||||
BucketMetadataAuthority::MissingBucket => return Err(Error::ConfigNotFound),
|
||||
BucketMetadataAuthority::MissingBucket => Err(Error::ConfigNotFound),
|
||||
},
|
||||
BucketMetadataAuthority::MissingBucket => return Err(Error::ConfigNotFound),
|
||||
};
|
||||
BucketMetadataAuthority::MissingBucket => Err(Error::ConfigNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_bucket_policy(&self, bucket: &str) -> Result<(BucketPolicy, OffsetDateTime)> {
|
||||
let bm = self.get_authoritative_policy_metadata(bucket).await?;
|
||||
|
||||
if let Some(config) = &bm.policy_config {
|
||||
Ok((config.clone(), bm.policy_config_updated_at))
|
||||
@@ -3506,6 +3517,17 @@ impl BucketMetadataSys {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads both the bucket policy presence and table-bucket marker from a single
|
||||
/// authoritative metadata lookup so authorization avoids repeated cache acquisitions.
|
||||
pub async fn get_bucket_authz_snapshot(&self, bucket: &str) -> Result<BucketAuthzSnapshot> {
|
||||
let bm = self.get_authoritative_policy_metadata(bucket).await?;
|
||||
let has_policy = bm.policy_config.is_some() || !bm.policy_config_json.is_empty();
|
||||
Ok(BucketAuthzSnapshot {
|
||||
has_policy,
|
||||
table_bucket_enabled: bm.table_bucket_enabled(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the raw JSON string of the bucket policy as originally stored.
|
||||
/// This preserves the exact format of the policy document as it was PUT.
|
||||
pub async fn get_bucket_policy_raw(&self, bucket: &str) -> Result<(String, OffsetDateTime)> {
|
||||
|
||||
@@ -903,6 +903,11 @@ impl ECStore {
|
||||
sys.read().await.get_bucket_policy(bucket).await
|
||||
}
|
||||
|
||||
pub async fn get_bucket_authz_snapshot(&self, bucket: &str) -> Result<metadata_sys::BucketAuthzSnapshot> {
|
||||
let sys = metadata_sys::require_bucket_metadata_sys_in(&self.ctx)?;
|
||||
sys.read().await.get_bucket_authz_snapshot(bucket).await
|
||||
}
|
||||
|
||||
pub async fn get_bucket_policy_raw(&self, bucket: &str) -> Result<(String, OffsetDateTime)> {
|
||||
let sys = metadata_sys::require_bucket_metadata_sys_in(&self.ctx)?;
|
||||
sys.read().await.get_bucket_policy_raw(bucket).await
|
||||
|
||||
+46
-42
@@ -47,7 +47,6 @@ use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use subtle::ConstantTimeEq;
|
||||
use time::OffsetDateTime;
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
#[cfg(not(test))]
|
||||
@@ -129,27 +128,25 @@ async fn resolve_policy_plugin_state() -> PolicyPluginState {
|
||||
}
|
||||
}
|
||||
|
||||
static POLICY_PLUGIN_STATE: OnceLock<Arc<RwLock<PolicyPluginState>>> = OnceLock::new();
|
||||
static POLICY_PLUGIN_STATE: OnceLock<arc_swap::ArcSwap<PolicyPluginState>> = OnceLock::new();
|
||||
|
||||
fn get_policy_plugin_state() -> Arc<RwLock<PolicyPluginState>> {
|
||||
POLICY_PLUGIN_STATE
|
||||
.get_or_init(|| {
|
||||
let configured = opa::is_configured();
|
||||
let state = Arc::new(RwLock::new(if configured {
|
||||
PolicyPluginState::Initializing
|
||||
} else {
|
||||
PolicyPluginState::Disabled
|
||||
}));
|
||||
if configured {
|
||||
let state = Arc::clone(&state);
|
||||
tokio::spawn(async move {
|
||||
let next_state = resolve_policy_plugin_state().await;
|
||||
*state.write().await = next_state;
|
||||
});
|
||||
}
|
||||
state
|
||||
})
|
||||
.clone()
|
||||
fn get_policy_plugin_state() -> &'static arc_swap::ArcSwap<PolicyPluginState> {
|
||||
POLICY_PLUGIN_STATE.get_or_init(|| {
|
||||
let configured = opa::is_configured();
|
||||
let initial = if configured {
|
||||
PolicyPluginState::Initializing
|
||||
} else {
|
||||
PolicyPluginState::Disabled
|
||||
};
|
||||
let state = arc_swap::ArcSwap::from_pointee(initial);
|
||||
if configured {
|
||||
tokio::spawn(async move {
|
||||
let next_state = resolve_policy_plugin_state().await;
|
||||
get_policy_plugin_state().store(Arc::new(next_state));
|
||||
});
|
||||
}
|
||||
state
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -590,32 +587,39 @@ impl<T: Store> IamSys<T> {
|
||||
}
|
||||
|
||||
pub async fn set_policy_plugin_client(client: rustfs_policy::policy::opa::AuthZPlugin) {
|
||||
let policy_plugin_state = get_policy_plugin_state();
|
||||
let mut guard = policy_plugin_state.write().await;
|
||||
*guard = PolicyPluginState::Ready(client);
|
||||
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Ready(client)));
|
||||
}
|
||||
|
||||
/// Restricted credentials require the built-in parent/session intersection.
|
||||
/// External authorization bypasses that path, so only Disabled is supported.
|
||||
pub async fn ensure_restricted_credential_vending() -> Result<()> {
|
||||
if matches!(Self::policy_plugin_state().await, PolicyPluginState::Disabled) {
|
||||
if matches!(**get_policy_plugin_state().load(), PolicyPluginState::Disabled) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::IAMActionNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lock-free check for whether an external policy plugin (OPA) is active and ready.
|
||||
pub fn is_policy_plugin_ready() -> bool {
|
||||
matches!(**get_policy_plugin_state().load(), PolicyPluginState::Ready(_))
|
||||
}
|
||||
|
||||
/// Lock-free check for whether `access_key` is a cached STS account.
|
||||
pub fn has_sts_account(&self, access_key: &str) -> bool {
|
||||
self.store.cache.snapshot().sts_accounts.contains_key(access_key)
|
||||
}
|
||||
|
||||
pub async fn get_policy_plugin_client() -> Option<rustfs_policy::policy::opa::AuthZPlugin> {
|
||||
let policy_plugin_state = get_policy_plugin_state();
|
||||
let guard = policy_plugin_state.read().await;
|
||||
match &*guard {
|
||||
let guard = get_policy_plugin_state().load();
|
||||
match &**guard {
|
||||
PolicyPluginState::Ready(client) => Some(client.clone()),
|
||||
PolicyPluginState::Disabled | PolicyPluginState::Initializing | PolicyPluginState::Failed => None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn policy_plugin_state() -> PolicyPluginState {
|
||||
get_policy_plugin_state().read().await.clone()
|
||||
(**get_policy_plugin_state().load()).clone()
|
||||
}
|
||||
|
||||
pub async fn load_group(&self, name: &str) -> Result<()> {
|
||||
@@ -4694,7 +4698,7 @@ mod tests {
|
||||
claims: &marked_claims,
|
||||
deny_only: false,
|
||||
};
|
||||
*get_policy_plugin_state().write().await = PolicyPluginState::Disabled;
|
||||
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Disabled));
|
||||
let denied = iam.prepare_auth(&args).await;
|
||||
let disabled_terminal = matches!(iam.try_eval_prepared(&denied, &args).await, Err(Error::IAMActionNotAllowed));
|
||||
let inside = Args {
|
||||
@@ -4734,13 +4738,13 @@ mod tests {
|
||||
// The captured Disabled preparation stays on built-in intersection even
|
||||
// if an external policy client becomes ready before evaluation.
|
||||
let captured_still_terminal = matches!(iam.try_eval_prepared(&denied, &args).await, Err(Error::IAMActionNotAllowed));
|
||||
*get_policy_plugin_state().write().await = PolicyPluginState::Initializing;
|
||||
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Initializing));
|
||||
let pending = iam.prepare_auth(&args).await;
|
||||
let initializing_terminal = matches!(iam.try_eval_prepared(&pending, &args).await, Err(Error::IAMActionNotAllowed));
|
||||
*get_policy_plugin_state().write().await = PolicyPluginState::Failed;
|
||||
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Failed));
|
||||
let failed = iam.prepare_auth(&args).await;
|
||||
let failed_terminal = matches!(iam.try_eval_prepared(&failed, &args).await, Err(Error::IAMActionNotAllowed));
|
||||
*get_policy_plugin_state().write().await = previous;
|
||||
get_policy_plugin_state().store(Arc::new(previous));
|
||||
assert!(public_allows, "C07_PUBLIC_BUCKET_CONTROL: real public policy permits outside object");
|
||||
assert!(
|
||||
disabled_terminal && captured_still_terminal,
|
||||
@@ -4866,7 +4870,7 @@ mod tests {
|
||||
|
||||
let groups = None;
|
||||
let conditions = HashMap::new();
|
||||
*get_policy_plugin_state().write().await = PolicyPluginState::Disabled;
|
||||
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Disabled));
|
||||
let mut results = Vec::new();
|
||||
for action in [
|
||||
AdminAction::ListServiceAccountsAdminAction,
|
||||
@@ -4899,7 +4903,7 @@ mod tests {
|
||||
let ordinary_allowed = iam.is_allowed(&ordinary_args).await;
|
||||
results.push((action, terminal, ordinary_allowed));
|
||||
}
|
||||
*get_policy_plugin_state().write().await = previous;
|
||||
get_policy_plugin_state().store(Arc::new(previous));
|
||||
|
||||
for (action, terminal, ordinary_allowed) in results {
|
||||
assert!(
|
||||
@@ -4925,19 +4929,19 @@ mod tests {
|
||||
let active_rejected = IamSys::<StsTestMockStore>::ensure_restricted_credential_vending()
|
||||
.await
|
||||
.is_err();
|
||||
*get_policy_plugin_state().write().await = PolicyPluginState::Initializing;
|
||||
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Initializing));
|
||||
let initializing_rejected = IamSys::<StsTestMockStore>::ensure_restricted_credential_vending()
|
||||
.await
|
||||
.is_err();
|
||||
*get_policy_plugin_state().write().await = PolicyPluginState::Failed;
|
||||
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Failed));
|
||||
let failed_rejected = IamSys::<StsTestMockStore>::ensure_restricted_credential_vending()
|
||||
.await
|
||||
.is_err();
|
||||
*get_policy_plugin_state().write().await = PolicyPluginState::Disabled;
|
||||
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Disabled));
|
||||
let disabled_allowed = IamSys::<StsTestMockStore>::ensure_restricted_credential_vending()
|
||||
.await
|
||||
.is_ok();
|
||||
*get_policy_plugin_state().write().await = previous;
|
||||
get_policy_plugin_state().store(Arc::new(previous));
|
||||
assert!(
|
||||
active_rejected && initializing_rejected && failed_rejected,
|
||||
"C07_EXTERNAL_POLICY_BOUND: external authorization cannot bypass minted session scope"
|
||||
@@ -5016,7 +5020,7 @@ mod tests {
|
||||
outcomes.push((service_account, spoofed_oidc_claims, enabled, correct));
|
||||
}
|
||||
}
|
||||
*get_policy_plugin_state().write().await = previous;
|
||||
get_policy_plugin_state().store(Arc::new(previous));
|
||||
for (service_account, spoofed_oidc_claims, enabled, correct) in outcomes {
|
||||
assert!(
|
||||
correct,
|
||||
@@ -5055,7 +5059,7 @@ mod tests {
|
||||
let prepared = iam_sys.prepare_auth(&args).await;
|
||||
let needs_initial_tags = prepared.needs_existing_object_tag;
|
||||
let needs_secondary_tags = prepared.needs_existing_object_tag_for_args(&args).await;
|
||||
*get_policy_plugin_state().write().await = previous_state;
|
||||
get_policy_plugin_state().store(Arc::new(previous_state));
|
||||
|
||||
assert!(needs_initial_tags, "OPA mode must request existing object tags before evaluation");
|
||||
assert!(needs_secondary_tags, "OPA mode must request existing object tags for secondary actions");
|
||||
@@ -5300,7 +5304,7 @@ mod tests {
|
||||
assert!(!iam.is_allowed(&args).await, "ordinary PutBucketTagging must not bypass unreadable tags");
|
||||
outcomes.push(with_bucket_tag_deletion(iam.is_allowed(&args)).await);
|
||||
}
|
||||
*get_policy_plugin_state().write().await = previous;
|
||||
get_policy_plugin_state().store(Arc::new(previous));
|
||||
(outcomes, error, denied)
|
||||
},
|
||||
)
|
||||
|
||||
+8
-5
@@ -258,9 +258,9 @@ pub async fn check_key_valid_with_context(
|
||||
return Err(owned_error!(InternalError, "get_global_action_cred {:?}", IamError::IamSysNotInitialized));
|
||||
};
|
||||
|
||||
let sys_cred = cred.clone();
|
||||
|
||||
if !constant_time_eq(&cred.access_key, access_key) {
|
||||
let matched_root = constant_time_eq(&cred.access_key, access_key);
|
||||
let sys_cred = if !matched_root {
|
||||
let root_copy = cred.clone();
|
||||
let iam_store = match ctx {
|
||||
Some(context) if context.iam().is_ready() => Ok(context.iam().handle()),
|
||||
Some(_) => Err(()),
|
||||
@@ -318,13 +318,16 @@ pub async fn check_key_valid_with_context(
|
||||
};
|
||||
|
||||
cred = u.credentials;
|
||||
}
|
||||
Some(root_copy)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let claims = check_claims_from_token_with_context(session_token, &cred, ctx)?;
|
||||
|
||||
cred.claims = if !claims.is_empty() { Some(claims) } else { None };
|
||||
|
||||
let owner = has_root_access(&sys_cred, &cred);
|
||||
let owner = has_root_access(sys_cred.as_ref().unwrap_or(&cred), &cred);
|
||||
Ok((cred, owner))
|
||||
}
|
||||
|
||||
|
||||
@@ -30,14 +30,16 @@ use crate::app::{RequestCredentials, RequestEnvelope, RequestHead};
|
||||
use crate::auth::{get_session_token, keystone_is_owner};
|
||||
use crate::runtime_sources::ServerContextSlot;
|
||||
use crate::server::gateway_handlers::{OperationTable, metadata_listing, serves};
|
||||
use crate::server::gateway_stack::OwnedKeystoneIdentity;
|
||||
use crate::server::gateway_stack::{AuthorizedReadProof, EarlyAuthHandoff, OwnedKeystoneIdentity};
|
||||
use crate::shared_types::{NativeTlsTransport, RemoteAddr};
|
||||
use crate::storage_api::server::http::access::access_owned::bucket_core::authorize_delete_bucket;
|
||||
use crate::storage_api::server::http::access::access_owned::object_commit::{has_non_empty_request_tags, write_tagging_action};
|
||||
use crate::storage_api::server::http::access::access_owned::object_misc::{
|
||||
authorize_select_object_content, decide_delete_object,
|
||||
};
|
||||
use crate::storage_api::server::http::access::access_owned::object_read::authorize_get_object_attributes;
|
||||
use crate::storage_api::server::http::access::access_owned::object_read::{
|
||||
authorize_get_object_attributes, capture_odm_read_generation,
|
||||
};
|
||||
use crate::storage_api::server::http::access::{
|
||||
AccessMarkers, AuthorizationRequest, BucketConfigMutationSnapshot, BucketGenerationGuard, CopySourceBucketGenerationGuard,
|
||||
DenialAuditor, ObjectTagConditions, OdmReadGenerationGuard, PendingDeleteBucketGenerationGuard, PostObjectPolicyHeaders,
|
||||
@@ -143,23 +145,103 @@ impl EarlyAuthorizer {
|
||||
if let Err(decision) = install_caller(&mut prepared, &self.server_ctx).await {
|
||||
return decision;
|
||||
}
|
||||
if !matches!(prepared.caller, Caller::Anonymous) && policy_plugin_ready().await {
|
||||
if !matches!(prepared.caller, Caller::Anonymous) && policy_plugin_ready() {
|
||||
// An active OPA plugin is an external HTTP webhook evaluated once per check in the
|
||||
// handler, after request body/tag validation and without duplicate outbound queries.
|
||||
handoff_early_auth(context, &self.server_ctx, &mut prepared, raw_query.is_empty(), None);
|
||||
return Decision::Allow;
|
||||
}
|
||||
// Capture the migration source generation before policy evaluation, matching
|
||||
// `authorize_get_object` / `authorize_head_object`, so the early-read proof remains bound
|
||||
// to the bucket incarnation that was actually authorized.
|
||||
let odm_read_generation = match eval {
|
||||
Eval::GetObject | Eval::HeadObject => {
|
||||
Some(capture_odm_read_generation(&self.server_ctx, &prepared.envelope, bucket).await)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let mut route = RouteRequest {
|
||||
inner: &mut prepared.envelope,
|
||||
evaluate_table: true,
|
||||
};
|
||||
decision_of(evaluate(&mut route, eval, bucket, key, version.as_deref()).await)
|
||||
let eval_result = evaluate(&mut route, eval, bucket, key, version.as_deref()).await;
|
||||
if eval_result.is_ok() {
|
||||
let read_proof = build_authorized_read_proof(eval, &prepared.envelope, bucket, key, version, odm_read_generation);
|
||||
handoff_early_auth(context, &self.server_ctx, &mut prepared, raw_query.is_empty(), read_proof);
|
||||
}
|
||||
decision_of(eval_result)
|
||||
}
|
||||
}
|
||||
|
||||
async fn policy_plugin_ready() -> bool {
|
||||
rustfs_iam::sys::IamSys::<rustfs_iam::store::object::ObjectStore>::get_policy_plugin_client()
|
||||
.await
|
||||
.is_some()
|
||||
fn build_authorized_read_proof(
|
||||
eval: Eval,
|
||||
envelope: &RequestEnvelope,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
version: Option<String>,
|
||||
odm_read_generation: Option<OdmReadGenerationGuard>,
|
||||
) -> Option<AuthorizedReadProof> {
|
||||
// Only reuse early authorization when the wire headers already carried `Host` (HTTP/1.1
|
||||
// and standard HTTP/2); HTTP/2 requests relying on `:authority` -> `Host` synthesis in
|
||||
// `RequestEnvelope::from_gateway` keep full handler re-evaluation.
|
||||
if !envelope.headers().contains_key(http::header::HOST) {
|
||||
return None;
|
||||
}
|
||||
let operation = match eval {
|
||||
Eval::GetObject => dto::GetObject::NAME,
|
||||
Eval::HeadObject if get_header(envelope.headers(), SUFFIX_SOURCE_REPLICATION_CHECK).as_deref() != Some("true") => {
|
||||
dto::HeadObject::NAME
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(AuthorizedReadProof {
|
||||
operation,
|
||||
bucket: bucket.to_owned(),
|
||||
key: key.to_owned(),
|
||||
version_id: version,
|
||||
odm_read_generation: odm_read_generation?,
|
||||
})
|
||||
}
|
||||
|
||||
fn handoff_early_auth(
|
||||
context: &GatewayRequestContext<'_>,
|
||||
server_ctx: &Arc<ServerContextSlot>,
|
||||
prepared: &mut PreparedRequest,
|
||||
unmodified_headers: bool,
|
||||
authorized_read: Option<AuthorizedReadProof>,
|
||||
) {
|
||||
let Some(handoff) = context.server_extensions().get::<EarlyAuthHandoff>() else {
|
||||
return;
|
||||
};
|
||||
let access_key = match &prepared.caller {
|
||||
Caller::Anonymous => None,
|
||||
Caller::Signed { access_key } => Some(access_key.clone()),
|
||||
// Keystone requests skip the handoff slot; `admit` validates the host-verified identity directly.
|
||||
Caller::Keystone { .. } => return,
|
||||
};
|
||||
let Some(mut req_info) = prepared.envelope.req_info().cloned() else {
|
||||
return;
|
||||
};
|
||||
req_info.bucket = None;
|
||||
req_info.object = None;
|
||||
req_info.version_id = None;
|
||||
req_info.replication_request_authorized = false;
|
||||
// When `raw_query` is empty, `hoist_signed_query_params` is a no-op so `prepared.envelope`
|
||||
// still holds the exact wire headers built from `header_view.iter_raw()`. Moving it into the
|
||||
// handoff avoids cloning the entire HeaderMap a second time in `RequestEnvelope::from_gateway`.
|
||||
let headers = unmodified_headers.then(|| std::mem::take(prepared.envelope.headers_mut()));
|
||||
handoff.store(
|
||||
Arc::as_ptr(server_ctx) as usize,
|
||||
access_key,
|
||||
prepared.session_token.clone(),
|
||||
req_info,
|
||||
headers,
|
||||
authorized_read,
|
||||
);
|
||||
}
|
||||
|
||||
fn policy_plugin_ready() -> bool {
|
||||
rustfs_iam::sys::IamSys::<rustfs_iam::store::object::ObjectStore>::is_policy_plugin_ready()
|
||||
}
|
||||
|
||||
/// Who the gate resolves, classified the way [`super::gateway_handlers::access::admit`] does.
|
||||
@@ -187,7 +269,7 @@ fn prepare_request(
|
||||
raw_query: &str,
|
||||
server_ctx: &Arc<ServerContextSlot>,
|
||||
) -> Result<PreparedRequest, Decision> {
|
||||
let mut headers = HeaderMap::new();
|
||||
let mut headers = HeaderMap::with_capacity(16);
|
||||
for (name, value) in header_view.iter_raw() {
|
||||
headers.append(name.clone(), value.clone());
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
|
||||
use crate::app::RequestEnvelope;
|
||||
use crate::runtime_sources::ServerContextSlot;
|
||||
use crate::server::gateway_stack::EarlyAuthHandoff;
|
||||
use crate::storage_api::server::http::access::{
|
||||
VerifiedSignature, admit_operation, authorize_bucket_config_mutation as authorize_config_mutation,
|
||||
authorize_bucket_tag_deletion as authorize_tag_deletion, resolve_req_info,
|
||||
@@ -55,6 +56,7 @@ pub(super) fn admit<'a>(
|
||||
.is_some_and(|scheme| scheme.family() == SigFamily::V2);
|
||||
let operation = context.operation();
|
||||
let envelope = RequestEnvelope::from_gateway(context, server_ctx, signature);
|
||||
let early_handoff = context.transport_extensions().get::<EarlyAuthHandoff>().cloned();
|
||||
let keystone = context.header_token_principal().map(|_| {
|
||||
super::envelope::keystone_identity(context).map(|identity| (identity.credentials().clone(), identity.had_session_token()))
|
||||
});
|
||||
@@ -75,6 +77,12 @@ pub(super) fn admit<'a>(
|
||||
info.cred = Some(credentials);
|
||||
info.keystone_session_present = Some(had_session_token);
|
||||
info
|
||||
} else if let Some(mut info) = early_handoff
|
||||
.as_ref()
|
||||
.and_then(|handoff| handoff.take_caller(Arc::as_ptr(server_ctx) as usize, access_key.as_deref(), &session_token))
|
||||
{
|
||||
info.request_context = envelope.request_context().cloned();
|
||||
info
|
||||
} else {
|
||||
resolve_req_info(server_ctx, access_key.as_deref(), &session_token, envelope.request_context().cloned()).await?
|
||||
};
|
||||
|
||||
@@ -28,7 +28,7 @@ use crate::app::object::request_body::BodyReadControl;
|
||||
use crate::app::{RequestCredentials, RequestEnvelope, RequestHead};
|
||||
use crate::auth::get_session_token;
|
||||
use crate::runtime_sources::ServerContextSlot;
|
||||
use crate::server::gateway_stack::OwnedKeystoneIdentity;
|
||||
use crate::server::gateway_stack::{EarlyAuthHandoff, OwnedKeystoneIdentity};
|
||||
use crate::shared_types::{NativeTlsTransport, RemoteAddr};
|
||||
use crate::storage_api::server::http::access::{AccessMarkers, VerifiedSignature};
|
||||
use crate::storage_api::server::http::request_context::RequestContext;
|
||||
@@ -57,10 +57,20 @@ impl RequestEnvelope {
|
||||
signature: VerifiedSignature,
|
||||
) -> S3Result<Self> {
|
||||
let uri = request_uri(context)?;
|
||||
let mut headers = HeaderMap::new();
|
||||
for (name, value) in context.headers().iter_raw() {
|
||||
headers.append(name.clone(), value.clone());
|
||||
}
|
||||
let mut headers = if context.raw_query().is_empty()
|
||||
&& let Some(handed) = context
|
||||
.transport_extensions()
|
||||
.get::<EarlyAuthHandoff>()
|
||||
.and_then(|handoff| handoff.take_headers(Arc::as_ptr(server_ctx) as usize))
|
||||
{
|
||||
handed
|
||||
} else {
|
||||
let mut map = HeaderMap::with_capacity(16);
|
||||
for (name, value) in context.headers().iter_raw() {
|
||||
map.append(name.clone(), value.clone());
|
||||
}
|
||||
map
|
||||
};
|
||||
if !headers.contains_key(http::header::HOST)
|
||||
&& let Some(authority) = context.target_authority()
|
||||
{
|
||||
|
||||
@@ -21,12 +21,14 @@ use crate::app::object_usecase::{
|
||||
};
|
||||
use crate::app::{Answered, RequestEnvelope};
|
||||
use crate::runtime_sources::AppContext;
|
||||
use crate::server::gateway_stack::EarlyAuthHandoff;
|
||||
use crate::storage_api::server::http::access::access_owned::object_read::{
|
||||
authorize_get_object, authorize_get_object_attributes, authorize_head_object,
|
||||
authorize_get_object, authorize_get_object_attributes, authorize_head_object, finish_early_authorized_read,
|
||||
};
|
||||
use rustfs_gateway::{Req, Resp, dto};
|
||||
use rustfs_s3_ops::S3Operation;
|
||||
use rustfs_s3_types::{S3ErrorCode, S3Result, s3_error};
|
||||
use rustfs_utils::http::{SUFFIX_SOURCE_REPLICATION_CHECK, get_header};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) const ROWS: &[OpRow] = &[
|
||||
@@ -43,14 +45,22 @@ impl Served for dto::HeadObject {
|
||||
.server_context()
|
||||
.cloned()
|
||||
.ok_or_else(|| s3_error!(InternalError, "server context is missing"))?;
|
||||
authorize_head_object(
|
||||
&server_ctx,
|
||||
envelope,
|
||||
input.bucket.as_str(),
|
||||
input.key.as_str(),
|
||||
input.version_id.as_deref(),
|
||||
)
|
||||
.await
|
||||
let bucket = input.bucket.as_str();
|
||||
let key = input.key.as_str();
|
||||
let version_id = input.version_id.as_deref();
|
||||
if get_header(envelope.headers(), SUFFIX_SOURCE_REPLICATION_CHECK).as_deref() != Some("true")
|
||||
&& let Some(source_generation) =
|
||||
request
|
||||
.context()
|
||||
.transport_extensions()
|
||||
.get::<EarlyAuthHandoff>()
|
||||
.and_then(|handoff| {
|
||||
handoff.take_authorized_read(Arc::as_ptr(&server_ctx) as usize, Self::NAME, bucket, key, version_id)
|
||||
})
|
||||
{
|
||||
return finish_early_authorized_read(envelope, bucket, key, version_id, source_generation);
|
||||
}
|
||||
authorize_head_object(&server_ctx, envelope, bucket, key, version_id).await
|
||||
}
|
||||
async fn execute(context: Option<Arc<AppContext>>, envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
|
||||
let result = DefaultObjectUsecase::with_context(context)
|
||||
@@ -68,14 +78,20 @@ impl Served for dto::GetObject {
|
||||
.server_context()
|
||||
.cloned()
|
||||
.ok_or_else(|| s3_error!(InternalError, "server context is missing"))?;
|
||||
authorize_get_object(
|
||||
&server_ctx,
|
||||
envelope,
|
||||
input.bucket.as_str(),
|
||||
input.key.as_str(),
|
||||
input.version_id.as_deref(),
|
||||
)
|
||||
.await
|
||||
let bucket = input.bucket.as_str();
|
||||
let key = input.key.as_str();
|
||||
let version_id = input.version_id.as_deref();
|
||||
if let Some(source_generation) = request
|
||||
.context()
|
||||
.transport_extensions()
|
||||
.get::<EarlyAuthHandoff>()
|
||||
.and_then(|handoff| {
|
||||
handoff.take_authorized_read(Arc::as_ptr(&server_ctx) as usize, Self::NAME, bucket, key, version_id)
|
||||
})
|
||||
{
|
||||
return finish_early_authorized_read(envelope, bucket, key, version_id, source_generation);
|
||||
}
|
||||
authorize_get_object(&server_ctx, envelope, bucket, key, version_id).await
|
||||
}
|
||||
async fn execute(context: Option<Arc<AppContext>>, envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
|
||||
let log_error = super::error::object_error_logger("GetObject", request.context().transport_extensions().clone());
|
||||
|
||||
@@ -350,6 +350,7 @@ impl GatewayStack {
|
||||
let extensions = request.extensions_mut();
|
||||
extensions.remove::<KeystoneEstablished>();
|
||||
extensions.remove::<OwnedKeystoneIdentity>();
|
||||
extensions.remove::<EarlyAuthHandoff>();
|
||||
let validation = extensions.remove::<rustfs_keystone::KeystoneRequestIdentity>();
|
||||
let valid = match (validation, self.keystone_auth.as_ref()) {
|
||||
(Some(validation), Some(provider)) => {
|
||||
@@ -370,6 +371,7 @@ impl GatewayStack {
|
||||
(Some(_), None) => false,
|
||||
(None, _) => true,
|
||||
};
|
||||
extensions.insert(EarlyAuthHandoff::new());
|
||||
let secure_transport = attach_host_facts(extensions);
|
||||
let refusal_request_id = unsigned_extension_refusal.as_ref().map(|_| {
|
||||
extensions
|
||||
@@ -626,18 +628,130 @@ impl RequestIdCarrier for RequestContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// One-shot per-request handoff from [`super::gateway_authorizer::EarlyAuthorizer`] to
|
||||
/// [`super::gateway_handlers`], installed fresh on every request in [`GatewayStack::call`].
|
||||
/// Avoids repeating identical credential resolution and policy evaluation on the hot read path
|
||||
/// while requiring exact binding to `server_ctx`, caller identity, and operation target.
|
||||
#[derive(Clone, Default)]
|
||||
pub(in crate::server) struct EarlyAuthHandoff {
|
||||
slot: Arc<parking_lot::Mutex<Option<EarlyAuthHandoffState>>>,
|
||||
}
|
||||
|
||||
struct EarlyAuthHandoffState {
|
||||
server_ctx_ptr: usize,
|
||||
access_key: Option<String>,
|
||||
session_token: Option<String>,
|
||||
req_info: Option<crate::storage_api::server::http::access::ReqInfo>,
|
||||
headers: Option<http::HeaderMap>,
|
||||
authorized_read: Option<AuthorizedReadProof>,
|
||||
}
|
||||
|
||||
pub(in crate::server) struct AuthorizedReadProof {
|
||||
pub(in crate::server) operation: &'static str,
|
||||
pub(in crate::server) bucket: String,
|
||||
pub(in crate::server) key: String,
|
||||
pub(in crate::server) version_id: Option<String>,
|
||||
/// Migration source generation captured prior to early policy evaluation so recreating the
|
||||
/// bucket between early authorization and handler entry cannot rebind the read to a new bucket.
|
||||
pub(in crate::server) odm_read_generation: crate::storage_api::server::http::access::OdmReadGenerationGuard,
|
||||
}
|
||||
|
||||
impl EarlyAuthHandoff {
|
||||
pub(in crate::server) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub(in crate::server) fn store(
|
||||
&self,
|
||||
server_ctx_ptr: usize,
|
||||
access_key: Option<String>,
|
||||
session_token: Option<String>,
|
||||
req_info: crate::storage_api::server::http::access::ReqInfo,
|
||||
headers: Option<http::HeaderMap>,
|
||||
authorized_read: Option<AuthorizedReadProof>,
|
||||
) {
|
||||
*self.slot.lock() = Some(EarlyAuthHandoffState {
|
||||
server_ctx_ptr,
|
||||
access_key,
|
||||
session_token,
|
||||
req_info: Some(req_info),
|
||||
headers,
|
||||
authorized_read,
|
||||
});
|
||||
}
|
||||
|
||||
pub(in crate::server) fn take_headers(&self, server_ctx_ptr: usize) -> Option<http::HeaderMap> {
|
||||
let mut guard = self.slot.lock();
|
||||
let state = guard.as_mut()?;
|
||||
if state.server_ctx_ptr != server_ctx_ptr {
|
||||
return None;
|
||||
}
|
||||
state.headers.take()
|
||||
}
|
||||
|
||||
pub(in crate::server) fn take_caller(
|
||||
&self,
|
||||
server_ctx_ptr: usize,
|
||||
access_key: Option<&str>,
|
||||
session_token: &str,
|
||||
) -> Option<crate::storage_api::server::http::access::ReqInfo> {
|
||||
let mut guard = self.slot.lock();
|
||||
let state = guard.as_mut()?;
|
||||
let token_matches = state.session_token.as_deref().unwrap_or("") == session_token;
|
||||
if state.server_ctx_ptr != server_ctx_ptr || state.access_key.as_deref() != access_key || !token_matches {
|
||||
*guard = None;
|
||||
return None;
|
||||
}
|
||||
state.req_info.take()
|
||||
}
|
||||
|
||||
pub(in crate::server) fn take_authorized_read(
|
||||
&self,
|
||||
server_ctx_ptr: usize,
|
||||
operation: &'static str,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
version_id: Option<&str>,
|
||||
) -> Option<crate::storage_api::server::http::access::OdmReadGenerationGuard> {
|
||||
let mut guard = self.slot.lock();
|
||||
let state = guard.take()?;
|
||||
if state.server_ctx_ptr != server_ctx_ptr {
|
||||
return None;
|
||||
}
|
||||
let proof = state.authorized_read?;
|
||||
if proof.operation == operation && proof.bucket == bucket && proof.key == key && proof.version_id.as_deref() == version_id
|
||||
{
|
||||
Some(proof.odm_read_generation)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The root credentials of one server as they are now, read strictly from this server's installed
|
||||
/// `AppContext` (never falling back to process-global credentials or token-signing keys). `None`
|
||||
/// while this server context is uninstalled, lacks root credentials, or cannot verify a signature,
|
||||
/// which the adapters answer as unavailable.
|
||||
pub(super) fn live_root(server_ctx: Arc<ServerContextSlot>) -> impl Fn() -> Option<Arc<RootCredentials>> + Send + Sync + 'static {
|
||||
let cached: parking_lot::RwLock<Option<(String, String, Arc<RootCredentials>)>> = parking_lot::RwLock::new(None);
|
||||
move || {
|
||||
let root = server_ctx.installed_app_context()?.action_credentials().get()?;
|
||||
{
|
||||
let guard = cached.read();
|
||||
if let Some((ak, sk, creds)) = guard.as_ref()
|
||||
&& crate::auth::constant_time_eq(ak, &root.access_key)
|
||||
&& crate::auth::constant_time_eq(sk, &root.secret_key)
|
||||
{
|
||||
return Some(Arc::clone(creds));
|
||||
}
|
||||
}
|
||||
// Match `check_claims_from_token_with_context`: STS session tokens are signed with this
|
||||
// server context's root secret rather than a process-global key.
|
||||
RootCredentials::new(&root.access_key, &root.secret_key, &root.secret_key)
|
||||
let built = RootCredentials::new(&root.access_key, &root.secret_key, &root.secret_key)
|
||||
.ok()
|
||||
.map(Arc::new)
|
||||
.map(Arc::new)?;
|
||||
*cached.write() = Some((root.access_key, root.secret_key, Arc::clone(&built)));
|
||||
Some(built)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1371,3 +1371,147 @@ async fn production_gateway_stack_blocks_presigned_sigv4a_upload_part_replicatio
|
||||
);
|
||||
assert!(body.contains("<Code>AccessDenied</Code>"), "{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_auth_handoff_enforces_exact_binding_and_one_shot_consumption() {
|
||||
use crate::storage_api::server::http::access::{OdmReadGenerationGuard, ReqInfo};
|
||||
|
||||
let handoff = EarlyAuthHandoff::new();
|
||||
let info = ReqInfo {
|
||||
is_owner: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut sample_headers = http::HeaderMap::new();
|
||||
sample_headers.insert(http::header::HOST, http::HeaderValue::from_static("example.test"));
|
||||
let expected_guard = OdmReadGenerationGuard::Failed {
|
||||
code: rustfs_s3_types::S3ErrorCode::NoSuchBucket,
|
||||
message: "captured-pre-authz".to_owned(),
|
||||
};
|
||||
handoff.store(
|
||||
42,
|
||||
Some("ak-1".to_owned()),
|
||||
Some("tok-1".to_owned()),
|
||||
info,
|
||||
Some(sample_headers),
|
||||
Some(AuthorizedReadProof {
|
||||
operation: "GetObject",
|
||||
bucket: "b".to_owned(),
|
||||
key: "k".to_owned(),
|
||||
version_id: Some("v1".to_owned()),
|
||||
odm_read_generation: expected_guard,
|
||||
}),
|
||||
);
|
||||
|
||||
// Header handoff matches server_ctx and is one-shot.
|
||||
assert!(handoff.take_headers(999).is_none(), "wrong server_ctx must not consume headers");
|
||||
let handed_headers = handoff.take_headers(42).expect("matching server_ctx must take headers");
|
||||
assert_eq!(handed_headers.get(http::header::HOST).unwrap(), "example.test");
|
||||
assert!(handoff.take_headers(42).is_none(), "header handoff must be one-shot");
|
||||
|
||||
// Caller binding succeeds once and rejects second consumption.
|
||||
let taken = handoff
|
||||
.take_caller(42, Some("ak-1"), "tok-1")
|
||||
.expect("matching caller must succeed");
|
||||
assert!(taken.is_owner);
|
||||
assert!(handoff.take_caller(42, Some("ak-1"), "tok-1").is_none(), "caller handoff is one-shot");
|
||||
|
||||
// Read proof must match server_ctx, operation, bucket, key, and version_id, preserve its
|
||||
// captured ODM read generation, and be one-shot.
|
||||
let taken_guard = handoff
|
||||
.take_authorized_read(42, "GetObject", "b", "k", Some("v1"))
|
||||
.expect("matching read proof must succeed");
|
||||
match taken_guard {
|
||||
OdmReadGenerationGuard::Failed { code, message } => {
|
||||
assert_eq!(code, rustfs_s3_types::S3ErrorCode::NoSuchBucket);
|
||||
assert_eq!(message, "captured-pre-authz");
|
||||
}
|
||||
other => panic!("expected preserved pre-authz ODM guard, got {other:?}"),
|
||||
}
|
||||
assert!(
|
||||
handoff.take_authorized_read(42, "GetObject", "b", "k", Some("v1")).is_none(),
|
||||
"read proof must be one-shot"
|
||||
);
|
||||
|
||||
// A caller mismatch must also invalidate any stored read proof.
|
||||
handoff.store(
|
||||
42,
|
||||
Some("ak-1".to_owned()),
|
||||
None,
|
||||
ReqInfo::default(),
|
||||
None,
|
||||
Some(AuthorizedReadProof {
|
||||
operation: "GetObject",
|
||||
bucket: "b".to_owned(),
|
||||
key: "k".to_owned(),
|
||||
version_id: None,
|
||||
odm_read_generation: OdmReadGenerationGuard::Unavailable,
|
||||
}),
|
||||
);
|
||||
assert!(handoff.take_caller(42, Some("ak-other"), "").is_none());
|
||||
assert!(
|
||||
handoff.take_authorized_read(42, "GetObject", "b", "k", None).is_none(),
|
||||
"caller mismatch must clear the read proof"
|
||||
);
|
||||
|
||||
// Target mismatch must reject and consume the proof.
|
||||
handoff.store(
|
||||
42,
|
||||
Some("ak-1".to_owned()),
|
||||
None,
|
||||
ReqInfo::default(),
|
||||
None,
|
||||
Some(AuthorizedReadProof {
|
||||
operation: "GetObject",
|
||||
bucket: "b".to_owned(),
|
||||
key: "k".to_owned(),
|
||||
version_id: None,
|
||||
odm_read_generation: OdmReadGenerationGuard::Unavailable,
|
||||
}),
|
||||
);
|
||||
assert!(
|
||||
handoff
|
||||
.take_authorized_read(42, "GetObject", "b", "other-key", None)
|
||||
.is_none()
|
||||
);
|
||||
assert!(handoff.take_authorized_read(42, "GetObject", "b", "k", None).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn live_root_caches_arc_and_invalidates_on_credential_rotation() {
|
||||
let store = crate::app::gating_test_env::shared_gating_ecstore().await;
|
||||
if crate::runtime_sources::current_app_context().is_none() {
|
||||
crate::runtime_sources::install_test_app_context(Arc::clone(&store)).await;
|
||||
}
|
||||
let ambient = crate::runtime_sources::current_app_context().expect("ambient context");
|
||||
let context = Arc::new(crate::runtime_sources::AppContext::new(Arc::clone(&store), ambient.iam(), ambient.kms()));
|
||||
assert!(context.publish_action_credentials(rustfs_credentials::Credentials {
|
||||
access_key: "cachedrootone".to_owned(),
|
||||
secret_key: "cached-root-secret-one".to_owned(),
|
||||
status: "on".to_owned(),
|
||||
..Default::default()
|
||||
}));
|
||||
let slot = ServerContextSlot::new();
|
||||
assert!(slot.install(Arc::clone(&context)));
|
||||
|
||||
let lookup = live_root(Arc::clone(&slot));
|
||||
let first = lookup().expect("first root lookup");
|
||||
let second = lookup().expect("second root lookup");
|
||||
assert!(
|
||||
Arc::ptr_eq(&first, &second),
|
||||
"unchanged credentials must reuse cached Arc<RootCredentials>"
|
||||
);
|
||||
|
||||
let _ = context.publish_action_credentials(rustfs_credentials::Credentials {
|
||||
access_key: "cachedroottwo".to_owned(),
|
||||
secret_key: "cached-root-secret-two".to_owned(),
|
||||
status: "on".to_owned(),
|
||||
..Default::default()
|
||||
});
|
||||
let rotated = lookup().expect("rotated root lookup");
|
||||
assert!(
|
||||
!Arc::ptr_eq(&first, &rotated),
|
||||
"credential rotation must invalidate cached Arc<RootCredentials>"
|
||||
);
|
||||
assert_eq!(rotated.access_key(), "cachedroottwo");
|
||||
}
|
||||
|
||||
+57
-27
@@ -50,9 +50,21 @@ pub(super) fn claims_native_admin_read(method: &Method, uri: &Uri) -> bool {
|
||||
}
|
||||
|
||||
/// The S3 service of one server: the gateway stack with its website and control-plane services.
|
||||
#[derive(Clone)]
|
||||
///
|
||||
/// The route table is shared behind an `Arc` so cloning `S3StackService` across the outer Tower
|
||||
/// middleware stack costs a single reference-count bump instead of cloning every mounted host.
|
||||
/// `poll_ready` and `call` detach once via `Arc::make_mut` so Tower readiness and dispatch run on
|
||||
/// the same mutable `GatewayServices` instance.
|
||||
pub(crate) struct S3StackService<G, C = G, W = G> {
|
||||
services: GatewayServices<G, C, W>,
|
||||
services: Arc<GatewayServices<G, C, W>>,
|
||||
}
|
||||
|
||||
impl<G, C, W> Clone for S3StackService<G, C, W> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
services: Arc::clone(&self.services),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The encoded path selected for S3, without the pre-authentication query.
|
||||
@@ -91,67 +103,85 @@ impl<G> S3StackService<G> {
|
||||
/// The stack around the gateway S3 service `s3`, with no other host attached yet.
|
||||
pub(crate) fn new(s3: G) -> Self {
|
||||
Self {
|
||||
services: GatewayServices {
|
||||
services: Arc::new(GatewayServices {
|
||||
s3,
|
||||
native_website: None,
|
||||
native_console: None,
|
||||
reserved_console: None,
|
||||
native_admin: None,
|
||||
control_plane: None,
|
||||
},
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<G, C, W> S3StackService<G, C, W> {
|
||||
impl<G, C, W> S3StackService<G, C, W>
|
||||
where
|
||||
G: Clone,
|
||||
C: Clone,
|
||||
W: Clone,
|
||||
{
|
||||
fn into_services(self) -> GatewayServices<G, C, W> {
|
||||
Arc::unwrap_or_clone(self.services)
|
||||
}
|
||||
|
||||
/// Attaches the native console service.
|
||||
pub(crate) fn with_native_console<N>(self, native_console: Option<N>) -> S3StackService<G, N, W> {
|
||||
let services = self.services;
|
||||
let services = self.into_services();
|
||||
S3StackService {
|
||||
services: GatewayServices {
|
||||
services: Arc::new(GatewayServices {
|
||||
s3: services.s3,
|
||||
native_website: services.native_website,
|
||||
native_console,
|
||||
reserved_console: services.reserved_console,
|
||||
native_admin: services.native_admin,
|
||||
control_plane: services.control_plane,
|
||||
},
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Attaches the reserved-console SigV4 host used when the native console is disabled on this
|
||||
/// listener (e.g. the S3 port while a dedicated console listener serves assets).
|
||||
pub(crate) fn with_reserved_console(mut self, reserved_console: Option<G>) -> Self {
|
||||
self.services.reserved_console = reserved_console;
|
||||
self
|
||||
pub(crate) fn with_reserved_console(self, reserved_console: Option<G>) -> Self {
|
||||
let mut services = self.into_services();
|
||||
services.reserved_console = reserved_console;
|
||||
Self {
|
||||
services: Arc::new(services),
|
||||
}
|
||||
}
|
||||
|
||||
/// Attaches the website service: every request `claim` selects goes to it before any other
|
||||
/// routing.
|
||||
pub(crate) fn with_native_website<N>(self, native_website: Option<(HostClaim, N)>) -> S3StackService<G, C, N> {
|
||||
let services = self.services;
|
||||
let services = self.into_services();
|
||||
S3StackService {
|
||||
services: GatewayServices {
|
||||
services: Arc::new(GatewayServices {
|
||||
s3: services.s3,
|
||||
native_website,
|
||||
native_console: services.native_console,
|
||||
reserved_console: services.reserved_console,
|
||||
native_admin: services.native_admin,
|
||||
control_plane: services.control_plane,
|
||||
},
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Attaches the signed admin service.
|
||||
pub(crate) fn with_native_admin(mut self, native_admin: Option<G>) -> Self {
|
||||
self.services.native_admin = native_admin;
|
||||
self
|
||||
pub(crate) fn with_native_admin(self, native_admin: Option<G>) -> Self {
|
||||
let mut services = self.into_services();
|
||||
services.native_admin = native_admin;
|
||||
Self {
|
||||
services: Arc::new(services),
|
||||
}
|
||||
}
|
||||
|
||||
/// Attaches the host of every other claimed route.
|
||||
pub(crate) fn with_control_plane(mut self, control_plane: Option<G>) -> Self {
|
||||
self.services.control_plane = control_plane;
|
||||
self
|
||||
pub(crate) fn with_control_plane(self, control_plane: Option<G>) -> Self {
|
||||
let mut services = self.into_services();
|
||||
services.control_plane = control_plane;
|
||||
Self {
|
||||
services: Arc::new(services),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,9 +249,9 @@ impl<G, C, W> GatewayServices<G, C, W> {
|
||||
|
||||
impl<G, C, W, B, R, E> Service<Request<B>> for S3StackService<G, C, W>
|
||||
where
|
||||
G: Service<Request<B>, Response = http::Response<R>, Error = E>,
|
||||
C: Service<Request<B>, Response = http::Response<R>, Error = E>,
|
||||
W: Service<Request<B>, Response = http::Response<R>, Error = E>,
|
||||
G: Service<Request<B>, Response = http::Response<R>, Error = E> + Clone,
|
||||
C: Service<Request<B>, Response = http::Response<R>, Error = E> + Clone,
|
||||
W: Service<Request<B>, Response = http::Response<R>, Error = E> + Clone,
|
||||
G::Future: Send + 'static,
|
||||
C::Future: Send + 'static,
|
||||
W::Future: Send + 'static,
|
||||
@@ -232,7 +262,7 @@ where
|
||||
type Future = Answer<R, E>;
|
||||
|
||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
let services = &mut self.services;
|
||||
let services = Arc::make_mut(&mut self.services);
|
||||
ready!(services.s3.poll_ready(cx))?;
|
||||
for host in [
|
||||
&mut services.reserved_console,
|
||||
@@ -254,7 +284,7 @@ where
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Request<B>) -> Self::Future {
|
||||
self.services.call(request)
|
||||
Arc::make_mut(&mut self.services).call(request)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -629,8 +659,8 @@ mod tests {
|
||||
|
||||
async fn answered_by_any<C, W>(service: &mut S3StackService<Named, C, W>, request: Request<()>) -> &'static str
|
||||
where
|
||||
C: Service<Request<()>, Response = Response<&'static str>, Error = Infallible>,
|
||||
W: Service<Request<()>, Response = Response<&'static str>, Error = Infallible>,
|
||||
C: Service<Request<()>, Response = Response<&'static str>, Error = Infallible> + Clone,
|
||||
W: Service<Request<()>, Response = Response<&'static str>, Error = Infallible> + Clone,
|
||||
C::Future: Send + 'static,
|
||||
W::Future: Send + 'static,
|
||||
{
|
||||
|
||||
@@ -21,8 +21,9 @@
|
||||
//! Upstream: the legacy hook in `storage/access.rs` and the batch's `server/gateway_handlers/object_read.rs`.
|
||||
//! Downstream: the shared shapes in `storage/access.rs`.
|
||||
|
||||
pub(crate) use crate::storage::authorization::capture_odm_read_generation;
|
||||
use crate::storage::authorization::{
|
||||
AuthorizationRequest, authorize_object_request, authorize_request, capture_odm_read_generation, req_info_mut,
|
||||
AuthorizationRequest, OdmReadGenerationGuard, authorize_object_request, authorize_request, req_info_mut,
|
||||
};
|
||||
use crate::storage::authorization_actions::versioned_read_action;
|
||||
use crate::storage::storage_api::runtime_sources_consumer::ServerContextSlot;
|
||||
@@ -44,6 +45,26 @@ pub(crate) async fn authorize_get_object<R: AuthorizationRequest + ?Sized>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies handler-side read guards (signed query hoisting, `ReqInfo` target binding, and the
|
||||
/// `OdmReadGenerationGuard` captured before early policy evaluation) after the gateway's early
|
||||
/// gate already approved the exact same versioned read policy check.
|
||||
pub(crate) fn finish_early_authorized_read<R: AuthorizationRequest + ?Sized>(
|
||||
req: &mut R,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
version_id: Option<&str>,
|
||||
source_generation: OdmReadGenerationGuard,
|
||||
) -> S3Result<()> {
|
||||
let query = req.uri().query().map(str::to_owned);
|
||||
crate::auth::hoist_signed_query_params(req.headers_mut(), query.as_deref())?;
|
||||
let info = req_info_mut(req)?;
|
||||
info.bucket = Some(bucket.to_owned());
|
||||
info.object = Some(key.to_owned());
|
||||
info.version_id = version_id.map(str::to_owned);
|
||||
req.install_odm_read_generation(source_generation);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Both HEAD edges retain the captured ODM generation and the additional replication decision.
|
||||
pub(crate) async fn authorize_head_object<R: AuthorizationRequest + ?Sized>(
|
||||
server_ctx: &ServerContextSlot,
|
||||
|
||||
@@ -358,10 +358,73 @@ pub(crate) async fn authorize_request_core<R: AuthorizationRequest + ?Sized>(
|
||||
location_constraint: Option<String>,
|
||||
internal_object_authorization: bool,
|
||||
) -> S3Result<()> {
|
||||
if can_take_owner_read_fast_path(req, action, location_constraint.as_deref(), internal_object_authorization)
|
||||
&& try_owner_read_fast_path(req).await?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let facts = policy_request_facts(req, action, location_constraint.as_deref())?;
|
||||
authorize_request_with_facts(req, &facts, internal_object_authorization).await
|
||||
}
|
||||
|
||||
/// Checks whether a root/owner object read can be decided from a single bucket metadata snapshot
|
||||
/// without building full policy facts/conditions (only when no bucket policy and no table bucket
|
||||
/// exist; any policy, table bucket, STS credential, probe, or error falls back to full evaluation).
|
||||
fn can_take_owner_read_fast_path<R: AuthorizationRequest + ?Sized>(
|
||||
req: &R,
|
||||
action: Action,
|
||||
location_constraint: Option<&str>,
|
||||
internal_object_authorization: bool,
|
||||
) -> bool {
|
||||
if internal_object_authorization
|
||||
|| location_constraint.is_some()
|
||||
|| req.permission_probe()
|
||||
|| req.uri().query().is_some()
|
||||
|| !matches!(action, Action::S3Action(S3Action::GetObjectAction | S3Action::GetObjectVersionAction))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some(req_info) = req.req_info() else {
|
||||
return false;
|
||||
};
|
||||
if !req_info.is_owner {
|
||||
return false;
|
||||
}
|
||||
let Some(cred) = req_info.cred.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
if !cred.session_token.is_empty()
|
||||
|| cred.is_temp()
|
||||
|| cred.is_service_account()
|
||||
|| cred
|
||||
.claims
|
||||
.as_ref()
|
||||
.is_some_and(|claims| claims.contains_key(rustfs_iam::sys::PLUGIN_ATTEMPT_CREDENTIAL_CLAIM))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let bucket = req_info.bucket.as_deref().unwrap_or_default();
|
||||
!bucket.is_empty() && !is_reserved_meta_bucket(bucket)
|
||||
}
|
||||
|
||||
async fn try_owner_read_fast_path<R: AuthorizationRequest + ?Sized>(req: &R) -> S3Result<bool> {
|
||||
let req_info = req.req_info().ok_or_else(missing_req_info_error)?;
|
||||
let Some(cred) = req_info.cred.as_ref() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let bucket = req_info.bucket.as_deref().unwrap_or_default();
|
||||
let store = request_object_store(req)?;
|
||||
let iam_store = request_iam_store(req)?;
|
||||
if iam_store.has_sts_account(&cred.access_key) {
|
||||
return Ok(false);
|
||||
}
|
||||
match store.get_bucket_authz_snapshot(bucket).await {
|
||||
Ok(snapshot) if !snapshot.has_policy && !snapshot.table_bucket_enabled => Ok(true),
|
||||
Err(StorageError::ConfigNotFound) => Ok(true),
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks whether a caller may learn that the current object is absent. Only called
|
||||
/// on a terminal read error, after the original object authorization succeeded.
|
||||
pub(crate) async fn authorize_missing_object_disclosure<R: AuthorizationRequest + ?Sized>(req: &mut R) -> S3Result<()> {
|
||||
|
||||
Reference in New Issue
Block a user