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

@@ -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;
}