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

@@ -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);
@@ -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) {
@@ -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 {
@@ -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}")
@@ -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
@@ -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
@@ -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
@@ -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 {
@@ -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");
}
}
@@ -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) {
@@ -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
@@ -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 {
@@ -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",
@@ -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 + "}}}";
}
}
@@ -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");
}
}
@@ -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());
}
}
}
@@ -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));
}
}
@@ -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"));