Skip to content

armgit / floci

Public Imported from GitHub
0

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

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

Abhigya1320995d7007
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md
index 06aa89ac15..aa1d497a18 100644
--- a/docs/services/api-gateway.md
+++ b/docs/services/api-gateway.md
@@ -566,6 +566,19 @@ Routes carrying `authorizationType: AWS_IAM`: including those an OpenAPI import
`awsSigv4` security scheme: require a signed caller; see
[IAM Authorization](#iam-authorization).
+Lambda authorizer policies are evaluated the same way for REST APIs, HTTP APIs (payload
+formats 1.0 and 2.0) and WebSocket `$connect` routes, against the request's execute-api ARN.
+An invocation requires a matching `execute-api:Invoke` Allow; a matching Deny takes
+precedence regardless of statement order. Statements may be an object or an array,
+and actions and resources may be strings or arrays with wildcards. No matching Allow
+returns 403; a malformed policy returns 500. HTTP API simple responses continue to
+use `isAuthorized` instead of an IAM policy.
+
+Conditions can test `aws:SourceIp` (IPv4 and IPv6 CIDR ranges), `aws:SecureTransport` and
+`aws:CurrentTime`. The source IP is the connection's transport address, so a
+caller-supplied `X-Forwarded-For` header does not override it. An empty `Condition`
+object places no condition on its statement, as in IAM.
+
### Supported Operations
| Category | Operations |
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/CidrCanonicalizer.java b/src/main/java/io/github/hectorvent/floci/core/common/CidrCanonicalizer.java
index da07c17f37..c86fd85246 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/CidrCanonicalizer.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/CidrCanonicalizer.java
@@ -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();
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 bc777c927a..80ff21ae8f 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
@@ -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.
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/AuthorizerPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/AuthorizerPolicyEvaluator.java
new file mode 100644
index 0000000000..d8ed46fd70
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/AuthorizerPolicyEvaluator.java
@@ -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;
+ }
+}
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
index b3b6505d13..47298492f8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizer.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizer.java
@@ -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) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketAuthorizerService.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketAuthorizerService.java
index ecf9ad9272..fa2210c0f8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketAuthorizerService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketAuthorizerService.java
@@ -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");
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java
index c45c37feea..0c51e80a19 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java
@@ -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();
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketProxyEventBuilder.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketProxyEventBuilder.java
index 4e6a0486d8..4ac9510098 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketProxyEventBuilder.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketProxyEventBuilder.java
@@ -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();
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
index ab7aa9dcad..4a2190214e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
@@ -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 ?)
// -----------------------------------------------------------------------
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 004fd68d7d..1b7cfeea7d 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, null, new ApiGatewayExecuteRouteContext(), null, 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, null, new ApiGatewayExecuteRouteContext(), null, 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, null, new ApiGatewayExecuteRouteContext(), null, 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, null, new ApiGatewayExecuteRouteContext(), null, 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/ApiGatewayProxyMatchTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java
index 1f2e363356..416c350128 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, null);
+ new ApiGatewayExecuteRouteContext(), null, 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/BuildV2AuthorizerEventTrailingSlashTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.java
index 3098c2e14b..6ff9718ae0 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);
+ , 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 6eba69ab89..6d1f6ee7c6 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);
+ , 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 225d7d826f..1d0f5a8ec0 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);
+ , 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 b4fce74583..0f67ed306c 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);
+ , 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 fc5669144f..a69497a8bb 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);
+ , 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 b86c85d7ee..fcd94d0374 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);
+ , 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/HttpApiAuthorizerPolicyTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/HttpApiAuthorizerPolicyTest.java
new file mode 100644
index 0000000000..e075df9120
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/HttpApiAuthorizerPolicyTest.java
@@ -0,0 +1,191 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
+import io.github.hectorvent.floci.services.apigatewayv2.AuthorizerPolicyFixtures;
+import io.github.hectorvent.floci.services.apigatewayv2.model.Api;
+import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
+import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;
+import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+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.vertx.http.runtime.CurrentVertxRequest;
+import io.vertx.core.http.HttpConnection;
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.web.RoutingContext;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriInfo;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+class HttpApiAuthorizerPolicyTest {
+
+ private ObjectMapper mapper;
+ private ApiGatewayV2Service gateway;
+ private LambdaService lambda;
+ private HttpHeaders headers;
+ private UriInfo uri;
+ private CurrentVertxRequest currentVertxRequest;
+ private SocketAddress remoteAddress;
+
+ @BeforeEach
+ void setUp() {
+ mapper = new ObjectMapper();
+ gateway = mock(ApiGatewayV2Service.class);
+ lambda = mock(LambdaService.class);
+ headers = mock(HttpHeaders.class);
+ uri = mock(UriInfo.class);
+ currentVertxRequest = mock(CurrentVertxRequest.class);
+ RoutingContext routingContext = mock(RoutingContext.class);
+ HttpServerRequest request = mock(HttpServerRequest.class);
+ HttpConnection connection = mock(HttpConnection.class);
+ remoteAddress = mock(SocketAddress.class);
+ when(currentVertxRequest.getCurrent()).thenReturn(routingContext);
+ when(routingContext.request()).thenReturn(request);
+ when(request.connection()).thenReturn(connection);
+ when(connection.remoteAddress()).thenReturn(remoteAddress);
+ when(remoteAddress.hostAddress()).thenReturn("127.0.0.1");
+ when(headers.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());
+ when(uri.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
+ when(uri.getRequestUri()).thenReturn(URI.create("http://localhost/execute-api/api/test/items"));
+ when(lambda.invoke(eq("us-east-1"), eq("backend"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenAnswer(invocation -> {
+ JsonNode event = mapper.readTree((byte[]) invocation.getArgument(2));
+ assertEquals(7, event.at("/requestContext/authorizer/lambda/tenant/id").asInt());
+ return result("{\"statusCode\":200,\"body\":\"allowed\"}");
+ });
+ }
+
+ static Stream<Arguments> httpPolicies() {
+ return Stream.of("1.0", "2.0").flatMap(version -> AuthorizerPolicyFixtures.policies().map(policy -> {
+ Object[] arguments = policy.get();
+ return Arguments.of(version, arguments[0], arguments[1], arguments[2]);
+ }));
+ }
+
+ @ParameterizedTest(name = "{0}: {1}")
+ @MethodSource("httpPolicies")
+ void evaluatesAllStatementsAgainstRequestArn(String version, String scenario, String statements, int expectedStatus) {
+ assertPolicy(version, statements, expectedStatus);
+ }
+
+ private void assertPolicy(String version, String statements, int expectedStatus) {
+ when(lambda.invoke(eq("us-east-1"), eq("authorizer"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenAnswer(invocation -> {
+ JsonNode event = mapper.readTree((byte[]) invocation.getArgument(2));
+ String arn = event.path("1.0".equals(version) ? "methodArn" : "routeArn").asText();
+ assertEquals("arn:aws:execute-api:us-east-1:000000000000:api/test/GET/items", arn);
+ String rendered = AuthorizerPolicyFixtures.renderStatements(statements, arn);
+ return result("{\"principalId\":\"user\",\"policyDocument\":{\"Version\":\"2012-10-17\","
+ + "\"Statement\":" + rendered + "},\"context\":{\"tenant\":{\"id\":7}}}");
+ });
+ ApiGatewayExecuteController controller = controller(version, false);
+ try (Response response = controller.handleGet(headers, uri, "api", "test", "items")) {
+ assertEquals(expectedStatus, response.getStatus(), "payload version " + version);
+ }
+ verify(lambda, times(expectedStatus == 200 ? 1 : 0))
+ .invoke(eq("us-east-1"), eq("backend"), any(byte[].class), eq(InvocationType.RequestResponse));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"203.0.113.42", "2001:db8::42"})
+ void sourceIpConditionsUseTransportAddress(String sourceIp) {
+ when(remoteAddress.hostAddress()).thenReturn(sourceIp);
+ when(headers.getHeaderString("X-Forwarded-For")).thenReturn("198.51.100.42");
+ String statements = "[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
+ + "{\"Effect\":\"Deny\",\"Action\":\"*\",\"Resource\":\"*\","
+ + "\"Condition\":{\"IpAddress\":{\"aws:SourceIp\":\"" + sourceIp + "\"}}}]";
+ assertPolicy("2.0", statements, 403);
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "1.0, 2001:db8::42, 403",
+ "2.0, 2001:db8::42, 403",
+ "1.0, 2001:db9::42, 200",
+ "2.0, 2001:db9::42, 200",
+ "2.0, 203.0.113.42, 200"
+ })
+ void ipv6CidrDenyOverridesAllow(String version, String sourceIp, int expectedStatus) {
+ when(remoteAddress.hostAddress()).thenReturn(sourceIp);
+ String statements = """
+ [{"Effect":"Allow","Action":"*","Resource":"*"},
+ {"Effect":"Deny","Action":"*","Resource":"*",
+ "Condition":{"IpAddress":{"aws:SourceIp":"2001:db8::/32"}}}]
+ """;
+ assertPolicy(version, statements, expectedStatus);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"https, 200", "http, 403"})
+ void secureTransportConditionUsesRequestScheme(String scheme, int expectedStatus) {
+ when(uri.getRequestUri()).thenReturn(URI.create(scheme + "://localhost/execute-api/api/test/items"));
+ String statements = """
+ [{"Effect":"Allow","Action":"*","Resource":"*",
+ "Condition":{"Bool":{"aws:SecureTransport":"true"}}}]
+ """;
+ assertPolicy("2.0", statements, expectedStatus);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void simpleResponsesUseIsAuthorized(boolean authorized) {
+ when(lambda.invoke(eq("us-east-1"), eq("authorizer"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(result("{\"isAuthorized\":" + authorized + ",\"context\":{\"tenant\":{\"id\":7}}}"));
+ try (Response response = controller("2.0", true).handleGet(headers, uri, "api", "test", "items")) {
+ assertEquals(authorized ? 200 : 403, response.getStatus());
+ }
+ verify(lambda, times(authorized ? 1 : 0))
+ .invoke(eq("us-east-1"), eq("backend"), any(byte[].class), eq(InvocationType.RequestResponse));
+ }
+
+ private ApiGatewayExecuteController controller(String version, boolean simpleResponses) {
+ Authorizer authorizer = new Authorizer();
+ authorizer.setAuthorizerType("REQUEST");
+ authorizer.setAuthorizerUri("arn:aws:lambda:us-east-1:000000000000:function:authorizer");
+ authorizer.setAuthorizerPayloadFormatVersion(version);
+ authorizer.setEnableSimpleResponses(simpleResponses);
+ Route route = new Route();
+ route.setRouteKey("GET /items");
+ route.setAuthorizationType("CUSTOM");
+ route.setAuthorizerId("auth");
+ route.setTarget("integrations/backend");
+ Integration integration = new Integration();
+ integration.setIntegrationType("AWS_PROXY");
+ integration.setIntegrationUri("arn:aws:lambda:us-east-1:000000000000:function:backend");
+ integration.setPayloadFormatVersion("2.0");
+ when(gateway.getApi("us-east-1", "api")).thenReturn(new Api());
+ when(gateway.findMatchingRoute("us-east-1", "api", "GET", "/items")).thenReturn(route);
+ when(gateway.getAuthorizer("us-east-1", "api", "auth")).thenReturn(authorizer);
+ when(gateway.getIntegration("us-east-1", "api", "backend")).thenReturn(integration);
+
+ ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext(currentVertxRequest);
+ routeContext.routeToHttpApi("us-east-1");
+ return new ApiGatewayExecuteController(null, null, gateway, lambda,
+ new RegionResolver("us-east-1", "000000000000"), mapper, null, null, null, null, null,
+ routeContext, null, null, null, null, new AuthorizerPolicyEvaluator(new IamPolicyEvaluator(mapper)));
+ }
+
+ private InvokeResult result(String payload) {
+ return new InvokeResult(200, null, payload.getBytes(StandardCharsets.UTF_8), null, "request");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java
index b89d72b43a..0bc6a398b1 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);
+ , 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 acd43815f7..ed3c599f5b 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
@@ -62,7 +62,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, null, new ApiGatewayExecuteRouteContext(), null, 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 bacf4b0bca..a906e3d3ab 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, null, new ApiGatewayExecuteRouteContext(), null, 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/RestLambdaAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizerTest.java
index 84f24cb991..45864e5675 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/RestLambdaAuthorizerTest.java
@@ -1,10 +1,14 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.apigatewayv2.AuthorizerPolicyFixtures;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.util.List;
@@ -22,7 +26,7 @@ class RestLambdaAuthorizerTest {
@BeforeEach
void createAuthorizer() {
when(clock.instant()).thenReturn(now);
- authorizer = new RestLambdaAuthorizer(mapper, new IamPolicyEvaluator(mapper), clock);
+ authorizer = new RestLambdaAuthorizer(mapper, new AuthorizerPolicyEvaluator(new IamPolicyEvaluator(mapper)), clock);
}
@Test
@@ -69,6 +73,22 @@ class RestLambdaAuthorizerTest {
assertFalse(authorizer.permits(result, "api/stage/GET/allowed/child", Map.of("aws:SourceIp", List.of("198.51.100.10"))));
}
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("io.github.hectorvent.floci.services.apigatewayv2.AuthorizerPolicyFixtures#policies")
+ void sharesPolicySemanticsWithHttpAndWebSocketApis(String scenario, String statements, int expectedStatus)
+ throws Exception {
+ String arn = "arn:aws:execute-api:us-east-1:000000000000:api/test/GET/items";
+ byte[] payload = ("{\"principalId\":\"user\",\"policyDocument\":{\"Version\":\"2012-10-17\",\"Statement\":"
+ + AuthorizerPolicyFixtures.renderStatements(statements, arn) + "}}").getBytes(StandardCharsets.UTF_8);
+ if (expectedStatus == 500) {
+ assertThrows(IllegalArgumentException.class, () -> authorizer.parse(payload));
+ return;
+ }
+ RestLambdaAuthorizer.Result result = authorizer.parse(payload);
+ assertEquals(expectedStatus == 200,
+ authorizer.permits(result, arn, AuthorizerPolicyEvaluator.requestConditions("127.0.0.1", false)));
+ }
+
@Test
void scalarContextRetainsTypesAndIsImmutable() throws Exception {
byte[] payload = mapper.writeValueAsBytes(Map.of("principalId", "principal", "context",
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/AuthorizerPolicyFixtures.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/AuthorizerPolicyFixtures.java
new file mode 100644
index 0000000000..051cf8dd07
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/AuthorizerPolicyFixtures.java
@@ -0,0 +1,97 @@
+package io.github.hectorvent.floci.services.apigatewayv2;
+
+import org.junit.jupiter.params.provider.Arguments;
+
+import java.util.Locale;
+import java.util.stream.Stream;
+
+public final class AuthorizerPolicyFixtures {
+
+ private AuthorizerPolicyFixtures() {}
+
+ public static String renderStatements(String statements, String arn) {
+ return statements.replace("${arn}", arn).replace("${upperArn}", arn.toUpperCase(Locale.ROOT))
+ .replace("${prefix}", arn.substring(0, arn.indexOf("/")));
+ }
+
+ public static Stream<Arguments> policies() {
+ String allow = statement("Allow", "execute-api:Invoke", "${arn}");
+ String deny = statement("Deny", "execute-api:Invoke", "${arn}");
+ String unrelatedAllow = statement("Allow", "execute-api:Invoke", "${arn}/other");
+ String unrelatedDeny = statement("Deny", "execute-api:Invoke", "${arn}/other");
+ String localAddresses = "[\"127.0.0.0/8\",\"::1/128\"]";
+ String otherAddress = "\"198.51.100.0/24\"";
+ return Stream.of(
+ Arguments.of("exact allow", "[" + allow + "]", 200),
+ Arguments.of("implicit deny", "[" + unrelatedAllow + "]", 403),
+ Arguments.of("wrong action", "[" + statement("Allow", "s3:GetObject", "*") + "]", 403),
+ Arguments.of("later deny", "[" + allow + "," + deny + "]", 403),
+ Arguments.of("earlier deny", "[" + deny + "," + allow + "]", 403),
+ Arguments.of("unrelated deny", "[" + unrelatedDeny + "," + allow + "]", 200),
+ Arguments.of("later allow", "[" + unrelatedAllow + "," + allow + "]", 200),
+ Arguments.of("singleton statement", allow, 200),
+ Arguments.of("wildcard", "[" + statement("Allow", "execute-api:*", "${prefix}/*") + "]", 200),
+ Arguments.of("action and resource lists", "[{\"Effect\":\"Allow\","
+ + "\"Action\":[\"s3:GetObject\",\"EXECUTE-API:Invoke\"],"
+ + "\"Resource\":[\"${arn}/other\",\"${arn}\"]}]", 200),
+ Arguments.of("case sensitive resource", "[" + statement("Allow", "execute-api:Invoke", "${upperArn}") + "]", 403),
+ Arguments.of("missing action", "[{\"Effect\":\"Allow\",\"Resource\":\"*\"}]", 500),
+ Arguments.of("missing resource", "[{\"Effect\":\"Allow\",\"Action\":\"execute-api:Invoke\"}]", 500),
+ Arguments.of("malformed later statement", "[" + allow + ",{}]", 500),
+ Arguments.of("invalid effect", "[{\"Effect\":\"Other\",\"Action\":\"*\",\"Resource\":\"*\"}]", 500),
+ Arguments.of("empty statements", "[]", 500),
+ Arguments.of("missing effect", "[{\"Action\":\"*\",\"Resource\":\"*\"}]", 500),
+ Arguments.of("both action fields", "[{\"Effect\":\"Allow\",\"Action\":\"*\","
+ + "\"NotAction\":\"s3:*\",\"Resource\":\"*\"}]", 500),
+ Arguments.of("negated action", "[{\"Effect\":\"Allow\",\"NotAction\":\"s3:*\",\"Resource\":\"${arn}\"}]", 200),
+ Arguments.of("negated resource excludes request", "[{\"Effect\":\"Allow\","
+ + "\"Action\":\"execute-api:Invoke\",\"NotResource\":\"${arn}\"}]", 403),
+ Arguments.of("invalid action list", "[{\"Effect\":\"Allow\",\"Action\":[\"*\",1],\"Resource\":\"*\"}]", 500),
+ Arguments.of("matching source IP deny", "[" + allow + ","
+ + ipStatement("Deny", "IpAddress", localAddresses) + "]", 403),
+ Arguments.of("nonmatching source IP deny", "[" + allow + ","
+ + ipStatement("Deny", "IpAddress", otherAddress) + "]", 200),
+ Arguments.of("matching source IP allow", "[" + ipStatement("Allow", "IpAddress", localAddresses) + "]", 200),
+ Arguments.of("nonmatching source IP allow", "[" + ipStatement("Allow", "IpAddress", otherAddress) + "]", 403),
+ Arguments.of("negated source IP deny", "[" + allow + ","
+ + ipStatement("Deny", "NotIpAddress", otherAddress) + "]", 403),
+ Arguments.of("empty condition is unconditional", "[{\"Effect\":\"Allow\",\"Action\":\"*\","
+ + "\"Resource\":\"*\",\"Condition\":{}}]", 200),
+ Arguments.of("empty later condition denies", "[" + allow + ",{\"Effect\":\"Deny\",\"Action\":\"*\","
+ + "\"Resource\":\"*\",\"Condition\":{}}]", 403),
+ Arguments.of("insecure transport deny", "[" + allow + ","
+ + conditionStatement("Deny", "Bool", "aws:SecureTransport", "\"false\"") + "]", 403),
+ Arguments.of("secure transport allow", "["
+ + conditionStatement("Allow", "Bool", "aws:SecureTransport", "\"true\"") + "]", 403),
+ Arguments.of("current time allow", "["
+ + conditionStatement("Allow", "DateGreaterThan", "aws:CurrentTime", "\"2000-01-01T00:00:00Z\"") + "]", 200),
+ Arguments.of("invalid condition", "[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\",\"Condition\":true}]", 500),
+ Arguments.of("condition operator without keys", "[{\"Effect\":\"Allow\",\"Action\":\"*\","
+ + "\"Resource\":\"*\",\"Condition\":{\"StringEquals\":\"invalid\"}}]", 500),
+ Arguments.of("condition operator with empty keys", "[{\"Effect\":\"Allow\",\"Action\":\"*\","
+ + "\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{}}}]", 500),
+ Arguments.of("unknown condition operator deny", "[" + allow + ","
+ + conditionStatement("Deny", "IpAddres", "aws:SourceIp", localAddresses) + "]", 500),
+ Arguments.of("empty condition values deny", "[" + allow + ","
+ + ipStatement("Deny", "NotIpAddress", "[]") + "]", 500),
+ Arguments.of("object condition value", "["
+ + ipStatement("Allow", "IpAddress", "{\"cidr\":\"127.0.0.0/8\"}") + "]", 500),
+ Arguments.of("if exists operator", "["
+ + conditionStatement("Allow", "StringEqualsIfExists", "aws:Unset", "\"x\"") + "]", 200),
+ Arguments.of("boolean condition value", "[" + allow + ","
+ + conditionStatement("Deny", "Bool", "aws:SecureTransport", "false") + "]", 403));
+ }
+
+ private static String statement(String effect, String action, String resource) {
+ return "{\"Effect\":\"" + effect + "\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
+ }
+
+ private static String ipStatement(String effect, String operator, String addresses) {
+ return conditionStatement(effect, operator, "aws:SourceIp", addresses);
+ }
+
+ private static String conditionStatement(String effect, String operator, String key, String values) {
+ return "{\"Effect\":\"" + effect + "\",\"Action\":\"execute-api:Invoke\",\"Resource\":\"${arn}\","
+ + "\"Condition\":{\"" + operator + "\":{\"" + key + "\":" + values + "}}}";
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/LambdaAuthorizerPolicyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/LambdaAuthorizerPolicyIntegrationTest.java
new file mode 100644
index 0000000000..07e3c94f99
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/LambdaAuthorizerPolicyIntegrationTest.java
@@ -0,0 +1,139 @@
+package io.github.hectorvent.floci.services.apigatewayv2;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
+import io.quarkus.test.InjectMock;
+import io.quarkus.test.common.http.TestHTTPResource;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.WebSocket;
+import java.net.http.WebSocketHandshakeException;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+@QuarkusTest
+class LambdaAuthorizerPolicyIntegrationTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String AUTHORIZER_FUNCTION = "policy-authorizer";
+ private static final String BACKEND_FUNCTION = "policy-backend";
+
+ @InjectMock
+ LambdaService lambdaService;
+
+ @TestHTTPResource("/")
+ URI baseUri;
+
+ private String apiId;
+
+ @AfterEach
+ void deleteApi() {
+ if (apiId != null) {
+ given().delete("/v2/apis/" + apiId).then().statusCode(204);
+ }
+ }
+
+ @ParameterizedTest(name = "HTTP: {0}")
+ @MethodSource("io.github.hectorvent.floci.services.apigatewayv2.AuthorizerPolicyFixtures#policies")
+ void httpRequestsEnforceAuthorizerPolicies(String scenario, String statements, int expectedStatus) {
+ configureApi("HTTP");
+ stubAuthorizer(statements);
+ when(lambdaService.invoke(eq("us-east-1"), eq(BACKEND_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(result("{\"statusCode\":200,\"body\":\"allowed\"}"));
+ given().header("X-Forwarded-For", "198.51.100.42")
+ .get("/execute-api/" + apiId + "/test/items").then().statusCode(expectedStatus);
+ verify(lambdaService, times(expectedStatus == 200 ? 1 : 0))
+ .invoke(eq("us-east-1"), eq(BACKEND_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
+ }
+
+ @ParameterizedTest(name = "WebSocket: {0}")
+ @MethodSource("io.github.hectorvent.floci.services.apigatewayv2.AuthorizerPolicyFixtures#policies")
+ void webSocketHandshakeEnforcesAuthorizerPolicies(String scenario, String statements, int expectedStatus) throws Exception {
+ configureApi("WEBSOCKET");
+ stubAuthorizer(statements);
+ URI uri = URI.create(WebSocketTestSupport.buildWsUrl(baseUri, apiId, "test"));
+ try (HttpClient client = HttpClient.newHttpClient()) {
+ CompletableFuture<WebSocket> handshakeFuture = client.newWebSocketBuilder()
+ .header("X-Forwarded-For", "198.51.100.42")
+ .buildAsync(uri, new WebSocket.Listener() {});
+ try {
+ assertHandshake(handshakeFuture, expectedStatus);
+ } finally {
+ if (handshakeFuture.isDone() && !handshakeFuture.isCompletedExceptionally()) {
+ handshakeFuture.join().abort();
+ } else {
+ handshakeFuture.cancel(true);
+ }
+ }
+ }
+ }
+
+ private void assertHandshake(CompletableFuture<WebSocket> handshakeFuture, int expectedStatus) throws Exception {
+ if (expectedStatus == 200) {
+ WebSocket socket = handshakeFuture.get(10, TimeUnit.SECONDS);
+ socket.sendClose(WebSocket.NORMAL_CLOSURE, "done").get(10, TimeUnit.SECONDS);
+ return;
+ }
+ ExecutionException exception = assertThrows(ExecutionException.class,
+ () -> handshakeFuture.get(10, TimeUnit.SECONDS));
+ WebSocketHandshakeException handshake = assertInstanceOf(WebSocketHandshakeException.class, exception.getCause());
+ assertEquals(expectedStatus, handshake.getResponse().statusCode());
+ }
+
+ private void configureApi(String protocol) {
+ apiId = given().contentType(ContentType.JSON)
+ .body(Map.of("name", "policy-evaluation", "protocolType", protocol,
+ "routeSelectionExpression", "$request.body.action"))
+ .post("/v2/apis").then().statusCode(201).extract().path("apiId");
+ String apiPath = "/v2/apis/" + apiId;
+ given().contentType(ContentType.JSON).body(Map.of("stageName", "test"))
+ .post(apiPath + "/stages").then().statusCode(201);
+ String authorizerId = given().contentType(ContentType.JSON)
+ .body(Map.of("name", "policy", "authorizerType", "REQUEST", "authorizerPayloadFormatVersion", "2.0",
+ "authorizerUri", "arn:aws:lambda:us-east-1:000000000000:function:" + AUTHORIZER_FUNCTION))
+ .post(apiPath + "/authorizers").then().statusCode(201).extract().path("authorizerId");
+ boolean webSocket = "WEBSOCKET".equals(protocol);
+ Map<String, String> integration = webSocket ? Map.of("integrationType", "MOCK")
+ : Map.of("integrationType", "AWS_PROXY", "payloadFormatVersion", "2.0",
+ "integrationUri", "arn:aws:lambda:us-east-1:000000000000:function:" + BACKEND_FUNCTION);
+ String integrationId = given().contentType(ContentType.JSON).body(integration)
+ .post(apiPath + "/integrations").then().statusCode(201).extract().path("integrationId");
+ given().contentType(ContentType.JSON)
+ .body(Map.of("routeKey", webSocket ? "$connect" : "GET /items", "authorizationType", "CUSTOM",
+ "authorizerId", authorizerId, "target", "integrations/" + integrationId))
+ .post(apiPath + "/routes").then().statusCode(201);
+ }
+
+ private void stubAuthorizer(String statements) {
+ when(lambdaService.invoke(eq("us-east-1"), eq(AUTHORIZER_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenAnswer(invocation -> {
+ JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
+ String arn = event.has("routeArn") ? event.path("routeArn").asText() : event.path("methodArn").asText();
+ String suffix = event.has("routeArn") ? "/GET/items" : "/$connect";
+ assertEquals("arn:aws:execute-api:us-east-1:000000000000:" + apiId + "/test" + suffix, arn);
+ return result("{\"principalId\":\"user\",\"policyDocument\":{\"Version\":\"2012-10-17\",\"Statement\":"
+ + AuthorizerPolicyFixtures.renderStatements(statements, arn) + "}}");
+ });
+ }
+
+ private InvokeResult result(String payload) {
+ return new InvokeResult(200, null, payload.getBytes(StandardCharsets.UTF_8), null, "request");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketAuthorizerPolicyTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketAuthorizerPolicyTest.java
new file mode 100644
index 0000000000..9507340584
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketAuthorizerPolicyTest.java
@@ -0,0 +1,106 @@
+package io.github.hectorvent.floci.services.apigatewayv2.websocket;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.apigateway.AuthorizerPolicyEvaluator;
+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
+import io.github.hectorvent.floci.services.apigatewayv2.AuthorizerPolicyFixtures;
+import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+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 org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+class WebSocketAuthorizerPolicyTest {
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("io.github.hectorvent.floci.services.apigatewayv2.AuthorizerPolicyFixtures#policies")
+ void evaluatesAllStatementsAgainstConnectArn(String scenario, String statements, int expectedStatus) throws Exception {
+ assertPolicy(statements, expectedStatus, "127.0.0.1");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"203.0.113.42", "2001:db8::42"})
+ void sourceIpConditionsUseConnectionAddress(String sourceIp) throws Exception {
+ String statements = "[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
+ + "{\"Effect\":\"Deny\",\"Action\":\"*\",\"Resource\":\"*\","
+ + "\"Condition\":{\"IpAddress\":{\"aws:SourceIp\":\"" + sourceIp + "\"}}}]";
+ assertPolicy(statements, 403, sourceIp);
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "2001:db8::42, 403",
+ "2001:db9::42, 200",
+ "203.0.113.42, 200"
+ })
+ void ipv6CidrDenyOverridesAllow(String sourceIp, int expectedStatus) throws Exception {
+ String statements = """
+ [{"Effect":"Allow","Action":"*","Resource":"*"},
+ {"Effect":"Deny","Action":"*","Resource":"*",
+ "Condition":{"IpAddress":{"aws:SourceIp":"2001:db8::/32"}}}]
+ """;
+ assertPolicy(statements, expectedStatus, sourceIp);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"true, 200", "false, 403"})
+ void secureTransportConditionUsesHandshakeScheme(boolean secureTransport, int expectedStatus) throws Exception {
+ String statements = """
+ [{"Effect":"Allow","Action":"*","Resource":"*",
+ "Condition":{"Bool":{"aws:SecureTransport":"true"}}}]
+ """;
+ assertPolicy(statements, expectedStatus, "127.0.0.1", secureTransport);
+ }
+
+ private void assertPolicy(String statements, int expectedStatus, String sourceIp) throws Exception {
+ assertPolicy(statements, expectedStatus, sourceIp, false);
+ }
+
+ private void assertPolicy(String statements, int expectedStatus, String sourceIp, boolean secureTransport)
+ throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ ApiGatewayV2Service gateway = mock(ApiGatewayV2Service.class);
+ LambdaService lambda = mock(LambdaService.class);
+ Authorizer authorizer = new Authorizer();
+ authorizer.setAuthorizerType("REQUEST");
+ authorizer.setAuthorizerUri("arn:aws:lambda:us-east-1:000000000000:function:authorizer");
+ when(gateway.getAuthorizer("us-east-1", "api", "auth")).thenReturn(authorizer);
+ WebSocketProxyEventBuilder builder = new WebSocketProxyEventBuilder();
+ builder.objectMapper = mapper;
+ builder.regionResolver = new RegionResolver("us-east-1", "000000000000");
+ when(lambda.invoke(eq("us-east-1"), eq("authorizer"), any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenAnswer(invocation -> {
+ JsonNode event = mapper.readTree((byte[]) invocation.getArgument(2));
+ String arn = event.path("methodArn").asText();
+ assertEquals("arn:aws:execute-api:us-east-1:000000000000:api/test/$connect", arn);
+ String rendered = AuthorizerPolicyFixtures.renderStatements(statements, arn);
+ String payload = "{\"principalId\":\"user\",\"policyDocument\":{\"Version\":\"2012-10-17\","
+ + "\"Statement\":" + rendered + "},\"context\":{\"tenant\":7}}";
+ return new InvokeResult(200, null, payload.getBytes(StandardCharsets.UTF_8), null, "request");
+ });
+ WebSocketAuthorizerService service = new WebSocketAuthorizerService(gateway, lambda, builder, mapper,
+ new AuthorizerPolicyEvaluator(new IamPolicyEvaluator(mapper)));
+ WebSocketAuthorizerService.AuthorizerResult result = service.invokeAndEvaluate("us-east-1", "api", "test", "auth",
+ "connection", 0, Map.of(), Map.of(), sourceIp, secureTransport, "agent", Map.of());
+ assertEquals(expectedStatus, result.statusCode());
+ assertEquals(expectedStatus == 200, result.allowed());
+ if (result.allowed()) {
+ assertEquals(Map.of("tenant", 7), result.context());
+ } else {
+ assertNull(result.context());
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.java
index 90c15fa4ea..3543385418 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.java
@@ -46,6 +46,41 @@ class IamPolicyConditionMatchingTest {
assertEquals(expected, decision(operator, List.of(pattern), List.of(value)));
}
+ @ParameterizedTest
+ @CsvSource({
+ "203.0.113.0/24, 203.0.113.42, ALLOW",
+ "203.0.113.0/24, 203.0.114.42, DENY",
+ "203.0.113.129/25, 203.0.113.255, ALLOW",
+ "203.0.113.129/25, 203.0.113.127, DENY",
+ "0.0.0.0/0, 203.0.113.42, ALLOW",
+ "203.0.113.42/32, 203.0.113.42, ALLOW",
+ "203.0.113.42/32, 203.0.113.43, DENY",
+ "2001:db8::/32, 2001:db8::42, ALLOW",
+ "2001:db8::/32, 2001:db9::42, DENY",
+ "2001:db8::1234/33, 2001:db8:7fff::42, ALLOW",
+ "2001:db8::1234/33, 2001:db8:8000::42, DENY",
+ "::/0, 2001:db8::42, ALLOW",
+ "2001:db8::42/128, 2001:0db8:0:0:0:0:0:0042, ALLOW",
+ "2001:db8::42/128, 2001:db8::43, DENY",
+ "2001:db8::42/127, 2001:db8::43, ALLOW",
+ "2001:db8::42/127, 2001:db8::44, DENY",
+ "::/0, 203.0.113.42, DENY",
+ "0.0.0.0/0, 2001:db8::42, DENY",
+ "2001:db8::/129, 2001:db8::42, DENY",
+ "2001:db8::/-1, 2001:db8::42, DENY",
+ "203.0.113.0/33, 203.0.113.42, DENY",
+ "203.0.113.0/-1, 203.0.113.42, DENY",
+ "999.0.0.0/0, 203.0.113.42, DENY",
+ "example.com/0, 203.0.113.42, DENY",
+ "2001:db8::/32/extra, 2001:db8::42, DENY",
+ "2001:db8::/32, invalid, DENY"
+ })
+ void ipConditionsMatchAddressFamilyAndPrefix(String range, String sourceIp, Decision expected) {
+ assertEquals(expected, decision("IpAddress", List.of(range), List.of(sourceIp)));
+ Decision negated = expected == Decision.ALLOW ? Decision.DENY : Decision.ALLOW;
+ assertEquals(negated, decision("NotIpAddress", List.of(range), List.of(sourceIp)));
+ }
+
@Test
void setOperatorsRemainCaseSensitive() {
assertEquals(Decision.DENY, decision("ForAllValues:StringLike",
@@ -72,16 +107,17 @@ class IamPolicyConditionMatchingTest {
}
private Decision decision(String operator, List<String> patterns, List<String> values) {
+ String conditionKey = operator.endsWith("IpAddress") ? "aws:SourceIp" : "aws:SourceArn";
String policy;
try {
policy = new ObjectMapper().writeValueAsString(Map.of(
"Version", "2012-10-17",
"Statement", List.of(Map.of("Effect", "Allow", "Action", "s3:GetObject", "Resource", "*",
- "Condition", Map.of(operator, Map.of("aws:SourceArn", patterns))))));
+ "Condition", Map.of(operator, Map.of(conditionKey, patterns))))));
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
return evaluator.simulateCustomPolicy(List.of(policy), "s3:GetObject", "*",
- Map.of("aws:SourceArn", values));
+ Map.of(conditionKey, values));
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java
index 86142052e0..f07fe8a1bf 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java
@@ -54,6 +54,16 @@ class IamPolicyEvaluatorTest {
});
}
+ @Test
+ void supportedConditionOperatorsIncludeQuantifiersAndIfExists() {
+ assertTrue(IamPolicyEvaluator.isSupportedConditionOperator("IpAddress"));
+ assertTrue(IamPolicyEvaluator.isSupportedConditionOperator("ForAnyValue:StringLikeIfExists"));
+ assertTrue(IamPolicyEvaluator.isSupportedConditionOperator("Null"));
+ assertFalse(IamPolicyEvaluator.isSupportedConditionOperator("NullIfExists"));
+ assertFalse(IamPolicyEvaluator.isSupportedConditionOperator("IpAddres"));
+ assertFalse(IamPolicyEvaluator.isSupportedConditionOperator("forallvalues:StringEquals"));
+ }
+
@Test
void wildcardMatchesLiteralAsteriskInValue() {
assertTrue(IamPolicyEvaluator.caseSensitiveGlobMatches("a*", "a*b"));