fix(sqs): reject empty and malformed message attribute values (#8061)

SendMessage and SendMessageBatch on both the JSON and query protocols now answer InvalidParameterValue for a message attribute whose StringValue or BinaryValue is empty or whose BinaryValue is not base64, instead of storing an empty value or failing with a 500 on the decode. In a batch, only the entry carrying the bad attribute fails; the other entries are still sent.

An attribute missing its DataType, or carrying neither a StringValue nor a
BinaryValue, was silently dropped while an empty value was rejected. Both now
fail with InvalidParameterValue, using the wording LocalStack's snapshot tests
record: 'Missing required parameter DataType' and the existing non-empty value
message.

SendMessageBatch now writes the failed entry as soon as its attributes fail
to parse and skips it, rather than carrying the exception to the send loop.
The query handler parses SendMessage and SendMessageBatch attributes through
one helper.

A batch entry with an invalid message attribute was left out of the batch
payload total, so a batch over MaximumMessageSize only because of that
entry was accepted and the bad entry reported as a per-entry failure.
LocalStack and moto both sum every entry before any per-entry check, so the
total now comes from each entry's raw body and attributes, independent of
attribute validation, and such a batch fails whole with BatchRequestTooLong.

The empty-value error derived the base type with split("\\.")[0], which
throws ArrayIndexOutOfBoundsException, surfacing as a 500, for a DataType
of "." or "..". Take the substring before the first '.' instead.

A DataType whose base type (the part before the first period) is not
String, Number or Binary, such as "Strin", "Foo" or ".", was accepted.
SendMessage now rejects it with InvalidParameterValue, and SendMessageBatch
fails only that entry. The match is case-sensitive, and the message follows
LocalStack's check_attributes in localstack-core/localstack/services/sqs/
provider.py, which names the parameter literally as
MessageAttributes.Attribute_name.DataType. LocalStack's f-string drops the
space in "prefixed with"; the space is kept here.

The empty-String-value, missing-DataType and DataType-prefix messages come
from LocalStack's check_attributes. The empty Number and Binary value and
invalid base64 messages are Floci's own wording, unconfirmed against AWS,
so those cases now assert the error code only.

computeMessageSize now counts each attribute through the same helper the batch payload check uses on raw wire fields, so the name, type and value byte rule lives in one place.

Adds JSON and Query batches whose bodies fit the 1 MiB limit but whose invalid entry's attribute pushes the batch over it, plus service tests for UTF-8 byte lengths, decoded binary lengths, the invalid-base64 fallback and computeMessageSize.

Signed-off-by: Tyler Webb <tyler.webb@verkada.com>
This commit is contained in:
Tyler Webb authored and GitHub committed 2026-11-13 09:01:59 -04:00
1 parent 236e20003f
commit e41cc9b88d
7 files changed
+505 -83

No files matched your search

+2
View File
@@ -105,6 +105,8 @@ aws sqs set-queue-attributes \
`DelaySeconds` must be 0 to 900, both on a message and as a queue attribute: `SendMessage` rejects other values with `InvalidParameterValue` (in `SendMessageBatch` only that entry fails), and `CreateQueue` and `SetQueueAttributes` reject them with `InvalidAttributeValue`.
A message attribute with no `DataType`, with a `DataType` whose base type (the part before the first `.`) is not `String`, `Number` or `Binary`, with no value, with an empty `StringValue` or `BinaryValue`, or with a `BinaryValue` that is not base64 is rejected by `SendMessage` with `InvalidParameterValue` on both the JSON and query protocols. The base type match is case-sensitive, so `Number.int` is accepted while `number` is not, and a `DataType` such as `.` that starts with a period is rejected because its base type is empty. In `SendMessageBatch` only the entry carrying that attribute fails; the other entries are sent. The entry still counts toward the batch payload total, so a batch over the batch payload limit fails whole with `BatchRequestTooLong` even when the excess comes from that entry.
`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. `CreateQueue` on an existing name compares requested attributes against these reported values, so asking for `SqsManagedSseEnabled=false` on a queue that reports `true` fails with `QueueAlreadyExists` (`QueueNameExists` over JSON).
## Message Retention
@@ -17,6 +17,7 @@ import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -197,6 +198,26 @@ public class SqsJsonHandler {
return Response.ok(response).build();
}
private static MessageAttributeValue messageAttribute(String name, JsonNode attribute) {
return SqsService.messageAttributeValue(name, attribute.path("DataType").asText(null),
attribute.path("StringValue").asText(null), attribute.path("BinaryValue").asText(null));
}
private static int messageAttributesSize(JsonNode attrsNode) {
int size = 0;
if (!attrsNode.isObject()) {
return size;
}
Iterator<Map.Entry<String, JsonNode>> attributes = attrsNode.fields();
while (attributes.hasNext()) {
Map.Entry<String, JsonNode> attribute = attributes.next();
JsonNode value = attribute.getValue();
size += SqsService.messageAttributeSize(attribute.getKey(), value.path("DataType").asText(null),
value.path("StringValue").asText(null), value.path("BinaryValue").asText(null));
}
return size;
}
private Response handleSendMessage(JsonNode request, String region) {
String queueUrl = request.path("QueueUrl").asText(null);
String messageBody = request.path("MessageBody").asText(null);
@@ -208,20 +229,8 @@ public class SqsJsonHandler {
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
JsonNode attrsNode = request.path("MessageAttributes");
if (attrsNode.isObject()) {
attrsNode.fields().forEachRemaining(entry -> {
String name = entry.getKey();
String dataType = entry.getValue().path("DataType").asText(null);
String stringValue = entry.getValue().path("StringValue").asText(null);
String binaryValueBase64 = entry.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));
}
}
});
attrsNode.fields().forEachRemaining(entry ->
messageAttributes.put(entry.getKey(), messageAttribute(entry.getKey(), entry.getValue())));
}
// The AWS SDK only allows AWSTraceHeader to be set via MessageSystemAttributes;
@@ -386,29 +395,23 @@ public class SqsJsonHandler {
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");
totalSize += SqsService.computeMessageSize(messageBody, null) + messageAttributesSize(attrsNode);
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
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));
}
}
});
try {
attrsNode.fields().forEachRemaining(attrEntry -> messageAttributes.put(attrEntry.getKey(),
messageAttribute(attrEntry.getKey(), attrEntry.getValue())));
} catch (AwsException e) {
failed.add(batchFailure(id, e));
continue;
}
}
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));
@@ -435,12 +438,7 @@ public class SqsJsonHandler {
}
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);
failed.add(batchFailure(id, e));
}
}
@@ -452,6 +450,15 @@ public class SqsJsonHandler {
return Response.ok(response).build();
}
private ObjectNode batchFailure(String id, AwsException e) {
ObjectNode fail = objectMapper.createObjectNode();
fail.put("Id", id);
fail.put("Code", e.getErrorCode());
fail.put("Message", e.getMessage());
fail.put("SenderFault", true);
return fail;
}
private Response handleListDeadLetterSourceQueues(JsonNode request, String region) {
String queueUrl = request.path("QueueUrl").asText(null);
List<String> queues = sqsService.listDeadLetterSourceQueues(queueUrl, region);
@@ -227,22 +227,7 @@ public class SqsQueryHandler {
String messageGroupId = getParam(params, "MessageGroupId");
String messageDeduplicationId = getParam(params, "MessageDeduplicationId");
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
for (int i = 1; ; i++) {
String name = getParam(params, "MessageAttribute." + i + ".Name");
if (name == null) break;
String dataType = getParam(params, "MessageAttribute." + i + ".Value.DataType");
String stringValue = getParam(params, "MessageAttribute." + i + ".Value.StringValue");
String binaryValueBase64 = getParam(params, "MessageAttribute." + i + ".Value.BinaryValue");
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));
}
}
}
Map<String, MessageAttributeValue> messageAttributes = messageAttributes(params, "");
// The AWS SDK only allows AWSTraceHeader to be set via MessageSystemAttributes;
// capture it (if present) so ReceiveMessage can return it as a system attribute.
@@ -382,21 +367,15 @@ public class SqsQueryHandler {
String messageGroupId = getParam(params, "SendMessageBatchRequestEntry." + i + ".MessageGroupId");
String messageDeduplicationId = getParam(params, "SendMessageBatchRequestEntry." + i + ".MessageDeduplicationId");
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
for (int j = 1; ; j++) {
String name = getParam(params, "SendMessageBatchRequestEntry." + i + ".MessageAttribute." + j + ".Name");
if (name == null) break;
String dataType = getParam(params, "SendMessageBatchRequestEntry." + i + ".MessageAttribute." + j + ".Value.DataType");
String stringValue = getParam(params, "SendMessageBatchRequestEntry." + i + ".MessageAttribute." + j + ".Value.StringValue");
String binaryValueBase64 = getParam(params, "SendMessageBatchRequestEntry." + i + ".MessageAttribute." + j + ".Value.BinaryValue");
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 entryPrefix = "SendMessageBatchRequestEntry." + i + ".";
totalSize += SqsService.computeMessageSize(body, null) + messageAttributesSize(params, entryPrefix);
Map<String, MessageAttributeValue> messageAttributes;
try {
messageAttributes = messageAttributes(params, entryPrefix);
} catch (AwsException e) {
writeBatchFailure(xml, id, e);
continue;
}
String entryAwsTraceHeader = null;
@@ -410,7 +389,6 @@ public class SqsQueryHandler {
}
}
totalSize += SqsService.computeMessageSize(body, messageAttributes);
parsedEntries.add(new ParsedEntry(id, body, delaySeconds, messageGroupId,
messageDeduplicationId, messageAttributes, entryAwsTraceHeader));
}
@@ -436,18 +414,55 @@ public class SqsQueryHandler {
}
xml.end("SendMessageBatchResultEntry");
} catch (AwsException e) {
xml.start("BatchResultErrorEntry")
.elem("Id", id)
.elem("Code", e.getErrorCode())
.elem("Message", e.getMessage())
.elem("SenderFault", "true")
.end("BatchResultErrorEntry");
writeBatchFailure(xml, id, e);
}
}
return Response.ok(AwsQueryResponse.envelope("SendMessageBatch", null, xml.build())).build();
}
private Map<String, MessageAttributeValue> messageAttributes(MultivaluedMap<String, String> params,
String prefix) {
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
for (int i = 1; ; i++) {
String attributePrefix = prefix + "MessageAttribute." + i;
String name = getParam(params, attributePrefix + ".Name");
if (name == null) {
break;
}
messageAttributes.put(name, SqsService.messageAttributeValue(name,
getParam(params, attributePrefix + ".Value.DataType"),
getParam(params, attributePrefix + ".Value.StringValue"),
getParam(params, attributePrefix + ".Value.BinaryValue")));
}
return messageAttributes;
}
private int messageAttributesSize(MultivaluedMap<String, String> params, String prefix) {
int size = 0;
for (int i = 1; ; i++) {
String attributePrefix = prefix + "MessageAttribute." + i;
String name = getParam(params, attributePrefix + ".Name");
if (name == null) {
break;
}
size += SqsService.messageAttributeSize(name,
getParam(params, attributePrefix + ".Value.DataType"),
getParam(params, attributePrefix + ".Value.StringValue"),
getParam(params, attributePrefix + ".Value.BinaryValue"));
}
return size;
}
private static void writeBatchFailure(XmlBuilder xml, String id, AwsException e) {
xml.start("BatchResultErrorEntry")
.elem("Id", id)
.elem("Code", e.getErrorCode())
.elem("Message", e.getMessage())
.elem("SenderFault", "true")
.end("BatchResultErrorEntry");
}
private Response handleListDeadLetterSourceQueues(MultivaluedMap<String, String> params, String region) {
String queueUrl = getParam(params, "QueueUrl");
List<String> queues = sqsService.listDeadLetterSourceQueues(queueUrl, region);
@@ -42,6 +42,7 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
@@ -1370,6 +1371,83 @@ public class SqsService implements Resettable, ResourceProvider {
}
}
/**
* Builds a message (user) attribute from its wire fields. A BinaryValue takes precedence over a StringValue.
*
* @throws AwsException InvalidParameterValue when the DataType is missing or empty, when its base type (the part
* before the first period) is not String, Number or Binary, when the attribute has no
* value or an empty one, or when the BinaryValue is not valid base64
*/
public static MessageAttributeValue messageAttributeValue(String name, String dataType, String stringValue,
String binaryValueBase64) {
if (dataType == null || dataType.isEmpty()) {
throw new AwsException("InvalidParameterValue", "Missing required parameter DataType", 400);
}
String baseDataType = baseDataType(dataType);
if (!"String".equals(baseDataType) && !"Number".equals(baseDataType) && !"Binary".equals(baseDataType)) {
throw new AwsException("InvalidParameterValue",
"Type for parameter MessageAttributes.Attribute_name.DataType must be prefixed with "
+ "\"String\", \"Binary\", or \"Number\", but was: " + dataType, 400);
}
if (binaryValueBase64 != null) {
byte[] binaryValue;
try {
binaryValue = Base64.getDecoder().decode(binaryValueBase64);
} catch (IllegalArgumentException e) {
throw new AwsException("InvalidParameterValue",
"Message (user) attribute '" + name + "' has an invalid binary value.", 400);
}
if (binaryValue.length == 0) {
throw emptyAttributeValue(name, baseDataType);
}
return new MessageAttributeValue(binaryValue, dataType);
}
if (stringValue == null || stringValue.isEmpty()) {
throw emptyAttributeValue(name, baseDataType);
}
return new MessageAttributeValue(stringValue, dataType);
}
private static AwsException emptyAttributeValue(String name, String baseDataType) {
return new AwsException("InvalidParameterValue", "Message (user) attribute '" + name
+ "' must contain a non-empty value of type '" + baseDataType + "'.", 400);
}
private static String baseDataType(String dataType) {
int dot = dataType.indexOf('.');
return dot < 0 ? dataType : dataType.substring(0, dot);
}
/**
* Wire-level size, in bytes, of one message (user) attribute as sent, whether or not it is valid: name UTF-8 +
* type UTF-8 + value bytes. A BinaryValue counts its decoded length, or its UTF-8 length when it is not base64.
*/
public static int messageAttributeSize(String name, String dataType, String stringValue,
String binaryValueBase64) {
byte[] binaryValue = null;
if (binaryValueBase64 != null) {
try {
binaryValue = Base64.getDecoder().decode(binaryValueBase64);
} catch (IllegalArgumentException e) {
binaryValue = binaryValueBase64.getBytes(StandardCharsets.UTF_8);
}
}
return messageAttributeSize(name, dataType, stringValue, binaryValue);
}
private static int messageAttributeSize(String name, String dataType, String stringValue, byte[] binaryValue) {
int total = name.getBytes(StandardCharsets.UTF_8).length;
if (dataType != null) {
total += dataType.getBytes(StandardCharsets.UTF_8).length;
}
if (binaryValue != null) {
total += binaryValue.length;
} else if (stringValue != null) {
total += stringValue.getBytes(StandardCharsets.UTF_8).length;
}
return total;
}
/**
* Total wire-level message size, in bytes, matching AWS SQS accounting:
* UTF-8 body bytes + per-attribute (name UTF-8 + type UTF-8 + value bytes).
@@ -1380,16 +1458,9 @@ public class SqsService implements Resettable, ResourceProvider {
return total;
}
for (Map.Entry<String, MessageAttributeValue> entry : attributes.entrySet()) {
total += entry.getKey().getBytes(StandardCharsets.UTF_8).length;
MessageAttributeValue value = entry.getValue();
if (value.getDataType() != null) {
total += value.getDataType().getBytes(StandardCharsets.UTF_8).length;
}
if (value.getBinaryValue() != null) {
total += value.getBinaryValue().length;
} else if (value.getStringValue() != null) {
total += value.getStringValue().getBytes(StandardCharsets.UTF_8).length;
}
total += messageAttributeSize(entry.getKey(), value.getDataType(), value.getStringValue(),
value.getBinaryValue());
}
return total;
}
@@ -1076,6 +1076,170 @@ class SqsIntegrationTest {
}
}
@Test
void malformedMessageAttributeValuesAreRejected() {
String attributeQueueUrl = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", "query-attribute-value-queue")
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
try {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", attributeQueueUrl)
.formParam("MessageBody", "x")
.formParam("MessageAttribute.1.Name", "empty")
.formParam("MessageAttribute.1.Value.DataType", "String")
.formParam("MessageAttribute.1.Value.StringValue", "")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Type", equalTo("Sender"))
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
.body("ErrorResponse.Error.Message", equalTo(
"Message (user) attribute 'empty' must contain a non-empty value of type 'String'."));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", attributeQueueUrl)
.formParam("MessageBody", "x")
.formParam("MessageAttribute.1.Name", "bin")
.formParam("MessageAttribute.1.Value.DataType", "Binary")
.formParam("MessageAttribute.1.Value.BinaryValue", "not base64!")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", attributeQueueUrl)
.formParam("MessageBody", "x")
.formParam("MessageAttribute.1.Name", "bin")
.formParam("MessageAttribute.1.Value.DataType", "Binary")
.formParam("MessageAttribute.1.Value.BinaryValue", "")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", attributeQueueUrl)
.formParam("MessageBody", "x")
.formParam("MessageAttribute.1.Name", "novalue")
.formParam("MessageAttribute.1.Value.DataType", "String")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
.body("ErrorResponse.Error.Message", equalTo(
"Message (user) attribute 'novalue' must contain a non-empty value of type 'String'."));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", attributeQueueUrl)
.formParam("MessageBody", "x")
.formParam("MessageAttribute.1.Name", "notype")
.formParam("MessageAttribute.1.Value.StringValue", "v")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
.body("ErrorResponse.Error.Message", equalTo("Missing required parameter DataType"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", attributeQueueUrl)
.formParam("MessageBody", "x")
.formParam("MessageAttribute.1.Name", "odd")
.formParam("MessageAttribute.1.Value.DataType", ".")
.formParam("MessageAttribute.1.Value.StringValue", "v")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
.body("ErrorResponse.Error.Message", equalTo("Type for parameter "
+ "MessageAttributes.Attribute_name.DataType must be prefixed with "
+ "\"String\", \"Binary\", or \"Number\", but was: ."));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessageBatch")
.formParam("QueueUrl", attributeQueueUrl)
.formParam("SendMessageBatchRequestEntry.1.Id", "ok")
.formParam("SendMessageBatchRequestEntry.1.MessageBody", "x")
.formParam("SendMessageBatchRequestEntry.1.MessageAttribute.1.Name", "bin")
.formParam("SendMessageBatchRequestEntry.1.MessageAttribute.1.Value.DataType", "Binary")
.formParam("SendMessageBatchRequestEntry.1.MessageAttribute.1.Value.BinaryValue", "AQID")
.formParam("SendMessageBatchRequestEntry.2.Id", "empty")
.formParam("SendMessageBatchRequestEntry.2.MessageBody", "x")
.formParam("SendMessageBatchRequestEntry.2.MessageAttribute.1.Name", "a")
.formParam("SendMessageBatchRequestEntry.2.MessageAttribute.1.Value.DataType", "Number")
.formParam("SendMessageBatchRequestEntry.2.MessageAttribute.1.Value.StringValue", "")
.formParam("SendMessageBatchRequestEntry.3.Id", "bad-binary")
.formParam("SendMessageBatchRequestEntry.3.MessageBody", "x")
.formParam("SendMessageBatchRequestEntry.3.MessageAttribute.1.Name", "b")
.formParam("SendMessageBatchRequestEntry.3.MessageAttribute.1.Value.DataType", "Binary")
.formParam("SendMessageBatchRequestEntry.3.MessageAttribute.1.Value.BinaryValue", "not base64!")
.when().post("/").then()
.statusCode(200)
.body("SendMessageBatchResponse.SendMessageBatchResult.SendMessageBatchResultEntry.Id", equalTo("ok"))
.body("SendMessageBatchResponse.SendMessageBatchResult.BatchResultErrorEntry.Id",
contains("empty", "bad-binary"))
.body("SendMessageBatchResponse.SendMessageBatchResult.BatchResultErrorEntry.Code",
everyItem(equalTo("InvalidParameterValue")))
.body("SendMessageBatchResponse.SendMessageBatchResult.BatchResultErrorEntry.SenderFault",
everyItem(equalTo("true")));
String bigBody = "x".repeat(400_000);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessageBatch")
.formParam("QueueUrl", attributeQueueUrl)
.formParam("SendMessageBatchRequestEntry.1.Id", "a")
.formParam("SendMessageBatchRequestEntry.1.MessageBody", bigBody)
.formParam("SendMessageBatchRequestEntry.2.Id", "b")
.formParam("SendMessageBatchRequestEntry.2.MessageBody", bigBody)
.formParam("SendMessageBatchRequestEntry.3.Id", "c")
.formParam("SendMessageBatchRequestEntry.3.MessageBody", bigBody)
.formParam("SendMessageBatchRequestEntry.3.MessageAttribute.1.Name", "a")
.formParam("SendMessageBatchRequestEntry.3.MessageAttribute.1.Value.DataType", "String")
.formParam("SendMessageBatchRequestEntry.3.MessageAttribute.1.Value.StringValue", "")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("BatchRequestTooLong"));
String fittingBody = "x".repeat(300_000);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessageBatch")
.formParam("QueueUrl", attributeQueueUrl)
.formParam("SendMessageBatchRequestEntry.1.Id", "a")
.formParam("SendMessageBatchRequestEntry.1.MessageBody", fittingBody)
.formParam("SendMessageBatchRequestEntry.2.Id", "b")
.formParam("SendMessageBatchRequestEntry.2.MessageBody", fittingBody)
.formParam("SendMessageBatchRequestEntry.3.Id", "c")
.formParam("SendMessageBatchRequestEntry.3.MessageBody", fittingBody)
.formParam("SendMessageBatchRequestEntry.3.MessageAttribute.1.Name", "big")
.formParam("SendMessageBatchRequestEntry.3.MessageAttribute.1.Value.StringValue",
"y".repeat(200_000))
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("BatchRequestTooLong"));
assertEquals("1", allQueueAttributes(attributeQueueUrl).get("ApproximateNumberOfMessages"));
} finally {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteQueue")
.formParam("QueueUrl", attributeQueueUrl)
.when().post("/");
}
}
@Test
void receiveMessageReturnsPerMessageSenderId() {
String testQueueUrl = given()
@@ -1085,6 +1085,140 @@ class SqsJsonProtocolTest {
.body("__type", equalTo("InvalidParameterValue"));
}
@Test
void malformedMessageAttributeValuesAreRejected() {
String attributeQueueUrl = given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.CreateQueue")
.body("{\"QueueName\":\"json-attribute-value-queue\"}")
.when().post("/").then().statusCode(200)
.extract().jsonPath().getString("QueueUrl");
try {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.SendMessage")
.body("{\"QueueUrl\":\"" + attributeQueueUrl + "\",\"MessageBody\":\"x\","
+ "\"MessageAttributes\":{\"empty\":{\"DataType\":\"String\",\"StringValue\":\"\"}}}")
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValue"))
.body("message", equalTo(
"Message (user) attribute 'empty' must contain a non-empty value of type 'String'."));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.SendMessage")
.body("{\"QueueUrl\":\"" + attributeQueueUrl + "\",\"MessageBody\":\"x\","
+ "\"MessageAttributes\":{\"count\":{\"DataType\":\"Number.int\",\"StringValue\":\"\"}}}")
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValue"));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.SendMessage")
.body("{\"QueueUrl\":\"" + attributeQueueUrl + "\",\"MessageBody\":\"x\","
+ "\"MessageAttributes\":{\"bin\":{\"DataType\":\"Binary\",\"BinaryValue\":\"not base64!\"}}}")
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValue"));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.SendMessage")
.body("{\"QueueUrl\":\"" + attributeQueueUrl + "\",\"MessageBody\":\"x\","
+ "\"MessageAttributes\":{\"bin\":{\"DataType\":\"Binary\",\"BinaryValue\":\"\"}}}")
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValue"));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.SendMessage")
.body("{\"QueueUrl\":\"" + attributeQueueUrl + "\",\"MessageBody\":\"x\","
+ "\"MessageAttributes\":{\"novalue\":{\"DataType\":\"String\"}}}")
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValue"))
.body("message", equalTo(
"Message (user) attribute 'novalue' must contain a non-empty value of type 'String'."));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.SendMessage")
.body("{\"QueueUrl\":\"" + attributeQueueUrl + "\",\"MessageBody\":\"x\","
+ "\"MessageAttributes\":{\"notype\":{\"StringValue\":\"v\"}}}")
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValue"))
.body("message", equalTo("Missing required parameter DataType"));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.SendMessage")
.body("{\"QueueUrl\":\"" + attributeQueueUrl + "\",\"MessageBody\":\"x\","
+ "\"MessageAttributes\":{\"odd\":{\"DataType\":\"Strin\",\"StringValue\":\"v\"}}}")
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValue"))
.body("message", equalTo("Type for parameter MessageAttributes.Attribute_name.DataType must be "
+ "prefixed with \"String\", \"Binary\", or \"Number\", but was: Strin"));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.SendMessageBatch")
.body("{\"QueueUrl\":\"" + attributeQueueUrl + "\",\"Entries\":["
+ "{\"Id\":\"ok\",\"MessageBody\":\"x\",\"MessageAttributes\":"
+ "{\"bin\":{\"DataType\":\"Binary\",\"BinaryValue\":\"AQID\"}}},"
+ "{\"Id\":\"empty\",\"MessageBody\":\"x\",\"MessageAttributes\":"
+ "{\"a\":{\"DataType\":\"Number\",\"StringValue\":\"\"}}},"
+ "{\"Id\":\"bad-binary\",\"MessageBody\":\"x\",\"MessageAttributes\":"
+ "{\"b\":{\"DataType\":\"Binary\",\"BinaryValue\":\"not base64!\"}}},"
+ "{\"Id\":\"plain\",\"MessageBody\":\"x\"}]}")
.when().post("/").then()
.statusCode(200)
.body("Successful.Id", containsInAnyOrder("ok", "plain"))
.body("Failed.Id", contains("empty", "bad-binary"))
.body("Failed.Code", everyItem(equalTo("InvalidParameterValue")))
.body("Failed.SenderFault", everyItem(equalTo(true)));
String bigBody = "x".repeat(400_000);
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.SendMessageBatch")
.body("{\"QueueUrl\":\"" + attributeQueueUrl + "\",\"Entries\":["
+ "{\"Id\":\"a\",\"MessageBody\":\"" + bigBody + "\"},"
+ "{\"Id\":\"b\",\"MessageBody\":\"" + bigBody + "\"},"
+ "{\"Id\":\"c\",\"MessageBody\":\"" + bigBody + "\",\"MessageAttributes\":"
+ "{\"a\":{\"DataType\":\"String\",\"StringValue\":\"\"}}}]}")
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("BatchRequestTooLong"));
String fittingBody = "x".repeat(300_000);
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.SendMessageBatch")
.body("{\"QueueUrl\":\"" + attributeQueueUrl + "\",\"Entries\":["
+ "{\"Id\":\"a\",\"MessageBody\":\"" + fittingBody + "\"},"
+ "{\"Id\":\"b\",\"MessageBody\":\"" + fittingBody + "\"},"
+ "{\"Id\":\"c\",\"MessageBody\":\"" + fittingBody + "\",\"MessageAttributes\":"
+ "{\"big\":{\"StringValue\":\"" + "y".repeat(200_000) + "\"}}}]}")
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("BatchRequestTooLong"));
assertMessageCounts(attributeQueueUrl, "2", "0");
} finally {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AmazonSQS.DeleteQueue")
.body("{\"QueueUrl\":\"" + attributeQueueUrl + "\"}")
.when().post("/");
}
}
@Test
void redrivePolicyReadsBackAsCompactJson() {
String dlqUrl = given()
@@ -1546,6 +1546,35 @@ class SqsServiceTest {
() -> sqsService.sendMessage(queue.getQueueUrl(), body, 0, null, null, attrs, "us-east-1"));
}
@Test
void messageAttributeSize_countsUtf8BytesOfNameTypeAndStringValue() {
assertEquals(6 + 6 + 6, SqsService.messageAttributeSize("na\u00efve", "String", "\u20acuro", null));
}
@Test
void messageAttributeSize_countsDecodedBinaryLength() {
assertEquals(3 + 6 + 6, SqsService.messageAttributeSize("bin", "Binary", null, "AAECAwQF"));
}
@Test
void messageAttributeSize_countsInvalidBase64AsItsUtf8Length() {
assertEquals(3 + 6 + 11, SqsService.messageAttributeSize("bin", "Binary", null, "not base64!"));
}
@Test
void messageAttributeSize_countsAnAttributeWithNoDataType() {
assertEquals(3 + 5, SqsService.messageAttributeSize("big", null, "value", null));
}
@Test
void computeMessageSize_countsEachAttributeLikeItsWireFields() {
Map<String, MessageAttributeValue> attrs = Map.of(
"na\u00efve", new MessageAttributeValue("\u20acuro", "String"),
"bin", new MessageAttributeValue(new byte[] {0, 1, 2, 3, 4, 5}, "Binary"));
assertEquals(4 + 18 + 15, SqsService.computeMessageSize("body", attrs));
}
@Test
void addPermission_appendsLabelledStatementToPolicy() {
Queue queue = sqsService.createQueue("perm-queue", null, "us-east-1");