fix(sns): refuse a topic policy that grants an action SNS does not have (#9080)

SetTopicAttributes and CreateTopic stored any Policy, so a topic policy
granting an action SNS does not have, such as sns:PublishBatch, was kept
and an AWS::SNS::TopicPolicy carrying one reached CREATE_COMPLETE. Both
now check every sns: Action of every statement against the list
AddPermission uses, ignoring case, and answer the same InvalidParameter
("Policy statement action out of service scope!"). A refused
SetTopicAttributes keeps the old policy and a refused CreateTopic creates
no topic. Receive, which AWS's former default topic policy granted, is
added to that list. Wildcards, NotAction, other services' actions and a
value that is not JSON are left unchecked.

Closes #8897
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-11-20 15:00:04 -04:00
1 parent 7e2d9e83fb
commit c9aad84192
3 files changed
+153 -5

No files matched your search

+5
View File
@@ -56,6 +56,11 @@ reports or CloudWatch delivery logs.
`AddPermission` and `RemovePermission` edit the topic's `Policy` attribute the way AWS does: the
label becomes the statement's `Sid` and each account becomes its `root` principal. A topic with no
policy set starts from the default one AWS gives a new topic, and `GetTopicAttributes` returns it.
A policy may only grant SNS's own actions: `AddPermission`, and a `Policy` set through
`SetTopicAttributes` or `CreateTopic`, answer `InvalidParameter` ("Policy statement action out of
service scope!") for an `sns:` action SNS does not have, such as `sns:PublishBatch`, which AWS
covers with `sns:Publish`. `Receive` is accepted, and action names in a policy are matched
ignoring case. Wildcards, `NotAction` and other services' actions are not checked.
Under IAM enforcement the topic policy decides what AWS services may publish to the topic, such as
[SES's event destinations and notifications](ses.md#iam-enforcement), and takes part in an IAM
caller's request the way any [resource-based policy](iam.md#resource-based-policies) does when the
@@ -29,6 +29,7 @@ import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.firehose.FirehoseService;
import io.floci.aws.services.firehose.model.Record;
import io.floci.aws.services.iam.PolicyDocument;
import io.floci.aws.services.lambda.LambdaService;
import io.floci.aws.services.lambda.model.InvocationType;
import io.floci.aws.services.sns.model.PlatformApplication;
@@ -78,6 +79,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ApplicationScoped
public class SnsService implements Resettable, ResourceProvider {
@@ -106,8 +108,10 @@ public class SnsService implements Resettable, ResourceProvider {
private static final int SANDBOX_PAGE_SIZE = 100;
/**
* The actions a topic policy statement can grant, which are SNS's actions in AWS's service
* reference (https://servicereference.us-east-1.amazonaws.com/v1/sns/sns.json).
* {@code AddPermission} refuses any other name.
* reference (https://servicereference.us-east-1.amazonaws.com/v1/sns/sns.json), plus
* {@code Receive}, which AWS's former default topic policy granted and AWS still accepts.
* {@code AddPermission} refuses any other name, and a policy set on a topic any other
* {@code sns:} action.
*/
private static final Set<String> SNS_POLICY_ACTIONS = Set.of(
"AddPermission", "CheckIfPhoneNumberIsOptedOut", "ConfirmSubscription",
@@ -121,7 +125,11 @@ public class SnsService implements Resettable, ResourceProvider {
"ListTagsForResource", "ListTopics", "OptInPhoneNumber", "Publish", "PutDataProtectionPolicy",
"RemovePermission", "SetEndpointAttributes", "SetPlatformApplicationAttributes",
"SetSMSAttributes", "SetSubscriptionAttributes", "SetTopicAttributes", "Subscribe",
"TagResource", "Unsubscribe", "UntagResource", "VerifySMSSandboxPhoneNumber");
"TagResource", "Unsubscribe", "UntagResource", "VerifySMSSandboxPhoneNumber", "Receive");
/** {@link #SNS_POLICY_ACTIONS} in lower case: a policy's action names are matched ignoring case. */
private static final Set<String> SNS_POLICY_ACTIONS_LOWER_CASE = SNS_POLICY_ACTIONS.stream()
.map(action -> action.toLowerCase(Locale.ROOT))
.collect(Collectors.toUnmodifiableSet());
/** What the default statement of a topic's policy grants its owner. */
private static final List<String> DEFAULT_TOPIC_POLICY_ACTIONS = List.of(
"SNS:GetTopicAttributes", "SNS:SetTopicAttributes", "SNS:AddPermission",
@@ -611,6 +619,9 @@ public class SnsService implements Resettable, ResourceProvider {
if (attributes != null && attributes.containsKey(MAXIMUM_MESSAGE_SIZE)) {
validateMaximumMessageSize(attributes.get(MAXIMUM_MESSAGE_SIZE), true);
}
if (attributes != null) {
requireSnsPolicyActions(attributes.get("Policy"));
}
String topicArn = regionResolver.buildArn("sns", region, name);
String key = topicKey(region, topicArn);
@@ -735,10 +746,46 @@ public class SnsService implements Resettable, ResourceProvider {
&& validateMaximumMessageSize(attributeValue, false) > DEFAULT_MAX_MESSAGE_SIZE) {
requireLargePayloadSubscriptions(topicArn, region);
}
if ("Policy".equals(attributeName)) {
requireSnsPolicyActions(attributeValue);
}
topic.getAttributes().put(attributeName, attributeValue);
topicStore.put(key, topic);
}
/**
* Refuses a topic policy whose statements grant an {@code sns:} action SNS does not have, as
* AWS does. Wildcards, {@code NotAction}, actions of other services and a value that is not
* JSON are left alone.
*/
private void requireSnsPolicyActions(String policy) {
if (policy == null || policy.isBlank()) {
return;
}
JsonNode document;
try {
document = objectMapper.readTree(policy);
} catch (JsonProcessingException ignored) {
// Not JSON: this check only reads the actions of a policy that parses.
return;
}
for (JsonNode statement : PolicyDocument.statementsOf(document)) {
JsonNode actions = statement.path("Action");
for (JsonNode action : actions.isArray() ? actions : List.of(actions)) {
String name = action.asText("").toLowerCase(Locale.ROOT);
if (name.startsWith("sns:") && !name.contains("*") && !name.contains("?")
&& !SNS_POLICY_ACTIONS_LOWER_CASE.contains(name.substring(4))) {
throw actionOutOfServiceScope();
}
}
}
}
private static AwsException actionOutOfServiceScope() {
return new AwsException("InvalidParameter",
"Invalid parameter: Policy statement action out of service scope!", 400);
}
/** Exists for CloudFormation rollback: SetTopicAttributes cannot unset an attribute. */
public synchronized void removeTopicAttribute(String topicArn, String attributeName, String region) {
String key = topicKey(region, topicArn);
@@ -772,8 +819,7 @@ public class SnsService implements Resettable, ResourceProvider {
Topic topic = topicStore.get(key).orElseThrow(SnsService::permissionTopicNotFound);
for (String action : actionNames) {
if (!SNS_POLICY_ACTIONS.contains(action)) {
throw new AwsException("InvalidParameter",
"Invalid parameter: Policy statement action out of service scope!", 400);
throw actionOutOfServiceScope();
}
}
ObjectNode policy = topicPolicy(topic, topicArn);
@@ -0,0 +1,97 @@
package io.floci.aws.services.sns;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.InvalidParameterException;
import java.net.URI;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* A topic policy may only grant SNS's own actions. There is no {@code sns:PublishBatch}: the
* batching guide says PublishBatch "uses the same Publish API action for IAM policies", and AWS
* answers a statement that grants an action SNS does not have with {@code InvalidParameter},
* as {@code AddPermission} already does here.
*/
@QuarkusTest
class SnsTopicPolicyActionScopeIntegrationTest {
private static final String OUT_OF_SCOPE = "Invalid parameter: Policy statement action out of service scope!";
@TestHTTPResource("/")
URI endpoint;
@Test
void setTopicAttributesRefusesAPolicyGrantingAnActionSnsDoesNotHave() {
try (SnsClient sns = client()) {
String topicArn = sns.createTopic(r -> r.name("policy-scope-" + UUID.randomUUID())).topicArn();
String defaultPolicy = policyOf(sns, topicArn);
InvalidParameterException refused = assertThrows(InvalidParameterException.class,
() -> sns.setTopicAttributes(r -> r.topicArn(topicArn).attributeName("Policy")
.attributeValue(policy(topicArn, "[\"sns:Publish\", \"sns:PublishBatch\"]"))));
assertEquals(OUT_OF_SCOPE, refused.awsErrorDetails().errorMessage());
assertEquals(defaultPolicy, policyOf(sns, topicArn));
}
}
@Test
void createTopicRefusesAPolicyGrantingAnActionSnsDoesNotHaveAndCreatesNoTopic() {
try (SnsClient sns = client()) {
String name = "policy-scope-" + UUID.randomUUID();
String topicArn = "arn:aws:sns:us-east-1:000000000000:" + name;
InvalidParameterException refused = assertThrows(InvalidParameterException.class,
() -> sns.createTopic(r -> r.name(name)
.attributes(Map.of("Policy", policy(topicArn, "\"sns:PublishBatch\"")))));
assertEquals(OUT_OF_SCOPE, refused.awsErrorDetails().errorMessage());
assertFalse(sns.listTopics().topics().stream().anyMatch(topic -> topic.topicArn().equals(topicArn)));
}
}
@Test
void actionNamesAreMatchedIgnoringCaseAndReceiveIsAccepted() {
try (SnsClient sns = client()) {
String topicArn = sns.createTopic(r -> r.name("policy-scope-" + UUID.randomUUID())).topicArn();
String policy = policy(topicArn, "[\"sns:publish\", \"SNS:Receive\"]");
sns.setTopicAttributes(r -> r.topicArn(topicArn).attributeName("Policy").attributeValue(policy));
assertEquals(policy, policyOf(sns, topicArn));
}
}
@Test
void addPermissionAcceptsReceive() {
try (SnsClient sns = client()) {
String topicArn = sns.createTopic(r -> r.name("policy-scope-" + UUID.randomUUID())).topicArn();
sns.addPermission(r -> r.topicArn(topicArn).label("receive-grant")
.awsAccountIds("111122223333").actionNames("Receive"));
}
}
private static String policy(String topicArn, String actions) {
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\","
+ "\"Action\":" + actions + ",\"Resource\":\"" + topicArn + "\"}]}";
}
private static String policyOf(SnsClient sns, String topicArn) {
return sns.getTopicAttributes(r -> r.topicArn(topicArn)).attributes().get("Policy");
}
private SnsClient client() {
return AwsTestClients.create(SnsClient.builder(), "000000000000", Region.US_EAST_1, endpoint);
}
}