Light, fluffy, and always free - The AWS Local Emulator alternative
fix(sqs): send JSON responses with content length (#6209)
Jimmy Liu Jiad7c139cb6933
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.javaindex aa4ab70f07..03822340de 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java@@ -205,6 +205,18 @@ public class AwsJsonController {}return DynamoDbResponses.withCrc32(response, objectMapper);}+ if ("sqs".equals(serviceKey) && response.getEntity() != null+ && !(response.getEntity() instanceof byte[])) {+ byte[] bodyBytes = JsonResponseBytes.serializeOrNull(response.getEntity(), objectMapper,+ LOG, "Failed to serialize SQS JSON response");+ if (bodyBytes == null) {+ return response;+ }+ return Response.fromResponse(response)+ .entity(bodyBytes)+ .type(CONTENT_TYPE_AWS_JSON_1_0)+ .build();+ }return response;}}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/JsonResponseBytes.java b/src/main/java/io/github/hectorvent/floci/core/common/JsonResponseBytes.javanew file mode 100644index 0000000000..d08c228ed5--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/core/common/JsonResponseBytes.java@@ -0,0 +1,25 @@+package io.github.hectorvent.floci.core.common;++import com.fasterxml.jackson.databind.ObjectMapper;+import org.jboss.logging.Logger;++public final class JsonResponseBytes {++ private JsonResponseBytes() {}++ public static byte[] serializeOrNull(Object entity, ObjectMapper objectMapper,+ Logger logger, String failureMessage) {+ try {+ if (entity == null) {+ return new byte[0];+ }+ if (entity instanceof byte[] bytes) {+ return bytes;+ }+ return objectMapper.writeValueAsBytes(entity);+ } catch (Exception e) {+ logger.warn(failureMessage, e);+ return null;+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbResponses.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbResponses.javaindex d39d07a8f6..12d7dfaf2c 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbResponses.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbResponses.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.dynamodb;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.JsonResponseBytes;import jakarta.ws.rs.core.MediaType;import jakarta.ws.rs.core.MultivaluedMap;import jakarta.ws.rs.core.Response;@@ -59,18 +60,9 @@ public final class DynamoDbResponses {if (response == null) {return null;}- Object entity = response.getEntity();- byte[] bodyBytes;- try {- if (entity == null) {- bodyBytes = new byte[0];- } else if (entity instanceof byte[] b) {- bodyBytes = b;- } else {- bodyBytes = objectMapper.writeValueAsBytes(entity);- }- } catch (Exception e) {- LOG.warn("Failed to serialize DynamoDB response for CRC32 computation", e);+ byte[] bodyBytes = JsonResponseBytes.serializeOrNull(response.getEntity(), objectMapper,+ LOG, "Failed to serialize DynamoDB response for CRC32 computation");+ if (bodyBytes == null) {return response;}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AwsJsonControllerSerializationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AwsJsonControllerSerializationTest.javanew file mode 100644index 0000000000..b453bfec8a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/core/common/AwsJsonControllerSerializationTest.java@@ -0,0 +1,54 @@+package io.github.hectorvent.floci.core.common;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;+import jakarta.ws.rs.core.HttpHeaders;+import jakarta.ws.rs.core.Response;+import org.junit.jupiter.api.Test;++import java.util.Optional;+import java.util.Set;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++class AwsJsonControllerSerializationTest {++ @Test+ void sqsSerializationFailurePreservesOriginalResponse() throws Exception {+ ObjectMapper mapper = new ObjectMapper() {+ @Override+ public byte[] writeValueAsBytes(Object value) throws JsonProcessingException {+ throw new JsonProcessingException("expected serialization failure") {};+ }+ };+ ResolvedServiceCatalog catalog = mock(ResolvedServiceCatalog.class);+ ServiceDescriptor descriptor = new ServiceDescriptor("sqs", "sqs", true, true,+ "sqs", "memory", 0, null, ServiceProtocol.QUERY, Set.of(ServiceProtocol.JSON),+ Set.of("AmazonSQS."), Set.of("sqs"), Set.of(), Set.of(), Set.of());+ when(catalog.matchTarget("AmazonSQS.Test"))+ .thenReturn(Optional.of(new ServiceCatalog.TargetMatch(descriptor, "AmazonSQS.", "Test")));+ RegionResolver regionResolver = mock(RegionResolver.class);+ HttpHeaders headers = mock(HttpHeaders.class);+ when(regionResolver.resolveRegion(headers)).thenReturn("us-east-1");+ SqsJsonHandler sqs = mock(SqsJsonHandler.class);+ Object entity = new Object();+ Response original = Response.status(202).entity(entity)+ .header("x-amzn-query-error", "example;Sender").build();+ when(sqs.handle(eq("Test"), any(), eq("us-east-1"))).thenReturn(original);++ AwsJsonController controller = new AwsJsonController(mapper, catalog, regionResolver,+ null, null, sqs, null, null, null, null, null, null, null, null, null, null);+ Response result = controller.handleJsonRequest("AmazonSQS.Test", headers, "{}");++ assertSame(original, result);+ assertEquals(202, result.getStatus());+ assertSame(entity, result.getEntity());+ assertEquals("example;Sender", result.getHeaderString("x-amzn-query-error"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbResponsesTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbResponsesTest.javaindex 118523ab5c..2bb52f6f12 100644--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbResponsesTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbResponsesTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.dynamodb;+import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ObjectNode;import jakarta.ws.rs.core.MediaType;@@ -114,6 +115,21 @@ class DynamoDbResponsesTest {assertNull(DynamoDbResponses.withCrc32(null, mapper));}+ @Test+ void withCrc32_serializationFailurePreservesOriginalResponse() {+ ObjectMapper failingMapper = new ObjectMapper() {+ @Override+ public byte[] writeValueAsBytes(Object value) throws JsonProcessingException {+ throw new JsonProcessingException("expected serialization failure") {};+ }+ };+ Response original = Response.status(202).entity(new Object())+ .header("x-amzn-requestid", "request-123").build();++ assertSame(original, DynamoDbResponses.withCrc32(original, failingMapper));+ assertNull(original.getHeaderString("X-Amz-Crc32"));+ }+@Testvoid legacyErrorsRetainMessageHeadersAndOriginalBackendBody() {ObjectNode entity = mapper.createObjectNode()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 5ae9ae3050..605718f4d6 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@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.sqs;import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.Response;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.MethodOrderer;import org.junit.jupiter.api.Order;@@ -14,6 +15,7 @@ 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.assertNull;import static org.junit.jupiter.api.Assertions.assertTrue;/**@@ -955,6 +957,58 @@ class SqsJsonProtocolTest {}}+ @Test+ void largeJsonReceiveMessageUsesContentLength() {+ String framingQueueUrl = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.CreateQueue")+ .body("{\"QueueName\":\"json-response-framing-queue\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().jsonPath().getString("QueueUrl");+ try {+ String messageBody = "x".repeat(12_000);+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.SendMessage")+ .body("{\"QueueUrl\":\"" + framingQueueUrl + "\",\"MessageBody\":\"" + messageBody + "\"}")+ .when().post("/")+ .then().statusCode(200);++ for (String path : List.of("/", "/" + ACCOUNT_ID + "/json-response-framing-queue")) {+ Response response = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.ReceiveMessage")+ .body("{\"QueueUrl\":\"" + framingQueueUrl+ + "\",\"MaxNumberOfMessages\":1,\"VisibilityTimeout\":0}")+ .when().post(path)+ .then().statusCode(200)+ .body("Messages[0].Body", equalTo(messageBody))+ .extract().response();++ int bodyLength = response.asByteArray().length;+ assertTrue(bodyLength > 8_191);+ assertEquals(Integer.toString(bodyLength), response.getHeader("Content-Length"));+ assertNull(response.getHeader("Transfer-Encoding"));+ }++ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.ReceiveMessage")+ .body("{\"QueueUrl\":\"" + framingQueueUrl + "\",\"WaitTimeSeconds\":21}")+ .when().post("/")+ .then().statusCode(400)+ .header("x-amzn-query-error", equalTo("InvalidParameterValue;Sender"))+ .body("__type", equalTo("InvalidParameterValue"));+ } finally {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.DeleteQueue")+ .body("{\"QueueUrl\":\"" + framingQueueUrl + "\"}")+ .when().post("/");+ }+ }+private static void assertMessageCounts(String url, String visible, String notVisible) {given().contentType(CONTENT_TYPE)