Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(apigateway): validate and cache REST Lambda authorizers (#5002)

Abhigyaae3adfe992b6
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayAuthorizerCacheCompatibilityTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayAuthorizerCacheCompatibilityTest.java
new file mode 100644
index 0000000000..5c2ac4f3b6
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayAuthorizerCacheCompatibilityTest.java
@@ -0,0 +1,69 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
+import software.amazon.awssdk.services.apigateway.model.AuthorizerType;
+import software.amazon.awssdk.services.apigateway.model.BadRequestException;
+import software.amazon.awssdk.services.apigateway.model.IntegrationType;
+import software.amazon.awssdk.services.apigateway.model.NotFoundException;
+import software.amazon.awssdk.services.apigateway.model.PatchOperation;
+
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class ApiGatewayAuthorizerCacheCompatibilityTest {
+ private static final String AUTHORIZER_URI = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
+ + "arn:aws:lambda:us-east-1:000000000000:function:identity-source-authorizer/invocations";
+
+ @Test
+ void cachedRequestAuthorizerRequiresIdentitySourceOnCreateAndUpdate() {
+ try (ApiGatewayClient gateway = TestFixtures.apiGatewayClient()) {
+ String apiId = gateway.createRestApi(request -> request.name("request-authorizer-identity-sdk")).id();
+ try {
+ assertThatThrownBy(() -> gateway.createAuthorizer(request -> request.restApiId(apiId)
+ .name("default-caching").type(AuthorizerType.REQUEST).authorizerUri(AUTHORIZER_URI)))
+ .isInstanceOf(BadRequestException.class);
+ assertThatThrownBy(() -> gateway.createAuthorizer(request -> request.restApiId(apiId)
+ .name("explicit-caching").type(AuthorizerType.REQUEST).authorizerUri(AUTHORIZER_URI)
+ .authorizerResultTtlInSeconds(300).identitySource(" ")))
+ .isInstanceOf(BadRequestException.class);
+ String authorizerId = gateway.createAuthorizer(request -> request.restApiId(apiId)
+ .name("uncached").type(AuthorizerType.REQUEST).authorizerUri(AUTHORIZER_URI).authorizerResultTtlInSeconds(0)).id();
+ assertThatThrownBy(() -> gateway.updateAuthorizer(request -> request.restApiId(apiId)
+ .authorizerId(authorizerId).patchOperations(PatchOperation.builder()
+ .op("replace").path("/authorizerResultTtlInSeconds").value("300").build())))
+ .isInstanceOf(BadRequestException.class);
+ assertThat(gateway.getAuthorizer(request -> request.restApiId(apiId).authorizerId(authorizerId))
+ .authorizerResultTtlInSeconds()).isZero();
+ assertThat(gateway.getAuthorizers(request -> request.restApiId(apiId)).items()).hasSize(1);
+ } finally {
+ gateway.deleteRestApi(request -> request.restApiId(apiId));
+ }
+ }
+ }
+
+ @Test
+ void flushStageAuthorizersCacheUsesSdkWireProtocol() {
+ try (ApiGatewayClient gateway = TestFixtures.apiGatewayClient()) {
+ String apiId = gateway.createRestApi(request -> request.name("authorizer-cache-sdk")).id();
+ try {
+ String rootId = gateway.getResources(request -> request.restApiId(apiId)).items().stream()
+ .filter(resource -> "/".equals(resource.path())).findFirst().orElseThrow().id();
+ gateway.putMethod(request -> request.restApiId(apiId).resourceId(rootId)
+ .httpMethod("GET").authorizationType("NONE"));
+ gateway.putIntegration(request -> request.restApiId(apiId).resourceId(rootId)
+ .httpMethod("GET").type(IntegrationType.MOCK)
+ .requestTemplates(Map.of("application/json", "{\"statusCode\":200}")));
+ gateway.createDeployment(request -> request.restApiId(apiId).stageName("test"));
+ assertThat(gateway.flushStageAuthorizersCache(request -> request.restApiId(apiId).stageName("test"))
+ .sdkHttpResponse().statusCode()).isEqualTo(202);
+ assertThatThrownBy(() -> gateway.flushStageAuthorizersCache(request -> request.restApiId(apiId).stageName("missing")))
+ .isInstanceOf(NotFoundException.class);
+ } finally {
+ gateway.deleteRestApi(request -> request.restApiId(apiId));
+ }
+ }
+ }
+}
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md
index 2bf0fa44d8..d7bd0ad04a 100644
--- a/docs/services/api-gateway.md
+++ b/docs/services/api-gateway.md
@@ -87,7 +87,7 @@ includes mapping templates and applies to both `ImportRestApi` and `PutRestApi`.
| **Integrations** | PutIntegration, GetIntegration, UpdateIntegration, DeleteIntegration |
| **Integration Responses** | PutIntegrationResponse, GetIntegrationResponse, UpdateIntegrationResponse, DeleteIntegrationResponse |
| **Deployments** | CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment |
-| **Stages** | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage |
+| **Stages** | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, FlushStageAuthorizersCache |
| **Authorizers** | CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer |
| **API Keys** | CreateApiKey, ImportApiKeys, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey |
| **Usage Plans** | CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, GetUsage |
@@ -153,6 +153,34 @@ immediately.
> disabled, or deleted key is still executed — it simply arrives with a null `identity.apiKey` rather
> than being rejected with `403`.
+### REST Lambda Authorizers
+
+TOKEN and REQUEST authorizers must return a nonempty `principalId` and an IAM policy. Floci
+checks all statements against `execute-api:Invoke` and the current method ARN, including
+wildcards, conditions and explicit deny precedence. A policy that does not grant the method
+returns `403`. Invalid policies or non-scalar context values return `500`. Scalar context keys,
+including keys such as `tenant-id`, are retained in Lambda proxy events.
+The alphanumeric and underscore restriction in the mapping reference applies to properties
+referenced through `$context.authorizer.property`, not to the returned context map.
+
+A missing TOKEN identity header returns `401` without invoking Lambda. For a REQUEST
+authorizer with caching enabled, every configured identity source must be present and nonempty.
+Creating or updating a cached REQUEST authorizer without an identity source returns `400`.
+The default TTL is 300 seconds, so omitting the TTL still requires an identity source.
+With caching disabled, REQUEST authorizers receive the request even when identity sources
+are missing. A Lambda `Unauthorized` error returns `401`; other function errors return `500`.
+
+`authorizerResultTtlInSeconds` caches the validated policy, principal and context together.
+A zero TTL disables caching. Cache entries are scoped to the account, region, API, stage,
+deployment, authorizer configuration and ordered identity values. Each cache hit evaluates
+the policy for the current method again. `FlushStageAuthorizersCache` clears a stage's entries
+through `DELETE /restapis/{apiId}/stages/{stageName}/cache/authorizers` and returns `202`.
+A flush also invalidates pending invocations, so a result started before the flush cannot
+repopulate that stage's cache afterward.
+
+See the AWS [Lambda authorizer workflow](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html)
+and [response contract](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html).
+
### Custom Domain Names
A domain created with `CreateDomainName` is `AVAILABLE` at once. Its `regionalDomainName` is
@@ -331,8 +359,8 @@ Use alphanumeric or underscore authorizer context keys, as required by the
[AWS mapping contract](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html).
For example, return `userClaims` in the authorizer context and map
`integration.request.header.X-User-Claims` from `context.authorizer.userClaims`. The HTTP header
-name can contain hyphens. REST Lambda authorizer result caching is not implemented; setting
-`authorizerResultTtlInSeconds` does not currently suppress repeat Lambda invocations.
+name can contain hyphens. REST Lambda authorizer policy evaluation, response validation and
+result caching are handled separately from these integration mappings.
A backend response body larger than the 10 MB API Gateway payload quota yields `413` with `{"message":"Request Entity Too Large"}`. The same limit applies to HTTP API `HTTP_PROXY` integrations.
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
index c03cb97964..f8d338b29f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
@@ -73,16 +73,29 @@ public class ApiGatewayController {
private final ApiGatewayV2OpenApiImporter v2OpenApiImporter;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
+ private final RestLambdaAuthorizer restLambdaAuthorizer;
@Inject
public ApiGatewayController(ApiGatewayService service, ApiGatewayV2Service v2Service,
ApiGatewayV2OpenApiImporter v2OpenApiImporter,
- RegionResolver regionResolver, ObjectMapper objectMapper) {
+ RegionResolver regionResolver, ObjectMapper objectMapper,
+ RestLambdaAuthorizer restLambdaAuthorizer) {
this.service = service;
this.v2Service = v2Service;
this.v2OpenApiImporter = v2OpenApiImporter;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
+ this.restLambdaAuthorizer = restLambdaAuthorizer;
+ }
+
+ @DELETE
+ @Path("restapis/{apiId}/stages/{stageName}/cache/authorizers")
+ public Response flushStageAuthorizersCache(@Context HttpHeaders headers, @PathParam("apiId") String apiId,
+ @PathParam("stageName") String stageName) {
+ String region = regionResolver.resolveRegion(headers);
+ service.getStage(region, apiId, stageName);
+ restLambdaAuthorizer.flush(new RestLambdaAuthorizer.Scope(regionResolver.getAccountId(), region, apiId, stageName));
+ return Response.accepted().build();
}
private static final TypeReference<List<Map<String, String>>> PATCH_OPERATIONS =
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 e6611e8a92..f6ce8b8e1c 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
@@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.apigatewayv2.JwtSignatureVerifier;
import io.github.hectorvent.floci.services.apigatewayv2.model.Api;
+// REST and v2 both define Authorizer; the less-used REST type is qualified below.
import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
import io.github.hectorvent.floci.services.apigatewayv2.websocket.ConnectionInfo;
@@ -114,6 +115,7 @@ public class ApiGatewayExecuteController {
private final JwtSignatureVerifier jwtSignatureVerifier;
private final RequestContext requestContext;
private final ExecuteApiSigV4Authorizer sigV4Authorizer;
+ private final RestLambdaAuthorizer restLambdaAuthorizer;
@Inject
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, CognitoUserPoolAuthorizer cognitoAuthorizer,
@@ -127,7 +129,7 @@ public class ApiGatewayExecuteController {
ApiGatewayExecuteRouteContext routeContext,
JwtSignatureVerifier jwtSignatureVerifier,
RequestContext requestContext,
- ExecuteApiSigV4Authorizer sigV4Authorizer) {
+ ExecuteApiSigV4Authorizer sigV4Authorizer, RestLambdaAuthorizer restLambdaAuthorizer) {
this.apiGatewayService = apiGatewayService;
this.cognitoAuthorizer = cognitoAuthorizer;
this.apiGatewayV2Service = apiGatewayV2Service;
@@ -143,6 +145,7 @@ public class ApiGatewayExecuteController {
this.jwtSignatureVerifier = jwtSignatureVerifier;
this.requestContext = requestContext;
this.sigV4Authorizer = sigV4Authorizer;
+ this.restLambdaAuthorizer = restLambdaAuthorizer;
}
/** Matches an ELBv2 listener ARN (ALB {@code app/} or NLB {@code net/}); group 1 = region. */
@@ -904,7 +907,9 @@ public class ApiGatewayExecuteController {
for (Map.Entry<String, String> param : requestParameters.entrySet()) {
String dest = param.getKey();
String resolved = resolveRequestParameter(param.getValue(), queryMap, pathMap, headerMap, mappingContext);
- if (resolved == null) continue;
+ if (resolved == null) {
+ continue;
+ }
if (dest.startsWith("integration.request.header.")) {
outHeaders.put(dest.substring("integration.request.header.".length()), resolved);
} else if (dest.startsWith("integration.request.querystring.")) {
@@ -1012,47 +1017,120 @@ public class ApiGatewayExecuteController {
return new AuthorizerResult(null, result.principalId(), result.context());
}
if ("CUSTOM".equals(authorizationType)) {
- String authorizerId = method.getAuthorizerId();
- if (authorizerId == null) {
- return new AuthorizerResult(null, null, null);
- }
+ return invokeLambdaAuthorizer(scope, region, apiId, stageName, httpMethod, requestPath,
+ resourcePath, resourceId, stage, method, headers, uriInfo, resolvedApiKey);
+ }
+ return new AuthorizerResult(null, null, null);
+ }
- io.github.hectorvent.floci.services.apigateway.model.Authorizer auth = apiGatewayService.getAuthorizer(region, apiId, authorizerId);
- String authorizerType = auth.getType();
- String lambdaName = functionNameFromUri(auth.getAuthorizerUri());
- if ((!"TOKEN".equals(authorizerType) && !"REQUEST".equals(authorizerType))
- || lambdaName == null || lambdaName.isBlank()) {
- return new AuthorizerResult(gatewayResponseOr(Response.status(500).build(), scope,
- GatewayResponseType.AUTHORIZER_CONFIGURATION_ERROR, null), null, null);
+ private AuthorizerResult invokeLambdaAuthorizer(GatewayResponseScope scope, String region, String apiId,
+ String stageName, String httpMethod, String requestPath,
+ String resourcePath, String resourceId, Stage stage,
+ MethodConfig method, HttpHeaders headers, UriInfo uriInfo,
+ ResolvedApiKey resolvedApiKey) {
+ if (method.getAuthorizerId() == null) {
+ return authorizerError(scope, GatewayResponseType.AUTHORIZER_CONFIGURATION_ERROR, 500);
+ }
+ try {
+ io.github.hectorvent.floci.services.apigateway.model.Authorizer auth =
+ apiGatewayService.getAuthorizer(region, apiId, method.getAuthorizerId());
+ String function = functionNameFromUri(auth.getAuthorizerUri());
+ if ((!"TOKEN".equals(auth.getType()) && !"REQUEST".equals(auth.getType()))
+ || function == null || function.isBlank()) {
+ return authorizerError(scope, GatewayResponseType.AUTHORIZER_CONFIGURATION_ERROR, 500);
+ }
+ int ttl = Integer.parseInt(auth.getAuthorizerResultTtlInSeconds());
+ String event = toAuthorizerEvent(auth, headers, region, apiId, stageName, httpMethod,
+ requestPath, resourcePath, resourceId, stage, uriInfo, resolvedApiKey);
+ List<String> identities = authorizerIdentityValues(scope, auth, event);
+ if (("TOKEN".equals(auth.getType()) || ttl > 0) && identities == null) {
+ return authorizerError(scope, GatewayResponseType.UNAUTHORIZED, 401);
+ }
+ RestLambdaAuthorizer.CacheKey key = new RestLambdaAuthorizer.CacheKey(
+ new RestLambdaAuthorizer.Scope(regionResolver.getAccountId(), region, apiId, stageName),
+ stage.getDeploymentId(), auth.getId(), auth.getAuthorizerUri(), auth.getType(),
+ auth.getIdentitySource(), ttl, identities != null ? identities : List.of());
+ RestLambdaAuthorizer.Result verified = restLambdaAuthorizer.get(key);
+ if (verified == null) {
+ try (RestLambdaAuthorizer.Invocation pending = restLambdaAuthorizer.beginInvocation(key)) {
+ InvokeResult invocation = lambdaService.invoke(region, function,
+ event.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);
+ if (invocation.getFunctionError() != null) {
+ return lambdaAuthorizerFailure(scope, invocation);
+ }
+ verified = restLambdaAuthorizer.parse(invocation.getPayload());
+ pending.cache(verified);
+ }
}
+ String methodArn = buildMethodArn(region, apiId, stageName, httpMethod, requestPath);
+ Map<String, List<String>> conditions = Map.of("aws:SourceIp", List.of(routeContext.sourceIp()),
+ "aws:SecureTransport", List.of(Boolean.toString("https".equals(uriInfo.getRequestUri().getScheme()))),
+ "aws:CurrentTime", List.of(Instant.now().toString()));
+ if (!restLambdaAuthorizer.permits(verified, methodArn, conditions)) {
+ return authorizerError(scope, GatewayResponseType.ACCESS_DENIED, 403);
+ }
+ return new AuthorizerResult(null, verified.principalId(), verified.context());
+ } catch (Exception exception) {
+ LOG.warnv("Authorizer failure: {0}", exception.getMessage());
+ return authorizerError(scope, GatewayResponseType.AUTHORIZER_FAILURE, 500);
+ }
+ }
- String event = toAuthorizerEvent(auth, headers, region, apiId, stageName, httpMethod, requestPath, resourcePath, resourceId, stage, uriInfo, resolvedApiKey);
- try {
- InvokeResult result = lambdaService.invoke(region, lambdaName, event.getBytes(), InvocationType.RequestResponse);
- if (result.getFunctionError() != null) {
- return new AuthorizerResult(gatewayResponseOr(Response.status(403).build(), scope,
- GatewayResponseType.AUTHORIZER_FAILURE, null), null, null);
- }
+ private AuthorizerResult lambdaAuthorizerFailure(GatewayResponseScope scope, InvokeResult invocation) throws IOException {
+ JsonNode error = objectMapper.readTree(invocation.getPayload());
+ boolean unauthorized = error != null && ("Unauthorized".equals(error.asText())
+ || "Unauthorized".equals(error.path("errorMessage").asText()));
+ return authorizerError(scope, unauthorized ? GatewayResponseType.UNAUTHORIZED
+ : GatewayResponseType.AUTHORIZER_FAILURE, unauthorized ? 401 : 500);
+ }
- JsonNode policy = objectMapper.readTree(result.getPayload());
- String effect = policy.path("policyDocument").path("Statement").get(0).path("Effect").asText("Deny");
- if ("Deny".equalsIgnoreCase(effect)) {
- return new AuthorizerResult(
- gatewayResponse(scope, GatewayResponseType.ACCESS_DENIED, 403,
- "User is not authorized to access this resource"),
- null,
- null);
- }
- String principalId = policy.path("principalId").asText(null);
- Map<String, Object> context = extractAuthorizerContext(policy.path("context"));
- return new AuthorizerResult(null, principalId, context);
- } catch (Exception e) {
- LOG.warnv("Authorizer failure: {0}", e.getMessage());
- return new AuthorizerResult(gatewayResponseOr(Response.status(500).build(), scope,
- GatewayResponseType.AUTHORIZER_FAILURE, null), null, null);
+ private AuthorizerResult authorizerError(GatewayResponseScope scope, GatewayResponseType type, int status) {
+ String message = switch (type) {
+ case UNAUTHORIZED -> "Unauthorized";
+ case ACCESS_DENIED -> "User is not authorized to access this resource";
+ default -> "Internal server error";
+ };
+ return new AuthorizerResult(gatewayResponse(scope, type, status, message), null, null);
+ }
+
+ private List<String> authorizerIdentityValues(GatewayResponseScope scope,
+ io.github.hectorvent.floci.services.apigateway.model.Authorizer auth, String event) throws IOException {
+ if (auth.getIdentitySource() == null || auth.getIdentitySource().isBlank()) {
+ return null;
+ }
+ List<String> identities = new ArrayList<>();
+ Map<String, Object> context = "REQUEST".equals(auth.getType())
+ ? objectMapper.convertValue(objectMapper.readTree(event).path("requestContext"), MAP_TYPE) : Map.of();
+ for (String source : auth.getIdentitySource().split(",", -1)) {
+ source = source.trim();
+ String value = authorizerIdentityValue(scope, auth.getType(), source, context);
+ if (value == null || value.isEmpty()) {
+ return null;
}
+ identities.add(value);
}
- return new AuthorizerResult(null, null, null);
+ return identities;
+ }
+
+ private String authorizerIdentityValue(GatewayResponseScope scope, String type, String source,
+ Map<String, Object> context) {
+ if (source.startsWith("method.request.header.")) {
+ return scope.headers().getHeaderString(source.substring("method.request.header.".length()));
+ }
+ if (!"REQUEST".equals(type)) {
+ return null;
+ }
+ if (source.startsWith("method.request.querystring.")) {
+ return scope.uriInfo().getQueryParameters().getFirst(source.substring("method.request.querystring.".length()));
+ }
+ if (source.startsWith("stageVariables.")) {
+ return scope.stage().getVariables().get(source.substring("stageVariables.".length()));
+ }
+ if (source.startsWith("context.")) {
+ Object resolved = contextValue(context, source.substring("context.".length()));
+ return resolved != null ? resolved.toString() : null;
+ }
+ return null;
}
private Response validateRequest(GatewayResponseScope scope, String region, String apiId, MethodConfig method,
@@ -1141,13 +1219,6 @@ public class ApiGatewayExecuteController {
return null;
}
- private Map<String, Object> extractAuthorizerContext(JsonNode contextNode) {
- if (contextNode == null || contextNode.isMissingNode() || contextNode.isNull() || !contextNode.isObject()) {
- return null;
- }
- return objectMapper.convertValue(contextNode, MAP_TYPE);
- }
-
private String toAuthorizerEvent(io.github.hectorvent.floci.services.apigateway.model.Authorizer auth,
HttpHeaders headers, String region, String apiId, String stageName,
String httpMethod, String requestPath,
@@ -1204,7 +1275,7 @@ public class ApiGatewayExecuteController {
// identity.apiKey / identity.apiKeyId: resolve from usage plans linked to this (apiId, stage)
ObjectNode identity = ctx.putObject("identity");
- identity.put("sourceIp", "127.0.0.1");
+ identity.put("sourceIp", routeContext.sourceIp());
String userAgent = headers.getHeaderString("User-Agent");
identity.put("userAgent", userAgent != null ? userAgent : "");
if (resolvedApiKey != null) {
@@ -1320,9 +1391,9 @@ public class ApiGatewayExecuteController {
String arnRegion = region != null ? region : regionResolver.getDefaultRegion();
String domainName = AwsEndpoints.executeApiHost(apiId, arnRegion);
long nowMillis = System.currentTimeMillis();
- String requestTime = java.time.format.DateTimeFormatter
+ String requestTime = DateTimeFormatter
.ofPattern("dd/MMM/yyyy:HH:mm:ss Z")
- .format(java.time.ZonedDateTime.now(java.time.ZoneOffset.UTC));
+ .format(ZonedDateTime.now(ZoneOffset.UTC));
ObjectNode ctx = event.putObject("requestContext");
ctx.put("accountId", regionResolver.getAccountId());
@@ -1359,7 +1430,7 @@ public class ApiGatewayExecuteController {
identity.putNull("cognitoIdentityId");
identity.putNull("cognitoIdentityPoolId");
identity.putNull("principalOrgId");
- identity.put("sourceIp", "127.0.0.1");
+ identity.put("sourceIp", routeContext.sourceIp());
putOrNull(identity, "user", iamIdentity == null ? null : iamIdentity.userId());
String userAgent = headers.getHeaderString("User-Agent");
identity.put("userAgent", userAgent != null ? userAgent : "");
@@ -2040,7 +2111,9 @@ public class ApiGatewayExecuteController {
private String resolveRequestParameter(String source, Map<String, String> queryParams,
Map<String, String> pathParams, Map<String, String> headers,
Map<String, Object> context) {
- if (source == null) return null;
+ if (source == null) {
+ return null;
+ }
if (source.startsWith("method.request.querystring.")) {
return queryParams.get(source.substring("method.request.querystring.".length()));
}
@@ -3622,7 +3695,7 @@ public class ApiGatewayExecuteController {
context.put("status", status);
Map<String, Object> identity = new LinkedHashMap<>();
- identity.put("sourceIp", "127.0.0.1");
+ identity.put("sourceIp", routeContext.sourceIp());
identity.put("userAgent", scope.headers() != null ? scope.headers().getHeaderString("User-Agent") : null);
context.put("identity", identity);
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java
index 9950f21855..a204abb1c7 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java
@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.apigateway;
+import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
+import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.RequestScoped;
+import jakarta.inject.Inject;
import jakarta.ws.rs.core.UriInfo;
/**
@@ -10,6 +13,22 @@ import jakarta.ws.rs.core.UriInfo;
@RequestScoped
public class ApiGatewayExecuteRouteContext {
+ private final CurrentVertxRequest currentVertxRequest;
+
+ public ApiGatewayExecuteRouteContext() {
+ this(null);
+ }
+
+ @Inject
+ public ApiGatewayExecuteRouteContext(CurrentVertxRequest currentVertxRequest) {
+ this.currentVertxRequest = currentVertxRequest;
+ }
+
+ String sourceIp() {
+ RoutingContext context = currentVertxRequest != null ? currentVertxRequest.getCurrent() : null;
+ return context != null ? context.request().connection().remoteAddress().hostAddress() : "127.0.0.1";
+ }
+
private String httpApiRegion;
private boolean restApiRoute;
private String signedRequestPath;
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
index da5f88c163..c2bfbc8505 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
@@ -990,6 +990,8 @@ public class ApiGatewayService implements ResourceProvider {
authorizer.setAuthorizerUri((String) request.get("authorizerUri"));
authorizer.setIdentitySource((String) request.get("identitySource"));
authorizer.setAuthorizerResultTtlInSeconds(String.valueOf(request.getOrDefault("authorizerResultTtlInSeconds", "300")));
+ validateRequestAuthorizerIdentitySource(authorizer.getType(), authorizer.getIdentitySource(),
+ authorizer.getAuthorizerResultTtlInSeconds());
// COGNITO_USER_POOLS authorizers carry the pool ARNs; keep them so get-authorizer reflects them.
if (request.get("providerARNs") instanceof List<?> arns) {
List<String> providerArns = new ArrayList<>();
@@ -1065,6 +1067,7 @@ public class ApiGatewayService implements ResourceProvider {
}
}
}
+ validateRequestAuthorizerIdentitySource(authorizer.getType(), newIdentitySource, newTtl);
authorizer.setName(newName);
authorizer.setAuthorizerUri(newAuthorizerUri);
authorizer.setIdentitySource(newIdentitySource);
@@ -1073,6 +1076,22 @@ public class ApiGatewayService implements ResourceProvider {
return authorizer;
}
+ private static void validateRequestAuthorizerIdentitySource(String type, String identitySource, String ttl) {
+ if (!"REQUEST".equals(type)) {
+ return;
+ }
+ int ttlSeconds;
+ try {
+ ttlSeconds = Integer.parseInt(ttl);
+ } catch (NumberFormatException exception) {
+ throw new AwsException("BadRequestException", "authorizerResultTtlInSeconds must be an integer", 400);
+ }
+ if (ttlSeconds > 0 && (identitySource == null || identitySource.isBlank())) {
+ throw new AwsException("BadRequestException",
+ "Identity source is required for a REQUEST authorizer when caching is enabled", 400);
+ }
+ }
+
// ──────────────────────────── API Keys ────────────────────────────
public ApiKey createApiKey(String region, Map<String, Object> request) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizer.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizer.java
new file mode 100644
index 0000000000..b3b6505d13
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizer.java
@@ -0,0 +1,197 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+import io.github.hectorvent.floci.services.iam.model.CallerContext;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.io.IOException;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+/** Validates and caches REST Lambda authorizer policies, then evaluates each requested method. */
+@ApplicationScoped
+public class RestLambdaAuthorizer {
+ static final int MAX_ENTRIES = 1_000;
+
+ private final ObjectMapper objectMapper;
+ private final IamPolicyEvaluator policyEvaluator;
+ private final Clock clock;
+ private final ConcurrentHashMap<CacheKey, Entry> cache = new ConcurrentHashMap<>();
+ private final Set<Invocation> pendingInvocations = new HashSet<>();
+
+ @Inject
+ public RestLambdaAuthorizer(ObjectMapper objectMapper, IamPolicyEvaluator policyEvaluator) {
+ this(objectMapper, policyEvaluator, Clock.systemUTC());
+ }
+
+ RestLambdaAuthorizer(ObjectMapper objectMapper, IamPolicyEvaluator policyEvaluator, Clock clock) {
+ this.objectMapper = objectMapper;
+ this.policyEvaluator = policyEvaluator;
+ this.clock = clock;
+ }
+
+ record Scope(String accountId, String region, String apiId, String stageName) { }
+
+ record CacheKey(Scope scope, String deploymentId, String authorizerId, String uri,
+ String type, String identitySource, int ttlSeconds, List<String> identityValues) {
+ CacheKey {
+ identityValues = List.copyOf(identityValues);
+ }
+ }
+
+ record Result(String principalId, String policyDocument, Map<String, Object> context) {
+ Result {
+ context = Map.copyOf(context);
+ }
+ }
+
+ private record Entry(Result result, Instant expiresAt) { }
+
+ Result parse(byte[] payload) throws IOException {
+ JsonNode output = objectMapper.readTree(payload);
+ if (output == null || !output.isObject() || !output.path("principalId").isTextual()
+ || output.path("principalId").asText().isEmpty()) {
+ throw new IllegalArgumentException("Authorizer must return a nonempty principalId");
+ }
+ JsonNode policy = output.path("policyDocument");
+ validatePolicy(policy);
+ return new Result(output.path("principalId").asText(), policy.toString(), parseContext(output.get("context")));
+ }
+
+ private static void validatePolicy(JsonNode policy) {
+ JsonNode statements = policy.path("Statement");
+ if (!policy.isObject() || (!statements.isObject() && !statements.isArray()) || statements.isEmpty()) {
+ throw new IllegalArgumentException("Authorizer must return a policy with statements");
+ }
+ if (statements.isObject()) {
+ validateStatement(statements);
+ return;
+ }
+ for (JsonNode statement : statements) {
+ validateStatement(statement);
+ }
+ }
+
+ private static void validateStatement(JsonNode statement) {
+ String effect = statement.path("Effect").asText();
+ if (!statement.isObject() || (!"Allow".equals(effect) && !"Deny".equals(effect))
+ || (statement.has("Action") == statement.has("NotAction"))
+ || (statement.has("Resource") == statement.has("NotResource"))
+ || !validStringOrList(statement.has("Action") ? statement.get("Action") : statement.path("NotAction"))
+ || !validStringOrList(statement.has("Resource") ? statement.get("Resource") : statement.path("NotResource"))
+ || (statement.has("Condition") && !statement.get("Condition").isObject())) {
+ throw new IllegalArgumentException("Invalid authorizer policy statement");
+ }
+ }
+
+ private static boolean validStringOrList(JsonNode value) {
+ if (value.isTextual()) {
+ return !value.asText().isEmpty();
+ }
+ if (!value.isArray() || value.isEmpty()) {
+ return false;
+ }
+ for (JsonNode item : value) {
+ if (!item.isTextual() || item.asText().isEmpty()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private Map<String, Object> parseContext(JsonNode context) {
+ if (context == null) {
+ return Map.of();
+ }
+ if (!context.isObject()) {
+ throw new IllegalArgumentException("Authorizer context must be an object");
+ }
+ Map<String, Object> values = new LinkedHashMap<>();
+ for (Map.Entry<String, JsonNode> property : context.properties()) {
+ JsonNode value = property.getValue();
+ if (!value.isTextual() && !value.isNumber() && !value.isBoolean()) {
+ throw new IllegalArgumentException("Authorizer context must contain scalar values");
+ }
+ values.put(property.getKey(), objectMapper.convertValue(value, Object.class));
+ }
+ return values;
+ }
+
+ boolean permits(Result result, String methodArn, Map<String, List<String>> conditions) {
+ return policyEvaluator.evaluate(CallerContext.of(List.of(result.policyDocument())), null,
+ "execute-api:Invoke", methodArn, conditions) == IamPolicyEvaluator.Decision.ALLOW;
+ }
+
+ Result get(CacheKey key) {
+ if (key.ttlSeconds() <= 0) {
+ return null;
+ }
+ Entry entry = cache.get(key);
+ if (entry == null) {
+ return null;
+ }
+ if (!entry.expiresAt().isAfter(clock.instant())) {
+ cache.remove(key, entry);
+ return null;
+ }
+ return entry.result();
+ }
+
+ synchronized Invocation beginInvocation(CacheKey key) {
+ Invocation invocation = new Invocation(key);
+ if (key.ttlSeconds() > 0) {
+ pendingInvocations.add(invocation);
+ }
+ return invocation;
+ }
+
+ final class Invocation implements AutoCloseable {
+ private final CacheKey key;
+
+ private Invocation(CacheKey key) {
+ this.key = key;
+ }
+
+ void cache(Result result) {
+ synchronized (RestLambdaAuthorizer.this) {
+ // Flush removes pending invocations too, so a pre-flush result cannot refill the cache.
+ if (pendingInvocations.remove(this)) {
+ put(key, result);
+ }
+ }
+ }
+
+ @Override
+ public void close() {
+ synchronized (RestLambdaAuthorizer.this) {
+ pendingInvocations.remove(this);
+ }
+ }
+ }
+
+ // Called under the same lock as invocation registration and stage invalidation.
+ private void put(CacheKey key, Result result) {
+ Instant now = clock.instant();
+ cache.entrySet().removeIf(entry -> !entry.getValue().expiresAt().isAfter(now));
+ if (!cache.containsKey(key) && cache.size() >= MAX_ENTRIES) {
+ cache.entrySet().stream().min(Comparator.comparing(entry -> entry.getValue().expiresAt()))
+ .ifPresent(entry -> cache.remove(entry.getKey(), entry.getValue()));
+ }
+ cache.put(key, new Entry(result, now.plusSeconds(key.ttlSeconds())));
+ }
+
+ synchronized void flush(Scope scope) {
+ pendingInvocations.removeIf(invocation -> invocation.key.scope().equals(scope));
+ cache.keySet().removeIf(key -> key.scope().equals(scope));
+ }
+}
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 a71722f0e6..004fd68d7d 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
@@ -37,7 +37,7 @@ class ApiGatewayExecuteControllerTest {
return new ApiGatewayExecuteController(
null, null, null, null,
regionResolver, objectMapper, null,
- null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
}
@Test
@@ -352,7 +352,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, null, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
- null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
Response response = controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);
@@ -382,7 +382,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, null, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
- null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);
@@ -416,7 +416,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, null, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
- null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
controller.dispatch("GET", "restapi1", "prod", "hello", headers, null, null);
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpContextMappingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpContextMappingIntegrationTest.java
index c89fa2d8ac..4c1fbd877d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpContextMappingIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpContextMappingIntegrationTest.java
@@ -10,7 +10,6 @@ import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
-import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
@@ -34,6 +33,7 @@ import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@QuarkusTest
@@ -223,6 +223,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
assertNotEquals(previousRequestId, requestId);
previousRequestId = requestId;
}
+ verify(lambdaService).invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
}
@ParameterizedTest
@@ -231,13 +232,10 @@ class ApiGatewayHttpContextMappingIntegrationTest {
configureAuthorizer(0);
configureIntegration(type, "GET");
deploy();
- for (String token : List.of("", "Bearer forged")) {
- RequestSpecification request = given().header("X-User-Claims", "forged");
- if (!token.isEmpty()) {
- request.header("Authorization", token);
- }
- request.get("/execute-api/" + apiId + "/test/orders/42").then().statusCode(403);
- }
+ given().header("X-User-Claims", "forged")
+ .get("/execute-api/" + apiId + "/test/orders/42").then().statusCode(401);
+ given().header("X-User-Claims", "forged").header("Authorization", "Bearer forged")
+ .get("/execute-api/" + apiId + "/test/orders/42").then().statusCode(403);
assertEquals(0, backendRequests.get());
}
@@ -277,7 +275,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
private void configureAuthorizer(int ttl) throws Exception {
configureAuthorizer(ttl, Map.of("userClaims", "verified-claims", "principalId", "forged-principal",
- "numberKey", 123, "booleanKey", true, "objectKey", Map.of("nested", "value")));
+ "numberKey", 123, "booleanKey", true));
}
private void configureAuthorizer(int ttl, Map<String, Object> context) throws Exception {
@@ -308,7 +306,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
parameters.put("integration.request.header.X-Number", "context.authorizer.numberKey");
parameters.put("integration.request.header.X-Boolean", "context.authorizer.booleanKey");
parameters.put("integration.request.header.X-Missing", "context.authorizer.missing");
- parameters.put("integration.request.header.X-Object", "context.authorizer.objectKey");
+ parameters.put("integration.request.header.X-Object", "context.identity");
parameters.put("integration.request.header.X-Request-Id", "context.requestId");
parameters.put("integration.request.header.X-Context-Stage", "context.stage");
parameters.put("integration.request.header.X-Context-Path", "context.path");
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java
index 7061989629..1f2e363356 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java
@@ -36,7 +36,7 @@ class ApiGatewayProxyMatchTest {
ctrl = new ApiGatewayExecuteController(apiGatewayService, null, apiGatewayV2Service, lambdaService,
new RegionResolver("us-east-1", "000000000000"),
new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service, null,
- new ApiGatewayExecuteRouteContext(), null, null, null);
+ new ApiGatewayExecuteRouteContext(), null, null, null, null);
}
private ApiGatewayResource resource(String id, String parentId, String pathPart, String path) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPutRestApiMergeAuthorizationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPutRestApiMergeAuthorizationTest.java
index 1507e012e4..2e5b2bba18 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPutRestApiMergeAuthorizationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPutRestApiMergeAuthorizationTest.java
@@ -211,10 +211,14 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {
}
""";
private static final byte[] DENY_POLICY = """
- {"principalId":"blocked","policyDocument":{"Statement":[{"Effect":"Deny"}]}}
+ {"principalId":"blocked","policyDocument":{"Version":"2012-10-17","Statement":[
+ {"Effect":"Deny","Action":"execute-api:Invoke","Resource":"*"}
+ ]}}
""".getBytes(StandardCharsets.UTF_8);
private static final byte[] ALLOW_POLICY = """
- {"principalId":"allowed","policyDocument":{"Statement":[{"Effect":"Allow"}]}}
+ {"principalId":"allowed","policyDocument":{"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"execute-api:Invoke","Resource":"*"}
+ ]}}
""".getBytes(StandardCharsets.UTF_8);
@InjectMock
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRootResourceLookupTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRootResourceLookupTest.java
index 02f6051e7f..589ef69c29 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRootResourceLookupTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRootResourceLookupTest.java
@@ -99,7 +99,7 @@ class ApiGatewayRootResourceLookupTest {
ObjectMapper objectMapper = new ObjectMapper();
ApiGatewayController controller = new ApiGatewayController(mockedService,
mock(ApiGatewayV2Service.class), mock(ApiGatewayV2OpenApiImporter.class),
- regionResolver, objectMapper);
+ regionResolver, objectMapper, null);
Response response = controller.getRestApis(headers);
JsonNode body = objectMapper.readTree((String) response.getEntity());
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 64a26f85c1..3098c2e14b 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
@@ -48,7 +48,7 @@ class BuildV2AuthorizerEventTrailingSlashTest {
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null, null
- );
+ , null);
}
private JsonNode buildEvent(String normalizedPath, String rawRequestUri) throws Exception {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java
index 519df55a6d..6eba69ab89 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java
@@ -51,7 +51,7 @@ class BuildV2ProxyEventBodyEncodingTest {
null, null, null, null,
regionResolver, objectMapper, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
- );
+ , null);
}
@ParameterizedTest(name = "{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 7b4442d5b6..225d7d826f 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
@@ -47,7 +47,7 @@ class BuildV2ProxyEventJwtClaimsTest {
null, null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
- );
+ , null);
}
@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
index 663403c8c1..b4fce74583 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventLambdaAuthorizerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventLambdaAuthorizerTest.java
@@ -51,7 +51,7 @@ class BuildV2ProxyEventLambdaAuthorizerTest {
null, null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
- );
+ , null);
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java
index e9b9e933c1..fc5669144f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java
@@ -42,7 +42,7 @@ class BuildV2ProxyEventPathParametersTest {
null, null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
- );
+ , null);
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventTrailingSlashTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventTrailingSlashTest.java
index ad50c8b8ed..b86c85d7ee 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventTrailingSlashTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventTrailingSlashTest.java
@@ -47,7 +47,7 @@ class BuildV2ProxyEventTrailingSlashTest {
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null, null
- );
+ , null);
}
private JsonNode buildEvent(String normalizedPath, String rawRequestUri, String routeKey) throws Exception {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java
index a404fcc367..b89d72b43a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java
@@ -30,7 +30,7 @@ class JwtClaimsWireFormatTest {
null, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null, null
- );
+ , null);
}
private static String unsignedToken(String claimsJson) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java
index e5b3ae1d52..7e843d2e96 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java
@@ -60,7 +60,7 @@ class ProxyEventIamIdentityTest {
controller = new ApiGatewayExecuteController(
null, null, null, null,
regionResolver, MAPPER, null,
- null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.java
index 148b2f037e..bacf4b0bca 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.java
@@ -50,7 +50,7 @@ class ProxyEventPathParametersTest {
controller = new ApiGatewayExecuteController(
null, null, null, null,
regionResolver, MAPPER, null,
- null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
}
private JsonNode pathParametersFor(String path, String resourcePath) throws Exception {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizerIntegrationTest.java
new file mode 100644
index 0000000000..e0a5daee39
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizerIntegrationTest.java
@@ -0,0 +1,389 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+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.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+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.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@QuarkusTest
+class RestLambdaAuthorizerIntegrationTest {
+ private static final String FUNCTION = "rest-contract-authorizer";
+ private static final String AUTHORIZER_URI = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
+ + "arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION + "/invocations";
+
+ @InjectMock
+ LambdaService lambdaService;
+
+ private String apiId;
+ private String authorizerId;
+
+ @BeforeEach
+ void createApi() {
+ apiId = given().contentType(ContentType.JSON).body(Map.of("name", "rest-authorizer-contract"))
+ .post("/restapis").then().statusCode(201).extract().path("id");
+ String rootId = given().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item[0].id");
+ for (String path : List.of("allowed", "other")) {
+ String resourceId = given().contentType(ContentType.JSON).body(Map.of("pathPart", path))
+ .post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201).extract().path("id");
+
+ }
+ }
+
+ @AfterEach
+ void deleteApi() {
+ given().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"resource", "action", "laterDeny", "firstUnmatched"})
+ void evaluatesEveryStatementAgainstRequestedActionAndResource(String scenario) throws Exception {
+ configure("TOKEN", 0, "method.request.header.Authorization");
+ Map<String, String> allow = statement("Allow", "execute-api:Invoke", "*");
+ List<Map<String, String>> statements = switch (scenario) {
+ case "resource" -> List.of(statement("Allow", "execute-api:Invoke", methodArn("other")));
+ case "action" -> List.of(statement("Allow", "execute-api:ManageConnections", "*"));
+ case "laterDeny" -> List.of(allow, statement("Deny", "execute-api:Invoke", methodArn("allowed")));
+ default -> List.of(statement("Deny", "execute-api:Invoke", methodArn("other")), allow);
+ };
+ respond(Map.of("principalId", "verified", "policyDocument", policy(statements)));
+ given().header("Authorization", "token").get(execute("allowed"))
+ .then().statusCode("firstUnmatched".equals(scenario) ? 200 : 403);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"principal", "object", "array", "null", "policy"})
+ void invalidOutputFailsBeforeIntegration(String scenario) throws Exception {
+ configure("TOKEN", 0, "method.request.header.Authorization");
+ Map<String, Object> output = new LinkedHashMap<>();
+ output.put("principalId", "verified");
+ output.put("policyDocument", policy(List.of(statement("Allow", "execute-api:Invoke", "*"))));
+ switch (scenario) {
+ case "principal" -> output.remove("principalId");
+ case "object" -> output.put("context", Map.of("claims", Map.of("nested", "value")));
+ case "array" -> output.put("context", Map.of("claims", List.of("value")));
+ case "null" -> output.put("context", Collections.singletonMap("claims", null));
+ default -> output.put("policyDocument", Map.of("Statement", List.of(Map.of("Effect", "Allow"))));
+ }
+ respond(output);
+ given().header("Authorization", "token").get(execute("allowed")).then().statusCode(500);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"default,missing", "300,missing", "300,empty", "300,blank"})
+ void cachedRequestAuthorizerRequiresIdentitySourceAtCreation(String ttl, String source) {
+ Map<String, Object> request = new LinkedHashMap<>();
+ request.put("name", "invalid-request-authorizer");
+ request.put("type", "REQUEST");
+ request.put("authorizerUri", AUTHORIZER_URI);
+ if (!"default".equals(ttl)) {
+ request.put("authorizerResultTtlInSeconds", Integer.parseInt(ttl));
+ }
+ if (!"missing".equals(source)) {
+ request.put("identitySource", "blank".equals(source) ? " " : "");
+ }
+ given().contentType(ContentType.JSON).body(request)
+ .post("/restapis/" + apiId + "/authorizers").then().statusCode(400);
+ given().get("/restapis/" + apiId + "/authorizers")
+ .then().statusCode(200).body("item.size()", equalTo(0));
+ }
+
+ @Test
+ void uncachedRequestAuthorizerCanOmitIdentitySource() throws Exception {
+ configure("REQUEST", 0, null);
+ allowAll();
+ given().get(execute("allowed")).then().statusCode(200);
+ verifyInvocation(1);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"300,method.request.header.Authorization,/identitySource, ",
+ "0,,/authorizerResultTtlInSeconds,300"})
+ void invalidRequestAuthorizerUpdateLeavesConfigurationUnchanged(int ttl, String source, String path, String value) {
+ configure("REQUEST", ttl, source);
+ given().contentType(ContentType.JSON).body(Map.of("patchOperations", List.of(
+ Map.of("op", "replace", "path", "/name", "value", "changed"),
+ Map.of("op", "replace", "path", path, "value", value != null ? value : ""))))
+ .patch("/restapis/" + apiId + "/authorizers/" + authorizerId).then().statusCode(400);
+ given().get("/restapis/" + apiId + "/authorizers/" + authorizerId).then().statusCode(200)
+ .body("name", equalTo("contract"), "authorizerResultTtlInSeconds", equalTo(ttl));
+ }
+
+ @Test
+ void requestAuthorizerCanEnableCachingAndIdentitySourceInOnePatch() {
+ configure("REQUEST", 0, null);
+ given().contentType(ContentType.JSON).body(Map.of("patchOperations", List.of(
+ Map.of("op", "replace", "path", "/authorizerResultTtlInSeconds", "value", "300"),
+ Map.of("op", "replace", "path", "/identitySource", "value", "method.request.header.Authorization"))))
+ .patch("/restapis/" + apiId + "/authorizers/" + authorizerId).then().statusCode(200)
+ .body("authorizerResultTtlInSeconds", equalTo(300),
+ "identitySource", equalTo("method.request.header.Authorization"));
+ }
+
+ @Test
+ void cachedHyphenatedContextReachesLambdaProxy() throws Exception {
+ configure("TOKEN", 300, "method.request.header.Authorization");
+ respond(Map.of("principalId", "verified", "context", Map.of("tenant-id", "tenant-one", "plan.level", 2),
+ "policyDocument", policy(List.of(statement("Allow", "execute-api:Invoke", "*")))));
+ String resourceId = given().get("/restapis/" + apiId + "/resources").then().extract()
+ .path("item.find { it.path == '/allowed' }.id");
+ given().contentType(ContentType.JSON).body(Map.of("type", "AWS_PROXY", "httpMethod", "POST",
+ "uri", AUTHORIZER_URI.replace(FUNCTION, "context-proxy")))
+ .put(methodPath(resourceId) + "/integration").then().statusCode(201);
+ when(lambdaService.invoke(eq("us-east-1"), eq("context-proxy"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenAnswer(invocation -> {
+ ObjectMapper mapper = new ObjectMapper();
+ String context = mapper.readTree((byte[]) invocation.getArgument(2))
+ .path("requestContext").path("authorizer").toString();
+ return new InvokeResult(200, null,
+ mapper.writeValueAsBytes(Map.of("statusCode", 200, "body", context)), null, "proxy-request");
+ });
+ deploy("test");
+ for (int request = 0; request < 2; request++) {
+ given().header("Authorization", "token").get(execute("allowed"))
+ .then().statusCode(200).body("'tenant-id'", equalTo("tenant-one"),
+ "'plan.level'", equalTo("2"), "principalId", equalTo("verified"));
+ }
+ verifyInvocation(1);
+ }
+
+ @Test
+ void missingTokenIsUnauthorizedWithoutInvokingLambda() throws Exception {
+ configure("TOKEN", 0, "method.request.header.Authorization");
+ allowAll();
+ given().get(execute("allowed")).then().statusCode(401);
+ verifyInvocation(0);
+ }
+
+ @Test
+ void cachedPolicyAndContextAreReusedButPolicyStillGatesEachRoute() throws Exception {
+ configure("TOKEN", 300, "method.request.header.Authorization");
+ respond(Map.of("principalId", "verified", "context", Map.of("userClaims", "trusted"),
+ "policyDocument", policy(List.of(statement("Allow", "execute-api:Invoke", methodArn("allowed"))))));
+ for (int i = 0; i < 2; i++) {
+ given().header("Authorization", "token").header("X-User-Claims", "forged")
+ .get(execute("allowed")).then().statusCode(200)
+ .body("principal", equalTo("verified"), "claims", equalTo("trusted"));
+ }
+ given().header("Authorization", "token").get(execute("other")).then().statusCode(403);
+ verifyInvocation(1);
+ }
+
+ @Test
+ void zeroTtlInvokesForEachRequest() throws Exception {
+ configure("TOKEN", 0, "method.request.header.Authorization");
+ allowAll();
+ for (int i = 0; i < 2; i++) {
+ given().header("Authorization", "token").get(execute("allowed")).then().statusCode(200);
+ }
+ verifyInvocation(2);
+ }
+
+ @Test
+ void flushingStageAndRedeployingInvalidateCachedResult() throws Exception {
+ configure("TOKEN", 300, "method.request.header.Authorization");
+ allowAll();
+ given().header("Authorization", "token").get(execute("allowed")).then().statusCode(200);
+ given().delete("/restapis/" + apiId + "/stages/test/cache/authorizers").then().statusCode(202).body(equalTo(""));
+ given().header("Authorization", "token").get(execute("allowed")).then().statusCode(200);
+ deploy("test");
+ given().header("Authorization", "token").get(execute("allowed")).then().statusCode(200);
+ verifyInvocation(3);
+ given().delete("/restapis/" + apiId + "/stages/missing/cache/authorizers").then().statusCode(404);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"TOKEN", "REQUEST"})
+ void flushPreventsInFlightInvocationFromRestoringStaleContext(String type) throws Exception {
+ configure(type, 300, "method.request.header.Authorization");
+ CountDownLatch started = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ AtomicInteger invocations = new AtomicInteger();
+ when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenAnswer(invocation -> {
+ boolean first = invocations.incrementAndGet() == 1;
+ if (first) {
+ started.countDown();
+ assertTrue(release.await(10, TimeUnit.SECONDS), "Authorizer invocation was not released");
+ }
+ byte[] payload = new ObjectMapper().writeValueAsBytes(Map.of("principalId", "verified",
+ "policyDocument", policy(List.of(statement("Allow", "execute-api:Invoke", "*"))),
+ "context", Map.of("userClaims", first ? "stale" : "fresh")));
+ return new InvokeResult(200, null, payload, null, "lambda-request");
+ });
+ try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
+ Future<?> request = executor.submit(() -> given().header("Authorization", "token")
+ .get(execute("allowed")).then().statusCode(200).body("claims", equalTo("stale")));
+ try {
+ assertTrue(started.await(10, TimeUnit.SECONDS), "Authorizer invocation did not start");
+ given().delete("/restapis/" + apiId + "/stages/test/cache/authorizers").then().statusCode(202);
+ } finally {
+ release.countDown();
+ }
+ request.get(10, TimeUnit.SECONDS);
+ }
+ for (int i = 0; i < 2; i++) {
+ given().header("Authorization", "token").get(execute("allowed"))
+ .then().statusCode(200).body("claims", equalTo("fresh"));
+ }
+ verifyInvocation(2);
+ }
+
+ @Test
+ void changedAuthorizerConfigurationInvalidatesCachedResult() throws Exception {
+ configure("TOKEN", 300, "method.request.header.Authorization");
+ allowAll();
+ given().header("Authorization", "token").get(execute("allowed")).then().statusCode(200);
+ given().contentType(ContentType.JSON).body(Map.of("patchOperations", List.of(Map.of(
+ "op", "replace", "path", "/identitySource", "value", "method.request.header.New-Token"))))
+ .patch("/restapis/" + apiId + "/authorizers/" + authorizerId).then().statusCode(200);
+ given().header("New-Token", "token").get(execute("allowed")).then().statusCode(200);
+ verifyInvocation(2);
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {0, 300})
+ void requestIdentitySourcesAreRequiredOnlyWhenCaching(int ttl) throws Exception {
+ configure("REQUEST", ttl, "method.request.header.Authorization,method.request.querystring.tenant");
+ allowAll();
+ given().header("Authorization", "token").get(execute("allowed"))
+ .then().statusCode(ttl == 0 ? 200 : 401);
+ verifyInvocation(ttl == 0 ? 1 : 0);
+ }
+
+ @Test
+ void requestCacheUsesAllIdentitySources() throws Exception {
+ configure("REQUEST", 300, "method.request.header.Authorization,method.request.querystring.tenant");
+ allowAll();
+ for (String tenant : List.of("one", "one", "two")) {
+ given().header("Authorization", "token").queryParam("tenant", tenant)
+ .get(execute("allowed")).then().statusCode(200);
+ }
+ verifyInvocation(2);
+ }
+
+ @Test
+ void requestContextIdentitySourcesSeparateRoutePolicies() throws Exception {
+ configure("REQUEST", 300, "method.request.header.Authorization,context.resourcePath");
+ allowAll();
+ for (String path : List.of("allowed", "allowed", "other")) {
+ given().header("Authorization", "token").get(execute(path)).then().statusCode(200);
+ }
+ verifyInvocation(2);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"Unauthorized", "failure"})
+ void lambdaErrorsDistinguishUnauthorizedFromFailure(String message) throws Exception {
+ configure("TOKEN", 300, "method.request.header.Authorization");
+ byte[] payload = new ObjectMapper().writeValueAsBytes(Map.of("errorMessage", message));
+ when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new InvokeResult(200, "Unhandled", payload, null, "lambda-error"));
+ for (int i = 0; i < 2; i++) {
+ given().header("Authorization", "token").get(execute("allowed"))
+ .then().statusCode("Unauthorized".equals(message) ? 401 : 500);
+ }
+ verifyInvocation(2);
+ }
+
+ private void configure(String type, int ttl, String identitySource) {
+ Map<String, Object> request = new LinkedHashMap<>(Map.of("name", "contract", "type", type,
+ "authorizerUri", AUTHORIZER_URI, "authorizerResultTtlInSeconds", ttl));
+ if (identitySource != null) {
+ request.put("identitySource", identitySource);
+ }
+ authorizerId = given().contentType(ContentType.JSON).body(request)
+ .post("/restapis/" + apiId + "/authorizers").then().statusCode(201).extract().path("id");
+ List<String> resources = given().get("/restapis/" + apiId + "/resources")
+ .then().extract().path("item.findAll { it.path != '/' }.id");
+ for (String resourceId : resources) {
+ given().contentType(ContentType.JSON).body(Map.of("authorizationType", "CUSTOM", "authorizerId", authorizerId))
+ .put(methodPath(resourceId)).then().statusCode(201);
+ given().contentType(ContentType.JSON).body(Map.of("type", "MOCK",
+ "requestTemplates", Map.of("application/json", "{\"statusCode\":200}")))
+ .put(methodPath(resourceId) + "/integration").then().statusCode(201);
+ given().contentType(ContentType.JSON).body(Map.of())
+ .put(methodPath(resourceId) + "/responses/200").then().statusCode(201);
+ given().contentType(ContentType.JSON).body(Map.of("responseTemplates", Map.of("application/json",
+ "{\"principal\":\"$context.authorizer.principalId\","
+ + "\"claims\":\"$context.authorizer.userClaims\"}")))
+ .put(methodPath(resourceId) + "/integration/responses/200").then().statusCode(201);
+ }
+ deploy("test");
+ }
+
+ private void deploy(String stage) {
+ given().contentType(ContentType.JSON).body(Map.of("stageName", stage))
+ .post("/restapis/" + apiId + "/deployments").then().statusCode(201);
+ }
+
+ private void allowAll() throws Exception {
+ respond(Map.of("principalId", "verified", "policyDocument",
+ policy(List.of(statement("Allow", "execute-api:Invoke", "*")))));
+ }
+
+ private void respond(Map<String, Object> output) throws Exception {
+ byte[] payload = new ObjectMapper().writeValueAsBytes(output);
+ when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(new InvokeResult(200, null, payload, null, "lambda-request"));
+ }
+
+ private void verifyInvocation(int count) {
+ if (count == 0) {
+ verify(lambdaService, never()).invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
+ } else {
+ verify(lambdaService, times(count)).invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
+ }
+ }
+
+ private static Map<String, String> statement(String effect, String action, String resource) {
+ return Map.of("Effect", effect, "Action", action, "Resource", resource);
+ }
+
+ private static Map<String, Object> policy(List<Map<String, String>> statements) {
+ return Map.of("Version", "2012-10-17", "Statement", statements);
+ }
+
+ private String methodPath(String resourceId) {
+ return "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";
+ }
+
+ private String methodArn(String path) {
+ return "arn:aws:execute-api:us-east-1:000000000000:" + apiId + "/test/GET/" + path;
+ }
+
+ private String execute(String path) {
+ return "/execute-api/" + apiId + "/test/" + path;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizerTest.java
new file mode 100644
index 0000000000..84f24cb991
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizerTest.java
@@ -0,0 +1,119 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+class RestLambdaAuthorizerTest {
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final Clock clock = mock(Clock.class);
+ private final Instant now = Instant.parse("2026-10-03T00:00:00Z");
+ private RestLambdaAuthorizer authorizer;
+
+ @BeforeEach
+ void createAuthorizer() {
+ when(clock.instant()).thenReturn(now);
+ authorizer = new RestLambdaAuthorizer(mapper, new IamPolicyEvaluator(mapper), clock);
+ }
+
+ @Test
+ void expiresAtTtlBoundaryAndZeroTtlDoesNotCache() {
+ RestLambdaAuthorizer.Result result = new RestLambdaAuthorizer.Result("principal", "{}", Map.of("claims", "trusted"));
+ RestLambdaAuthorizer.CacheKey key = key("account", "region", "api", "stage", "deployment", "token", 10);
+ cache(key, result);
+ when(clock.instant()).thenReturn(now.plusSeconds(9));
+ assertSame(result, authorizer.get(key));
+ when(clock.instant()).thenReturn(now.plusSeconds(10));
+ assertNull(authorizer.get(key));
+ RestLambdaAuthorizer.CacheKey disabled = key("account", "region", "api", "stage", "deployment", "token", 0);
+ cache(disabled, result);
+ assertNull(authorizer.get(disabled));
+ }
+
+ @Test
+ void cacheIsScopedAndFlushOnlyRemovesTargetStage() {
+ RestLambdaAuthorizer.CacheKey target = key("account", "region", "api", "stage", "deployment", "token", 300);
+ List<RestLambdaAuthorizer.CacheKey> others = List.of(
+ key("other", "region", "api", "stage", "deployment", "token", 300),
+ key("account", "other", "api", "stage", "deployment", "token", 300),
+ key("account", "region", "other", "stage", "deployment", "token", 300),
+ key("account", "region", "api", "other", "deployment", "token", 300));
+ RestLambdaAuthorizer.Result result = new RestLambdaAuthorizer.Result("principal", "{}", Map.of());
+ cache(target, result);
+ others.forEach(key -> cache(key, result));
+ assertNull(authorizer.get(key("account", "region", "api", "stage", "new-deployment", "token", 300)));
+ assertNull(authorizer.get(key("account", "region", "api", "stage", "deployment", "other-token", 300)));
+ authorizer.flush(target.scope());
+ assertNull(authorizer.get(target));
+ others.forEach(key -> assertSame(result, authorizer.get(key)));
+ }
+
+ @Test
+ void policyArraysWildcardsAndConditionsUseIamEvaluation() throws Exception {
+ byte[] payload = mapper.writeValueAsBytes(Map.of("principalId", "principal", "policyDocument", Map.of(
+ "Version", "2012-10-17", "Statement", List.of(Map.of("Effect", "Allow",
+ "Action", List.of("execute-api:Invoke"), "Resource", List.of("*/GET/allowed/*"),
+ "Condition", Map.of("IpAddress", Map.of("aws:SourceIp", "192.0.2.0/24")))))));
+ RestLambdaAuthorizer.Result result = authorizer.parse(payload);
+ assertTrue(authorizer.permits(result, "api/stage/GET/allowed/child", Map.of("aws:SourceIp", List.of("192.0.2.10"))));
+ assertFalse(authorizer.permits(result, "api/stage/GET/other/child", Map.of("aws:SourceIp", List.of("192.0.2.10"))));
+ assertFalse(authorizer.permits(result, "api/stage/GET/allowed/child", Map.of("aws:SourceIp", List.of("198.51.100.10"))));
+ }
+
+ @Test
+ void scalarContextRetainsTypesAndIsImmutable() throws Exception {
+ byte[] payload = mapper.writeValueAsBytes(Map.of("principalId", "principal", "context",
+ Map.of("tenant-id", "trusted", "number", 2, "boolean", true), "policyDocument",
+ Map.of("Statement", Map.of("Effect", "Allow", "Action", "execute-api:Invoke", "Resource", "*"))));
+ RestLambdaAuthorizer.Result result = authorizer.parse(payload);
+ assertEquals(Map.of("tenant-id", "trusted", "number", 2, "boolean", true), result.context());
+ assertThrows(UnsupportedOperationException.class, () -> result.context().put("claims", "forged"));
+ assertTrue(authorizer.permits(result, "method", Map.of()));
+ }
+
+ @Test
+ void flushInvalidatesOnlyPendingInvocationsInItsScope() {
+ RestLambdaAuthorizer.CacheKey target = key("account", "region", "api", "stage", "deployment", "token", 300);
+ RestLambdaAuthorizer.CacheKey other = key("account", "region", "api", "other", "deployment", "token", 300);
+ RestLambdaAuthorizer.Result result = new RestLambdaAuthorizer.Result("principal", "{}", Map.of());
+ try (RestLambdaAuthorizer.Invocation beforeFlush = authorizer.beginInvocation(target);
+ RestLambdaAuthorizer.Invocation unaffected = authorizer.beginInvocation(other)) {
+ authorizer.flush(target.scope());
+ cache(target, result);
+ beforeFlush.cache(new RestLambdaAuthorizer.Result("stale", "{}", Map.of()));
+ unaffected.cache(result);
+ assertSame(result, authorizer.get(target));
+ assertSame(result, authorizer.get(other));
+ }
+ }
+
+ @Test
+ void closedInvocationCannotInsertResult() {
+ RestLambdaAuthorizer.CacheKey key = key("account", "region", "api", "stage", "deployment", "token", 300);
+ RestLambdaAuthorizer.Invocation invocation = authorizer.beginInvocation(key);
+ invocation.close();
+ invocation.cache(new RestLambdaAuthorizer.Result("principal", "{}", Map.of()));
+ assertNull(authorizer.get(key));
+ }
+
+ private void cache(RestLambdaAuthorizer.CacheKey key, RestLambdaAuthorizer.Result result) {
+ try (RestLambdaAuthorizer.Invocation invocation = authorizer.beginInvocation(key)) {
+ invocation.cache(result);
+ }
+ }
+
+ private static RestLambdaAuthorizer.CacheKey key(String account, String region, String api, String stage,
+ String deployment, String token, int ttl) {
+ return new RestLambdaAuthorizer.CacheKey(new RestLambdaAuthorizer.Scope(account, region, api, stage),
+ deployment, "authorizer", "uri", "TOKEN", "method.request.header.Authorization", ttl, List.of(token));
+ }
+}