fix(apigatewayv2): propagate Lambda REQUEST authorizer context to HTTP API backends (#2715)

* fix(apigatewayv2): propagate Lambda REQUEST authorizer context to HTTP API backends

A REQUEST authorizer's response context was parsed only to read isAuthorized
or the policy Effect, then discarded. enforceRequestAuthorizerV2 returned a
bare Response (null meaning "allowed"), so nothing could carry the context to
buildV2ProxyEvent and the backend Lambda received no requestContext.authorizer
at all. A real HTTP API delivers it under requestContext.authorizer.lambda,
which is how an authorizer hands verified identity to the integration, so a
backend that reads it sees an empty object and rejects every authorized
request.

This completes #1011 (issue #812), which added REQUEST authorizer invocation
for HTTP APIs but only wired the allow/deny decision, and brings v2 in line
with #581, which propagated the authorizer context on the v1/REST path. The
WebSocket $connect path already does the same via WebSocketProxyEventBuilder,
so HTTP APIs were the last of the three to drop it.

Return a RequestAuthorizerResult carrying the context, mirroring the
JwtAuthorizerResult the JWT path already threads through, and render it as
requestContext.authorizer.lambda.

Values are not flattened to strings the way the v1/REST path flattens its
authorizer context: an HTTP API hands the context to the integration as JSON.
The developer guide's own simple-response example returns a string, a number,
a boolean, an array and a map, and all five now survive to the backend.

principalId is deliberately left out - where AWS surfaces it in a 2.0 proxy
event was not measured - and an authorizer that allows without returning a
context leaves the authorizer node absent rather than rendering
"lambda": null, for the same reason.

Covered end to end in HttpApiRequestAuthorizerTest (IAM-policy and simple
responses, nesting and scalar types, contextless allow) and at the builder in
BuildV2ProxyEventLambdaAuthorizerTest.

* chore(apigatewayv2): trim comments on the authorizer-context change

Drops narration and change history, keeping only what is not recoverable from
the code: the RequestAuthorizerResult contract, why the context is not
flattened the way the v1/REST path flattens it, and the two intentional
omissions (principalId, absent node rather than "lambda": null).

Per AGENTS.md: prefer self-explanatory code over comments, document
intentional deviations clearly.

* fix(apigatewayv2): brace the authorizer error branch

AGENTS.md requires braces on every conditional.

---------

Co-authored-by: local <local@example.com>
This commit is contained in:
Brian Taylorandlocal authored and GitHub committed 2026-08-30 17:11:06 -04:00
1 parent 02f9754ac7
commit 908d70db3d
4 files changed
+362 -50

No files matched your search

@@ -117,7 +117,7 @@ class BuildV2ProxyEventJwtClaimsTest {
JsonNode event = new ObjectMapper().readTree(json);
assertFalse(event.get("requestContext").has("authorizer"),
"requestContext.authorizer must be absent for routes with no JWT authorizer claims (Auth: NONE or CUSTOM)");
"requestContext.authorizer must be absent for routes with no JWT claims and no Lambda authorizer context");
}
@Test
@@ -0,0 +1,134 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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.LinkedHashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Verifies that {@link ApiGatewayExecuteController#buildV2ProxyEvent} populates
* {@code requestContext.authorizer.lambda} for HTTP API (V2) routes behind a Lambda REQUEST
* authorizer.
*
* <p>The end-to-end path is covered by HttpApiRequestAuthorizerTest; these assertions pin the
* rendered shape without needing a Lambda container.
*/
class BuildV2ProxyEventLambdaAuthorizerTest {
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<>());
when(headers.getHeaderString("User-Agent")).thenReturn(null);
uriInfo = mock(UriInfo.class);
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(uriInfo.getRequestUri()).thenReturn(new URI("http://localhost:4566/api/stage/v1/things"));
controller = new ApiGatewayExecuteController(
null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null
);
}
@Test
void populatesAuthorizerLambdaContext() throws Exception {
ObjectNode context = MAPPER.createObjectNode();
context.put("userId", "user123");
context.put("role", "admin");
String json = controller.buildV2ProxyEvent(
"POST", "/v1/things", "$default",
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-1", null, null,
context);
JsonNode event = MAPPER.readTree(json);
JsonNode lambda = event.at("/requestContext/authorizer/lambda");
assertFalse(lambda.isMissingNode(), "requestContext.authorizer.lambda must be present");
assertEquals("user123", lambda.get("userId").asText());
assertEquals("admin", lambda.get("role").asText());
assertFalse(event.at("/requestContext/authorizer").has("jwt"),
"a Lambda authorizer must not render the JWT-authorizer node");
}
@Test
void keepsNestedObjectsAndScalarTypes() throws Exception {
// The developer guide's simple-response example returns a string, a number, a boolean,
// an array and a map, so all five have to survive.
ObjectNode context = MAPPER.createObjectNode();
ObjectNode claims = context.putObject("jwt").putObject("claims");
claims.put("sub", "user-abc");
context.put("tenantId", "CONDO_1");
context.put("requestCount", 3);
context.put("active", true);
context.putArray("groups").add("admin").add("auditor");
String json = controller.buildV2ProxyEvent(
"GET", "/v1/things", "$default",
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-2", null, null,
context);
JsonNode lambda = MAPPER.readTree(json).at("/requestContext/authorizer/lambda");
assertEquals("user-abc", lambda.at("/jwt/claims/sub").asText(),
"nested objects must survive rather than being stringified");
assertEquals("CONDO_1", lambda.get("tenantId").asText());
assertTrue(lambda.get("requestCount").isNumber(), "a number must stay a number");
assertTrue(lambda.get("active").isBoolean(), "a boolean must stay a boolean");
assertTrue(lambda.get("groups").isArray(), "an array must stay an array");
assertEquals("auditor", lambda.get("groups").get(1).asText());
}
@Test
void omitsAuthorizerNodeWhenNoContextWasReturned() throws Exception {
String json = controller.buildV2ProxyEvent(
"GET", "/v1/things", "$default",
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-3", null, null,
null);
JsonNode event = MAPPER.readTree(json);
assertFalse(event.get("requestContext").has("authorizer"),
"an authorizer that allows without a context leaves the node absent");
}
@Test
void jwtClaimsWinOverLambdaContext() throws Exception {
// dispatchV2 can never hand over both; pinned so the event never grows two authorizer
// nodes if that changes.
Map<String, String> claims = new LinkedHashMap<>();
claims.put("sub", "user_01ABC");
ObjectNode context = MAPPER.createObjectNode();
context.put("userId", "user123");
String json = controller.buildV2ProxyEvent(
"GET", "/v1/things", "$default",
"abc123", "us-east-2", "$default", headers, uriInfo, null, "req-4", claims, null,
context);
JsonNode authorizer = MAPPER.readTree(json).at("/requestContext/authorizer");
assertEquals("user_01ABC", authorizer.at("/jwt/claims/sub").asText());
assertFalse(authorizer.has("lambda"), "the two authorizer shapes are mutually exclusive");
}
}
@@ -43,6 +43,8 @@ class HttpApiRequestAuthorizerTest {
private static String identitySourceAuthorizerId;
private static String echoV1AuthorizerId;
private static String echoV2AuthorizerId;
private static String nestedContextAuthorizerId;
private static String contextlessAuthorizerId;
private static final String ALLOW_FN = "httpv2-auth-allow-fn";
private static final String DENY_FN = "httpv2-auth-deny-fn";
@@ -51,6 +53,8 @@ class HttpApiRequestAuthorizerTest {
private static final String SIMPLE_DENY_FN = "httpv2-auth-simple-deny-fn";
private static final String ECHO_FN = "httpv2-auth-echo-fn";
private static final String BACKEND_FN = "httpv2-auth-backend-fn";
private static final String NESTED_CTX_FN = "httpv2-auth-nested-ctx-fn";
private static final String CONTEXTLESS_FN = "httpv2-auth-contextless-fn";
// ──────────────────────────── Setup ────────────────────────────
@@ -82,10 +86,16 @@ class HttpApiRequestAuthorizerTest {
@Order(2)
void setupLambdaFunctions() throws Exception {
// Backend Lambda
// Echoes requestContext.authorizer back. JSON.stringify drops the key entirely when the
// event carries none, which is what the contextless case asserts.
createNodeLambda(BACKEND_FN, """
exports.handler = async (event) => ({
statusCode: 200,
body: JSON.stringify({ message: "Hello from backend", path: event.rawPath })
body: JSON.stringify({
message: "Hello from backend",
path: event.rawPath,
authorizer: event.requestContext ? event.requestContext.authorizer : undefined
})
});
""");
@@ -132,6 +142,27 @@ class HttpApiRequestAuthorizerTest {
});
""");
// Simple-response authorizer whose context nests objects — an HTTP API delivers the
// context as JSON, so the nesting has to survive.
createNodeLambda(NESTED_CTX_FN, """
exports.handler = async (event) => ({
isAuthorized: true,
context: {
jwt: { claims: { sub: "user-abc", scope: "condo/read" } },
tenantId: "CONDO_1",
licenseTier: "PRO",
requestCount: 3,
active: true,
groups: ["admin", "auditor"]
}
});
""");
// Simple-response authorizer that allows without returning any context
createNodeLambda(CONTEXTLESS_FN, """
exports.handler = async (event) => ({ isAuthorized: true });
""");
// Echo authorizer that returns the event payload in context
createNodeLambda(ECHO_FN, """
exports.handler = async (event) => ({
@@ -148,7 +179,8 @@ class HttpApiRequestAuthorizerTest {
@Test
@Order(3)
void prewarmLambdaFunctions() {
for (String fn : new String[]{BACKEND_FN, ALLOW_FN, DENY_FN, ERROR_FN, SIMPLE_ALLOW_FN, SIMPLE_DENY_FN, ECHO_FN}) {
for (String fn : new String[]{BACKEND_FN, ALLOW_FN, DENY_FN, ERROR_FN, SIMPLE_ALLOW_FN,
SIMPLE_DENY_FN, ECHO_FN, NESTED_CTX_FN, CONTEXTLESS_FN}) {
given().contentType(ContentType.JSON).body("{}")
.when().post("/2015-03-31/functions/" + fn + "/invocations")
.then().statusCode(200);
@@ -242,6 +274,26 @@ class HttpApiRequestAuthorizerTest {
.then().statusCode(201)
.extract().path("authorizerId");
// Nested-context authorizer (format 2.0 with enableSimpleResponses)
nestedContextAuthorizerId = given()
.contentType(ContentType.JSON)
.body("""
{"name":"nested-ctx-auth","authorizerType":"REQUEST","authorizerPayloadFormatVersion":"2.0","enableSimpleResponses":true,"authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"}
""".formatted(NESTED_CTX_FN))
.when().post("/v2/apis/" + httpApiId + "/authorizers")
.then().statusCode(201)
.extract().path("authorizerId");
// Contextless simple-allow authorizer (format 2.0 with enableSimpleResponses)
contextlessAuthorizerId = given()
.contentType(ContentType.JSON)
.body("""
{"name":"contextless-auth","authorizerType":"REQUEST","authorizerPayloadFormatVersion":"2.0","enableSimpleResponses":true,"authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"}
""".formatted(CONTEXTLESS_FN))
.when().post("/v2/apis/" + httpApiId + "/authorizers")
.then().statusCode(201)
.extract().path("authorizerId");
// Echo authorizer (format 1.0)
echoV1AuthorizerId = given()
.contentType(ContentType.JSON)
@@ -281,6 +333,24 @@ class HttpApiRequestAuthorizerTest {
.then().statusCode(200);
}
/**
* The context an IAM-policy authorizer returns alongside its policy document reaches the
* backend under requestContext.authorizer.lambda.
*/
@Test
@Order(15)
void iamPolicyContextReachesBackend() throws Exception {
// Route still carries allowAuthorizerId from the previous test.
String body = given()
.when().get("/execute-api/" + httpApiId + "/test/hello")
.then().statusCode(200)
.extract().asString();
JsonNode lambda = MAPPER.readTree(body).path("authorizer").path("lambda");
assertEquals("user123", lambda.path("userId").asText());
assertEquals("admin", lambda.path("role").asText());
}
// ──────────────────────────── Test: Deny with IAM policy (format 1.0) ────────────────────────────
@Test
@@ -335,6 +405,78 @@ class HttpApiRequestAuthorizerTest {
.then().statusCode(200);
}
@Test
@Order(45)
void simpleResponseContextReachesBackend() throws Exception {
// Route still carries simpleAllowAuthorizerId from the previous test.
String body = given()
.when().get("/execute-api/" + httpApiId + "/test/hello")
.then().statusCode(200)
.extract().asString();
JsonNode lambda = MAPPER.readTree(body).path("authorizer").path("lambda");
assertEquals("simple-user", lambda.path("userId").asText());
assertEquals("premium", lambda.path("plan").asText());
assertTrue(MAPPER.readTree(body).path("authorizer").path("jwt").isMissingNode(),
"A Lambda authorizer must not render the JWT-authorizer node");
}
/**
* An HTTP API delivers the authorizer context as JSON, so nested objects and non-string
* scalars survive to the backend, unlike a REST API's flattened string map.
*/
@Test
@Order(46)
void nestedContextSurvivesToBackend() throws Exception {
given()
.contentType(ContentType.JSON)
.body("""
{"authorizationType":"CUSTOM","authorizerId":"%s"}
""".formatted(nestedContextAuthorizerId))
.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();
JsonNode lambda = MAPPER.readTree(body).path("authorizer").path("lambda");
assertEquals("user-abc", lambda.path("jwt").path("claims").path("sub").asText(),
"Nested objects must not be flattened or stringified");
assertEquals("condo/read", lambda.path("jwt").path("claims").path("scope").asText());
assertEquals("CONDO_1", lambda.path("tenantId").asText());
assertEquals("PRO", lambda.path("licenseTier").asText());
assertTrue(lambda.path("requestCount").isNumber(), "A number must stay a number");
assertEquals(3, lambda.path("requestCount").asInt());
assertTrue(lambda.path("active").isBoolean(), "A boolean must stay a boolean");
assertTrue(lambda.path("groups").isArray(), "An array must stay an array");
assertEquals("auditor", lambda.path("groups").get(1).asText());
}
/** An authorizer that allows without returning a context leaves the authorizer node absent. */
@Test
@Order(47)
void contextlessAllowLeavesAuthorizerNodeAbsent() throws Exception {
given()
.contentType(ContentType.JSON)
.body("""
{"authorizationType":"CUSTOM","authorizerId":"%s"}
""".formatted(contextlessAuthorizerId))
.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();
JsonNode response = MAPPER.readTree(body);
assertEquals("Hello from backend", response.path("message").asText());
assertTrue(response.path("authorizer").isMissingNode(),
"No context returned means no authorizer node on the proxy event");
}
// ──────────────────────────── Test: Simple response Deny (format 2.0) ────────────────────────────
@Test
@@ -431,10 +573,8 @@ class HttpApiRequestAuthorizerTest {
.when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId)
.then().statusCode(200);
// The echo authorizer allows the request and embeds the received event in its context.
// The backend Lambda receives the proxy event which does NOT include authorizer context
// in the v2 proxy event format. So we verify the authorizer was invoked (200 response)
// and then invoke the echo function directly with a realistic event to verify format.
// 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")
@@ -571,7 +711,8 @@ class HttpApiRequestAuthorizerTest {
void cleanup() {
if (routeId != null) given().when().delete("/v2/apis/" + httpApiId + "/routes/" + routeId);
if (httpApiId != null) given().when().delete("/v2/apis/" + httpApiId);
for (String fn : new String[]{BACKEND_FN, ALLOW_FN, DENY_FN, ERROR_FN, SIMPLE_ALLOW_FN, SIMPLE_DENY_FN, ECHO_FN}) {
for (String fn : new String[]{BACKEND_FN, ALLOW_FN, DENY_FN, ERROR_FN, SIMPLE_ALLOW_FN,
SIMPLE_DENY_FN, ECHO_FN, NESTED_CTX_FN, CONTEXTLESS_FN}) {
deleteFunction(fn);
}
}