Light, fluffy, and always free - The AWS Local Emulator alternative
fix(sqs): reject batch requests with more than 10 entries (#5331)
Vũ Thế Huy5d5e39a15e3c
diff --git a/compatibility-tests/sdk-test-python/tests/test_sqs.py b/compatibility-tests/sdk-test-python/tests/test_sqs.pyindex e1487f8625..b29eaba90e 100644--- a/compatibility-tests/sdk-test-python/tests/test_sqs.py+++ b/compatibility-tests/sdk-test-python/tests/test_sqs.py@@ -4,6 +4,7 @@ import jsonimport timeimport pytest+from botocore.exceptions import ClientErrorclass TestSQSQueue:@@ -100,6 +101,18 @@ class TestSQSMessages:assert len(response["Successful"]) == 3assert len(response.get("Failed", [])) == 0+ def test_send_message_batch_rejects_more_than_ten_entries(self, sqs_client, test_queue):+ """Test SendMessageBatch with 11 entries fails and sends nothing."""+ entries = [{"Id": f"m{i}", "MessageBody": f"Batch {i}"} for i in range(11)]+ with pytest.raises(ClientError) as error:+ sqs_client.send_message_batch(QueueUrl=test_queue, Entries=entries)+ assert error.value.response["Error"]["Code"] in (+ "TooManyEntriesInBatchRequest",+ "AWS.SimpleQueueService.TooManyEntriesInBatchRequest",+ )+ response = sqs_client.receive_message(QueueUrl=test_queue, MaxNumberOfMessages=10)+ assert len(response.get("Messages", [])) == 0+def test_delete_message_batch(self, sqs_client, test_queue):"""Test DeleteMessageBatch deletes multiple messages."""sqs_client.send_message_batch(diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsException.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsException.javaindex 51a1d645bd..5c34fee8ee 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsException.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsException.java@@ -26,7 +26,8 @@ public class AwsException extends RuntimeException {"AWS.SimpleQueueService.NonExistentQueue", "QueueDoesNotExist","QueueAlreadyExists", "QueueNameExists","ReceiptHandleIsInvalid", "ReceiptHandleIsInvalid",- "TooManyEntriesInBatchRequest", "TooManyEntriesInBatchRequest",+ "AWS.SimpleQueueService.TooManyEntriesInBatchRequest", "TooManyEntriesInBatchRequest",+ "AWS.SimpleQueueService.EmptyBatchRequest", "EmptyBatchRequest","BatchEntryIdNotUnique", "BatchEntryIdNotDistinct");diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.javaindex ba4d50dca8..31e06802a6 100644--- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java@@ -326,28 +326,27 @@ public class SqsJsonHandler {private Response handleDeleteMessageBatch(JsonNode request, String region) {String queueUrl = request.path("QueueUrl").asText(null);- JsonNode entries = request.path("Entries");+ JsonNode entries = requireBatchEntries(request);+ sqsService.validateBatchEntryCount("DeleteMessageBatchRequestEntry", entries.size());ArrayNode successful = objectMapper.createArrayNode();ArrayNode failed = objectMapper.createArrayNode();- if (entries.isArray()) {- for (JsonNode entry : entries) {- String id = entry.path("Id").asText();- String receiptHandle = entry.path("ReceiptHandle").asText(null);- try {- sqsService.deleteMessageInBatch(queueUrl, receiptHandle, region);- ObjectNode success = objectMapper.createObjectNode();- success.put("Id", id);- successful.add(success);- } catch (AwsException e) {- ObjectNode fail = objectMapper.createObjectNode();- fail.put("Id", id);- fail.put("Code", e.getErrorCode());- fail.put("Message", e.getMessage());- fail.put("SenderFault", true);- failed.add(fail);- }+ for (JsonNode entry : entries) {+ String id = entry.path("Id").asText();+ String receiptHandle = entry.path("ReceiptHandle").asText(null);+ try {+ sqsService.deleteMessageInBatch(queueUrl, receiptHandle, region);+ ObjectNode success = objectMapper.createObjectNode();+ success.put("Id", id);+ successful.add(success);+ } catch (AwsException e) {+ ObjectNode fail = objectMapper.createObjectNode();+ fail.put("Id", id);+ fail.put("Code", e.getErrorCode());+ fail.put("Message", e.getMessage());+ fail.put("SenderFault", true);+ failed.add(fail);}}@@ -361,7 +360,8 @@ public class SqsJsonHandler {private Response handleSendMessageBatch(JsonNode request, String region) {String queueUrl = request.path("QueueUrl").asText(null);- JsonNode entries = request.path("Entries");+ JsonNode entries = requireBatchEntries(request);+ sqsService.validateBatchEntryCount("SendMessageBatchRequestEntry", entries.size());ArrayNode successful = objectMapper.createArrayNode();ArrayNode failed = objectMapper.createArrayNode();@@ -371,72 +371,70 @@ public class SqsJsonHandler {List<ParsedEntry> parsedEntries = new ArrayList<>();int totalSize = 0;- if (entries.isArray()) {- for (JsonNode entry : entries) {- String id = entry.path("Id").asText();- String messageBody = entry.path("MessageBody").asText(null);- JsonNode entryDelayNode = entry.path("DelaySeconds");- Integer delaySeconds = parseOptionalInteger(entryDelayNode, "DelaySeconds");- String messageGroupId = entry.path("MessageGroupId").asText(null);- String messageDeduplicationId = entry.path("MessageDeduplicationId").asText(null);-- Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();- JsonNode attrsNode = entry.path("MessageAttributes");- if (attrsNode.isObject()) {- attrsNode.fields().forEachRemaining(attrEntry -> {- String name = attrEntry.getKey();- String dataType = attrEntry.getValue().path("DataType").asText(null);- String stringValue = attrEntry.getValue().path("StringValue").asText(null);- String binaryValueBase64 = attrEntry.getValue().path("BinaryValue").asText(null);- if (dataType != null) {- if (binaryValueBase64 != null) {- byte[] binaryValue = Base64.getDecoder().decode(binaryValueBase64);- messageAttributes.put(name, new MessageAttributeValue(binaryValue, dataType));- } else if (stringValue != null) {- messageAttributes.put(name, new MessageAttributeValue(stringValue, dataType));- }+ for (JsonNode entry : entries) {+ String id = entry.path("Id").asText();+ String messageBody = entry.path("MessageBody").asText(null);+ JsonNode entryDelayNode = entry.path("DelaySeconds");+ Integer delaySeconds = parseOptionalInteger(entryDelayNode, "DelaySeconds");+ String messageGroupId = entry.path("MessageGroupId").asText(null);+ String messageDeduplicationId = entry.path("MessageDeduplicationId").asText(null);++ Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();+ JsonNode attrsNode = entry.path("MessageAttributes");+ if (attrsNode.isObject()) {+ attrsNode.fields().forEachRemaining(attrEntry -> {+ String name = attrEntry.getKey();+ String dataType = attrEntry.getValue().path("DataType").asText(null);+ String stringValue = attrEntry.getValue().path("StringValue").asText(null);+ String binaryValueBase64 = attrEntry.getValue().path("BinaryValue").asText(null);+ if (dataType != null) {+ if (binaryValueBase64 != null) {+ byte[] binaryValue = Base64.getDecoder().decode(binaryValueBase64);+ messageAttributes.put(name, new MessageAttributeValue(binaryValue, dataType));+ } else if (stringValue != null) {+ messageAttributes.put(name, new MessageAttributeValue(stringValue, dataType));}- });- }+ }+ });+ }- String entryAwsTraceHeader = entry.path("MessageSystemAttributes")- .path("AWSTraceHeader").path("StringValue").asText(null);+ String entryAwsTraceHeader = entry.path("MessageSystemAttributes")+ .path("AWSTraceHeader").path("StringValue").asText(null);- totalSize += SqsService.computeMessageSize(messageBody, messageAttributes);- parsedEntries.add(new ParsedEntry(id, messageBody, delaySeconds,- messageGroupId, messageDeduplicationId, messageAttributes,- entryAwsTraceHeader));- }+ totalSize += SqsService.computeMessageSize(messageBody, messageAttributes);+ parsedEntries.add(new ParsedEntry(id, messageBody, delaySeconds,+ messageGroupId, messageDeduplicationId, messageAttributes,+ entryAwsTraceHeader));}sqsService.validateBatchPayloadSize(queueUrl, region, totalSize);String senderId = sqsService.resolveCallerSenderId(queueUrl);for (ParsedEntry parsed : parsedEntries) {- String id = parsed.id();- try {- Message msg = sqsService.sendMessage(queueUrl, parsed.body(), parsed.delay(),- parsed.groupId(), parsed.dedupId(), parsed.attributes(),- parsed.awsTraceHeader(), senderId, region);- ObjectNode success = objectMapper.createObjectNode();- success.put("Id", id);- success.put("MessageId", msg.getMessageId());- success.put("MD5OfMessageBody", msg.getMd5OfBody());- if (msg.getMd5OfMessageAttributes() != null) {- success.put("MD5OfMessageAttributes", msg.getMd5OfMessageAttributes());- }- if (msg.getSequenceNumber() > 0) {- success.put("SequenceNumber", String.valueOf(msg.getSequenceNumber()));- }- successful.add(success);- } catch (AwsException e) {- ObjectNode fail = objectMapper.createObjectNode();- fail.put("Id", id);- fail.put("Code", e.getErrorCode());- fail.put("Message", e.getMessage());- fail.put("SenderFault", true);- failed.add(fail);+ String id = parsed.id();+ try {+ Message msg = sqsService.sendMessage(queueUrl, parsed.body(), parsed.delay(),+ parsed.groupId(), parsed.dedupId(), parsed.attributes(),+ parsed.awsTraceHeader(), senderId, region);+ ObjectNode success = objectMapper.createObjectNode();+ success.put("Id", id);+ success.put("MessageId", msg.getMessageId());+ success.put("MD5OfMessageBody", msg.getMd5OfBody());+ if (msg.getMd5OfMessageAttributes() != null) {+ success.put("MD5OfMessageAttributes", msg.getMd5OfMessageAttributes());}+ if (msg.getSequenceNumber() > 0) {+ success.put("SequenceNumber", String.valueOf(msg.getSequenceNumber()));+ }+ successful.add(success);+ } catch (AwsException e) {+ ObjectNode fail = objectMapper.createObjectNode();+ fail.put("Id", id);+ fail.put("Code", e.getErrorCode());+ fail.put("Message", e.getMessage());+ fail.put("SenderFault", true);+ failed.add(fail);+ }}ObjectNode response = objectMapper.createObjectNode();@@ -512,16 +510,15 @@ public class SqsJsonHandler {private Response handleChangeMessageVisibilityBatch(JsonNode request, String region) {String queueUrl = request.path("QueueUrl").asText(null);- JsonNode entries = request.path("Entries");+ JsonNode entries = requireBatchEntries(request);+ sqsService.validateBatchEntryCount("ChangeMessageVisibilityBatchRequestEntry", entries.size());List<SqsService.ChangeVisibilityBatchEntry> batchEntries = new ArrayList<>();- if (entries.isArray()) {- for (JsonNode entry : entries) {- batchEntries.add(new SqsService.ChangeVisibilityBatchEntry(- entry.path("Id").asText(),- entry.path("ReceiptHandle").asText(null),- entry.path("VisibilityTimeout").asInt(30)));- }+ for (JsonNode entry : entries) {+ batchEntries.add(new SqsService.ChangeVisibilityBatchEntry(+ entry.path("Id").asText(),+ entry.path("ReceiptHandle").asText(null),+ entry.path("VisibilityTimeout").asInt(30)));}List<SqsService.BatchResultEntry> results =@@ -615,4 +612,17 @@ public class SqsJsonHandler {}return node.asInt();}++ private JsonNode requireBatchEntries(JsonNode request) {+ JsonNode entries = request.path("Entries");+ if (entries.isMissingNode() || entries.isNull()) {+ throw new AwsException("MissingParameter",+ "The request must contain the parameter Entries.", 400);+ }+ if (!entries.isArray()) {+ throw new AwsException("InvalidParameterValue",+ "Value for parameter Entries is invalid. Reason: Must be an array.", 400);+ }+ return entries;+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.javaindex 5c1f7f0743..4777d52cbf 100644--- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java@@ -17,6 +17,7 @@ import org.jboss.logging.Logger;import java.util.ArrayList;import java.util.Base64;import java.util.HashMap;+import java.util.HashSet;import java.util.LinkedHashSet;import java.util.List;import java.util.Map;@@ -331,6 +332,8 @@ public class SqsQueryHandler {private Response handleDeleteMessageBatch(MultivaluedMap<String, String> params, String region) {String queueUrl = getParam(params, "QueueUrl");+ sqsService.validateBatchEntryCount("DeleteMessageBatchRequestEntry",+ countBatchEntries(params, "DeleteMessageBatchRequestEntry"));XmlBuilder xml = new XmlBuilder();for (int i = 1; ; i++) {@@ -355,6 +358,8 @@ public class SqsQueryHandler {private Response handleSendMessageBatch(MultivaluedMap<String, String> params, String region) {String queueUrl = getParam(params, "QueueUrl");+ sqsService.validateBatchEntryCount("SendMessageBatchRequestEntry",+ countBatchEntries(params, "SendMessageBatchRequestEntry"));XmlBuilder xml = new XmlBuilder();record ParsedEntry(String id, String body, Integer delay, String groupId, String dedupId,@@ -504,6 +509,8 @@ public class SqsQueryHandler {private Response handleChangeMessageVisibilityBatch(MultivaluedMap<String, String> params, String region) {String queueUrl = getParam(params, "QueueUrl");+ sqsService.validateBatchEntryCount("ChangeMessageVisibilityBatchRequestEntry",+ countBatchEntries(params, "ChangeMessageVisibilityBatchRequestEntry"));List<SqsService.ChangeVisibilityBatchEntry> entries = new ArrayList<>();for (int i = 1; ; i++) {String id = getParam(params, "ChangeMessageVisibilityBatchRequestEntry." + i + ".Id");@@ -573,6 +580,24 @@ public class SqsQueryHandler {// --- Helpers ---+ private int countBatchEntries(MultivaluedMap<String, String> params, String entryPrefix) {+ if (params == null) {+ return 0;+ }+ String prefix = entryPrefix + ".";+ Set<String> indices = new HashSet<>();+ for (String key : params.keySet()) {+ if (key != null && key.startsWith(prefix)) {+ int dotIndex = key.indexOf('.', prefix.length());+ String index = dotIndex > 0 ? key.substring(prefix.length(), dotIndex) : key.substring(prefix.length());+ if (!index.isEmpty()) {+ indices.add(index);+ }+ }+ }+ return indices.size();+ }+private String getParam(MultivaluedMap<String, String> params, String name) {return params.getFirst(name);}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.javaindex 37ff8cd4d2..bea83779b5 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@@ -63,6 +63,7 @@ public class SqsService implements Resettable, ResourceProvider {private static final int DEDUP_WINDOW_SECONDS = 300; // 5 minutesprivate static final int DEDUP_LOCK_STRIPES = 256;private static final int MAX_RECEIVE_WAIT_TIME_SECONDS = 20;+ private static final int MAX_BATCH_ENTRIES = 10;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.@@ -1086,6 +1087,23 @@ public class SqsService implements Resettable, ResourceProvider {return keyId != null && !keyId.isEmpty();}+ /**+ * Reject a batch call carrying no entries or more than {@value #MAX_BATCH_ENTRIES}. AWS applies+ * both checks to {@code SendMessageBatch}, {@code DeleteMessageBatch} and+ * {@code ChangeMessageVisibilityBatch} alike, fails the whole request and processes no entry.+ */+ public void validateBatchEntryCount(String entryTypeName, int entryCount) {+ if (entryCount == 0) {+ throw new AwsException("AWS.SimpleQueueService.EmptyBatchRequest",+ "There should be at least one " + entryTypeName + " in the request.", 400);+ }+ if (entryCount > MAX_BATCH_ENTRIES) {+ throw new AwsException("AWS.SimpleQueueService.TooManyEntriesInBatchRequest",+ "Maximum number of entries per request are " + MAX_BATCH_ENTRIES+ + ". You have sent " + entryCount + ".", 400);+ }+ }+/*** 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 ofdiff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsIntegrationTest.javaindex 7fb6eee656..05be7eaa59 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@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.sqs;import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;import io.restassured.path.xml.XmlPath;+import io.restassured.specification.RequestSpecification;import org.junit.jupiter.api.*;import java.util.LinkedHashMap;@@ -1031,4 +1032,225 @@ class SqsIntegrationTest {}return attributes;}++ @Test+ void batchRequestsWithMoreThanTenEntriesAreRejectedWithoutProcessingAnyEntry() {+ String batchQueueUrl = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateQueue")+ .formParam("QueueName", "query-batch-limit-queue")+ .when().post("/")+ .then().statusCode(200)+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");+ try {+ // 1. SendMessageBatch with 11 entries rejects and stores nothing+ RequestSpecification sendRequest = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "SendMessageBatch")+ .formParam("QueueUrl", batchQueueUrl);+ for (int i = 1; i <= 11; i++) {+ sendRequest = sendRequest+ .formParam("SendMessageBatchRequestEntry." + i + ".Id", "e" + i)+ .formParam("SendMessageBatchRequestEntry." + i + ".MessageBody", "m" + i);+ }+ sendRequest.when().post("/")+ .then().statusCode(400)+ .body(containsString("AWS.SimpleQueueService.TooManyEntriesInBatchRequest"));++ assertEquals("0", allQueueAttributes(batchQueueUrl).get("ApproximateNumberOfMessages"));+ assertEquals("0", allQueueAttributes(batchQueueUrl).get("ApproximateNumberOfMessagesNotVisible"));++ // 2. Seed 2 messages and receive them to get valid receipt handles+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "SendMessage")+ .formParam("QueueUrl", batchQueueUrl)+ .formParam("MessageBody", "seed-1")+ .when().post("/")+ .then().statusCode(200);++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "SendMessage")+ .formParam("QueueUrl", batchQueueUrl)+ .formParam("MessageBody", "seed-2")+ .when().post("/")+ .then().statusCode(200);++ XmlPath receiveXml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "ReceiveMessage")+ .formParam("QueueUrl", batchQueueUrl)+ .formParam("MaxNumberOfMessages", "10")+ .formParam("VisibilityTimeout", "300")+ .when().post("/")+ .then().statusCode(200)+ .extract().xmlPath();+ List<String> receiptHandles = receiveXml.getList(+ "ReceiveMessageResponse.ReceiveMessageResult.Message.ReceiptHandle", String.class);+ assertEquals(2, receiptHandles.size());++ assertEquals("0", allQueueAttributes(batchQueueUrl).get("ApproximateNumberOfMessages"));+ assertEquals("2", allQueueAttributes(batchQueueUrl).get("ApproximateNumberOfMessagesNotVisible"));++ // 3. ChangeMessageVisibilityBatch with 11 entries rejects and does not change visibility+ addReceiptHandleEntries(+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "ChangeMessageVisibilityBatch")+ .formParam("QueueUrl", batchQueueUrl),+ "ChangeMessageVisibilityBatchRequestEntry", "v", receiptHandles,+ Map.of("VisibilityTimeout", "0"))+ .when().post("/")+ .then().statusCode(400)+ .body(containsString("AWS.SimpleQueueService.TooManyEntriesInBatchRequest"));++ assertEquals("0", allQueueAttributes(batchQueueUrl).get("ApproximateNumberOfMessages"));+ assertEquals("2", allQueueAttributes(batchQueueUrl).get("ApproximateNumberOfMessagesNotVisible"));++ // 4. DeleteMessageBatch with 11 entries rejects and preserves seeded messages+ addReceiptHandleEntries(+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteMessageBatch")+ .formParam("QueueUrl", batchQueueUrl),+ "DeleteMessageBatchRequestEntry", "d", receiptHandles, Map.of())+ .when().post("/")+ .then().statusCode(400)+ .body(containsString("AWS.SimpleQueueService.TooManyEntriesInBatchRequest"));++ assertEquals("0", allQueueAttributes(batchQueueUrl).get("ApproximateNumberOfMessages"));+ assertEquals("2", allQueueAttributes(batchQueueUrl).get("ApproximateNumberOfMessagesNotVisible"));+ } finally {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteQueue")+ .formParam("QueueUrl", batchQueueUrl)+ .when().post("/");+ }+ }++ @Test+ void batchRequestsWithNumberingGapAreRejectedWhenTotalEntriesExceedTen() {+ String batchQueueUrl = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateQueue")+ .formParam("QueueName", "query-batch-gap-queue")+ .when().post("/")+ .then().statusCode(200)+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");+ try {+ // Indices 1..4 and 6..12: gap at 5, total 11 entries+ RequestSpecification request = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "SendMessageBatch")+ .formParam("QueueUrl", batchQueueUrl);+ int[] indices = {1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12};+ for (int idx : indices) {+ request = request+ .formParam("SendMessageBatchRequestEntry." + idx + ".Id", "e" + idx)+ .formParam("SendMessageBatchRequestEntry." + idx + ".MessageBody", "m" + idx);+ }+ request.when().post("/")+ .then()+ .statusCode(400)+ .body(containsString("AWS.SimpleQueueService.TooManyEntriesInBatchRequest"));++ assertEquals("0", allQueueAttributes(batchQueueUrl).get("ApproximateNumberOfMessages"));+ } finally {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteQueue")+ .formParam("QueueUrl", batchQueueUrl)+ .when().post("/");+ }+ }++ @Test+ void batchRequestsWithEleventhEntryMissingIdAreRejectedWhenTotalEntriesExceedTen() {+ String batchQueueUrl = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateQueue")+ .formParam("QueueName", "query-batch-no-id-queue")+ .when().post("/")+ .then().statusCode(200)+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");+ try {+ // Entries 1..10 have Id and MessageBody; entry 11 has MessageBody but no Id+ RequestSpecification request = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "SendMessageBatch")+ .formParam("QueueUrl", batchQueueUrl);+ for (int i = 1; i <= 10; i++) {+ request = request+ .formParam("SendMessageBatchRequestEntry." + i + ".Id", "e" + i)+ .formParam("SendMessageBatchRequestEntry." + i + ".MessageBody", "m" + i);+ }+ request = request+ .formParam("SendMessageBatchRequestEntry.11.MessageBody", "m11");++ request.when().post("/")+ .then()+ .statusCode(400)+ .body(containsString("AWS.SimpleQueueService.TooManyEntriesInBatchRequest"));++ assertEquals("0", allQueueAttributes(batchQueueUrl).get("ApproximateNumberOfMessages"));+ } finally {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteQueue")+ .formParam("QueueUrl", batchQueueUrl)+ .when().post("/");+ }+ }++ @Test+ void batchRequestsWithNoEntriesAreRejected() {+ String batchQueueUrl = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateQueue")+ .formParam("QueueName", "query-batch-empty-queue")+ .when().post("/")+ .then().statusCode(200)+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");+ try {+ Map<String, String> expectedMessages = Map.of(+ "SendMessageBatch", "There should be at least one SendMessageBatchRequestEntry in the request.",+ "DeleteMessageBatch", "There should be at least one DeleteMessageBatchRequestEntry in the request.",+ "ChangeMessageVisibilityBatch", "There should be at least one ChangeMessageVisibilityBatchRequestEntry in the request."+ );+ for (Map.Entry<String, String> testCase : expectedMessages.entrySet()) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", testCase.getKey())+ .formParam("QueueUrl", batchQueueUrl)+ .when().post("/")+ .then().statusCode(400)+ .body(containsString("AWS.SimpleQueueService.EmptyBatchRequest"))+ .body(containsString(testCase.getValue()));+ }+ } finally {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteQueue")+ .formParam("QueueUrl", batchQueueUrl)+ .when().post("/");+ }+ }++ // Eleven entries: the real handles first, "dummy-rh" for the rest. extraParams are appended to each entry.+ private static RequestSpecification addReceiptHandleEntries(+ RequestSpecification request, String entryPrefix, String idPrefix,+ List<String> receiptHandles, Map<String, String> extraParams) {+ for (int i = 1; i <= 11; i++) {+ String rh = i <= receiptHandles.size() ? receiptHandles.get(i - 1) : "dummy-rh";+ request = request+ .formParam(entryPrefix + "." + i + ".Id", idPrefix + i)+ .formParam(entryPrefix + "." + i + ".ReceiptHandle", rh);+ for (Map.Entry<String, String> extra : extraParams.entrySet()) {+ request = request.formParam(entryPrefix + "." + i + "." + extra.getKey(), extra.getValue());+ }+ }+ return request;+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsJsonProtocolTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsJsonProtocolTest.javaindex e43f3b088b..65a63a2e3e 100644--- a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsJsonProtocolTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsJsonProtocolTest.java@@ -8,8 +8,12 @@ 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.Map;+import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.*;+import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertTrue;/**@@ -761,4 +765,232 @@ class SqsJsonProtocolTest {.when().post("/");}}++ @Test+ void batchRequestsWithMoreThanTenEntriesAreRejectedWithoutProcessingAnyEntry() {+ String batchQueueUrl = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.CreateQueue")+ .body("{\"QueueName\":\"json-batch-limit-queue\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().jsonPath().getString("QueueUrl");+ try {+ // 1. SendMessageBatch with 11 entries rejects and stores nothing+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.SendMessageBatch")+ .body(batchBody(batchQueueUrl, 11))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("TooManyEntriesInBatchRequest"));++ assertMessageCounts(batchQueueUrl, "0", "0");++ // 2. Seed 2 messages and receive them to get valid receipt handles+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.SendMessage")+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\",\"MessageBody\":\"seed-1\"}")+ .when().post("/")+ .then().statusCode(200);++ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.SendMessage")+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\",\"MessageBody\":\"seed-2\"}")+ .when().post("/")+ .then().statusCode(200);++ List<String> receiptHandles = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.ReceiveMessage")+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\",\"MaxNumberOfMessages\":10,\"VisibilityTimeout\":300}")+ .when().post("/")+ .then().statusCode(200)+ .extract().jsonPath().getList("Messages.ReceiptHandle");+ assertEquals(2, receiptHandles.size());++ assertMessageCounts(batchQueueUrl, "0", "2");++ // 3. ChangeMessageVisibilityBatch with 11 entries rejects and does not change visibility+ String visEntries = receiptHandleEntries("v", receiptHandles, ",\"VisibilityTimeout\":0");+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.ChangeMessageVisibilityBatch")+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\",\"Entries\":[" + visEntries + "]}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("TooManyEntriesInBatchRequest"));++ assertMessageCounts(batchQueueUrl, "0", "2");++ // 4. DeleteMessageBatch with 11 entries rejects and preserves seeded messages+ String delEntries = receiptHandleEntries("d", receiptHandles, "");+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.DeleteMessageBatch")+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\",\"Entries\":[" + delEntries + "]}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("TooManyEntriesInBatchRequest"));++ assertMessageCounts(batchQueueUrl, "0", "2");+ } finally {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.DeleteQueue")+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\"}")+ .when().post("/");+ }+ }++ @Test+ void batchRequestsWithMissingOrNonArrayEntriesAreRejected() {+ String batchQueueUrl = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.CreateQueue")+ .body("{\"QueueName\":\"json-batch-invalid-entries-queue\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().jsonPath().getString("QueueUrl");+ try {+ for (String target : List.of("SendMessageBatch", "DeleteMessageBatch", "ChangeMessageVisibilityBatch")) {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS." + target)+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\"}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("MissingParameter"));++ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS." + target)+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\",\"Entries\":\"not-an-array\"}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterValue"));+ }++ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.GetQueueAttributes")+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\",\"AttributeNames\":[\"ApproximateNumberOfMessages\"]}")+ .when().post("/")+ .then().statusCode(200)+ .body("Attributes.ApproximateNumberOfMessages", equalTo("0"));+ } finally {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.DeleteQueue")+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\"}")+ .when().post("/");+ }+ }++ @Test+ void batchRequestsWithNoEntriesAreRejected() {+ String batchQueueUrl = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.CreateQueue")+ .body("{\"QueueName\":\"json-batch-empty-queue\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().jsonPath().getString("QueueUrl");+ try {+ Map<String, String> expectedMessages = Map.of(+ "SendMessageBatch", "There should be at least one SendMessageBatchRequestEntry in the request.",+ "DeleteMessageBatch", "There should be at least one DeleteMessageBatchRequestEntry in the request.",+ "ChangeMessageVisibilityBatch", "There should be at least one ChangeMessageVisibilityBatchRequestEntry in the request."+ );+ for (Map.Entry<String, String> testCase : expectedMessages.entrySet()) {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS." + testCase.getKey())+ .body(batchBody(batchQueueUrl, 0))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("EmptyBatchRequest"))+ .body("message", equalTo(testCase.getValue()));+ }+ } finally {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.DeleteQueue")+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\"}")+ .when().post("/");+ }+ }++ @Test+ void sendMessageBatchAcceptsExactlyTenEntries() {+ String batchQueueUrl = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.CreateQueue")+ .body("{\"QueueName\":\"json-batch-ten-queue\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().jsonPath().getString("QueueUrl");+ try {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.SendMessageBatch")+ .body(batchBody(batchQueueUrl, 10))+ .when().post("/")+ .then().statusCode(200)+ .body("Successful", hasSize(10));+ } finally {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.DeleteQueue")+ .body("{\"QueueUrl\":\"" + batchQueueUrl + "\"}")+ .when().post("/");+ }+ }++ private static void assertMessageCounts(String url, String visible, String notVisible) {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.GetQueueAttributes")+ .body("{\"QueueUrl\":\"" + url + "\",\"AttributeNames\":[\"ApproximateNumberOfMessages\",\"ApproximateNumberOfMessagesNotVisible\"]}")+ .when().post("/")+ .then().statusCode(200)+ .body("Attributes.ApproximateNumberOfMessages", equalTo(visible))+ .body("Attributes.ApproximateNumberOfMessagesNotVisible", equalTo(notVisible));+ }++ // Eleven entries: the real handles first, "dummy-rh" for the rest. extraMembers is appended to each entry.+ private static String receiptHandleEntries(String idPrefix, List<String> receiptHandles, String extraMembers) {+ StringBuilder entries = new StringBuilder();+ for (int i = 0; i < 11; i++) {+ if (i > 0) {+ entries.append(',');+ }+ String receiptHandle = i < receiptHandles.size() ? receiptHandles.get(i) : "dummy-rh";+ entries.append("{\"Id\":\"").append(idPrefix).append(i).append("\",\"ReceiptHandle\":\"")+ .append(receiptHandle).append('"').append(extraMembers).append('}');+ }+ return entries.toString();+ }++ // One body shape serves all three batch actions: unknown members are ignored, and the+ // entry-count check runs before any entry is read.+ private static String batchBody(String url, int entryCount) {+ StringBuilder entries = new StringBuilder();+ for (int i = 0; i < entryCount; i++) {+ if (i > 0) {+ entries.append(',');+ }+ entries.append("{\"Id\":\"e").append(i).append("\",\"MessageBody\":\"m").append(i)+ .append("\",\"ReceiptHandle\":\"rh\",\"VisibilityTimeout\":0}");+ }+ return "{\"QueueUrl\":\"" + url + "\",\"Entries\":[" + entries + "]}";+ }}