From 9eabfaf9bc1292ca7d91b087967969fe8ff48b7f Mon Sep 17 00:00:00 2001 From: Aniket Shukla Date: Wed, 28 Oct 2026 18:39:52 +0530 Subject: [PATCH] fix(apigateway): map Lambda context in HTTP proxy requests (#6818) --- docs/services/api-gateway.md | 6 + .../ApiGatewayExecuteController.java | 7 +- ...xyLambdaContextMappingIntegrationTest.java | 185 ++++++++++++++++++ 3 files changed, 196 insertions(+), 2 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyLambdaContextMappingIntegrationTest.java diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index 21cd3193ea..e2c3020c4f 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -747,6 +747,12 @@ or string. A missing or empty configured value returns `401` without invoking Lambda in either format. Repeated request values use each event's delivered representation: last value in format `1.0`, comma-joined values in format `2.0`. +HTTP API `HTTP_PROXY` integrations can map values from a successful Lambda +authorizer's context into request headers, query strings, and paths. For a returned +`context` containing `tenantId`, use `$context.authorizer.tenantId` in +`requestParameters`. String, numeric, and boolean context values are rendered as +text. This works with format `1.0` policy responses and format `2.0` simple responses. + A Lambda proxy integration's response is read as AWS reads it (measured): a function that raises, a format 1.0 result that is not an object with a `statusCode`, and a `statusCode` that is not a whole number from 100 to 599 (text that spells one, such as `"201"`, is taken) are answered `500` with 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 f05c53acfc..9bde1376d9 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 @@ -2864,7 +2864,7 @@ public class ApiGatewayExecuteController { if ("HTTP_PROXY".equalsIgnoreCase(integrationType)) { return dispatchHttpProxyV2(integration, route, httpMethod, path, headers, uriInfo, body, - apiId, stageName, jwtClaims, region); + apiId, stageName, jwtClaims, lambdaAuthorizerContext, region); } String functionName = functionNameFromUri(integration.getIntegrationUri()); @@ -2918,6 +2918,7 @@ public class ApiGatewayExecuteController { Route route, String httpMethod, String path, HttpHeaders headers, UriInfo uriInfo, byte[] body, String apiId, String stageName, Map jwtClaims, + ObjectNode lambdaAuthorizerContext, String region) { // CDK HttpAlbIntegration sets integrationUri to an ALB listener ARN. Resolve it // to the listener's bound localhost port so HttpProxyInvoker (which assumes a @@ -2995,6 +2996,8 @@ public class ApiGatewayExecuteController { // would otherwise have $context.authorizer.claims.* resolve from the unverified header // token instead of the one the authorizer actually checked. Map claims = jwtClaims != null ? Map.copyOf(jwtClaims) : Map.of(); + Map authorizerContext = lambdaAuthorizerContext == null + ? Map.of() : objectMapper.convertValue(lambdaAuthorizerContext, MAP_TYPE); String sourceIp = requestHeaders.getOrDefault("X-Forwarded-For", "127.0.0.1"); io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext ctx = @@ -3003,7 +3006,7 @@ public class ApiGatewayExecuteController { pathParams.getOrDefault("proxy", ""), route.getRouteKey(), UUID.randomUUID().toString(), sourceIp, requestHeaders, queryParams, pathParams, body, - claims, Map.of(), multiValueHeaders, multiValueQueryParams); + claims, authorizerContext, multiValueHeaders, multiValueQueryParams); LOG.debugv("execute-api v2: {0} {1}/{2}{3} → HTTP_PROXY {4}", httpMethod, apiId, stageName, path, effective.getIntegrationUri()); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyLambdaContextMappingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyLambdaContextMappingIntegrationTest.java new file mode 100644 index 0000000000..b7e1904261 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyLambdaContextMappingIntegrationTest.java @@ -0,0 +1,185 @@ +package io.github.hectorvent.floci.services.apigatewayv2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sun.net.httpserver.HttpServer; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static io.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.AUTHORIZER; +import static io.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.result; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.verifyNoInteractions; + +@QuarkusTest +class HttpProxyLambdaContextMappingIntegrationTest { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private final AtomicReference received = new AtomicReference<>(); + private final AtomicInteger backendCalls = new AtomicInteger(); + private HttpServer backend; + private String apiId; + private String routeId; + private String payloadFormat = "2.0"; + private boolean allowed = true; + private ObjectNode context; + + @InjectMock LambdaService lambdaService; + + @BeforeEach + void startBackendAndStubAuthorizer() throws Exception { + context = MAPPER.createObjectNode().put("tenantId", "2").put("count", 7).put("active", true); + backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + backend.createContext("/", exchange -> { + backendCalls.incrementAndGet(); + ObjectNode request = MAPPER.createObjectNode(); + for (String header : List.of("x-tenant", "x-count", "x-active", "x-missing", "x-static", "x-request-id")) { + request.put(header, exchange.getRequestHeaders().getFirst(header)); + } + request.put("path", exchange.getRequestURI().getPath()); + request.put("query", exchange.getRequestURI().getRawQuery()); + received.set(request); + byte[] bytes = "ok".getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, bytes.length); + exchange.getResponseBody().write(bytes); + exchange.close(); + }); + backend.start(); + LambdaAuthorizerApiFixtures.stubAuthorizer(lambdaService, event -> { + ObjectNode response = MAPPER.createObjectNode(); + if ("2.0".equals(payloadFormat)) { + response.put("isAuthorized", allowed); + } else { + response.put("principalId", "verified-user"); + ObjectNode policy = response.putObject("policyDocument").put("Version", "2012-10-17"); + policy.putArray("Statement").addObject().put("Action", "execute-api:Invoke") + .put("Effect", allowed ? "Allow" : "Deny").put("Resource", event.path("methodArn").asText()); + } + if (context != null) { + response.set("context", context); + } + return result(response.toString()); + }); + } + + @AfterEach + void cleanUp() { + try { + if (apiId != null) { + given().delete("/v2/apis/" + apiId).then().statusCode(204); + } + } finally { + if (backend != null) { + backend.stop(0); + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"1.0", "2.0"}) + void mapsVerifiedContextToHeadersQueryAndPath(String format) { + payloadFormat = format; + configureApi(); + invoke("first"); + JsonNode request = received.get(); + assertNotNull(request); + assertEquals("2", request.path("x-tenant").asText()); + assertEquals("7", request.path("x-count").asText()); + assertEquals("true", request.path("x-active").asText()); + assertEquals("fixed", request.path("x-static").asText()); + assertFalse(request.path("x-request-id").asText().isBlank()); + assertTrue(request.path("x-missing").isNull()); + assertEquals("/tenant/2", request.path("path").asText()); + assertEquals("tenant=2", request.path("query").asText()); + } + + @Test + void contextlessAllowDoesNotMapMissingValues() { + context = null; + configureApi(); + invoke("first"); + assertTrue(received.get().path("x-count").isNull()); + assertTrue(received.get().path("query").isNull()); + } + + @Test + void eachRequestUsesItsAuthorizerResultAndPublicRoutesHaveNoContext() { + configureApi(); + invoke("first"); + assertEquals("2", received.get().path("x-tenant").asText()); + context.put("tenantId", "3"); + invoke("second"); + assertEquals("3", received.get().path("x-tenant").asText()); + given().contentType(ContentType.JSON).body(Map.of("authorizationType", "NONE")) + .patch("/v2/apis/" + apiId + "/routes/" + routeId).then().statusCode(200); + invoke("third"); + assertTrue(received.get().path("x-count").isNull()); + assertTrue(received.get().path("query").isNull()); + } + + @Test + void deniedRequestsNeverReachTheBackend() { + allowed = false; + configureApi(); + given().header("Authorization", "Bearer denied").get(path()).then().statusCode(403); + assertEquals(0, backendCalls.get()); + } + + @Test + void missingIdentityNeverInvokesAuthorizerOrBackend() { + configureApi(); + given().get(path()).then().statusCode(401); + verifyNoInteractions(lambdaService); + assertEquals(0, backendCalls.get()); + } + + private void configureApi() { + apiId = HttpProxyApiFixtures.createProxyApi("lambda-context-mapping", "", "test", + backend.getAddress().getPort(), "/items"); + String apiPath = "/v2/apis/" + apiId; + String integrationId = given().get(apiPath + "/integrations").then().statusCode(200) + .extract().path("items[0].integrationId"); + given().contentType(ContentType.JSON).body(Map.of("requestParameters", Map.of( + "overwrite:header.x-tenant", "$context.authorizer.tenantId", + "append:header.x-count", "$context.authorizer.count", + "overwrite:header.x-active", "$context.authorizer.active", + "overwrite:header.x-missing", "$context.authorizer.missing", + "overwrite:header.x-static", "fixed", + "overwrite:header.x-request-id", "$context.requestId", + "overwrite:querystring.tenant", "$context.authorizer.tenantId", + "overwrite:path", "/tenant/$context.authorizer.tenantId"))) + .patch(apiPath + "/integrations/" + integrationId).then().statusCode(200); + String authorizerId = given().contentType(ContentType.JSON).body(Map.of( + "name", "mapping-authorizer", "authorizerType", "REQUEST", "authorizerUri", AUTHORIZER, + "authorizerPayloadFormatVersion", payloadFormat, "enableSimpleResponses", "2.0".equals(payloadFormat), + "authorizerResultTtlInSeconds", 0, "identitySource", List.of("$request.header.Authorization"))) + .post(apiPath + "/authorizers").then().statusCode(201).extract().path("authorizerId"); + routeId = given().get(apiPath + "/routes").then().statusCode(200).extract().path("items[0].routeId"); + given().contentType(ContentType.JSON).body(Map.of("authorizationType", "CUSTOM", "authorizerId", authorizerId)) + .patch(apiPath + "/routes/" + routeId).then().statusCode(200); + } + + private void invoke(String token) { + given().header("Authorization", "Bearer " + token).header("x-tenant", "forged") + .get(path()).then().statusCode(200); + } + + private String path() { + return "/execute-api/" + apiId + "/test/items"; + } +}