diff --git a/docs/services/sqs.md b/docs/services/sqs.md index 99485c01a3..8026bc1ad2 100644 --- a/docs/services/sqs.md +++ b/docs/services/sqs.md @@ -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 diff --git a/src/main/java/io/floci/aws/services/sqs/SqsJsonHandler.java b/src/main/java/io/floci/aws/services/sqs/SqsJsonHandler.java index 800919a172..f284fea293 100644 --- a/src/main/java/io/floci/aws/services/sqs/SqsJsonHandler.java +++ b/src/main/java/io/floci/aws/services/sqs/SqsJsonHandler.java @@ -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> attributes = attrsNode.fields(); + while (attributes.hasNext()) { + Map.Entry 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 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 messageAttributes = new HashMap<>(); JsonNode attrsNode = entry.path("MessageAttributes"); + totalSize += SqsService.computeMessageSize(messageBody, null) + messageAttributesSize(attrsNode); + + Map 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 queues = sqsService.listDeadLetterSourceQueues(queueUrl, region); diff --git a/src/main/java/io/floci/aws/services/sqs/SqsQueryHandler.java b/src/main/java/io/floci/aws/services/sqs/SqsQueryHandler.java index 12bb35bafd..5ef9203856 100644 --- a/src/main/java/io/floci/aws/services/sqs/SqsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/sqs/SqsQueryHandler.java @@ -227,22 +227,7 @@ public class SqsQueryHandler { String messageGroupId = getParam(params, "MessageGroupId"); String messageDeduplicationId = getParam(params, "MessageDeduplicationId"); - Map 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 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 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 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 messageAttributes(MultivaluedMap params, + String prefix) { + Map 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 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 params, String region) { String queueUrl = getParam(params, "QueueUrl"); List queues = sqsService.listDeadLetterSourceQueues(queueUrl, region); diff --git a/src/main/java/io/floci/aws/services/sqs/SqsService.java b/src/main/java/io/floci/aws/services/sqs/SqsService.java index f01fe5d7d1..d999226042 100644 --- a/src/main/java/io/floci/aws/services/sqs/SqsService.java +++ b/src/main/java/io/floci/aws/services/sqs/SqsService.java @@ -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 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; } diff --git a/src/test/java/io/floci/aws/services/sqs/SqsIntegrationTest.java b/src/test/java/io/floci/aws/services/sqs/SqsIntegrationTest.java index 6a8e0720e6..e3b1d0f9d2 100644 --- a/src/test/java/io/floci/aws/services/sqs/SqsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/sqs/SqsIntegrationTest.java @@ -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() diff --git a/src/test/java/io/floci/aws/services/sqs/SqsJsonProtocolTest.java b/src/test/java/io/floci/aws/services/sqs/SqsJsonProtocolTest.java index 2659ed3a7c..d4860b01db 100644 --- a/src/test/java/io/floci/aws/services/sqs/SqsJsonProtocolTest.java +++ b/src/test/java/io/floci/aws/services/sqs/SqsJsonProtocolTest.java @@ -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() diff --git a/src/test/java/io/floci/aws/services/sqs/SqsServiceTest.java b/src/test/java/io/floci/aws/services/sqs/SqsServiceTest.java index ad163203f8..0e94e8549b 100644 --- a/src/test/java/io/floci/aws/services/sqs/SqsServiceTest.java +++ b/src/test/java/io/floci/aws/services/sqs/SqsServiceTest.java @@ -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 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");