diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index 24d136d4cf..3dd8b01877 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -115,7 +115,7 @@ floci: sqs: enabled: true default-visibility-timeout: 30 # Seconds - max-message-size: 1048576 # Bytes (1 MB) + max-message-size: 1048576 # Bytes (1 MiB, the AWS maximum) clear-fifo-deduplication-cache-on-purge: false # When true, PurgeQueue clears SQS FIFO dedup and SNS FIFO topic dedup for topics subscribed to that queue s3: diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 616a4429cd..d31b7f6514 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -158,7 +158,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s |---|---|---| | `FLOCI_SERVICES_SQS_ENABLED` | `true` | Enable the SQS service | | `FLOCI_SERVICES_SQS_DEFAULT_VISIBILITY_TIMEOUT` | `30` | Default message visibility timeout in seconds | -| `FLOCI_SERVICES_SQS_MAX_MESSAGE_SIZE` | `1048576` | Maximum message body size in bytes (1 MB) | +| `FLOCI_SERVICES_SQS_MAX_MESSAGE_SIZE` | `1048576` | Maximum message body size in bytes (1 MiB) | | `FLOCI_SERVICES_SQS_CLEAR_FIFO_DEDUPLICATION_CACHE_ON_PURGE` | `false` | Reset the deduplication cache when a FIFO queue is purged | ### SNS diff --git a/docs/services/sqs.md b/docs/services/sqs.md index d858c3c78b..c208de3b76 100644 --- a/docs/services/sqs.md +++ b/docs/services/sqs.md @@ -92,13 +92,21 @@ aws sqs set-queue-attributes \ --endpoint-url $AWS_ENDPOINT_URL ``` +## Queue Attributes + +`GetQueueAttributes` with `--attribute-names All` returns the set AWS returns for a standard queue: `QueueArn`, `CreatedTimestamp`, `LastModifiedTimestamp`, `ApproximateNumberOfMessages`, `ApproximateNumberOfMessagesNotVisible`, `ApproximateNumberOfMessagesDelayed`, `VisibilityTimeout`, `MaximumMessageSize`, `MessageRetentionPeriod`, `DelaySeconds`, `ReceiveMessageWaitTimeSeconds` and `SqsManagedSseEnabled`. `Policy`, `RedrivePolicy` and `KmsMasterKeyId` appear only once set, and FIFO queues also report `FifoQueue` and `ContentBasedDeduplication`. + +`MaximumMessageSize` defaults to `1048576` bytes, the AWS default and maximum since August 2025, when AWS raised both from `262144`. `CreateQueue` and `SetQueueAttributes` reject values outside 1024 to 1048576 with `InvalidAttributeValue`; raising `FLOCI_SERVICES_SQS_MAX_MESSAGE_SIZE` above the AWS maximum raises that accepted ceiling with it. Lowering the variable below 1048576 only changes the default a new queue receives: the accepted ceiling stays at the AWS maximum, so a queue can still be set to `1048576` explicitly. + +`SqsManagedSseEnabled` is `true` for a queue with no `KmsMasterKeyId`, matching AWS, and `false` once a KMS key is set. It is derived on read rather than stored, so clearing `KmsMasterKeyId` returns the queue to `true`, unless you set `SqsManagedSseEnabled` yourself, in which case your value stands. AWS does not document the cleared-key case crisply, so that behaviour is Floci's choice rather than a copied one. + ## Configuration | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_SQS_ENABLED` | `true` | Enable or disable the service | | `FLOCI_SERVICES_SQS_DEFAULT_VISIBILITY_TIMEOUT` | `30` | Default message visibility timeout (seconds) | -| `FLOCI_SERVICES_SQS_MAX_MESSAGE_SIZE` | `1048576` | Maximum message size in bytes (1 MB) | +| `FLOCI_SERVICES_SQS_MAX_MESSAGE_SIZE` | `1048576` | Maximum message size in bytes (1 MiB) | | `FLOCI_SERVICES_SQS_CLEAR_FIFO_DEDUPLICATION_CACHE_ON_PURGE` | `false` | When `true`, `PurgeQueue` also clears the FIFO deduplication cache for the queue and any SNS FIFO topics subscribed to it | ## Examples diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java index dd419d2d79..fc1ece88e1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java @@ -1436,6 +1436,14 @@ public class SnsService implements Resettable, ResourceProvider { sub.getProtocol(), sub.getEndpoint()); } } 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. LOG.warnv("Failed to deliver SNS message to {0}: {1}", sub.getEndpoint(), e.getMessage()); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java index 3c341ef6b7..3cee5ca85c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java @@ -40,6 +40,10 @@ public class SqsService implements Resettable, ResourceProvider { private static final int MAX_RECEIVE_WAIT_TIME_SECONDS = 20; private static final int MAX_TERMINAL_MOVE_TASKS = 10; private static final Duration TERMINAL_MOVE_TASK_TTL = Duration.ofHours(1); + /** AWS accepts MaximumMessageSize between 1 KiB and 1 MiB; 1 MiB is also the default. + * Both the maximum and the default were raised from 256 KiB in August 2025. */ + private static final int MIN_MAXIMUM_MESSAGE_SIZE = 1024; + private static final int AWS_MAXIMUM_MESSAGE_SIZE = 1048576; private final StorageBackend queueStore; private final StorageBackend> messageStore; @@ -152,6 +156,9 @@ public class SqsService implements Resettable, ResourceProvider { private final int defaultVisibilityTimeout; private final int maxMessageSize; + /** Upper bound accepted for the MaximumMessageSize attribute. Raising max-message-size above + * the AWS limit widens this bound so the configured default stays settable explicitly. */ + private final int maxAllowedMessageSize; private final String baseUrl; private final RegionResolver regionResolver; private final boolean clearFifoDeduplicationCacheOnPurge; @@ -228,6 +235,7 @@ public class SqsService implements Resettable, ResourceProvider { this.dedupStore = dedupStore; this.defaultVisibilityTimeout = defaultVisibilityTimeout; this.maxMessageSize = maxMessageSize; + this.maxAllowedMessageSize = Math.max(AWS_MAXIMUM_MESSAGE_SIZE, maxMessageSize); this.baseUrl = baseUrl; this.regionResolver = regionResolver; this.clearFifoDeduplicationCacheOnPurge = clearFifoDeduplicationCacheOnPurge; @@ -362,6 +370,8 @@ public class SqsService implements Resettable, ResourceProvider { attributes.put("FifoQueue", "true"); } + validateMaximumMessageSize(attributes); + String accountId = regionResolver.getAccountId(); String queueUrl = baseUrl + "/" + accountId + "/" + queueName; String storageKey = regionKey(region, queueUrl); @@ -484,6 +494,26 @@ public class SqsService implements Resettable, ResourceProvider { attrs.put("ApproximateNumberOfMessagesNotVisible", String.valueOf(counts.inFlight())); attrs.put("ApproximateNumberOfMessagesDelayed", String.valueOf(counts.delayed())); + // Derived at read time and never stored, so it cannot go stale behind a + // KmsMasterKeyId that was later cleared. A KMS key always wins; otherwise an + // explicit SqsManagedSseEnabled stands, and a queue with neither reports the AWS + // default. What AWS does with a queue whose KMS key is cleared is not documented + // crisply, so reverting to the default is a choice, not a copied behaviour. + if (hasKmsMasterKey(attrs)) { + attrs.put("SqsManagedSseEnabled", "false"); + } else { + attrs.putIfAbsent("SqsManagedSseEnabled", "true"); + } + attrs.putIfAbsent("VisibilityTimeout", String.valueOf(defaultVisibilityTimeout)); + // Report the size that SendMessage actually enforces. A queue stored before the + // range existed can carry a value above the ceiling, and advertising it would + // promise a payload the send path then rejects. + attrs.put("MaximumMessageSize", + String.valueOf(parseMaxMessageSize(attrs.get("MaximumMessageSize")))); + attrs.putIfAbsent("DelaySeconds", "0"); + attrs.putIfAbsent("ReceiveMessageWaitTimeSeconds", "0"); + attrs.putIfAbsent("MessageRetentionPeriod", "345600"); + if (attributeNames == null || attributeNames.contains("All")) { return attrs; } @@ -649,12 +679,47 @@ public class SqsService implements Resettable, ResourceProvider { return maxMessageSize; } try { - return Math.min(1048576, Math.max(1024, Integer.parseInt(value))); + return Math.min(maxAllowedMessageSize, + Math.max(MIN_MAXIMUM_MESSAGE_SIZE, Integer.parseInt(value.trim()))); } catch (NumberFormatException ignored) { return maxMessageSize; } } + /** + * Reject a MaximumMessageSize outside the range AWS accepts, on CreateQueue and + * SetQueueAttributes alike. An empty value on SetQueueAttributes resets the attribute + * and is left to the caller. + */ + private void validateMaximumMessageSize(Map attributes) { + if (attributes == null) { + return; + } + String value = attributes.get("MaximumMessageSize"); + if (value == null || value.isEmpty()) { + return; + } + int parsed; + try { + parsed = Integer.parseInt(value.trim()); + } catch (NumberFormatException ignored) { + throw invalidMaximumMessageSize(); + } + if (parsed < MIN_MAXIMUM_MESSAGE_SIZE || parsed > maxAllowedMessageSize) { + throw invalidMaximumMessageSize(); + } + } + + private AwsException invalidMaximumMessageSize() { + return new AwsException("InvalidAttributeValue", + "Invalid value for the parameter MaximumMessageSize.", 400); + } + + private static boolean hasKmsMasterKey(Map attributes) { + String keyId = attributes.get("KmsMasterKeyId"); + return keyId != null && !keyId.isEmpty(); + } + /** * Validate that the combined payload of a {@code SendMessageBatch} call fits within * the queue's {@code MaximumMessageSize}. AWS counts the batch limit as the sum of @@ -940,6 +1005,7 @@ public class SqsService implements Resettable, ResourceProvider { Queue queue = queueStore.get(storageKey) .orElseThrow(() -> new AwsException("AWS.SimpleQueueService.NonExistentQueue", "The specified queue does not exist.", 400)); + validateMaximumMessageSize(attributes); if (attributes != null) { for (Map.Entry entry : attributes.entrySet()) { if (entry.getValue() == null || entry.getValue().isEmpty()) { diff --git a/src/test/java/io/github/hectorvent/floci/config/ApplicationDefaultsTest.java b/src/test/java/io/github/hectorvent/floci/config/ApplicationDefaultsTest.java index d346385400..0e3694ad97 100644 --- a/src/test/java/io/github/hectorvent/floci/config/ApplicationDefaultsTest.java +++ b/src/test/java/io/github/hectorvent/floci/config/ApplicationDefaultsTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.config; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; +import io.smallrye.config.WithDefault; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -39,6 +40,22 @@ class ApplicationDefaultsTest { "production application.yml should allow 2048 MB request bodies by default"); } + @Test + void productionConfigUsesTheAwsSqsMaximumMessageSize() throws IOException, NoSuchMethodException { + JsonNode config = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile()); + + assertEquals(1048576, + config.path("floci").path("services").path("sqs").path("max-message-size").asInt(), + "production application.yml should use the AWS SQS maximum of 1048576 bytes"); + + WithDefault fallback = EmulatorConfig.SqsServiceConfig.class + .getMethod("maxMessageSize") + .getAnnotation(WithDefault.class); + assertNotNull(fallback, "maxMessageSize should declare a fallback default"); + assertEquals("1048576", fallback.value(), + "the EmulatorConfig fallback should match the AWS SQS maximum too"); + } + @Test void productionConfigDoesNotSeedIamDeployerPrincipalByDefault() throws IOException { JsonNode config = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile()); diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsIntegrationTest.java index fa10100864..af34e10493 100644 --- a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsIntegrationTest.java @@ -4,7 +4,13 @@ import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.*; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.hamcrest.Matchers.*; @@ -754,4 +760,95 @@ class SqsIntegrationTest { .when().post("/"); } } + + @Test + void getQueueAttributesAllReturnsTheAwsAttributeSetForAStandardQueue() { + String attrQueueUrl = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateQueue") + .formParam("QueueName", "query-attribute-defaults-queue") + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl"); + + try { + Map attributes = allQueueAttributes(attrQueueUrl); + + assertEquals("1048576", attributes.get("MaximumMessageSize"), + "MaximumMessageSize must default to the AWS value of 1048576 bytes"); + assertEquals("true", attributes.get("SqsManagedSseEnabled"), + "A queue without a KMS key reports SSE-SQS enabled"); + assertEquals("30", attributes.get("VisibilityTimeout")); + assertEquals("345600", attributes.get("MessageRetentionPeriod")); + assertEquals("0", attributes.get("DelaySeconds")); + assertEquals("0", attributes.get("ReceiveMessageWaitTimeSeconds")); + assertTrue(attributes.containsKey("QueueArn")); + assertTrue(attributes.containsKey("CreatedTimestamp")); + assertTrue(attributes.containsKey("LastModifiedTimestamp")); + assertTrue(attributes.containsKey("ApproximateNumberOfMessages")); + assertTrue(attributes.containsKey("ApproximateNumberOfMessagesNotVisible")); + assertTrue(attributes.containsKey("ApproximateNumberOfMessagesDelayed")); + assertFalse(attributes.containsKey("Policy"), + "Policy is only returned once set"); + assertFalse(attributes.containsKey("RedrivePolicy"), + "RedrivePolicy is only returned once set"); + } finally { + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteQueue") + .formParam("QueueUrl", attrQueueUrl) + .when().post("/"); + } + } + + @Test + void setQueueAttributesRejectsMaximumMessageSizeAboveTheAwsLimit() { + String limitQueueUrl = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateQueue") + .formParam("QueueName", "query-max-message-size-range-queue") + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl"); + + try { + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "SetQueueAttributes") + .formParam("QueueUrl", limitQueueUrl) + .formParam("Attribute.1.Name", "MaximumMessageSize") + .formParam("Attribute.1.Value", "1048577") + .when().post("/").then() + .statusCode(400) + .body(containsString("InvalidAttributeValue")); + + assertEquals("1048576", allQueueAttributes(limitQueueUrl).get("MaximumMessageSize"), + "A rejected SetQueueAttributes must leave the stored value untouched"); + } finally { + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteQueue") + .formParam("QueueUrl", limitQueueUrl) + .when().post("/"); + } + } + + private static Map allQueueAttributes(String url) { + var xml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "GetQueueAttributes") + .formParam("QueueUrl", url) + .formParam("AttributeName.1", "All") + .when().post("/").then() + .statusCode(200) + .extract().xmlPath(); + + List names = xml.getList( + "GetQueueAttributesResponse.GetQueueAttributesResult.Attribute.Name", String.class); + List values = xml.getList( + "GetQueueAttributesResponse.GetQueueAttributesResult.Attribute.Value", String.class); + Map attributes = new LinkedHashMap<>(); + for (int i = 0; i < names.size(); i++) { + attributes.put(names.get(i), values.get(i)); + } + return attributes; + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java index f2d30c791e..a7fc809f47 100644 --- a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java @@ -65,6 +65,192 @@ class SqsServiceTest { assertEquals("60", queue.getAttributes().get("VisibilityTimeout")); } + @Test + void getQueueAttributes_defaultsMatchAws() { + String region = "eu-west-1"; + Queue queue = sqsService.createQueue("defaults-queue", null, region); + + Map attrs = sqsService.getQueueAttributes(queue.getQueueUrl(), List.of("All"), region); + assertEquals("1048576", attrs.get("MaximumMessageSize"), + "MaximumMessageSize must default to the AWS value of 1048576 bytes"); + assertEquals("true", attrs.get("SqsManagedSseEnabled"), + "A queue without a KMS key reports SSE-SQS enabled"); + assertEquals("30", attrs.get("VisibilityTimeout")); + assertEquals("345600", attrs.get("MessageRetentionPeriod")); + assertEquals("0", attrs.get("DelaySeconds")); + assertEquals("0", attrs.get("ReceiveMessageWaitTimeSeconds")); + assertNotNull(attrs.get("QueueArn")); + assertNotNull(attrs.get("CreatedTimestamp")); + assertNotNull(attrs.get("LastModifiedTimestamp")); + assertNotNull(attrs.get("ApproximateNumberOfMessages")); + assertNotNull(attrs.get("ApproximateNumberOfMessagesNotVisible")); + assertNotNull(attrs.get("ApproximateNumberOfMessagesDelayed")); + assertFalse(attrs.containsKey("Policy"), "Policy is only returned once set"); + assertFalse(attrs.containsKey("RedrivePolicy"), "RedrivePolicy is only returned once set"); + } + + @Test + void getQueueAttributes_sqsManagedSseDisabledWhenKmsKeyIsSet() { + String region = "eu-west-1"; + Queue queue = sqsService.createQueue("kms-queue", null, region); + sqsService.setQueueAttributes(queue.getQueueUrl(), + Map.of("KmsMasterKeyId", "alias/aws/sqs"), region); + + Map attrs = sqsService.getQueueAttributes(queue.getQueueUrl(), List.of("All"), region); + assertEquals("false", attrs.get("SqsManagedSseEnabled"), + "A KMS master key takes over from SSE-SQS"); + } + + @Test + void getQueueAttributes_sqsManagedSseDisabledWhenQueueIsCreatedWithAKmsKey() { + String region = "eu-west-1"; + Queue queue = sqsService.createQueue("kms-at-create-queue", + Map.of("KmsMasterKeyId", "alias/aws/sqs"), region); + + assertEquals("false", + sqsService.getQueueAttributes(queue.getQueueUrl(), List.of("All"), region) + .get("SqsManagedSseEnabled")); + } + + @Test + void getQueueAttributes_sqsManagedSseReturnsToTheDefaultWhenTheKmsKeyIsCleared() { + String region = "eu-west-1"; + Queue queue = sqsService.createQueue("kms-cleared-queue", + Map.of("KmsMasterKeyId", "alias/aws/sqs"), region); + assertEquals("false", + sqsService.getQueueAttributes(queue.getQueueUrl(), List.of("All"), region) + .get("SqsManagedSseEnabled")); + + sqsService.setQueueAttributes(queue.getQueueUrl(), Map.of("KmsMasterKeyId", ""), region); + + Map attrs = sqsService.getQueueAttributes(queue.getQueueUrl(), List.of("All"), region); + assertFalse(attrs.containsKey("KmsMasterKeyId"), "An empty value clears the attribute"); + assertEquals("true", attrs.get("SqsManagedSseEnabled"), + "Nothing derived from the KMS key may outlive it"); + } + + @Test + void getQueueAttributes_explicitSqsManagedSseFalseSurvivesAnUnrelatedUpdate() { + String region = "eu-west-1"; + Queue queue = sqsService.createQueue("sse-off-queue", + Map.of("SqsManagedSseEnabled", "false"), region); + sqsService.setQueueAttributes(queue.getQueueUrl(), Map.of("DelaySeconds", "5"), region); + + Map attrs = sqsService.getQueueAttributes(queue.getQueueUrl(), List.of("All"), region); + assertEquals("false", attrs.get("SqsManagedSseEnabled"), + "A value the user set is intent, not derived state, and has to survive"); + assertEquals("5", attrs.get("DelaySeconds")); + } + + @Test + void getQueueAttributes_selectsSqsManagedSseEnabledByName() { + String region = "eu-west-1"; + Queue queue = sqsService.createQueue("sse-named-queue", null, region); + + Map attrs = sqsService.getQueueAttributes(queue.getQueueUrl(), + List.of("SqsManagedSseEnabled"), region); + assertEquals(Map.of("SqsManagedSseEnabled", "true"), attrs); + } + + @Test + void createQueue_rejectsMaximumMessageSizeOutsideAwsRange() { + for (String invalid : List.of("1048577", "1023", "0", "-1", "abc")) { + AwsException ex = assertThrows(AwsException.class, + () -> sqsService.createQueue("range-queue-" + invalid, + Map.of("MaximumMessageSize", invalid), "eu-west-1"), + "MaximumMessageSize " + invalid + " must be rejected"); + assertEquals("InvalidAttributeValue", ex.getErrorCode()); + assertTrue(ex.getMessage().contains("MaximumMessageSize"), ex.getMessage()); + } + } + + @Test + void createQueue_acceptsMaximumMessageSizeRangeBounds() { + String region = "eu-west-1"; + for (String valid : List.of("1024", "1048576")) { + Queue queue = sqsService.createQueue("bounds-queue-" + valid, + Map.of("MaximumMessageSize", valid), region); + assertEquals(valid, + sqsService.getQueueAttributes(queue.getQueueUrl(), List.of("MaximumMessageSize"), region) + .get("MaximumMessageSize")); + } + } + + @Test + void createQueue_acceptsTheAwsCeilingWhenTheConfiguredMaximumIsLower() { + String region = "eu-west-1"; + var service = new SqsService(new InMemoryStorage<>(), 30, 131072, BASE_URL, clock); + + Queue defaulted = service.createQueue("lowered-config-default-queue", null, region); + assertEquals("131072", + service.getQueueAttributes(defaulted.getQueueUrl(), List.of("MaximumMessageSize"), region) + .get("MaximumMessageSize"), + "The configured maximum is what a new queue defaults to"); + + Queue raised = service.createQueue("lowered-config-raised-queue", + Map.of("MaximumMessageSize", "1048576"), region); + assertEquals("1048576", + service.getQueueAttributes(raised.getQueueUrl(), List.of("MaximumMessageSize"), region) + .get("MaximumMessageSize"), + "Lowering the configured maximum moves the default, not the ceiling AWS accepts"); + assertDoesNotThrow( + () -> service.sendMessage(raised.getQueueUrl(), "x".repeat(1_000_000), 0, region), + "The accepted ceiling and the enforced ceiling have to agree"); + } + + @Test + void getQueueAttributes_clampsAStoredMaximumMessageSizeAboveTheCeiling() { + String region = "us-east-1"; + var store = new InMemoryStorage(); + var service = new SqsService(store, 30, 1048576, BASE_URL, clock); + Queue queue = service.createQueue("legacy-size-queue", null, region); + + // A queue persisted by a build that allowed 2 MB, which no validation path can produce. + String storageKey = store.keys().iterator().next(); + Queue stored = store.get(storageKey).orElseThrow(); + stored.getAttributes().put("MaximumMessageSize", "2097152"); + store.put(storageKey, stored); + + assertEquals("1048576", + service.getQueueAttributes(queue.getQueueUrl(), List.of("MaximumMessageSize"), region) + .get("MaximumMessageSize"), + "A stored value above the ceiling must be reported as the size actually enforced"); + AwsException ex = assertThrows(AwsException.class, + () -> service.sendMessage(queue.getQueueUrl(), "x".repeat(1_200_000), 0, region), + "The reported size and the enforced size have to agree"); + assertTrue(ex.getMessage().contains("1048576"), ex.getMessage()); + } + + @Test + void setQueueAttributes_rejectsMaximumMessageSizeOutsideAwsRange() { + String region = "eu-west-1"; + Queue queue = sqsService.createQueue("set-range-queue", null, region); + + AwsException ex = assertThrows(AwsException.class, + () -> sqsService.setQueueAttributes(queue.getQueueUrl(), + Map.of("MaximumMessageSize", "1048577"), region)); + assertEquals("InvalidAttributeValue", ex.getErrorCode()); + assertEquals("1048576", + sqsService.getQueueAttributes(queue.getQueueUrl(), List.of("MaximumMessageSize"), region) + .get("MaximumMessageSize"), + "A rejected SetQueueAttributes must leave the stored value untouched"); + } + + @Test + void setQueueAttributes_acceptsMaximumMessageSizeWithinAwsRange() { + String region = "eu-west-1"; + Queue queue = sqsService.createQueue("set-valid-range-queue", null, region); + sqsService.setQueueAttributes(queue.getQueueUrl(), + Map.of("MaximumMessageSize", "2048"), region); + + assertEquals("2048", + sqsService.getQueueAttributes(queue.getQueueUrl(), List.of("MaximumMessageSize"), region) + .get("MaximumMessageSize")); + AwsException ex = assertThrows(AwsException.class, + () -> sqsService.sendMessage(queue.getQueueUrl(), "x".repeat(3000), 0, region)); + assertTrue(ex.getMessage().contains("2048"), ex.getMessage()); + } + @Test void createQueueWithTags_tagsReturnedByListQueueTags() { // Regression test for https://github.com/floci-io/floci/issues/699