From 5772e49470772a2c32dc6ac1b3eeea15f2e5a450 Mon Sep 17 00:00:00 2001 From: Dixit R Jain Date: Sun, 24 May 2026 20:08:17 +0530 Subject: [PATCH] feat(apigateway): add Lambda REQUEST authorizer support for HTTP API v2 routes (#1011) Implement Lambda REQUEST authorizer invocation for HTTP API routes configured with authorizationType=CUSTOM. Previously, Floci silently skipped authorization for these routes. Supports: - Payload format version 1.0 (REST API-compatible event shape) - Payload format version 2.0 (HTTP API-native event shape) - Simple responses (isAuthorized: true/false) when enableSimpleResponses=true - IAM policy document responses (policyDocument with Allow/Deny) - Identity source validation ($request.header.X, $request.querystring.X) returning 401 without invoking Lambda when sources are missing Closes #812 --- .../ApiGatewayExecuteController.java | 272 ++++++++ .../HttpApiRequestAuthorizerTest.java | 580 ++++++++++++++++++ 2 files changed, 852 insertions(+) create mode 100644 src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java 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 ea2c644109..340963a492 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 @@ -1149,6 +1149,11 @@ public class ApiGatewayExecuteController { if (authError != null) return authError; } + if ("CUSTOM".equalsIgnoreCase(route.getAuthorizationType()) && route.getAuthorizerId() != null) { + Response authError = enforceRequestAuthorizerV2(region, apiId, stageName, route, httpMethod, path, headers, uriInfo); + if (authError != null) return authError; + } + if (route.getTarget() == null) { return Response.status(500) .entity(jsonMessage("No integration configured")) @@ -1409,6 +1414,273 @@ public class ApiGatewayExecuteController { return null; // authorized } + // ──────────────────────────── HTTP API v2 Lambda REQUEST authorizer ──────────────────────────── + + /** + * 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 + */ + private Response 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) + .entity(jsonMessage("Authorizer not found")) + .type(MediaType.APPLICATION_JSON).build(); + } + + if (!"REQUEST".equalsIgnoreCase(authorizer.getAuthorizerType())) { + return null; // Not a REQUEST authorizer — skip + } + + // Validate identity sources — if any configured source is missing, return 401 without invoking Lambda + List identitySources = authorizer.getIdentitySource(); + if (identitySources != null && !identitySources.isEmpty()) { + MultivaluedMap queryParams = uriInfo.getQueryParameters(); + for (String expression : identitySources) { + if (expression.startsWith("$request.header.")) { + String headerName = expression.substring("$request.header.".length()); + String value = headers.getHeaderString(headerName); + if (value == null || value.isEmpty()) { + return Response.status(401) + .entity(jsonMessage("Unauthorized")) + .type(MediaType.APPLICATION_JSON).build(); + } + } 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) + .entity(jsonMessage("Unauthorized")) + .type(MediaType.APPLICATION_JSON).build(); + } + } + // $context.* identity sources are always present — no validation needed + } + } + + // Build the authorizer event payload based on the configured payload format version + String payloadFormatVersion = authorizer.getAuthorizerPayloadFormatVersion(); + String eventJson; + if ("2.0".equals(payloadFormatVersion)) { + eventJson = buildRequestAuthorizerEventV2(httpMethod, path, route.getRouteKey(), + apiId, stageName, region, headers, uriInfo); + } else { + // Default to 1.0 format + eventJson = buildRequestAuthorizerEventV1(httpMethod, path, apiId, stageName, region, headers, uriInfo); + } + + // Extract the Lambda function name from the authorizer URI + String functionName = functionNameFromUri(authorizer.getAuthorizerUri()); + if (functionName == null) { + LOG.warnv("Cannot extract function name from authorizer URI: {0}", authorizer.getAuthorizerUri()); + return Response.status(500) + .entity(jsonMessage("Internal Server Error")) + .type(MediaType.APPLICATION_JSON).build(); + } + + // Invoke the authorizer Lambda + InvokeResult invokeResult; + try { + invokeResult = lambdaService.invoke(region, functionName, + 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) + .entity(jsonMessage("Internal Server Error")) + .type(MediaType.APPLICATION_JSON).build(); + } + + // 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) + .entity(jsonMessage("Internal Server Error")) + .type(MediaType.APPLICATION_JSON).build(); + } + + 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) + .entity(jsonMessage("Internal Server Error")) + .type(MediaType.APPLICATION_JSON).build(); + } + + // Parse the authorizer response + try { + JsonNode response = objectMapper.readTree(payload); + + // Check if simple responses are enabled (format 2.0 feature) + Boolean enableSimpleResponses = authorizer.getEnableSimpleResponses(); + if (Boolean.TRUE.equals(enableSimpleResponses)) { + // Simple response format: {"isAuthorized": true/false, "context": {...}} + 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) + .entity(jsonMessage("Internal Server Error")) + .type(MediaType.APPLICATION_JSON).build(); + } + if (!isAuthorized.asBoolean(false)) { + return Response.status(403) + .entity(jsonMessage("Forbidden")) + .type(MediaType.APPLICATION_JSON).build(); + } + return null; // authorized + } + + // 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) + .entity(jsonMessage("Internal Server Error")) + .type(MediaType.APPLICATION_JSON).build(); + } + + 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) + .entity(jsonMessage("Internal Server Error")) + .type(MediaType.APPLICATION_JSON).build(); + } + + String effect = statements.get(0).path("Effect").asText("Deny"); + if ("Deny".equalsIgnoreCase(effect)) { + return Response.status(403) + .entity(jsonMessage("User is not authorized to access this resource")) + .type(MediaType.APPLICATION_JSON).build(); + } + + if (!"Allow".equalsIgnoreCase(effect)) { + LOG.warnv("Authorizer response has unrecognized Effect '{0}' for API {1}", effect, apiId); + return Response.status(500) + .entity(jsonMessage("Internal Server Error")) + .type(MediaType.APPLICATION_JSON).build(); + } + + return null; // authorized + } catch (Exception e) { + LOG.warnv("Failed to parse authorizer response for API {0}: {1}", apiId, e.getMessage()); + return Response.status(500) + .entity(jsonMessage("Internal Server Error")) + .type(MediaType.APPLICATION_JSON).build(); + } + } + + /** + * Builds a REQUEST authorizer event in payload format version 1.0. + * Compatible with REST API (v1) REQUEST authorizer shape. + */ + private String buildRequestAuthorizerEventV1(String httpMethod, String path, + String apiId, String stageName, String region, + HttpHeaders headers, UriInfo uriInfo) { + ObjectNode event = objectMapper.createObjectNode(); + event.put("version", "1.0"); + event.put("type", "REQUEST"); + event.put("methodArn", buildMethodArn(region, apiId, stageName, httpMethod, path)); + event.put("resource", path); + event.put("path", path); + event.put("httpMethod", httpMethod); + + putSingleValueHeaders(event, headers); + putMultiValueHeaders(event, headers); + putQueryStringParameters(event, uriInfo); + putMultiValueQueryStringParameters(event, uriInfo); + + event.putObject("pathParameters"); + event.putNull("stageVariables"); + + // Request context + ObjectNode ctx = event.putObject("requestContext"); + ctx.put("accountId", regionResolver.getAccountId()); + ctx.put("apiId", apiId); + ctx.put("httpMethod", httpMethod); + ctx.put("path", path); + ctx.put("resourcePath", path); + ctx.put("stage", stageName); + ctx.put("requestId", UUID.randomUUID().toString()); + + try { + return objectMapper.writeValueAsString(event); + } catch (Exception e) { + throw new RuntimeException("Failed to serialize v1 authorizer event", e); + } + } + + /** + * Builds a REQUEST authorizer event in payload format version 2.0. + * Uses the newer HTTP API-native shape with routeArn, routeKey, rawPath, and requestContext.http. + */ + private String buildRequestAuthorizerEventV2(String httpMethod, String path, String routeKey, + String apiId, String stageName, String region, + HttpHeaders headers, UriInfo uriInfo) { + ObjectNode event = objectMapper.createObjectNode(); + event.put("version", "2.0"); + event.put("type", "REQUEST"); + event.put("routeArn", buildMethodArn(region, apiId, stageName, httpMethod, path)); + event.put("routeKey", routeKey != null ? routeKey : "$default"); + event.put("rawPath", path); + event.put("rawQueryString", uriInfo.getRequestUri().getRawQuery() != null + ? uriInfo.getRequestUri().getRawQuery() : ""); + + // Headers (lowercase keys for v2) + ObjectNode headersNode = event.putObject("headers"); + MultivaluedMap reqHeaders = headers.getRequestHeaders(); + for (Map.Entry> e : reqHeaders.entrySet()) { + if (!e.getValue().isEmpty()) headersNode.put(e.getKey().toLowerCase(), e.getValue().get(0)); + } + + // Query string parameters + MultivaluedMap queryParams = uriInfo.getQueryParameters(); + if (!queryParams.isEmpty()) { + ObjectNode qsp = event.putObject("queryStringParameters"); + for (Map.Entry> e : queryParams.entrySet()) { + if (!e.getValue().isEmpty()) qsp.put(e.getKey(), e.getValue().get(0)); + } + } + + event.putObject("pathParameters"); + event.putNull("stageVariables"); + + // Request context + ObjectNode ctx = event.putObject("requestContext"); + String arnRegion = region != null ? region : regionResolver.getDefaultRegion(); + ctx.put("accountId", regionResolver.getAccountId()); + ctx.put("apiId", apiId); + ctx.put("domainName", apiId + ".execute-api." + arnRegion + ".amazonaws.com"); + ctx.put("domainPrefix", apiId); + ctx.put("requestId", UUID.randomUUID().toString()); + ctx.put("routeKey", routeKey != null ? routeKey : "$default"); + ctx.put("stage", stageName); + ctx.put("time", java.time.format.DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z") + .format(java.time.ZonedDateTime.now())); + ctx.put("timeEpoch", System.currentTimeMillis()); + + ObjectNode http = ctx.putObject("http"); + http.put("method", httpMethod); + http.put("path", path); + http.put("protocol", "HTTP/1.1"); + http.put("sourceIp", "127.0.0.1"); + http.put("userAgent", headers.getHeaderString("User-Agent") != null + ? headers.getHeaderString("User-Agent") : ""); + + try { + return objectMapper.writeValueAsString(event); + } catch (Exception e) { + throw new RuntimeException("Failed to serialize v2 authorizer event", e); + } + } + private String extractToken(Authorizer authorizer, HttpHeaders headers) { List sources = authorizer.getIdentitySource(); if (sources == null || sources.isEmpty()) { 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 new file mode 100644 index 0000000000..0c4bb62f2a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java @@ -0,0 +1,580 @@ +package io.github.hectorvent.floci.services.apigatewayv2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +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.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Integration tests for Lambda REQUEST authorizer on HTTP API (v2) routes (issue #812). + * + *

Covers payload format versions 1.0 and 2.0, simple responses, identity source + * validation, and deny/allow/error scenarios. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class HttpApiRequestAuthorizerTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String httpApiId; + private static String integrationId; + private static String routeId; + private static String allowAuthorizerId; + private static String denyAuthorizerId; + private static String errorAuthorizerId; + private static String simpleAllowAuthorizerId; + private static String simpleDenyAuthorizerId; + private static String identitySourceAuthorizerId; + private static String echoV1AuthorizerId; + private static String echoV2AuthorizerId; + + private static final String ALLOW_FN = "httpv2-auth-allow-fn"; + private static final String DENY_FN = "httpv2-auth-deny-fn"; + private static final String ERROR_FN = "httpv2-auth-error-fn"; + private static final String SIMPLE_ALLOW_FN = "httpv2-auth-simple-allow-fn"; + 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"; + + // ──────────────────────────── Setup ──────────────────────────── + + @Test + @Order(1) + void setupHttpApi() { + httpApiId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"http-v2-authorizer-test","protocolType":"HTTP"} + """) + .when().post("/v2/apis") + .then() + .statusCode(201) + .body("apiId", notNullValue()) + .extract().path("apiId"); + + given() + .contentType(ContentType.JSON) + .body(""" + {"stageName":"test"} + """) + .when().post("/v2/apis/" + httpApiId + "/stages") + .then() + .statusCode(201); + } + + @Test + @Order(2) + void setupLambdaFunctions() throws Exception { + // Backend Lambda + createNodeLambda(BACKEND_FN, """ + exports.handler = async (event) => ({ + statusCode: 200, + body: JSON.stringify({ message: "Hello from backend", path: event.rawPath }) + }); + """); + + // Authorizer that returns Allow policy (IAM policy format) + createNodeLambda(ALLOW_FN, """ + exports.handler = async (event) => ({ + principalId: "user123", + policyDocument: { + Version: "2012-10-17", + Statement: [{ Action: "execute-api:Invoke", Effect: "Allow", Resource: event.methodArn || event.routeArn || "*" }] + }, + context: { userId: "user123", role: "admin" } + }); + """); + + // Authorizer that returns Deny policy + createNodeLambda(DENY_FN, """ + exports.handler = async (event) => ({ + principalId: "user123", + policyDocument: { + Version: "2012-10-17", + Statement: [{ Action: "execute-api:Invoke", Effect: "Deny", Resource: event.methodArn || event.routeArn || "*" }] + } + }); + """); + + // Authorizer that throws an error + createNodeLambda(ERROR_FN, """ + exports.handler = async (event) => { throw new Error("Authorizer error"); }; + """); + + // Authorizer that returns simple Allow response (format 2.0) + createNodeLambda(SIMPLE_ALLOW_FN, """ + exports.handler = async (event) => ({ + isAuthorized: true, + context: { userId: "simple-user", plan: "premium" } + }); + """); + + // Authorizer that returns simple Deny response (format 2.0) + createNodeLambda(SIMPLE_DENY_FN, """ + exports.handler = async (event) => ({ + isAuthorized: false + }); + """); + + // Echo authorizer that returns the event payload in context + createNodeLambda(ECHO_FN, """ + exports.handler = async (event) => ({ + principalId: "echo-user", + policyDocument: { + Version: "2012-10-17", + Statement: [{ Action: "execute-api:Invoke", Effect: "Allow", Resource: event.methodArn || event.routeArn || "*" }] + }, + context: { receivedEvent: JSON.stringify(event) } + }); + """); + } + + @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}) { + given().contentType(ContentType.JSON).body("{}") + .when().post("/2015-03-31/functions/" + fn + "/invocations") + .then().statusCode(200); + } + } + + @Test + @Order(4) + void setupIntegrationAndRoute() { + integrationId = given() + .contentType(ContentType.JSON) + .body(""" + {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST","payloadFormatVersion":"2.0"} + """.formatted(BACKEND_FN)) + .when().post("/v2/apis/" + httpApiId + "/integrations") + .then() + .statusCode(201) + .extract().path("integrationId"); + + routeId = given() + .contentType(ContentType.JSON) + .body(""" + {"routeKey":"GET /hello","target":"integrations/%s"} + """.formatted(integrationId)) + .when().post("/v2/apis/" + httpApiId + "/routes") + .then() + .statusCode(201) + .extract().path("routeId"); + } + + @Test + @Order(5) + void setupAuthorizers() { + // Allow authorizer (IAM policy format, payload version 1.0) + allowAuthorizerId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"allow-auth","authorizerType":"REQUEST","authorizerPayloadFormatVersion":"1.0","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"} + """.formatted(ALLOW_FN)) + .when().post("/v2/apis/" + httpApiId + "/authorizers") + .then().statusCode(201) + .extract().path("authorizerId"); + + // Deny authorizer (IAM policy format, payload version 1.0) + denyAuthorizerId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"deny-auth","authorizerType":"REQUEST","authorizerPayloadFormatVersion":"1.0","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"} + """.formatted(DENY_FN)) + .when().post("/v2/apis/" + httpApiId + "/authorizers") + .then().statusCode(201) + .extract().path("authorizerId"); + + // Error authorizer + errorAuthorizerId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"error-auth","authorizerType":"REQUEST","authorizerPayloadFormatVersion":"1.0","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"} + """.formatted(ERROR_FN)) + .when().post("/v2/apis/" + httpApiId + "/authorizers") + .then().statusCode(201) + .extract().path("authorizerId"); + + // Simple allow authorizer (format 2.0 with enableSimpleResponses) + simpleAllowAuthorizerId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"simple-allow-auth","authorizerType":"REQUEST","authorizerPayloadFormatVersion":"2.0","enableSimpleResponses":true,"authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"} + """.formatted(SIMPLE_ALLOW_FN)) + .when().post("/v2/apis/" + httpApiId + "/authorizers") + .then().statusCode(201) + .extract().path("authorizerId"); + + // Simple deny authorizer (format 2.0 with enableSimpleResponses) + simpleDenyAuthorizerId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"simple-deny-auth","authorizerType":"REQUEST","authorizerPayloadFormatVersion":"2.0","enableSimpleResponses":true,"authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"} + """.formatted(SIMPLE_DENY_FN)) + .when().post("/v2/apis/" + httpApiId + "/authorizers") + .then().statusCode(201) + .extract().path("authorizerId"); + + // Identity source authorizer (requires Authorization header) + identitySourceAuthorizerId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"identity-auth","authorizerType":"REQUEST","authorizerPayloadFormatVersion":"1.0","identitySource":"$request.header.Authorization","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"} + """.formatted(ALLOW_FN)) + .when().post("/v2/apis/" + httpApiId + "/authorizers") + .then().statusCode(201) + .extract().path("authorizerId"); + + // Echo authorizer (format 1.0) + echoV1AuthorizerId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"echo-auth-v1","authorizerType":"REQUEST","authorizerPayloadFormatVersion":"1.0","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"} + """.formatted(ECHO_FN)) + .when().post("/v2/apis/" + httpApiId + "/authorizers") + .then().statusCode(201) + .extract().path("authorizerId"); + + // Echo authorizer (format 2.0) + echoV2AuthorizerId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"echo-auth-v2","authorizerType":"REQUEST","authorizerPayloadFormatVersion":"2.0","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"} + """.formatted(ECHO_FN)) + .when().post("/v2/apis/" + httpApiId + "/authorizers") + .then().statusCode(201) + .extract().path("authorizerId"); + } + + // ──────────────────────────── Test: Allow with IAM policy (format 1.0) ──────────────────────────── + + @Test + @Order(10) + void requestAuthorizerAllowsWithIamPolicy() { + given() + .contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(allowAuthorizerId)) + .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId) + .then().statusCode(200); + + given() + .when().get("/execute-api/" + httpApiId + "/test/hello") + .then().statusCode(200); + } + + // ──────────────────────────── Test: Deny with IAM policy (format 1.0) ──────────────────────────── + + @Test + @Order(20) + void requestAuthorizerDeniesWithIamPolicy() { + given() + .contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(denyAuthorizerId)) + .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId) + .then().statusCode(200); + + given() + .when().get("/execute-api/" + httpApiId + "/test/hello") + .then().statusCode(403); + } + + // ──────────────────────────── Test: Authorizer invocation error returns 500 ──────────────────────────── + + @Test + @Order(30) + void requestAuthorizerErrorReturns500() { + given() + .contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(errorAuthorizerId)) + .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId) + .then().statusCode(200); + + given() + .when().get("/execute-api/" + httpApiId + "/test/hello") + .then().statusCode(500); + } + + // ──────────────────────────── Test: Simple response Allow (format 2.0) ──────────────────────────── + + @Test + @Order(40) + void simpleResponseAllows() { + given() + .contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(simpleAllowAuthorizerId)) + .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId) + .then().statusCode(200); + + given() + .when().get("/execute-api/" + httpApiId + "/test/hello") + .then().statusCode(200); + } + + // ──────────────────────────── Test: Simple response Deny (format 2.0) ──────────────────────────── + + @Test + @Order(50) + void simpleResponseDenies() { + given() + .contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(simpleDenyAuthorizerId)) + .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId) + .then().statusCode(200); + + given() + .when().get("/execute-api/" + httpApiId + "/test/hello") + .then().statusCode(403); + } + + // ──────────────────────────── Test: Missing identity source returns 401 ──────────────────────────── + + @Test + @Order(60) + void missingIdentitySourceReturns401() { + given() + .contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(identitySourceAuthorizerId)) + .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId) + .then().statusCode(200); + + // Request WITHOUT the required Authorization header — should get 401 + given() + .when().get("/execute-api/" + httpApiId + "/test/hello") + .then().statusCode(401); + } + + // ──────────────────────────── Test: Present identity source allows invocation ──────────────────────────── + + @Test + @Order(61) + void presentIdentitySourceAllowsInvocation() { + // Route still has identitySourceAuthorizerId from previous test + given() + .header("Authorization", "Bearer my-token") + .when().get("/execute-api/" + httpApiId + "/test/hello") + .then().statusCode(200); + } + + // ──────────────────────────── Test: Query string identity source validation ──────────────────────────── + + @Test + @Order(70) + void queryStringIdentitySourceValidation() { + String qsAuthorizerId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"qs-identity-auth","authorizerType":"REQUEST","authorizerPayloadFormatVersion":"1.0","identitySource":"$request.querystring.token","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"} + """.formatted(ALLOW_FN)) + .when().post("/v2/apis/" + httpApiId + "/authorizers") + .then().statusCode(201) + .extract().path("authorizerId"); + + given() + .contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(qsAuthorizerId)) + .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId) + .then().statusCode(200); + + // Without required query param — 401 + given() + .when().get("/execute-api/" + httpApiId + "/test/hello") + .then().statusCode(401); + + // With required query param — succeeds + given() + .queryParam("token", "my-secret-token") + .when().get("/execute-api/" + httpApiId + "/test/hello") + .then().statusCode(200); + } + + // ──────────────────────────── Test: Payload format 1.0 event shape ──────────────────────────── + + @Test + @Order(80) + void payloadFormat10EventShape() throws Exception { + given() + .contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(echoV1AuthorizerId)) + .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. + String response = given() + .header("X-Custom-Header", "test-value") + .queryParam("foo", "bar") + .when().get("/execute-api/" + httpApiId + "/test/hello") + .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); + assertNotNull(authEventStr, "Echo authorizer should embed receivedEvent in context"); + JsonNode authEvent = MAPPER.readTree(authEventStr); + + assertEquals("REQUEST", authEvent.path("type").asText(), "Event type should be REQUEST"); + assertEquals("1.0", authEvent.path("version").asText(), "Event version should be 1.0"); + 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"); + } + + // ──────────────────────────── Test: Payload format 2.0 event shape ──────────────────────────── + + @Test + @Order(90) + void payloadFormat20EventShape() throws Exception { + given() + .contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(echoV2AuthorizerId)) + .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId) + .then().statusCode(200); + + String response = given() + .header("X-Custom-Header", "test-value-v2") + .queryParam("key", "value") + .when().get("/execute-api/" + httpApiId + "/test/hello") + .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); + assertNotNull(authEventStr, "Echo authorizer should embed receivedEvent in context"); + JsonNode authEvent = MAPPER.readTree(authEventStr); + + assertEquals("REQUEST", authEvent.path("type").asText(), "Event type should be REQUEST"); + assertEquals("2.0", authEvent.path("version").asText(), "Event version should be 2.0"); + 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"); + } + + // ──────────────────────────── Test: No authorizer (NONE) allows request ──────────────────────────── + + @Test + @Order(100) + void noAuthorizerAllowsRequest() { + given() + .contentType(ContentType.JSON) + .body(""" + {"authorizationType":"NONE","authorizerId":null} + """) + .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId) + .then().statusCode(200); + + given() + .when().get("/execute-api/" + httpApiId + "/test/hello") + .then().statusCode(200); + } + + // ──────────────────────────── Cleanup ──────────────────────────── + + @Test + @Order(999) + 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}) { + deleteFunction(fn); + } + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private static void createNodeLambda(String functionName, String handlerSource) throws Exception { + String zipBase64 = Base64.getEncoder().encodeToString(zipEntries(Map.of("index.js", handlerSource))); + given() + .contentType(ContentType.JSON) + .body(""" + {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}} + """.formatted(functionName, zipBase64)) + .when().post("/2015-03-31/functions") + .then().statusCode(201); + } + + private static byte[] zipEntries(Map entries) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ZipOutputStream zos = new ZipOutputStream(baos)) { + for (Map.Entry entry : entries.entrySet()) { + zos.putNextEntry(new ZipEntry(entry.getKey())); + zos.write(entry.getValue().getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + } + } + return baos.toByteArray(); + } + + private static void deleteFunction(String functionName) { + int statusCode = given() + .when().delete("/2015-03-31/functions/" + functionName) + .then().extract().statusCode(); + assertTrue(statusCode == 204 || statusCode == 404); + } +}