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

* fix: evaluate and cache REST Lambda authorizer policies

* fix: share REST request context and complete parameter mappings

* fix: prevent stale REST authorizer caching after stage flush

* fix: use valid authorizer policies in REST import tests

* chore: align API Gateway imports with repository style

* fix(apigateway): isolate authorizer contracts and validate cached identities

* chore(apigateway): align restored context code with style guide

* chore: order API Gateway SDK test imports
This commit is contained in:
Abhigya authored and GitHub committed 2026-10-03 21:54:36 -04:00
1 parent 6568700e02
commit ae3adfe992
23 files changed
+1013 -85

No files matched your search

@@ -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 =
@@ -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,49 +1017,122 @@ 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);
}
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);
}
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);
}
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);
}
return invokeLambdaAuthorizer(scope, region, apiId, stageName, httpMethod, requestPath,
resourcePath, resourceId, stage, method, headers, uriInfo, resolvedApiKey);
}
return new AuthorizerResult(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);
}
}
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);
}
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 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,
HttpHeaders headers, UriInfo uriInfo, byte[] body) {
String validatorId = method.getRequestValidatorId();
@@ -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);
@@ -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;
@@ -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) {
@@ -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));
}
}