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

@@ -1479,9 +1479,14 @@ public class ApiGatewayExecuteController {
jwtScopes = jwtResult.scopes();
}
ObjectNode lambdaAuthorizerContext = null;
if ("CUSTOM".equalsIgnoreCase(route.getAuthorizationType()) && route.getAuthorizerId() != null) {
Response authError = enforceRequestAuthorizerV2(region, apiId, stageName, route, httpMethod, path, headers, uriInfo);
if (authError != null) return authError;
RequestAuthorizerResult requestResult =
enforceRequestAuthorizerV2(region, apiId, stageName, route, httpMethod, path, headers, uriInfo);
if (requestResult.errorResponse() != null) {
return requestResult.errorResponse();
}
lambdaAuthorizerContext = requestResult.context();
}
if (route.getTarget() == null) {
@@ -1520,7 +1525,8 @@ public class ApiGatewayExecuteController {
String requestId = UUID.randomUUID().toString();
String eventJson = buildV2ProxyEvent(httpMethod, path, route.getRouteKey(),
apiId, region, stageName, headers, uriInfo, body, requestId, jwtClaims, jwtScopes);
apiId, region, stageName, headers, uriInfo, body, requestId, jwtClaims, jwtScopes,
lambdaAuthorizerContext);
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → Lambda {4}", httpMethod, apiId, stageName, path, functionName);
@@ -1801,26 +1807,29 @@ public class ApiGatewayExecuteController {
// ──────────────────────────── HTTP API v2 Lambda REQUEST authorizer ────────────────────────────
// A null errorResponse means authorized, as in JwtAuthorizerResult.
private record RequestAuthorizerResult(Response errorResponse, ObjectNode context) {}
/**
* Enforces a Lambda REQUEST authorizer on an HTTP API (v2) route.
* Supports both payload format versions (1.0 and 2.0) and simple responses.
*
* @return null if authorized, or an error Response if denied/unauthorized
* @return a result whose errorResponse is null when authorized
*/
private Response enforceRequestAuthorizerV2(String region, String apiId, String stageName,
private RequestAuthorizerResult enforceRequestAuthorizerV2(String region, String apiId, String stageName,
Route route, String httpMethod, String path,
HttpHeaders headers, UriInfo uriInfo) {
Authorizer authorizer;
try {
authorizer = apiGatewayV2Service.getAuthorizer(region, apiId, route.getAuthorizerId());
} catch (AwsException e) {
return Response.status(500)
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Authorizer not found"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
if (!"REQUEST".equalsIgnoreCase(authorizer.getAuthorizerType())) {
return null; // Not a REQUEST authorizer — skip
return new RequestAuthorizerResult(null, null); // Not a REQUEST authorizer — skip
}
// Validate identity sources — if any configured source is missing, return 401 without invoking Lambda
@@ -1832,17 +1841,17 @@ public class ApiGatewayExecuteController {
String headerName = expression.substring("$request.header.".length());
String value = headers.getHeaderString(headerName);
if (value == null || value.isEmpty()) {
return Response.status(401)
return new RequestAuthorizerResult(Response.status(401)
.entity(jsonMessage("Unauthorized"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
} else if (expression.startsWith("$request.querystring.")) {
String paramName = expression.substring("$request.querystring.".length());
String value = queryParams.getFirst(paramName);
if (value == null || value.isEmpty()) {
return Response.status(401)
return new RequestAuthorizerResult(Response.status(401)
.entity(jsonMessage("Unauthorized"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
}
// $context.* identity sources are always present — no validation needed
@@ -1864,9 +1873,9 @@ public class ApiGatewayExecuteController {
String functionName = functionNameFromUri(authorizer.getAuthorizerUri());
if (functionName == null) {
LOG.warnv("Cannot extract function name from authorizer URI: {0}", authorizer.getAuthorizerUri());
return Response.status(500)
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
// Invoke the authorizer Lambda
@@ -1876,26 +1885,26 @@ public class ApiGatewayExecuteController {
eventJson.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);
} catch (Exception e) {
LOG.warnv("Lambda REQUEST authorizer invocation failed for API {0}: {1}", apiId, e.getMessage());
return Response.status(500)
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
// Check for function error (Lambda threw an exception)
if (invokeResult.getFunctionError() != null) {
LOG.warnv("Lambda REQUEST authorizer returned function error for API {0}: {1}",
apiId, invokeResult.getFunctionError());
return Response.status(500)
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
byte[] payload = invokeResult.getPayload();
if (payload == null || payload.length == 0) {
LOG.warnv("Lambda REQUEST authorizer returned empty payload for API {0}", apiId);
return Response.status(500)
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
// Parse the authorizer response
@@ -1909,66 +1918,77 @@ public class ApiGatewayExecuteController {
JsonNode isAuthorized = response.path("isAuthorized");
if (isAuthorized.isMissingNode() || isAuthorized.isNull()) {
LOG.warnv("Lambda REQUEST authorizer simple response missing isAuthorized for API {0}", apiId);
return Response.status(500)
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
if (!isAuthorized.asBoolean(false)) {
return Response.status(403)
return new RequestAuthorizerResult(Response.status(403)
.entity(jsonMessage("Forbidden"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
return null; // authorized
return new RequestAuthorizerResult(null, requestAuthorizerContext(response));
}
// IAM policy document format
JsonNode policyDocument = response.path("policyDocument");
if (policyDocument.isMissingNode() || policyDocument.isNull()) {
LOG.warnv("Authorizer response missing policyDocument for API {0}", apiId);
return Response.status(500)
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
JsonNode statements = policyDocument.path("Statement");
if (statements.isMissingNode() || statements.isNull()
|| !statements.isArray() || statements.isEmpty()) {
LOG.warnv("Authorizer response missing or empty Statement array for API {0}", apiId);
return Response.status(500)
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
String effect = statements.get(0).path("Effect").asText("Deny");
if ("Deny".equalsIgnoreCase(effect)) {
return Response.status(403)
return new RequestAuthorizerResult(Response.status(403)
.entity(jsonMessage("User is not authorized to access this resource"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
if (!"Allow".equalsIgnoreCase(effect)) {
LOG.warnv("Authorizer response has unrecognized Effect '{0}' for API {1}", effect, apiId);
return Response.status(500)
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
return null; // authorized
return new RequestAuthorizerResult(null, requestAuthorizerContext(response));
} catch (Exception e) {
LOG.warnv("Failed to parse authorizer response for API {0}: {1}", apiId, e.getMessage());
return Response.status(500)
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build();
.type(MediaType.APPLICATION_JSON).build(), null);
}
}
/**
* The {@code context} an authorizer response carries, or null when it carries none.
*
* <p>Values are not flattened to strings the way the v1/REST path flattens them
* (extractAuthorizerContext): an HTTP API delivers the context to the backend as JSON, so
* nested objects survive. A non-object context is treated as absent, as AWS rejects those.
*/
private ObjectNode requestAuthorizerContext(JsonNode response) {
JsonNode context = response.path("context");
return context.isObject() && !context.isEmpty() ? (ObjectNode) context : null;
}
/**
* 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.
* is.
*/
String buildRequestAuthorizerEventV1(String httpMethod, String path,
String apiId, String stageName, String region,
@@ -2218,15 +2238,24 @@ public class ApiGatewayExecuteController {
// jwtClaims is non-null only when the route's authorizer is JWT-type and verification
// succeeded (see dispatchV2/enforceJwtAuthorizer) - null means either no authorizer on this
// route (Auth: NONE) or a CUSTOM/REQUEST authorizer. jwtScopes is non-null only when that
// route additionally carries authorizationScopes (see JwtAuthorizerResult). Unlike the
// v1/REST CUSTOM-authorizer path (buildV1ProxyEvent's principalId/context handling), a v2
// CUSTOM/REQUEST authorizer's response context is not currently threaded into
// requestContext.authorizer here at all.
// route additionally carries authorizationScopes (see JwtAuthorizerResult).
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) {
return buildV2ProxyEvent(httpMethod, path, routeKey, apiId, region, stageName,
headers, uriInfo, body, requestId, jwtClaims, jwtScopes, null);
}
// lambdaAuthorizerContext is what a CUSTOM/REQUEST authorizer returned (see
// enforceRequestAuthorizerV2). It is mutually exclusive with jwtClaims: a route carries one
// authorizer, not both.
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) {
// 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
@@ -2302,6 +2331,14 @@ public class ApiGatewayExecuteController {
ArrayNode scopesNode = jwtNode.putArray("scopes");
jwtScopes.forEach(scopesNode::add);
}
} else if (lambdaAuthorizerContext != null) {
// AWS delivers the context verbatim under requestContext.authorizer.lambda, nesting
// included, unlike a REST API's flattened string map.
//
// Two omissions, both because the AWS behaviour could not be measured: principalId
// is not surfaced here, and a context-less allow leaves the authorizer node absent
// rather than rendering "lambda": null.
ctx.putObject("authorizer").set("lambda", lambdaAuthorizerContext);
}
if (body != null && body.length > 0) {