diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index efb22a9fba..f2a1d86cb5 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -232,8 +232,8 @@ Rejections are `403`, and never reach the integration: | Signature mismatch | `The request signature we calculated does not match…` / `InvalidSignatureException` | `Forbidden` | A verified caller reaches the integration as `requestContext.identity.{accessKey, accountId, caller, -user, userArn}` on a REST proxy event, and as `requestContext.authorizer.iam` on an HTTP API 2.0 -event. +user, userArn}` on a REST proxy or HTTP API 1.0 event, and as `requestContext.authorizer.iam` on an +HTTP API 2.0 event. As on AWS, a REST (v1) `AWS_PROXY` or `HTTP_PROXY` integration never receives the caller's `Authorization` header when the method is `AWS_IAM`, and on any method the header is dropped if it 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.java index 8bff5614c9..0f1adf82d6 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 @@ -2622,16 +2622,24 @@ public class ApiGatewayExecuteController { } String requestId = UUID.randomUUID().toString(); - String eventJson = buildV2ProxyEvent(httpMethod, path, route.getRouteKey(), - apiId, region, stageName, headers, uriInfo, body, requestId, jwtClaims, jwtScopes, - lambdaAuthorizerContext, iamIdentity); + boolean payloadV1 = "1.0".equals(integration.getPayloadFormatVersion()); + Map stageVariables = payloadV1 + ? apiGatewayV2Service.getStage(region, apiId, stageName).getStageVariables() + : null; + String eventJson = payloadV1 + ? buildV1ProxyEvent(httpMethod, path, route.getRouteKey(), + apiId, region, stageName, stageVariables, headers, uriInfo, body, requestId, + jwtClaims, jwtScopes, lambdaAuthorizerContext, iamIdentity) + : buildV2ProxyEvent(httpMethod, path, route.getRouteKey(), + apiId, region, stageName, headers, uriInfo, body, requestId, jwtClaims, jwtScopes, + lambdaAuthorizerContext, iamIdentity); LOG.debugv("execute-api v2: {0} {1}/{2}{3} → Lambda {4}", httpMethod, apiId, stageName, path, functionName); try { InvokeResult result = lambdaService.invoke(region, functionName, eventJson.getBytes(), InvocationType.RequestResponse); - return buildProxyResponse(result, true, !"1.0".equals(integration.getPayloadFormatVersion())); + return buildProxyResponse(result, true, !payloadV1); } catch (AwsException e) { if (e.getHttpStatus() == 404) { return Response.status(404) @@ -3398,6 +3406,72 @@ public class ApiGatewayExecuteController { }; } + /** Reuses the REST v1 event shape, then applies the documented HTTP API v1 differences. */ + String buildV1ProxyEvent(String httpMethod, String path, String routeKey, + String apiId, String region, String stageName, + Map stageVariables, + HttpHeaders headers, UriInfo uriInfo, byte[] body, String requestId, + Map jwtClaims, List jwtScopes, + ObjectNode lambdaAuthorizerContext, + ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) { + String[] routeParts = routeKey == null ? new String[0] : routeKey.split("\\s+", 2); + String resourcePath = routeParts.length == 2 ? routeParts[1] : path; + String json = buildProxyEvent(region, apiId, httpMethod, path, resourcePath, null, + stageName, null, headers, uriInfo, body, requestId, null, null, null, iamIdentity); + + try { + ObjectNode event = (ObjectNode) objectMapper.readTree(json); + event.put("version", "1.0"); + if (stageVariables != null && !stageVariables.isEmpty()) { + ObjectNode variables = event.putObject("stageVariables"); + stageVariables.forEach(variables::put); + } + + Map> lowercaseHeaders = new LinkedHashMap<>(); + headers.getRequestHeaders().forEach((name, values) -> + lowercaseHeaders.computeIfAbsent(name.toLowerCase(Locale.ROOT), ignored -> new ArrayList<>()) + .addAll(values)); + putSingleValueHeaders(event, lowercaseHeaders); + putMultiValueHeaders(event, lowercaseHeaders); + + if (event.path("pathParameters").isEmpty()) { + event.putNull("pathParameters"); + } + + ObjectNode context = (ObjectNode) event.path("requestContext"); + context.putNull("resourceId"); + // Payload 1.0 keeps claims and scopes directly under authorizer; jwt belongs to 2.0. + if (jwtClaims != null) { + ObjectNode authorizer = context.putObject("authorizer"); + ObjectNode claims = authorizer.putObject("claims"); + jwtClaims.forEach(claims::put); + if (jwtScopes == null) { + authorizer.putNull("scopes"); + } else { + ArrayNode scopes = authorizer.putArray("scopes"); + jwtScopes.forEach(scopes::add); + } + } else if (lambdaAuthorizerContext != null) { + context.putObject("authorizer").set("lambda", lambdaAuthorizerContext); + } else { + ObjectNode authorizer = context.putObject("authorizer"); + authorizer.putNull("claims"); + authorizer.putNull("scopes"); + } + + if (body != null && body.length > 0) { + boolean isText = isV2TextContentType(headers.getHeaderString(HttpHeaders.CONTENT_TYPE)); + event.put("body", isText + ? new String(body, StandardCharsets.UTF_8) + : Base64.getEncoder().encodeToString(body)); + event.put("isBase64Encoded", !isText); + } + return objectMapper.writeValueAsString(event); + } catch (Exception e) { + throw new RuntimeException("Failed to serialize v1 proxy event", e); + } + } + String buildV2ProxyEvent(String httpMethod, String path, String routeKey, String apiId, String region, String stageName, HttpHeaders headers, UriInfo uriInfo, diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java index 5f36bc33c4..4c7962a263 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java @@ -620,6 +620,48 @@ class ApiGatewayExecuteControllerTest { new byte[0], "req-1", null, null, null, null)); } + @Test + void payloadFormatOneUsesV1EventShape() throws Exception { + ApiGatewayExecuteController controller = controller(new ObjectMapper()); + UriInfo uriInfo = uriInfoFor("http://localhost/echo-v1?q=1&q=2"); + MultivaluedMap query = new MultivaluedHashMap<>(); + query.addAll("q", "1", "2"); + when(uriInfo.getQueryParameters()).thenReturn(query); + HttpHeaders headers = emptyHeaders(); + MultivaluedMap requestHeaders = new MultivaluedHashMap<>(); + requestHeaders.addAll("X-Trace", "first", "second"); + when(headers.getRequestHeaders()).thenReturn(requestHeaders); + + JsonNode event = new ObjectMapper().readTree(controller.buildV1ProxyEvent( + "GET", "/echo-v1", "GET /echo-v1", "api1", "us-east-1", "test", + Map.of("environment", "review"), headers, uriInfo, new byte[0], "req-1", + Map.of("sub", "user-1"), List.of("read"), null, null)); + + assertEquals("1.0", event.path("version").asText()); + assertEquals("/echo-v1", event.path("resource").asText()); + assertEquals("/echo-v1", event.path("path").asText()); + assertEquals("GET", event.path("httpMethod").asText()); + assertTrue(event.path("rawPath").isMissingNode()); + assertTrue(event.path("pathParameters").isNull()); + assertEquals("review", event.path("stageVariables").path("environment").asText()); + assertTrue(event.path("requestContext").path("resourceId").isNull()); + assertTrue(event.path("requestContext").path("requestTime").isTextual()); + assertTrue(event.path("requestContext").path("requestTimeEpoch").asLong() > 0); + assertTrue(event.path("requestContext").path("routeKey").isMissingNode()); + assertTrue(event.path("requestContext").path("time").isMissingNode()); + assertTrue(event.path("requestContext").path("timeEpoch").isMissingNode()); + assertEquals("user-1", event.path("requestContext").path("authorizer").path("claims") + .path("sub").asText()); + assertEquals("read", event.path("requestContext").path("authorizer").path("scopes") + .path(0).asText()); + assertTrue(event.path("requestContext").path("authorizer").path("jwt").isMissingNode()); + assertEquals("second", event.path("headers").path("x-trace").asText()); + assertTrue(event.path("headers").path("X-Trace").isMissingNode()); + JsonNode queryValues = event.path("multiValueQueryStringParameters").path("q"); + assertEquals("1", queryValues.path(0).asText()); + assertEquals("2", queryValues.path(1).asText()); + } + @Test void v2RequestAuthorizerEventTimeIsEnglishUtcUnderNonUtcHost() throws Exception { ApiGatewayExecuteController controller = controller(new ObjectMapper()); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java index ed3c599f5b..a6e7fc4e9e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java @@ -13,6 +13,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.net.URI; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -132,6 +133,19 @@ class ProxyEventIamIdentityTest { "a route with no authorizer must not grow an authorizer node"); } + @Test + void httpApiPayloadOneKeepsTheSignatureHeader() throws Exception { + requestHeaders.add("Authorization", SIGV4); + + JsonNode event = MAPPER.readTree(controller.buildV1ProxyEvent( + "GET", "/iam", "GET /iam", "api1", "us-east-1", "test", Map.of(), + headers, uriInfo, null, "req-v1", null, null, null, CALLER)); + + assertEquals(SIGV4, event.path("headers").path("authorization").asText()); + assertEquals(SIGV4, + event.path("multiValueHeaders").path("authorization").path(0).asText()); + } + @Test void awsIamMethodDropsTheSignatureButKeepsTheOtherSigningHeaders() throws Exception { requestHeaders.add("Authorization", SIGV4); 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.java index bc73ad045e..157bcd79ea 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiLambdaProxyEventMultiValueIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiLambdaProxyEventMultiValueIntegrationTest.java @@ -14,9 +14,8 @@ 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. + * End to end checks of the events Lambda proxy integrations receive. Format 2.0 combines repeated + * values and moves cookies into a {@code cookies} array, while format 1.0 keeps multi-value maps. */ @QuarkusTest @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @@ -59,7 +58,7 @@ class HttpApiLambdaProxyEventMultiValueIntegrationTest { given() .contentType(ContentType.JSON) .body(""" - {"stageName":"test"} + {"stageName":"test","stageVariables":{"environment":"review"}} """) .when().post("/v2/apis/" + apiId + "/stages") .then().statusCode(201); @@ -81,6 +80,24 @@ class HttpApiLambdaProxyEventMultiValueIntegrationTest { """.formatted(integrationId)) .when().post("/v2/apis/" + apiId + "/routes") .then().statusCode(201); + + String v1IntegrationId = given() + .contentType(ContentType.JSON) + .body(""" + {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST","payloadFormatVersion":"1.0"} + """.formatted(FUNCTION_NAME)) + .when().post("/v2/apis/" + apiId + "/integrations") + .then() + .statusCode(201) + .extract().path("integrationId"); + + given() + .contentType(ContentType.JSON) + .body(""" + {"routeKey":"GET /echo-v1","target":"integrations/%s"} + """.formatted(v1IntegrationId)) + .when().post("/v2/apis/" + apiId + "/routes") + .then().statusCode(201); } @Test @@ -130,6 +147,24 @@ class HttpApiLambdaProxyEventMultiValueIntegrationTest { .body("cookies", nullValue()); } + @Test + @Order(14) + void payloadFormatOneUsesV1Event() { + given() + .queryParam("q", "1", "2") + .when().get("/execute-api/" + apiId + "/test/echo-v1") + .then() + .statusCode(200) + .body("version", equalTo("1.0")) + .body("resource", equalTo("/echo-v1")) + .body("path", equalTo("/echo-v1")) + .body("httpMethod", equalTo("GET")) + .body("rawPath", nullValue()) + .body("stageVariables.environment", equalTo("review")) + .body("multiValueHeaders", notNullValue()) + .body("multiValueQueryStringParameters.q", contains("1", "2")); + } + @Test @Order(999) void cleanup() throws Exception {