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. + * + *
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. * *
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 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