Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Brian Taylor908d70db3d13
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 3ab551190f..8d20ff5491 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
@@ -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) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java
index 911488b0b7..047becb996 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java
@@ -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
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventLambdaAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventLambdaAuthorizerTest.java
new file mode 100644
index 0000000000..05ba2cb705
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventLambdaAuthorizerTest.java
@@ -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");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java
index d322b93126..ee208bbf30 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java
@@ -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);
}
}