feat(iam): read S3 and S3 Control from the generated tables (#9155)

S3 leaves the registry's hand rules and ResourceArnBuilder's S3 branch: its requests are matched
on their botocore routes, checked as the actions the authorized-actions file gives them, on the
resources the request-resources table reads. regen_rest_routes.py no longer lists s3 as hand-routed,
and regen_iam_request_resources.py reads s3 instead of leaving it to the builder; the tables gain
S3's and S3 Control's 195 operations and nothing else changes. Operations sharing a route are told
apart by the query parameters and headers botocore requires, an S3 Control request by its route's
model, which also picks S3 Control's error envelope (isS3ControlRequest), and a member the two
clients locate apart is read for the client whose route the request matched.

An object key is read as S3 reads it, keeping the slashes it was sent with, through
RequestPathLabels, a per-namespace hook S3 implements with S3ObjectKeys. DeleteObjects names its
keys in its XML body, so it takes s3:DeleteObject's types from the S3 user guide's Either row and is
unread: the filter leaves it to S3, which checks each key.

The registry's S3 rules, S3 Control rules and sub-resource overrides are deleted, with the tests of
Floci's own handler order, the regional S3 Control ARN form, and a version for HEAD, HEAD
?annotation and Select, none of which an AWS source gives.

S3 also runs only what botocore routes, so what runs is what is checked: a request naming annotationName
is GetObjectAnnotation and a HEAD naming one HeadObject, SelectObjectContent runs on
?select&select-type=2 and reads the current version, the S3 Control tagging handler decodes its ARN
once, and a request two operations' routes take alike is refused under enforcement.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-21 17:44:36 -04:00
1 parent 546770ab69
commit 4735606fb9
29 files changed
+912 -1143

No files matched your search

@@ -480,7 +480,9 @@ class RequestResourceMembersTest {
@TestFactory
Stream<DynamicTest> everyResourceOfTheTableIsReadFromAJsonBodyAndAForm() {
RequestResourceMembers.Table table = RequestResourceMembers.table();
return table.operations().entrySet().stream().flatMap(operation -> operation.getValue().stream()
// An unread operation names what it acts on in a body the reader does not read, so it reads none of it.
return table.operations().entrySet().stream().filter(operation -> !table.unread().contains(operation.getKey()))
.flatMap(operation -> operation.getValue().stream()
.map(resource -> DynamicTest.dynamicTest(operation.getKey() + " " + resource, () -> {
String namespace = operation.getKey().substring(0, operation.getKey().indexOf(':'));
String name = operation.getKey().substring(namespace.length() + 1);
@@ -534,9 +536,9 @@ class RequestResourceMembersTest {
&& other.when().equals(resource.when()) && other.unless().equals(resource.unless()))
&& (other.endpoint() == null || resource.endpoint() == null
|| other.endpoint().equals(resource.endpoint())))
.map(other -> other == resource ? expected : expected(
table.formats().get(namespace).get(other.types().getFirst()).format(), other,
"000000000000", given.keySet()))
.flatMap(other -> other == resource ? inTheRequestsRegionToo(expected, resource).stream()
: Stream.of(expected(table.formats().get(namespace).get(other.types().getFirst())
.format(), other, "000000000000", given.keySet())))
.distinct().toList();
StoredResourceArns stored = runningOn(namespace, arn, resource.byDefault());
assertEquals(named, RequestResources.of(operation.getKey(),
@@ -803,6 +805,21 @@ class RequestResourceMembersTest {
}
}
/**
* The ARN a request names in a member, and, for one whose format gives it a Region of its own (a Multi-Region
* Access Point request's, in us-west-2), the same ARN in the request's, us-east-1, where the reader checks a named
* resource as well.
*/
private static List<String> inTheRequestsRegionToo(String expected, Resource resource) {
if (resource.arn() == null || !AwsArnUtils.isArn(expected)) {
return List.of(expected);
}
AwsArnUtils.Arn named = AwsArnUtils.parse(expected);
return named.region().isEmpty() || named.region().equals("us-east-1") ? List.of(expected)
: List.of(expected, new AwsArnUtils.Arn(named.partition(), named.service(), "us-east-1",
named.accountId(), named.resource()).toString());
}
private static String document(String formats, String resource) {
return "{\"namespaces\":{\"a\":[]}," + formats + ",\"operations\":{\"a:Op\":{\"resources\":[" + resource + "]}}}";
}
@@ -638,7 +638,8 @@ class IamActionRegistryTest {
@Test
void aTrailingSlashIsCheckedAsTheRouteWithoutIt() {
// The router matches /clusters/ as /clusters, so the rule ending at the route's last segment covers it.
// An S3 path is matched as sent, as before: a key may end in a slash.
// An S3 path is matched as sent: a key may end in a slash, and one of slashes alone arrives as
// S3SlashOnlyKeyFilter rewrites it, escaped.
String[][] routes = {
{"eks", "POST", "/clusters/", "eks:CreateCluster"},
{"eks", "GET", "/clusters/c/node-groups/ng/", "eks:DescribeNodegroup"},
@@ -647,9 +648,9 @@ class IamActionRegistryTest {
{"lambda", "GET", "/2015-03-31/functions/fn/", "lambda:GetFunction"},
{"s3", "GET", "/bucket/", "s3:ListBucket"},
{"s3", "GET", "/bucket/folder/", "s3:GetObject"},
{"s3", "PUT", "/bucket//", "s3:PutObject"},
{"s3", "GET", "/bucket//", "s3:GetObject"},
{"s3", "DELETE", "/bucket//", "s3:DeleteObject"},
{"s3", "PUT", "/bucket/%2F", "s3:PutObject"},
{"s3", "GET", "/bucket/%2F", "s3:GetObject"},
{"s3", "DELETE", "/bucket/%2F", "s3:DeleteObject"},
};
for (String[] route : routes) {
assertEquals(route[3], registry.resolveRoute(route[0], mockCtx(route[1], route[2],
@@ -780,29 +781,13 @@ class IamActionRegistryTest {
assertEquals("s3:PutObjectLegalHold", s3Action("PUT", "/bucket/key", "legal-hold"));
assertEquals("s3:GetObjectAnnotation", s3Action("GET", "/bucket/key", "annotation", "annotationName=n"));
assertEquals("s3:ListObjectAnnotations", s3Action("GET", "/bucket/key", "annotation"));
assertEquals("s3:ListObjectAnnotations", s3Action("GET", "/bucket/key", "annotation", "annotationName="));
assertEquals("s3:GetObjectAnnotation", s3Action("HEAD", "/bucket/key", "annotation", "annotationName=n"));
assertEquals("s3:PutObjectAnnotation", s3Action("PUT", "/bucket/key", "annotation"));
assertEquals("s3:DeleteObjectAnnotation", s3Action("DELETE", "/bucket/key", "annotation"));
}
@Test
void s3ObjectSubresourcesFollowTheOrderTheControllerDispatchesThem() {
assertEquals("s3:GetObjectTagging", s3Action("GET", "/bucket/key", "acl", "tagging"));
assertEquals("s3:PutObjectTagging", s3Action("PUT", "/bucket/key", "acl", "tagging"));
assertEquals("s3:ListMultipartUploadParts", s3Action("GET", "/bucket/key", "acl", "uploadId=u1"));
assertEquals("s3:GetObjectRetention", s3Action("GET", "/bucket/key", "acl", "retention"));
assertEquals("s3:DeleteObjectTagging", s3Action("DELETE", "/bucket/key", "acl", "tagging"));
assertEquals("s3:DeleteObjectAnnotation", s3Action("DELETE", "/bucket/key", "annotation", "uploadId=u1"));
assertEquals("s3:PutObject", s3Action("POST", "/bucket/key", "uploads", "restore"));
assertEquals("s3:RestoreObject", s3Action("POST", "/bucket/key", "restore", "uploadId=u1"));
assertEquals("s3:GetObject", s3Action("POST", "/bucket/key", "select", "uploadId=u1"));
}
@Test
void s3VersionedObjectRequestsResolveToTheVersionActions() {
assertEquals("s3:GetObjectVersion", s3Action("GET", "/bucket/key", "versionId=v1"));
assertEquals("s3:GetObjectVersion", s3Action("HEAD", "/bucket/key", "versionId=v1"));
assertEquals("s3:DeleteObjectVersion", s3Action("DELETE", "/bucket/key", "versionId=v1"));
assertEquals("s3:GetObjectVersionAcl", s3Action("GET", "/bucket/key", "acl", "versionId=v1"));
assertEquals("s3:PutObjectVersionAcl", s3Action("PUT", "/bucket/key", "acl", "versionId=v1"));
@@ -814,8 +799,6 @@ class IamActionRegistryTest {
assertEquals("s3:GetObjectVersionTagging", s3Action("GET", "/bucket/key", "tagging", "versionId=null"));
assertEquals("s3:GetObjectVersionAnnotation",
s3Action("GET", "/bucket/key", "annotation", "annotationName=n", "versionId=v1"));
assertEquals("s3:GetObjectVersionAnnotation",
s3Action("HEAD", "/bucket/key", "annotation", "annotationName=n", "versionId=v1"));
assertEquals("s3:ListObjectVersionAnnotations",
s3Action("GET", "/bucket/key", "annotation", "versionId=v1"));
assertEquals("s3:PutObjectVersionAnnotation",
@@ -824,8 +807,6 @@ class IamActionRegistryTest {
s3Action("DELETE", "/bucket/key", "annotation", "annotationName=n", "versionId=v1"));
// GetObjectAttributes of a version is checked as the read of that version.
assertEquals("s3:GetObjectVersion", s3Action("GET", "/bucket/key", "attributes", "versionId=v1"));
// S3Controller selects from the version a versionId names.
assertEquals("s3:GetObjectVersion", s3Action("POST", "/bucket/key", "select", "versionId=v1"));
// Retention and legal hold have no version action; the upload operations take no version.
assertEquals("s3:GetObjectRetention", s3Action("GET", "/bucket/key", "retention", "versionId=v1"));
assertEquals("s3:PutObjectLegalHold", s3Action("PUT", "/bucket/key", "legal-hold", "versionId=v1"));
@@ -929,27 +910,6 @@ class IamActionRegistryTest {
mockCtx("GET", "/2015-03-31/functions", new MultivaluedHashMap<>(), null, "")));
}
@Test
void s3AccelerateYieldsToSubresourcesDispatchedFirst() {
MultivaluedMap<String, String> withRequestPayment = new MultivaluedHashMap<>();
withRequestPayment.add("requestPayment", "");
withRequestPayment.add("accelerate", "");
assertEquals("s3:PutBucketRequestPayment",
registry.resolve("s3", mockCtx("PUT", "/bucket", withRequestPayment, null, "")));
MultivaluedMap<String, String> withLocation = new MultivaluedHashMap<>();
withLocation.add("location", "");
withLocation.add("accelerate", "");
assertEquals("s3:GetBucketLocation",
registry.resolve("s3", mockCtx("GET", "/bucket", withLocation, null, "")));
// uploads is a GET-only dispatch branch; on PUT it is inert and accelerate executes,
// so the mapping must still claim the request there.
MultivaluedMap<String, String> withUploads = new MultivaluedHashMap<>();
withUploads.add("uploads", "");
withUploads.add("accelerate", "");
assertEquals("s3:PutAccelerateConfiguration",
registry.resolve("s3", mockCtx("PUT", "/bucket", withUploads, null, "")));
}
@Test
void s3ReplicationResolvesToItsOwnActions() {
// Without the override, PUT ?replication resolves to s3:CreateBucket — a
@@ -980,41 +940,6 @@ class IamActionRegistryTest {
registry.resolve("s3", mockCtx("DELETE", "/bucket/key.txt", replication, null, "")));
}
@Test
void s3ReplicationYieldsToSubresourcesDispatchedFirst() {
// The first dispatched subresource determines the required permission.
MultivaluedMap<String, String> withRequestPayment = new MultivaluedHashMap<>();
withRequestPayment.add("requestPayment", "");
withRequestPayment.add("replication", "");
assertEquals("s3:PutBucketRequestPayment",
registry.resolve("s3", mockCtx("PUT", "/bucket", withRequestPayment, null, "")));
MultivaluedMap<String, String> withLocation = new MultivaluedHashMap<>();
withLocation.add("location", "");
withLocation.add("replication", "");
assertEquals("s3:GetBucketLocation",
registry.resolve("s3", mockCtx("GET", "/bucket", withLocation, null, "")));
// The DELETE chain dispatches website ahead of replication.
MultivaluedMap<String, String> withWebsite = new MultivaluedHashMap<>();
withWebsite.add("website", "");
withWebsite.add("replication", "");
assertEquals("s3:DeleteBucketWebsite",
registry.resolve("s3", mockCtx("DELETE", "/bucket", withWebsite, null, "")));
// requestPayment has no DELETE dispatch branch; it is inert there and
// replication executes, so the mapping must still claim the request.
MultivaluedMap<String, String> deleteWithRequestPayment = new MultivaluedHashMap<>();
deleteWithRequestPayment.add("requestPayment", "");
deleteWithRequestPayment.add("replication", "");
assertEquals("s3:PutReplicationConfiguration",
registry.resolve("s3", mockCtx("DELETE", "/bucket", deleteWithRequestPayment, null, "")));
// uploads is a GET-only dispatch branch; on PUT it is inert and replication
// executes, so the mapping must still claim the request there.
MultivaluedMap<String, String> putWithUploads = new MultivaluedHashMap<>();
putWithUploads.add("uploads", "");
putWithUploads.add("replication", "");
assertEquals("s3:PutReplicationConfiguration",
registry.resolve("s3", mockCtx("PUT", "/bucket", putWithUploads, null, "")));
}
@Test
void s3ReplicationAndAcceleratePrecedenceFollowsEachMethodsDispatchOrder() {
// PUT and GET dispatch accelerate ahead of replication; DELETE routes
@@ -1030,36 +955,6 @@ class IamActionRegistryTest {
registry.resolve("s3", mockCtx("DELETE", "/bucket", both, null, "")));
}
@Test
void s3ReplicationDoesNotPreemptAclOrTagging() {
// Appending an inert ?replication must not downgrade a stricter resolution.
MultivaluedMap<String, String> withAcl = new MultivaluedHashMap<>();
withAcl.add("replication", "");
withAcl.add("acl", "");
assertEquals("s3:PutBucketAcl",
registry.resolve("s3", mockCtx("PUT", "/bucket", withAcl, null, "")));
MultivaluedMap<String, String> withTagging = new MultivaluedHashMap<>();
withTagging.add("replication", "");
withTagging.add("tagging", "");
assertEquals("s3:PutBucketTagging",
registry.resolve("s3", mockCtx("DELETE", "/bucket", withTagging, null, "")));
}
@Test
void s3AccelerateDoesNotPreemptAclOrTagging() {
// Appending an inert ?accelerate must not downgrade a stricter resolution.
MultivaluedMap<String, String> withAcl = new MultivaluedHashMap<>();
withAcl.add("accelerate", "");
withAcl.add("acl", "");
assertEquals("s3:PutBucketAcl",
registry.resolve("s3", mockCtx("PUT", "/bucket", withAcl, null, "")));
MultivaluedMap<String, String> withTagging = new MultivaluedHashMap<>();
withTagging.add("accelerate", "");
withTagging.add("tagging", "");
assertEquals("s3:DeleteObjectTagging",
registry.resolve("s3", mockCtx("DELETE", "/bucket/key.txt", withTagging, null, "")));
}
@Test
void s3BucketSubResourceWritesResolveToTheirOwnActionNotCreateBucket() {
// The live failure: CDK's BucketNotificationsHandler role grants s3:PutBucketNotification
@@ -1120,10 +1015,7 @@ class IamActionRegistryTest {
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, "")));
// DeleteObjects names its keys in its body, which S3Controller checks one by one.
assertNull(bucketAction("POST", "delete"));
}
@@ -2,6 +2,7 @@ package io.floci.aws.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.RequestResources;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -45,32 +46,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");
/**
* 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
* request falls through to the S3 data plane and is checked as the object or bucket
* operation that runs.
*/
private static final Set<String> SERVED_S3_CONTROL_OPERATIONS = Set.of(
"DeletePublicAccessBlock", "GetPublicAccessBlock", "ListAccessPoints", "ListTagsForResource",
"PutPublicAccessBlock", "TagResource", "UntagResource");
/**
* The account-level Block Public Access, the one route the Service Reference cannot settle.
* It files S3's and S3 Control's GetPublicAccessBlock, PutPublicAccessBlock and
* DeletePublicAccessBlock under the bucket actions (s3:GetBucketPublicAccessBlock,
* s3:PutBucketPublicAccessBlock and s3:DeleteBucketPublicAccessBlock), one action between
* the two clients, although the account level is a different permission. The S3 User
* Guide's Block Public Access page gives the account level s3:PutAccountPublicAccessBlock
* to write and s3:GetAccountPublicAccessBlock to read, and a delete needs the same action
* as the write it undoes.
* https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-control-block-public-access.html
*/
private static final Map<String, String> ACCOUNT_PUBLIC_ACCESS_BLOCK_ACTIONS = Map.of(
"GetPublicAccessBlock", "s3:GetAccountPublicAccessBlock",
"PutPublicAccessBlock", "s3:PutAccountPublicAccessBlock",
"DeletePublicAccessBlock", "s3:PutAccountPublicAccessBlock");
private final IamActionRegistry registry = new IamActionRegistry();
@TestFactory
@@ -157,14 +132,9 @@ class IamRestRouteCoverageTest {
Stream<DynamicTest> everyOperationOfARoutedScopeResolvesToItsActionWhenFlociCanCheckIt() throws IOException {
JsonNode document = load("/aws/rest-routes.json");
JsonNode models = document.path("models");
JsonNode authorizedActions = load("/aws/iam-authorized-actions.json");
JsonNode authorized = authorizedActions.path("authorizedActions");
JsonNode requestResources = load("/aws/iam-request-resources.json");
Set<String> handBuilt = new HashSet<>();
requestResources.path("handBuilt").forEach(namespace -> handBuilt.add(namespace.asText()));
Set<String> byMethod = new HashSet<>();
authorizedActions.path("authorizedByMethod").properties().forEach(scope ->
scope.getValue().forEach(operation -> byMethod.add(scope.getKey() + ":" + operation.asText())));
List<DynamicTest> tests = new ArrayList<>();
for (String model : routedModels(document)) {
String scope = models.path(model).path("credentialScope").asText();
@@ -173,20 +143,22 @@ class IamRestRouteCoverageTest {
Map.Entry<String, JsonNode> operation = operations.next();
String method = operation.getValue().path("method").asText();
List<Route> routes = new ArrayList<>(List.of(new Route(scope, model, operation.getKey(), method,
operation.getValue().path("requestUri").asText())));
operation.getValue().path("requestUri").asText(), operation.getValue().path("requires"))));
operation.getValue().path("alternatives").forEach(alternative -> routes.add(new Route(scope, model,
operation.getKey(), alternative.path("method").asText(method),
alternative.path("requestUri").asText())));
boolean read = requestResources.path("operations").has(scope + ":" + operation.getKey());
// An unread operation names what it acts on in a body the reader does not read, so it is left to its
// service, as one whose resources nothing reads is.
boolean read = RequestResources.reads(scope + ":" + operation.getKey());
for (Route route : routes) {
String action = byMethod.contains(scope + ":" + operation.getKey())
? scope + ":" + route.method()
: authorized.path(scope).path(operation.getKey()).asText(scope + ":" + operation.getKey());
String expected = handBuilt.contains(scope) || read
|| IamAuthorizedActions.actsOnNoResourceType(action)
? action : null;
tests.add(DynamicTest.dynamicTest(route.toString(),
() -> assertEquals(expected, resolve(route), route.toString())));
tests.add(DynamicTest.dynamicTest(route.toString(), () -> {
ContainerRequestContext request = route.request();
String action = IamAuthorizedActions.actionFor(scope, operation.getKey(), route.method(),
model, request.getUriInfo().getQueryParameters());
String expected = handBuilt.contains(scope) || read
|| IamAuthorizedActions.actsOnNoResourceType(action) ? action : null;
assertEquals(expected, registry.resolveRoute(scope, request), route.toString());
}));
}
}
}
@@ -209,53 +181,26 @@ class IamRestRouteCoverageTest {
while (operations.hasNext()) {
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());
operation.getValue().path("requestUri").asText(), operation.getValue().path("requires"));
tests.add(DynamicTest.dynamicTest(model + " " + operation.getKey(), () -> {
ContainerRequestContext request = route.request();
String matched = IamRestRoutes.vendored().operation(scope, route.method(),
request.getUriInfo().getPath(), request.getUriInfo().getQueryParameters()).orElse(null);
assertEquals(IamAuthorizedActions.actionFor(scope, operation.getKey(), route.method()),
matched == null ? null : IamAuthorizedActions.actionFor(scope, matched, route.method()),
route.toString());
MultivaluedMap<String, String> query = request.getUriInfo().getQueryParameters();
String matched = IamRestRoutes.vendored().match(scope, route.method(),
request.getUriInfo().getPath(), query, false, request.getHeaders())
.map(match -> IamAuthorizedActions.actionFor(scope, match.operation(), route.method(),
match.model(), query))
.orElse(null);
assertEquals(IamAuthorizedActions.actionFor(scope, operation.getKey(), route.method(), model, query),
matched, route.toString());
// No request an SDK sends on a route is one two operations' routes take alike, which is refused.
assertFalse(IamRestRoutes.vendored().ambiguous(scope, route.method(), request.getUriInfo().getPath(),
query, false, request.getHeaders()), route.toString());
}));
}
}
return tests.stream();
}
/**
* Every route of the s3control model, which signs with the s3 scope. A route Floci serves is
* checked as the action the Service Reference gives the operation, with the account-level
* Block Public Access as its one written-down exception; a route Floci does not serve runs
* as the S3 data plane, so it must not resolve to any of the served routes' actions.
*/
@TestFactory
Stream<DynamicTest> everyS3ControlRouteIsCheckedAsTheServiceReferenceGivesIt() throws IOException {
JsonNode models = load("/aws/rest-routes.json").path("models");
JsonNode authorized = load("/aws/iam-authorized-actions.json").path("authorizedActions");
Map<String, String> served = new HashMap<>();
for (String operation : SERVED_S3_CONTROL_OPERATIONS) {
served.put(operation, ACCOUNT_PUBLIC_ACCESS_BLOCK_ACTIONS.getOrDefault(operation,
authorized.path("s3").path(operation).asText("s3:" + operation)));
}
List<DynamicTest> tests = new ArrayList<>();
Iterator<Map.Entry<String, JsonNode>> operations =
models.path("s3control").path("operations").fields();
while (operations.hasNext()) {
Map.Entry<String, JsonNode> operation = operations.next();
Route route = new Route("s3", "s3control", operation.getKey(),
operation.getValue().path("method").asText(),
operation.getValue().path("requestUri").asText());
String expected = served.get(operation.getKey());
tests.add(expected == null
? DynamicTest.dynamicTest("s3control " + operation.getKey() + " (not served)",
() -> assertFalse(served.containsValue(resolve(route)), route.toString()))
: DynamicTest.dynamicTest("s3control " + operation.getKey(),
() -> assertEquals(expected, resolve(route), route.toString())));
}
return tests.stream();
}
/** The models of every credential scope the vendored routes do not list as hand-routed. */
private static List<String> routedModels(JsonNode document) {
List<String> models = new ArrayList<>();
@@ -306,7 +306,10 @@ class IamRestRoutesTest {
assertEquals(Optional.empty(), get("/nothing"));
}
/** The vendored routes load, a model routed under the scope it signs with, and S3 is left to its rules. */
/**
* The vendored routes load, a model routed under the scope it signs with: S3 and S3 Control under the s3 scope, a
* route several operations share told apart by what each requires.
*/
@Test
void theVendoredRoutesAreRead() {
assertEquals(Optional.of("GetFunction"),
@@ -317,7 +320,32 @@ class IamRestRoutesTest {
IamRestRoutes.vendored().operation("es", "GET", "/2021-01-01/opensearch/domain/logs", null));
assertEquals(Optional.of("DescribeElasticsearchDomain"),
IamRestRoutes.vendored().operation("es", "GET", "/2015-01-01/es/domain/logs", null));
assertEquals(Optional.empty(), IamRestRoutes.vendored().operation("s3", "GET", "/bucket", null));
assertEquals(Optional.of("ListObjects"), IamRestRoutes.vendored().operation("s3", "GET", "/bucket", null));
MultivaluedMap<String, String> upload = new MultivaluedHashMap<>();
upload.add("uploadId", "u");
assertEquals(Optional.of("ListParts"), IamRestRoutes.vendored().operation("s3", "GET", "/bucket/key", upload));
assertEquals(Optional.of("GetPublicAccessBlock"), IamRestRoutes.vendored()
.match("s3", "GET", "/v20180820/configuration/publicAccessBlock", null)
.filter(match -> "s3control".equals(match.model())).map(IamRestRoutes.Match::operation));
}
/**
* A request two operations' routes take alike, none outranking the other, is ambiguous: one naming two of S3's
* sub-resources. One a route requiring more takes over one requiring less is not.
*/
@Test
void aRequestTwoOperationsRoutesTakeAlikeIsAmbiguous() {
MultivaluedMap<String, String> both = new MultivaluedHashMap<>();
both.add("cors", "");
both.add("policy", "");
assertTrue(IamRestRoutes.vendored().ambiguous("s3", "PUT", "/bucket", both, false, null));
MultivaluedMap<String, String> one = new MultivaluedHashMap<>();
one.add("cors", "");
assertFalse(IamRestRoutes.vendored().ambiguous("s3", "PUT", "/bucket", one, false, null));
MultivaluedMap<String, String> part = new MultivaluedHashMap<>();
part.add("partNumber", "1");
part.add("uploadId", "u");
assertFalse(IamRestRoutes.vendored().ambiguous("s3", "PUT", "/bucket/key", part, false, null));
}
@ParameterizedTest
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.ProtocolClaim;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.core.common.RequestPathLabels;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.common.WireProtocol;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
@@ -25,6 +26,7 @@ import io.floci.aws.services.iam.model.ServerCertificate;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.lambda.LambdaStoredResourceArns;
import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService;
import io.floci.aws.services.s3.S3RequestPathLabels;
import io.floci.aws.services.sqs.SqsService;
import io.floci.aws.services.sqs.SqsServiceFactory;
import io.floci.aws.services.sqs.SqsStoredResourceArns;
@@ -1947,97 +1949,28 @@ class ResourceArnBuilderTest {
builder.buildResources("sns", "sns:TagResource", ctx, "us-east-1", ACCOUNT, "aws"));
}
// ── S3 ──────────────────────────────────────────────────────────────────────
// ── S3 and S3 Control ───────────────────────────────────────────────────────
@Test
void s3BuildsBucketArn() {
when(uriInfo.getPath()).thenReturn("/my-bucket");
String arn = builder.build("s3", ctx, "us-east-1", "000000000000");
assertEquals("arn:aws:s3:::my-bucket", arn);
/** The resources an S3 or S3 Control request names, read from the generated table on the route it matches. */
private List<String> s3(ResourceArnBuilder from, String method, String sent, String operation, String region,
String partition) {
when(ctx.getMethod()).thenReturn(method);
request(sent);
return from.buildResources("s3", "s3:" + operation, ctx, region, ACCOUNT, partition);
}
@Test
void s3BuildsArnsInTheRequestRegionsPartition() {
when(uriInfo.getPath()).thenReturn("/my-bucket/key.txt");
assertEquals("arn:aws-cn:s3:::my-bucket/key.txt",
builder.build("s3", ctx, "cn-north-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/");
assertEquals("arn:aws-us-gov:s3:::*", builder.build("s3", ctx, "us-gov-west-1", "000000000000"));
private List<String> s3(String method, String sent, String operation) {
return s3(builder, method, sent, operation, "us-east-1", "aws");
}
@Test
void s3BuildsObjectArn() {
when(uriInfo.getPath()).thenReturn("/my-bucket/folder/file.json");
String arn = builder.build("s3", ctx, "us-east-1", "000000000000");
assertEquals("arn:aws:s3:::my-bucket/folder/file.json", arn);
}
/**
* S3VirtualHostFilter rewrites a virtual-hosted bucket-level request (GET /) to
* /bucket/. The resource is still the bucket, so the ARN must carry no trailing
* slash or a policy naming arn:aws:s3:::bucket stops matching and an allowed
* ListBucket is denied for every SDK that defaults to virtual-hosted addressing.
*/
@Test
void s3BuildsBucketArnForVirtualHostedRewrittenPath() {
when(uriInfo.getPath()).thenReturn("/my-bucket/");
String arn = builder.build("s3", ctx, "us-east-1", "000000000000");
assertEquals("arn:aws:s3:::my-bucket", arn);
}
@Test
void s3KeepsTrailingSlashOfAFolderMarkerKey() {
when(uriInfo.getPath()).thenReturn("/my-bucket/folder/");
String arn = builder.build("s3", ctx, "us-east-1", "000000000000");
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 builder reading S3's keys as S3 does, from {@code received}, the path the server received. */
private static ResourceArnBuilder readingS3Keys(String received) {
RequestPathLabels s3Keys = new S3RequestPathLabels(vertxRequestOn(received));
@SuppressWarnings("unchecked")
Instance<RequestPathLabels> labels = mock(Instance.class);
when(labels.isUnsatisfied()).thenReturn(false);
when(labels.iterator()).thenAnswer(invocation -> List.of(s3Keys).iterator());
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, labels);
}
/** A current request whose path is {@code sentPath}, the path the server received. */
@@ -2051,90 +1984,72 @@ class ResourceArnBuilderTest {
return current;
}
// ── S3 Control ─────────────────────────────────────────────────────────────
/** A bucket and an object are named by their route's labels, in the partition of the request's Region. */
@Test
void anS3RequestIsCheckedOnTheBucketOrObjectItsRouteNames() {
assertEquals(List.of("arn:aws:s3:::my-bucket"), s3("PUT", "/my-bucket", "CreateBucket"));
assertEquals(List.of("arn:aws:s3:::my-bucket"), s3("GET", "/my-bucket?list-type=2", "ListObjectsV2"));
assertEquals(List.of("arn:aws:s3:::my-bucket/folder/file.json"),
s3("GET", "/my-bucket/folder/file.json", "GetObject"));
assertEquals(List.of("arn:aws-cn:s3:::my-bucket/key.txt"),
s3(builder, "GET", "/my-bucket/key.txt", "GetObject", "cn-north-1", "aws-cn"));
// ListBuckets acts on no resource type.
assertEquals(List.of("*"), s3("GET", "/", "ListBuckets"));
}
/**
* An S3 Control tagging route names the resource it acts on by its ARN, and that ARN as
* written is what the request is checked against. The data-plane reading of the path, which
* issue #6537 reports, checked s3:GetObject on a bucket named v20180820, so a policy
* allowing the tagging action on the real bucket never matched. The ARN is the caller's own
* naming of the resource, kept as the ARN-carrying requests of other services are: the plain
* general-purpose form and the directory-bucket form the Go SDK and Terraform send alike.
* A key keeps the slashes it is sent with, and so does the ARN the request is checked against, read as S3 reads
* it: {@code PUT /bucket//email.txt} stores the key {@code /email.txt}; read from the router's collapsed path it
* would be checked on {@code bucket/email.txt}, so a grant on that object would cover this one.
*/
@Test
void s3ControlTaggingIsCheckedAgainstTheArnTheRouteNames() {
for (String action : List.of("s3:ListTagsForResource", "s3:TagResource", "s3:UntagResource")) {
when(uriInfo.getPath()).thenReturn("/v20180820/tags/arn:aws:s3:::repro-bucket");
void anS3KeyKeepsTheSlashesItWasSentWith() {
assertEquals(List.of("arn:aws:s3:::my-bucket//email.txt"),
s3(readingS3Keys("/my-bucket//email.txt"), "PUT", "/my-bucket//email.txt", "PutObject", "us-east-1",
"aws"));
assertEquals(List.of("arn:aws:s3:::my-bucket/a//b.txt"),
s3(readingS3Keys("/my-bucket/a//b.txt"), "GET", "/my-bucket/a//b.txt", "GetObject", "us-east-1",
"aws"));
assertEquals(List.of("arn:aws:s3:::my-bucket/folder/"),
s3(readingS3Keys("/my-bucket/folder/"), "PUT", "/my-bucket/folder/", "PutObject", "us-east-1", "aws"));
// Virtual-hosted: S3VirtualHostFilter put the bucket into the path, and the server received the key alone.
assertEquals(List.of("arn:aws:s3:::my-bucket//email.txt"),
s3(readingS3Keys("//email.txt"), "GET", "/my-bucket//email.txt", "GetObject", "us-east-1", "aws"));
}
/**
* An S3 Control tagging route names the resource it acts on by its ARN, and that ARN as written, percent-encoded as
* the Go SDK sends it or not, is what the request is checked against, never a bucket named v20180820 (issue
* #6537). One naming no ARN stays on the wildcard, under which the handler refuses it.
*/
@Test
void anS3ControlTaggingRouteIsCheckedOnTheArnItNames() {
for (String[] call : List.of(new String[] {"GET", "ListTagsForResource"}, new String[] {"POST", "TagResource"},
new String[] {"DELETE", "UntagResource"})) {
assertEquals(List.of("arn:aws:s3:::repro-bucket"),
builder.buildResources("s3", action, ctx, "us-east-1", ACCOUNT, "aws"), action);
when(uriInfo.getPath())
.thenReturn("/v20180820/tags/arn:aws:s3:us-east-1:000000000000:bucket/repro-bucket");
assertEquals(List.of("arn:aws:s3:us-east-1:000000000000:bucket/repro-bucket"),
builder.buildResources("s3", action, ctx, "us-east-1", ACCOUNT, "aws"), action);
s3(call[0], "/v20180820/tags/arn:aws:s3:::repro-bucket", call[1]), call[1]);
assertEquals(List.of("arn:aws:s3:::repro-bucket"),
s3(call[0], "/v20180820/tags/arn%3Aaws%3As3%3A%3A%3Arepro-bucket", call[1]), call[1]);
}
assertEquals(List.of("*"), s3("GET", "/v20180820/tags/not-an-arn", "ListTagsForResource"));
}
/**
* 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.
* AWS gives s3:ListAccessPoints and the account-level Block Public Access actions no resource type, so a request
* of them is checked on the wildcard alone, as other namespaces' no-resource actions are.
*/
@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"));
void anS3ControlAccountRouteIsCheckedOnTheWildcardAlone() {
assertEquals(List.of("*"), s3("GET", "/v20180820/accesspoint", "ListAccessPoints"));
assertEquals(List.of("*"), s3("GET", "/v20180820/configuration/publicAccessBlock", "GetPublicAccessBlock"));
assertEquals(List.of("*"), s3("PUT", "/v20180820/configuration/publicAccessBlock", "PutPublicAccessBlock"));
}
/** A tagging route naming no ARN stays on the wildcard, under which the handler refuses it. */
/** A data-plane request into a bucket named v20180820 keeps its own bucket and object. */
@Test
void s3ControlTaggingNamingNoArnLeavesTheWildcard() {
when(uriInfo.getPath()).thenReturn("/v20180820/tags/not-an-arn");
assertEquals(List.of("*"),
builder.buildResources("s3", "s3:ListTagsForResource", ctx, "us-east-1", ACCOUNT, "aws"));
}
/**
* AWS gives s3:ListAccessPoints and the account-level Block Public Access actions no
* resource type, so the request is checked against the wildcard alone, as the no-resource
* actions of other namespaces are (the KMS list operations): a bucket-scoped statement,
* {@code arn:<partition>:s3:::*} or any other ARN, grants them nothing, and a NotResource
* naming any bucket denies the call.
*/
@Test
void s3ControlAccountRoutesAreCheckedAgainstTheWildcardAlone() {
when(uriInfo.getPath()).thenReturn("/v20180820/accesspoint");
assertEquals(List.of("*"),
builder.buildResources("s3", "s3:ListAccessPoints", ctx, "us-east-1", ACCOUNT, "aws"));
when(uriInfo.getPath()).thenReturn("/v20180820/configuration/publicAccessBlock");
assertEquals(List.of("*"),
builder.buildResources("s3", "s3:PutAccountPublicAccessBlock", ctx, "us-east-1", ACCOUNT, "aws"));
assertEquals(List.of("*"),
builder.buildResources("s3", "s3:GetAccountPublicAccessBlock", ctx, "us-east-1", ACCOUNT, "aws"));
assertEquals(List.of("*"),
builder.buildResources("s3", "s3:PutAccountPublicAccessBlock", ctx, "us-gov-west-1", ACCOUNT,
"aws-us-gov"));
}
/**
* 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 slashes of its key included.
*/
@Test
void aDataPlaneOperationUnderTheS3ControlPrefixKeepsItsOwnArn() {
when(uriInfo.getPath()).thenReturn("/v20180820/tags/key.txt");
assertEquals(List.of("arn:aws:s3:::v20180820/tags/key.txt"),
builder.buildResources("s3", "s3:PutObject", ctx, "us-east-1", ACCOUNT, "aws"));
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"));
void aDataPlaneRequestUnderTheS3ControlPrefixKeepsItsOwnBucketAndObject() {
assertEquals(List.of("arn:aws:s3:::v20180820/tags/key.txt"), s3("PUT", "/v20180820/tags/key.txt", "PutObject"));
assertEquals(List.of("arn:aws:s3:::v20180820"), s3("GET", "/v20180820", "ListObjects"));
}
// ── The vendored table of request resources ─────────────────────────────────
@@ -156,17 +156,57 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
f.select("a/rows.csv").statusCode(200);
}
/**
* SelectObjectContent is POST ?select&select-type=2, as botocore routes it: a request naming ?select alone is the
* object's other POST route, checked as s3:PutObject, and S3 runs no query on it, so a caller allowed to write but
* not to read gets none of the object.
*/
@Test
void selectingFromAVersionNeedsGetObjectVersion() {
// S3Controller selects from the version named, so it is checked as reading that version.
Fixture f = new Fixture("select-version", true);
String versionId = f.seedVersion("a/rows.csv");
void aSelectWithoutItsTypeReadsNothing() {
Fixture f = new Fixture("select-untyped", false);
f.seed("a/rows.csv");
f.policy(f.allow("s3:PutObject"));
ValidatableResponse response = f.user().queryParam("select", "")
.contentType("application/xml")
.body("""
<SelectObjectContentRequest>
<Expression>SELECT * FROM S3Object</Expression>
<ExpressionType>SQL</ExpressionType>
<InputSerialization><CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV></InputSerialization>
<OutputSerialization><CSV/></OutputSerialization>
</SelectObjectContentRequest>
""")
.when().post(f.path("a/rows.csv")).then();
response.statusCode(not(200)).body(not(containsString("1,one")));
}
/**
* Botocore gives SelectObjectContent's request no version, and the S3 user guide requires s3:GetObject for it alone,
* so it reads the current version whatever versionId it names: a caller allowed s3:GetObject reads no older one.
*/
@Test
void aSelectReadsTheCurrentVersionWhateverItNames() {
Fixture f = new Fixture("select-current", true);
String old = f.admin().body("id,name\n1,old\n").when().put(f.path("a/rows.csv"))
.then().statusCode(200).extract().header("x-amz-version-id");
f.admin().body("id,name\n2,new\n").when().put(f.path("a/rows.csv")).then().statusCode(200);
f.policy(f.allow("s3:GetObject"));
denied(f.select("a/rows.csv", versionId), "s3:GetObjectVersion");
f.select("a/rows.csv", old).statusCode(200)
.body(containsString("2,new")).body(not(containsString("1,old")));
}
f.policy(f.allow("s3:GetObjectVersion"));
f.select("a/rows.csv", versionId).statusCode(200);
/**
* A request naming two of a bucket's sub-resources is taken alike by both their routes, and runs as whichever S3's
* handler picks, so it is refused even for a caller allowed both actions.
*/
@Test
void aRequestNamingTwoSubresourcesIsRefused() {
Fixture f = new Fixture("two-subresources", false);
f.policy(f.allowOnBucket("s3:PutBucketCORS", "s3:PutBucketPolicy"));
f.user().queryParam("cors", "").queryParam("policy", "").body("{}")
.when().put("/" + f.bucket).then().statusCode(403).body(containsString("AccessDenied"));
}
@Test
@@ -496,22 +536,6 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
.when().put(f.path("a/created")).then().statusCode(200);
}
@Test
void aRequestNamingTwoSubresourcesIsCheckedAsTheOneThatRuns() {
// S3 serves ?tagging before ?acl, so this request returns the object's tags.
Fixture f = new Fixture("order", false);
f.seed("a/tagged");
f.policy(f.allow("s3:GetObjectAcl"));
denied(f.user().queryParam("acl", "").queryParam("tagging", "").when().get(f.path("a/tagged")).then(),
"s3:GetObjectTagging");
f.policy(f.allow("s3:GetObjectTagging"));
f.user().queryParam("acl", "").queryParam("tagging", "").when().get(f.path("a/tagged")).then()
.statusCode(200)
.body(containsString("<Tagging"));
}
@Test
void readingAVersionNeedsGetObjectVersion() {
// The API reference: with a versionId, s3:GetObjectVersion is needed and s3:GetObject is not.
@@ -127,7 +127,8 @@ class S3AnnotationsIntegrationTest {
@Test
@Order(7)
void headObjectAnnotationMatchesGetStatus() {
void aHeadNamingAnAnnotationIsAHeadOfTheObject() {
// Botocore models no HEAD of an annotation, so the request is HeadObject, whichever annotation it names.
given()
.when()
.head("/" + BUCKET + "/docs/report.txt?annotation&annotationName=labels")
@@ -138,7 +139,7 @@ class S3AnnotationsIntegrationTest {
.when()
.head("/" + BUCKET + "/docs/report.txt?annotation&annotationName=missing")
.then()
.statusCode(404);
.statusCode(200);
}
@Test
@@ -211,13 +212,14 @@ class S3AnnotationsIntegrationTest {
@Test
@Order(13)
void emptyAnnotationNameDispatchesToList() {
void anEmptyAnnotationNameIsRefusedAsTheGetItNames() {
// A request naming annotationName is GetObjectAnnotation, as botocore reads it, so an empty one is refused.
given()
.when()
.get("/" + BUCKET + "/docs/report.txt?annotation&annotationName=")
.then()
.statusCode(200)
.body(containsString("<ListObjectAnnotationsOutput"));
.statusCode(400)
.body(containsString("<Code>InvalidAnnotationName</Code>"));
}
// ========== Versioned bucket behavior ==========
@@ -73,8 +73,10 @@ class S3ControlIamEnforcementIntegrationTest {
{"Effect":"Allow","Action":"s3:ListTagsForResource","Resource":"arn:aws:s3:::%1$s"}]}"""
.formatted(bucket));
// The Go SDK sends the ARN's colons percent-encoded once: RestAssured must not encode the % again.
String encodedArn = "arn%3Aaws%3As3%3A%3A%3A" + bucket;
given()
.urlEncodingEnabled(false)
.header("Authorization", auth(user, "s3"))
.header("x-amz-account-id", ACCOUNT)
.when()
@@ -163,35 +165,63 @@ class S3ControlIamEnforcementIntegrationTest {
}
/**
* The regional ARN form, the one the tagging operation's own request pattern and the AWS
* CLI examples use, is the request's resource as written: a policy naming it authorizes the
* read, because the ARN is not rewritten into the global form a data-plane path mints.
* The ARN is decoded once, as the Go SDK encodes it once and IAM reads the route: one encoded twice names no ARN
* after that, so the handler refuses it rather than act on a bucket whose policy denies the call.
*/
@Test
void listTagsForResourceIsAuthorizedByAPolicyOnTheRegionalArnForm() {
String bucket = bucketWithTags("control-regional");
void anArnEncodedTwiceNamesNoBucket() {
String bucket = bucketWithTags("control-double-encoded");
given()
.header("Authorization", auth("test", "s3"))
.contentType("application/json")
.body("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Principal":"*","Action":"s3:ListTagsForResource",
"Resource":"arn:aws:s3:::%1$s"}]}"""
.formatted(bucket))
.when()
.put("/" + bucket + "?policy")
.then()
.statusCode(200);
String user = userWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:ListTagsForResource",
"Resource":"arn:aws:s3:us-east-1:000000000000:bucket/%1$s"}]}"""
.formatted(bucket));
{"Effect":"Allow","Action":"s3:ListTagsForResource","Resource":"*"}]}""");
given()
.urlEncodingEnabled(false)
.header("Authorization", auth(user, "s3"))
.header("x-amz-account-id", ACCOUNT)
.when()
.get("/v20180820/tags/arn:aws:s3:us-east-1:000000000000:bucket/" + bucket)
.get("/v20180820/tags/arn%253Aaws%253As3%253A%253A%253A" + bucket)
.then()
.statusCode(200)
.body(containsString("<ListTagsForResourceResult"))
.body(containsString("<Key>Env</Key>"));
.statusCode(400)
.body(containsString("<Code>InvalidRequest</Code>"))
.body(not(containsString("<Key>Env</Key>")));
}
/**
* A bucket policy is resolved from the bucket the tagged ARN names, not from the bucket the
* data-plane reading of the ARN's resource part would find: the regional form's resource is
* {@code bucket/<name>}, and the real bucket's policy denying the control action must deny a
* caller whose identity policy allows it.
* A request matching an S3 Control route Floci does not serve reaches no handler: the router answers every path
* under {@code /v20180820} that S3ControlController does not serve with 404, so none runs as an object of a bucket
* named v20180820, whatever IAM checks it as.
*/
@Test
void anS3ControlRouteFlociDoesNotServeRunsNothing() {
for (String[] call : new String[][] {{"PUT", "/v20180820/bucket/foo"}, {"DELETE", "/v20180820/bucket/foo"},
{"GET", "/v20180820/accesspoint/foo"}, {"PUT", "/v20180820"}}) {
given()
.header("Authorization", auth("test", "s3"))
.header("x-amz-account-id", ACCOUNT)
.body("x")
.when()
.request(call[0], call[1])
.then()
.statusCode(404);
}
}
/**
* A bucket policy is resolved from the bucket the tagged ARN names: the bucket's policy denying
* the control action denies a caller whose identity policy allows it.
*/
@Test
void aBucketPolicyOnTheTaggedBucketDeniesTheControlRead() {
@@ -202,7 +232,7 @@ class S3ControlIamEnforcementIntegrationTest {
.body("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Principal":"*","Action":"s3:ListTagsForResource",
"Resource":"arn:aws:s3:us-east-1:000000000000:bucket/%1$s"}]}"""
"Resource":"arn:aws:s3:::%1$s"}]}"""
.formatted(bucket))
.when()
.put("/" + bucket + "?policy")
@@ -217,7 +247,7 @@ class S3ControlIamEnforcementIntegrationTest {
.header("Authorization", auth(user, "s3"))
.header("x-amz-account-id", ACCOUNT)
.when()
.get("/v20180820/tags/arn:aws:s3:us-east-1:000000000000:bucket/" + bucket)
.get("/v20180820/tags/arn:aws:s3:::" + bucket)
.then()
.statusCode(403)
.body(containsString("is not authorized to perform: s3:ListTagsForResource"));
@@ -391,91 +421,6 @@ class S3ControlIamEnforcementIntegrationTest {
.body(containsString("is not authorized to perform: s3:ListAccessPoints"));
}
/**
* The regional form names the account whose bucket it acts on, so a grant on
* {@code arn:aws:s3:us-east-1:222222222222:bucket/<name>} authorizes a caller in another
* account, whom the bucket's own policy admits, to read and change the tags of
* 222222222222's bucket, and never of its own same-named one, which the plain bucket name
* would otherwise resolve to. The bucket's policy is found in the account the ARN names,
* the same bucket the read and the write act on.
*/
@Test
void aRegionalArnActsOnTheBucketOfTheAccountItNames() {
String bucket = "control-cross-account-" + UUID.randomUUID().toString().substring(0, 8);
String regionalArn = "arn:aws:s3:us-east-1:" + OTHER_ACCOUNT + ":bucket/" + bucket;
cleanup.register(() -> EnforcementFixtures.removeBucket(baseUri.getPort(),
auth(OTHER_ACCOUNT, "s3"), bucket));
cleanup.register(() -> EnforcementFixtures.removeBucket(baseUri.getPort(),
auth("test", "s3"), bucket));
createBucketWithTag(bucket, "Team", "other", auth(OTHER_ACCOUNT, "s3"));
createBucketWithTag(bucket, "Team", "own", auth("test", "s3"));
String userName = "s3-control-cross-" + UUID.randomUUID().toString().substring(0, 8);
EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser(cleanup,
baseUri.getPort(), auth("test", "iam"), userName);
String userArn = "arn:aws:iam::" + ACCOUNT + ":user/" + userName;
String identityPolicy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:ListTagsForResource","s3:TagResource"],
"Resource":"%1$s"}]}"""
.formatted(regionalArn);
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth("test", "iam"), userName, "p",
identityPolicy);
String user = credentials.accessKeyId();
given()
.header("Authorization", auth(OTHER_ACCOUNT, "s3"))
.contentType("application/json")
.body("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"%1$s"},
"Action":["s3:ListTagsForResource","s3:TagResource"],
"Resource":"%2$s"}]}"""
.formatted(userArn, regionalArn))
.when()
.put("/" + bucket + "?policy")
.then()
.statusCode(200);
given()
.header("Authorization", auth(user, "s3"))
.header("x-amz-account-id", ACCOUNT)
.when()
.get("/v20180820/tags/" + regionalArn)
.then()
.statusCode(200)
.body(containsString("<Key>Team</Key>"))
.body(containsString("<Value>other</Value>"));
given()
.header("Authorization", auth(user, "s3"))
.header("x-amz-account-id", ACCOUNT)
.contentType("application/xml")
.body("<Tagging><Tags><Tag><Key>Owner</Key><Value>team</Value></Tag></Tags></Tagging>")
.when()
.post("/v20180820/tags/" + regionalArn)
.then()
.statusCode(204);
given()
.header("Authorization", auth(OTHER_ACCOUNT, "s3"))
.when()
.get("/" + bucket + "?tagging")
.then()
.statusCode(200)
.body(containsString("<Key>Owner</Key>"))
.body(not(containsString("<Value>own</Value>")));
given()
.header("Authorization", auth("test", "s3"))
.when()
.get("/" + bucket + "?tagging")
.then()
.statusCode(200)
.body(containsString("<Value>own</Value>"))
.body(not(containsString("<Key>Owner</Key>")));
}
/**
* A tagging ARN naming a bucket its account does not own answers {@code NoSuchBucket}, not
* the tags of the caller's same-named bucket: the handler acts on the bucket the ARN names
@@ -37,7 +37,8 @@ class S3ControlUrlEncodedArnIntegrationTest {
private static final String DECODED_ARN =
"arn:aws:s3:" + REGION + ":" + ACCOUNT + ":bucket/" + BUCKET;
// What the Go SDK actually puts on the wire: colons AND slashes URL-encoded.
// What the Go SDK actually puts on the wire: colons AND slashes URL-encoded, once, which RestAssured must not
// encode again.
private static final String ENCODED_ARN =
"arn%3Aaws%3As3%3A" + REGION + "%3A" + ACCOUNT + "%3Abucket%2F" + BUCKET;
@@ -82,6 +83,7 @@ class S3ControlUrlEncodedArnIntegrationTest {
@DisplayName("ListTagsForResource accepts URL-encoded ARN from Go AWS SDK v2 (#435)")
void listTagsForResourceWithUrlEncodedArn() {
given()
.urlEncodingEnabled(false)
.header("x-amz-account-id", ACCOUNT)
.when()
.get("/v20180820/tags/" + ENCODED_ARN)
@@ -119,6 +121,7 @@ class S3ControlUrlEncodedArnIntegrationTest {
"</Tags></Tagging>";
given()
.urlEncodingEnabled(false)
.header("x-amz-account-id", ACCOUNT)
.contentType("application/xml")
.body(body)
@@ -128,6 +131,7 @@ class S3ControlUrlEncodedArnIntegrationTest {
.statusCode(204);
String response = given()
.urlEncodingEnabled(false)
.header("x-amz-account-id", ACCOUNT)
.when()
.get("/v20180820/tags/" + ENCODED_ARN)
@@ -144,6 +148,7 @@ class S3ControlUrlEncodedArnIntegrationTest {
@DisplayName("UntagResource accepts URL-encoded ARN from Go AWS SDK v2 (#435)")
void untagResourceWithUrlEncodedArn() {
given()
.urlEncodingEnabled(false)
.header("x-amz-account-id", ACCOUNT)
.when()
.delete("/v20180820/tags/" + ENCODED_ARN + "?tagKeys=CostCenter")
@@ -151,6 +156,7 @@ class S3ControlUrlEncodedArnIntegrationTest {
.statusCode(204);
given()
.urlEncodingEnabled(false)
.header("x-amz-account-id", ACCOUNT)
.when()
.get("/v20180820/tags/" + ENCODED_ARN)
@@ -177,7 +183,7 @@ class S3ControlUrlEncodedArnIntegrationTest {
@Order(7)
@DisplayName("Malformed percent-encoding returns S3 Control ErrorResponse wrapper (#435, #557)")
void malformedPercentEncodingReturnsXmlError() {
// %ZZ is not a valid percent-encoding sequence; URLDecoder throws IAE.
// %ZZ is not a valid percent-encoding sequence, so what the router decodes names no ARN.
Response response = given()
.header("x-amz-account-id", ACCOUNT)
.when()
@@ -209,6 +215,7 @@ class S3ControlUrlEncodedArnIntegrationTest {
// Go SDK v2 percent-encodes colons: arn%3Aaws%3As3%3A%3A%3A<bucket>
String encodedPlainArn = "arn%3Aaws%3As3%3A%3A%3A" + BUCKET;
given()
.urlEncodingEnabled(false)
.header("x-amz-account-id", ACCOUNT)
.when()
.get("/v20180820/tags/" + encodedPlainArn)