Light, fluffy, and always free - The AWS Local Emulator alternative
fix(apigatewayv2): preserve trailing slash in HTTP API event path (#2367)
Ravi Arnan Irianto64696375082a
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 a667d6b229..b7983114e3 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@@ -1819,16 +1819,30 @@ public class ApiGatewayExecuteController {/*** Builds a REQUEST authorizer event in payload format version 1.0.* Compatible with REST API (v1) REQUEST authorizer shape.+ *+ * <p>Package-private so the shape can be asserted directly, the way {@code buildV2ProxyEvent}+ * is: a REQUEST authorizer's context never reaches the v2 proxy event, so these fields are+ * not observable end to end.*/- private String buildRequestAuthorizerEventV1(String httpMethod, String path,- String apiId, String stageName, String region,- HttpHeaders headers, UriInfo uriInfo) {+ String buildRequestAuthorizerEventV1(String httpMethod, String path,+ String apiId, String stageName, String region,+ HttpHeaders headers, UriInfo uriInfo) {+ // The JAX-RS {proxy} binding strips a trailing slash before dispatchV2 rebuilds the+ // path, so recover it from the raw request URI for the delivered path fields. methodArn+ // keeps the normalized path, as in the REST authorizer event (see toAuthorizerEvent),+ // because it is matched against IAM-style policy resources where a stray trailing slash+ // would silently fail an authorizer's wildcards. `resource` and requestContext.resourcePath+ // do NOT: an HTTP API has no REST-style resource template, so both are copies of the+ // request path here rather than of a matched resource, and AWS's own 1.0 payload example+ // shows `resource` and `path` carrying the same value.+ String preservedPath = preserveTrailingSlash(path, uriInfo.getRequestUri().getRawPath());+ObjectNode event = objectMapper.createObjectNode();event.put("version", "1.0");event.put("type", "REQUEST");event.put("methodArn", buildMethodArn(region, apiId, stageName, httpMethod, path));- event.put("resource", path);- event.put("path", path);+ event.put("resource", preservedPath);+ event.put("path", preservedPath);event.put("httpMethod", httpMethod);putSingleValueHeaders(event, headers);@@ -1844,8 +1858,8 @@ public class ApiGatewayExecuteController {ctx.put("accountId", regionResolver.getAccountId());ctx.put("apiId", apiId);ctx.put("httpMethod", httpMethod);- ctx.put("path", path);- ctx.put("resourcePath", path);+ ctx.put("path", preservedPath);+ ctx.put("resourcePath", preservedPath);ctx.put("stage", stageName);ctx.put("requestId", UUID.randomUUID().toString());@@ -1863,12 +1877,17 @@ public class ApiGatewayExecuteController {private String buildRequestAuthorizerEventV2(String httpMethod, String path, String routeKey,String apiId, String stageName, String region,HttpHeaders headers, UriInfo uriInfo) {+ // rawPath is by contract the raw, unmodified path, so recover the trailing slash the+ // JAX-RS {proxy} binding stripped. routeArn keeps the normalized path for the same reason+ // methodArn does in the 1.0 shape above.+ String preservedPath = preserveTrailingSlash(path, uriInfo.getRequestUri().getRawPath());+ObjectNode event = objectMapper.createObjectNode();event.put("version", "2.0");event.put("type", "REQUEST");event.put("routeArn", buildMethodArn(region, apiId, stageName, httpMethod, path));event.put("routeKey", routeKey != null ? routeKey : "$default");- event.put("rawPath", path);+ event.put("rawPath", preservedPath);event.put("rawQueryString", uriInfo.getRequestUri().getRawQuery() != null? uriInfo.getRequestUri().getRawQuery() : "");@@ -1907,7 +1926,7 @@ public class ApiGatewayExecuteController {ObjectNode http = ctx.putObject("http");http.put("method", httpMethod);- http.put("path", path);+ http.put("path", preservedPath);http.put("protocol", "HTTP/1.1");http.put("sourceIp", "127.0.0.1");http.put("userAgent", headers.getHeaderString("User-Agent") != null@@ -2011,10 +2030,17 @@ public class ApiGatewayExecuteController {String apiId, String region, String stageName,HttpHeaders headers, UriInfo uriInfo,byte[] body, String requestId, Map<String, String> jwtClaims) {+ // The JAX-RS {proxy} binding strips a trailing slash, but rawPath is by contract the+ // raw path and routers treat /x and /x/ as distinct routes. Recover it from the raw+ // request URI for the event path fields. Route matching in dispatchV2 and the+ // pathParameters extraction below continue to use the normalized `path`, mirroring what+ // buildProxyEvent already does for REST (V1).+ String preservedPath = preserveTrailingSlash(path, uriInfo.getRequestUri().getRawPath());+ObjectNode event = objectMapper.createObjectNode();event.put("version", "2.0");event.put("routeKey", routeKey != null ? routeKey : "$default");- event.put("rawPath", path);+ event.put("rawPath", preservedPath);MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();event.put("rawQueryString", uriInfo.getRequestUri().getRawQuery() != null@@ -2052,7 +2078,7 @@ public class ApiGatewayExecuteController {ObjectNode http = ctx.putObject("http");http.put("method", httpMethod);- http.put("path", path);+ http.put("path", preservedPath);http.put("protocol", "HTTP/1.1");http.put("sourceIp", "127.0.0.1");http.put("userAgent", headers.getHeaderString("User-Agent") != nulldiff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.javanew file mode 100644index 0000000000..d54bcef598--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.java@@ -0,0 +1,94 @@+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.UriInfo;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.net.URI;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * Verifies the trailing-slash field split in the HTTP API REQUEST authorizer event, payload+ * format 1.0 ({@code buildRequestAuthorizerEventV1}).+ *+ * <p>{@code resource}, {@code path} and {@code requestContext.resourcePath} are copies of the+ * request path in this shape, because an HTTP API has no REST-style resource template, so all+ * three carry the delivered path. {@code methodArn} stays normalized: it is matched against+ * IAM-style policy resources, where a stray trailing slash silently fails an authorizer's+ * wildcards.+ */+class BuildV2AuthorizerEventTrailingSlashTest {++ private ApiGatewayExecuteController controller;+ private HttpHeaders headers;+ private UriInfo uriInfo;++ @BeforeEach+ void setUp() {+ RegionResolver regionResolver = mock(RegionResolver.class);+ when(regionResolver.getAccountId()).thenReturn("000000000000");++ headers = mock(HttpHeaders.class);+ when(headers.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());++ uriInfo = mock(UriInfo.class);+ when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());++ controller = new ApiGatewayExecuteController(+ null, null, null,+ regionResolver, new ObjectMapper(), null,+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null+ );+ }++ private JsonNode buildEvent(String normalizedPath, String rawRequestUri) throws Exception {+ when(uriInfo.getRequestUri()).thenReturn(new URI(rawRequestUri));+ String json = controller.buildRequestAuthorizerEventV1(+ "GET", normalizedPath, "abc123", "test", "us-east-1", headers, uriInfo);+ return new ObjectMapper().readTree(json);+ }++ @Test+ void deliveredPathFieldsKeepTrailingSlash() throws Exception {+ JsonNode event = buildEvent("/thing", "http://localhost:4566/api/test/thing/");+ assertEquals("/thing/", event.get("path").asText(),+ "path is the delivered request path");+ assertEquals("/thing/", event.get("resource").asText(),+ "an HTTP API has no resource template, so resource mirrors path");+ assertEquals("/thing/", event.get("requestContext").get("path").asText());+ assertEquals("/thing/", event.get("requestContext").get("resourcePath").asText(),+ "requestContext.resourcePath mirrors resource");+ }++ @Test+ void methodArnStaysNormalized() throws Exception {+ JsonNode event = buildEvent("/thing", "http://localhost:4566/api/test/thing/");+ assertTrue(event.get("methodArn").asText().endsWith("abc123/test/GET/thing"),+ "methodArn is matched against IAM-style policy resources, so it keeps the "+ + "normalized path: was " + event.get("methodArn").asText());+ }++ @Test+ void requestWithoutTrailingSlashIsUnchanged() throws Exception {+ JsonNode event = buildEvent("/thing", "http://localhost:4566/api/test/thing");+ assertEquals("/thing", event.get("path").asText());+ assertEquals("/thing", event.get("resource").asText());+ assertEquals("/thing", event.get("requestContext").get("resourcePath").asText());+ }++ @Test+ void rootPathIsUnchanged() throws Exception {+ JsonNode event = buildEvent("/", "http://localhost:4566/api/test/");+ assertEquals("/", event.get("path").asText());+ assertEquals("/", event.get("resource").asText());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventTrailingSlashTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventTrailingSlashTest.javanew file mode 100644index 0000000000..c2eed8a169--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventTrailingSlashTest.java@@ -0,0 +1,95 @@+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.UriInfo;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.net.URI;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * Verifies that {@link ApiGatewayExecuteController#buildV2ProxyEvent} preserves a trailing+ * slash in the HTTP API (V2) event path fields, the way {@code buildProxyEvent} already does+ * for REST (V1) since #1557. The JAX-RS {@code {proxy}} binding strips it, so the raw request+ * URI is the only place it survives.+ *+ * <p>Mirrors the V1 settlement: {@code rawPath} and {@code requestContext.http.path} keep the+ * slash, while {@code pathParameters} stay normalized because they come from the matcher.+ */+class BuildV2ProxyEventTrailingSlashTest {++ private ApiGatewayExecuteController controller;+ private HttpHeaders headers;+ private UriInfo uriInfo;++ @BeforeEach+ void setUp() {+ RegionResolver regionResolver = mock(RegionResolver.class);+ when(regionResolver.getAccountId()).thenReturn("000000000000");++ headers = mock(HttpHeaders.class);+ when(headers.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());+ when(headers.getHeaderString("User-Agent")).thenReturn(null);++ uriInfo = mock(UriInfo.class);+ when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());++ controller = new ApiGatewayExecuteController(+ null, null, null,+ regionResolver, new ObjectMapper(), null,+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null+ );+ }++ private JsonNode buildEvent(String normalizedPath, String rawRequestUri, String routeKey) throws Exception {+ when(uriInfo.getRequestUri()).thenReturn(new URI(rawRequestUri));+ String json = controller.buildV2ProxyEvent(+ "GET", normalizedPath, routeKey,+ "abc123", "us-east-1", "$default", headers, uriInfo, null, "req-1");+ return new ObjectMapper().readTree(json);+ }++ @Test+ void rawPathKeepsTrailingSlashFromRawRequestUri() throws Exception {+ JsonNode event = buildEvent("/thing", "http://localhost:4566/api/stage/thing/", "$default");+ assertEquals("/thing/", event.get("rawPath").asText(),+ "rawPath is by contract the raw path, so the trailing slash must survive");+ }++ @Test+ void requestContextHttpPathKeepsTrailingSlash() throws Exception {+ JsonNode event = buildEvent("/thing", "http://localhost:4566/api/stage/thing/", "$default");+ assertEquals("/thing/", event.get("requestContext").get("http").get("path").asText(),+ "requestContext.http.path mirrors rawPath on real AWS");+ }++ @Test+ void pathParametersStayNormalized() throws Exception {+ JsonNode event = buildEvent("/thing", "http://localhost:4566/api/stage/thing/", "ANY /{proxy+}");+ assertEquals("/thing/", event.get("rawPath").asText());+ assertEquals("thing", event.get("pathParameters").get("proxy").asText(),+ "pathParameters come from the matcher, which runs on the normalized path");+ }++ @Test+ void requestWithoutTrailingSlashIsUnchanged() throws Exception {+ JsonNode event = buildEvent("/thing", "http://localhost:4566/api/stage/thing", "$default");+ assertEquals("/thing", event.get("rawPath").asText());+ assertEquals("/thing", event.get("requestContext").get("http").get("path").asText());+ }++ @Test+ void rootPathIsUnchanged() throws Exception {+ JsonNode event = buildEvent("/", "http://localhost:4566/api/stage/", "$default");+ assertEquals("/", event.get("rawPath").asText());+ assertEquals("/", event.get("requestContext").get("http").get("path").asText());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.javaindex 0c4bb62f2a..d322b93126 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java@@ -534,6 +534,36 @@ class HttpApiRequestAuthorizerTest {.then().statusCode(200);}+ // ──────────────────────── Trailing slash preservation (#2136) ────────────────────────++ /**+ * A trailing slash is significant in the delivered path, and rawPath is by contract the raw+ * path. The route key stays {@code GET /hello}, so route matching still runs on the+ * normalized path while the Lambda receives the slash. REST (V1) has behaved this way since+ * #1557; this pins the same behaviour for HTTP APIs.+ */+ @Test+ @Order(110)+ void trailingSlashReachesTheLambdaRawPath() throws Exception {+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"authorizationType":"NONE","authorizerId":null}+ """)+ .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId)+ .then().statusCode(200);++ String body = given()+ .when().get("/execute-api/" + httpApiId + "/test/hello/")+ .then().statusCode(200)+ .extract().asString();++ // The backend Lambda echoes event.rawPath back as "path".+ JsonNode response = MAPPER.readTree(body);+ assertEquals("/hello/", response.path("path").asText(),+ "rawPath must keep the trailing slash the JAX-RS {proxy} binding strips");+ }+// ──────────────────────────── Cleanup ────────────────────────────@Test