diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index 27c7902852..8012fffb59 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -728,6 +728,15 @@ curl http://{apiId}.execute-api.{region}.localhost.floci.io:4566/{stageName}/{pa APIs created or updated with `disableExecuteApiEndpoint` reject requests to this default hostname with `404 Not Found`, matching AWS HTTP API behavior. +HTTP API Lambda REQUEST authorizers resolve header, query string, context, and +stage variable sources once, in configured order. Format `2.0` carries the values +in an `identitySource` array; format `1.0` carries them as comma-separated +`identitySource` and `authorizationToken` strings. Headers are case-insensitive; +query names are case-sensitive. No configured sources produces an empty array +or string. A missing or empty configured value returns `401` without invoking +Lambda in either format. Repeated request values use each event's delivered +representation: last value in format `1.0`, comma-joined values in format `2.0`. + A Lambda proxy integration's response is read as AWS reads it (measured): a function that raises, a format 1.0 result that is not an object with a `statusCode`, and a `statusCode` that is not a whole number from 100 to 599 (text that spells one, such as `"201"`, is taken) are answered `500` with 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 4d16b26848..362571ceb9 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 @@ -3263,43 +3263,35 @@ public class ApiGatewayExecuteController { return new RequestAuthorizerResult(null, null); // Not a REQUEST authorizer — skip } - // Validate identity sources — if any configured source is missing, return 401 without invoking Lambda + String payloadFormatVersion = authorizer.getAuthorizerPayloadFormatVersion(); + boolean formatTwo = "2.0".equals(payloadFormatVersion); + ObjectNode event = formatTwo + ? buildRequestAuthorizerEventV2(httpMethod, path, route.getRouteKey(), + apiId, stageName, region, headers, uriInfo, stageVariables) + : buildRequestAuthorizerEventV1(httpMethod, path, apiId, stageName, + region, headers, uriInfo, stageVariables); + ((ObjectNode) event.path("requestContext")).put("routeKey", route.getRouteKey()); + List identityValues = new ArrayList<>(); 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 new RequestAuthorizerResult(Response.status(401) - .entity(jsonMessage("Unauthorized")) - .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 new RequestAuthorizerResult(Response.status(401) - .entity(jsonMessage("Unauthorized")) - .type(MediaType.APPLICATION_JSON).build(), null); - } + if (identitySources != null) { + for (String source : identitySources) { + String value = httpApiAuthorizerIdentityValue(event, source); + if (value == null || value.isEmpty()) { + return new RequestAuthorizerResult(Response.status(401) + .entity(jsonMessage("Unauthorized")) + .type(MediaType.APPLICATION_JSON).build(), null); } - // $context.* identity sources are always present — no validation needed + identityValues.add(value); } } - - // 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, stageVariables); + if (formatTwo) { + event.set("identitySource", objectMapper.valueToTree(identityValues)); } else { - // Default to 1.0 format - eventJson = buildRequestAuthorizerEventV1(httpMethod, path, apiId, stageName, - region, headers, uriInfo, stageVariables); + String identities = String.join(",", identityValues); + event.put("identitySource", identities); + event.put("authorizationToken", identities); } + String eventJson = event.toString(); // Extract the Lambda function name from the authorizer URI String functionName = functionNameFromUri(authorizer.getAuthorizerUri()); @@ -3411,7 +3403,7 @@ public class ApiGatewayExecuteController { *

