Light, fluffy, and always free - The AWS Local Emulator alternative
fix(iam): refuse SNS requests with AuthorizationError (#6621)
Priamo Germosen7c0ee9248056
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamAuthorizedActionTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamAuthorizedActionTest.javaindex 3111585701..4645f36fc3 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamAuthorizedActionTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamAuthorizedActionTest.java@@ -10,8 +10,8 @@ import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;import software.amazon.awssdk.services.iam.IamClient;import software.amazon.awssdk.services.iam.model.AccessKey;import software.amazon.awssdk.services.sns.SnsClient;+import software.amazon.awssdk.services.sns.model.AuthorizationErrorException;import software.amazon.awssdk.services.sns.model.PublishBatchResultEntry;-import software.amazon.awssdk.services.sns.model.SnsException;import software.amazon.awssdk.services.sqs.SqsClient;import software.amazon.awssdk.services.sqs.model.SendMessageBatchResultEntry;import software.amazon.awssdk.services.sqs.model.SqsException;@@ -125,13 +125,16 @@ class IamAuthorizedActionTest {}@Test- @DisplayName("a policy naming PublishBatch, which is no IAM action, grants nothing")+ @DisplayName("a policy naming PublishBatch, which is no IAM action, grants nothing, refused as SNS's AuthorizationError")void aPolicyNamingPublishBatchGrantsNothing() {allow("sns:PublishBatch");assertThatThrownBy(() -> sns.publishBatch(r -> r.topicArn(topicArn).publishBatchRequestEntries(e -> e.id("one").message("hello"))))- .isInstanceOfSatisfying(SnsException.class, error -> assertThat(error.statusCode()).isEqualTo(403));+ .isInstanceOfSatisfying(AuthorizationErrorException.class, error -> {+ assertThat(error.statusCode()).isEqualTo(403);+ assertThat(error.awsErrorDetails().errorCode()).isEqualTo("AuthorizationError");+ });}private void allow(String action) {diff --git a/docs/services/iam.md b/docs/services/iam.mdindex 5f394be0a5..a2f05eeeb5 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -1435,8 +1435,9 @@ Policy evaluation follows the standard AWS precedence:IAM authorization denials return HTTP 400 `AccessDeniedException` for AWS JSON 1.0/1.1requests. REST-JSON requests return HTTP 403 `AccessDeniedException`; AWS Query and S3-requests retain HTTP 403 XML `AccessDenied` responses. The routed protocol determines-the status, not just the request's content type.+requests retain HTTP 403 XML `AccessDenied` responses, except SNS's, which return HTTP 403+`AuthorizationError`, the error every SNS operation lists for a caller denied access, whichever+action is denied. The routed protocol determines the status, not just the request's content type.A request is checked against the resources it names. Floci builds their ARNs itself for S3, Lambda,SQS, SNS, DynamoDB, Kinesis, SSM, KMS, IAM, Resource Groups, EventBridge Scheduler, EventBridgediff --git a/docs/services/sns.md b/docs/services/sns.mdindex 5e20a2623c..933592ccab 100644--- a/docs/services/sns.md+++ b/docs/services/sns.md@@ -60,7 +60,10 @@ Under IAM enforcement the topic policy decides what AWS services may publish to[SES's event destinations and notifications](ses.md#iam-enforcement), and takes part in an IAMcaller's request the way any [resource-based policy](iam.md#resource-based-policies) does when therequest names the topic in a JSON-protocol body. A Query-protocol request carries the topic in its-form body, which enforcement does not read yet, so the topic policy plays no part in it.+form body, which enforcement does not read yet, so the topic policy plays no part in it. A+Query-protocol request that IAM enforcement refuses answers `AuthorizationError` (HTTP 403), the+error every SNS operation lists for a caller denied access, which SDKs raise as+`AuthorizationErrorException`.## SMS sandbox and opt-outdiff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.javaindex 1ca56e1f30..71a3af0a42 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@@ -1709,7 +1709,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {* <ul>* <li>S3 → S3-flavored XML {@code <Error>...</Error>}</li>* <li>{@code application/x-www-form-urlencoded} body → AWS Query- * {@code <ErrorResponse>...</ErrorResponse>} (IAM/STS/EC2/SQS/SNS/...)</li>+ * {@code <ErrorResponse>...</ErrorResponse>} (IAM/STS/EC2/SQS/SNS/...), with the code+ * {@link #queryAccessDeniedCode} gives the service that serves the request</li>* <li>JSON 1.x: JSON with HTTP 400; REST-JSON: JSON with HTTP 403</li>* <li>CBOR: the request's own encoding with HTTP 403, from {@link #accessDeniedForRequest},* which has the request to read it from</li>@@ -1750,12 +1751,22 @@ public class IamEnforcementFilter implements ContainerRequestFilter {return s3XmlAccessDenied(message, resourcePath);}if (protocol == WireProtocol.AWS_QUERY || isFormEncoded(requestMediaType)) {- return queryXmlAccessDenied(message);+ return queryXmlError(queryAccessDeniedCode(credentialScope), message);}int status = protocol == WireProtocol.AWS_JSON_1_0 || protocol == WireProtocol.AWS_JSON_1_1 ? 400 : 403;return jsonAccessDenied(message, status);}+ /**+ * The code a Query service refuses a request it does not authorize with, whichever action was denied:+ * SNS's {@code AuthorizationError}, a 403 every SNS operation lists ("Indicates that the user has been+ * denied access to the requested resource") and the one SDKs raise as {@code AuthorizationErrorException},+ * and {@code AccessDenied} for every other service.+ */+ private static String queryAccessDeniedCode(String credentialScope) {+ return "sns".equals(credentialScope) ? "AuthorizationError" : "AccessDenied";+ }+private static String formatS3ResourcePath(String resourceArn) {String tail = AwsArnUtils.resourceIfArnFor(resourceArn, "s3").orElse(null);if (tail == null || tail.isEmpty() || "*".equals(tail)) {diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.javaindex cb07caa59f..d33485e237 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java@@ -2024,6 +2024,27 @@ class IamEnforcementFilterTest {assertTrue(body.contains("<RequestId>"), body);}+ /**+ * SNS refuses with its own {@code AuthorizationError}, the 403 every SNS operation lists, whichever action is+ * denied (a role it is passed as well as its own); another Query service still answers {@code AccessDenied}.+ */+ @Test+ void snsRefusesWithItsAuthorizationError() {+ for (String action : List.of("sns:Publish", "iam:PassRole")) {+ Response r = IamEnforcementFilter.accessDeniedResponse(+ action, "sns", MediaType.APPLICATION_FORM_URLENCODED_TYPE);++ assertEquals(403, r.getStatus());+ String body = entityString(r);+ assertTrue(body.contains("<Code>AuthorizationError</Code>"), body);+ assertTrue(body.contains("<Type>Sender</Type>"), body);+ assertTrue(body.contains("User is not authorized to perform: " + action), body);+ }+ String sqs = entityString(IamEnforcementFilter.accessDeniedResponse(+ "sqs:SendMessage", "sqs", MediaType.APPLICATION_FORM_URLENCODED_TYPE));+ assertTrue(sqs.contains("<Code>AccessDenied</Code>"), sqs);+ }+@Testvoid s3GetsS3FlavoredXmlError() {// S3 — credential-scope is "s3"; S3 errors are <Error>... at the root, no <ErrorResponse> wrapper.diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamAuthorizedActionEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamAuthorizedActionEnforcementIntegrationTest.javaindex ed77021cc6..498a3223ad 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamAuthorizedActionEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamAuthorizedActionEnforcementIntegrationTest.java@@ -88,41 +88,27 @@ class IamAuthorizedActionEnforcementIntegrationTest {@Testvoid aBatchPublishIsGrantedByPublish() {- String topicArn = given()- .header("Authorization", auth(ACCOUNT_ID, "sns"))- .contentType("application/x-www-form-urlencoded")- .formParam("Action", "CreateTopic")- .formParam("Version", "2010-03-31")- .formParam("Name", "authorized-" + UUID.randomUUID())- .when()- .post("/")- .then()- .statusCode(200)- .extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");- cleanup.register(() -> given()- .header("Authorization", auth(ACCOUNT_ID, "sns"))- .contentType("application/x-www-form-urlencoded")- .formParam("Action", "DeleteTopic")- .formParam("Version", "2010-03-31")- .formParam("TopicArn", topicArn)- .when().post("/").then().statusCode(200));+ String topicArn = createTopic();String accessKeyId = userAllowed("sns:Publish");- given()- .header("Authorization", auth(accessKeyId, "sns"))- .contentType("application/x-www-form-urlencoded")- .formParam("Action", "PublishBatch")- .formParam("Version", "2010-03-31")- .formParam("TopicArn", topicArn)- .formParam("PublishBatchRequestEntries.member.1.Id", "one")- .formParam("PublishBatchRequestEntries.member.1.Message", "hello")- .when()- .post("/")- .then()+ snsQuery(accessKeyId, "PublishBatch", publishBatch(topicArn)).statusCode(200).body("PublishBatchResponse.PublishBatchResult.Successful.member.Id", equalTo("one"));}+ /** SNS refuses with its own {@code AuthorizationError}, the 403 every SNS operation lists. */+ @Test+ void aPolicyNamingTheBatchPublishGrantsNothingAndSnsRefusesWithAuthorizationError() {+ String topicArn = createTopic();+ String accessKeyId = userAllowed("sns:PublishBatch");++ snsQuery(accessKeyId, "PublishBatch", publishBatch(topicArn))+ .statusCode(403)+ .body("ErrorResponse.Error.Code", equalTo("AuthorizationError"))+ .body("ErrorResponse.Error.Type", equalTo("Sender"))+ .body(containsString("sns:Publish"));+ }+@Testvoid aTransactGetIsCheckedItemByItemAgainstEachLeadingKey() {// AWS checks TransactGetItems as dynamodb:GetItem, and Floci checks each Get that way with@@ -211,6 +197,20 @@ class IamAuthorizedActionEnforcementIntegrationTest {return queueUrl;}+ private String createTopic() {+ String topicArn = snsQuery(ACCOUNT_ID, "CreateTopic", Map.of("Name", "authorized-" + UUID.randomUUID()))+ .statusCode(200)+ .extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");+ cleanup.register(() -> snsQuery(ACCOUNT_ID, "DeleteTopic", Map.of("TopicArn", topicArn))+ .statusCode(200));+ return topicArn;+ }++ private static Map<String, String> publishBatch(String topicArn) {+ return Map.of("TopicArn", topicArn, "PublishBatchRequestEntries.member.1.Id", "one",+ "PublishBatchRequestEntries.member.1.Message", "hello");+ }+private String userAllowed(String action) {return userWithPolicy("""{"Version":"2012-10-17","Statement":[@@ -259,6 +259,16 @@ class IamAuthorizedActionEnforcementIntegrationTest {.then();}+ private static ValidatableResponse snsQuery(String accessKeyId, String action, Map<String, String> params) {+ RequestSpecification spec = given()+ .header("Authorization", auth(accessKeyId, "sns"))+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", action)+ .formParam("Version", "2010-03-31");+ params.forEach(spec::formParam);+ return spec.when().post("/").then();+ }+private static ValidatableResponse sqsQuery(String accessKeyId, String action, Map<String, String> params) {RequestSpecification spec = given().header("Authorization", auth(accessKeyId, "sqs"))