feat(sns): add the MaximumMessageSize topic attribute for 1 MiB payloads (#3953)

* feat(sns): add the MaximumMessageSize topic attribute for 1 MiB payloads

AWS raised the SNS payload ceiling from 256 KiB to 1 MiB behind a new
per-topic MaximumMessageSize attribute. The default stays 262144, so an
unconfigured topic is unchanged.

CreateTopic and SetTopicAttributes validate the 1024-1048576 range, Publish
and PublishBatch size against the topic's value, and a topic above 262144 is
held to its subscription constraints: sqs, firehose or lambda only, and at
most 100 subscriptions. AWS::SNS::Topic forwards the property too.

Two things the same code path had wrong, both checked against the live API:
Subject was counted towards the publish limit when AWS does not count it, and
PublishBatch returned the SQS wording rather than the SNS one.

* fix(sns): ignore an out-of-range persisted MaximumMessageSize

Validation only guards new writes. A topic stored before the attribute was
known carries whatever the old generic setter accepted, so the read path
could hand back a value above 1 MiB and wave a publish past the AWS ceiling,
or one at zero and reject every publish. Out of range now falls back to the
default, exactly as a nonnumeric value already did.

Also covers the attribute end to end on both wire protocols -- create, set,
get, and the oversized Publish and PublishBatch errors on Query and JSON 1.1
-- since the existing suite drives SnsService directly and cannot catch a
regression in parameter extraction or error serialization.
This commit is contained in:
Stuart Lang authored and GitHub committed 2026-09-19 19:05:22 -04:00
1 parent 5ac07733e9
commit 7d9f499f2d
6 files changed
+804 -21

No files matched your search

+43
View File
@@ -88,6 +88,49 @@ Supported subscription protocols:
- `http` / `https` — posts to an HTTP endpoint
- `application` — fans out to a mobile push platform endpoint (see [Mobile push](#mobile-push-mock))
## Message size
`MaximumMessageSize` is the per-topic limit, in bytes, on a published payload. It accepts `1024`
to `1048576` (1 MiB) and defaults to `262144` (256 KiB). AWS raised the maximum in September 2026
but left the default alone, so a topic that never sets the attribute behaves exactly as it did
before. `GetTopicAttributes` omits the attribute until it is set rather than reporting the
default.
```bash
aws sns set-topic-attributes --topic-arn $TOPIC_ARN \
--attribute-name MaximumMessageSize --attribute-value 1048576 \
--endpoint-url $AWS_ENDPOINT_URL
```
The limit counts the message body plus, per message attribute, its name, data type and value.
`Subject` is not counted. `PublishBatch` counts the sum of all its entries against the same
limit and fails the whole call rather than individual entries.
A topic above `262144` is restricted: at most 100 subscriptions, every one of them `sqs`,
`firehose` or `lambda`. Floci enforces the protocol rule on `Subscribe` and `SetTopicAttributes`
alike, and the subscription count on `SetTopicAttributes` only — matching AWS, which lets an
already-raised topic drift past 100 and catches it the next time the attribute is set. Pending
confirmations count towards both. (`firehose` subscriptions are accepted for validation but not
delivered to, as before.)
| Action | Condition | Error code | HTTP |
|---|---|---|---|
| `CreateTopic`, `SetTopicAttributes` | `MaximumMessageSize` not an integer between 1024 and 1048576 | `InvalidParameter` | 400 |
| `SetTopicAttributes` | Raised above 262144 with a subscription that is not `sqs`, `firehose` or `lambda` | `InvalidParameter` | 400 |
| `SetTopicAttributes` | Raised above 262144 with more than 100 subscriptions | `InvalidParameter` | 400 |
| `Subscribe` | Unsupported protocol on a topic above 262144 | `InvalidParameter` | 400 |
| `Publish` | Payload exceeds the topic's `MaximumMessageSize` | `InvalidParameter` | 400 |
| `PublishBatch` | Entries sum to more than the topic's `MaximumMessageSize` | `BatchRequestTooLong` | 400 |
CloudFormation carries the setting through: `AWS::SNS::Topic` forwards `MaximumMessageSize`, and
an update that drops the property returns the topic to the default.
A raised topic fanning out to SQS needs headroom. The notification envelope wraps the body in a
few hundred bytes of JSON, so a publish at 1 MiB no longer fits a queue at the SQS maximum and is
dropped on delivery — silently, as any delivery failure is. Keep the topic below the queue's own
`MaximumMessageSize`, or subscribe with `RawMessageDelivery=true` so the body is forwarded
unwrapped.
## FIFO topics
A topic whose name ends in `.fifo` is a FIFO topic. `Publish` and `PublishBatch` require a
@@ -48,6 +48,7 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
String topicName = ctx.resolveOptional(props, "TopicName");
String contentBasedDedupFlag = ctx.resolveOptional(props, "ContentBasedDeduplication");
String throughputScope = ctx.resolveOptional(props, "FifoThroughputScope");
String maximumMessageSize = ctx.resolveOptional(props, "MaximumMessageSize");
// The .fifo suffix is what makes SnsService treat a topic as FIFO, so an explicitly named
// one is FIFO with or without the flag, which only has to steer a generated name.
boolean fifo = "true".equalsIgnoreCase(ctx.resolveOptional(props, "FifoTopic"))
@@ -83,6 +84,9 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
if (throughputScope != null && !throughputScope.isBlank()) {
attributes.put("FifoThroughputScope", throughputScope);
}
if (maximumMessageSize != null && !maximumMessageSize.isBlank()) {
attributes.put("MaximumMessageSize", maximumMessageSize);
}
var topic = snsService.createTopic(topicName, attributes, Map.of(), ctx.region());
// createTopic leaves an existing topic untouched, so an update writes the mutable
@@ -93,6 +97,14 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
desired.putIfAbsent("ContentBasedDeduplication", "false");
desired.putIfAbsent("FifoThroughputScope", "Topic");
}
// A dropped MaximumMessageSize goes back to the AWS default, but only where one was
// set: writing the default onto a topic that never carried the attribute would make
// GetTopicAttributes report something real SNS omits.
if (!desired.containsKey("MaximumMessageSize")
&& topic.getAttributes().containsKey("MaximumMessageSize")) {
desired.put("MaximumMessageSize",
String.valueOf(SnsService.DEFAULT_MAX_MESSAGE_SIZE));
}
desired.forEach((name, value) ->
snsService.setTopicAttributes(topic.getTopicArn(), name, value, ctx.region()));
}
@@ -61,7 +61,17 @@ public class SnsService implements Resettable, ResourceProvider {
private static final Logger LOG = Logger.getLogger(SnsService.class);
private static final Duration FIFO_DEDUP_WINDOW = Duration.ofMinutes(5);
private static final int MAX_PUBLISH_SIZE = 262_144;
/** Default value of the {@code MaximumMessageSize} topic attribute, and the ceiling below
* which a topic carries no subscription restrictions. AWS raised the maximum to 1 MiB in
* September 2026 but left the default at 256 KiB, so an unconfigured topic is unchanged. */
public static final int DEFAULT_MAX_MESSAGE_SIZE = 262_144;
private static final int MIN_MAX_MESSAGE_SIZE = 1_024;
private static final int MAX_MAX_MESSAGE_SIZE = 1_048_576;
/** The only protocols allowed on a topic above {@link #DEFAULT_MAX_MESSAGE_SIZE}. */
private static final Set<String> LARGE_PAYLOAD_PROTOCOLS = Set.of("sqs", "firehose", "lambda");
/** How many subscriptions a topic above {@link #DEFAULT_MAX_MESSAGE_SIZE} may carry. */
private static final int LARGE_PAYLOAD_SUBSCRIPTION_LIMIT = 100;
private static final String MAXIMUM_MESSAGE_SIZE = "MaximumMessageSize";
private static final int PUSH_CAPTURE_LIMIT = 1000;
private static final String CONTROL_TOWER_AGGREGATE_SECURITY_TOPIC =
"aws-controltower-AggregateSecurityNotifications";
@@ -186,6 +196,9 @@ public class SnsService implements Resettable, ResourceProvider {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidParameter", "Topic name is required.", 400);
}
if (attributes != null && attributes.containsKey(MAXIMUM_MESSAGE_SIZE)) {
validateMaximumMessageSize(attributes.get(MAXIMUM_MESSAGE_SIZE), true);
}
String topicArn = regionResolver.buildArn("sns", region, name);
String key = topicKey(region, topicArn);
@@ -269,10 +282,109 @@ public class SnsService implements Resettable, ResourceProvider {
String key = topicKey(region, topicArn);
Topic topic = topicStore.get(key)
.orElseThrow(() -> new AwsException("NotFound", "Topic does not exist.", 404));
if (MAXIMUM_MESSAGE_SIZE.equals(attributeName)
&& validateMaximumMessageSize(attributeValue, false) > DEFAULT_MAX_MESSAGE_SIZE) {
requireLargePayloadSubscriptions(topicArn, region);
}
topic.getAttributes().put(attributeName, attributeValue);
topicStore.put(key, topic);
}
/**
* Parse and range-check a {@code MaximumMessageSize} attribute value, returning it. AWS
* parses strictly: surrounding whitespace, a decimal point and an empty value are all
* rejected rather than trimmed, coerced or treated as a reset -- which is where this
* differs from the SQS attribute of the same name. {@code CreateTopic} reports the same
* reason behind its own prefix.
*/
private static int validateMaximumMessageSize(String value, boolean onCreate) {
int parsed = -1;
if (value != null) {
try {
parsed = Integer.parseInt(value);
} catch (NumberFormatException ignored) {
parsed = -1;
}
}
if (parsed < MIN_MAX_MESSAGE_SIZE || parsed > MAX_MAX_MESSAGE_SIZE) {
throw new AwsException("InvalidParameter",
"Invalid parameter: " + (onCreate ? "Attributes Reason: " : "")
+ MAXIMUM_MESSAGE_SIZE + ": " + (value == null ? "" : value)
+ " is not an integer between " + MIN_MAX_MESSAGE_SIZE + " and "
+ MAX_MAX_MESSAGE_SIZE + " bytes", 400);
}
return parsed;
}
/**
* Enforce what AWS asks of a topic carrying payloads above 256 KiB: at most 100
* subscriptions, every one of them Amazon SQS, Amazon Data Firehose or Lambda. Pending
* confirmations count towards both. Only the protocol half is also checked on Subscribe --
* AWS lets the count drift past 100 once the attribute is already raised, and catches it
* the next time the attribute is set.
*/
private void requireLargePayloadSubscriptions(String topicArn, String region) {
List<Subscription> subs = subscriptionsByTopic(topicArn, region);
for (Subscription sub : subs) {
requireLargePayloadProtocol(sub.getProtocol());
}
if (subs.size() > LARGE_PAYLOAD_SUBSCRIPTION_LIMIT) {
throw new AwsException("InvalidParameter",
"Invalid parameter: A topic with " + MAXIMUM_MESSAGE_SIZE + " greater than "
+ DEFAULT_MAX_MESSAGE_SIZE + " bytes supports a maximum of "
+ LARGE_PAYLOAD_SUBSCRIPTION_LIMIT + " subscriptions", 400);
}
}
private static void requireLargePayloadProtocol(String protocol) {
if (protocol != null && LARGE_PAYLOAD_PROTOCOLS.contains(protocol)) {
return;
}
throw new AwsException("InvalidParameter",
"Invalid parameter: " + MAXIMUM_MESSAGE_SIZE + " greater than "
+ DEFAULT_MAX_MESSAGE_SIZE
+ " bytes is not supported for the following protocol: ["
+ protocol + "]", 400);
}
/** The topic's configured {@code MaximumMessageSize}, or the AWS default when unset. */
private int topicMaxMessageSize(String topicArn, String region) {
return topicStore.get(topicKey(region, topicArn))
.map(SnsService::maxMessageSize)
.orElse(DEFAULT_MAX_MESSAGE_SIZE);
}
/**
* The read path is deliberately more forgiving than {@link #validateMaximumMessageSize}: a
* topic persisted before the attribute was known holds whatever the old generic setter
* accepted, and an out-of-range value there is as unusable as a nonnumeric one. Above the
* AWS ceiling it would wave a publish past the limit AWS enforces; at zero or below it
* would reject every publish and silently gate subscriptions. Both fall back to the
* default rather than being honoured.
*/
private static int maxMessageSize(Topic topic) {
String value = topic.getAttributes().get(MAXIMUM_MESSAGE_SIZE);
if (value == null) {
return DEFAULT_MAX_MESSAGE_SIZE;
}
try {
int parsed = Integer.parseInt(value);
if (parsed >= MIN_MAX_MESSAGE_SIZE && parsed <= MAX_MAX_MESSAGE_SIZE) {
return parsed;
}
} catch (NumberFormatException ignored) {
// Not a number at all: same treatment as out of range, handled below.
}
return DEFAULT_MAX_MESSAGE_SIZE;
}
private static void requireWithinMaxMessageSize(int payloadSize, int maxMessageSize) {
if (payloadSize > maxMessageSize) {
throw new AwsException("InvalidParameter",
"Invalid parameter: Message too long", 400);
}
}
public Subscription subscribe(String topicArn, String protocol, String endpoint, String region, Map<String, String> attributes) {
String topicKey = topicKey(region, topicArn);
if (topicStore.get(topicKey).isEmpty() && !ensureControlTowerManagedTopic(topicArn, region)) {
@@ -286,6 +398,9 @@ public class SnsService implements Resettable, ResourceProvider {
throw new AwsException("InvalidParameter",
"Invalid parameter: Endpoint scheme does not match protocol '" + protocol + "'.", 400);
}
if (topicMaxMessageSize(topicArn, region) > DEFAULT_MAX_MESSAGE_SIZE) {
requireLargePayloadProtocol(protocol);
}
for (Subscription existing : subscriptionsByTopic(topicArn, region)) {
if (protocol.equals(existing.getProtocol())
@@ -394,14 +509,13 @@ public class SnsService implements Resettable, ResourceProvider {
Map<String, MessageAttributeValue> messageAttributes,
String messageGroupId, String messageDeduplicationId, String region) {
int messageBytes = message == null ? 0 : message.getBytes(StandardCharsets.UTF_8).length;
int payloadSize = computePublishSize(messageBytes, subject, messageAttributes);
if (payloadSize > MAX_PUBLISH_SIZE) {
throw new AwsException("InvalidParameter",
"Invalid parameter: Message too long", 400);
}
// The limit is a per-topic attribute, so it cannot be applied until the topic is in
// hand. SMS and mobile-push publishes never reach a topic and keep the AWS default.
int payloadSize = computePublishSize(messageBytes, messageAttributes);
// Send SMS
if (phoneNumber != null) {
requireWithinMaxMessageSize(payloadSize, DEFAULT_MAX_MESSAGE_SIZE);
String messageId = UUID.randomUUID().toString();
String effectiveRegion = region != null ? region : "us-east-1";
SentSms sms = new SentSms(messageId, effectiveRegion, phoneNumber,
@@ -421,6 +535,7 @@ public class SnsService implements Resettable, ResourceProvider {
}
if (isEndpointArn(effectiveArn)) {
requireWithinMaxMessageSize(payloadSize, DEFAULT_MAX_MESSAGE_SIZE);
return publishToEndpoint(effectiveArn, message, subject, messageStructure,
messageAttributes, region);
}
@@ -434,6 +549,8 @@ public class SnsService implements Resettable, ResourceProvider {
Topic topic = topicStore.get(topicStoreKey)
.orElseThrow(() -> new AwsException("NotFound", "Topic does not exist.", 404));
requireWithinMaxMessageSize(payloadSize, maxMessageSize(topic));
validateTopicMessageStructure(message, messageStructure);
boolean isFifo = "true".equals(topic.getAttributes().get("FifoTopic"));
@@ -840,16 +957,15 @@ public class SnsService implements Resettable, ResourceProvider {
int batchSize = 0;
for (Map<String, Object> entry : entries) {
String message = (String) entry.get("Message");
String subject = (String) entry.get("Subject");
@SuppressWarnings("unchecked")
Map<String, MessageAttributeValue> attrs =
(Map<String, MessageAttributeValue>) entry.get("MessageAttributes");
int entryMessageBytes = message == null ? 0 : message.getBytes(StandardCharsets.UTF_8).length;
batchSize += computePublishSize(entryMessageBytes, subject, attrs);
batchSize += computePublishSize(entryMessageBytes, attrs);
}
if (batchSize > MAX_PUBLISH_SIZE) {
if (batchSize > maxMessageSize(topic)) {
throw new AwsException("BatchRequestTooLong",
"Batch requests cannot be longer than " + MAX_PUBLISH_SIZE + " bytes.", 400);
"The length of all the messages put together is more than the limit.", 400);
}
boolean isFifo = "true".equals(topic.getAttributes().get("FifoTopic"));
@@ -1592,13 +1708,13 @@ public class SnsService implements Resettable, ResourceProvider {
}
} catch (Exception e) {
// Delivery failures are per-subscriber and never reported to the publisher, which
// matches AWS. SNS caps a publish at MAX_PUBLISH_SIZE (262144 bytes) while SQS
// accepts up to 1048576 bytes, so for ordinary text the non-raw sqs envelope stays
// under the queue limit. That is not a guarantee: the envelope is serialized as
// JSON, and escaping expands every control character below 0x20 to six bytes, so a
// publish made largely of them can serialize several times larger and cross the
// limit. A queue configured with a smaller MaximumMessageSize crosses it more
// easily still. Either way the message is dropped here.
// matches AWS. Both SNS and SQS now top out at 1048576 bytes, so a publish at the
// SNS limit no longer fits a queue at all: the non-raw sqs envelope wraps the body
// in a few hundred bytes of JSON, and escaping expands every control character
// below 0x20 to six bytes, so a publish made largely of them can serialize several
// times larger. A topic left at the 262144-byte default clears an ordinary queue
// with room to spare; a queue configured with a smaller MaximumMessageSize crosses
// the limit more easily. Either way the message is dropped here.
LOG.warnv("Failed to deliver SNS message to {0}: {1}", sub.getEndpoint(), e.getMessage());
}
}
@@ -1810,12 +1926,14 @@ public class SnsService implements Resettable, ResourceProvider {
return AwsArnUtils.arnToQueueUrl(arn, baseUrl);
}
private static int computePublishSize(int messageBytes, String subject,
/**
* Payload size as AWS counts it against {@code MaximumMessageSize}: UTF-8 body bytes plus,
* per attribute, its name, data type and value. {@code Subject} is excluded -- a publish of
* exactly the limit succeeds however long its subject is.
*/
private static int computePublishSize(int messageBytes,
Map<String, MessageAttributeValue> attributes) {
int total = messageBytes;
if (subject != null) {
total += subject.getBytes(StandardCharsets.UTF_8).length;
}
if (attributes != null) {
for (Map.Entry<String, MessageAttributeValue> entry : attributes.entrySet()) {
total += entry.getKey().getBytes(StandardCharsets.UTF_8).length;
@@ -258,6 +258,50 @@ class SnsCfnProvisionerTest {
verify(sns).setTopicAttributes(TOPIC_ARN, "ContentBasedDeduplication", "false", REGION);
}
@Test
void maximumMessageSizeIsForwardedOnlyWhenSet() {
ArgumentCaptor<Map<String, String>> attrs = ArgumentCaptor.forClass(Map.class);
when(sns.createTopic(anyString(), attrs.capture(), anyMap(), anyString())).thenReturn(topic(TOPIC_ARN));
provision("AWS::SNS::Topic", """
{"TopicName": "events", "MaximumMessageSize": 1048576}
""");
assertEquals("1048576", attrs.getValue().get("MaximumMessageSize"));
setUp();
ArgumentCaptor<Map<String, String>> plain = ArgumentCaptor.forClass(Map.class);
when(sns.createTopic(anyString(), plain.capture(), anyMap(), anyString())).thenReturn(topic(TOPIC_ARN));
provision("AWS::SNS::Topic", """
{"TopicName": "events"}
""");
assertFalse(plain.getValue().containsKey("MaximumMessageSize"),
"an absent size must not be sent as an empty attribute");
}
/**
* Dropping the property returns the topic to the AWS default -- but only where the topic
* actually carries one, since real SNS omits the attribute until it is set.
*/
@Test
void anUpdateThatDropsMaximumMessageSizeResetsItOnlyWhenSet() {
Topic raised = topic(TOPIC_ARN);
raised.getAttributes().put("MaximumMessageSize", "1048576");
when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION))).thenReturn(raised);
provisionUpdate("""
{"TopicName": "events"}
""");
verify(sns).setTopicAttributes(TOPIC_ARN, "MaximumMessageSize", "262144", REGION);
setUp();
when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION))).thenReturn(topic(TOPIC_ARN));
provisionUpdate("""
{"TopicName": "events"}
""");
verify(sns, never()).setTopicAttributes(anyString(), eq("MaximumMessageSize"),
anyString(), anyString());
}
/** Real SNS rejects both attributes on a standard topic, so an update must not invent them. */
@Test
void aStandardTopicUpdateWritesNoFifoDefaults() {
@@ -8,6 +8,7 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.List;
import java.util.UUID;
import static io.restassured.RestAssured.given;
@@ -35,6 +36,8 @@ class SnsIntegrationTest {
private static String rawDeliverySubArn;
private static String envelopeQueueUrl;
private static String envelopeSubArn;
private static String maxSizeQueryTopicArn;
private static String maxSizeJsonTopicArn;
@Test
@Order(1)
@@ -904,6 +907,247 @@ class SnsIntegrationTest {
.body(containsString("UnsupportedOperation"));
}
// --- MaximumMessageSize, over both wire protocols ---
// SnsMaximumMessageSizeTest covers the rules; these cover the wire: parameter extraction,
// attribute omission, error codes and AWS-shaped serialization on Query and JSON 1.1.
@Test
@Order(60)
void maximumMessageSize_queryProtocol_createsAndReadsBackTheAttribute() {
maxSizeQueryTopicArn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "max-size-query-topic")
.formParam("Attributes.entry.1.key", "MaximumMessageSize")
.formParam("Attributes.entry.1.value", "1048576")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTopicAttributes")
.formParam("TopicArn", maxSizeQueryTopicArn)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<key>MaximumMessageSize</key>"))
.body(containsString("<value>1048576</value>"));
}
/** AWS omits the attribute until it is set rather than reporting the default. */
@Test
@Order(61)
void maximumMessageSize_queryProtocol_omittedUntilSet() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTopicAttributes")
.formParam("TopicArn", topicArn)
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("MaximumMessageSize")));
}
@Test
@Order(62)
void maximumMessageSize_queryProtocol_rejectsValueOutsideRangeOnCreate() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "max-size-rejected-topic")
.formParam("Attributes.entry.1.key", "MaximumMessageSize")
.formParam("Attributes.entry.1.value", "999")
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameter"))
.body("ErrorResponse.Error.Message", equalTo("Invalid parameter: Attributes Reason: "
+ "MaximumMessageSize: 999 is not an integer between 1024 and 1048576 bytes"));
}
/** A 300 KiB publish clears the raised topic but would fail at the 256 KiB default. */
@Test
@Order(63)
void maximumMessageSize_queryProtocol_publishAboveTheDefaultLimit() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Publish")
.formParam("TopicArn", maxSizeQueryTopicArn)
.formParam("Message", "x".repeat(307_200))
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<MessageId>"));
}
@Test
@Order(64)
void maximumMessageSize_queryProtocol_rejectsOversizedPublishAndBatch() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SetTopicAttributes")
.formParam("TopicArn", maxSizeQueryTopicArn)
.formParam("AttributeName", "MaximumMessageSize")
.formParam("AttributeValue", "1024")
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Publish")
.formParam("TopicArn", maxSizeQueryTopicArn)
.formParam("Message", "x".repeat(1025))
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameter"))
.body("ErrorResponse.Error.Message", equalTo("Invalid parameter: Message too long"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "PublishBatch")
.formParam("TopicArn", maxSizeQueryTopicArn)
.formParam("PublishBatchRequestEntries.member.1.Id", "big1")
.formParam("PublishBatchRequestEntries.member.1.Message", "x".repeat(600))
.formParam("PublishBatchRequestEntries.member.2.Id", "big2")
.formParam("PublishBatchRequestEntries.member.2.Message", "x".repeat(600))
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("BatchRequestTooLong"))
.body("ErrorResponse.Error.Message",
equalTo("The length of all the messages put together is more than the limit."));
}
@Test
@Order(65)
void maximumMessageSize_jsonProtocol_createsAndReadsBackTheAttribute() {
maxSizeJsonTopicArn = given()
.contentType(SNS_CONTENT_TYPE)
.header("X-Amz-Target", "SNS_20100331.CreateTopic")
.body("""
{
"Name": "max-size-json-topic",
"Attributes": {"MaximumMessageSize": "1048576"}
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("TopicArn", notNullValue())
.extract().path("TopicArn");
given()
.contentType(SNS_CONTENT_TYPE)
.header("X-Amz-Target", "SNS_20100331.GetTopicAttributes")
.body("{\"TopicArn\": \"%s\"}".formatted(maxSizeJsonTopicArn))
.when()
.post("/")
.then()
.statusCode(200)
.body("Attributes.MaximumMessageSize", equalTo("1048576"));
}
@Test
@Order(66)
void maximumMessageSize_jsonProtocol_rejectsValueOutsideRangeOnSet() {
given()
.contentType(SNS_CONTENT_TYPE)
.header("X-Amz-Target", "SNS_20100331.SetTopicAttributes")
.body("""
{
"TopicArn": "%s",
"AttributeName": "MaximumMessageSize",
"AttributeValue": "1048577"
}
""".formatted(maxSizeJsonTopicArn))
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameter"))
.body("message", equalTo("Invalid parameter: MaximumMessageSize: 1048577 "
+ "is not an integer between 1024 and 1048576 bytes"));
}
@Test
@Order(67)
void maximumMessageSize_jsonProtocol_rejectsOversizedPublishAndBatch() {
given()
.contentType(SNS_CONTENT_TYPE)
.header("X-Amz-Target", "SNS_20100331.SetTopicAttributes")
.body("""
{
"TopicArn": "%s",
"AttributeName": "MaximumMessageSize",
"AttributeValue": "1024"
}
""".formatted(maxSizeJsonTopicArn))
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType(SNS_CONTENT_TYPE)
.header("X-Amz-Target", "SNS_20100331.Publish")
.body("{\"TopicArn\": \"%s\", \"Message\": \"%s\"}"
.formatted(maxSizeJsonTopicArn, "x".repeat(1025)))
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameter"))
.body("message", equalTo("Invalid parameter: Message too long"));
given()
.contentType(SNS_CONTENT_TYPE)
.header("X-Amz-Target", "SNS_20100331.PublishBatch")
.body("""
{
"TopicArn": "%s",
"PublishBatchRequestEntries": [
{"Id": "big1", "Message": "%s"},
{"Id": "big2", "Message": "%s"}
]
}
""".formatted(maxSizeJsonTopicArn, "x".repeat(600), "x".repeat(600)))
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("BatchRequestTooLong"))
.body("message",
equalTo("The length of all the messages put together is more than the limit."));
}
@Test
@Order(68)
void maximumMessageSize_cleanup() {
for (String arn : List.of(maxSizeQueryTopicArn, maxSizeJsonTopicArn)) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteTopic")
.formParam("TopicArn", arn)
.when()
.post("/")
.then()
.statusCode(200);
}
}
/**
* Drains all pending messages from the given SQS queue using PurgeQueue.
*/
@@ -0,0 +1,322 @@
package io.github.hectorvent.floci.services.sns;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.sns.model.Topic;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* The {@code MaximumMessageSize} topic attribute, which AWS added in September 2026 to raise the
* SNS payload ceiling from 256 KiB to 1 MiB. Every expectation here -- error codes, error wording,
* boundary values and the subscription constraints -- was taken from the live API.
*/
class SnsMaximumMessageSizeTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final int DEFAULT = 262_144;
private static final int ONE_MIB = 1_048_576;
private SnsService snsService;
@BeforeEach
void setUp() {
snsService = new SnsService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver(REGION, ACCOUNT),
null,
null);
}
private String topic(String name) {
return snsService.createTopic(name, null, null, REGION).getTopicArn();
}
private String largeTopic(String name) {
String arn = topic(name);
snsService.setTopicAttributes(arn, "MaximumMessageSize", String.valueOf(ONE_MIB), REGION);
return arn;
}
/**
* Write a value straight onto the stored topic, the way one persisted before this attribute
* was validated carries it: the old generic {@code SetTopicAttributes} wrote anything
* through. {@code createTopic} returns the stored instance for a name that already exists,
* so this is the same topic the service reads back.
*/
private void persistUnvalidated(String name, String value) {
snsService.createTopic(name, null, null, REGION)
.getAttributes().put("MaximumMessageSize", value);
}
// --- The attribute itself ---
/** AWS omits the attribute entirely until it is set; it does not report the default. */
@Test
void getTopicAttributes_omitsMaximumMessageSizeUntilSet() {
String arn = topic("unset");
assertFalse(snsService.getTopicAttributes(arn, REGION).containsKey("MaximumMessageSize"));
snsService.setTopicAttributes(arn, "MaximumMessageSize", "1048576", REGION);
assertEquals("1048576",
snsService.getTopicAttributes(arn, REGION).get("MaximumMessageSize"));
}
@Test
void setTopicAttributes_acceptsRangeBoundaries() {
String arn = topic("bounds");
for (String value : List.of("1024", "262144", "1048576")) {
snsService.setTopicAttributes(arn, "MaximumMessageSize", value, REGION);
assertEquals(value,
snsService.getTopicAttributes(arn, REGION).get("MaximumMessageSize"));
}
}
/**
* AWS parses the value strictly -- no trimming, no decimals -- and rejects an empty value
* outright rather than treating it as a reset, which is how the SQS attribute of the same
* name behaves.
*/
@Test
void setTopicAttributes_rejectsValuesOutsideRange() {
String arn = topic("invalid");
for (String value : List.of("1023", "1048577", "0", "-1", "abc", "1024.5", "", " 262144 ")) {
AwsException ex = assertThrows(AwsException.class, () ->
snsService.setTopicAttributes(arn, "MaximumMessageSize", value, REGION));
assertEquals("InvalidParameter", ex.getErrorCode());
assertEquals("Invalid parameter: MaximumMessageSize: " + value
+ " is not an integer between 1024 and 1048576 bytes", ex.getMessage());
}
}
/** CreateTopic reports the same reason behind its own {@code Attributes Reason:} prefix. */
@Test
void createTopic_rejectsValueOutsideRange() {
AwsException ex = assertThrows(AwsException.class, () -> snsService.createTopic(
"bad", Map.of("MaximumMessageSize", "999"), null, REGION));
assertEquals("InvalidParameter", ex.getErrorCode());
assertEquals("Invalid parameter: Attributes Reason: MaximumMessageSize: 999 "
+ "is not an integer between 1024 and 1048576 bytes", ex.getMessage());
}
@Test
void createTopic_acceptsMaximumMessageSize() {
Topic created = snsService.createTopic(
"big", Map.of("MaximumMessageSize", "1048576"), null, REGION);
assertEquals("1048576", created.getAttributes().get("MaximumMessageSize"));
assertNotNull(snsService.publish(created.getTopicArn(), null, "x".repeat(300_000), null, REGION));
}
/** FIFO topics take the attribute too. */
@Test
void fifoTopic_supportsMaximumMessageSize() {
Topic fifo = snsService.createTopic("orders.fifo",
Map.of("MaximumMessageSize", "1048576"), null, REGION);
assertEquals("true", fifo.getAttributes().get("FifoTopic"));
assertNotNull(snsService.publish(fifo.getTopicArn(), null, null, "x".repeat(300_000),
null, null, "group-1", "dedup-1", REGION));
}
// --- Publish ---
@Test
void publish_defaultTopic_acceptsExactlyTheDefaultLimit() {
String arn = topic("default-limit");
assertNotNull(snsService.publish(arn, null, "x".repeat(DEFAULT), null, REGION));
AwsException ex = assertThrows(AwsException.class, () ->
snsService.publish(arn, null, "x".repeat(DEFAULT + 1), null, REGION));
assertEquals("InvalidParameter", ex.getErrorCode());
assertEquals("Invalid parameter: Message too long", ex.getMessage());
}
@Test
void publish_raisedTopic_acceptsExactlyOneMebibyte() {
String arn = largeTopic("raised-limit");
assertNotNull(snsService.publish(arn, null, "x".repeat(ONE_MIB), null, REGION));
AwsException ex = assertThrows(AwsException.class, () ->
snsService.publish(arn, null, "x".repeat(ONE_MIB + 1), null, REGION));
assertEquals("InvalidParameter", ex.getErrorCode());
}
/** Lowering the attribute takes effect immediately. */
@Test
void publish_loweredTopic_rejectsBelowTheDefault() {
String arn = topic("lowered");
snsService.setTopicAttributes(arn, "MaximumMessageSize", "1024", REGION);
assertNotNull(snsService.publish(arn, null, "x".repeat(1024), null, REGION));
assertThrows(AwsException.class, () ->
snsService.publish(arn, null, "x".repeat(1025), null, REGION));
}
/** Subject is not counted: a message at exactly the limit publishes whatever its subject. */
@Test
void publish_subjectDoesNotCountTowardsTheLimit() {
String arn = topic("subject");
assertNotNull(snsService.publish(arn, null, "x".repeat(DEFAULT), "s".repeat(100), REGION));
}
/** Attributes are counted as name + data type + value, exactly. */
@Test
void publish_attributesCountTowardsTheLimit() {
String arn = topic("attrs");
// "attr1" (5) + "String" (6) + a 44-byte value = 55 bytes of attribute.
Map<String, MessageAttributeValue> attrs = Map.of(
"attr1", new MessageAttributeValue("v".repeat(44), "String"));
assertNotNull(snsService.publish(arn, null, null, "x".repeat(DEFAULT - 55),
null, attrs, REGION));
assertThrows(AwsException.class, () -> snsService.publish(arn, null, null,
"x".repeat(DEFAULT - 54), null, attrs, REGION));
}
/** An SMS publish never reaches a topic, so it keeps the default limit. */
@Test
void publish_toPhoneNumber_keepsTheDefaultLimit() {
assertNotNull(snsService.publish(null, null, "+819012345678",
"x".repeat(DEFAULT), null, null, REGION));
assertThrows(AwsException.class, () -> snsService.publish(null, null, "+819012345678",
"x".repeat(DEFAULT + 1), null, null, REGION));
}
/**
* A persisted value outside the AWS range is not honoured on the way back out. Validation
* only guards new writes, so a topic stored before the attribute existed could otherwise
* lift a publish past the 1 MiB ceiling, or -- at zero or below -- reject every publish.
*/
@Test
void publish_persistedValueOutsideRange_fallsBackToTheDefault() {
String arn = topic("legacy");
for (String value : List.of("5242880", "0", "-1", "abc")) {
persistUnvalidated("legacy", value);
assertNotNull(snsService.publish(arn, null, "x".repeat(DEFAULT), null, REGION));
AwsException ex = assertThrows(AwsException.class, () ->
snsService.publish(arn, null, "x".repeat(DEFAULT + 1), null, REGION));
assertEquals("Invalid parameter: Message too long", ex.getMessage());
}
}
/** It does not gate subscriptions either: the topic counts as sitting at the default. */
@Test
void subscribe_persistedValueOutsideRange_appliesNoProtocolConstraint() {
String arn = topic("legacy-gate");
persistUnvalidated("legacy-gate", "5242880");
assertNotNull(snsService.subscribe(arn, "email", "nobody@example.com", REGION, Map.of()));
}
// --- PublishBatch ---
@Test
void publishBatch_sumsEntriesAgainstTheTopicLimit() {
String arn = topic("batch");
List<Map<String, Object>> entries = List.of(
Map.of("Id", "1", "Message", "x".repeat(131_072)),
Map.of("Id", "2", "Message", "x".repeat(131_073)));
AwsException ex = assertThrows(AwsException.class, () ->
snsService.publishBatch(arn, entries, REGION));
assertEquals("BatchRequestTooLong", ex.getErrorCode());
assertEquals("The length of all the messages put together is more than the limit.",
ex.getMessage());
snsService.setTopicAttributes(arn, "MaximumMessageSize", String.valueOf(ONE_MIB), REGION);
assertEquals(2, snsService.publishBatch(arn, entries, REGION).successful().size());
}
// --- Subscription constraints above 256 KiB ---
@Test
void subscribe_aboveDefault_rejectsUnsupportedProtocols() {
String arn = largeTopic("protocols");
for (String protocol : List.of("email", "email-json", "sms", "http", "https", "application")) {
AwsException ex = assertThrows(AwsException.class, () -> snsService.subscribe(
arn, protocol, protocol.startsWith("http") ? protocol + "://example.com/hook"
: "endpoint-" + protocol, REGION, Map.of()));
assertEquals("InvalidParameter", ex.getErrorCode());
assertEquals("Invalid parameter: MaximumMessageSize greater than 262144 bytes "
+ "is not supported for the following protocol: [" + protocol + "]",
ex.getMessage());
}
}
@Test
void subscribe_aboveDefault_allowsSqsFirehoseAndLambda() {
String arn = largeTopic("allowed-protocols");
for (String protocol : List.of("sqs", "firehose", "lambda")) {
assertNotNull(snsService.subscribe(arn, protocol, "arn:aws:" + protocol
+ ":us-east-1:000000000000:target", REGION, Map.of()));
}
}
/** Pending confirmations count: an unconfirmed email subscription still blocks the raise. */
@Test
void setTopicAttributes_rejectsRaiseWithUnsupportedSubscription() {
String arn = topic("has-email");
snsService.subscribe(arn, "email", "nobody@example.com", REGION, Map.of());
AwsException ex = assertThrows(AwsException.class, () -> snsService.setTopicAttributes(
arn, "MaximumMessageSize", "1048576", REGION));
assertEquals("InvalidParameter", ex.getErrorCode());
assertEquals("Invalid parameter: MaximumMessageSize greater than 262144 bytes "
+ "is not supported for the following protocol: [email]", ex.getMessage());
assertFalse(snsService.getTopicAttributes(arn, REGION).containsKey("MaximumMessageSize"));
}
@Test
void setTopicAttributes_rejectsRaiseAboveOneHundredSubscriptions() {
String arn = topic("many-subs");
for (int i = 0; i < 100; i++) {
snsService.subscribe(arn, "sqs", "arn:aws:sqs:us-east-1:000000000000:q" + i,
REGION, Map.of());
}
snsService.setTopicAttributes(arn, "MaximumMessageSize", "1048576", REGION);
snsService.subscribe(arn, "sqs", "arn:aws:sqs:us-east-1:000000000000:q100", REGION, Map.of());
AwsException ex = assertThrows(AwsException.class, () -> snsService.setTopicAttributes(
arn, "MaximumMessageSize", "1048575", REGION));
assertEquals("InvalidParameter", ex.getErrorCode());
assertEquals("Invalid parameter: A topic with MaximumMessageSize greater than 262144 "
+ "bytes supports a maximum of 100 subscriptions", ex.getMessage());
}
/**
* AWS only enforces the subscription count when the attribute is set, so a raised topic can
* drift past 100 subscriptions and only fail the next time it is set.
*/
@Test
void subscribe_aboveDefault_doesNotEnforceTheSubscriptionCount() {
String arn = largeTopic("drift");
for (int i = 0; i <= 100; i++) {
assertNotNull(snsService.subscribe(arn, "sqs",
"arn:aws:sqs:us-east-1:000000000000:q" + i, REGION, Map.of()));
}
assertEquals(101, snsService.listSubscriptionsByTopic(arn, REGION).size());
}
/** Neither constraint applies at or below the default, however many subscriptions there are. */
@Test
void setTopicAttributes_atOrBelowDefault_ignoresSubscriptionConstraints() {
String arn = topic("lower-freely");
snsService.subscribe(arn, "email", "nobody@example.com", REGION, Map.of());
for (int i = 0; i < 120; i++) {
snsService.subscribe(arn, "sqs", "arn:aws:sqs:us-east-1:000000000000:q" + i,
REGION, Map.of());
}
snsService.setTopicAttributes(arn, "MaximumMessageSize", "262144", REGION);
assertEquals("262144",
snsService.getTopicAttributes(arn, REGION).get("MaximumMessageSize"));
}
}