From d0706be988fc58e28fe603cf6563e1aaa4e4467e Mon Sep 17 00:00:00 2001 From: Antoine Popineau Date: Tue, 10 Feb 2026 21:57:07 +0100 Subject: [PATCH] Refactor how anonymous access is checked and add granular method grants. Anonymous access can now be configured by allowing specific S3 methods. Currently, this only includes `s3:HeadObject` and `s3:GetObject`. Umbrella grants can also be used that translate to lists of methods (`garage:ReadObject` -> [`s3:HeadObject`, `s3:GetObject`]. The CLI takes either a list of `--allow`ed methods, or a `--revoke-all`. `ReqCtx` is now represented by an enum of either an authenticated requests or an anonymous one. Handlers will take either one of those depending on whether they allow anonymous access or not. `ReqCtxEnum` implements `TryInto` to transform into the requested type (where building an anonymous context always works, but building an authenticated one only works if the request contained valid credentials). When building an anonymous context, the bucket anonymous configuration will be checked against the requested endpoint to check if all required methods are allowed anonymously. --- Cargo.lock | 1 + src/api/admin/api.rs | 5 +- src/api/admin/bucket.rs | 53 +++++- src/api/common/helpers.rs | 96 +++++++++- src/api/common/signature/mod.rs | 11 +- src/api/k2v/api_server.rs | 12 +- src/api/s3/api_server.rs | 314 +++++++++++++------------------ src/api/s3/get.rs | 4 +- src/api/s3/router.rs | 18 ++ src/garage/cli/remote/bucket.rs | 17 +- src/garage/cli/structs.rs | 6 +- src/model/bucket_table.rs | 29 ++- src/model/s3/anonymous_access.rs | 34 ++++ src/model/s3/mod.rs | 1 + 14 files changed, 381 insertions(+), 220 deletions(-) create mode 100644 src/model/s3/anonymous_access.rs diff --git a/Cargo.lock b/Cargo.lock index a3f84b56..cff42503 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1589,6 +1589,7 @@ dependencies = [ "format_table", "futures", "garage_api_common", + "garage_api_s3", "garage_block", "garage_model", "garage_rpc", diff --git a/src/api/admin/api.rs b/src/api/admin/api.rs index 29e5e083..e8659292 100644 --- a/src/api/admin/api.rs +++ b/src/api/admin/api.rs @@ -940,8 +940,9 @@ pub struct GetBucketInfoResponse { /// Object lifecycle rules for this bucket #[serde(default, skip_serializing_if = "Option::is_none")] pub lifecycle_rules: Option>, + /// List of methods that can be invoked anonymously + pub anonymous_access: Vec, /// List of access keys that have permissions granted on this bucket - pub anonymous_access: bool, pub keys: Vec, /// Number of objects in this bucket pub objects: i64, @@ -1047,7 +1048,7 @@ pub struct UpdateBucketWebsiteAccess { #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct UpdateBucketAnonymousAccess { - pub enabled: bool, + pub methods: Vec, } // ---- DeleteBucket ---- diff --git a/src/api/admin/bucket.rs b/src/api/admin/bucket.rs index 4e2ec91e..77e26947 100644 --- a/src/api/admin/bucket.rs +++ b/src/api/admin/bucket.rs @@ -1,4 +1,6 @@ use std::collections::HashMap; +use std::collections::HashSet; +use std::str::FromStr; use std::sync::Arc; use std::time::Duration; @@ -381,7 +383,47 @@ impl RequestHandler for UpdateBucketRequest { } if let Some(aa) = self.body.anonymous_access { - state.anonymous_access.update(aa.enabled); + use AnonymousMethod::*; + + #[inline] + fn invalid_method(name: &str) -> Error { + Error::bad_request(format!("invalid anonymous method: {name}")) + } + + match aa.methods.as_slice() { + &[] => { + state.anonymous_access.update(None.into()); + } + + names => { + let methods = names.iter().try_fold( + HashSet::new(), + |mut acc, name| -> Result<_, Error> { + match name { + name if name.starts_with("garage:") => match name.as_str() { + "garage:ReadObject" => acc.extend([HeadObject, GetObject]), + _ => Err(invalid_method(name))?, + }, + + name if name.starts_with("s3:") => { + acc.insert( + AnonymousMethod::from_str(name) + .map_err(|_| invalid_method(name))?, + ); + } + + _ => Err(invalid_method(name))?, + } + + Ok(acc) + }, + )?; + + state + .anonymous_access + .update(Some(methods.into_iter().collect()).into()); + } + } } if let Some(q) = self.body.quotas { @@ -812,7 +854,14 @@ async fn bucket_info_results( .map(xml::lifecycle::LifecycleRule::from_garage_lifecycle_rule) .collect::>() }), - anonymous_access: *state.anonymous_access.get(), + anonymous_access: state + .anonymous_access + .get() + .0 + .iter() + .flatten() + .map(|m| m.as_ref().to_string()) + .collect(), keys: relevant_keys .into_values() .map(|key| { diff --git a/src/api/common/helpers.rs b/src/api/common/helpers.rs index 6fc4aa13..0f306cc2 100644 --- a/src/api/common/helpers.rs +++ b/src/api/common/helpers.rs @@ -1,4 +1,4 @@ -use std::convert::Infallible; +use std::convert::{Infallible, TryFrom}; use std::sync::Arc; use futures::{Stream, StreamExt, TryStreamExt}; @@ -10,10 +10,10 @@ use hyper::{ }; use serde::{Deserialize, Serialize}; -use garage_model::bucket_table::BucketParams; +use garage_model::bucket_table::{Bucket, BucketParams}; use garage_model::garage::Garage; use garage_model::key_table::Key; -use garage_util::data::Uuid; +use garage_util::data::{FixedBytes32, Uuid}; use garage_util::error::Error as GarageError; use crate::common_error::{CommonError as Error, *}; @@ -31,6 +31,85 @@ pub enum Authorization { Owner, } +pub enum ReqCtxEnum { + Anonymous(AnonReqCtx), + Authenticated(ReqCtx), +} + +impl ReqCtxEnum { + pub fn anonymous(garage: Arc, bucket: Bucket, bucket_name: String) -> ReqCtxEnum { + let bucket_params = bucket.state.into_option().unwrap(); + + ReqCtxEnum::Anonymous(AnonReqCtx { + garage, + bucket_id: bucket.id, + bucket_name, + bucket_params, + }) + } + + pub fn authenticated( + garage: Arc, + api_key: Key, + bucket: Bucket, + bucket_name: String, + ) -> ReqCtxEnum { + let bucket_params = bucket.state.into_option().unwrap(); + + ReqCtxEnum::Authenticated(ReqCtx { + garage, + bucket_id: bucket.id, + bucket_name, + bucket_params, + api_key, + }) + } + + pub fn bucket_id(&self) -> FixedBytes32 { + match self { + ReqCtxEnum::Anonymous(ctx) => ctx.bucket_id, + ReqCtxEnum::Authenticated(ctx) => ctx.bucket_id, + } + } + + pub fn bucket_name(&self) -> &String { + match self { + ReqCtxEnum::Anonymous(ctx) => &ctx.bucket_name, + ReqCtxEnum::Authenticated(ctx) => &ctx.bucket_name, + } + } + + pub fn bucket_params(&self) -> &BucketParams { + match self { + ReqCtxEnum::Anonymous(ctx) => &ctx.bucket_params, + ReqCtxEnum::Authenticated(ctx) => &ctx.bucket_params, + } + } +} + +pub struct AnonReqCtx { + pub garage: Arc, + pub bucket_id: Uuid, + pub bucket_name: String, + pub bucket_params: BucketParams, +} + +impl TryFrom for AnonReqCtx { + type Error = Error; + + fn try_from(value: ReqCtxEnum) -> Result { + match value { + ReqCtxEnum::Anonymous(ctx) => Ok(ctx), + ReqCtxEnum::Authenticated(ctx) => Ok(AnonReqCtx { + garage: ctx.garage, + bucket_id: ctx.bucket_id, + bucket_name: ctx.bucket_name, + bucket_params: ctx.bucket_params, + }), + } + } +} + /// The values which are known for each request related to a bucket pub struct ReqCtx { pub garage: Arc, @@ -40,6 +119,17 @@ pub struct ReqCtx { pub api_key: Key, } +impl TryFrom for ReqCtx { + type Error = Error; + + fn try_from(value: ReqCtxEnum) -> Result { + match value { + ReqCtxEnum::Anonymous(_) => Err(Error::Forbidden("Access denied".into())), + ReqCtxEnum::Authenticated(ctx) => Ok(ctx), + } + } +} + /// Host to bucket /// /// Convert a host, like "bucket.garage-site.tld" to the corresponding bucket "bucket", diff --git a/src/api/common/signature/mod.rs b/src/api/common/signature/mod.rs index 47662a68..fffefcff 100644 --- a/src/api/common/signature/mod.rs +++ b/src/api/common/signature/mod.rs @@ -60,7 +60,7 @@ pub enum ContentSha256Header { pub struct VerifiedRequest { pub request: Request, - pub access_key: Key, + pub access_key: Option, pub content_sha256_header: ContentSha256Header, } @@ -78,13 +78,12 @@ pub fn verify_request( service, )?; - let access_key = checked_signature - .key - .ok_or_else(|| Error::forbidden("Access Denied"))?; - + // If the above did not short-circuit, it means we either have a properly + // signed request for the provided key, or an unauthenticated request, + // either way, return the Option. Ok(VerifiedRequest { request, - access_key, + access_key: checked_signature.key, content_sha256_header: checked_signature.content_sha256_header, }) } diff --git a/src/api/k2v/api_server.rs b/src/api/k2v/api_server.rs index 6bc6eaaa..4f860965 100644 --- a/src/api/k2v/api_server.rs +++ b/src/api/k2v/api_server.rs @@ -1,6 +1,7 @@ use std::borrow::Cow; use std::sync::Arc; +use garage_api_common::signature::VerifiedRequest; use hyper::{body::Incoming as IncomingBody, Method, Request, Response}; use tokio::sync::watch; @@ -82,8 +83,15 @@ impl ApiHandler for K2VApiServer { } let verified_request = verify_request(&garage, req, "k2v")?; - let req = verified_request.request; - let api_key = verified_request.access_key; + + let VerifiedRequest { + request: req, + access_key: Some(api_key), + .. + } = verified_request + else { + return Err(Error::forbidden("Access denied".to_string())); + }; let bucket = garage .bucket_helper() diff --git a/src/api/s3/api_server.rs b/src/api/s3/api_server.rs index 8e9164e9..77f52778 100644 --- a/src/api/s3/api_server.rs +++ b/src/api/s3/api_server.rs @@ -1,4 +1,5 @@ use std::borrow::Cow; +use std::convert::TryInto; use std::sync::Arc; use hyper::header; @@ -17,7 +18,7 @@ use garage_api_common::common_error::CommonError; use garage_api_common::cors::*; use garage_api_common::generic_server::*; use garage_api_common::helpers::*; -use garage_api_common::signature::verify_request; +use garage_api_common::signature::{verify_request, VerifiedRequest}; use crate::bucket::*; use crate::copy::*; @@ -68,94 +69,6 @@ impl S3ApiServer { endpoint => Err(CommonError::NotImplemented(endpoint.name().to_owned()).into()), } } - - /// This method checks if the called method and requested bucket can be used - /// together for anonymous access, to provide short-circuiting before - /// permissions are looked at. - /// - /// It returns `None` if either the method is not usable anonymously, or if - /// the bucket does not have anonymous access enabled. Calling code can - /// understand it to mean other means of authentication should be performed. - /// - /// If it returns `Some`, anonymous access was attemped, and can contain - /// either the response, or an error. In this case, processing it done and - /// calling code should return the response. - async fn try_handle_anonymous_request( - &self, - req: &Request<()>, - endpoint: Endpoint, - bucket_name: &String, - ) -> Option, Error>> { - let bucket = self - .garage - .bucket_helper() - .resolve_global_bucket(bucket_name) - .await; - - let bucket = match bucket { - Ok(Some(bucket)) => bucket, - Ok(None) => return Some(Err(Error::NoSuchKey)), - Err(err) => return Some(Err(err.into())), - }; - - let params = bucket.state.into_option().unwrap(); - - if *params.anonymous_access.get() { - match endpoint { - Endpoint::HeadObject { - key, part_number, .. - } => { - return Some( - handle_head_without_ctx( - self.garage.clone(), - req, - bucket.id, - &key, - part_number, - ) - .await, - ); - } - - Endpoint::GetObject { - key, - part_number, - response_cache_control, - response_content_disposition, - response_content_encoding, - response_content_language, - response_content_type, - response_expires, - .. - } => { - let overrides = GetObjectOverrides { - response_cache_control, - response_content_disposition, - response_content_encoding, - response_content_language, - response_content_type, - response_expires, - }; - - return Some( - handle_get_without_ctx( - self.garage.clone(), - req, - bucket.id, - &key, - part_number, - overrides, - ) - .await, - ); - } - - _ => {} - } - } - - None - } } impl ApiHandler for S3ApiServer { @@ -211,81 +124,97 @@ impl ApiHandler for S3ApiServer { return Ok(options_res.map(|_empty_body: EmptyBody| empty_body())); } - // Split the request to prevent moving the body, which is required later. - let (parts, body) = req.into_parts(); - - // Try methods that can be used with anonymous access: HeadObject and - // GetObject. Both require a bucket name. If we get a response from - // this, return the content immediately. Otherwise, move on with - // processing. - if let Some(ref bucket_name) = bucket_name { - let req = Request::from_parts(parts.clone(), ()); - - if let Some(response) = self - .try_handle_anonymous_request(&req, endpoint.clone(), bucket_name) - .await - { - return response; - } - } - - let req = Request::from_parts(parts, body); let verified_request = verify_request(&garage, req, "s3")?; - let req = verified_request.request; - let api_key = verified_request.access_key; - let bucket_name = match bucket_name { - None => { - return self - .handle_request_without_bucket(req, api_key, endpoint) - .await + // Depending on whether we have an authenticated request, we are going + // to take two different paths to authorization: + // + // 1. If the request contained valid credentials, those need to go + // through authorization (check that the API key have the necessary + // access level for the requested method) + // + // 2. On the other hand, if we have an unauthenticated request, we + // verify that the bucket has all the methods required by the endpoint + // allowlisted. + let (ctx, req): (ReqCtxEnum, Request) = match verified_request { + VerifiedRequest { + request: req, + access_key: Some(api_key), + .. + } => { + let bucket_name = match bucket_name { + None => { + return self + .handle_request_without_bucket(req, api_key, endpoint) + .await + } + Some(bucket) => bucket, + }; + + // Special code path for CreateBucket API endpoint + if let Endpoint::CreateBucket {} = endpoint { + return handle_create_bucket(&garage, req, &api_key.key_id, bucket_name).await; + } + + let bucket = garage + .bucket_helper() + .resolve_bucket_fast(&bucket_name, &api_key) + .map_err(pass_helper_error)?; + let bucket_id = bucket.id; + + // Return HTTP 501 Not Implemented before permission check + if !endpoint.is_implemented() { + return Err(CommonError::NotImplemented(endpoint.name().to_owned()).into()); + } + + let allowed = match endpoint.authorization_type() { + Authorization::Read => api_key.allow_read(&bucket_id), + Authorization::Write => api_key.allow_write(&bucket_id), + Authorization::Owner => api_key.allow_owner(&bucket_id), + _ => unreachable!(), + }; + + if !allowed { + return Err(Error::forbidden("Operation is not allowed for this key.")); + } + + ( + ReqCtxEnum::authenticated(garage, api_key, bucket, bucket_name), + req, + ) + } + + anonymous_request => { + let Some(bucket_name) = bucket_name else { + return Err(Error::forbidden("Access denied")); + }; + + // Let's not leak existence of a bucket on anonymous access, we return a generic Access denied. + let Ok(Some(bucket)) = garage + .bucket_helper() + .resolve_global_bucket_fast(&bucket_name) + else { + return Err(Error::forbidden("Access denied")); + }; + + if !endpoint.can_be_accessed_anonymously(&bucket) { + return Err(Error::forbidden("Access denied")); + } + + ( + ReqCtxEnum::anonymous(garage, bucket, bucket_name), + anonymous_request.request, + ) } - Some(bucket) => bucket.to_string(), }; - // Special code path for CreateBucket API endpoint - if let Endpoint::CreateBucket {} = endpoint { - return handle_create_bucket(&garage, req, &api_key.key_id, bucket_name).await; - } - - let bucket = garage - .bucket_helper() - .resolve_bucket_fast(&bucket_name, &api_key) - .map_err(pass_helper_error)?; - let bucket_id = bucket.id; - let bucket_params = bucket.state.into_option().unwrap(); - - // Return HTTP 501 Not Implemented before permission check - if !endpoint.is_implemented() { - return Err(CommonError::NotImplemented(endpoint.name().to_owned()).into()); - } - - let allowed = match endpoint.authorization_type() { - Authorization::Read => api_key.allow_read(&bucket_id), - Authorization::Write => api_key.allow_write(&bucket_id), - Authorization::Owner => api_key.allow_owner(&bucket_id), - _ => unreachable!(), - }; - - if !allowed { - return Err(Error::forbidden("Operation is not allowed for this key.")); - } - - let matching_cors = find_matching_cors_rule(&bucket_params, &req)? + let matching_cors = find_matching_cors_rule(ctx.bucket_params(), &req)? .map(|(rule, origin)| (rule.clone(), origin.to_string())); - let ctx = ReqCtx { - garage, - bucket_id, - bucket_name, - bucket_params, - api_key, - }; - let resp = match endpoint { Endpoint::HeadObject { key, part_number, .. - } => handle_head(ctx, &req.map(|_| ()), &key, part_number).await, + } => handle_head(ctx.try_into()?, &req.map(|_| ()), &key, part_number).await, Endpoint::GetObject { key, part_number, @@ -305,38 +234,45 @@ impl ApiHandler for S3ApiServer { response_content_type, response_expires, }; - handle_get(ctx, &req.map(|_| ()), &key, part_number, overrides).await + handle_get( + ctx.try_into()?, + &req.map(|_| ()), + &key, + part_number, + overrides, + ) + .await } Endpoint::UploadPart { key, part_number, upload_id, - } => handle_put_part(ctx, req, &key, part_number, &upload_id).await, - Endpoint::CopyObject { key } => handle_copy(ctx, &req, &key).await, + } => handle_put_part(ctx.try_into()?, req, &key, part_number, &upload_id).await, + Endpoint::CopyObject { key } => handle_copy(ctx.try_into()?, &req, &key).await, Endpoint::UploadPartCopy { key, part_number, upload_id, - } => handle_upload_part_copy(ctx, &req, &key, part_number, &upload_id).await, - Endpoint::PutObject { key } => handle_put(ctx, req, &key).await, + } => handle_upload_part_copy(ctx.try_into()?, &req, &key, part_number, &upload_id).await, + Endpoint::PutObject { key } => handle_put(ctx.try_into()?, req, &key).await, Endpoint::AbortMultipartUpload { key, upload_id } => { - handle_abort_multipart_upload(ctx, &key, &upload_id).await + handle_abort_multipart_upload(ctx.try_into()?, &key, &upload_id).await } - Endpoint::DeleteObject { key, .. } => handle_delete(ctx, &key).await, + Endpoint::DeleteObject { key, .. } => handle_delete(ctx.try_into()?, &key).await, Endpoint::CreateMultipartUpload { key } => { - handle_create_multipart_upload(ctx, &req, &key).await + handle_create_multipart_upload(ctx.try_into()?, &req, &key).await } Endpoint::CompleteMultipartUpload { key, upload_id } => { - handle_complete_multipart_upload(ctx, req, &key, &upload_id).await + handle_complete_multipart_upload(ctx.try_into()?, req, &key, &upload_id).await } Endpoint::HeadBucket {} => { let response = Response::builder().body(empty_body()).unwrap(); Ok(response) } - Endpoint::DeleteBucket {} => handle_delete_bucket(ctx).await, - Endpoint::GetBucketLocation {} => handle_get_bucket_location(ctx), + Endpoint::DeleteBucket {} => handle_delete_bucket(ctx.try_into()?).await, + Endpoint::GetBucketLocation {} => handle_get_bucket_location(ctx.try_into()?), Endpoint::GetBucketVersioning {} => handle_get_bucket_versioning(), - Endpoint::GetBucketAcl {} => handle_get_bucket_acl(ctx), + Endpoint::GetBucketAcl {} => handle_get_bucket_acl(ctx.try_into()?), Endpoint::ListObjects { delimiter, encoding_type, @@ -346,8 +282,8 @@ impl ApiHandler for S3ApiServer { } => { let query = ListObjectsQuery { common: ListQueryCommon { - bucket_name: ctx.bucket_name.clone(), - bucket_id, + bucket_name: ctx.bucket_name().clone(), + bucket_id: ctx.bucket_id(), delimiter, page_size: max_keys.unwrap_or(1000).clamp(1, 1000), prefix: prefix.unwrap_or_default(), @@ -358,7 +294,7 @@ impl ApiHandler for S3ApiServer { continuation_token: None, start_after: None, }; - handle_list(ctx, &query).await + handle_list(ctx.try_into()?, &query).await } Endpoint::ListObjectsV2 { delimiter, @@ -373,8 +309,8 @@ impl ApiHandler for S3ApiServer { if list_type == "2" { let query = ListObjectsQuery { common: ListQueryCommon { - bucket_name: ctx.bucket_name.clone(), - bucket_id, + bucket_name: ctx.bucket_name().clone(), + bucket_id: ctx.bucket_id(), delimiter, page_size: max_keys.unwrap_or(1000).clamp(1, 1000), urlencode_resp: encoding_type.map(|e| e == "url").unwrap_or(false), @@ -385,7 +321,7 @@ impl ApiHandler for S3ApiServer { continuation_token, start_after, }; - handle_list(ctx, &query).await + handle_list(ctx.try_into()?, &query).await } else { Err(Error::bad_request(format!( "Invalid endpoint: list-type={}", @@ -403,8 +339,8 @@ impl ApiHandler for S3ApiServer { } => { let query = ListMultipartUploadsQuery { common: ListQueryCommon { - bucket_name: ctx.bucket_name.clone(), - bucket_id, + bucket_name: ctx.bucket_name().clone(), + bucket_id: ctx.bucket_id(), delimiter, page_size: max_uploads.unwrap_or(1000).clamp(1, 1000), prefix: prefix.unwrap_or_default(), @@ -413,7 +349,7 @@ impl ApiHandler for S3ApiServer { key_marker, upload_id_marker, }; - handle_list_multipart_upload(ctx, &query).await + handle_list_multipart_upload(ctx.try_into()?, &query).await } Endpoint::ListParts { key, @@ -422,24 +358,28 @@ impl ApiHandler for S3ApiServer { upload_id, } => { let query = ListPartsQuery { - bucket_name: ctx.bucket_name.clone(), + bucket_name: ctx.bucket_name().clone(), key, upload_id, part_number_marker: part_number_marker.map(|p| p.min(10000)), max_parts: max_parts.unwrap_or(1000).clamp(1, 1000), }; - handle_list_parts(ctx, req, &query).await + handle_list_parts(ctx.try_into()?, req, &query).await } - Endpoint::DeleteObjects {} => handle_delete_objects(ctx, req).await, - Endpoint::GetBucketWebsite {} => handle_get_website(ctx).await, - Endpoint::PutBucketWebsite {} => handle_put_website(ctx, req).await, - Endpoint::DeleteBucketWebsite {} => handle_delete_website(ctx).await, - Endpoint::GetBucketCors {} => handle_get_cors(ctx).await, - Endpoint::PutBucketCors {} => handle_put_cors(ctx, req).await, - Endpoint::DeleteBucketCors {} => handle_delete_cors(ctx).await, - Endpoint::GetBucketLifecycleConfiguration {} => handle_get_lifecycle(ctx).await, - Endpoint::PutBucketLifecycleConfiguration {} => handle_put_lifecycle(ctx, req).await, - Endpoint::DeleteBucketLifecycle {} => handle_delete_lifecycle(ctx).await, + Endpoint::DeleteObjects {} => handle_delete_objects(ctx.try_into()?, req).await, + Endpoint::GetBucketWebsite {} => handle_get_website(ctx.try_into()?).await, + Endpoint::PutBucketWebsite {} => handle_put_website(ctx.try_into()?, req).await, + Endpoint::DeleteBucketWebsite {} => handle_delete_website(ctx.try_into()?).await, + Endpoint::GetBucketCors {} => handle_get_cors(ctx.try_into()?).await, + Endpoint::PutBucketCors {} => handle_put_cors(ctx.try_into()?, req).await, + Endpoint::DeleteBucketCors {} => handle_delete_cors(ctx.try_into()?).await, + Endpoint::GetBucketLifecycleConfiguration {} => { + handle_get_lifecycle(ctx.try_into()?).await + } + Endpoint::PutBucketLifecycleConfiguration {} => { + handle_put_lifecycle(ctx.try_into()?, req).await + } + Endpoint::DeleteBucketLifecycle {} => handle_delete_lifecycle(ctx.try_into()?).await, _ => unreachable!(), // unimplemented check is earlier }; diff --git a/src/api/s3/get.rs b/src/api/s3/get.rs index 8ae2f32f..ed27a98d 100644 --- a/src/api/s3/get.rs +++ b/src/api/s3/get.rs @@ -193,7 +193,7 @@ fn handle_http_precondition( /// Handle HEAD request pub async fn handle_head( - ctx: ReqCtx, + ctx: AnonReqCtx, req: &Request<()>, key: &str, part_number: Option, @@ -321,7 +321,7 @@ pub async fn handle_head_without_ctx( /// Handle GET request pub async fn handle_get( - ctx: ReqCtx, + ctx: AnonReqCtx, req: &Request<()>, key: &str, part_number: Option, diff --git a/src/api/s3/router.rs b/src/api/s3/router.rs index 91ff27d1..6b9d63f2 100644 --- a/src/api/s3/router.rs +++ b/src/api/s3/router.rs @@ -1,5 +1,6 @@ use std::borrow::Cow; +use garage_model::bucket_table::{AnonymousMethod, Bucket}; use hyper::header::HeaderValue; use hyper::{HeaderMap, Method, Request}; @@ -689,6 +690,23 @@ impl Endpoint { Authorization::Owner } } + + /// Check that a bucket allows all anonymous methods required by an endpoint + pub fn can_be_accessed_anonymously(&self, bucket: &Bucket) -> bool { + use Endpoint::*; + + let bucket_params = bucket.state.as_option().unwrap(); + + match self { + HeadObject { .. } => { + bucket_params.has_anonymous_methods(&[AnonymousMethod::HeadObject]) + } + + GetObject { .. } => bucket_params.has_anonymous_methods(&[AnonymousMethod::GetObject]), + + _ => false, + } + } } // parameter name => struct field diff --git a/src/garage/cli/remote/bucket.rs b/src/garage/cli/remote/bucket.rs index 47c37d24..1c4de10f 100644 --- a/src/garage/cli/remote/bucket.rs +++ b/src/garage/cli/remote/bucket.rs @@ -328,6 +328,8 @@ impl Cli { body: UpdateBucketRequestBody { website_access: Some(wa), anonymous_access: None, + cors_rules: None, + lifecycle_rules: None, quotas: None, }, }) @@ -347,13 +349,13 @@ impl Cli { }) .await?; - if !(opt.allow ^ opt.deny) { + if !(!opt.allow.is_empty() ^ opt.revoke_all) { return Err(Error::Message( - "You must specify exactly one flag, either --allow or --deny".to_string(), + "You must specify exactly one flag, either --allow or --revoke-all".to_string(), )); } - let wa = UpdateBucketAnonymousAccess { enabled: opt.allow }; + let wa = UpdateBucketAnonymousAccess { methods: opt.allow }; let res = self .api_request(UpdateBucketRequest { @@ -579,7 +581,14 @@ fn print_bucket_info(bucket: &GetBucketInfoResponse) { info.extend([ String::new(), - format!("Anonymous access:\t{}", bucket.anonymous_access), + format!( + "Anonymous access:\t{}", + if bucket.anonymous_access.is_empty() { + "-".to_string() + } else { + bucket.anonymous_access.join(", ") + } + ), ]); if bucket.quotas.max_size.is_some() || bucket.quotas.max_objects.is_some() { diff --git a/src/garage/cli/structs.rs b/src/garage/cli/structs.rs index 8ad479c0..cada9d3a 100644 --- a/src/garage/cli/structs.rs +++ b/src/garage/cli/structs.rs @@ -339,11 +339,11 @@ pub struct WebsiteOpt { pub struct AnonymousAccessOpt { /// Allow anonymous access to all files in the bucket #[structopt(long = "allow")] - pub allow: bool, + pub allow: Vec, /// Deny anonymous access to any file in the bucket - #[structopt(long = "deny")] - pub deny: bool, + #[structopt(long = "revoke-all")] + pub revoke_all: bool, /// Bucket name pub bucket: String, diff --git a/src/model/bucket_table.rs b/src/model/bucket_table.rs index 613a1148..15144a53 100644 --- a/src/model/bucket_table.rs +++ b/src/model/bucket_table.rs @@ -246,13 +246,14 @@ mod v2 { } mod v3 { - use crate::{bucket_table::v2, permission::BucketKeyPerm}; + use crate::{bucket_table::v2, permission::BucketKeyPerm, s3::anonymous_access}; use garage_util::crdt; use garage_util::data::Uuid; use serde::{Deserialize, Serialize}; use super::v08; + pub use anonymous_access::AnonymousMethod; pub use v08::{BucketQuotas, CorsRule, LifecycleExpiration, LifecycleFilter, LifecycleRule}; pub use v2::{Redirect, RedirectAll, RedirectCondition, RoutingRule, WebsiteConfig}; @@ -275,7 +276,7 @@ mod v3 { /// Map of aliases that are or have been given to this bucket /// in the global namespace /// (not authoritative: this is just used as an indication to - /// map back to aliases when doing ListBuckets) + /// map back to aliases when doing `ListBuckets`) pub aliases: crdt::LwwMap, /// Map of aliases that are or have been given to this bucket /// in namespaces local to keys @@ -285,13 +286,13 @@ mod v3 { /// Whether this bucket is allowed for website access /// (under all of its global alias names), /// and if so, the website configuration XML document - pub website_config: crdt::Lww>, + pub website_config: crdt::Lww>, /// CORS rules - pub cors_config: crdt::Lww>>, - /// Whether to allow anonymous read-only access - pub anonymous_access: crdt::Lww, + pub cors_config: crdt::Lww>>, + /// Whether to allow anonymous read-only access + pub anonymous_access: crdt::Lww>>, /// Lifecycle configuration - pub lifecycle_config: crdt::Lww>>, + pub lifecycle_config: crdt::Lww>>, /// Bucket quotas pub quotas: crdt::Lww, } @@ -318,13 +319,23 @@ mod v3 { }) }), cors_config: x.cors_config, - anonymous_access: crdt::Lww::new(false), + anonymous_access: crdt::Lww::new(None.into()), lifecycle_config: x.lifecycle_config, quotas: x.quotas, }), } } } + + impl BucketParams { + /// Checks whether all anonymous access methods are allowed on the bucket + pub fn has_anonymous_methods(&self, methods: &[AnonymousMethod]) -> bool { + match self.anonymous_access.get().inner() { + None => false, + Some(allowed) => methods.iter().all(|m| allowed.contains(m)), + } + } + } } pub use v3::*; @@ -344,7 +355,7 @@ impl BucketParams { website_config: crdt::Lww::new(None.into()), cors_config: crdt::Lww::new(None.into()), lifecycle_config: crdt::Lww::new(None.into()), - anonymous_access: crdt::Lww::new(false), + anonymous_access: crdt::Lww::new(None.into()), quotas: crdt::Lww::new(BucketQuotas::default()), } } diff --git a/src/model/s3/anonymous_access.rs b/src/model/s3/anonymous_access.rs new file mode 100644 index 00000000..96456f56 --- /dev/null +++ b/src/model/s3/anonymous_access.rs @@ -0,0 +1,34 @@ +use std::str::FromStr; + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Ord, PartialOrd, Serialize, Deserialize)] +pub enum AnonymousMethod { + HeadObject, + GetObject, +} + +impl AsRef for AnonymousMethod { + fn as_ref(&self) -> &'static str { + use AnonymousMethod::*; + + match self { + HeadObject => "s3:HeadObject", + GetObject => "s3:GetObject", + } + } +} + +impl FromStr for AnonymousMethod { + type Err = &'static str; + + fn from_str(s: &str) -> Result { + use AnonymousMethod::*; + + match s { + "s3:HeadObject" => Ok(HeadObject), + "s3:GetObject" => Ok(GetObject), + _ => Err("invalid anonymous method"), + } + } +} diff --git a/src/model/s3/mod.rs b/src/model/s3/mod.rs index 5c776fb0..a4831e16 100644 --- a/src/model/s3/mod.rs +++ b/src/model/s3/mod.rs @@ -1,3 +1,4 @@ +pub mod anonymous_access; pub mod block_ref_table; pub mod mpu_table; pub mod object_table;