mirror of
https://github.com/deuxfleurs-org/garage.git
synced 2026-12-03 06:26:43 +00:00
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.
This commit is contained in:
committed by
Alex Auvolat
parent
8bf75679b9
commit
d0706be988
Generated
+1
@@ -1589,6 +1589,7 @@ dependencies = [
|
||||
"format_table",
|
||||
"futures",
|
||||
"garage_api_common",
|
||||
"garage_api_s3",
|
||||
"garage_block",
|
||||
"garage_model",
|
||||
"garage_rpc",
|
||||
|
||||
@@ -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<Vec<xml::lifecycle::LifecycleRule>>,
|
||||
/// List of methods that can be invoked anonymously
|
||||
pub anonymous_access: Vec<String>,
|
||||
/// List of access keys that have permissions granted on this bucket
|
||||
pub anonymous_access: bool,
|
||||
pub keys: Vec<GetBucketInfoKey>,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
// ---- DeleteBucket ----
|
||||
|
||||
+51
-2
@@ -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::<Vec<_>>()
|
||||
}),
|
||||
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| {
|
||||
|
||||
@@ -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<Garage>, 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<Garage>,
|
||||
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<Garage>,
|
||||
pub bucket_id: Uuid,
|
||||
pub bucket_name: String,
|
||||
pub bucket_params: BucketParams,
|
||||
}
|
||||
|
||||
impl TryFrom<ReqCtxEnum> for AnonReqCtx {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: ReqCtxEnum) -> Result<Self, Self::Error> {
|
||||
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<Garage>,
|
||||
@@ -40,6 +119,17 @@ pub struct ReqCtx {
|
||||
pub api_key: Key,
|
||||
}
|
||||
|
||||
impl TryFrom<ReqCtxEnum> for ReqCtx {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: ReqCtxEnum) -> Result<Self, Self::Error> {
|
||||
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",
|
||||
|
||||
@@ -60,7 +60,7 @@ pub enum ContentSha256Header {
|
||||
|
||||
pub struct VerifiedRequest {
|
||||
pub request: Request<streaming::ReqBody>,
|
||||
pub access_key: Key,
|
||||
pub access_key: Option<Key>,
|
||||
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<Key>.
|
||||
Ok(VerifiedRequest {
|
||||
request,
|
||||
access_key,
|
||||
access_key: checked_signature.key,
|
||||
content_sha256_header: checked_signature.content_sha256_header,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
+127
-187
@@ -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<Result<Response<ResBody>, 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<ReqBody>) = 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
|
||||
};
|
||||
|
||||
|
||||
+2
-2
@@ -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<u64>,
|
||||
@@ -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<u64>,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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<String>,
|
||||
|
||||
/// 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,
|
||||
|
||||
@@ -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<String, bool>,
|
||||
/// 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<Option<WebsiteConfig>>,
|
||||
pub website_config: crdt::Lww<crdt::CancelingOption<WebsiteConfig>>,
|
||||
/// CORS rules
|
||||
pub cors_config: crdt::Lww<Option<Vec<CorsRule>>>,
|
||||
/// Whether to allow anonymous read-only access
|
||||
pub anonymous_access: crdt::Lww<bool>,
|
||||
pub cors_config: crdt::Lww<crdt::CancelingOption<Vec<CorsRule>>>,
|
||||
/// Whether to allow anonymous read-only access
|
||||
pub anonymous_access: crdt::Lww<crdt::CancelingOption<Vec<AnonymousMethod>>>,
|
||||
/// Lifecycle configuration
|
||||
pub lifecycle_config: crdt::Lww<Option<Vec<LifecycleRule>>>,
|
||||
pub lifecycle_config: crdt::Lww<crdt::CancelingOption<Vec<LifecycleRule>>>,
|
||||
/// Bucket quotas
|
||||
pub quotas: crdt::Lww<BucketQuotas>,
|
||||
}
|
||||
@@ -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()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<str> 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<Self, Self::Err> {
|
||||
use AnonymousMethod::*;
|
||||
|
||||
match s {
|
||||
"s3:HeadObject" => Ok(HeadObject),
|
||||
"s3:GetObject" => Ok(GetObject),
|
||||
_ => Err("invalid anonymous method"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod anonymous_access;
|
||||
pub mod block_ref_table;
|
||||
pub mod mpu_table;
|
||||
pub mod object_table;
|
||||
|
||||
Reference in New Issue
Block a user