fix(apigatewayv2): include stage variables in Lambda events (#5416)

* fix(apigatewayv2): include stage variables in Lambda events

* fix(apigatewayv2): tolerate missing stages during variable lookup
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-10-12 10:32:46 -04:00
1 parent e61b66fb22
commit 22c4c32e3a
9 files changed
+188 -66

No files matched your search

@@ -1231,14 +1231,8 @@ public class ApiGatewayExecuteController {
pathParams.forEach(ppNode::put);
}
// stageVariables: populate from the Stage object (null if no variables configured)
Map<String, String> stageVars = stage != null ? stage.getVariables() : null;
if (stageVars != null && !stageVars.isEmpty()) {
ObjectNode svNode = node.putObject("stageVariables");
stageVars.forEach(svNode::put);
} else {
node.putNull("stageVariables");
}
putStageVariables(node, stageVars);
ObjectNode ctx = node.putObject("requestContext");
ctx.put("accountId", regionResolver.getAccountId());
@@ -1363,14 +1357,8 @@ public class ApiGatewayExecuteController {
extractPathParams(resourcePath, path).forEach(pathParams::put);
greedyPathParam(resourcePath, path).forEach(pathParams::put);
// stageVariables: populate from the Stage object (null if no variables configured)
Map<String, String> stageVars = stage != null ? stage.getVariables() : null;
if (stageVars != null && !stageVars.isEmpty()) {
ObjectNode svNode = event.putObject("stageVariables");
stageVars.forEach(svNode::put);
} else {
event.putNull("stageVariables");
}
putStageVariables(event, stageVars);
String arnRegion = region != null ? region : regionResolver.getDefaultRegion();
String domainName = restDomainName(apiId, arnRegion, headers);
@@ -2555,6 +2543,8 @@ public class ApiGatewayExecuteController {
.type(MediaType.APPLICATION_JSON).build();
}
Map<String, String> stageVariables = apiGatewayV2Service.getStageVariables(region, apiId, stageName);
// A route carries exactly one authorizationType, so AWS_IAM, JWT and CUSTOM are mutually
// exclusive branches. AWS_IAM was previously absent here, which let an unsigned request
// through to the integration as if the route were NONE.
@@ -2580,7 +2570,8 @@ public class ApiGatewayExecuteController {
ObjectNode lambdaAuthorizerContext = null;
if ("CUSTOM".equalsIgnoreCase(route.getAuthorizationType()) && route.getAuthorizerId() != null) {
RequestAuthorizerResult requestResult =
enforceRequestAuthorizerV2(region, apiId, stageName, route, httpMethod, path, headers, uriInfo);
enforceRequestAuthorizerV2(region, apiId, stageName, route, httpMethod, path,
headers, uriInfo, stageVariables);
if (requestResult.errorResponse() != null) {
return requestResult.errorResponse();
}
@@ -2623,16 +2614,13 @@ public class ApiGatewayExecuteController {
String requestId = UUID.randomUUID().toString();
boolean payloadV1 = "1.0".equals(integration.getPayloadFormatVersion());
Map<String, String> 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);
lambdaAuthorizerContext, iamIdentity, stageVariables);
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → Lambda {4}", httpMethod, apiId, stageName, path, functionName);
@@ -3025,7 +3013,8 @@ public class ApiGatewayExecuteController {
*/
private RequestAuthorizerResult enforceRequestAuthorizerV2(String region, String apiId, String stageName,
Route route, String httpMethod, String path,
HttpHeaders headers, UriInfo uriInfo) {
HttpHeaders headers, UriInfo uriInfo,
Map<String, String> stageVariables) {
Authorizer authorizer = findV2Authorizer(region, apiId, route.getAuthorizerId()).orElse(null);
if (authorizer == null) {
return new RequestAuthorizerResult(Response.status(500)
@@ -3068,10 +3057,11 @@ public class ApiGatewayExecuteController {
String eventJson;
if ("2.0".equals(payloadFormatVersion)) {
eventJson = buildRequestAuthorizerEventV2(httpMethod, path, route.getRouteKey(),
apiId, stageName, region, headers, uriInfo);
apiId, stageName, region, headers, uriInfo, stageVariables);
} else {
// Default to 1.0 format
eventJson = buildRequestAuthorizerEventV1(httpMethod, path, apiId, stageName, region, headers, uriInfo);
eventJson = buildRequestAuthorizerEventV1(httpMethod, path, apiId, stageName,
region, headers, uriInfo, stageVariables);
}
// Extract the Lambda function name from the authorizer URI
@@ -3186,7 +3176,8 @@ public class ApiGatewayExecuteController {
*/
String buildRequestAuthorizerEventV1(String httpMethod, String path,
String apiId, String stageName, String region,
HttpHeaders headers, UriInfo uriInfo) {
HttpHeaders headers, UriInfo uriInfo,
Map<String, String> stageVariables) {
// 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),
@@ -3211,7 +3202,7 @@ public class ApiGatewayExecuteController {
putMultiValueQueryStringParameters(event, uriInfo);
event.putObject("pathParameters");
event.putNull("stageVariables");
putStageVariables(event, stageVariables);
// Request context
ObjectNode ctx = event.putObject("requestContext");
@@ -3236,7 +3227,8 @@ public class ApiGatewayExecuteController {
*/
String buildRequestAuthorizerEventV2(String httpMethod, String path, String routeKey,
String apiId, String stageName, String region,
HttpHeaders headers, UriInfo uriInfo) {
HttpHeaders headers, UriInfo uriInfo,
Map<String, String> stageVariables) {
// 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.
@@ -3254,7 +3246,7 @@ public class ApiGatewayExecuteController {
putV2CookiesHeadersAndQuery(event, headers.getRequestHeaders(), uriInfo.getQueryParameters());
event.putObject("pathParameters");
event.putNull("stageVariables");
putStageVariables(event, stageVariables);
// Request context
ObjectNode ctx = event.putObject("requestContext");
@@ -3406,6 +3398,15 @@ public class ApiGatewayExecuteController {
};
}
private static void putStageVariables(ObjectNode event, Map<String, String> stageVariables) {
if (stageVariables == null || stageVariables.isEmpty()) {
event.putNull("stageVariables");
return;
}
ObjectNode variables = event.putObject("stageVariables");
stageVariables.forEach(variables::put);
}
/** 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,
@@ -3422,10 +3423,7 @@ public class ApiGatewayExecuteController {
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);
}
putStageVariables(event, stageVariables);
Map<String, List<String>> lowercaseHeaders = new LinkedHashMap<>();
headers.getRequestHeaders().forEach((name, values) ->
@@ -3513,6 +3511,18 @@ public class ApiGatewayExecuteController {
byte[] body, String requestId, Map<String, String> jwtClaims,
List<String> jwtScopes, ObjectNode lambdaAuthorizerContext,
ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) {
return buildV2ProxyEvent(httpMethod, path, routeKey, apiId, region, stageName,
headers, uriInfo, body, requestId, jwtClaims, jwtScopes, lambdaAuthorizerContext,
iamIdentity, null);
}
String buildV2ProxyEvent(String httpMethod, String path, String routeKey,
String apiId, String region, String stageName,
HttpHeaders headers, UriInfo uriInfo,
byte[] body, String requestId, Map<String, String> jwtClaims,
List<String> jwtScopes, ObjectNode lambdaAuthorizerContext,
ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity,
Map<String, String> stageVariables) {
// 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
@@ -3537,6 +3547,10 @@ public class ApiGatewayExecuteController {
pathParams.forEach(pp::put);
}
if (stageVariables != null && !stageVariables.isEmpty()) {
putStageVariables(event, stageVariables);
}
ObjectNode ctx = event.putObject("requestContext");
ctx.put("accountId", regionResolver.getAccountId());
ctx.put("apiId", apiId);
@@ -829,6 +829,12 @@ public class ApiGatewayV2Service {
.orElseThrow(() -> new AwsException("NotFoundException", "Stage not found", 404));
}
public Map<String, String> getStageVariables(String region, String apiId, String stageName) {
return stageStore.get(stageKey(region, apiId, stageName))
.map(Stage::getStageVariables)
.orElse(Map.of());
}
public List<Stage> getStages(String region, String apiId) {
getApi(region, apiId);
String prefix = region + "::" + apiId + "::";
@@ -667,7 +667,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = controller(new ObjectMapper());
assertEnglishUtcTimeUnderNonUtcHost(() -> controller.buildRequestAuthorizerEventV2("GET", "/items",
"GET /items", "api1", "$default", "us-east-1", emptyHeaders(),
uriInfoFor("http://localhost/items")));
uriInfoFor("http://localhost/items"), null));
}
private static HttpHeaders emptyHeaders() {
@@ -54,7 +54,7 @@ class BuildV2AuthorizerEventTrailingSlashTest {
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);
"GET", normalizedPath, "abc123", "test", "us-east-1", headers, uriInfo, null);
return new ObjectMapper().readTree(json);
}
@@ -65,7 +65,7 @@ class BuildV2ProxyEventMultiValueTest {
"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);
"abc123", "$default", "us-east-1", headers, uriInfo, null);
};
return new ObjectMapper().readTree(json);
}
@@ -0,0 +1,92 @@
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 java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class BuildV2ProxyEventStageVariablesTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private ApiGatewayExecuteController controller;
private HttpHeaders headers;
private UriInfo uriInfo;
@BeforeEach
void setUp() throws Exception {
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<>());
when(uriInfo.getRequestUri()).thenReturn(new URI("http://localhost:4566/echo"));
controller = new ApiGatewayExecuteController(
null, null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null);
}
@Test
void includesConfiguredStageVariables() throws Exception {
JsonNode event = buildEvent(Map.of("mode", "production", "region", "local"));
assertEquals("production", event.path("stageVariables").path("mode").asText());
assertEquals("local", event.path("stageVariables").path("region").asText());
}
@Test
void omitsStageVariablesWithoutConfiguredStageVariables() throws Exception {
JsonNode event = buildEvent(Map.of());
assertFalse(event.has("stageVariables"));
}
@Test
void authorizerEventsIncludeConfiguredStageVariables() throws Exception {
for (JsonNode event : buildAuthorizerEvents(Map.of("environment", "review"))) {
assertEquals("review", event.path("stageVariables").path("environment").asText());
}
}
@Test
void authorizerEventsRenderNullWithoutConfiguredStageVariables() throws Exception {
for (JsonNode event : buildAuthorizerEvents(Map.of())) {
assertTrue(event.path("stageVariables").isNull());
}
}
private JsonNode buildEvent(Map<String, String> stageVariables) throws Exception {
return MAPPER.readTree(controller.buildV2ProxyEvent(
"GET", "/echo", "GET /echo", "abc123", "us-east-1", "test",
headers, uriInfo, null, "req-1", null, null, null, null, stageVariables));
}
private List<JsonNode> buildAuthorizerEvents(Map<String, String> stageVariables) throws Exception {
return List.of(
MAPPER.readTree(controller.buildRequestAuthorizerEventV1(
"GET", "/echo", "abc123", "test", "us-east-1",
headers, uriInfo, stageVariables)),
MAPPER.readTree(controller.buildRequestAuthorizerEventV2(
"GET", "/echo", "GET /echo", "abc123", "test", "us-east-1",
headers, uriInfo, stageVariables)));
}
}
@@ -1,16 +1,22 @@
package io.github.hectorvent.floci.services.apigatewayv2;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import jakarta.inject.Inject;
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 java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Stage access logging, throttling defaults and per-route overrides, plus the API's version.
@@ -22,6 +28,9 @@ import static org.hamcrest.Matchers.notNullValue;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ApiGatewayV2StageSettingsTest {
@Inject
ApiGatewayV2Service service;
private static final ObjectMapper mapper = new ObjectMapper();
private static String apiId;
@@ -122,4 +131,21 @@ class ApiGatewayV2StageSettingsTest {
.body("defaultRouteSettings.throttlingBurstLimit", org.hamcrest.Matchers.nullValue())
.body("defaultRouteSettings.dataTraceEnabled", org.hamcrest.Matchers.nullValue());
}
@Test
@Order(6)
void stageVariablesLookupReturnsConfiguredValuesOrEmptyMap() {
Map<String, String> variables = Map.of("backend", "blue");
given().contentType(ContentType.JSON)
.body("{\"stageName\":\"variables\",\"stageVariables\":{\"backend\":\"blue\"}}")
.when().post("/v2/apis/" + apiId + "/stages")
.then().statusCode(201);
assertEquals(variables, service.getStageVariables("us-east-1", apiId, "variables"));
assertEquals(Map.of(), service.getStageVariables("us-east-1", apiId, "sparse"));
assertEquals(Map.of(), service.getStageVariables("us-east-1", apiId, "missing"));
assertEquals(Map.of(), service.getStageVariables("us-west-2", apiId, "variables"));
assertEquals(Map.of(), service.getStageVariables("us-east-1", "other-api", "variables"));
assertThrows(AwsException.class, () -> service.getStage("us-east-1", apiId, "missing"));
}
}
@@ -165,6 +165,16 @@ class HttpApiLambdaProxyEventMultiValueIntegrationTest {
.body("multiValueQueryStringParameters.q", contains("1", "2"));
}
@Test
@Order(15)
void stageVariablesReachTheLambdaEvent() {
given()
.when().get("/execute-api/" + apiId + "/test/echo")
.then()
.statusCode(200)
.body("stageVariables.environment", equalTo("review"));
}
@Test
@Order(999)
void cleanup() throws Exception {
@@ -80,7 +80,7 @@ class HttpApiRequestAuthorizerTest {
given()
.contentType(ContentType.JSON)
.body("""
{"stageName":"test"}
{"stageName":"test","stageVariables":{"environment":"review"}}
""")
.when().post("/v2/apis/" + httpApiId + "/stages")
.then()
@@ -578,8 +578,6 @@ class HttpApiRequestAuthorizerTest {
.when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId)
.then().statusCode(200);
// The echo authorizer embeds the event it received in its context, so assert that shape
// by invoking the echo function directly rather than unwrapping it through two hops.
String response = given()
.header("X-Custom-Header", "test-value")
.queryParam("foo", "bar")
@@ -587,23 +585,10 @@ class HttpApiRequestAuthorizerTest {
.then().statusCode(200)
.extract().body().asString();
// Backend received the request — authorizer allowed it
JsonNode backendResponse = MAPPER.readTree(response);
assertEquals("Hello from backend", backendResponse.path("message").asText());
// Verify format by invoking echo function with a v1-shaped event
String testEvent = """
{"version":"1.0","type":"REQUEST","methodArn":"arn:aws:execute-api:us-east-1:000000000000:%s/test/GET/hello","resource":"/hello","path":"/hello","httpMethod":"GET","headers":{"X-Custom-Header":"test-value"},"queryStringParameters":{"foo":"bar"}}
""".formatted(httpApiId);
String echoResponse = given()
.contentType(ContentType.JSON)
.body(testEvent)
.when().post("/2015-03-31/functions/" + ECHO_FN + "/invocations")
.then().statusCode(200)
.extract().body().asString();
JsonNode echoResult = MAPPER.readTree(echoResponse);
String authEventStr = echoResult.path("context").path("receivedEvent").asText(null);
String authEventStr = backendResponse.path("authorizer").path("lambda")
.path("receivedEvent").asText(null);
assertNotNull(authEventStr, "Echo authorizer should embed receivedEvent in context");
JsonNode authEvent = MAPPER.readTree(authEventStr);
@@ -612,6 +597,7 @@ class HttpApiRequestAuthorizerTest {
assertNotNull(authEvent.path("methodArn").asText(null), "Event should have methodArn");
assertEquals("/hello", authEvent.path("resource").asText(), "Event should have resource");
assertEquals("GET", authEvent.path("httpMethod").asText(), "Event should have httpMethod");
assertEquals("review", authEvent.path("stageVariables").path("environment").asText());
}
// ──────────────────────────── Test: Payload format 2.0 event shape ────────────────────────────
@@ -634,23 +620,10 @@ class HttpApiRequestAuthorizerTest {
.then().statusCode(200)
.extract().body().asString();
// Backend received the request — authorizer allowed it
JsonNode backendResponse = MAPPER.readTree(response);
assertEquals("Hello from backend", backendResponse.path("message").asText());
// Verify format by invoking echo function with a v2-shaped event
String testEvent = """
{"version":"2.0","type":"REQUEST","routeArn":"arn:aws:execute-api:us-east-1:000000000000:%s/test/GET/hello","routeKey":"GET /hello","rawPath":"/hello","rawQueryString":"key=value","headers":{"x-custom-header":"test-value-v2"},"queryStringParameters":{"key":"value"},"requestContext":{"accountId":"000000000000","apiId":"%s","http":{"method":"GET","path":"/hello"}}}
""".formatted(httpApiId, httpApiId);
String echoResponse = given()
.contentType(ContentType.JSON)
.body(testEvent)
.when().post("/2015-03-31/functions/" + ECHO_FN + "/invocations")
.then().statusCode(200)
.extract().body().asString();
JsonNode echoResult = MAPPER.readTree(echoResponse);
String authEventStr = echoResult.path("context").path("receivedEvent").asText(null);
String authEventStr = backendResponse.path("authorizer").path("lambda")
.path("receivedEvent").asText(null);
assertNotNull(authEventStr, "Echo authorizer should embed receivedEvent in context");
JsonNode authEvent = MAPPER.readTree(authEventStr);
@@ -659,6 +632,7 @@ class HttpApiRequestAuthorizerTest {
assertNotNull(authEvent.path("routeArn").asText(null), "Event should have routeArn");
assertEquals("GET /hello", authEvent.path("routeKey").asText(), "Event should have routeKey");
assertEquals("/hello", authEvent.path("rawPath").asText(), "Event should have rawPath");
assertEquals("review", authEvent.path("stageVariables").path("environment").asText());
}
// ──────────────────────────── Test: No authorizer (NONE) allows request ────────────────────────────