mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(iam): authorize S3 Control routes as their own s3 actions (#6681)
* fix(iam): authorize S3 Control routes as their own s3 actions S3 Control clients sign with the s3 scope, so under IAM enforcement its /v20180820 routes fell through to the S3 data-plane rules and were checked as s3:GetObject, PutObject or DeleteObject on a bucket named v20180820, which no policy can name: a role allowed s3:ListTagsForResource on a bucket was denied its tag list, and Terraform's AWS provider, which reads bucket tags through S3 Control, never fell back to GetBucketTagging, leaving aws_s3_bucket unrefreshable. Map the routes to the actions the Service Authorization Reference gives them: ListTagsForResource, TagResource and UntagResource are checked against the ARN the route names, as written and decoded as the handler decodes it; ListAccessPoints and the account-level Block Public Access, to which the S3 User Guide gives no resource, against every bucket in the request's partition; the account control takes the PutAccountPublicAccessBlock and GetAccountPublicAccessBlock actions. A data-plane operation under the same prefix keeps its own bucket-and-object ARN. A denial now answers in S3 Control's own ErrorResponse envelope, the only one the s3control SDK deserializers read, so the message naming the missing action survives to the client. Closes #6537 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * fix(iam): answer the three control-route gaps the review found A tagging query on a control route still reached the data-plane override, so GET /v20180820/tags/<arn>?tagging was checked as s3:GetObjectTagging while the handler read the bucket's tags: the control rules now match before the query overrides, and a caller holding only the object action is denied where one holding the control action passes. A tagging ARN in the regional form was rewritten to the global form downstream and its bucket misread, so a policy naming the regional form the API reference requires was denied; the provider now keeps a control tagging ARN as written and reads the bucket it names. The account actions returned arn:<partition>:s3:::*, which a bucket-scoped statement matches; they now return the literal wildcard, so a bucket-scoped statement grants no account-wide action, the convention the KMS no-resource actions follow. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * fix(iam): drive S3 Control route authorization from AWS's own data The s3control model is vendored in rest-routes.json, regen_rest_routes carries it under the s3 scope, as s3control signs with s3, and IamRestRouteCoverageTest checks every S3 Control route Floci serves against the Service Reference. The hand-written S3_CONTROL_RULES and S3_CONTROL_ACTIONS lists are gone: the control routes are entries of the one rules table, flagged to match before the S3 data-plane query overrides so ?tagging on a tagging route cannot re-point the authorization, and a denial answers in S3 Control's ErrorResponse envelope by following the route instead of an action-name list. The account-level Block Public Access is the one written-down exception, as the reference files S3's and S3 Control's Get, Put and DeletePublicAccessBlock under the bucket actions and the Block Public Access page gives the account level its own actions. A tagging ARN is read once, by the handler, the IAM check and the bucket-policy lookup together: S3ControlArnUtils decodes and parses it with AwsArnUtils.parse, and the regional form's account is the account whose bucket the request acts on, so a grant on arn:aws:s3:us-east-1:222222222222:bucket/reports no longer lets a caller in 111111111111 read and change the tags of its own same-named bucket: it reads and writes 222222222222's bucket, and answers NoSuchBucket when that account holds no bucket of the name. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * fix(s3): read the policy provider's ARNs without decoding them The provider received every ARN already decoded, the data plane's from the request path and a control tagging one re-minted by the rule that read it off the wire, but the one-parse helper decoded again, so an object key carrying a plus sign or a literal percent sequence changed its bytes before IAM checked it: a policy on arn:aws:s3:::example/a+b.txt denied the very object it named. The provider parses without decoding now; the wire decode stays where it belongs, at the control request boundary. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> --------- Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
1 parent
6b10bf24c9
commit
97ecbdd656
15 files changed
+1294
-72
No files matched your search
@@ -1783,6 +1783,12 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
// 403, the status the Kinesis and CloudWatch common errors give AccessDeniedException.
|
||||
return cborError(ctx, "AccessDeniedException", accessDeniedMessage(action), 403);
|
||||
}
|
||||
// The route decides the envelope, not the resolved action: a request on an S3 Control
|
||||
// route is S3 Control's however its action reads, and only its ErrorResponse wrapper
|
||||
// reaches the s3control SDK deserializers (issue #557).
|
||||
if (IamActionRegistry.isS3ControlRequest(credentialScope, ctx)) {
|
||||
return s3ControlXmlAccessDenied(accessDeniedMessage(action));
|
||||
}
|
||||
return accessDeniedResponse(action, credentialScope, ctx.getMediaType(), resourceArn, protocol);
|
||||
}
|
||||
|
||||
@@ -1862,6 +1868,31 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
return s3Xml("AccessDenied", message, resourcePath, 403);
|
||||
}
|
||||
|
||||
/**
|
||||
* S3 Control's own access-denied answer, which unlike S3's error body wraps the error in an
|
||||
* {@code <ErrorResponse>} the s3control SDK deserializers read (issue #557): the bare
|
||||
* {@code <Error>} S3 answers with collapses to {@code UnknownError} there, hiding the message
|
||||
* that names the action a caller is missing, which Terraform's AWS provider matches to fall
|
||||
* back from {@code ListTagsForResource} to {@code GetBucketTagging}. The same envelope as
|
||||
* {@code S3ControlController}'s, and no {@code Resource} element: the ARN a tagging route
|
||||
* names is the resource, not a bucket and key.
|
||||
*/
|
||||
private static Response s3ControlXmlAccessDenied(String message) {
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String xml = new XmlBuilder()
|
||||
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
|
||||
.start("ErrorResponse", AwsNamespaces.S3_CONTROL)
|
||||
.start("Error")
|
||||
.elem("Code", "AccessDenied")
|
||||
.elem("Message", message)
|
||||
.elem("RequestId", requestId)
|
||||
.end("Error")
|
||||
.elem("RequestId", requestId)
|
||||
.end("ErrorResponse")
|
||||
.build();
|
||||
return Response.status(403).type(MediaType.APPLICATION_XML).entity(xml).build();
|
||||
}
|
||||
|
||||
private static Response s3Xml(String code, String message, String resourcePath, int status) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
|
||||
|
||||
@@ -36,10 +36,12 @@ public class IamActionRegistry {
|
||||
/**
|
||||
* A route and the action it is checked as. A rule naming a query parameter matches only a request
|
||||
* carrying it with that value, as {@code GET /layers?find=LayerVersion} is GetLayerVersionByArn
|
||||
* where {@code GET /layers} is ListLayers.
|
||||
* where {@code GET /layers} is ListLayers. A rule flagged to match before the S3 query
|
||||
* overrides is one of the S3 Control routes, which the control plane answers whatever its
|
||||
* query string carries.
|
||||
*/
|
||||
private record ActionRule(String service, String method, Pattern pathPattern, String queryParameter,
|
||||
String queryValue, String action) {
|
||||
String queryValue, String action, boolean beforeS3QueryOverrides) {
|
||||
|
||||
boolean matches(String scope, String requestMethod, String path, ContainerRequestContext ctx) {
|
||||
return service.equals(scope) && method.equals(requestMethod) && pathPattern.matcher(path).find()
|
||||
@@ -48,7 +50,36 @@ public class IamActionRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The routes of the S3 Control model, checked as the actions the Service Reference gives
|
||||
* them by {@code IamRestRouteCoverageTest}. S3 Control clients sign with the s3 scope
|
||||
* (botocore's s3control model declares signingName "s3"), so its operations are
|
||||
* {@code s3:} actions, and its routes must be matched before the S3 data-plane query
|
||||
* overrides: the control plane answers a tagging route whatever its query string carries,
|
||||
* so a parameter such as {@code ?tagging} must not re-point the authorization at the
|
||||
* data-plane object tagging it suggests, and the data-plane rules below would otherwise
|
||||
* read {@code /v20180820/...} as a bucket named v20180820.
|
||||
*
|
||||
* <p>The account-level Block Public Access is the one route the Service Reference cannot
|
||||
* settle, because it files S3's and S3 Control's GetPublicAccessBlock, PutPublicAccessBlock
|
||||
* and DeletePublicAccessBlock under the bucket actions; the S3 User Guide's Block Public
|
||||
* Access page gives the account level its own actions, and the exception is written down
|
||||
* where the data is checked. ListAccessPoints and the account actions have no resource
|
||||
* type, so IAM checks them against the wildcard rather than a bucket.
|
||||
*/
|
||||
private static final List<ActionRule> RULES = List.of(
|
||||
// ── S3 Control ───────────────────────────────────────────────────────────
|
||||
s3ControlRule("GET", "^/v20180820/tags/.+", "s3:ListTagsForResource"),
|
||||
s3ControlRule("POST", "^/v20180820/tags/.+", "s3:TagResource"),
|
||||
s3ControlRule("DELETE", "^/v20180820/tags/.+", "s3:UntagResource"),
|
||||
s3ControlRule("GET", "^/v20180820/accesspoint/?$", "s3:ListAccessPoints"),
|
||||
s3ControlRule("PUT", "^/v20180820/configuration/publicAccessBlock/?$",
|
||||
"s3:PutAccountPublicAccessBlock"),
|
||||
s3ControlRule("GET", "^/v20180820/configuration/publicAccessBlock/?$",
|
||||
"s3:GetAccountPublicAccessBlock"),
|
||||
s3ControlRule("DELETE", "^/v20180820/configuration/publicAccessBlock/?$",
|
||||
"s3:PutAccountPublicAccessBlock"),
|
||||
|
||||
// ── S3 ─────────────────────────────────────────────────────────────────
|
||||
rule("s3", "GET", "^/?$", "s3:ListAllMyBuckets"),
|
||||
rule("s3", "PUT", "^/[^/]+/?$", "s3:CreateBucket"),
|
||||
@@ -519,7 +550,35 @@ public class IamActionRegistry {
|
||||
private static ActionRule rule(String service, String method, String path, String queryParameter,
|
||||
String queryValue, String action) {
|
||||
return new ActionRule(service, method, Pattern.compile(path, Pattern.CASE_INSENSITIVE), queryParameter,
|
||||
queryValue, action);
|
||||
queryValue, action, false);
|
||||
}
|
||||
|
||||
private static ActionRule s3ControlRule(String method, String path, String action) {
|
||||
return new ActionRule("s3", method, Pattern.compile(path, Pattern.CASE_INSENSITIVE), null, null,
|
||||
action, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the request is one of the S3 Control routes, as the rules flag them. A denial then
|
||||
* answers in S3 Control's own REST-XML envelope, the only one the s3control SDK
|
||||
* deserializers read (issue #557), so the route decides the shape and not the action: the
|
||||
* data plane resolves actions a control route never shares, and an action-name list would
|
||||
* have to track every route to stay right. A request whose route cannot be read, which only
|
||||
* a synthetic context is, is not a control one.
|
||||
*/
|
||||
public static boolean isS3ControlRequest(String credentialScope, ContainerRequestContext ctx) {
|
||||
if (!"s3".equals(credentialScope) || ctx.getMethod() == null || ctx.getUriInfo() == null
|
||||
|| ctx.getUriInfo().getRequestUri() == null) {
|
||||
return false;
|
||||
}
|
||||
String method = ctx.getMethod().toUpperCase();
|
||||
String path = rawPath(ctx.getUriInfo());
|
||||
for (ActionRule rule : RULES) {
|
||||
if (rule.beforeS3QueryOverrides() && rule.matches(credentialScope, method, path, ctx)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -589,12 +648,20 @@ public class IamActionRegistry {
|
||||
// bucket's one trailing slash, so an S3 path is matched as sent.
|
||||
String path = "s3".equals(credentialScope) ? rawPath(ctx.getUriInfo()) : routedPath(ctx.getUriInfo());
|
||||
|
||||
// S3 sub-resource override: the URL path alone doesn't distinguish
|
||||
// s3:GetObjectAcl / s3:PutObjectAcl from s3:GetObject / s3:PutObject
|
||||
// — only the {@code ?acl} query parameter does. Without this hook,
|
||||
// an actor with s3:GetObject permission could read ACLs that their
|
||||
// policy intends to forbid.
|
||||
if ("s3".equals(credentialScope)) {
|
||||
// An S3 Control route is matched before the query overrides below, which would read the
|
||||
// query string of a route the control plane answers whatever it carries: ?tagging on a
|
||||
// tagging route is caller-supplied noise, not the object sub-resource it names.
|
||||
for (ActionRule rule : RULES) {
|
||||
if (rule.beforeS3QueryOverrides() && rule.matches(credentialScope, method, path, ctx)) {
|
||||
return rule.action();
|
||||
}
|
||||
}
|
||||
// S3 sub-resource override: the URL path alone doesn't distinguish
|
||||
// s3:GetObjectAcl / s3:PutObjectAcl from s3:GetObject / s3:PutObject:
|
||||
// only the {@code ?acl} query parameter does. Without this hook,
|
||||
// an actor with s3:GetObject permission could read ACLs that their
|
||||
// policy intends to forbid.
|
||||
String s3SubAction = resolveS3SubResourceAction(method, ctx);
|
||||
if (s3SubAction != null) {
|
||||
return s3SubAction;
|
||||
|
||||
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.kms.KmsService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableTokens;
|
||||
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
|
||||
import io.github.hectorvent.floci.services.s3.S3ControlArnUtils;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
@@ -66,6 +67,9 @@ public class ResourceArnBuilder {
|
||||
*/
|
||||
private static final String UNASSIGNED_SECRET_SUFFIX = "-??????";
|
||||
|
||||
/** Where an S3 Control tagging route carries the ARN of the resource it acts on. */
|
||||
private static final String S3_CONTROL_TAGS_PREFIX = "/v20180820/tags/";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
/**
|
||||
* Looked up lazily through a provider: this builder is constructed by the enforcement filter,
|
||||
@@ -173,7 +177,7 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
String path = ctx.getUriInfo().getPath();
|
||||
return switch (credentialScope) {
|
||||
case "s3" -> List.of(buildS3Arn(path, region));
|
||||
case "s3" -> buildS3Resources(operation, path, region);
|
||||
case "lambda" -> List.of(buildLambdaArn(path, ctx, region, accountId));
|
||||
case "sqs" -> List.of(buildSqsArn(ctx, region, accountId));
|
||||
case "sns" -> List.of(buildSnsArn(ctx, region, accountId));
|
||||
@@ -803,6 +807,52 @@ public class ResourceArnBuilder {
|
||||
return AwsArnUtils.Arn.global(partition, "s3", "", stripped).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The resources an s3-scope request names, which an S3 Control operation reads differently
|
||||
* from an S3 data-plane path. S3 Control clients sign with the s3 scope and its operations
|
||||
* are {@code s3:} actions (the Service Authorization Reference lists them under Amazon S3),
|
||||
* so the operation, not the path, tells the two apart: a tagging route carries the ARN of the
|
||||
* bucket or access point it acts on in its path, and the request is checked against that ARN
|
||||
* as written, the way every ARN-carrying request is; the Service Authorization Reference
|
||||
* gives ListAccessPoints and the account-level Block Public Access no resource type, so
|
||||
* those are checked against the wildcard alone, as the no-resource actions of other
|
||||
* namespaces are (the KMS list operations), and a bucket-scoped statement grants them
|
||||
* nothing. Any other operation is the data plane, checked against the bucket or object its
|
||||
* path names.
|
||||
*/
|
||||
private List<String> buildS3Resources(String operation, String path, String region) {
|
||||
if (operation == null) {
|
||||
return List.of(buildS3Arn(path, region));
|
||||
}
|
||||
return switch (operation) {
|
||||
case "s3:ListTagsForResource", "s3:TagResource", "s3:UntagResource" ->
|
||||
List.of(taggedS3ControlArn(path));
|
||||
case "s3:ListAccessPoints", "s3:PutAccountPublicAccessBlock",
|
||||
"s3:GetAccountPublicAccessBlock" -> List.of("*");
|
||||
default -> List.of(buildS3Arn(path, region));
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN an S3 Control tagging route names in its path, read with the one parse the handler
|
||||
* and the policy lookup share: the Go SDK, and so Terraform's provider, percent-encodes the
|
||||
* ARN's colons and slashes, so the path may still carry them. A path naming no ARN leaves
|
||||
* the wildcard, which the handler answers {@code InvalidRequest} under, and nothing is
|
||||
* rebuilt from the bucket it names: the ARN as the caller wrote it is the resource.
|
||||
*/
|
||||
private static String taggedS3ControlArn(String path) {
|
||||
String tagged = path.startsWith(S3_CONTROL_TAGS_PREFIX)
|
||||
? path.substring(S3_CONTROL_TAGS_PREFIX.length()) : null;
|
||||
if (tagged == null) {
|
||||
return "*";
|
||||
}
|
||||
try {
|
||||
return S3ControlArnUtils.parse(tagged).map(AwsArnUtils.Arn::toString).orElse("*");
|
||||
} catch (IllegalArgumentException malformedEncoding) {
|
||||
return "*";
|
||||
}
|
||||
}
|
||||
|
||||
// ── Lambda ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The resource ARN an S3 Control tagging route names in its path, read the one way every reader
|
||||
* of it shares: decoded once, because the Go SDK v2, and so Terraform's provider, percent-encodes
|
||||
* the ARN's colons and slashes while the Java SDK sends them literally, then parsed with
|
||||
* {@link AwsArnUtils#parse}. Two documented forms name a bucket (the S3 Control API reference,
|
||||
* ListTagsForResource): the regional {@code arn:<partition>:s3:<region>:<account>:bucket/<name>}
|
||||
* the operation's own request pattern and the AWS CLI examples use, and the global
|
||||
* {@code arn:<partition>:s3:::<name>}. The regional form's account and region are the ones the
|
||||
* handler, the policy lookup and the IAM check all act on, so a request naming another account's
|
||||
* bucket acts on that account's bucket and never on the caller's same-named one.
|
||||
*/
|
||||
public final class S3ControlArnUtils {
|
||||
|
||||
/** The regional form's resource prefix: {@code bucket/<name>}. */
|
||||
private static final String BUCKET_RESOURCE_PREFIX = "bucket/";
|
||||
|
||||
private S3ControlArnUtils() {}
|
||||
|
||||
/**
|
||||
* The tagging route's ARN, decoded as its handler decodes it and parsed once. Empty when the
|
||||
* value is null, blank or not an s3 ARN; {@link IllegalArgumentException} when its
|
||||
* percent-encoding is malformed.
|
||||
*/
|
||||
public static Optional<AwsArnUtils.Arn> parse(String resourceArn) {
|
||||
if (resourceArn == null || resourceArn.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String decoded = URLDecoder.decode(resourceArn, StandardCharsets.UTF_8);
|
||||
return AwsArnUtils.isArnFor(decoded, "s3") ? Optional.of(AwsArnUtils.parse(decoded)) : Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code arn} is the regional form: the only S3 ARN that fills its region and carries
|
||||
* its bucket after {@code bucket/}. No S3 data-plane ARN fills the region, so this reading can
|
||||
* never collide with the data-plane one of a bucket actually named {@code bucket}.
|
||||
*/
|
||||
public static boolean regionalBucketForm(AwsArnUtils.Arn arn) {
|
||||
return !arn.region().isEmpty() && arn.resource().startsWith(BUCKET_RESOURCE_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the ARN names a bucket the tagging routes act on: the regional form, or the global
|
||||
* one whose whole resource is the bucket's name. Anything else, an access point ARN included,
|
||||
* names a resource these routes do not serve.
|
||||
*/
|
||||
public static boolean namesBucket(AwsArnUtils.Arn arn) {
|
||||
return regionalBucketForm(arn)
|
||||
|| (arn.region().isEmpty() && arn.accountId().isEmpty()
|
||||
&& !arn.resource().isEmpty() && arn.resource().indexOf('/') < 0);
|
||||
}
|
||||
|
||||
/** The bucket the ARN names: after {@code bucket/} in the regional form, the whole resource in the global one. */
|
||||
public static String bucketName(AwsArnUtils.Arn arn) {
|
||||
return regionalBucketForm(arn) ? arn.resource().substring(BUCKET_RESOURCE_PREFIX.length()) : arn.resource();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
@@ -24,11 +25,11 @@ import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.jboss.resteasy.reactive.server.ServerExceptionMapper;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
@@ -75,8 +76,9 @@ public class S3ControlController {
|
||||
@HeaderParam("x-amz-account-id") String accountId) {
|
||||
|
||||
try {
|
||||
String bucketName = extractBucketName(resourceArn);
|
||||
Map<String, String> tags = s3Service.getBucketTagging(bucketName);
|
||||
AwsArnUtils.Arn arn = taggedBucketArn(resourceArn);
|
||||
Map<String, String> tags = s3Service.getBucketTaggingForAccount(arn.accountId(),
|
||||
S3ControlArnUtils.bucketName(arn));
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
|
||||
@@ -278,10 +280,10 @@ public class S3ControlController {
|
||||
byte[] body) {
|
||||
|
||||
try {
|
||||
String bucketName = extractBucketName(resourceArn);
|
||||
AwsArnUtils.Arn arn = taggedBucketArn(resourceArn);
|
||||
String xml = new String(body, StandardCharsets.UTF_8);
|
||||
Map<String, String> tags = XmlParser.extractPairs(xml, "Tag", "Key", "Value");
|
||||
s3Service.putBucketTagging(bucketName, tags);
|
||||
s3Service.putBucketTaggingForAccount(arn.accountId(), S3ControlArnUtils.bucketName(arn), tags);
|
||||
return Response.noContent().build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -302,10 +304,12 @@ public class S3ControlController {
|
||||
@QueryParam("tagKeys") List<String> tagKeys) {
|
||||
|
||||
try {
|
||||
String bucketName = extractBucketName(resourceArn);
|
||||
Map<String, String> existing = new HashMap<>(s3Service.getBucketTagging(bucketName));
|
||||
AwsArnUtils.Arn arn = taggedBucketArn(resourceArn);
|
||||
String bucketName = S3ControlArnUtils.bucketName(arn);
|
||||
Map<String, String> existing =
|
||||
new HashMap<>(s3Service.getBucketTaggingForAccount(arn.accountId(), bucketName));
|
||||
tagKeys.forEach(existing::remove);
|
||||
s3Service.putBucketTagging(bucketName, existing);
|
||||
s3Service.putBucketTaggingForAccount(arn.accountId(), bucketName, existing);
|
||||
return Response.noContent().build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -313,47 +317,24 @@ public class S3ControlController {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the bucket name out of an S3 bucket ARN path parameter.
|
||||
*
|
||||
* <p>The AWS Go SDK v2 (used by Terraform) percent-encodes the ARN's
|
||||
* colons and slashes in the request path, while the Java SDK sends them
|
||||
* literally. We decode defensively so both forms work, and so routing
|
||||
* frameworks that leave {@code %2F} encoded in path segments don't break
|
||||
* us.
|
||||
*
|
||||
* <p>Two valid ARN forms are accepted:
|
||||
* <ul>
|
||||
* <li>S3 Control ARN: {@code arn:aws:s3:<region>:<account>:bucket/<name>}</li>
|
||||
* <li>Plain S3 ARN: {@code arn:aws:s3:::<name>} — sent by Go SDK v2 / Terraform provider v6</li>
|
||||
* </ul>
|
||||
* The bucket ARN a tagging route names, decoded and parsed the one way every reader of it
|
||||
* shares: the handler here, the IAM resource the request is checked against, and the bucket
|
||||
* policy lookup. The regional form carries the account and region of the bucket it names, and
|
||||
* the global form the caller's own account, so a request naming another account's bucket acts
|
||||
* on that account's bucket, never on the caller's same-named one.
|
||||
*/
|
||||
private String extractBucketName(String resourceArn) {
|
||||
String decoded;
|
||||
private static AwsArnUtils.Arn taggedBucketArn(String resourceArn) {
|
||||
Optional<AwsArnUtils.Arn> arn;
|
||||
try {
|
||||
decoded = URLDecoder.decode(resourceArn, StandardCharsets.UTF_8);
|
||||
arn = S3ControlArnUtils.parse(resourceArn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidRequest",
|
||||
"Malformed percent-encoding in resource ARN: " + e.getMessage(), 400);
|
||||
}
|
||||
|
||||
// Form 1: arn:<partition>:s3:<region>:<account>:bucket/<name>
|
||||
int idx = decoded.lastIndexOf(":bucket/");
|
||||
if (idx >= 0) {
|
||||
return decoded.substring(idx + ":bucket/".length());
|
||||
}
|
||||
|
||||
// Form 2: arn:<partition>:s3:::<name> (plain S3 ARN — no region, no account)
|
||||
// Go SDK v2 / Terraform provider v6 sends this form for general-purpose buckets.
|
||||
String[] parts = decoded.split(":", 6);
|
||||
if (parts.length == 6 && "s3".equals(parts[2])
|
||||
&& parts[3].isEmpty() && parts[4].isEmpty()
|
||||
&& !parts[5].isEmpty() && !parts[5].contains("/")) {
|
||||
return parts[5];
|
||||
}
|
||||
|
||||
throw new AwsException("InvalidRequest",
|
||||
"Unsupported resource type. Only S3 bucket ARNs are supported " +
|
||||
"(arn:aws:s3:<region>:<account>:bucket/<name> or arn:aws:s3:::<name>).", 400); // partition-literal: AWS's message text
|
||||
return arn.filter(S3ControlArnUtils::namesBucket)
|
||||
.orElseThrow(() -> new AwsException("InvalidRequest",
|
||||
"Unsupported resource type. Only S3 bucket ARNs are supported " +
|
||||
"(arn:aws:s3:<region>:<account>:bucket/<name> or arn:aws:s3:::<name>).", 400)); // partition-literal: AWS's message text
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+38
-11
@@ -26,11 +26,14 @@ public class S3ResourcePolicyProvider implements ResourcePolicyProvider {
|
||||
if (!"s3".equalsIgnoreCase(credentialScope) || resourceArn == null) {
|
||||
return List.of();
|
||||
}
|
||||
String bucketName = extractBucketName(resourceArn);
|
||||
AwsArnUtils.Arn arn = s3Arn(resourceArn);
|
||||
String bucketName = arn == null ? null : extractBucketName(arn);
|
||||
if (bucketName == null || bucketName.isEmpty() || "*".equals(bucketName)) {
|
||||
return List.of();
|
||||
}
|
||||
Optional<S3Service.BucketPolicyInfo> policyInfo = s3Service.findBucketPolicyInfo(bucketName);
|
||||
Optional<S3Service.BucketPolicyInfo> policyInfo = S3ControlArnUtils.regionalBucketForm(arn)
|
||||
? s3Service.findBucketPolicyInfoForAccount(arn.accountId(), bucketName)
|
||||
: s3Service.findBucketPolicyInfo(bucketName);
|
||||
return policyInfo.map(info -> List.of(new ResourcePolicy(info.policy(), info.ownerAccountId())))
|
||||
.orElseGet(List::of);
|
||||
}
|
||||
@@ -50,12 +53,26 @@ public class S3ResourcePolicyProvider implements ResourcePolicyProvider {
|
||||
if (!"s3".equalsIgnoreCase(credentialScope) || resourceArn == null) {
|
||||
return resourceArn;
|
||||
}
|
||||
String bucketName = extractBucketName(resourceArn);
|
||||
if (bucketName == null || bucketName.isEmpty() || "*".equals(bucketName)) {
|
||||
AwsArnUtils.Arn arn = s3Arn(resourceArn);
|
||||
if (arn == null || S3ControlArnUtils.regionalBucketForm(arn)) {
|
||||
return resourceArn;
|
||||
}
|
||||
String resource = AwsArnUtils.resourceIfArnFor(resourceArn, "s3").orElseThrow();
|
||||
return AwsArnUtils.Arn.global(s3Service.bucketPartition(bucketName), "s3", "", resource).toString();
|
||||
String bucketName = extractBucketName(arn);
|
||||
if (bucketName.isEmpty() || "*".equals(bucketName)) {
|
||||
return resourceArn;
|
||||
}
|
||||
return AwsArnUtils.Arn.global(s3Service.bucketPartition(bucketName), "s3", "", arn.resource()).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The request's resource, parsed without decoding: every ARN reaching here is already in its
|
||||
* decoded form, the data plane's from the request path and a control tagging one re-minted
|
||||
* by the rule that read it off the wire, so decoding again would rewrite an object key like
|
||||
* {@code a+b.txt} before IAM checks it. Null when it is not an s3 ARN, which leaves the
|
||||
* request its identity policy alone: no bucket policy applies, as when the bucket has none.
|
||||
*/
|
||||
private static AwsArnUtils.Arn s3Arn(String resourceArn) {
|
||||
return AwsArnUtils.isArnFor(resourceArn, "s3") ? AwsArnUtils.parse(resourceArn) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,11 +80,21 @@ public class S3ResourcePolicyProvider implements ResourcePolicyProvider {
|
||||
* no policy for a China or GovCloud bucket, which silently changed the access decision.
|
||||
*/
|
||||
static String extractBucketName(String resourceArn) {
|
||||
String tail = AwsArnUtils.resourceIfArnFor(resourceArn, "s3").orElse(null);
|
||||
if (tail == null) {
|
||||
return null;
|
||||
AwsArnUtils.Arn arn = s3Arn(resourceArn);
|
||||
return arn == null ? null : extractBucketName(arn);
|
||||
}
|
||||
|
||||
/**
|
||||
* The bucket of a parsed S3 ARN: the one after {@code bucket/} in the regional form a
|
||||
* control tagging route names, so a policy is looked up from the bucket the handler acts on
|
||||
* and not from a bucket named {@code bucket} with the real name as its key, and the bucket
|
||||
* before the first slash in every data-plane form.
|
||||
*/
|
||||
static String extractBucketName(AwsArnUtils.Arn arn) {
|
||||
if (S3ControlArnUtils.regionalBucketForm(arn)) {
|
||||
return S3ControlArnUtils.bucketName(arn);
|
||||
}
|
||||
int slash = tail.indexOf('/');
|
||||
return slash < 0 ? tail : tail.substring(0, slash);
|
||||
int slash = arn.resource().indexOf('/');
|
||||
return slash < 0 ? arn.resource() : arn.resource().substring(0, slash);
|
||||
}
|
||||
}
|
||||
@@ -3761,21 +3761,71 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
// --- Bucket Tagging ---
|
||||
|
||||
public void putBucketTagging(String bucketName, Map<String, String> tags) {
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404));
|
||||
bucket.setTags(tags != null ? tags : new java.util.HashMap<>());
|
||||
bucketStore.put(bucketName, bucket);
|
||||
LOG.debugv("Put tags on bucket: {0}", bucketName);
|
||||
putBucketTaggingForAccount(null, bucketName, tags);
|
||||
}
|
||||
|
||||
public Map<String, String> getBucketTagging(String bucketName) {
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404));
|
||||
return getBucketTaggingForAccount(null, bucketName);
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of the bucket a control-plane tagging ARN names: the bucket of that name in
|
||||
* {@code accountId}'s partition, the calling account's when the ARN carries none, as the
|
||||
* global form does not. A bucket another account owns is read exactly where it lives and
|
||||
* never fallen back to the caller's same-named one: the ARN names another account's bucket
|
||||
* or no bucket at all, and either way the answer is {@code NoSuchBucket}.
|
||||
*/
|
||||
public Map<String, String> getBucketTaggingForAccount(String accountId, String bucketName) {
|
||||
Bucket bucket = bucketForAccount(accountId, bucketName);
|
||||
return bucket.getTags() != null ? bucket.getTags() : Map.of();
|
||||
}
|
||||
|
||||
/** Replaces the tags of the bucket a control-plane tagging ARN names, in the partition it names. */
|
||||
public void putBucketTaggingForAccount(String accountId, String bucketName, Map<String, String> tags) {
|
||||
Bucket bucket = bucketForAccount(accountId, bucketName);
|
||||
bucket.setTags(tags != null ? tags : new HashMap<>());
|
||||
writeBucketForAccount(namedAccount(accountId), bucketName, bucket);
|
||||
LOG.debugv("Put tags on bucket {0} of account {1}", bucketName, namedAccount(accountId));
|
||||
}
|
||||
|
||||
/**
|
||||
* The bucket of that name in the account a tagging ARN names, resolved the same way for the
|
||||
* tag read, the tag write and the policy lookup. The calling account's own partition is read
|
||||
* through {@link StorageBackend#get}, which also migrates pre-multi-account data; another
|
||||
* account's is read exactly, and a store with no partitions at all has the one bucket the
|
||||
* name can mean.
|
||||
*/
|
||||
private Bucket bucketForAccount(String accountId, String bucketName) {
|
||||
String account = namedAccount(accountId);
|
||||
AccountAwareStorageBackend<Bucket> aware = accountAwareBucketStore();
|
||||
Optional<Bucket> bucket = account.equals(ownerId()) || aware == null
|
||||
? bucketStore.get(bucketName)
|
||||
: aware.getForAccount(account, bucketName);
|
||||
return bucket.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404));
|
||||
}
|
||||
|
||||
/** Writes a bucket back to the partition {@link #bucketForAccount} read it from. */
|
||||
private void writeBucketForAccount(String account, String bucketName, Bucket bucket) {
|
||||
AccountAwareStorageBackend<Bucket> aware = accountAwareBucketStore();
|
||||
if (!account.equals(ownerId()) && aware != null) {
|
||||
aware.putForAccount(account, bucketName, bucket);
|
||||
} else {
|
||||
bucketStore.put(bucketName, bucket);
|
||||
}
|
||||
}
|
||||
|
||||
/** The account an ARN names: its own account field, the calling account's when it carries none. */
|
||||
private String namedAccount(String accountId) {
|
||||
return accountId != null && !accountId.isBlank() ? accountId : ownerId();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private AccountAwareStorageBackend<Bucket> accountAwareBucketStore() {
|
||||
return bucketStore instanceof AccountAwareStorageBackend<?> aware
|
||||
? (AccountAwareStorageBackend<Bucket>) aware : null;
|
||||
}
|
||||
|
||||
public void putBucketWebsite(String bucketName, WebsiteConfiguration config) {
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
@@ -5437,6 +5487,23 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
.map(entry -> new BucketPolicyInfo(entry.value().getPolicy(), entry.account()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The policy of the bucket a control-plane tagging ARN names, in the account the ARN names:
|
||||
* the same bucket {@link #getBucketTaggingForAccount} reads the tags of, so a bucket policy
|
||||
* denying the control actions reaches the bucket the handler acts on. The calling account
|
||||
* keeps {@link #findBucketPolicyInfo}'s resolution, which spans partitions under the global
|
||||
* bucket namespace.
|
||||
*/
|
||||
public Optional<BucketPolicyInfo> findBucketPolicyInfoForAccount(String accountId, String bucketName) {
|
||||
String account = namedAccount(accountId);
|
||||
AccountAwareStorageBackend<Bucket> aware = accountAwareBucketStore();
|
||||
if (account.equals(ownerId()) || aware == null) {
|
||||
return findBucketPolicyInfo(bucketName);
|
||||
}
|
||||
return aware.getForAccount(account, bucketName)
|
||||
.map(bucket -> new BucketPolicyInfo(bucket.getPolicy(), account));
|
||||
}
|
||||
|
||||
public Optional<String> findBucketPolicy(String bucketName) {
|
||||
return findBucketPolicyInfo(bucketName)
|
||||
.map(BucketPolicyInfo::policy)
|
||||
|
||||
Reference in new issue
Block a user