fix(s3): refuse an unserved sub-resource and keep a key's own slashes (#8019)

A bucket request that names a sub-resource Floci does not serve fell through
to the bucket's own operation: DELETE ?metadataConfiguration and
?metadataTable deleted an empty bucket, GET ?abac and ?metadataTable listed
it, PUT ?abac created a bucket that did not exist, and HEAD ?acl ran
HeadBucket. The same happened to a sub-resource sent with a method AWS defines
none for, such as DELETE ?versioning. A POST naming one got a 400 asking for
?delete, and no IAM check at all.

The bucket handlers, HEAD and POST among them, now refuse such a request
where they would have run the bucket's operation. A sub-resource the AWS model
defines for the method is answered 501 NotImplemented, and one it defines for
other methods only 405 MethodNotAllowed, as DELETE ?accelerate already was.
A browser-form upload and DeleteObjects still run first on a POST. The
sub-resources are read from botocore's S3 model in the vendored
rest-routes.json, so one AWS adds is refused once the table is regenerated,
not run as the bucket, and their names from the parsed query parameters, so
an escaped & inside a value, ?prefix=reports%26abac, names none. The IAM
check matches: an unserved sub-resource is checked as the action the Service
Reference gives the operation it names (DELETE ?metadataTable needs
s3:DeleteBucketMetadataTableConfiguration, not s3:DeleteBucket, and
POST ?metadataTable s3:CreateBucketMetadataTableConfiguration), which lets
the route coverage test drop the two operations it exempted.

A key made only of slashes was read as the bucket too: JAX-RS collapses
PUT /bucket// to the bucket's path, so it ran CreateBucket and was checked as
s3:CreateBucket, where it writes the key "/". A filter now escapes such a
key's slashes in the path the router matches, path-style and virtual-hosted,
so S3 and the IAM check both act on the object, arn:aws:s3:::bucket//. One
trailing slash, /bucket/, is still the bucket.

The resource ARN a request is checked against read the same collapsed path,
which named another object whenever a key carried a slash of its own.
PUT /bucket//email.txt stores the key "/email.txt" and the controller and the
condition resolver both read it that way, from the path as it arrived, while
the ARN came out as arn:aws:s3:::bucket/email.txt: a grant on that object
covered this one, and a statement naming bucket//* matched nothing it names.
A key with a double slash inside it, a//b.txt, was checked as a/b.txt the
same way. The ARN is now built from the key those two already read, through
one reader the three share, so the object stored, the object a condition
describes and the object a policy is matched against are the same one. An S3
Control operation, told apart by the operation as before and not by its path,
names no object and is left as it was: the ARN in its path is still taken as
written.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-11 10:53:14 -06:00
1 parent 4d4f20b812
commit d250eb276e
17 files changed
+774 -58

No files matched your search