Package-private so the shape can be asserted directly, the way {@code buildV2ProxyEvent} * is. */ - String buildRequestAuthorizerEventV1(String httpMethod, String path, + ObjectNode buildRequestAuthorizerEventV1(String httpMethod, String path, String apiId, String stageName, String region, HttpHeaders headers, UriInfo uriInfo, Map stageVariables) { @@ -3450,19 +3442,25 @@ public class ApiGatewayExecuteController { ctx.put("resourcePath", preservedPath); 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); - } + ctx.put("protocol", "HTTP/1.1"); + Instant now = Instant.now(); + ctx.put("requestTime", GATEWAY_REQUEST_TIME.format(now.atZone(ZoneOffset.UTC))); + ctx.put("requestTimeEpoch", now.toEpochMilli()); + String arnRegion = region != null ? region : regionResolver.getDefaultRegion(); + ctx.put("domainName", AwsEndpoints.executeApiHost(apiId, arnRegion)); + ctx.put("domainPrefix", apiId); + ObjectNode identity = ctx.putObject("identity"); + identity.put("sourceIp", "127.0.0.1"); + identity.put("userAgent", headers.getHeaderString("User-Agent") != null + ? headers.getHeaderString("User-Agent") : ""); + return event; } /** * 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. */ - String buildRequestAuthorizerEventV2(String httpMethod, String path, String routeKey, + ObjectNode buildRequestAuthorizerEventV2(String httpMethod, String path, String routeKey, String apiId, String stageName, String region, HttpHeaders headers, UriInfo uriInfo, Map stageVariables) { @@ -3506,11 +3504,43 @@ public class ApiGatewayExecuteController { 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); + return event; + } + + private static String httpApiAuthorizerIdentityValue(ObjectNode event, String source) { + boolean formatTwo = "2.0".equals(event.path("version").asText()); + JsonNode value; + if (source.startsWith("$request.header.")) { + return findHeaderIgnoreCase(event.path("headers"), source.substring("$request.header.".length())).orElse(null); + } else if (source.startsWith("$request.querystring.")) { + value = event.path("queryStringParameters").path(source.substring("$request.querystring.".length())); + } else if (source.startsWith("$stageVariables.")) { + value = event.path("stageVariables").path(source.substring("$stageVariables.".length())); + } else if (source.startsWith("$context.")) { + String variable = source.substring("$context.".length()); + if ("path".equals(variable)) { + JsonNode context = event.path("requestContext"); + String stage = context.path("stage").asText(); + String path = formatTwo ? context.path("http").path("path").asText() : context.path("path").asText(); + return ("$default".equals(stage) ? "" : "/" + stage) + path; + } + String field = "extendedRequestId".equals(variable) ? "requestId" : variable; + if (formatTwo) { + field = switch (variable) { + case "httpMethod" -> "http.method"; + case "protocol" -> "http.protocol"; + case "identity.sourceIp" -> "http.sourceIp"; + case "identity.userAgent" -> "http.userAgent"; + case "requestTime" -> "time"; + case "requestTimeEpoch" -> "timeEpoch"; + default -> field; + }; + } + value = event.at("/requestContext/" + field.replace('.', '/')); + } else { + return null; } + return value.isValueNode() && !value.isNull() ? value.asText() : null; } private String extractToken(Authorizer authorizer, HttpHeaders headers, UriInfo uriInfo) { @@ -3887,7 +3917,7 @@ public class ApiGatewayExecuteController { ObjectNode headersNode = event.putObject("headers"); for (Map.Entry> e : requestHeaders.entrySet()) { if (!e.getValue().isEmpty()) { - headersNode.put(e.getKey().toLowerCase(), String.join(",", e.getValue())); + headersNode.put(e.getKey().toLowerCase(Locale.ROOT), String.join(",", e.getValue())); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java index 0f30855102..5e224bb80d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java @@ -767,7 +767,7 @@ class ApiGatewayExecuteControllerTest { ApiGatewayExecuteController controller = controller(new ObjectMapper()); assertEnglishUtcTimeUnderNonUtcHost(() -> controller.buildRequestAuthorizerEventV2("GET", "/items", "GET /items", "api1", "$default", "us-east-1", emptyHeaders(), - uriInfoFor("http://localhost/items"), null)); + uriInfoFor("http://localhost/items"), null).toString()); } private static HttpHeaders emptyHeaders() { diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.java index e24a01ad3f..fa948c94dc 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.java @@ -53,9 +53,8 @@ class BuildV2AuthorizerEventTrailingSlashTest { private JsonNode buildEvent(String normalizedPath, String rawRequestUri) throws Exception { when(uriInfo.getRequestUri()).thenReturn(new URI(rawRequestUri)); - String json = controller.buildRequestAuthorizerEventV1( + return controller.buildRequestAuthorizerEventV1( "GET", normalizedPath, "abc123", "test", "us-east-1", headers, uriInfo, null); - return new ObjectMapper().readTree(json); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventMultiValueTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventMultiValueTest.java index 23c46a0460..361ceae765 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventMultiValueTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventMultiValueTest.java @@ -13,6 +13,7 @@ import org.junit.jupiter.params.provider.EnumSource; import java.net.URI; import java.util.List; +import java.util.Locale; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -65,7 +66,7 @@ class BuildV2ProxyEventMultiValueTest { "abc123", "us-east-1", "$default", headers, uriInfo, null, "req-1"); case AUTHORIZER -> controller.buildRequestAuthorizerEventV2( "GET", "/echo", "GET /echo", - "abc123", "$default", "us-east-1", headers, uriInfo, null); + "abc123", "$default", "us-east-1", headers, uriInfo, null).toString(); }; return new ObjectMapper().readTree(json); } @@ -82,6 +83,19 @@ class BuildV2ProxyEventMultiValueTest { assertEquals("x", qsp.get("single").asText()); } + @ParameterizedTest + @EnumSource(Builder.class) + void headerNamesUseLocaleIndependentCaseFolding(Builder builder) throws Exception { + requestHeaders.add("X-Identity", "identity-value"); + Locale original = Locale.getDefault(); + try { + Locale.setDefault(Locale.forLanguageTag("tr-TR")); + assertEquals("identity-value", buildEvent(builder).path("headers").path("x-identity").asText()); + } finally { + Locale.setDefault(original); + } + } + @ParameterizedTest @EnumSource(Builder.class) void repeatedHeaderIsCommaJoined(Builder builder) throws Exception { diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventStageVariablesTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventStageVariablesTest.java index a854873f80..d64d5feed7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventStageVariablesTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventStageVariablesTest.java @@ -82,11 +82,11 @@ class BuildV2ProxyEventStageVariablesTest { private List buildAuthorizerEvents(Map stageVariables) throws Exception { return List.of( - MAPPER.readTree(controller.buildRequestAuthorizerEventV1( + controller.buildRequestAuthorizerEventV1( "GET", "/echo", "abc123", "test", "us-east-1", - headers, uriInfo, stageVariables)), - MAPPER.readTree(controller.buildRequestAuthorizerEventV2( + headers, uriInfo, stageVariables), + controller.buildRequestAuthorizerEventV2( "GET", "/echo", "GET /echo", "abc123", "test", "us-east-1", - headers, uriInfo, stageVariables))); + headers, uriInfo, stageVariables)); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiAuthorizerIdentitySourceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiAuthorizerIdentitySourceIntegrationTest.java new file mode 100644 index 0000000000..cfa918819d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiAuthorizerIdentitySourceIntegrationTest.java @@ -0,0 +1,230 @@ +package io.github.hectorvent.floci.services.apigatewayv2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import static io.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.AUTHORIZER; +import static io.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.BACKEND; +import static io.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.result; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +@QuarkusTest +class HttpApiAuthorizerIdentitySourceIntegrationTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @InjectMock + LambdaService lambdaService; + + private final AtomicReference authorizerEvent = new AtomicReference<>(); + private String apiId; + private String stageName = "test"; + private String payloadFormat = "2.0"; + private boolean allowed = true; + + @BeforeEach + void stubLambdaBoundary() { + LambdaAuthorizerApiFixtures.stubAuthorizer(lambdaService, event -> { + authorizerEvent.set(event); + if ("1.0".equals(payloadFormat)) { + return result("{\"principalId\":\"user\",\"policyDocument\":{\"Version\":\"2012-10-17\"," + + "\"Statement\":[{\"Action\":\"execute-api:Invoke\",\"Effect\":\"" + + (allowed ? "Allow" : "Deny") + "\",\"Resource\":\"" + + event.path("methodArn").asText() + "\"}]}}"); + } + return result("{\"isAuthorized\":" + allowed + "}"); + }); + LambdaAuthorizerApiFixtures.stubBackend(lambdaService); + } + + @AfterEach + void deleteApi() { + if (apiId != null) { + given().delete("/v2/apis/" + apiId).then().statusCode(204); + } + } + + @Test + void headerIdentityIsAnArrayAndKeepsTheBearerPrefix() { + configureApi(List.of("$request.header.authorization")); + given().header("Authorization", "Bearer opaque-token").get(path()).then().statusCode(200); + assertIdentities(List.of("Bearer opaque-token")); + } + + @Test + void multipleSourcesKeepConfiguredOrderAndResolveContextAndStageValues() { + configureApi(List.of("$context.routeKey", "$stageVariables.tenant", "$request.querystring.Token", + "$request.header.X-Identity", "$context.stage", "$context.requestId")); + given().header("x-identity", "header-value").queryParam("Token", "query-value") + .get(path()).then().statusCode(200); + JsonNode event = authorizerEvent.get(); + assertNotNull(event); + assertIdentities(List.of("GET /items", "stage-tenant", "query-value", "header-value", "test", + event.path("requestContext").path("requestId").asText())); + } + + @Test + void contextAliasesUseTheValuesFromThisEvent() { + configureApi(List.of("$context.httpMethod", "$context.protocol", "$context.identity.sourceIp", + "$context.identity.userAgent", "$context.requestTime", "$context.requestTimeEpoch", "$context.extendedRequestId")); + given().header("User-Agent", "identity-client").get(path()).then().statusCode(200); + JsonNode context = authorizerEvent.get().path("requestContext"); + assertIdentities(List.of("GET", "HTTP/1.1", context.path("http").path("sourceIp").asText(), + "identity-client", context.path("time").asText(), context.path("timeEpoch").asText(), + context.path("requestId").asText())); + } + + @ParameterizedTest + @CsvSource({"1.0,test", "1.0,$default", "2.0,test", "2.0,$default"}) + void contextPathIncludesOnlyANamedStage(String format, String stage) { + payloadFormat = format; + stageName = stage; + configureApi(List.of("$context.path")); + given().get(path()).then().statusCode(200); + assertIdentities(List.of("$default".equals(stage) ? "/items" : "/test/items")); + } + + @Test + void repeatedRequestValuesAreJoinedLikeTheEventFields() { + configureApi(List.of("$request.querystring.Token", "$request.header.X-Identity", "$request.querystring.Token")); + given().header("X-Identity", "first", "second").queryParam("Token", "one", "two") + .get(path()).then().statusCode(200); + assertIdentities(List.of("one,two", "first,second", "one,two")); + } + + @ParameterizedTest + @ValueSource(strings = {"1.0", "2.0"}) + void noConfiguredSourcesProducesAnEmptyIdentityValue(String format) { + payloadFormat = format; + configureApi(List.of()); + given().get(path()).then().statusCode(200); + assertIdentities(List.of()); + } + + @ParameterizedTest + @ValueSource(strings = {"$request.header.Missing", "$request.querystring.Missing", "$request.querystring.Token", + "$stageVariables.missing", "$context.missing", "$context.http"}) + void missingOrWrongCaseRequestSourceDoesNotInvokeLambda(String source) { + configureApi(List.of(source)); + given().queryParam("token", "wrong-case").get(path()).then().statusCode(401); + verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(AUTHORIZER), any(byte[].class), eq(InvocationType.RequestResponse)); + verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(BACKEND), any(byte[].class), eq(InvocationType.RequestResponse)); + } + + @Test + void emptyConfiguredValueDoesNotInvokeLambda() { + configureApi(List.of("$request.querystring.Token")); + given().queryParam("Token", "").get(path()).then().statusCode(401); + verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(AUTHORIZER), any(byte[].class), eq(InvocationType.RequestResponse)); + } + + @Test + void formatOneResolvesSourcesAndRendersCommaSeparatedIdentityFields() { + payloadFormat = "1.0"; + configureApi(List.of("$request.header.authorization", "$request.querystring.Token", + "$stageVariables.tenant", "$context.routeKey", "$context.stage", "$context.requestId")); + given().header("Authorization", "Bearer identity").queryParam("Token", "query-value") + .get(path()).then().statusCode(200); + String expected = "Bearer identity,query-value,stage-tenant,GET /items,test," + + authorizerEvent.get().path("requestContext").path("requestId").asText(); + assertEquals(expected, authorizerEvent.get().path("identitySource").asText()); + assertEquals(expected, authorizerEvent.get().path("authorizationToken").asText()); + } + + @Test + void formatOneContextAliasesUseTheValuesFromThisEvent() { + payloadFormat = "1.0"; + configureApi(List.of("$context.httpMethod", "$context.protocol", "$context.identity.sourceIp", + "$context.identity.userAgent", "$context.requestTime", "$context.requestTimeEpoch", "$context.extendedRequestId")); + given().header("User-Agent", "identity-client").get(path()).then().statusCode(200); + JsonNode context = authorizerEvent.get().path("requestContext"); + assertEquals(String.join(",", "GET", "HTTP/1.1", context.path("identity").path("sourceIp").asText(), + "identity-client", context.path("requestTime").asText(), context.path("requestTimeEpoch").asText(), + context.path("requestId").asText()), authorizerEvent.get().path("identitySource").asText()); + } + + @ParameterizedTest + @ValueSource(strings = {"$request.header.Missing", "$request.querystring.Missing", "$request.querystring.Token", + "$stageVariables.missing", "$context.missing", "$context.identity"}) + void formatOneMissingOrWrongCaseSourceDoesNotInvokeLambda(String source) { + payloadFormat = "1.0"; + configureApi(List.of(source)); + given().queryParam("token", "wrong-case").get(path()).then().statusCode(401); + verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(AUTHORIZER), any(byte[].class), eq(InvocationType.RequestResponse)); + verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(BACKEND), any(byte[].class), eq(InvocationType.RequestResponse)); + } + + @Test + void formatOneRepeatedRequestValuesUseTheLastDeliveredValues() { + payloadFormat = "1.0"; + configureApi(List.of("$request.querystring.Token", "$request.header.X-Identity", "$request.querystring.Token")); + given().header("X-Identity", "first", "second").queryParam("Token", "one", "two") + .get(path()).then().statusCode(200); + assertIdentities(List.of("two", "second", "two")); + } + + @Test + void formatOneEmptyLastQueryValueDoesNotInvokeLambda() { + payloadFormat = "1.0"; + configureApi(List.of("$request.querystring.Token")); + given().queryParam("Token", "present", "").get(path()).then().statusCode(401); + verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(AUTHORIZER), any(byte[].class), eq(InvocationType.RequestResponse)); + } + + @ParameterizedTest + @ValueSource(strings = {"1.0", "2.0"}) + void anEarlierEmptyQueryValueDoesNotHideTheDeliveredValue(String format) { + payloadFormat = format; + configureApi(List.of("$request.querystring.Token")); + given().queryParam("Token", "", "present").get(path()).then().statusCode(200); + assertIdentities(List.of("1.0".equals(format) ? "present" : ",present")); + } + + @Test + void identityValuesDoNotBypassADenyResponse() { + allowed = false; + configureApi(List.of("$request.header.Authorization")); + given().header("Authorization", "Bearer denied-token").get(path()).then().statusCode(403); + assertIdentities(List.of("Bearer denied-token")); + verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(BACKEND), any(byte[].class), eq(InvocationType.RequestResponse)); + } + + private void assertIdentities(List expected) { + assertNotNull(authorizerEvent.get()); + JsonNode identities = "1.0".equals(payloadFormat) ? MAPPER.valueToTree(String.join(",", expected)) : MAPPER.valueToTree(expected); + assertEquals(identities, authorizerEvent.get().get("identitySource")); + if ("1.0".equals(payloadFormat)) { + assertEquals(identities, authorizerEvent.get().get("authorizationToken")); + } + } + + private String path() { + return "/execute-api/" + apiId + "/" + stageName + "/items"; + } + + private void configureApi(List sources) { + apiId = LambdaAuthorizerApiFixtures.createApi("HTTP", stageName, Map.of("tenant", "stage-tenant"), + Map.of("authorizerPayloadFormatVersion", payloadFormat, "enableSimpleResponses", "2.0".equals(payloadFormat), + "identitySource", sources)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/LambdaAuthorizerApiFixtures.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/LambdaAuthorizerApiFixtures.java new file mode 100644 index 0000000000..e9a4de229b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/LambdaAuthorizerApiFixtures.java @@ -0,0 +1,69 @@ +package io.github.hectorvent.floci.services.apigatewayv2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.github.hectorvent.floci.services.lambda.model.InvokeResult; +import io.restassured.http.ContentType; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.Function; + +import static io.restassured.RestAssured.given; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +final class LambdaAuthorizerApiFixtures { + + static final String REGION = "us-east-1"; + static final String AUTHORIZER = "arn:aws:lambda:us-east-1:000000000000:function:fixture-authorizer"; + static final String BACKEND = "arn:aws:lambda:us-east-1:000000000000:function:fixture-backend"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private LambdaAuthorizerApiFixtures() {} + + static String createApi(String protocol, String stageName, Map stageVariables, + Map authorizerFields) { + String apiId = given().contentType(ContentType.JSON) + .body(Map.of("name", "lambda-authorizer", "protocolType", protocol, + "routeSelectionExpression", "$request.body.action")) + .post("/v2/apis").then().statusCode(201).extract().path("apiId"); + String apiPath = "/v2/apis/" + apiId; + given().contentType(ContentType.JSON).body(Map.of("stageName", stageName, "stageVariables", stageVariables)) + .post(apiPath + "/stages").then().statusCode(201); + Map authorizer = new LinkedHashMap<>(authorizerFields); + authorizer.put("name", "fixture-authorizer"); + authorizer.put("authorizerType", "REQUEST"); + authorizer.put("authorizerUri", AUTHORIZER); + String authorizerId = given().contentType(ContentType.JSON).body(authorizer) + .post(apiPath + "/authorizers").then().statusCode(201).extract().path("authorizerId"); + boolean webSocket = "WEBSOCKET".equals(protocol); + Map integration = webSocket ? Map.of("integrationType", "MOCK") + : Map.of("integrationType", "AWS_PROXY", "payloadFormatVersion", "2.0", "integrationUri", BACKEND); + String integrationId = given().contentType(ContentType.JSON).body(integration) + .post(apiPath + "/integrations").then().statusCode(201).extract().path("integrationId"); + given().contentType(ContentType.JSON) + .body(Map.of("routeKey", webSocket ? "$connect" : "GET /items", "authorizationType", "CUSTOM", + "authorizerId", authorizerId, "target", "integrations/" + integrationId)) + .post(apiPath + "/routes").then().statusCode(201); + return apiId; + } + + static void stubAuthorizer(LambdaService lambdaService, Function response) { + when(lambdaService.invokeTarget(eq(REGION), eq(AUTHORIZER), any(byte[].class), eq(InvocationType.RequestResponse))) + .thenAnswer(invocation -> response.apply(MAPPER.readTree((byte[]) invocation.getArgument(2)))); + } + + static void stubBackend(LambdaService lambdaService) { + when(lambdaService.invokeTarget(eq(REGION), eq(BACKEND), any(byte[].class), eq(InvocationType.RequestResponse))) + .thenReturn(result("{\"statusCode\":200,\"body\":\"allowed\"}")); + } + + static InvokeResult result(String payload) { + return new InvokeResult(200, null, payload.getBytes(StandardCharsets.UTF_8), null, "request"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/LambdaAuthorizerPolicyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/LambdaAuthorizerPolicyIntegrationTest.java index ae2a937e18..da57525330 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/LambdaAuthorizerPolicyIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/LambdaAuthorizerPolicyIntegrationTest.java @@ -1,14 +1,10 @@ package io.github.hectorvent.floci.services.apigatewayv2; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.InvocationType; -import io.github.hectorvent.floci.services.lambda.model.InvokeResult; import io.quarkus.test.InjectMock; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; -import io.restassured.http.ContentType; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -17,12 +13,13 @@ import java.net.URI; import java.net.http.HttpClient; import java.net.http.WebSocket; import java.net.http.WebSocketHandshakeException; -import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; +import static io.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.BACKEND; +import static io.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.result; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; @@ -31,10 +28,6 @@ import static org.mockito.Mockito.*; @QuarkusTest class LambdaAuthorizerPolicyIntegrationTest { - private static final ObjectMapper MAPPER = new ObjectMapper(); - private static final String AUTHORIZER_FUNCTION = "policy-authorizer"; - private static final String BACKEND_FUNCTION = "policy-backend"; - @InjectMock LambdaService lambdaService; @@ -55,12 +48,11 @@ class LambdaAuthorizerPolicyIntegrationTest { void httpRequestsEnforceAuthorizerPolicies(String scenario, String statements, int expectedStatus) { configureApi("HTTP"); stubAuthorizer(statements); - when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + BACKEND_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse))) - .thenReturn(result("{\"statusCode\":200,\"body\":\"allowed\"}")); + LambdaAuthorizerApiFixtures.stubBackend(lambdaService); given().header("X-Forwarded-For", "198.51.100.42") .get("/execute-api/" + apiId + "/test/items").then().statusCode(expectedStatus); verify(lambdaService, times(expectedStatus == 200 ? 1 : 0)) - .invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + BACKEND_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)); + .invokeTarget(eq("us-east-1"), eq(BACKEND), any(byte[].class), eq(InvocationType.RequestResponse)); } @ParameterizedTest(name = "WebSocket: {0}") @@ -98,42 +90,16 @@ class LambdaAuthorizerPolicyIntegrationTest { } private void configureApi(String protocol) { - apiId = given().contentType(ContentType.JSON) - .body(Map.of("name", "policy-evaluation", "protocolType", protocol, - "routeSelectionExpression", "$request.body.action")) - .post("/v2/apis").then().statusCode(201).extract().path("apiId"); - String apiPath = "/v2/apis/" + apiId; - given().contentType(ContentType.JSON).body(Map.of("stageName", "test")) - .post(apiPath + "/stages").then().statusCode(201); - String authorizerId = given().contentType(ContentType.JSON) - .body(Map.of("name", "policy", "authorizerType", "REQUEST", "authorizerPayloadFormatVersion", "2.0", - "authorizerUri", "arn:aws:lambda:us-east-1:000000000000:function:" + AUTHORIZER_FUNCTION)) - .post(apiPath + "/authorizers").then().statusCode(201).extract().path("authorizerId"); - boolean webSocket = "WEBSOCKET".equals(protocol); - Map integration = webSocket ? Map.of("integrationType", "MOCK") - : Map.of("integrationType", "AWS_PROXY", "payloadFormatVersion", "2.0", - "integrationUri", "arn:aws:lambda:us-east-1:000000000000:function:" + BACKEND_FUNCTION); - String integrationId = given().contentType(ContentType.JSON).body(integration) - .post(apiPath + "/integrations").then().statusCode(201).extract().path("integrationId"); - given().contentType(ContentType.JSON) - .body(Map.of("routeKey", webSocket ? "$connect" : "GET /items", "authorizationType", "CUSTOM", - "authorizerId", authorizerId, "target", "integrations/" + integrationId)) - .post(apiPath + "/routes").then().statusCode(201); + apiId = LambdaAuthorizerApiFixtures.createApi(protocol, "test", Map.of(), Map.of("authorizerPayloadFormatVersion", "2.0")); } private void stubAuthorizer(String statements) { - when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + AUTHORIZER_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse))) - .thenAnswer(invocation -> { - JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2)); - String arn = event.has("routeArn") ? event.path("routeArn").asText() : event.path("methodArn").asText(); - String suffix = event.has("routeArn") ? "/GET/items" : "/$connect"; - assertEquals("arn:aws:execute-api:us-east-1:000000000000:" + apiId + "/test" + suffix, arn); - return result("{\"principalId\":\"user\",\"policyDocument\":{\"Version\":\"2012-10-17\",\"Statement\":" - + AuthorizerPolicyFixtures.renderStatements(statements, arn) + "}}"); - }); - } - - private InvokeResult result(String payload) { - return new InvokeResult(200, null, payload.getBytes(StandardCharsets.UTF_8), null, "request"); + LambdaAuthorizerApiFixtures.stubAuthorizer(lambdaService, event -> { + String arn = event.has("routeArn") ? event.path("routeArn").asText() : event.path("methodArn").asText(); + String suffix = event.has("routeArn") ? "/GET/items" : "/$connect"; + assertEquals("arn:aws:execute-api:us-east-1:000000000000:" + apiId + "/test" + suffix, arn); + return result("{\"principalId\":\"user\",\"policyDocument\":{\"Version\":\"2012-10-17\",\"Statement\":" + + AuthorizerPolicyFixtures.renderStatements(statements, arn) + "}}"); + }); } }