Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(iam): authorize a Smithy RPC v2 call as the operation its route runs (#5620)

Priamo Germosen29ead624f816
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 3aa607808e..5f905c9d7f 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -1114,8 +1114,13 @@ a Query `Action` field on it does not change the action it is checked as, and it
still percent-encoded, as the router matches it, so an encoded `/` inside a parameter cannot make
the route's rule miss.
-A request that names its operation, in a Query `Action` or an `X-Amz-Target` header, is authorized
-as the action AWS checks for that operation, which is usually the operation's own name. Where AWS
+A request that names its operation, in a Query `Action`, an `X-Amz-Target` header or a Smithy RPC v2
+path (`/service/<service>/operation/<operation>`), is authorized as the action AWS checks for that
+operation, which is usually the operation's own name. An RPC v2 call is checked as the service and
+operation in its path, the ones Floci runs, whatever its `smithy-protocol` header says, and an
+`X-Amz-Target` header on it does not change the action it is checked as. A CBOR body, on that path
+or on the `x-amz-cbor-1.1` one, names its resource and condition keys (a queue URL, a table name,
+`dynamodb:LeadingKeys`) the way a JSON body does, and they are read from it the same way. Where AWS
authorizes an operation as a single action of another name, Floci does the same: `SendMessageBatch`
is checked as `sqs:SendMessage` and `PublishBatch` as `sns:Publish`, so a policy granting the
single-message action covers the batch call, and one naming the batch operation, which is not an
@@ -1481,7 +1486,8 @@ lazily-resolved `ScpProvider` exists to avoid.
With enforcement on, a request carrying no `Authorization` header is refused with
`403 MissingAuthenticationToken` when its wire shape names a management operation: a JSON, CBOR or
-Query request, identified by `X-Amz-Target`, an rpcv2 path or an `Action` parameter.
+Query request, identified by `X-Amz-Target`, an rpcv2 path or an `Action` parameter. A call routed
+to the rpcv2 endpoint is one whatever its `smithy-protocol` header says.
Two carve-outs, both deliberate.
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java
index 1c8ec02466..0396317742 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java
@@ -48,6 +48,10 @@ public class AwsJsonCborController {
private static final String GENERIC_CBOR_MEDIA_TYPE = "application/cbor";
private static final String AWS_CBOR_1_1_MEDIA_TYPE = "application/x-amz-cbor-1.1";
+ /** The RPC v2 path parameters {@link IamEnforcementFilter} authorizes, as this endpoint dispatches them. */
+ static final String RPC_V2_SERVICE_PARAMETER = "serviceId";
+ static final String RPC_V2_OPERATION_PARAMETER = "operation";
+
private final ObjectMapper objectMapper;
private final ResolvedServiceCatalog catalog;
private final RegionResolver regionResolver;
@@ -289,8 +293,8 @@ public class AwsJsonCborController {
@Consumes({GENERIC_CBOR_MEDIA_TYPE, AWS_CBOR_1_1_MEDIA_TYPE})
@Produces({GENERIC_CBOR_MEDIA_TYPE, AWS_CBOR_1_1_MEDIA_TYPE})
public Response handleSmithyRpcV2Cbor(
- @PathParam("serviceId") String serviceId,
- @PathParam("operation") String operation,
+ @PathParam(RPC_V2_SERVICE_PARAMETER) String serviceId,
+ @PathParam(RPC_V2_OPERATION_PARAMETER) String operation,
@Context HttpHeaders httpHeaders,
byte[] body) {
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
index 479f0f6d9e..e1711dc4a6 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
@@ -288,6 +288,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if (!config.services().iam().enforcementEnabled()) {
return;
}
+ ProtocolClaim rpcV2Route = rpcV2RouteClaim(ctx);
+ if (rpcV2Route != null) {
+ // The claim filter runs before routing and can leave a call this endpoint serves
+ // unclaimed, as an unrecognised smithy-protocol value does. Every check below that reads
+ // the claim has to see the call that runs: unclaimed, an unsigned one would pass as REST.
+ ctx.setProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY, rpcV2Route);
+ }
String auth = ctx.getHeaderString("Authorization");
boolean emptyHeader = auth != null && auth.isBlank();
@@ -547,8 +554,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
/**
* Resolves both the IAM namespace and action from the service that will actually handle the
- * request. Query traffic shares the dispatch resolver with {@link AwsQueryController}; REST
- * traffic uses the JAX-RS resource class that won route matching.
+ * request. Query traffic shares the dispatch resolver with {@link AwsQueryController}; an RPC v2
+ * call takes the service and operation its route dispatches; REST traffic uses the JAX-RS
+ * resource class that won route matching.
*/
private ResolvedAuthorization resolveAuthorization(String auth, String claimedScope,
ContainerRequestContext ctx) {
@@ -567,6 +575,18 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
IamAuthorizedActions.actionFor(servingScope, queryAction));
}
+ // Read from the route rather than the claim: a path the claim filter takes for RPC v2 can
+ // reach another route, and an X-Amz-Target header names an operation this endpoint ignores.
+ ProtocolClaim rpcV2Route = rpcV2RouteClaim(ctx);
+ if (rpcV2Route != null) {
+ if (rpcV2Route.service() == null) {
+ return new ResolvedAuthorization(claimedScope, null); // no service: the endpoint answers 404
+ }
+ String servingScope = iamServiceScope(rpcV2Route.service(), claimedScope);
+ return new ResolvedAuthorization(servingScope,
+ IamAuthorizedActions.actionFor(servingScope, rpcV2Route.operation()));
+ }
+
ResolvedAuthorization routeAuthorization = restRouteAuthorization(ctx);
if (routeAuthorization != null) {
return routeAuthorization;
@@ -580,6 +600,25 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
: actionRegistry.resolve(servingScope, ctx));
}
+ /**
+ * The claim of a call JAX-RS routed to the Smithy RPC v2 endpoint, made from the service and
+ * operation in the route's path parameters, which are what that endpoint dispatches. Null for
+ * any other request.
+ */
+ private ProtocolClaim rpcV2RouteClaim(ContainerRequestContext ctx) {
+ if (resourceInfo == null || !AwsJsonCborController.class.equals(resourceInfo.getResourceClass())) {
+ return null;
+ }
+ MultivaluedMap<String, String> parameters = ctx.getUriInfo().getPathParameters();
+ String serviceId = parameters.getFirst(AwsJsonCborController.RPC_V2_SERVICE_PARAMETER);
+ String operation = parameters.getFirst(AwsJsonCborController.RPC_V2_OPERATION_PARAMETER);
+ if (serviceId == null || operation == null) {
+ return null;
+ }
+ return new ProtocolClaim(WireProtocol.RPCV2_CBOR, catalog.byCborSdkServiceId(serviceId).orElse(null),
+ operation, null);
+ }
+
/**
* The action a REST request's matched route maps to, read from the route alone. Null for any
* other request, and for a route no rule maps.
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
index 5e344cf539..0a42832371 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
@@ -14,6 +15,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.core.MediaType;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -44,6 +46,9 @@ public class ResourceArnBuilder {
/** What a service-linked role deletion task identifier starts with; see its resolver. */
private static final String DELETION_TASK_PREFIX = "task" + ServiceLinkedRoles.PATH;
+ /** Reads the CBOR bodies the RPC v2 and {@code x-amz-cbor-1.1} paths carry. */
+ private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
+
private final ObjectMapper objectMapper;
/**
* Looked up lazily through a provider: this builder is constructed by the enforcement filter,
@@ -929,7 +934,7 @@ public class ResourceArnBuilder {
return null;
}
try {
- JsonNode node = objectMapper.readTree(body);
+ JsonNode node = (isCbor(ctx.getMediaType()) ? CBOR_MAPPER : objectMapper).readTree(body);
ctx.setProperty("floci.bufferedJsonBody", node);
return node;
} catch (Exception e) {
@@ -937,6 +942,18 @@ public class ResourceArnBuilder {
}
}
+ /**
+ * A CBOR body, which names its resources in the same members a JSON body does. Both CBOR
+ * content types arrive as {@code application/cbor}: {@code AwsCborContentTypeFilter} rewrites
+ * {@code x-amz-cbor-1.1} before routing.
+ */
+ private static boolean isCbor(MediaType mediaType) {
+ return mediaType != null
+ && "application".equalsIgnoreCase(mediaType.getType())
+ && ("cbor".equalsIgnoreCase(mediaType.getSubtype())
+ || "x-amz-cbor-1.1".equalsIgnoreCase(mediaType.getSubtype()));
+ }
+
private String extractSegmentAfter(String path, String segment) {
String marker = "/" + segment + "/";
int idx = path.indexOf(marker);
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/RpcV2CborEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/RpcV2CborEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..d8b68dee9d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/RpcV2CborEnforcementIntegrationTest.java
@@ -0,0 +1,355 @@
+package io.github.hectorvent.floci.services.iam;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
+import io.github.hectorvent.floci.testing.EnforcementFixtures;
+import io.github.hectorvent.floci.testing.IamEnforcementProfile;
+import io.github.hectorvent.floci.testing.PartitionCleanup;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.common.http.TestHTTPResource;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.List;
+import java.util.UUID;
+
+import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A Smithy RPC v2 CBOR call names its operation in the path, not in a Query {@code Action} or an
+ * {@code X-Amz-Target} header, and is checked as that operation like any other call: an identity
+ * policy has to grant it, a deny refuses it, and an operation AWS authorizes as another action is
+ * checked as that action. The resource and condition keys a CBOR body names count as a JSON body's
+ * do.
+ */
+@QuarkusTest
+@TestProfile(IamEnforcementProfile.class)
+class RpcV2CborEnforcementIntegrationTest {
+
+ private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
+ private static final String ACCOUNT_ID = "000000000000";
+
+ @TestHTTPResource("/")
+ static URI baseUri;
+
+ @RegisterExtension
+ final PartitionCleanup cleanup = new PartitionCleanup();
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void anRpcV2CallIsGrantedByThePermissionItsOperationNeeds() {
+ String accessKeyId = userWithPolicy(allow("sqs:ListQueues"));
+
+ sqsRpcV2(accessKeyId, "sqs", "ListQueues", "{}")
+ .statusCode(200);
+ }
+
+ @Test
+ void anRpcV2CallIsRefusedWithoutThePermissionItsOperationNeeds() throws IOException {
+ String accessKeyId = userWithPolicy(allow("sns:ListTopics"));
+
+ assertAccessDenied(sqsRpcV2(accessKeyId, "sqs", "ListQueues", "{}"), "sqs:ListQueues");
+ }
+
+ @Test
+ void anRpcV2CallIsRefusedByAnExplicitDeny() throws IOException {
+ String accessKeyId = userWithPolicy("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"sqs:*","Resource":"*"},
+ {"Effect":"Deny","Action":"sqs:ListQueues","Resource":"*"}
+ ]}""");
+
+ assertAccessDenied(sqsRpcV2(accessKeyId, "sqs", "ListQueues", "{}"), "sqs:ListQueues");
+ }
+
+ @Test
+ void anRpcV2CallIsCheckedAgainstTheServiceThatServesItNotItsSigningScope() throws IOException {
+ // Signed for SNS, but the path sends it to SQS, which is what runs it.
+ String accessKeyId = userWithPolicy(allow("sns:*"));
+
+ assertAccessDenied(sqsRpcV2(accessKeyId, "sns", "ListQueues", "{}"), "sqs:ListQueues");
+ }
+
+ @Test
+ void anRpcV2CallIsCheckedAsThePathOperationNotAnXAmzTargetItCarries() throws IOException {
+ String queueUrl = createQueue();
+ String accessKeyId = userWithPolicy(allow("sqs:ListQueues"));
+
+ assertAccessDenied(sqsRpcV2(signed(accessKeyId, "sqs").header("smithy-protocol", "rpc-v2-cbor")
+ .header("X-Amz-Target", "AmazonSQS.ListQueues"),
+ "DeleteQueue", """
+ {"QueueUrl": "%s"}
+ """.formatted(queueUrl)),
+ "sqs:DeleteQueue");
+ }
+
+ @Test
+ void anRpcV2CallWithAnUnrecognisedProtocolHeaderIsStillChecked() throws IOException {
+ // The claim filter leaves this call unclaimed, and the endpoint serves it all the same.
+ String accessKeyId = userWithPolicy(allow("sns:ListTopics"));
+
+ assertAccessDenied(sqsRpcV2(signed(accessKeyId, "sqs").header("smithy-protocol", "unrecognised"),
+ "ListQueues", "{}"), "sqs:ListQueues");
+ }
+
+ @Test
+ void anUnsignedRpcV2CallWithAnUnrecognisedProtocolHeaderIsRefused() throws IOException {
+ byte[] body = sqsRpcV2(given().header("smithy-protocol", "unrecognised"), "ListQueues", "{}")
+ .statusCode(403)
+ .extract().asByteArray();
+
+ assertEquals("MissingAuthenticationTokenException", CBOR_MAPPER.readTree(body).path("__type").asText());
+ }
+
+ @Test
+ void anRpcV2BatchSendIsGrantedBySendMessage() {
+ String queueUrl = createQueue();
+ String accessKeyId = userWithPolicy(allow("sqs:SendMessage"));
+
+ sqsRpcV2(accessKeyId, "sqs", "SendMessageBatch", sendBatch(queueUrl))
+ .statusCode(200);
+ }
+
+ @Test
+ void anRpcV2PolicyNamingTheBatchOperationGrantsNothing() throws IOException {
+ String queueUrl = createQueue();
+ String accessKeyId = userWithPolicy(allow("sqs:SendMessageBatch"));
+
+ assertAccessDenied(sqsRpcV2(accessKeyId, "sqs", "SendMessageBatch", sendBatch(queueUrl)),
+ "sqs:SendMessage");
+ }
+
+ @Test
+ void anRpcV2CallIsCheckedAgainstTheQueueItsBodyNames() throws IOException {
+ String allowed = createQueue();
+ String other = createQueue();
+ String accessKeyId = userWithPolicy("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"sqs:SendMessage","Resource":"%s"}
+ ]}""".formatted(queueArn(allowed)));
+
+ sqsRpcV2(accessKeyId, "sqs", "SendMessage", sendMessage(allowed))
+ .statusCode(200);
+ assertAccessDenied(sqsRpcV2(accessKeyId, "sqs", "SendMessage", sendMessage(other)), "sqs:SendMessage");
+ }
+
+ @Test
+ void anRpcV2DenyOnOneQueueHoldsAlongsideABroadAllow() throws IOException {
+ String queueUrl = createQueue();
+ String accessKeyId = userWithPolicy("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"sqs:*","Resource":"*"},
+ {"Effect":"Deny","Action":"sqs:DeleteQueue","Resource":"%s"}
+ ]}""".formatted(queueArn(queueUrl)));
+
+ assertAccessDenied(sqsRpcV2(accessKeyId, "sqs", "DeleteQueue", """
+ {"QueueUrl": "%s"}
+ """.formatted(queueUrl)), "sqs:DeleteQueue");
+ }
+
+ @Test
+ void anRpcV2GetItemIsCheckedAgainstTheLeadingKeyItsBodyNames() throws IOException {
+ String table = createTable();
+ for (String id : List.of("mine", "theirs")) {
+ dynamoDbAsRoot("PutItem", """
+ {"TableName": "%s", "Item": {"id": {"S": "%s"}}}
+ """.formatted(table, id));
+ }
+ String accessKeyId = userWithPolicy("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
+ "Condition":{"ForAllValues:StringEquals":{"dynamodb:LeadingKeys":["mine"]}}}
+ ]}""");
+
+ rpcV2(signed(accessKeyId, "dynamodb").header("smithy-protocol", "rpc-v2-cbor"),
+ "DynamoDB_20120810", "GetItem", getItem(table, "mine"))
+ .statusCode(200);
+ assertAccessDenied(rpcV2(signed(accessKeyId, "dynamodb").header("smithy-protocol", "rpc-v2-cbor"),
+ "DynamoDB_20120810", "GetItem", getItem(table, "theirs")), "dynamodb:GetItem");
+ }
+
+ @Test
+ void aTargetedCborCallIsCheckedAgainstTheStreamItsBodyNames() throws IOException {
+ // The older CBOR shape, an x-amz-cbor-1.1 body with X-Amz-Target at the root, has the same
+ // body to read the resource from.
+ String stream = "rpcv2-" + UUID.randomUUID();
+ String accessKeyId = userWithPolicy("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"kinesis:*","Resource":"*"},
+ {"Effect":"Deny","Action":"kinesis:DeleteStream",
+ "Resource":"arn:aws:kinesis:us-east-1:%s:stream/%s"}
+ ]}""".formatted(ACCOUNT_ID, stream));
+
+ assertAccessDenied(signed(accessKeyId, "kinesis")
+ .header("X-Amz-Target", "Kinesis_20131202.DeleteStream")
+ .contentType("application/x-amz-cbor-1.1")
+ .body(cbor("""
+ {"StreamName": "%s"}
+ """.formatted(stream)))
+ .when()
+ .post("/")
+ .then(), "kinesis:DeleteStream");
+ }
+
+ private static void assertAccessDenied(ValidatableResponse response, String action) throws IOException {
+ JsonNode error = CBOR_MAPPER.readTree(response.statusCode(403).extract().asByteArray());
+ assertEquals("AccessDeniedException", error.path("__type").asText());
+ assertTrue(error.path("message").asText().contains(action), error.toString());
+ }
+
+ private static String sendBatch(String queueUrl) {
+ return """
+ {"QueueUrl": "%s", "Entries": [{"Id": "one", "MessageBody": "hello"}]}
+ """.formatted(queueUrl);
+ }
+
+ private static String sendMessage(String queueUrl) {
+ return """
+ {"QueueUrl": "%s", "MessageBody": "hello"}
+ """.formatted(queueUrl);
+ }
+
+ private static String getItem(String table, String id) {
+ return """
+ {"TableName": "%s", "Key": {"id": {"S": "%s"}}}
+ """.formatted(table, id);
+ }
+
+ private static String queueArn(String queueUrl) {
+ return given()
+ .header("Authorization", auth(ACCOUNT_ID, "sqs"))
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueAttributes")
+ .formParam("Version", "2012-11-05")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("AttributeName.1", "QueueArn")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath()
+ .setRoot("GetQueueAttributesResponse.GetQueueAttributesResult")
+ .getString("Attribute.find { it.Name == 'QueueArn' }.Value");
+ }
+
+ private String createTable() {
+ String table = "rpcv2-" + UUID.randomUUID();
+ dynamoDbAsRoot("CreateTable", """
+ {"TableName": "%s", "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
+ "AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
+ "BillingMode": "PAY_PER_REQUEST"}
+ """.formatted(table));
+ cleanup.register(() -> dynamoDbAsRoot("DeleteTable", """
+ {"TableName": "%s"}
+ """.formatted(table)));
+ return table;
+ }
+
+ private static void dynamoDbAsRoot(String operation, String body) {
+ given()
+ .header("Authorization", auth(ACCOUNT_ID, "dynamodb"))
+ .header("X-Amz-Target", "DynamoDB_20120810." + operation)
+ .contentType("application/x-amz-json-1.0")
+ .body(body)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private String createQueue() {
+ String queueUrl = given()
+ .header("Authorization", auth(ACCOUNT_ID, "sqs"))
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateQueue")
+ .formParam("Version", "2012-11-05")
+ .formParam("QueueName", "rpcv2-" + UUID.randomUUID())
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
+ cleanup.register(() -> given()
+ .header("Authorization", auth(ACCOUNT_ID, "sqs"))
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteQueue")
+ .formParam("Version", "2012-11-05")
+ .formParam("QueueUrl", queueUrl)
+ .when().post("/").then().statusCode(200));
+ return queueUrl;
+ }
+
+ private static String allow(String action) {
+ return """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"%s","Resource":"*"}
+ ]}""".formatted(action);
+ }
+
+ private String userWithPolicy(String document) {
+ String userName = "rpcv2-" + UUID.randomUUID().toString().substring(0, 8);
+ String accessKeyId = EnforcementFixtures.createUser(cleanup, baseUri.getPort(),
+ auth(ACCOUNT_ID, "iam"), userName).accessKeyId();
+ given()
+ .header("Authorization", auth(ACCOUNT_ID, "iam"))
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "PutUserPolicy")
+ .formParam("Version", "2010-05-08")
+ .formParam("UserName", userName)
+ .formParam("PolicyName", "only")
+ .formParam("PolicyDocument", document)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ return accessKeyId;
+ }
+
+ private static ValidatableResponse sqsRpcV2(String accessKeyId, String signingScope, String operation,
+ String jsonBody) {
+ return sqsRpcV2(signed(accessKeyId, signingScope).header("smithy-protocol", "rpc-v2-cbor"),
+ operation, jsonBody);
+ }
+
+ private static RequestSpecification signed(String accessKeyId, String signingScope) {
+ return given().header("Authorization", auth(accessKeyId, signingScope));
+ }
+
+ private static ValidatableResponse sqsRpcV2(RequestSpecification request, String operation, String jsonBody) {
+ return rpcV2(request, "AmazonSQS", operation, jsonBody);
+ }
+
+ private static ValidatableResponse rpcV2(RequestSpecification request, String serviceId, String operation,
+ String jsonBody) {
+ return request
+ .contentType("application/cbor")
+ .accept("application/cbor")
+ .body(cbor(jsonBody))
+ .when()
+ .post("/service/" + serviceId + "/operation/" + operation)
+ .then();
+ }
+
+ private static byte[] cbor(String json) {
+ try {
+ return CBOR_MAPPER.writeValueAsBytes(new ObjectMapper().readTree(json));
+ } catch (IOException e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+}