@@ -650,24 +650,10 @@ public class IamConditionContextResolver {
}
URI requestUri = ctx.getUriInfo().getRequestUri();
RoutingContext current = currentVertxRequest == null ? null : currentVertxRequest.getCurrent();
String rawPath = current != null && current.request() != null ? current.request().path()
String sentPath = current != null && current.request() != null ? current.request().path()
: requestUri == null ? null : requestUri.getRawPath();
String key = rawPath == null ? null
: S3ObjectKeys.fromRawPath(rawPath, requestUri == null ? null : requestUri.getPath(), bucket);
if (key == null) {
key = s3PathObjectKey(ctx.getUriInfo().getPath());
}
return key == null || key.isEmpty() ? null : key;
}
/** The object key of a path-style (or filter-rewritten) S3 path, null for a bucket-level one. */
private static String s3PathObjectKey(String path) {
String stripped = path.startsWith("/") ? path.substring(1) : path;
int slash = stripped.indexOf('/');
if (slash < 0 || slash == stripped.length() - 1) {
return null;
}
return stripped.substring(slash + 1);
return S3ObjectKeys.objectKey(sentPath, requestUri == null ? null : requestUri.getPath(),
ctx.getUriInfo().getPath(), bucket);
}
Map<String, List<String>> s3BucketListConditionContext(MultivaluedMap<String, String> queryParameters) {
@@ -11,6 +11,7 @@ import io.floci.aws.core.common.WireProtocol;
import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser;
import io.floci.aws.services.eks.EksController;
import io.floci.aws.services.route53.Route53Controller;
import io.floci.aws.services.s3.S3BucketSubresources;
import io.floci.aws.services.s3.S3ObjectActions;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.container.ContainerRequestContext;
@@ -891,6 +892,12 @@ public class IamActionRegistry {
&& "x-www-form-urlencoded".equalsIgnoreCase(mediaType.getSubtype());
}
private static boolean isFormUpload(MediaType mediaType) {
return mediaType != null
&& "multipart".equalsIgnoreCase(mediaType.getType())
&& "form-data".equalsIgnoreCase(mediaType.getSubtype());
}
/** One bucket sub-resource operation: the query parameter that selects it, and the IAM action. */
private record SubResourceAction(String queryParameter, String action) {}
@@ -976,6 +983,13 @@ public class IamActionRegistry {
if (!isBucketLevel) {
return objectSubResourceAction(method, params);
}
if ("POST".equals(method)) {
// S3Controller runs DeleteObjects and a browser-form PostObject ahead of any other sub-resource and
// checks them per key; another sub-resource S3 defines for POST, such as ?metadataTable, it answers
// NotImplemented, so that request is checked as the operation it names.
return params.containsKey("delete") || isFormUpload(ctx.getMediaType())
? null : unservedSubresourceAction(method, params);
}
List<SubResourceAction> chain = switch (method) {
case "GET" -> GET_BUCKET_SUBRESOURCES;
case "PUT" -> PUT_BUCKET_SUBRESOURCES;
@@ -987,6 +1001,23 @@ public class IamActionRegistry {
return entry.action();
}
}
return chain.isEmpty() ? null : unservedSubresourceAction(method, params);
}
/**
* A sub-resource S3 defines for the method that the lists above, or POST's DeleteObjects, do not hold is one
* S3Controller does not serve: it answers the request NotImplemented rather than run the bucket's operation, so
* the request is checked as the operation it names, as AWS checks it. Null when it names none, or one S3 defines
* for other methods only, which S3Controller refuses as not allowed.
*/
private static String unservedSubresourceAction(String method, MultivaluedMap<String, String> params) {
S3BucketSubresources subresources = S3BucketSubresources.vendored();
for (String name : subresources.names()) {
List<String> operations = subresources.operations(method, name);
if (params.containsKey(name) && operations.size() == 1) {
return IamAuthorizedActions.actionFor("s3", operations.get(0));
}
}
return null;
}
@@ -21,8 +21,11 @@ import io.floci.aws.services.lambda.LambdaArnUtils;
import io.floci.aws.services.lambda.durable.DurableTokens;
import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService;
import io.floci.aws.services.s3.S3ControlArnUtils;
import io.floci.aws.services.s3.S3ObjectKeys;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.sqs.SqsService;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
@@ -31,6 +34,7 @@ import jakarta.ws.rs.container.ContainerRequestContext;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
@@ -106,6 +110,12 @@ public class ResourceArnBuilder {
* its service follows with a minted id, or by members its minted ARN does not hold, is stored under.
*/
private final Instance<StoredResourceArns> storedResourceArns;
/**
* The current request, for the path as the client sent it: an S3 key keeps its own slashes,
* which JAX-RS has collapsed out of {@code UriInfo} by the time this runs. Null outside a
* request, as in a unit test, where the request URI's raw path stands in.
*/
private final CurrentVertxRequest currentVertxRequest;
@Inject
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
@@ -113,7 +123,8 @@ public class ResourceArnBuilder {
Instance<LambdaMicrovmsService> microvmsService,
Instance<EksService> eksService,
Instance<KmsService> kmsService,
Instance<StoredResourceArns> storedResourceArns) {
Instance<StoredResourceArns> storedResourceArns,
CurrentVertxRequest currentVertxRequest) {
this.objectMapper = objectMapper;
this.iamService = iamService;
this.secretsManagerService = secretsManagerService;
@@ -121,6 +132,17 @@ public class ResourceArnBuilder {
this.eksService = eksService;
this.kmsService = kmsService;
this.storedResourceArns = storedResourceArns;
this.currentVertxRequest = currentVertxRequest;
}
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
Instance<SecretsManagerService> secretsManagerService,
Instance<LambdaMicrovmsService> microvmsService,
Instance<EksService> eksService,
Instance<KmsService> kmsService,
Instance<StoredResourceArns> storedResourceArns) {
this(objectMapper, iamService, secretsManagerService, microvmsService, eksService, kmsService,
storedResourceArns, null);
}
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
@@ -161,6 +183,10 @@ public class ResourceArnBuilder {
this(objectMapper, null, null);
}
ResourceArnBuilder(ObjectMapper objectMapper, CurrentVertxRequest currentVertxRequest) {
this(objectMapper, null, null, null, null, null, null, currentVertxRequest);
}
public String build(String credentialScope, ContainerRequestContext ctx,
String region, String accountId) {
List<String> list = buildResources(credentialScope, ctx, region, accountId);
@@ -198,7 +224,7 @@ public class ResourceArnBuilder {
String path = "s3".equals(credentialScope) ? ctx.getUriInfo().getPath()
: IamActionRegistry.decodedPath(ctx);
return switch (credentialScope) {
case "s3" -> buildS3Resources(operation, path, region);
case "s3" -> buildS3Resources(operation, path, ctx, 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));
@@ -840,6 +866,46 @@ public class ResourceArnBuilder {
}
// ── S3 ──────────────────────────────────────────────────────────────────────
/**
* The path of an S3 data-plane request, {@code path} as JAX-RS matched it, with its object key
* read from the path as the client sent it. {@code UriInfo} carries JAX-RS's collapsing of
* consecutive slashes, which drops a key's own leading slash and so names another object:
* {@code PUT /bucket//email.txt} stores the key {@code /email.txt} but would be checked on
* {@code arn:aws:s3:::bucket/email.txt}, so a grant on that object would cover this one and a
* statement naming {@code bucket//*} would match nothing it names. {@code S3Controller} stores
* the object under the key read here and the IAM condition resolver describes that same key,
* so all three agree on which object the request is about. The bucket comes from the matched
* path, which {@code S3VirtualHostFilter} has put it into for a virtual-hosted request.
*/
private String s3Path(String path, ContainerRequestContext ctx) {
String bucket = s3Bucket(path);
if (bucket == null) {
return path;
}
URI requestUri = ctx.getUriInfo().getRequestUri();
RoutingContext current = currentVertxRequest == null ? null : currentVertxRequest.getCurrent();
String sentPath = current != null && current.request() != null ? current.request().path()
: requestUri == null ? null : requestUri.getRawPath();
String key = S3ObjectKeys.objectKey(sentPath, requestUri == null ? null : requestUri.getPath(),
path, bucket);
return key == null ? path : "/" + bucket + "/" + key;
}
/**
* The bucket an S3 data-plane path names an object in, or null when the path names no object to
* read a key for: the root, and a bucket on its own or with one trailing slash, which the ARN
* reads as the bucket itself.
*/
private static String s3Bucket(String path) {
if (path == null) {
return null;
}
String stripped = path.startsWith("/") ? path.substring(1) : path;
int slash = stripped.indexOf('/');
return slash <= 0 || slash == stripped.length() - 1 ? null : stripped.substring(0, slash);
}
// Minted in the request's partition; IamEnforcementFilter re-mints an existing bucket's ARN
// in the bucket's own partition through S3ResourcePolicyProvider before any policy sees it.
private String buildS3Arn(String path, String region) {
@@ -872,18 +938,19 @@ public class ResourceArnBuilder {
* 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.
* path names, even in a bucket named like the S3 Control prefix, {@code v20180820}.
*/
private List<String> buildS3Resources(String operation, String path, String region) {
private List<String> buildS3Resources(String operation, String path, ContainerRequestContext ctx,
String region) {
if (operation == null) {
return List.of(buildS3Arn(path, region));
return List.of(buildS3Arn(s3Path(path, ctx), 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));
default -> List.of(buildS3Arn(s3Path(path, ctx), region));
};
}
@@ -0,0 +1,97 @@
package io.floci.aws.services.s3;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.VendoredResources;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* The bucket sub-resources botocore's S3 model defines, read once from the vendored {@code aws/rest-routes.json}:
* each query parameter without a value that a {@code /{Bucket}} route names ({@code ?acl}, {@code ?metadataTable}),
* and the operations it selects by HTTP method. A bucket request naming one runs that operation in AWS, never the
* bucket's own, so {@link S3Controller} answers one it does not serve with an error, and the IAM registry checks it
* as the operation it names.
*
* <p>The file is generated by {@code tools/aws/regen_rest_routes.py}. A missing or malformed resource is a build
* defect, so loading fails with {@link IllegalStateException} rather than leaving every sub-resource to run as the
* bucket's operation.
*/
public final class S3BucketSubresources {
static final String RESOURCE_NAME = "aws/rest-routes.json";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String BUCKET_ROUTE = "/{Bucket}?";
private static final class Holder {
static final S3BucketSubresources VENDORED = VendoredResources.read(RESOURCE_NAME,
"S3 bucket sub-resource table", S3BucketSubresources::parse);
}
/** Each sub-resource's operations by method, in name order. */
private final Map<String, Map<String, List<String>>> operations;
private final List<String> names;
private S3BucketSubresources(Map<String, Map<String, List<String>>> operations, List<String> names) {
this.operations = operations;
this.names = names;
}
/** The sub-resources of the vendored model. */
public static S3BucketSubresources vendored() {
return Holder.VENDORED;
}
/** The sub-resources' names, in order. */
public List<String> names() {
return names;
}
/** The operations the sub-resource selects for the method, in order; empty when S3 defines none for it. */
public List<String> operations(String method, String subresource) {
return operations.getOrDefault(subresource, Map.of()).getOrDefault(method, List.of());
}
static S3BucketSubresources parse(InputStream in) throws IOException {
JsonNode document = MAPPER.readTree(in);
JsonNode model = document == null ? null : document.path("models").path("s3").path("operations");
if (model == null || !model.isObject() || model.isEmpty()) {
throw new IllegalStateException(RESOURCE_NAME + " carries no S3 operations");
}
Map<String, Map<String, TreeSet<String>>> found = new TreeMap<>();
model.properties().forEach(operation -> {
String method = operation.getValue().path("method").asText("");
String requestUri = operation.getValue().path("requestUri").asText("");
if (method.isEmpty() || !requestUri.startsWith("/")) {
throw new IllegalStateException(RESOURCE_NAME + " gives s3 " + operation.getKey()
+ " no HTTP method or no request URI");
}
if (!requestUri.startsWith(BUCKET_ROUTE)) {
return;
}
for (String parameter : requestUri.substring(BUCKET_ROUTE.length()).split("&")) {
if (!parameter.isEmpty() && parameter.indexOf('=') < 0) {
found.computeIfAbsent(parameter, ignored -> new TreeMap<>())
.computeIfAbsent(method, ignored -> new TreeSet<>())
.add(operation.getKey());
}
}
});
if (found.isEmpty()) {
throw new IllegalStateException(RESOURCE_NAME + " gives S3 no bucket sub-resource");
}
Map<String, Map<String, List<String>>> operations = new TreeMap<>();
found.forEach((name, byMethod) -> {
Map<String, List<String>> methods = new TreeMap<>();
byMethod.forEach((method, names) -> methods.put(method, List.copyOf(names)));
operations.put(name, Map.copyOf(methods));
});
return new S3BucketSubresources(Map.copyOf(operations), List.copyOf(found.keySet()));
}
}
@@ -308,6 +308,7 @@ public class S3Controller {
return headOnlyResponse(websiteResponse);
}
}
rejectUnservedSubresource("HEAD", uriInfo);
s3Service.authorizeBucketRead(bucket, "s3:ListBucket", authorization);
s3Service.headBucket(bucket);
String bucketRegion = s3Service.getBucketRegion(bucket);
@@ -418,20 +419,14 @@ public class S3Controller {
s3Service.putBucketReplication(bucket, new String(body, StandardCharsets.UTF_8));
return Response.ok().build();
}
// Must be handled here: an unmatched subresource falls through to CreateBucket below,
// which answers a metrics call with BucketAlreadyOwnedByYou.
if (hasQueryParam(uriInfo, "metrics")) {
s3Service.authorizeBucketWrite(bucket, "s3:PutMetricsConfiguration", authorization);
return handlePutBucketMetricsConfiguration(bucket, uriInfo, body);
}
// Same fall-through hazard as metrics: an intelligent-tiering PUT must not become a
// CreateBucket.
if (hasQueryParam(uriInfo, "intelligent-tiering")) {
s3Service.authorizeBucketWrite(bucket, "s3:PutIntelligentTieringConfiguration", authorization);
return handlePutBucketIntelligentTieringConfiguration(bucket, uriInfo, body);
}
// Same fall-through hazard as metrics: an analytics or inventory PUT must not become
// a CreateBucket.
if (hasQueryParam(uriInfo, "analytics")) {
s3Service.authorizeBucketWrite(bucket, "s3:PutAnalyticsConfiguration", authorization);
return handlePutBucketAnalyticsConfiguration(bucket, uriInfo, body);
@@ -440,6 +435,7 @@ public class S3Controller {
s3Service.authorizeBucketWrite(bucket, "s3:PutInventoryConfiguration", authorization);
return handlePutBucketInventoryConfiguration(bucket, uriInfo, body);
}
rejectUnservedSubresource("PUT", uriInfo);
// Detect a PutObject request that reached this handler before virtual-host rewriting.
if (isMisplacedObjectPut(httpHeaders, body, bucket)) {
@@ -569,36 +565,27 @@ public class S3Controller {
return Response.noContent().build();
}
if (hasQueryParam(uriInfo, "metrics")) {
// Likewise this must not fall through to deleting the bucket.
s3Service.authorizeBucketWrite(bucket, "s3:PutMetricsConfiguration", authorization);
s3Service.deleteBucketMetricsConfiguration(bucket, requireMetricsId(uriInfo));
return Response.noContent().build();
}
if (hasQueryParam(uriInfo, "intelligent-tiering")) {
// Likewise this must not fall through to deleting the bucket.
s3Service.authorizeBucketWrite(bucket, "s3:PutIntelligentTieringConfiguration", authorization);
s3Service.deleteBucketIntelligentTieringConfiguration(bucket,
requireIntelligentTieringId(uriInfo));
return Response.noContent().build();
}
if (hasQueryParam(uriInfo, "analytics")) {
// Likewise this must not fall through to deleting the bucket.
s3Service.authorizeBucketWrite(bucket, "s3:PutAnalyticsConfiguration", authorization);
s3Service.deleteBucketAnalyticsConfiguration(bucket, requireAnalyticsId(uriInfo));
return Response.noContent().build();
}
if (hasQueryParam(uriInfo, "inventory")) {
// Likewise this must not fall through to deleting the bucket.
s3Service.authorizeBucketWrite(bucket, "s3:PutInventoryConfiguration", authorization);
s3Service.deleteBucketInventoryConfiguration(bucket, requireInventoryId(uriInfo));
return Response.noContent().build();
}
if (hasQueryParam(uriInfo, "accelerate")) {
// AWS defines no DELETE for the accelerate subresource; reject it here so
// it does NOT fall through to deleting the whole bucket.
throw new AwsException("MethodNotAllowed",
"The specified method is not allowed against this resource.", 405);
}
rejectUnservedSubresource("DELETE", uriInfo);
s3Service.authorizeBucketWrite(bucket, "s3:DeleteBucket", authorization);
s3Service.deleteBucket(bucket);
return Response.noContent().build();
@@ -773,6 +760,7 @@ public class S3Controller {
return website;
}
}
rejectUnservedSubresource("GET", uriInfo);
s3Service.authorizeListBucket(bucket, authorization);
@@ -1676,6 +1664,7 @@ public class S3Controller {
body);
}
}
rejectUnservedSubresource("POST", uriInfo);
return xmlErrorResponse(new AwsException("InvalidArgument",
"POST on bucket requires ?delete parameter.", 400));
} catch (AwsException e) {
@@ -4591,6 +4580,32 @@ public class S3Controller {
}
}
/**
* Refuses a bucket request that names a sub-resource the handler above did not serve, rather than running the
* bucket's own operation in its place, which would create, list or delete the bucket: one S3 defines for the
* method is not implemented here, and one it defines for other methods only is not allowed. The names are read
* from the parsed query parameters, as the IAM check reads them, so an escaped {@code &} inside a value, as in
* {@code ?prefix=reports%26abac}, names no sub-resource.
*/
private static void rejectUnservedSubresource(String method, UriInfo uriInfo) {
S3BucketSubresources subresources = S3BucketSubresources.vendored();
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
boolean named = false;
for (String name : subresources.names()) {
if (params.containsKey(name)) {
if (!subresources.operations(method, name).isEmpty()) {
throw new AwsException("NotImplemented",
"A header you provided implies functionality that is not implemented.", 501);
}
named = true;
}
}
if (named) {
throw new AwsException("MethodNotAllowed",
"The specified method is not allowed against this resource.", 405);
}
}
private void validateRawUri() {
String rawPath = currentVertxRequest.getCurrent().request().path();
String decodedPath;
@@ -41,6 +41,37 @@ public final class S3ObjectKeys {
}
}
/**
* The decoded key an S3 request on {@code bucket} names, or null for a bucket-level request.
* {@code sentPath} is the path as the client sent it, where a key's own slashes survive, and
* {@code normalizedPath} the path JAX-RS matched, which stands in when the sent path carries no
* bucket, as for a request no Vert.x request backs. {@link S3Controller}, the IAM condition
* resolver and the resource ARN a request is checked against all read the key here, so the
* object stored, the object the conditions describe and the object the policy is matched
* against are the same one.
*/
public static String objectKey(String sentPath, String requestUriPath, String normalizedPath,
String bucket) {
String key = sentPath == null ? null : fromRawPath(sentPath, requestUriPath, bucket);
if (key == null) {
key = fromNormalizedPath(normalizedPath);
}
return key == null || key.isEmpty() ? null : key;
}
/** The object key of a path-style (or filter-rewritten) S3 path, null for a bucket-level one. */
static String fromNormalizedPath(String path) {
if (path == null) {
return null;
}
String stripped = path.startsWith("/") ? path.substring(1) : path;
int slash = stripped.indexOf('/');
if (slash < 0 || slash == stripped.length() - 1) {
return null;
}
return stripped.substring(slash + 1);
}
/** Decodes a URL path, skipping the decoder when it holds no escape and no plus. */
static String decodePath(String raw) {
return raw.indexOf('%') < 0 && raw.indexOf('+') < 0
@@ -0,0 +1,90 @@
package io.floci.aws.services.s3;
import io.floci.aws.core.common.RequestUriRewrite;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.ext.web.RoutingContext;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.core.UriBuilder;
import jakarta.ws.rs.ext.Provider;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Routes a request for a key made only of slashes as the object request it is. {@code PUT /bucket//} writes the
* key {@code /}, but JAX-RS collapses consecutive slashes before it matches a route, so the request would run as
* the bucket's operation (CreateBucket, ListObjects, DeleteBucket) and be authorized as that one. The key's
* slashes are escaped in the path the router matches, which keeps them inside the key, and {@code UriInfo}
* decodes them back, so {@link S3Controller} and the IAM check both see the object the request names. A key with
* anything besides slashes already reaches the object route, where the key is read from the path as sent
* ({@link S3ObjectKeys}).
*
* <p>Runs after {@link S3VirtualHostFilter}, which has put a virtual-hosted request's bucket into its path, and
* leaves alone a request signed for another service. An S3 Control route never matches as a bucket's own path,
* since each has more than one segment, so a bucket named like its prefix, {@code v20180820}, is read as a bucket.
*/
@Provider
@PreMatching
@Priority(Priorities.USER + 1)
@ApplicationScoped
public class S3SlashOnlyKeyFilter implements ContainerRequestFilter {
private static final Pattern BUCKET_PATH = Pattern.compile("/([^/]+)/?");
private final CurrentVertxRequest currentVertxRequest;
@Inject
public S3SlashOnlyKeyFilter(CurrentVertxRequest currentVertxRequest) {
this.currentVertxRequest = currentVertxRequest;
}
@Override
public void filter(ContainerRequestContext requestContext) {
RoutingContext routingContext = currentVertxRequest.getCurrent();
String sentPath = routingContext == null || routingContext.request() == null
? null : routingContext.request().path();
// A key of slashes alone ends the path with two, which every other request is passed on by.
if (sentPath == null || !sentPath.endsWith("//") || !sentPath.startsWith("/")
|| signedForAnotherService(requestContext)) {
return;
}
// Only a request the router would match as a bucket's own path, after any filter before this one rewrote it.
URI requestUri = requestContext.getUriInfo().getRequestUri();
Matcher routed = BUCKET_PATH.matcher(requestUri.getRawPath());
if (!routed.matches()) {
return;
}
String bucket = routed.group(1);
String key;
if (requestContext.getProperty(S3VirtualHostFilter.ORIGINAL_REQUEST_URI_PROPERTY) != null) {
key = sentPath.substring(1);
} else if (sentPath.startsWith("/" + bucket + "/")) {
key = sentPath.substring(bucket.length() + 2);
} else {
return;
}
if (key.isEmpty() || !key.chars().allMatch(c -> c == '/')) {
return;
}
URI objectUri = UriBuilder.fromUri(requestUri)
.replacePath("/" + bucket + "/" + "%2F".repeat(key.length()))
.build();
RequestUriRewrite.apply(requestContext, objectUri);
}
private static boolean signedForAnotherService(ContainerRequestContext requestContext) {
String authorization = requestContext.getHeaderString("Authorization");
if (authorization != null && authorization.contains("Credential=")) {
return !authorization.contains("/s3/aws4_request");
}
String credential = requestContext.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");
return credential != null && !credential.contains("/s3/aws4_request");
}
}