feat(gateway): serve bucket public access block operations

Route Get, Put, and DeletePublicAccessBlock through shared bucket use
cases. Preserve the persisted switch values, mutation incarnation fence,
reload behavior, audit status, and missing-configuration response.

Add six focused tests covering 25 refusal cases and 17 success cases
across both stacks and storage. Extend the refusal and counter matrix
for all three operations.

Substitute each IAM action and bucket, corrupt each operation's value,
change the missing-config status, and suppress each edge counter. The
round-trip and matrix tests reject those faults. Put and Delete tests
reject a missing incarnation fence, the wrong reload mode, and wrong
audit status. Read the durable replacement-bucket bytes after disabling
both fences.

Verify on 92050cdca with scoped nextest, both Clippy modes, script tests,
and local wire tests. Peer reload delivery was outside these local tests.
This commit is contained in:
overtrue
2026-11-16 02:08:14 +08:00
parent 3cb0aa137e
commit 4294c41ccf
5 changed files with 514 additions and 118 deletions
@@ -15,100 +15,97 @@
//! Bucket public access block use-case operations.
use super::*;
use crate::app::storage_api::s3::dto::{
DeletePublicAccessBlockInput, DeletePublicAccessBlockOutput, GetPublicAccessBlockInput, PutPublicAccessBlockInput,
PutPublicAccessBlockOutput,
};
use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Request, S3Response, S3Result};
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result};
impl DefaultBucketUsecase {
#[instrument(level = "debug", skip(self, req))]
pub async fn execute_delete_public_access_block(
&self,
req: S3Request<DeletePublicAccessBlockInput>,
) -> S3Result<S3Response<DeletePublicAccessBlockOutput>> {
let expected_incarnation_id = bucket_config_mutation_incarnation(&req, &req.input.bucket)?;
let request_context = req.extensions.get::<request_context::RequestContext>().cloned();
let DeletePublicAccessBlockInput { bucket, .. } = req.input;
#[instrument(level = "debug", skip(self, envelope))]
pub(crate) async fn execute_delete_public_access_block(&self, envelope: RequestEnvelope, bucket: &str) -> S3Result<()> {
RequestEnvelope::audit_only_operation(
envelope,
S3Operation::DeletePublicAccessBlock,
StatusCode::NO_CONTENT,
|envelope| async move {
let expected_incarnation_id = bucket_config_mutation_incarnation(&envelope, bucket)?;
let request_context = envelope.request_context().cloned();
let Some(store) = self.object_store() else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init".to_string()));
};
let Some(store) = self.object_store() else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init"));
};
store
.get_bucket_info(bucket, &BucketOptions::default())
.await
.map_err(ApiError::from)?;
store
.get_bucket_info(&bucket, &BucketOptions::default())
.await
.map_err(ApiError::from)?;
delete_bucket_config_for_incarnation(&bucket, BUCKET_PUBLIC_ACCESS_BLOCK_CONFIG, expected_incarnation_id)
.await
.map_err(ApiError::from)?;
notify_bucket_metadata_reload(bucket.clone(), "delete public access block", request_context, false).await;
Ok(S3Response::with_status(DeletePublicAccessBlockOutput::default(), StatusCode::NO_CONTENT))
delete_bucket_config_for_incarnation(bucket, BUCKET_PUBLIC_ACCESS_BLOCK_CONFIG, expected_incarnation_id)
.await
.map_err(ApiError::from)?;
notify_bucket_metadata_reload(bucket.to_owned(), "delete public access block", request_context, false).await;
Ok(())
},
)
.await
}
#[instrument(level = "debug", skip(self, req))]
pub async fn execute_get_public_access_block(
#[instrument(level = "debug", skip(self))]
pub(crate) async fn execute_get_public_access_block(
&self,
req: S3Request<GetPublicAccessBlockInput>,
bucket: &str,
) -> S3Result<PersistedPublicAccessBlockConfiguration> {
let GetPublicAccessBlockInput { bucket, .. } = req.input;
let Some(store) = self.object_store() else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init".to_string()));
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init"));
};
store
.get_bucket_info(&bucket, &BucketOptions::default())
.get_bucket_info(bucket, &BucketOptions::default())
.await
.map_err(ApiError::from)?;
let config = match metadata_sys::get_public_access_block_config(&bucket).await {
Ok((config, _)) => config,
Err(err) => {
if err == StorageError::ConfigNotFound {
return Err(S3Error::with_message(
S3ErrorCode::Custom("NoSuchPublicAccessBlockConfiguration".into()),
"Public access block configuration does not exist".to_string(),
));
}
return Err(ApiError::from(err).into());
match metadata_sys::get_public_access_block_config(bucket).await {
Ok((config, _)) => Ok(config),
Err(StorageError::ConfigNotFound) => {
let mut error = S3Error::with_message(
S3ErrorCode::Custom("NoSuchPublicAccessBlockConfiguration".into()),
"Public access block configuration does not exist",
);
// The legacy edge used the custom code with the server-error status.
error.set_status_code(StatusCode::INTERNAL_SERVER_ERROR);
Err(error)
}
};
Ok(config)
Err(err) => Err(ApiError::from(err).into()),
}
}
#[instrument(level = "debug", skip(self, req))]
pub async fn execute_put_public_access_block(
#[instrument(level = "debug", skip(self, envelope, prepared))]
pub(crate) async fn execute_put_public_access_block(
&self,
req: S3Request<PutPublicAccessBlockInput>,
envelope: RequestEnvelope,
bucket: &str,
prepared: S3Result<PersistedPublicAccessBlockConfiguration>,
) -> S3Result<S3Response<PutPublicAccessBlockOutput>> {
let expected_incarnation_id = bucket_config_mutation_incarnation(&req, &req.input.bucket)?;
let request_context = req.extensions.get::<request_context::RequestContext>().cloned();
let PutPublicAccessBlockInput { bucket, .. } = req.input;
) -> S3Result<()> {
RequestEnvelope::audit_only_operation(
envelope,
S3Operation::PutPublicAccessBlock,
StatusCode::OK,
|envelope| async move {
let expected_incarnation_id = bucket_config_mutation_incarnation(&envelope, bucket)?;
let request_context = envelope.request_context().cloned();
let Some(store) = self.object_store() else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init".to_string()));
};
let Some(store) = self.object_store() else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init"));
};
store
.get_bucket_info(bucket, &BucketOptions::default())
.await
.map_err(ApiError::from)?;
store
.get_bucket_info(&bucket, &BucketOptions::default())
.await
.map_err(ApiError::from)?;
let public_access_block_configuration = prepared?;
let data = serialize_config(&public_access_block_configuration)?;
update_bucket_config_for_incarnation(&bucket, BUCKET_PUBLIC_ACCESS_BLOCK_CONFIG, data, expected_incarnation_id)
.await
.map_err(ApiError::from)?;
notify_bucket_metadata_reload(bucket.clone(), "put public access block", request_context, false).await;
Ok(S3Response::new(PutPublicAccessBlockOutput::default()))
let data = serialize_config(&prepared?)?;
update_bucket_config_for_incarnation(bucket, BUCKET_PUBLIC_ACCESS_BLOCK_CONFIG, data, expected_incarnation_id)
.await
.map_err(ApiError::from)?;
notify_bucket_metadata_reload(bucket.to_owned(), "put public access block", request_context, false).await;
Ok(())
},
)
.await
}
}
@@ -116,50 +113,193 @@ impl DefaultBucketUsecase {
mod tests {
use super::*;
use crate::app::bucket_usecase::test_support::build_request;
use crate::app::storage_api::s3::dto::PublicAccessBlockConfiguration;
use crate::app::gating_test_env::{run_large_stack_test, shared_gating_ambient};
use crate::app::runtime_sources::ServerContextSlot;
use crate::app::storage_api::bucket_usecase::helper::MutationCompletionProbe;
use crate::app::storage_api::owned_parity::authorize_bucket_config_mutation;
use http::Method;
use rustfs_credentials::Credentials;
use rustfs_policy::policy::action::{Action, S3Action};
use serial_test::serial;
use std::sync::Mutex;
const ORIGINAL_XML: &[u8] =
b"<PublicAccessBlockConfiguration><BlockPublicPolicy>true</BlockPublicPolicy></PublicAccessBlockConfiguration>";
async fn public_access_block_mutation(put: bool, stale: bool) {
let (method, action, operation, reload, status) = if put {
(
Method::PUT,
S3Action::PutBucketPublicAccessBlockAction,
S3Operation::PutPublicAccessBlock,
"put public access block",
200,
)
} else {
(
Method::DELETE,
S3Action::DeleteBucketPublicAccessBlockAction,
S3Operation::DeletePublicAccessBlock,
"delete public access block",
204,
)
};
let context = shared_gating_ambient().await;
let store = context.object_store();
let bucket = format!("public-access-block-{}", uuid::Uuid::new_v4().simple());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
let server = ServerContextSlot::new();
assert!(server.install(Arc::clone(&context)));
let mut request = build_request((), method);
request.uri = format!("/{bucket}?publicAccessBlock").parse().expect("request URI");
request.extensions.insert(Arc::clone(&server));
request.extensions.insert(ReqInfo {
cred: Some(Credentials {
access_key: "public-access-block-owner".to_owned(),
..Default::default()
}),
is_owner: true,
..Default::default()
});
request.extensions.insert(request_context::RequestContext {
request_id: "public-access-block-fixture".to_owned(),
x_amz_request_id: "public-access-block-fixture".to_owned(),
trace_id: None,
span_id: None,
start_time: std::time::Instant::now(),
});
let mut envelope = RequestEnvelope::from_s3s(&request);
authorize_bucket_config_mutation(&server, &mut envelope, &bucket, Action::S3Action(action))
.await
.expect("bucket owner authorization installs the incarnation snapshot");
if stale {
store
.delete_bucket(&bucket, &DeleteBucketOptions::default())
.await
.expect("delete authorized bucket");
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("recreate bucket");
}
metadata_sys::update(&bucket, BUCKET_PUBLIC_ACCESS_BLOCK_CONFIG, ORIGINAL_XML.to_vec())
.await
.expect("seed config");
let usecase = DefaultBucketUsecase::with_context(Some(context));
let audits = MutationCompletionProbe::install(&bucket);
let reloads = Arc::new(Mutex::new(Vec::new()));
let record = Arc::clone(&reloads);
let result = BUCKET_METADATA_RELOAD_PROBE
.scope(
(
bucket.clone(),
Box::new(move |completed, label, maintenance| {
record.lock().expect("reload observer").push((completed, label, maintenance));
}),
),
async {
if put {
let config = PersistedPublicAccessBlockConfiguration {
block_public_policy: Some(false),
..Default::default()
};
usecase.execute_put_public_access_block(envelope, &bucket, Ok(config)).await
} else {
usecase.execute_delete_public_access_block(envelope, &bucket).await
}
},
)
.await;
let stored = metadata_sys::get_global_bucket_metadata_sys()
.expect("initialized metadata system")
.read()
.await
.get_config_from_disk(&bucket)
.await
.expect("persisted bucket metadata")
.public_access_block_config_xml;
let reloads = reloads.lock().expect("recorded reloads");
if stale {
assert_eq!(
result.expect_err("stale authorization must not mutate replacement").code(),
&S3ErrorCode::NoSuchBucket
);
assert_eq!(stored, ORIGINAL_XML);
assert!(reloads.is_empty());
} else {
result.expect("authorized mutation");
if put {
assert_eq!(stored, b"<PublicAccessBlockConfiguration><BlockPublicPolicy>false</BlockPublicPolicy></PublicAccessBlockConfiguration>");
} else {
assert!(stored.is_empty());
}
assert_eq!(
*reloads,
[(false, reload, false), (true, reload, false)],
"metadata reload completes without scanner maintenance"
);
let entries = audits.audits.lock().expect("audit entries");
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].api.name.as_deref(), Some(operation.as_str()));
assert_eq!(entries[0].api.status_code, Some(status));
assert!(audits.events.lock().expect("event entries").is_empty());
}
}
#[test]
#[serial]
fn put_public_access_block_rejects_stale_authorization() {
run_large_stack_test("public-access-block-put-stale", || public_access_block_mutation(true, true));
}
#[test]
#[serial]
fn delete_public_access_block_rejects_stale_authorization() {
run_large_stack_test("public-access-block-delete-stale", || public_access_block_mutation(false, true));
}
#[test]
#[serial]
fn put_public_access_block_reloads_and_audits() {
run_large_stack_test("public-access-block-put-completion", || public_access_block_mutation(true, false));
}
#[test]
#[serial]
fn delete_public_access_block_reloads_and_audits() {
run_large_stack_test("public-access-block-delete-completion", || public_access_block_mutation(false, false));
}
#[tokio::test]
async fn execute_delete_public_access_block_returns_internal_error_when_store_uninitialized() {
let input = DeletePublicAccessBlockInput::builder()
.bucket("test-bucket".to_string())
.build()
.unwrap();
let req = build_request(input, Method::DELETE);
let envelope = RequestEnvelope::from_s3s(&build_request((), Method::DELETE));
let usecase = DefaultBucketUsecase::without_context();
let err = usecase.execute_delete_public_access_block(req).await.unwrap_err();
let err = usecase
.execute_delete_public_access_block(envelope, "test-bucket")
.await
.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::InternalError);
}
#[tokio::test]
async fn execute_get_public_access_block_returns_internal_error_when_store_uninitialized() {
let input = GetPublicAccessBlockInput::builder()
.bucket("test-bucket".to_string())
.build()
.unwrap();
let req = build_request(input, Method::GET);
let usecase = DefaultBucketUsecase::without_context();
let err = usecase.execute_get_public_access_block(req).await.unwrap_err();
let err = usecase.execute_get_public_access_block("test-bucket").await.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::InternalError);
}
#[tokio::test]
async fn execute_put_public_access_block_returns_internal_error_when_store_uninitialized() {
let input = PutPublicAccessBlockInput::builder()
.bucket("test-bucket".to_string())
.public_access_block_configuration(PublicAccessBlockConfiguration::default())
.build()
.unwrap();
let req = build_request(input, Method::PUT);
let envelope = RequestEnvelope::from_s3s(&build_request((), Method::PUT));
let usecase = DefaultBucketUsecase::without_context();
let err = usecase
.execute_put_public_access_block(req, Ok(PersistedPublicAccessBlockConfiguration::default()))
.execute_put_public_access_block(envelope, "test-bucket", Ok(PersistedPublicAccessBlockConfiguration::default()))
.await
.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::InternalError);
@@ -22,7 +22,9 @@ use crate::app::{RequestEnvelope, dto_values};
use crate::runtime_sources::AppContext;
use crate::storage_api::server::http::access::authorize_bucket_request;
use rustfs_gateway::{Req, Resp, dto};
use rustfs_gateway_types::persistence::{parse_bucket_encryption_dto, parse_cors_dto, parse_tagging_dto};
use rustfs_gateway_types::persistence::{
PersistedPublicAccessBlockConfiguration, parse_bucket_encryption_dto, parse_cors_dto, parse_tagging_dto,
};
use rustfs_policy::policy::action::{Action, S3Action};
use rustfs_s3_ops::S3Operation;
use rustfs_s3_types::S3Result;
@@ -34,6 +36,9 @@ pub(super) const ROWS: &[OpRow] = &[
row::<dto::GetBucketTagging>(),
row::<dto::PutBucketCors>(),
row::<dto::DeleteBucketCors>(),
row::<dto::GetPublicAccessBlock>(),
row::<dto::PutPublicAccessBlock>(),
row::<dto::DeletePublicAccessBlock>(),
];
impl Served for dto::GetBucketCors {
@@ -122,3 +127,66 @@ impl Served for dto::DeleteBucketCors {
Ok(Resp::new(output))
}
}
impl Served for dto::GetPublicAccessBlock {
const METRIC: S3Operation = S3Operation::GetPublicAccessBlock;
async fn authorize(envelope: &mut RequestEnvelope, request: &Req<Self>) -> S3Result<()> {
let action = Action::S3Action(S3Action::GetBucketPublicAccessBlockAction);
Ok(authorize_bucket_request(envelope, request.input().bucket.as_str(), action).await?)
}
async fn execute(context: Option<Arc<AppContext>>, _envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
let stored = DefaultBucketUsecase::with_context(context)
.execute_get_public_access_block(request.input().bucket.as_str())
.await?;
Ok(Resp::new(dto::GetPublicAccessBlockOutput {
public_access_block_configuration: Some(dto::PublicAccessBlockConfiguration {
block_public_acls: stored.block_public_acls,
ignore_public_acls: stored.ignore_public_acls,
block_public_policy: stored.block_public_policy,
restrict_public_buckets: stored.restrict_public_buckets,
}),
}))
}
}
impl Served for dto::PutPublicAccessBlock {
const METRIC: S3Operation = S3Operation::PutPublicAccessBlock;
async fn authorize(envelope: &mut RequestEnvelope, request: &Req<Self>) -> S3Result<()> {
let action = Action::S3Action(S3Action::PutBucketPublicAccessBlockAction);
authorize_bucket_config_mutation(envelope, request.input().bucket.as_str(), action).await
}
async fn execute(context: Option<Arc<AppContext>>, envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
let input = request.into_input();
let config = input.public_access_block_configuration;
let prepared = PersistedPublicAccessBlockConfiguration {
block_public_acls: config.block_public_acls,
ignore_public_acls: config.ignore_public_acls,
block_public_policy: config.block_public_policy,
restrict_public_buckets: config.restrict_public_buckets,
};
DefaultBucketUsecase::with_context(context)
.execute_put_public_access_block(envelope, input.bucket.as_str(), Ok(prepared))
.await?;
Ok(Resp::new(dto::PutPublicAccessBlockOutput::default()))
}
}
impl Served for dto::DeletePublicAccessBlock {
const METRIC: S3Operation = S3Operation::DeletePublicAccessBlock;
async fn authorize(envelope: &mut RequestEnvelope, request: &Req<Self>) -> S3Result<()> {
let action = Action::S3Action(S3Action::DeleteBucketPublicAccessBlockAction);
authorize_bucket_config_mutation(envelope, request.input().bucket.as_str(), action).await
}
async fn execute(context: Option<Arc<AppContext>>, envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
DefaultBucketUsecase::with_context(context)
.execute_delete_public_access_block(envelope, request.input().bucket.as_str())
.await?;
Ok(Resp::new(dto::DeletePublicAccessBlockOutput::default()))
}
}
+2 -4
View File
@@ -3846,10 +3846,8 @@ impl S3Access for FS {
///
/// This method returns `Ok(())` by default.
async fn get_public_access_block(&self, req: &mut S3Request<GetPublicAccessBlockInput>) -> S3Result<()> {
let req_info = ext_req_info_mut(&mut req.extensions)?;
req_info.bucket = Some(req.input.bucket.clone());
authorize_request(req, Action::S3Action(S3Action::GetBucketPublicAccessBlockAction)).await
let bucket = req.input.bucket.clone();
authorize_bucket_request(req, &bucket, Action::S3Action(S3Action::GetBucketPublicAccessBlockAction)).await
}
/// Checks whether the HeadBucket request has accesses to the resources.
@@ -19,6 +19,7 @@
//! former trait method bodies, unchanged; the batch that moves these operations onto the gateway
//! owns this file and is the only one that edits it.
use crate::app::RequestEnvelope;
use crate::storage::ecfs::*;
use crate::storage::helper::audit_only_operation;
use crate::storage::s3_api;
@@ -70,11 +71,11 @@ impl FS {
&self,
req: S3Request<DeletePublicAccessBlockInput>,
) -> S3Result<S3Response<DeletePublicAccessBlockOutput>> {
let usecase = s3_api::bucket_usecase_for(self);
audit_only_operation(req, S3Operation::DeletePublicAccessBlock, |req| {
usecase.execute_delete_public_access_block(req)
})
.await
record_s3_op(S3Operation::DeletePublicAccessBlock);
s3_api::bucket_usecase_for(self)
.execute_delete_public_access_block(RequestEnvelope::from_s3s(&req), &req.input.bucket)
.await?;
Ok(S3Response::with_status(DeletePublicAccessBlockOutput::default(), StatusCode::NO_CONTENT))
}
#[instrument(name = "get_bucket_cors", level = "debug", skip(self, req))]
@@ -123,7 +124,7 @@ impl FS {
) -> S3Result<S3Response<GetPublicAccessBlockOutput>> {
record_s3_op(S3Operation::GetPublicAccessBlock);
let usecase = s3_api::bucket_usecase_for(self);
let config = usecase.execute_get_public_access_block(req).await?;
let config = usecase.execute_get_public_access_block(&req.input.bucket).await?;
Ok(S3Response::new(GetPublicAccessBlockOutput {
public_access_block_configuration: Some(persisted_to_s3s(&config)?),
}))
@@ -159,12 +160,12 @@ impl FS {
&self,
req: S3Request<PutPublicAccessBlockInput>,
) -> S3Result<S3Response<PutPublicAccessBlockOutput>> {
let prepared = persisted_from_s3s(&req.input.public_access_block_configuration);
let usecase = s3_api::bucket_usecase_for(self);
audit_only_operation(req, S3Operation::PutPublicAccessBlock, |req| {
usecase.execute_put_public_access_block(req, prepared)
})
.await
record_s3_op(S3Operation::PutPublicAccessBlock);
let prepared = persisted_from_s3s(&req.input.public_access_block_configuration).map_err(Into::into);
s3_api::bucket_usecase_for(self)
.execute_put_public_access_block(RequestEnvelope::from_s3s(&req), &req.input.bucket, prepared)
.await?;
Ok(S3Response::new(PutPublicAccessBlockOutput::default()))
}
#[instrument(name = "put_bucket_tagging", level = "debug", skip(self, req))]
@@ -24,9 +24,9 @@ use aws_sdk_s3::config::interceptors::{
BeforeDeserializationInterceptorContextRef, BeforeTransmitInterceptorContextMut, BeforeTransmitInterceptorContextRef,
};
use aws_sdk_s3::config::{ConfigBag, Intercept, RuntimeComponents};
use aws_sdk_s3::error::BoxError;
use aws_sdk_s3::error::{BoxError, ProvideErrorMetadata};
use aws_sdk_s3::operation::put_bucket_cors::builders::PutBucketCorsFluentBuilder;
use aws_sdk_s3::types::{CorsConfiguration, CorsRule, ServerSideEncryption};
use aws_sdk_s3::types::{CorsConfiguration, CorsRule, PublicAccessBlockConfiguration, ServerSideEncryption};
use futures::future::BoxFuture;
use rustfs::app::context::get_global_app_context;
use rustfs::embedded::RustFSServer;
@@ -62,6 +62,24 @@ pub(crate) const MATRIX: &[MatrixRow] = &[
..GET_ENCRYPTION
},
GET_TAGGING,
MatrixRow {
operation: "PutPublicAccessBlock",
metric: S3Operation::PutPublicAccessBlock,
has_error_body: true,
call: put_public_access_block,
},
MatrixRow {
operation: "GetPublicAccessBlock",
metric: S3Operation::GetPublicAccessBlock,
has_error_body: true,
call: get_public_access_block,
},
MatrixRow {
operation: "DeletePublicAccessBlock",
metric: S3Operation::DeletePublicAccessBlock,
has_error_body: true,
call: delete_public_access_block,
},
MatrixRow {
operation: "PutBucketCors",
metric: S3Operation::PutBucketCors,
@@ -472,3 +490,174 @@ fn the_gateway_stack_stores_and_removes_the_cors_document() {
fn the_legacy_stack_stores_and_removes_the_cors_document() {
with_stack(LEGACY, the_cors_document_is_stored_and_removed);
}
const PUBLIC_ACCESS_BLOCK_XML: &str = concat!(
"<PublicAccessBlockConfiguration><BlockPublicPolicy>false</BlockPublicPolicy>",
"<IgnorePublicAcls>true</IgnorePublicAcls><RestrictPublicBuckets>true</RestrictPublicBuckets>",
"</PublicAccessBlockConfiguration>",
);
fn public_access_block_document() -> PublicAccessBlockConfiguration {
PublicAccessBlockConfiguration::builder()
.ignore_public_acls(true)
.block_public_policy(false)
.restrict_public_buckets(true)
.build()
}
fn put_public_access_block<'a>(client: &'a Client, bucket: &'a str) -> BoxFuture<'a, Outcome> {
Box::pin(async move {
outcome(
client
.put_public_access_block()
.bucket(bucket)
.public_access_block_configuration(public_access_block_document())
.send()
.await,
)
})
}
fn get_public_access_block<'a>(client: &'a Client, bucket: &'a str) -> BoxFuture<'a, Outcome> {
Box::pin(async move {
outcome(client.get_public_access_block().bucket(bucket).send().await.map(|output| {
assert_eq!(
output.public_access_block_configuration(),
Some(&public_access_block_document()),
"persisted switches, including the omitted field"
);
}))
})
}
fn delete_public_access_block<'a>(client: &'a Client, bucket: &'a str) -> BoxFuture<'a, Outcome> {
Box::pin(async move { outcome(client.delete_public_access_block().bucket(bucket).send().await) })
}
async fn stored_public_access_block(bucket: &str) -> Vec<u8> {
metadata_sys::get(bucket)
.await
.expect("bucket metadata")
.public_access_block_config_xml
.clone()
}
async fn public_access_block_configuration(server: RustFSServer, checks_expected_owner: bool) {
const GRANTED: &str = "public-access-block-granted";
const OTHER: &str = "public-access-block-other";
const RESERVED: &str = "public-access-block-s3alias";
const MISSING: &str = "public-access-block-missing";
const WRITER: &str = "publicaccessblockwriter";
const READER: &str = "publicaccessblockreader";
const DELETER: &str = "publicaccessblockdeleter";
for bucket in [GRANTED, OTHER, RESERVED] {
create_bucket_in_the_store(bucket).await;
}
create_user_allowed_on_one_bucket(WRITER, "s3:PutBucketPublicAccessBlock", GRANTED).await;
create_user_allowed_on_one_bucket(READER, "s3:GetBucketPublicAccessBlock", GRANTED).await;
create_user_allowed_on_one_bucket(DELETER, "s3:DeleteBucketPublicAccessBlock", GRANTED).await;
let endpoint = server.endpoint();
let root = s3_client(&endpoint, server.access_key(), server.secret_key());
let writer = s3_client(&endpoint, WRITER, USER_SECRET_KEY);
let reader = s3_client(&endpoint, READER, USER_SECRET_KEY);
let deleter = s3_client(&endpoint, DELETER, USER_SECRET_KEY);
assert_read_error(put_public_access_block(&writer, OTHER).await, "AccessDenied", 403, "write outside grant");
assert!(stored_public_access_block(OTHER).await.is_empty());
assert_read_error(get_public_access_block(&reader, OTHER).await, "AccessDenied", 403, "read outside grant");
assert_read_error(
delete_public_access_block(&deleter, OTHER).await,
"AccessDenied",
403,
"delete outside grant",
);
assert_read_error(
get_public_access_block(&writer, GRANTED).await,
"AccessDenied",
403,
"put grant cannot read",
);
assert_read_error(
put_public_access_block(&reader, GRANTED).await,
"AccessDenied",
403,
"get grant cannot write",
);
assert_read_error(
delete_public_access_block(&writer, GRANTED).await,
"AccessDenied",
403,
"put grant cannot delete",
);
assert_read_error(get_public_access_block(&root, MISSING).await, "NoSuchBucket", 404, "read missing bucket");
assert_read_error(put_public_access_block(&root, MISSING).await, "NoSuchBucket", 404, "write missing bucket");
assert_read_error(
delete_public_access_block(&root, MISSING).await,
"NoSuchBucket",
404,
"delete missing bucket",
);
assert_eq!(
put_public_access_block(&writer, GRANTED).await,
Ok(()),
"writer on matching action and resource"
);
assert_eq!(stored_public_access_block(GRANTED).await, PUBLIC_ACCESS_BLOCK_XML.as_bytes());
assert_eq!(
get_public_access_block(&reader, GRANTED).await,
Ok(()),
"reader on matching action and resource"
);
let wrong_owner = outcome(
root.get_public_access_block()
.bucket(GRANTED)
.expected_bucket_owner("123456789012")
.send()
.await,
);
if checks_expected_owner {
assert_read_error(wrong_owner, "AccessDenied", 403, "expected owner mismatch");
} else {
assert_eq!(wrong_owner, Ok(()), "legacy expected owner header handling");
}
for attempt in ["configured", "unconfigured"] {
let status = StatusCapture::default();
let deleted = deleter
.delete_public_access_block()
.bucket(GRANTED)
.customize()
.interceptor(status.clone())
.send()
.await;
assert_eq!((outcome(deleted), status.take()), (Ok(()), Some(204)), "{attempt}");
assert!(stored_public_access_block(GRANTED).await.is_empty(), "{attempt}");
let error = reader
.get_public_access_block()
.bucket(GRANTED)
.send()
.await
.expect_err(attempt);
assert_eq!(error.message(), Some("Public access block configuration does not exist"), "{attempt}");
assert_read_error(outcome(Err::<(), _>(error)), "NoSuchPublicAccessBlockConfiguration", 500, attempt);
}
assert_eq!(put_public_access_block(&root, RESERVED).await, Ok(()));
assert_eq!(get_public_access_block(&root, RESERVED).await, Ok(()));
assert_eq!(delete_public_access_block(&root, RESERVED).await, Ok(()));
assert!(stored_public_access_block(RESERVED).await.is_empty());
server.shutdown().await;
}
#[test]
fn the_gateway_stack_serves_public_access_block_configuration() {
with_stack(GATEWAY, |server| public_access_block_configuration(server, true));
}
#[test]
fn the_legacy_stack_serves_public_access_block_configuration() {
with_stack(LEGACY, |server| public_access_block_configuration(server, false));
}