mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
4d4f20b812
commit
d250eb276e
17 files changed
+774
-58
No files matched your search
+11
-1
@@ -2122,9 +2122,19 @@ An S3 object operation is checked as the action the S3 documentation gives it:
|
||||
- Removing a configuration needs its Put action.
|
||||
- `DeleteBucketTagging` is checked as `s3:PutBucketTagging`, since AWS has no
|
||||
`s3:DeleteBucketTagging` action.
|
||||
- A bucket sub-resource Floci does not serve, such as S3 Metadata's `?metadataTable`, is checked
|
||||
as the action AWS's Service Reference gives the operation the AWS model names for it:
|
||||
`DELETE ?metadataTable` needs `s3:DeleteBucketMetadataTableConfiguration`, not
|
||||
`s3:DeleteBucket`, and `POST ?metadataTable` needs `s3:CreateBucketMetadataTableConfiguration`.
|
||||
S3 answers it `501 NotImplemented`.
|
||||
|
||||
A request naming several of these sub-resources is checked as the one S3 runs. `GET ?acl&tagging`
|
||||
returns the tags, so it needs `s3:GetObjectTagging`.
|
||||
returns the tags, so it needs `s3:GetObjectTagging`. An object key keeps every slash it is sent
|
||||
with, and the ARN the request is checked against keeps them too: `PUT /bucket//email.txt` writes the
|
||||
key `/email.txt` and needs `s3:PutObject` on `arn:aws:s3:::bucket//email.txt`, which a statement
|
||||
naming `bucket/email.txt` does not cover and one naming `bucket//*` does. The same holds inside a
|
||||
key, where `a//b.txt` is its own object. A key made only of slashes is an object as well:
|
||||
`PUT /bucket//` writes the key `/` and needs `s3:PutObject` on `arn:aws:s3:::bucket//`.
|
||||
|
||||
A request that passes a role to a service also needs `iam:PassRole` on that role, as the IAM user
|
||||
guide requires: "To pass a role (and its permissions) to an AWS service, a user must have
|
||||
|
||||
+13
-4
@@ -335,6 +335,13 @@ old path. The mapping is deterministic, so the same key always resolves to the s
|
||||
listing answers with the original key, which the object index holds, never with the encoded
|
||||
on-disk name.
|
||||
|
||||
A key keeps the slashes it is sent with: `PUT /bucket//file.txt` writes `/file.txt`, and a key made
|
||||
only of slashes is an object too, so `PUT /bucket//` writes the key `/` rather than creating the
|
||||
bucket. One trailing slash after the bucket, `/bucket/`, is still the bucket. The key is read from
|
||||
the path as it arrived wherever it is needed, so the object stored, the object an
|
||||
`s3:ExistingObjectTag` condition describes and the object ARN the request is authorized against are
|
||||
the same one (see [IAM](iam.md)).
|
||||
|
||||
## Bucket Regions
|
||||
|
||||
`CreateBucket` follows AWS's region rules, in every partition. The endpoint a request is signed for
|
||||
@@ -539,10 +546,12 @@ A denial answers in S3 Control's own REST-XML `<ErrorResponse>` envelope, which
|
||||
|
||||
## Not Implemented
|
||||
|
||||
These AWS S3 features have no handler in Floci. Calls will return an error (typically `404` or `NoSuchBucket`-style):
|
||||
|
||||
- Access logging (`PutBucketLogging`, `GetBucketLogging`)
|
||||
- Request payment (`PutBucketRequestPayment`, `GetBucketRequestPayment`)
|
||||
A bucket sub-resource the AWS model defines but Floci does not serve, such as S3 Metadata
|
||||
(`?metadataConfiguration`, `?metadataTable` and the journal, inventory and annotation table
|
||||
updates), attribute-based access control (`?abac`) or `CreateSession` (`?session`), is answered
|
||||
`501 NotImplemented`. A sub-resource sent with a method AWS does not define for it, such as
|
||||
`DELETE /bucket?versioning`, is answered `405 MethodNotAllowed`. Neither runs as the bucket's own
|
||||
operation, so neither creates, lists nor deletes the bucket.
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -1034,6 +1034,29 @@ class IamActionRegistryTest {
|
||||
registry.resolve("s3", mockCtx("DELETE", "/bucket", new MultivaluedHashMap<>(), null, "")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3BucketSubResourcesFlociDoesNotServeAreCheckedAsTheOperationsTheyName() {
|
||||
// S3Controller answers them NotImplemented instead of listing, creating or deleting the bucket, so they are
|
||||
// checked as AWS checks the operation the AWS model gives the sub-resource and method.
|
||||
assertEquals("s3:GetBucketMetadataTableConfiguration", bucketAction("GET", "metadataConfiguration"));
|
||||
assertEquals("s3:DeleteBucketMetadataTableConfiguration", bucketAction("DELETE", "metadataConfiguration"));
|
||||
assertEquals("s3:GetBucketMetadataTableConfiguration", bucketAction("GET", "metadataTable"));
|
||||
assertEquals("s3:DeleteBucketMetadataTableConfiguration", bucketAction("DELETE", "metadataTable"));
|
||||
assertEquals("s3:UpdateBucketMetadataJournalTableConfiguration", bucketAction("PUT", "metadataJournalTable"));
|
||||
assertEquals("s3:GetBucketAbac", bucketAction("GET", "abac"));
|
||||
assertEquals("s3:PutBucketAbac", bucketAction("PUT", "abac"));
|
||||
assertEquals("s3:CreateBucketMetadataTableConfiguration", bucketAction("POST", "metadataTable"));
|
||||
// A sub-resource sent with a method AWS defines none for is refused as not allowed, checked as before.
|
||||
assertEquals("s3:DeleteBucket", bucketAction("DELETE", "versioning"));
|
||||
assertEquals("s3:CreateBucket", bucketAction("PUT", "location"));
|
||||
assertNull(bucketAction("POST", "versioning"));
|
||||
// A browser-form PostObject runs ahead of any sub-resource and is checked per key, as DeleteObjects is.
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.add("metadataTable", "");
|
||||
assertNull(registry.resolve("s3", mockCtx("POST", "/bucket", params, MediaType.MULTIPART_FORM_DATA_TYPE, "")));
|
||||
assertNull(bucketAction("POST", "delete"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3BucketOnlySubResourcesStayInertOnAnObjectPath() {
|
||||
// ?notification on an object path is ignored by the object routes, so the request really
|
||||
|
||||
@@ -44,16 +44,6 @@ class IamRestRouteCoverageTest {
|
||||
/** The REST namespaces whose entries in {@code iam-authorized-actions.json} only the route table can apply. */
|
||||
private static final Set<String> ROUTED_NAMESPACES = Set.of("s3", "apigateway", "lambda");
|
||||
|
||||
/**
|
||||
* Operations Floci does not serve, whose request runs as another operation instead and so is checked
|
||||
* as that one: S3 has no bucket metadata configuration, and {@code ?metadataConfiguration} on a
|
||||
* bucket falls through to ListObjects and DeleteBucket. Checking it as the metadata table action
|
||||
* would let that action list or delete the bucket.
|
||||
*/
|
||||
private static final Map<String, String> RUN_AS_ANOTHER_OPERATION = Map.of(
|
||||
"GetBucketMetadataConfiguration", "s3:ListBucket",
|
||||
"DeleteBucketMetadataConfiguration", "s3:DeleteBucket");
|
||||
|
||||
/**
|
||||
* The S3 Control operations Floci serves, the rest-routes entry of which is a route the
|
||||
* registry maps. Every other operation of the s3control model has no route in Floci: the
|
||||
@@ -110,7 +100,7 @@ class IamRestRouteCoverageTest {
|
||||
while (entries.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = entries.next();
|
||||
List<Route> routes = routesOf(models, namespace, entry.getKey());
|
||||
String expected = RUN_AS_ANOTHER_OPERATION.getOrDefault(entry.getKey(), entry.getValue().asText());
|
||||
String expected = entry.getValue().asText();
|
||||
tests.add(DynamicTest.dynamicTest(namespace + " " + entry.getKey(), () -> {
|
||||
assertFalse(routes.isEmpty(), "no model route for " + entry.getKey());
|
||||
for (Route route : routes) {
|
||||
@@ -144,8 +134,7 @@ class IamRestRouteCoverageTest {
|
||||
Map.Entry<String, JsonNode> operation = operations.next();
|
||||
Route route = new Route(scope, model, operation.getKey(), operation.getValue().path("method").asText(),
|
||||
operation.getValue().path("requestUri").asText());
|
||||
String action = RUN_AS_ANOTHER_OPERATION.getOrDefault(operation.getKey(),
|
||||
authorized.path(scope).path(operation.getKey()).asText(scope + ":" + operation.getKey()));
|
||||
String action = authorized.path(scope).path(operation.getKey()).asText(scope + ":" + operation.getKey());
|
||||
boolean read = requestResources.path("operations").has(scope + ":" + operation.getKey());
|
||||
String expected = handBuilt.contains(scope) || read
|
||||
|| IamAuthorizedActions.actsOnNoResourceType(action)
|
||||
|
||||
@@ -20,6 +20,9 @@ import io.floci.aws.services.iam.model.ServerCertificate;
|
||||
import io.floci.aws.services.kms.KmsService;
|
||||
import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService;
|
||||
import io.floci.aws.services.secretsmanager.SecretsManagerService;
|
||||
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.ext.web.RoutingContext;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
@@ -1768,6 +1771,65 @@ class ResourceArnBuilderTest {
|
||||
assertEquals("arn:aws:s3:::my-bucket/folder/", arn);
|
||||
}
|
||||
|
||||
/**
|
||||
* A key keeps the slashes it is sent with, and so does the ARN the request is checked against.
|
||||
* {@code PUT /bucket//email.txt} stores the key {@code /email.txt}; read from the collapsed
|
||||
* path it was checked on {@code bucket/email.txt}, so a grant on that object covered this one
|
||||
* and a statement naming {@code bucket//*} reached nothing.
|
||||
*/
|
||||
@Test
|
||||
void s3ReadsAKeysOwnLeadingSlashFromThePathAsSent() {
|
||||
when(uriInfo.getPath()).thenReturn("/my-bucket/email.txt");
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost/my-bucket//email.txt"));
|
||||
|
||||
assertEquals("arn:aws:s3:::my-bucket//email.txt", builder.build("s3", ctx, "us-east-1", ACCOUNT));
|
||||
}
|
||||
|
||||
/** The same inside a key, where the collapsed path named a key one separator short. */
|
||||
@Test
|
||||
void s3KeepsADoubleSlashInsideAKey() {
|
||||
when(uriInfo.getPath()).thenReturn("/my-bucket/a/b.txt");
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost/my-bucket/a//b.txt"));
|
||||
|
||||
assertEquals("arn:aws:s3:::my-bucket/a//b.txt", builder.build("s3", ctx, "us-east-1", ACCOUNT));
|
||||
}
|
||||
|
||||
/**
|
||||
* Virtual-hosted, where the bucket came from the Host header and S3VirtualHostFilter rewrote the
|
||||
* path: the key's leading slash is then only in the request the server received.
|
||||
*/
|
||||
@Test
|
||||
void s3ReadsAVirtualHostedKeysOwnSlashFromTheRequestAsReceived() {
|
||||
when(uriInfo.getPath()).thenReturn("/my-bucket/email.txt");
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://my-bucket.localhost/my-bucket/email.txt"));
|
||||
ResourceArnBuilder withRequest = new ResourceArnBuilder(new ObjectMapper(), vertxRequestOn("//email.txt"));
|
||||
|
||||
assertEquals("arn:aws:s3:::my-bucket//email.txt", withRequest.build("s3", ctx, "us-east-1", ACCOUNT));
|
||||
}
|
||||
|
||||
/**
|
||||
* A key of slashes alone reaches the object route through the escaped path S3SlashOnlyKeyFilter
|
||||
* rewrites it to, and still reads as that object rather than as the bucket.
|
||||
*/
|
||||
@Test
|
||||
void s3KeepsAKeyOfOnlySlashes() {
|
||||
when(uriInfo.getPath()).thenReturn("/my-bucket//");
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost/my-bucket/%2F"));
|
||||
|
||||
assertEquals("arn:aws:s3:::my-bucket//", builder.build("s3", ctx, "us-east-1", ACCOUNT));
|
||||
}
|
||||
|
||||
/** A current request whose path is {@code sentPath}, the path the server received. */
|
||||
private static CurrentVertxRequest vertxRequestOn(String sentPath) {
|
||||
HttpServerRequest request = mock(HttpServerRequest.class);
|
||||
when(request.path()).thenReturn(sentPath);
|
||||
RoutingContext routingContext = mock(RoutingContext.class);
|
||||
when(routingContext.request()).thenReturn(request);
|
||||
CurrentVertxRequest current = mock(CurrentVertxRequest.class);
|
||||
when(current.getCurrent()).thenReturn(routingContext);
|
||||
return current;
|
||||
}
|
||||
|
||||
// ── S3 Control ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -1791,6 +1853,20 @@ class ResourceArnBuilderTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An S3 Control route names no object, so nothing of it is read as a bucket and a key: the ARN
|
||||
* in its path is still taken as written, percent-encoded as the Go SDK sends it or not.
|
||||
*/
|
||||
@Test
|
||||
void s3ControlTaggingIsNotReadAsABucketAndAKey() {
|
||||
when(uriInfo.getPath()).thenReturn("/v20180820/tags/arn:aws:s3:::repro-bucket");
|
||||
when(uriInfo.getRequestUri())
|
||||
.thenReturn(URI.create("http://localhost/v20180820/tags/arn%3Aaws%3As3%3A%3A%3Arepro-bucket"));
|
||||
|
||||
assertEquals(List.of("arn:aws:s3:::repro-bucket"),
|
||||
builder.buildResources("s3", "s3:TagResource", ctx, "us-east-1", ACCOUNT, "aws"));
|
||||
}
|
||||
|
||||
/** A tagging route naming no ARN stays on the wildcard, under which the handler refuses it. */
|
||||
@Test
|
||||
void s3ControlTaggingNamingNoArnLeavesTheWildcard() {
|
||||
@@ -1824,7 +1900,7 @@ class ResourceArnBuilderTest {
|
||||
/**
|
||||
* The operation tells S3 Control's requests from the data plane, not the path: a request a
|
||||
* data-plane action claims under the same prefix, a bucket actually named v20180820, keeps
|
||||
* the bucket and object ARN of its own path.
|
||||
* the bucket and object ARN of its own path, the slashes of its key included.
|
||||
*/
|
||||
@Test
|
||||
void aDataPlaneOperationUnderTheS3ControlPrefixKeepsItsOwnArn() {
|
||||
@@ -1834,6 +1910,10 @@ class ResourceArnBuilderTest {
|
||||
when(uriInfo.getPath()).thenReturn("/v20180820");
|
||||
assertEquals(List.of("arn:aws:s3:::v20180820"),
|
||||
builder.buildResources("s3", "s3:ListBucket", ctx, "us-east-1", ACCOUNT, "aws"));
|
||||
when(uriInfo.getPath()).thenReturn("/v20180820/a/b.txt");
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost/v20180820/a//b.txt"));
|
||||
assertEquals(List.of("arn:aws:s3:::v20180820/a//b.txt"),
|
||||
builder.buildResources("s3", "s3:PutObject", ctx, "us-east-1", ACCOUNT, "aws"));
|
||||
}
|
||||
|
||||
// ── The vendored table of request resources ─────────────────────────────────
|
||||
|
||||
+48
@@ -269,6 +269,54 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
|
||||
denied(f.user().when().get(f.path("doc")).then(), "s3:GetObject");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyOfOnlySlashesIsCheckedAsTheObjectItNames() {
|
||||
// PUT /bucket// writes the key "/". Collapsed to the bucket's path, it ran CreateBucket, checked as that.
|
||||
Fixture f = new Fixture("slash-only", false);
|
||||
f.policy(f.allowOnBucket("s3:CreateBucket", "s3:ListBucket", "s3:DeleteBucket"));
|
||||
rawDenied(f.raw("PUT", "/", null, f.accessKeyId, Map.of(), "slash"), "s3:PutObject");
|
||||
|
||||
f.policy("{\"Effect\":\"Allow\",\"Action\":[\"s3:PutObject\",\"s3:GetObject\",\"s3:DeleteObject\"],"
|
||||
+ "\"Resource\":\"arn:aws:s3:::" + f.bucket + "//\"}");
|
||||
assertEquals(200, f.raw("PUT", "/", null, f.accessKeyId, Map.of(), "slash").statusCode());
|
||||
assertEquals("slash", f.raw("GET", "/", null, f.accessKeyId, Map.of(), null).body());
|
||||
assertEquals(204, f.raw("DELETE", "/", null, f.accessKeyId, Map.of(), null).statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatStartsWithASlashIsCheckedAsTheObjectItNames() {
|
||||
// PUT /bucket//email.txt writes the key "/email.txt". Read from the collapsed path, it was
|
||||
// checked on arn:aws:s3:::bucket/email.txt, the other object.
|
||||
Fixture f = new Fixture("leading-slash", false);
|
||||
f.policy("{\"Effect\":\"Allow\",\"Action\":[\"s3:PutObject\",\"s3:GetObject\",\"s3:DeleteObject\"],"
|
||||
+ "\"Resource\":\"arn:aws:s3:::" + f.bucket + "/email.txt\"}");
|
||||
rawDenied(f.raw("PUT", "/email.txt", null, f.accessKeyId, Map.of(), "slash"), "s3:PutObject");
|
||||
|
||||
f.policy("{\"Effect\":\"Allow\",\"Action\":[\"s3:PutObject\",\"s3:GetObject\",\"s3:DeleteObject\"],"
|
||||
+ "\"Resource\":\"arn:aws:s3:::" + f.bucket + "//*\"}");
|
||||
assertEquals(200, f.raw("PUT", "/email.txt", null, f.accessKeyId, Map.of(), "slash").statusCode());
|
||||
assertEquals("slash", f.raw("GET", "/email.txt", null, f.accessKeyId, Map.of(), null).body());
|
||||
assertEquals(204, f.raw("DELETE", "/email.txt", null, f.accessKeyId, Map.of(), null).statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBucketSubresourceFlociDoesNotServeIsCheckedAsTheOperationItNames() {
|
||||
// DELETE ?metadataTable fell through to deleting the bucket, and was checked as s3:DeleteBucket.
|
||||
Fixture f = new Fixture("metadata-table", false);
|
||||
f.policy(f.allowOnBucket("s3:DeleteBucket"));
|
||||
denied(f.user().queryParam("metadataTable", "").when().delete("/" + f.bucket).then(),
|
||||
"s3:DeleteBucketMetadataTableConfiguration");
|
||||
// POST ?metadataTable, which no IAM rule mapped, went unchecked.
|
||||
denied(f.user().queryParam("metadataTable", "").when().post("/" + f.bucket).then(),
|
||||
"s3:CreateBucketMetadataTableConfiguration");
|
||||
|
||||
f.policy(f.allowOnBucket("s3:DeleteBucketMetadataTableConfiguration",
|
||||
"s3:CreateBucketMetadataTableConfiguration"));
|
||||
f.user().queryParam("metadataTable", "").when().delete("/" + f.bucket).then().statusCode(501);
|
||||
f.user().queryParam("metadataTable", "").when().post("/" + f.bucket).then().statusCode(501);
|
||||
f.admin().when().head("/" + f.bucket).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAnAnnotationWithTheBypassHeaderNeedsNoBypassPermission() {
|
||||
// The user guide: "The BypassGovernanceRetention permission does not apply to annotation
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package io.floci.aws.services.s3;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class S3BucketSubresourcesTest {
|
||||
|
||||
@Test
|
||||
void theVendoredModelGivesEachBucketSubresourceItsOperationsByMethod() {
|
||||
S3BucketSubresources subresources = S3BucketSubresources.vendored();
|
||||
|
||||
assertEquals(List.of("DeleteBucketMetadataTableConfiguration"),
|
||||
subresources.operations("DELETE", "metadataTable"));
|
||||
assertEquals(List.of("CreateBucketMetadataTableConfiguration"),
|
||||
subresources.operations("POST", "metadataTable"));
|
||||
assertEquals(List.of("GetBucketLifecycle", "GetBucketLifecycleConfiguration"),
|
||||
subresources.operations("GET", "lifecycle"));
|
||||
assertEquals(List.of(), subresources.operations("DELETE", "versioning"));
|
||||
assertEquals(List.of(), subresources.operations("GET", "no-such-subresource"));
|
||||
assertTrue(subresources.names().containsAll(List.of("abac", "acl", "delete", "metadataConfiguration",
|
||||
"session", "uploads", "versions")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aParameterWithAValueSelectsAVariantNotASubresource() {
|
||||
// ListObjectsV2 is /{Bucket}?list-type=2: the bucket listing, which runs on the bucket itself.
|
||||
assertFalse(S3BucketSubresources.vendored().names().contains("list-type"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyABucketRouteNamesABucketSubresource() throws IOException {
|
||||
S3BucketSubresources subresources = parse("""
|
||||
{"models": {"s3": {"operations": {
|
||||
"GetBucketAcl": {"method": "GET", "requestUri": "/{Bucket}?acl"},
|
||||
"GetObjectAcl": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?acl"},
|
||||
"PutObjectRetention": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}?retention"},
|
||||
"ListObjects": {"method": "GET", "requestUri": "/{Bucket}"}
|
||||
}}}}""");
|
||||
|
||||
assertEquals(List.of("acl"), subresources.names());
|
||||
assertEquals(List.of("GetBucketAcl"), subresources.operations("GET", "acl"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTableWithoutS3OrWithoutAUsableRouteFailsToLoad() {
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"models\": {}}"));
|
||||
assertThrows(IllegalStateException.class, () -> parse("""
|
||||
{"models": {"s3": {"operations": {"ListObjects": {"method": "GET", "requestUri": "/{Bucket}"}}}}}"""));
|
||||
assertThrows(IllegalStateException.class, () -> parse("""
|
||||
{"models": {"s3": {"operations": {"GetBucketAcl": {"requestUri": "/{Bucket}?acl"}}}}}"""));
|
||||
}
|
||||
|
||||
private static S3BucketSubresources parse(String json) throws IOException {
|
||||
return S3BucketSubresources.parse(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
}
|
||||
+31
@@ -162,6 +162,37 @@ class S3LeadingSlashKeyAuthEnforcementIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void aKeyOfOnlySlashesIsThatObjectPathStyleAndVirtualHosted() throws Exception {
|
||||
// "/bucket//" names the key "/", and "///" on a bucket's host the key "//": collapsed, each read as the bucket.
|
||||
URI pathStyle = URI.create(base() + "/" + BUCKET + "//");
|
||||
byte[] body = "one slash".getBytes(StandardCharsets.UTF_8);
|
||||
HttpResponse<String> put = send("PUT", pathStyle, body, LOCAL_SIGNER);
|
||||
assertEquals(200, put.statusCode(), put.body());
|
||||
assertEquals("one slash", send("GET", pathStyle, new byte[0], LOCAL_SIGNER).body());
|
||||
|
||||
URI virtualHosted = URI.create("http://" + BUCKET + ".localhost:" + RestAssured.port + "///");
|
||||
byte[] vhostBody = "two slashes".getBytes(StandardCharsets.UTF_8);
|
||||
RawResponse vhostPut = sendRaw("PUT", virtualHosted, vhostBody,
|
||||
LOCAL_SIGNER.headersFor("PUT", virtualHosted, vhostBody));
|
||||
assertEquals(200, vhostPut.status(), vhostPut.body());
|
||||
RawResponse vhostGet = sendRaw("GET", virtualHosted, new byte[0],
|
||||
LOCAL_SIGNER.headersFor("GET", virtualHosted, new byte[0]));
|
||||
assertEquals("two slashes", vhostGet.body());
|
||||
|
||||
given()
|
||||
.filter(LOCAL_SIGNER)
|
||||
.when()
|
||||
.get("/" + BUCKET + "?list-type=2")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<Key>/</Key>"), containsString("<Key>//</Key>"));
|
||||
assertEquals(204, send("DELETE", pathStyle, new byte[0], LOCAL_SIGNER).statusCode());
|
||||
assertEquals(204, send("DELETE", URI.create(base() + "/" + BUCKET + "///"), new byte[0], LOCAL_SIGNER)
|
||||
.statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void cleanup() throws Exception {
|
||||
HttpResponse<String> delete = send("DELETE", URI.create(base() + "/" + BUCKET + "/" + KEY),
|
||||
new byte[0], LOCAL_SIGNER);
|
||||
|
||||
@@ -282,4 +282,42 @@ class S3LeadingSlashKeyIntegrationTest {
|
||||
"List should show at least 2 objects (file.txt and /file.txt) but found " +
|
||||
keyCount + " <Key> entries. Bug: both keys collapsed into one. Response: " + body);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void aKeyOfOnlySlashesIsThatObjectNotTheBucket() throws Exception {
|
||||
// "/bucket//" names the key "/" and "/bucket///" the key "//": collapsed, either reads as the bucket.
|
||||
String bucket = "test-slash-only-bucket";
|
||||
given().when().put("/" + bucket).then().statusCode(200);
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
String base = baseUri.toString().replaceAll("/$", "");
|
||||
URI oneSlash = URI.create(base + "/" + bucket + "//");
|
||||
URI twoSlashes = URI.create(base + "/" + bucket + "///");
|
||||
|
||||
assertEquals(200, client.send(HttpRequest.newBuilder(oneSlash).PUT(HttpRequest.BodyPublishers.ofString("one"))
|
||||
.build(), HttpResponse.BodyHandlers.ofString()).statusCode());
|
||||
assertEquals(200, client.send(HttpRequest.newBuilder(twoSlashes).PUT(HttpRequest.BodyPublishers.ofString("two"))
|
||||
.build(), HttpResponse.BodyHandlers.ofString()).statusCode());
|
||||
assertEquals("one", client.send(HttpRequest.newBuilder(oneSlash).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()).body());
|
||||
assertEquals("two", client.send(HttpRequest.newBuilder(twoSlashes).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()).body());
|
||||
HttpResponse<String> head = client.send(HttpRequest.newBuilder(oneSlash)
|
||||
.method("HEAD", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, head.statusCode());
|
||||
assertEquals("3", head.headers().firstValue("content-length").orElse(null));
|
||||
given().when().get("/" + bucket + "?list-type=2").then().statusCode(200)
|
||||
.body(containsString("<Key>/</Key>"), containsString("<Key>//</Key>"));
|
||||
|
||||
HttpResponse<String> delete = client.send(HttpRequest.newBuilder(oneSlash).DELETE().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(204, delete.statusCode(), delete.body());
|
||||
assertEquals(404, client.send(HttpRequest.newBuilder(oneSlash).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()).statusCode());
|
||||
given().when().get("/" + bucket + "?list-type=2").then().statusCode(200)
|
||||
.body(not(containsString("<Key>/</Key>")), containsString("<Key>//</Key>"));
|
||||
|
||||
// One trailing slash is still the bucket.
|
||||
given().when().get("/" + bucket + "/").then().statusCode(200).body(containsString("<ListBucketResult"));
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package io.floci.aws.services.s3;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* A bucket request naming a sub-resource runs that sub-resource's operation in AWS, never the bucket's own. One
|
||||
* Floci does not serve used to fall through to the bucket's operation: {@code DELETE ?metadataTable} deleted the
|
||||
* bucket, {@code GET ?abac} listed it and {@code PUT ?abac} created it. The buckets here stay empty, since an empty
|
||||
* bucket is the one a fall-through DeleteBucket removes.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class S3UnservedBucketSubresourceIntegrationTest {
|
||||
|
||||
private static final List<String> METHODS = List.of("GET", "PUT", "DELETE", "POST", "HEAD");
|
||||
|
||||
@Test
|
||||
void aSubresourceFlociDoesNotServeIsNotImplementedAndLeavesTheBucketAlone() {
|
||||
String bucket = "unserved-subresource-bucket";
|
||||
given().when().put("/" + bucket).then().statusCode(200);
|
||||
String[][] requests = {
|
||||
{"DELETE", "metadataConfiguration"}, {"DELETE", "metadataTable"},
|
||||
{"GET", "metadataConfiguration"}, {"GET", "metadataTable"}, {"GET", "abac"}, {"GET", "session"},
|
||||
{"PUT", "abac"}, {"PUT", "metadataJournalTable"}, {"PUT", "metadataInventoryTable"},
|
||||
{"PUT", "metadataAnnotationTable"}, {"POST", "metadataConfiguration"}, {"POST", "metadataTable"},
|
||||
};
|
||||
for (String[] request : requests) {
|
||||
given().queryParam(request[1], "")
|
||||
.when()
|
||||
.request(request[0], "/" + bucket)
|
||||
.then()
|
||||
.statusCode(501)
|
||||
.body(containsString("<Code>NotImplemented</Code>"));
|
||||
}
|
||||
given().when().head("/" + bucket).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSubresourceSentWithAMethodAwsDefinesNoneForIsNotAllowed() {
|
||||
String bucket = "misdirected-subresource-bucket";
|
||||
given().when().put("/" + bucket).then().statusCode(200);
|
||||
String[][] requests = {
|
||||
{"DELETE", "versioning"}, {"DELETE", "acl"}, {"DELETE", "uploads"},
|
||||
{"PUT", "location"}, {"PUT", "uploads"}, {"GET", "delete"}, {"POST", "versioning"},
|
||||
};
|
||||
for (String[] request : requests) {
|
||||
given().queryParam(request[1], "")
|
||||
.when()
|
||||
.request(request[0], "/" + bucket)
|
||||
.then()
|
||||
.statusCode(405)
|
||||
.body(containsString("<Code>MethodNotAllowed</Code>"));
|
||||
}
|
||||
// AWS defines no sub-resource for HEAD, so none runs HeadBucket; a HEAD answer carries no body.
|
||||
given().queryParam("acl", "").when().head("/" + bucket).then().statusCode(405);
|
||||
given().when().head("/" + bucket).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEscapedAmpersandInAValueNamesNoSubresource() {
|
||||
// ?prefix=reports%26abac is one parameter whose value holds "&abac", not an ?abac sub-resource.
|
||||
String bucket = "escaped-ampersand-bucket";
|
||||
given().when().put("/" + bucket).then().statusCode(200);
|
||||
given().queryParam("prefix", "reports&abac")
|
||||
.when()
|
||||
.get("/" + bucket)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<ListBucketResult"), containsString("<Prefix>reports&abac</Prefix>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPutNamingASubresourceNeverCreatesTheBucket() {
|
||||
String bucket = "never-created-by-a-subresource";
|
||||
given().queryParam("abac", "").when().put("/" + bucket).then().statusCode(501);
|
||||
given().queryParam("location", "").when().put("/" + bucket).then().statusCode(405);
|
||||
given().when().head("/" + bucket).then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noSubresourceOfTheAwsModelRunsAsTheBucketsOwnOperation() {
|
||||
String bucket = "every-subresource-bucket";
|
||||
String missing = "every-subresource-missing";
|
||||
given().when().put("/" + bucket).then().statusCode(200);
|
||||
for (String name : S3BucketSubresources.vendored().names()) {
|
||||
for (String method : METHODS) {
|
||||
String response = given().queryParam(name, "").when().request(method, "/" + bucket)
|
||||
.then().extract().asString();
|
||||
given().when().head("/" + bucket).then().statusCode(200);
|
||||
if ("GET".equals(method)) {
|
||||
assertThat(method + " ?" + name, response,
|
||||
not(containsString("<ListBucketResult")));
|
||||
}
|
||||
}
|
||||
given().queryParam(name, "").when().put("/" + missing);
|
||||
given().when().head("/" + missing).then().statusCode(404);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user