Light, fluffy, and always free - The AWS Local Emulator alternative
fix(apigatewayv2): send cookies and comma-joined duplicates in the 2.0 event (#5152)
jwoa95c6369b321a28
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.javaindex f106a90dc7..bcffaba8c0 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java@@ -3220,21 +3220,7 @@ public class ApiGatewayExecuteController {event.put("rawQueryString", uriInfo.getRequestUri().getRawQuery() != null? uriInfo.getRequestUri().getRawQuery() : "");- // Headers (lowercase keys for v2)- ObjectNode headersNode = event.putObject("headers");- MultivaluedMap<String, String> reqHeaders = headers.getRequestHeaders();- for (Map.Entry<String, List<String>> e : reqHeaders.entrySet()) {- if (!e.getValue().isEmpty()) headersNode.put(e.getKey().toLowerCase(), e.getValue().get(0));- }-- // Query string parameters- MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();- if (!queryParams.isEmpty()) {- ObjectNode qsp = event.putObject("queryStringParameters");- for (Map.Entry<String, List<String>> e : queryParams.entrySet()) {- if (!e.getValue().isEmpty()) qsp.put(e.getKey(), e.getValue().get(0));- }- }+ putV2CookiesHeadersAndQuery(event, headers.getRequestHeaders(), uriInfo.getQueryParameters());event.putObject("pathParameters");event.putNull("stageVariables");@@ -3443,21 +3429,10 @@ public class ApiGatewayExecuteController {event.put("routeKey", routeKey != null ? routeKey : "$default");event.put("rawPath", preservedPath);- MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();event.put("rawQueryString", uriInfo.getRequestUri().getRawQuery() != null? uriInfo.getRequestUri().getRawQuery() : "");- ObjectNode headersNode = event.putObject("headers");- for (Map.Entry<String, java.util.List<String>> e : headers.getRequestHeaders().entrySet()) {- if (!e.getValue().isEmpty()) headersNode.put(e.getKey().toLowerCase(), e.getValue().get(0));- }-- if (!queryParams.isEmpty()) {- ObjectNode qsp = event.putObject("queryStringParameters");- for (Map.Entry<String, java.util.List<String>> e : queryParams.entrySet()) {- if (!e.getValue().isEmpty()) qsp.put(e.getKey(), e.getValue().get(0));- }- }+ putV2CookiesHeadersAndQuery(event, headers.getRequestHeaders(), uriInfo.getQueryParameters());Map<String, String> pathParams = extractV2PathParams(routeKey, path);if (!pathParams.isEmpty()) {@@ -3545,6 +3520,58 @@ public class ApiGatewayExecuteController {}}+ /**+ * Writes {@code cookies}, {@code headers} and {@code queryStringParameters} the way payload+ * format 2.0 carries them, for both the Lambda integration event and the Lambda authorizer+ * event. Format 2.0 has no multi-value maps: AWS combines duplicate headers and duplicate+ * query strings with commas, and lists the request's cookies in their own array, which is+ * left out when the request has none.+ */+ private static void putV2CookiesHeadersAndQuery(ObjectNode event,+ MultivaluedMap<String, String> requestHeaders,+ MultivaluedMap<String, String> queryParams) {+ List<String> cookies = v2Cookies(requestHeaders);+ if (!cookies.isEmpty()) {+ ArrayNode cookiesNode = event.putArray("cookies");+ cookies.forEach(cookiesNode::add);+ }++ ObjectNode headersNode = event.putObject("headers");+ for (Map.Entry<String, List<String>> e : requestHeaders.entrySet()) {+ if (!e.getValue().isEmpty()) {+ headersNode.put(e.getKey().toLowerCase(), String.join(",", e.getValue()));+ }+ }++ if (!queryParams.isEmpty()) {+ ObjectNode qsp = event.putObject("queryStringParameters");+ for (Map.Entry<String, List<String>> e : queryParams.entrySet()) {+ if (!e.getValue().isEmpty()) {+ qsp.put(e.getKey(), String.join(",", e.getValue()));+ }+ }+ }+ }++ /** Every cookie-pair from every {@code Cookie} header, in request order. */+ private static List<String> v2Cookies(MultivaluedMap<String, String> requestHeaders) {+ List<String> cookies = new ArrayList<>();+ for (Map.Entry<String, List<String>> e : requestHeaders.entrySet()) {+ if (!HttpHeaders.COOKIE.equalsIgnoreCase(e.getKey())) {+ continue;+ }+ for (String header : e.getValue()) {+ for (String cookie : header.split(";")) {+ String trimmed = cookie.trim();+ if (!trimmed.isEmpty()) {+ cookies.add(trimmed);+ }+ }+ }+ }+ return cookies;+ }+private static boolean isV2TextContentType(String contentType) {if (contentType == null || contentType.isBlank()) {return false;diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventMultiValueTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventMultiValueTest.javanew file mode 100644index 0000000000..c23521494b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventMultiValueTest.java@@ -0,0 +1,124 @@+package io.github.hectorvent.floci.services.apigateway;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.RegionResolver;+import jakarta.ws.rs.core.HttpHeaders;+import jakarta.ws.rs.core.MultivaluedHashMap;+import jakarta.ws.rs.core.MultivaluedMap;+import jakarta.ws.rs.core.UriInfo;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.EnumSource;++import java.net.URI;+import java.util.List;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * Payload format 2.0 has no {@code multiValueHeaders} or {@code multiValueQueryStringParameters}:+ * AWS combines duplicate headers and duplicate query strings with commas, and moves the request's+ * cookies into a {@code cookies} array. See "Payload format differences" in+ * https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html.+ * The Lambda authorizer gets the same 2.0 payload (see the format 2.0 example in+ * https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-lambda-authorizer.html),+ * so every case runs against both builders.+ */+class BuildV2ProxyEventMultiValueTest {++ private ApiGatewayExecuteController controller;+ private HttpHeaders headers;+ private MultivaluedMap<String, String> requestHeaders;+ private UriInfo uriInfo;+ private MultivaluedMap<String, String> queryParams;++ @BeforeEach+ void setUp() throws Exception {+ RegionResolver regionResolver = mock(RegionResolver.class);+ when(regionResolver.getAccountId()).thenReturn("000000000000");++ requestHeaders = new MultivaluedHashMap<>();+ headers = mock(HttpHeaders.class);+ when(headers.getRequestHeaders()).thenReturn(requestHeaders);++ queryParams = new MultivaluedHashMap<>();+ uriInfo = mock(UriInfo.class);+ when(uriInfo.getQueryParameters()).thenReturn(queryParams);+ when(uriInfo.getRequestUri()).thenReturn(new URI("http://localhost:4566/echo"));++ controller = new ApiGatewayExecuteController(+ null, null, null, null,+ regionResolver, new ObjectMapper(), null,+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null);+ }++ enum Builder { INTEGRATION, AUTHORIZER }++ private JsonNode buildEvent(Builder builder) throws Exception {+ String json = switch (builder) {+ case INTEGRATION -> controller.buildV2ProxyEvent(+ "GET", "/echo", "GET /echo",+ "abc123", "us-east-1", "$default", headers, uriInfo, null, "req-1");+ case AUTHORIZER -> controller.buildRequestAuthorizerEventV2(+ "GET", "/echo", "GET /echo",+ "abc123", "$default", "us-east-1", headers, uriInfo);+ };+ return new ObjectMapper().readTree(json);+ }++ @ParameterizedTest+ @EnumSource(Builder.class)+ void repeatedQueryKeyIsCommaJoined(Builder builder) throws Exception {+ queryParams.addAll("q", List.of("1", "2"));+ queryParams.add("single", "x");++ JsonNode qsp = buildEvent(builder).get("queryStringParameters");++ assertEquals("1,2", qsp.get("q").asText());+ assertEquals("x", qsp.get("single").asText());+ }++ @ParameterizedTest+ @EnumSource(Builder.class)+ void repeatedHeaderIsCommaJoined(Builder builder) throws Exception {+ requestHeaders.addAll("X-Trace", List.of("first", "second"));+ requestHeaders.add("X-Single", "only");++ JsonNode headersNode = buildEvent(builder).get("headers");++ assertEquals("first,second", headersNode.get("x-trace").asText());+ assertEquals("only", headersNode.get("x-single").asText());+ }++ @ParameterizedTest+ @EnumSource(Builder.class)+ void cookieHeaderIsSplitIntoCookiesArray(Builder builder) throws Exception {+ requestHeaders.add("Cookie", "a=1; b=2");++ JsonNode cookies = buildEvent(builder).get("cookies");++ assertEquals("[\"a=1\",\"b=2\"]", String.valueOf(cookies));+ }++ @ParameterizedTest+ @EnumSource(Builder.class)+ void everyCookieHeaderContributesToCookiesArray(Builder builder) throws Exception {+ requestHeaders.addAll("cookie", List.of("a=1; b=2", "c=3"));++ JsonNode cookies = buildEvent(builder).get("cookies");++ assertEquals("[\"a=1\",\"b=2\",\"c=3\"]", String.valueOf(cookies));+ }++ @ParameterizedTest+ @EnumSource(Builder.class)+ void requestWithoutCookiesOmitsCookiesField(Builder builder) throws Exception {+ requestHeaders.add("X-Single", "only");++ assertFalse(buildEvent(builder).has("cookies"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiLambdaProxyEventMultiValueIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiLambdaProxyEventMultiValueIntegrationTest.javanew file mode 100644index 0000000000..bc73ad045e--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiLambdaProxyEventMultiValueIntegrationTest.java@@ -0,0 +1,141 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.contains;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;++/**+ * End to end check of the payload format 2.0 event a Lambda proxy integration receives for+ * repeated query keys, repeated headers and cookies. Format 2.0 has no multi-value maps: AWS+ * combines duplicates with commas and moves cookies into a {@code cookies} array.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class HttpApiLambdaProxyEventMultiValueIntegrationTest {++ private static final String FUNCTION_NAME = "httpv2-multi-value-event-fn";++ private static String apiId;++ @Test+ @Order(1)+ void setupLambdaAndHttpApi() throws Exception {+ String zip = WebSocketTestSupport.createLambdaZip("""+ exports.handler = async (event) => ({+ statusCode: 200,+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(event)+ });+ """);++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(FUNCTION_NAME, zip))+ .when().post("/2015-03-31/functions")+ .then().statusCode(201);++ apiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"multi-value-event-test","protocolType":"HTTP"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test"}+ """)+ .when().post("/v2/apis/" + apiId + "/stages")+ .then().statusCode(201);++ String integrationId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST","payloadFormatVersion":"2.0"}+ """.formatted(FUNCTION_NAME))+ .when().post("/v2/apis/" + apiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"GET /echo","target":"integrations/%s"}+ """.formatted(integrationId))+ .when().post("/v2/apis/" + apiId + "/routes")+ .then().statusCode(201);+ }++ @Test+ @Order(10)+ void repeatedQueryKeysAreCommaJoined() {+ given()+ .queryParam("q", "1", "2")+ .queryParam("single", "x")+ .when().get("/execute-api/" + apiId + "/test/echo")+ .then()+ .statusCode(200)+ .body("rawQueryString", equalTo("q=1&q=2&single=x"))+ .body("queryStringParameters.q", equalTo("1,2"))+ .body("queryStringParameters.single", equalTo("x"));+ }++ @Test+ @Order(11)+ void repeatedHeadersAreCommaJoined() {+ given()+ .header("X-Trace", "first")+ .header("X-Trace", "second")+ .when().get("/execute-api/" + apiId + "/test/echo")+ .then()+ .statusCode(200)+ .body("headers.'x-trace'", equalTo("first,second"));+ }++ @Test+ @Order(12)+ void cookieHeaderIsDeliveredAsCookiesArray() {+ given()+ .header("Cookie", "a=1; b=2")+ .when().get("/execute-api/" + apiId + "/test/echo")+ .then()+ .statusCode(200)+ .body("cookies", contains("a=1", "b=2"));+ }++ @Test+ @Order(13)+ void requestWithoutCookiesHasNoCookiesField() {+ given()+ .when().get("/execute-api/" + apiId + "/test/echo")+ .then()+ .statusCode(200)+ .body("cookies", nullValue());+ }++ @Test+ @Order(999)+ void cleanup() throws Exception {+ if (apiId != null) {+ given().when().delete("/v2/apis/" + apiId);+ }+ WebSocketTestSupport.deleteFunctions(FUNCTION_NAME);+ }+}