fix(apigatewayv2): evaluate HTTP and WebSocket authorizer policies (#5020)

* fix(apigateway): evaluate Lambda authorizer policies with one evaluator

HTTP API (payload 1.0 and 2.0) and WebSocket $connect authorizers now
evaluate every policy statement against the execute-api ARN, instead of
reading only the first statement's Effect.

REST, HTTP and WebSocket APIs share AuthorizerPolicyEvaluator: one
validator and one set of condition keys (aws:SourceIp from the transport
address, aws:SecureTransport, aws:CurrentTime). IAM CIDR conditions now
match IPv6 ranges.

* fix(apigateway): reject malformed authorizer policy conditions

A Condition operator IAM does not know, an operator without keys, or a key
without values evaluated as a non-match or an unconditional match, so a
malformed Deny could be skipped and a malformed Allow could grant access.
Validate each operator and its values and return 500 instead. Numeric and
boolean condition values are now compared rather than dropped.

* fix(iam): leave scalar condition values to #5086

The numeric and boolean condition-value parsing moves to its own pull
request, together with the numeric and date comparison fixes it needs.

* docs: update the IAM operation count in the Service Matrix
This commit is contained in:
Abhigya authored and GitHub committed 2026-10-04 20:59:04 -05:00
1 parent 60c368e939
commit 1320995d70
27 files changed
+850 -132

No files matched your search

@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Optional;
/**
@@ -61,6 +62,31 @@ public final class CidrCanonicalizer {
return parse(cidr).map(parsed -> render(parsed).equals(cidr)).orElse(false);
}
/**
* Tests whether a literal address belongs to an IPv4 or IPv6 CIDR block.
* Malformed inputs and addresses from a different address family do not match.
* Neither input triggers DNS resolution.
*/
public static boolean contains(String cidr, String ip) {
Optional<ParsedCidr> parsed = parse(cidr);
if (parsed.isEmpty() || ip == null || ip.isBlank()) {
return false;
}
InetAddress address;
try {
address = InetAddress.ofLiteral(ip);
} catch (IllegalArgumentException ignored) {
// A malformed address cannot belong to a CIDR block.
return false;
}
ParsedCidr block = parsed.get();
byte[] networkBytes = block.address().getAddress();
byte[] addressBytes = address.getAddress();
return networkBytes.length == addressBytes.length
&& Arrays.equals(maskHostBits(networkBytes, block.prefixLength()),
maskHostBits(addressBytes, block.prefixLength()));
}
private static Optional<ParsedCidr> parse(String cidr) {
if (cidr == null || cidr.isBlank()) {
return Optional.empty();
@@ -122,6 +122,7 @@ public class ApiGatewayExecuteController {
private final RequestContext requestContext;
private final ExecuteApiSigV4Authorizer sigV4Authorizer;
private final RestLambdaAuthorizer restLambdaAuthorizer;
private final AuthorizerPolicyEvaluator authorizerPolicyEvaluator;
@Inject
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, CognitoUserPoolAuthorizer cognitoAuthorizer,
@@ -135,7 +136,8 @@ public class ApiGatewayExecuteController {
ApiGatewayExecuteRouteContext routeContext,
JwtSignatureVerifier jwtSignatureVerifier,
RequestContext requestContext,
ExecuteApiSigV4Authorizer sigV4Authorizer, RestLambdaAuthorizer restLambdaAuthorizer) {
ExecuteApiSigV4Authorizer sigV4Authorizer, RestLambdaAuthorizer restLambdaAuthorizer,
AuthorizerPolicyEvaluator authorizerPolicyEvaluator) {
this.apiGatewayService = apiGatewayService;
this.cognitoAuthorizer = cognitoAuthorizer;
this.apiGatewayV2Service = apiGatewayV2Service;
@@ -156,6 +158,7 @@ public class ApiGatewayExecuteController {
this.requestContext = requestContext;
this.sigV4Authorizer = sigV4Authorizer;
this.restLambdaAuthorizer = restLambdaAuthorizer;
this.authorizerPolicyEvaluator = authorizerPolicyEvaluator;
}
/** Matches an ELBv2 listener ARN (ALB {@code app/} or NLB {@code net/}); group 1 = region. */
@@ -1037,9 +1040,8 @@ public class ApiGatewayExecuteController {
}
}
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()));
Map<String, List<String>> conditions = AuthorizerPolicyEvaluator.requestConditions(
routeContext.sourceIp(), isSecureTransport(uriInfo));
if (!restLambdaAuthorizer.permits(verified, methodArn, conditions)) {
return authorizerError(scope, GatewayResponseType.ACCESS_DENIED, 403);
}
@@ -3111,29 +3113,14 @@ public class ApiGatewayExecuteController {
.type(MediaType.APPLICATION_JSON).build(), null);
}
JsonNode statements = policyDocument.path("Statement");
if (statements.isMissingNode() || statements.isNull()
|| !statements.isArray() || statements.isEmpty()) {
LOG.warnv("Authorizer response missing or empty Statement array for API {0}", apiId);
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build(), null);
}
String effect = statements.get(0).path("Effect").asText("Deny");
if ("Deny".equalsIgnoreCase(effect)) {
String methodArn = buildMethodArn(region, apiId, stageName, httpMethod, path);
if (!authorizerPolicyEvaluator.permits(policyDocument, methodArn,
routeContext.sourceIp(), isSecureTransport(uriInfo))) {
return new RequestAuthorizerResult(Response.status(403)
.entity(jsonMessage("User is not authorized to access this resource"))
.type(MediaType.APPLICATION_JSON).build(), null);
}
if (!"Allow".equalsIgnoreCase(effect)) {
LOG.warnv("Authorizer response has unrecognized Effect '{0}' for API {1}", effect, apiId);
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build(), null);
}
return new RequestAuthorizerResult(null, requestAuthorizerContext(response));
} catch (Exception e) {
LOG.warnv("Failed to parse authorizer response for API {0}: {1}", apiId, e.getMessage());
@@ -3155,6 +3142,10 @@ public class ApiGatewayExecuteController {
return context.isObject() && !context.isEmpty() ? (ObjectNode) context : null;
}
private static boolean isSecureTransport(UriInfo uriInfo) {
return "https".equals(uriInfo.getRequestUri().getScheme());
}
/**
* Builds a REQUEST authorizer event in payload format version 1.0.
* Compatible with REST API (v1) REQUEST authorizer shape.
@@ -0,0 +1,139 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
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.time.Instant;
import java.util.List;
import java.util.Map;
/**
* Validates Lambda authorizer policies and evaluates them against the requested execute-api ARN,
* so a policy means the same thing on REST, HTTP and WebSocket APIs.
*/
@ApplicationScoped
public class AuthorizerPolicyEvaluator {
private final IamPolicyEvaluator iamPolicyEvaluator;
@Inject
public AuthorizerPolicyEvaluator(IamPolicyEvaluator iamPolicyEvaluator) {
this.iamPolicyEvaluator = iamPolicyEvaluator;
}
/**
* Rejects a policy document API Gateway cannot evaluate.
*
* @throws IllegalArgumentException when the policy is malformed
*/
public static void validate(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") && !validCondition(statement.get("Condition")))) {
throw new IllegalArgumentException("Invalid authorizer policy statement");
}
}
/**
* An operator IAM does not know, or one with no keys or values, would otherwise evaluate as
* a non-match or an unconditional match, so a malformed Deny could be skipped or a malformed
* Allow could grant access. An empty {@code Condition} object stays valid, as in IAM.
*/
private static boolean validCondition(JsonNode condition) {
if (!condition.isObject()) {
return false;
}
for (Map.Entry<String, JsonNode> operator : condition.properties()) {
JsonNode keys = operator.getValue();
if (!IamPolicyEvaluator.isSupportedConditionOperator(operator.getKey())
|| !keys.isObject() || keys.isEmpty()) {
return false;
}
for (Map.Entry<String, JsonNode> key : keys.properties()) {
if (key.getKey().isEmpty() || !validConditionValues(key.getValue())) {
return false;
}
}
}
return true;
}
private static boolean validConditionValues(JsonNode values) {
if (!values.isArray()) {
return validConditionValue(values);
}
if (values.isEmpty()) {
return false;
}
for (JsonNode value : values) {
if (!validConditionValue(value)) {
return false;
}
}
return true;
}
private static boolean validConditionValue(JsonNode value) {
return value.isTextual() || value.isNumber() || value.isBoolean();
}
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;
}
/** The global condition keys an authorizer policy can test for the current request. */
public static Map<String, List<String>> requestConditions(String sourceIp, boolean secureTransport) {
return Map.of("aws:SourceIp", List.of(sourceIp),
"aws:SecureTransport", List.of(Boolean.toString(secureTransport)),
"aws:CurrentTime", List.of(Instant.now().toString()));
}
/**
* Validates the policy, then returns whether a matching Allow grants invocation without a
* matching explicit Deny.
*
* @throws IllegalArgumentException when the policy is malformed
*/
public boolean permits(JsonNode policyDocument, String methodArn, String sourceIp, boolean secureTransport) {
validate(policyDocument);
return permits(policyDocument.toString(), methodArn, requestConditions(sourceIp, secureTransport));
}
/** Returns whether an already validated policy grants invocation of the method ARN. */
public boolean permits(String policyDocument, String methodArn, Map<String, List<String>> conditions) {
return iamPolicyEvaluator.evaluate(CallerContext.of(List.of(policyDocument)), null,
"execute-api:Invoke", methodArn, conditions) == IamPolicyEvaluator.Decision.ALLOW;
}
}
@@ -2,8 +2,6 @@ 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;
@@ -24,17 +22,17 @@ public class RestLambdaAuthorizer {
static final int MAX_ENTRIES = 1_000;
private final ObjectMapper objectMapper;
private final IamPolicyEvaluator policyEvaluator;
private final AuthorizerPolicyEvaluator 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) {
public RestLambdaAuthorizer(ObjectMapper objectMapper, AuthorizerPolicyEvaluator policyEvaluator) {
this(objectMapper, policyEvaluator, Clock.systemUTC());
}
RestLambdaAuthorizer(ObjectMapper objectMapper, IamPolicyEvaluator policyEvaluator, Clock clock) {
RestLambdaAuthorizer(ObjectMapper objectMapper, AuthorizerPolicyEvaluator policyEvaluator, Clock clock) {
this.objectMapper = objectMapper;
this.policyEvaluator = policyEvaluator;
this.clock = clock;
@@ -64,51 +62,10 @@ public class RestLambdaAuthorizer {
throw new IllegalArgumentException("Authorizer must return a nonempty principalId");
}
JsonNode policy = output.path("policyDocument");
validatePolicy(policy);
AuthorizerPolicyEvaluator.validate(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();
@@ -128,8 +85,7 @@ public class RestLambdaAuthorizer {
}
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;
return policyEvaluator.permits(result.policyDocument(), methodArn, conditions);
}
Result get(CacheKey key) {
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigatewayv2.websocket;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.apigateway.AuthorizerPolicyEvaluator;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
@@ -33,16 +34,19 @@ public class WebSocketAuthorizerService {
private final LambdaService lambdaService;
private final WebSocketProxyEventBuilder proxyEventBuilder;
private final ObjectMapper objectMapper;
private final AuthorizerPolicyEvaluator authorizerPolicyEvaluator;
@Inject
public WebSocketAuthorizerService(ApiGatewayV2Service apiGatewayV2Service,
LambdaService lambdaService,
WebSocketProxyEventBuilder proxyEventBuilder,
ObjectMapper objectMapper) {
ObjectMapper objectMapper,
AuthorizerPolicyEvaluator authorizerPolicyEvaluator) {
this.apiGatewayV2Service = apiGatewayV2Service;
this.lambdaService = lambdaService;
this.proxyEventBuilder = proxyEventBuilder;
this.objectMapper = objectMapper;
this.authorizerPolicyEvaluator = authorizerPolicyEvaluator;
}
/**
@@ -82,7 +86,7 @@ public class WebSocketAuthorizerService {
String authorizerId, String connectionId, long connectedAt,
Map<String, List<String>> headers,
Map<String, List<String>> queryParams,
String sourceIp, String userAgent,
String sourceIp, boolean secureTransport, String userAgent,
Map<String, String> stageVariables) {
// Fetch the authorizer model
Authorizer authorizer = apiGatewayV2Service.getAuthorizer(region, apiId, authorizerId);
@@ -138,13 +142,15 @@ public class WebSocketAuthorizerService {
}
// Parse the policy document
return parseAuthorizerResponse(invokeResult, apiId);
return parseAuthorizerResponse(invokeResult, apiId, proxyEventBuilder.buildMethodArn(region, apiId, stageName),
sourceIp, secureTransport);
}
/**
* Parse the authorizer Lambda response and extract the policy decision.
*/
private AuthorizerResult parseAuthorizerResponse(InvokeResult invokeResult, String apiId) {
private AuthorizerResult parseAuthorizerResponse(InvokeResult invokeResult, String apiId, String methodArn,
String sourceIp, boolean secureTransport) {
// Check for function error
if (invokeResult.getFunctionError() != null) {
LOG.warnv("Lambda authorizer returned function error for API {0}: {1}",
@@ -166,24 +172,10 @@ public class WebSocketAuthorizerService {
return AuthorizerResult.error();
}
JsonNode statements = policyDocument.path("Statement");
if (statements.isMissingNode() || statements.isNull()
|| !statements.isArray() || statements.isEmpty()) {
LOG.warnv("Authorizer response missing or empty Statement array for API {0}", apiId);
return AuthorizerResult.error();
}
String effect = statements.get(0).path("Effect").asText("Deny");
if ("Deny".equalsIgnoreCase(effect)) {
if (!authorizerPolicyEvaluator.permits(policyDocument, methodArn, sourceIp, secureTransport)) {
return AuthorizerResult.deny();
}
if (!"Allow".equalsIgnoreCase(effect)) {
LOG.warnv("Authorizer response has unrecognized Effect '{0}' for API {1}",
effect, apiId);
return AuthorizerResult.error();
}
// Extract context map if present
Map<String, Object> context = null;
JsonNode contextNode = policy.path("context");
@@ -210,6 +210,7 @@ public class WebSocketHandler {
String sourceIp = ctx.request().remoteAddress() != null
? ctx.request().remoteAddress().host() : "127.0.0.1";
String userAgent = ctx.request().getHeader("User-Agent");
boolean secureTransport = ctx.request().isSSL();
// Load stage variables (default to empty map if null)
Map<String, String> stageVariables = stage.getStageVariables() != null
@@ -238,7 +239,7 @@ public class WebSocketHandler {
vertx.<WebSocketAuthorizerService.AuthorizerResult>executeBlocking(() -> {
return authorizerService.invokeAndEvaluate(region, apiId, stageName,
connectRoute.getAuthorizerId(), finalConnectionId, finalConnectedAt,
headers, queryParams, finalSourceIp, finalUserAgent, finalStageVariables);
headers, queryParams, finalSourceIp, secureTransport, finalUserAgent, finalStageVariables);
}).onSuccess(authResult -> {
if (!authResult.allowed()) {
ctx.response().setStatusCode(authResult.statusCode()).end();
@@ -291,7 +291,7 @@ public class WebSocketProxyEventBuilder {
return AwsEndpoints.executeApiHost(apiId, region);
}
private String buildMethodArn(String region, String apiId, String stageName) {
String buildMethodArn(String region, String apiId, String stageName) {
return AwsArnUtils.Arn.of("execute-api", region, regionResolver.getAccountId(),
apiId + "/" + stageName + "/$connect").toString();
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsServiceNamespaces;
import io.github.hectorvent.floci.core.common.CidrCanonicalizer;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.PolicyStatement;
@@ -927,6 +928,14 @@ public class IamPolicyEvaluator {
*/
private enum SetQuantifier { NONE, FOR_ALL_VALUES, FOR_ANY_VALUE }
private static final Set<String> SUPPORTED_CONDITION_OPERATORS = Set.of(
"StringEquals", "StringNotEquals", "StringEqualsIgnoreCase", "StringNotEqualsIgnoreCase",
"StringLike", "StringNotLike", "ArnEquals", "ArnLike", "ArnNotEquals", "ArnNotLike", "Bool",
"NumericEquals", "NumericNotEquals", "NumericLessThan", "NumericLessThanEquals",
"NumericGreaterThan", "NumericGreaterThanEquals", "DateEquals", "DateNotEquals",
"DateLessThan", "DateLessThanEquals", "DateGreaterThan", "DateGreaterThanEquals",
"IpAddress", "NotIpAddress");
private record ParsedOperator(SetQuantifier quantifier, String baseOp, boolean ifExists) {}
/**
@@ -951,6 +960,20 @@ public class IamPolicyEvaluator {
return new ParsedOperator(quantifier, baseOp, ifExists);
}
/**
* Returns whether {@link #evaluate} understands a condition operator, including its
* {@code ForAllValues:}/{@code ForAnyValue:} prefix and {@code IfExists} suffix. An unknown
* operator never matches, which silently disables a Deny, so callers that must fail closed
* on a malformed policy check this first.
*/
public static boolean isSupportedConditionOperator(String operator) {
ParsedOperator parsed = parseOperator(operator);
if ("Null".equals(parsed.baseOp())) {
return !parsed.ifExists() && parsed.quantifier() == SetQuantifier.NONE;
}
return SUPPORTED_CONDITION_OPERATORS.contains(parsed.baseOp());
}
/**
* Combines the policy's condition values for a single request value. Positive operators
* OR — the request value may match any listed value. Negated operators AND — the request
@@ -1101,33 +1124,11 @@ public class IamPolicyEvaluator {
private boolean matchesIpAddress(String condValue, String ctxValue) {
if (condValue.contains("/")) {
return matchesCidr(condValue, ctxValue);
return CidrCanonicalizer.contains(condValue, ctxValue);
}
return condValue.equals(ctxValue);
}
private boolean matchesCidr(String cidr, String ip) {
try {
String[] parts = cidr.split("/");
int prefix = Integer.parseInt(parts[1]);
long cidrAddr = ipToLong(parts[0]);
long ipAddr = ipToLong(ip);
long mask = prefix == 0 ? 0L : (0xFFFFFFFFL << (32 - prefix)) & 0xFFFFFFFFL;
return (cidrAddr & mask) == (ipAddr & mask);
} catch (Exception e) {
return false;
}
}
private long ipToLong(String ip) {
String[] octets = ip.split("\\.");
long result = 0;
for (String octet : octets) {
result = (result << 8) | Integer.parseInt(octet);
}
return result;
}
// -----------------------------------------------------------------------
// Glob matching (case-insensitive, supports * and ?)
// -----------------------------------------------------------------------