mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(apigateway): validate and cache REST Lambda authorizers (#5002)
* fix: evaluate and cache REST Lambda authorizer policies * fix: share REST request context and complete parameter mappings * fix: prevent stale REST authorizer caching after stage flush * fix: use valid authorizer policies in REST import tests * chore: align API Gateway imports with repository style * fix(apigateway): isolate authorizer contracts and validate cached identities * chore(apigateway): align restored context code with style guide * chore: order API Gateway SDK test imports
This commit is contained in:
1 parent
6568700e02
commit
ae3adfe992
23 files changed
+1013
-85
No files matched your search
+4
-4
@@ -37,7 +37,7 @@ class ApiGatewayExecuteControllerTest {
|
||||
return new ApiGatewayExecuteController(
|
||||
null, null, null, null,
|
||||
regionResolver, objectMapper, null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -352,7 +352,7 @@ class ApiGatewayExecuteControllerTest {
|
||||
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
|
||||
apiGatewayService, null, apiGatewayV2Service, null,
|
||||
regionResolver, new ObjectMapper(), null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
|
||||
|
||||
Response response = controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);
|
||||
|
||||
@@ -382,7 +382,7 @@ class ApiGatewayExecuteControllerTest {
|
||||
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
|
||||
apiGatewayService, null, apiGatewayV2Service, null,
|
||||
regionResolver, new ObjectMapper(), null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
|
||||
|
||||
controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);
|
||||
|
||||
@@ -416,7 +416,7 @@ class ApiGatewayExecuteControllerTest {
|
||||
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
|
||||
apiGatewayService, null, apiGatewayV2Service, null,
|
||||
regionResolver, new ObjectMapper(), null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
|
||||
|
||||
controller.dispatch("GET", "restapi1", "prod", "hello", headers, null, null);
|
||||
|
||||
|
||||
+8
-10
@@ -10,7 +10,6 @@ import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
@@ -34,6 +33,7 @@ import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@QuarkusTest
|
||||
@@ -223,6 +223,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
|
||||
assertNotEquals(previousRequestId, requestId);
|
||||
previousRequestId = requestId;
|
||||
}
|
||||
verify(lambdaService).invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -231,13 +232,10 @@ class ApiGatewayHttpContextMappingIntegrationTest {
|
||||
configureAuthorizer(0);
|
||||
configureIntegration(type, "GET");
|
||||
deploy();
|
||||
for (String token : List.of("", "Bearer forged")) {
|
||||
RequestSpecification request = given().header("X-User-Claims", "forged");
|
||||
if (!token.isEmpty()) {
|
||||
request.header("Authorization", token);
|
||||
}
|
||||
request.get("/execute-api/" + apiId + "/test/orders/42").then().statusCode(403);
|
||||
}
|
||||
given().header("X-User-Claims", "forged")
|
||||
.get("/execute-api/" + apiId + "/test/orders/42").then().statusCode(401);
|
||||
given().header("X-User-Claims", "forged").header("Authorization", "Bearer forged")
|
||||
.get("/execute-api/" + apiId + "/test/orders/42").then().statusCode(403);
|
||||
assertEquals(0, backendRequests.get());
|
||||
}
|
||||
|
||||
@@ -277,7 +275,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
|
||||
|
||||
private void configureAuthorizer(int ttl) throws Exception {
|
||||
configureAuthorizer(ttl, Map.of("userClaims", "verified-claims", "principalId", "forged-principal",
|
||||
"numberKey", 123, "booleanKey", true, "objectKey", Map.of("nested", "value")));
|
||||
"numberKey", 123, "booleanKey", true));
|
||||
}
|
||||
|
||||
private void configureAuthorizer(int ttl, Map<String, Object> context) throws Exception {
|
||||
@@ -308,7 +306,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
|
||||
parameters.put("integration.request.header.X-Number", "context.authorizer.numberKey");
|
||||
parameters.put("integration.request.header.X-Boolean", "context.authorizer.booleanKey");
|
||||
parameters.put("integration.request.header.X-Missing", "context.authorizer.missing");
|
||||
parameters.put("integration.request.header.X-Object", "context.authorizer.objectKey");
|
||||
parameters.put("integration.request.header.X-Object", "context.identity");
|
||||
parameters.put("integration.request.header.X-Request-Id", "context.requestId");
|
||||
parameters.put("integration.request.header.X-Context-Stage", "context.stage");
|
||||
parameters.put("integration.request.header.X-Context-Path", "context.path");
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ class ApiGatewayProxyMatchTest {
|
||||
ctrl = new ApiGatewayExecuteController(apiGatewayService, null, apiGatewayV2Service, lambdaService,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service, null,
|
||||
new ApiGatewayExecuteRouteContext(), null, null, null);
|
||||
new ApiGatewayExecuteRouteContext(), null, null, null, null);
|
||||
}
|
||||
|
||||
private ApiGatewayResource resource(String id, String parentId, String pathPart, String path) {
|
||||
|
||||
+6
-2
@@ -211,10 +211,14 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {
|
||||
}
|
||||
""";
|
||||
private static final byte[] DENY_POLICY = """
|
||||
{"principalId":"blocked","policyDocument":{"Statement":[{"Effect":"Deny"}]}}
|
||||
{"principalId":"blocked","policyDocument":{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Deny","Action":"execute-api:Invoke","Resource":"*"}
|
||||
]}}
|
||||
""".getBytes(StandardCharsets.UTF_8);
|
||||
private static final byte[] ALLOW_POLICY = """
|
||||
{"principalId":"allowed","policyDocument":{"Statement":[{"Effect":"Allow"}]}}
|
||||
{"principalId":"allowed","policyDocument":{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"execute-api:Invoke","Resource":"*"}
|
||||
]}}
|
||||
""".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
@InjectMock
|
||||
|
||||
+1
-1
@@ -99,7 +99,7 @@ class ApiGatewayRootResourceLookupTest {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
ApiGatewayController controller = new ApiGatewayController(mockedService,
|
||||
mock(ApiGatewayV2Service.class), mock(ApiGatewayV2OpenApiImporter.class),
|
||||
regionResolver, objectMapper);
|
||||
regionResolver, objectMapper, null);
|
||||
|
||||
Response response = controller.getRestApis(headers);
|
||||
JsonNode body = objectMapper.readTree((String) response.getEntity());
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ class BuildV2AuthorizerEventTrailingSlashTest {
|
||||
regionResolver, new ObjectMapper(), null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
|
||||
null, null
|
||||
);
|
||||
, null);
|
||||
}
|
||||
|
||||
private JsonNode buildEvent(String normalizedPath, String rawRequestUri) throws Exception {
|
||||
|
||||
+1
-1
@@ -51,7 +51,7 @@ class BuildV2ProxyEventBodyEncodingTest {
|
||||
null, null, null, null,
|
||||
regionResolver, objectMapper, null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
|
||||
);
|
||||
, null);
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ class BuildV2ProxyEventJwtClaimsTest {
|
||||
null, null, null, null,
|
||||
regionResolver, new ObjectMapper(), null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
|
||||
);
|
||||
, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -51,7 +51,7 @@ class BuildV2ProxyEventLambdaAuthorizerTest {
|
||||
null, null, null, null,
|
||||
regionResolver, MAPPER, null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
|
||||
);
|
||||
, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ class BuildV2ProxyEventPathParametersTest {
|
||||
null, null, null, null,
|
||||
regionResolver, new ObjectMapper(), null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
|
||||
);
|
||||
, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ class BuildV2ProxyEventTrailingSlashTest {
|
||||
regionResolver, new ObjectMapper(), null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
|
||||
null, null
|
||||
);
|
||||
, null);
|
||||
}
|
||||
|
||||
private JsonNode buildEvent(String normalizedPath, String rawRequestUri, String routeKey) throws Exception {
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ class JwtClaimsWireFormatTest {
|
||||
null, new ObjectMapper(), null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
|
||||
null, null
|
||||
);
|
||||
, null);
|
||||
}
|
||||
|
||||
private static String unsignedToken(String claimsJson) {
|
||||
|
||||
+1
-1
@@ -60,7 +60,7 @@ class ProxyEventIamIdentityTest {
|
||||
controller = new ApiGatewayExecuteController(
|
||||
null, null, null, null,
|
||||
regionResolver, MAPPER, null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ class ProxyEventPathParametersTest {
|
||||
controller = new ApiGatewayExecuteController(
|
||||
null, null, null, null,
|
||||
regionResolver, MAPPER, null,
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
|
||||
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null);
|
||||
}
|
||||
|
||||
private JsonNode pathParametersFor(String path, String resourcePath) throws Exception {
|
||||
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@QuarkusTest
|
||||
class RestLambdaAuthorizerIntegrationTest {
|
||||
private static final String FUNCTION = "rest-contract-authorizer";
|
||||
private static final String AUTHORIZER_URI = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
|
||||
+ "arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION + "/invocations";
|
||||
|
||||
@InjectMock
|
||||
LambdaService lambdaService;
|
||||
|
||||
private String apiId;
|
||||
private String authorizerId;
|
||||
|
||||
@BeforeEach
|
||||
void createApi() {
|
||||
apiId = given().contentType(ContentType.JSON).body(Map.of("name", "rest-authorizer-contract"))
|
||||
.post("/restapis").then().statusCode(201).extract().path("id");
|
||||
String rootId = given().get("/restapis/" + apiId + "/resources")
|
||||
.then().statusCode(200).extract().path("item[0].id");
|
||||
for (String path : List.of("allowed", "other")) {
|
||||
String resourceId = given().contentType(ContentType.JSON).body(Map.of("pathPart", path))
|
||||
.post("/restapis/" + apiId + "/resources/" + rootId)
|
||||
.then().statusCode(201).extract().path("id");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteApi() {
|
||||
given().delete("/restapis/" + apiId).then().statusCode(202);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"resource", "action", "laterDeny", "firstUnmatched"})
|
||||
void evaluatesEveryStatementAgainstRequestedActionAndResource(String scenario) throws Exception {
|
||||
configure("TOKEN", 0, "method.request.header.Authorization");
|
||||
Map<String, String> allow = statement("Allow", "execute-api:Invoke", "*");
|
||||
List<Map<String, String>> statements = switch (scenario) {
|
||||
case "resource" -> List.of(statement("Allow", "execute-api:Invoke", methodArn("other")));
|
||||
case "action" -> List.of(statement("Allow", "execute-api:ManageConnections", "*"));
|
||||
case "laterDeny" -> List.of(allow, statement("Deny", "execute-api:Invoke", methodArn("allowed")));
|
||||
default -> List.of(statement("Deny", "execute-api:Invoke", methodArn("other")), allow);
|
||||
};
|
||||
respond(Map.of("principalId", "verified", "policyDocument", policy(statements)));
|
||||
given().header("Authorization", "token").get(execute("allowed"))
|
||||
.then().statusCode("firstUnmatched".equals(scenario) ? 200 : 403);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"principal", "object", "array", "null", "policy"})
|
||||
void invalidOutputFailsBeforeIntegration(String scenario) throws Exception {
|
||||
configure("TOKEN", 0, "method.request.header.Authorization");
|
||||
Map<String, Object> output = new LinkedHashMap<>();
|
||||
output.put("principalId", "verified");
|
||||
output.put("policyDocument", policy(List.of(statement("Allow", "execute-api:Invoke", "*"))));
|
||||
switch (scenario) {
|
||||
case "principal" -> output.remove("principalId");
|
||||
case "object" -> output.put("context", Map.of("claims", Map.of("nested", "value")));
|
||||
case "array" -> output.put("context", Map.of("claims", List.of("value")));
|
||||
case "null" -> output.put("context", Collections.singletonMap("claims", null));
|
||||
default -> output.put("policyDocument", Map.of("Statement", List.of(Map.of("Effect", "Allow"))));
|
||||
}
|
||||
respond(output);
|
||||
given().header("Authorization", "token").get(execute("allowed")).then().statusCode(500);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"default,missing", "300,missing", "300,empty", "300,blank"})
|
||||
void cachedRequestAuthorizerRequiresIdentitySourceAtCreation(String ttl, String source) {
|
||||
Map<String, Object> request = new LinkedHashMap<>();
|
||||
request.put("name", "invalid-request-authorizer");
|
||||
request.put("type", "REQUEST");
|
||||
request.put("authorizerUri", AUTHORIZER_URI);
|
||||
if (!"default".equals(ttl)) {
|
||||
request.put("authorizerResultTtlInSeconds", Integer.parseInt(ttl));
|
||||
}
|
||||
if (!"missing".equals(source)) {
|
||||
request.put("identitySource", "blank".equals(source) ? " " : "");
|
||||
}
|
||||
given().contentType(ContentType.JSON).body(request)
|
||||
.post("/restapis/" + apiId + "/authorizers").then().statusCode(400);
|
||||
given().get("/restapis/" + apiId + "/authorizers")
|
||||
.then().statusCode(200).body("item.size()", equalTo(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void uncachedRequestAuthorizerCanOmitIdentitySource() throws Exception {
|
||||
configure("REQUEST", 0, null);
|
||||
allowAll();
|
||||
given().get(execute("allowed")).then().statusCode(200);
|
||||
verifyInvocation(1);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"300,method.request.header.Authorization,/identitySource, ",
|
||||
"0,,/authorizerResultTtlInSeconds,300"})
|
||||
void invalidRequestAuthorizerUpdateLeavesConfigurationUnchanged(int ttl, String source, String path, String value) {
|
||||
configure("REQUEST", ttl, source);
|
||||
given().contentType(ContentType.JSON).body(Map.of("patchOperations", List.of(
|
||||
Map.of("op", "replace", "path", "/name", "value", "changed"),
|
||||
Map.of("op", "replace", "path", path, "value", value != null ? value : ""))))
|
||||
.patch("/restapis/" + apiId + "/authorizers/" + authorizerId).then().statusCode(400);
|
||||
given().get("/restapis/" + apiId + "/authorizers/" + authorizerId).then().statusCode(200)
|
||||
.body("name", equalTo("contract"), "authorizerResultTtlInSeconds", equalTo(ttl));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestAuthorizerCanEnableCachingAndIdentitySourceInOnePatch() {
|
||||
configure("REQUEST", 0, null);
|
||||
given().contentType(ContentType.JSON).body(Map.of("patchOperations", List.of(
|
||||
Map.of("op", "replace", "path", "/authorizerResultTtlInSeconds", "value", "300"),
|
||||
Map.of("op", "replace", "path", "/identitySource", "value", "method.request.header.Authorization"))))
|
||||
.patch("/restapis/" + apiId + "/authorizers/" + authorizerId).then().statusCode(200)
|
||||
.body("authorizerResultTtlInSeconds", equalTo(300),
|
||||
"identitySource", equalTo("method.request.header.Authorization"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cachedHyphenatedContextReachesLambdaProxy() throws Exception {
|
||||
configure("TOKEN", 300, "method.request.header.Authorization");
|
||||
respond(Map.of("principalId", "verified", "context", Map.of("tenant-id", "tenant-one", "plan.level", 2),
|
||||
"policyDocument", policy(List.of(statement("Allow", "execute-api:Invoke", "*")))));
|
||||
String resourceId = given().get("/restapis/" + apiId + "/resources").then().extract()
|
||||
.path("item.find { it.path == '/allowed' }.id");
|
||||
given().contentType(ContentType.JSON).body(Map.of("type", "AWS_PROXY", "httpMethod", "POST",
|
||||
"uri", AUTHORIZER_URI.replace(FUNCTION, "context-proxy")))
|
||||
.put(methodPath(resourceId) + "/integration").then().statusCode(201);
|
||||
when(lambdaService.invoke(eq("us-east-1"), eq("context-proxy"), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(invocation -> {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
String context = mapper.readTree((byte[]) invocation.getArgument(2))
|
||||
.path("requestContext").path("authorizer").toString();
|
||||
return new InvokeResult(200, null,
|
||||
mapper.writeValueAsBytes(Map.of("statusCode", 200, "body", context)), null, "proxy-request");
|
||||
});
|
||||
deploy("test");
|
||||
for (int request = 0; request < 2; request++) {
|
||||
given().header("Authorization", "token").get(execute("allowed"))
|
||||
.then().statusCode(200).body("'tenant-id'", equalTo("tenant-one"),
|
||||
"'plan.level'", equalTo("2"), "principalId", equalTo("verified"));
|
||||
}
|
||||
verifyInvocation(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingTokenIsUnauthorizedWithoutInvokingLambda() throws Exception {
|
||||
configure("TOKEN", 0, "method.request.header.Authorization");
|
||||
allowAll();
|
||||
given().get(execute("allowed")).then().statusCode(401);
|
||||
verifyInvocation(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cachedPolicyAndContextAreReusedButPolicyStillGatesEachRoute() throws Exception {
|
||||
configure("TOKEN", 300, "method.request.header.Authorization");
|
||||
respond(Map.of("principalId", "verified", "context", Map.of("userClaims", "trusted"),
|
||||
"policyDocument", policy(List.of(statement("Allow", "execute-api:Invoke", methodArn("allowed"))))));
|
||||
for (int i = 0; i < 2; i++) {
|
||||
given().header("Authorization", "token").header("X-User-Claims", "forged")
|
||||
.get(execute("allowed")).then().statusCode(200)
|
||||
.body("principal", equalTo("verified"), "claims", equalTo("trusted"));
|
||||
}
|
||||
given().header("Authorization", "token").get(execute("other")).then().statusCode(403);
|
||||
verifyInvocation(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroTtlInvokesForEachRequest() throws Exception {
|
||||
configure("TOKEN", 0, "method.request.header.Authorization");
|
||||
allowAll();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
given().header("Authorization", "token").get(execute("allowed")).then().statusCode(200);
|
||||
}
|
||||
verifyInvocation(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void flushingStageAndRedeployingInvalidateCachedResult() throws Exception {
|
||||
configure("TOKEN", 300, "method.request.header.Authorization");
|
||||
allowAll();
|
||||
given().header("Authorization", "token").get(execute("allowed")).then().statusCode(200);
|
||||
given().delete("/restapis/" + apiId + "/stages/test/cache/authorizers").then().statusCode(202).body(equalTo(""));
|
||||
given().header("Authorization", "token").get(execute("allowed")).then().statusCode(200);
|
||||
deploy("test");
|
||||
given().header("Authorization", "token").get(execute("allowed")).then().statusCode(200);
|
||||
verifyInvocation(3);
|
||||
given().delete("/restapis/" + apiId + "/stages/missing/cache/authorizers").then().statusCode(404);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"TOKEN", "REQUEST"})
|
||||
void flushPreventsInFlightInvocationFromRestoringStaleContext(String type) throws Exception {
|
||||
configure(type, 300, "method.request.header.Authorization");
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicInteger invocations = new AtomicInteger();
|
||||
when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(invocation -> {
|
||||
boolean first = invocations.incrementAndGet() == 1;
|
||||
if (first) {
|
||||
started.countDown();
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS), "Authorizer invocation was not released");
|
||||
}
|
||||
byte[] payload = new ObjectMapper().writeValueAsBytes(Map.of("principalId", "verified",
|
||||
"policyDocument", policy(List.of(statement("Allow", "execute-api:Invoke", "*"))),
|
||||
"context", Map.of("userClaims", first ? "stale" : "fresh")));
|
||||
return new InvokeResult(200, null, payload, null, "lambda-request");
|
||||
});
|
||||
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
|
||||
Future<?> request = executor.submit(() -> given().header("Authorization", "token")
|
||||
.get(execute("allowed")).then().statusCode(200).body("claims", equalTo("stale")));
|
||||
try {
|
||||
assertTrue(started.await(10, TimeUnit.SECONDS), "Authorizer invocation did not start");
|
||||
given().delete("/restapis/" + apiId + "/stages/test/cache/authorizers").then().statusCode(202);
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
request.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
for (int i = 0; i < 2; i++) {
|
||||
given().header("Authorization", "token").get(execute("allowed"))
|
||||
.then().statusCode(200).body("claims", equalTo("fresh"));
|
||||
}
|
||||
verifyInvocation(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void changedAuthorizerConfigurationInvalidatesCachedResult() throws Exception {
|
||||
configure("TOKEN", 300, "method.request.header.Authorization");
|
||||
allowAll();
|
||||
given().header("Authorization", "token").get(execute("allowed")).then().statusCode(200);
|
||||
given().contentType(ContentType.JSON).body(Map.of("patchOperations", List.of(Map.of(
|
||||
"op", "replace", "path", "/identitySource", "value", "method.request.header.New-Token"))))
|
||||
.patch("/restapis/" + apiId + "/authorizers/" + authorizerId).then().statusCode(200);
|
||||
given().header("New-Token", "token").get(execute("allowed")).then().statusCode(200);
|
||||
verifyInvocation(2);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, 300})
|
||||
void requestIdentitySourcesAreRequiredOnlyWhenCaching(int ttl) throws Exception {
|
||||
configure("REQUEST", ttl, "method.request.header.Authorization,method.request.querystring.tenant");
|
||||
allowAll();
|
||||
given().header("Authorization", "token").get(execute("allowed"))
|
||||
.then().statusCode(ttl == 0 ? 200 : 401);
|
||||
verifyInvocation(ttl == 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestCacheUsesAllIdentitySources() throws Exception {
|
||||
configure("REQUEST", 300, "method.request.header.Authorization,method.request.querystring.tenant");
|
||||
allowAll();
|
||||
for (String tenant : List.of("one", "one", "two")) {
|
||||
given().header("Authorization", "token").queryParam("tenant", tenant)
|
||||
.get(execute("allowed")).then().statusCode(200);
|
||||
}
|
||||
verifyInvocation(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestContextIdentitySourcesSeparateRoutePolicies() throws Exception {
|
||||
configure("REQUEST", 300, "method.request.header.Authorization,context.resourcePath");
|
||||
allowAll();
|
||||
for (String path : List.of("allowed", "allowed", "other")) {
|
||||
given().header("Authorization", "token").get(execute(path)).then().statusCode(200);
|
||||
}
|
||||
verifyInvocation(2);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Unauthorized", "failure"})
|
||||
void lambdaErrorsDistinguishUnauthorizedFromFailure(String message) throws Exception {
|
||||
configure("TOKEN", 300, "method.request.header.Authorization");
|
||||
byte[] payload = new ObjectMapper().writeValueAsBytes(Map.of("errorMessage", message));
|
||||
when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(new InvokeResult(200, "Unhandled", payload, null, "lambda-error"));
|
||||
for (int i = 0; i < 2; i++) {
|
||||
given().header("Authorization", "token").get(execute("allowed"))
|
||||
.then().statusCode("Unauthorized".equals(message) ? 401 : 500);
|
||||
}
|
||||
verifyInvocation(2);
|
||||
}
|
||||
|
||||
private void configure(String type, int ttl, String identitySource) {
|
||||
Map<String, Object> request = new LinkedHashMap<>(Map.of("name", "contract", "type", type,
|
||||
"authorizerUri", AUTHORIZER_URI, "authorizerResultTtlInSeconds", ttl));
|
||||
if (identitySource != null) {
|
||||
request.put("identitySource", identitySource);
|
||||
}
|
||||
authorizerId = given().contentType(ContentType.JSON).body(request)
|
||||
.post("/restapis/" + apiId + "/authorizers").then().statusCode(201).extract().path("id");
|
||||
List<String> resources = given().get("/restapis/" + apiId + "/resources")
|
||||
.then().extract().path("item.findAll { it.path != '/' }.id");
|
||||
for (String resourceId : resources) {
|
||||
given().contentType(ContentType.JSON).body(Map.of("authorizationType", "CUSTOM", "authorizerId", authorizerId))
|
||||
.put(methodPath(resourceId)).then().statusCode(201);
|
||||
given().contentType(ContentType.JSON).body(Map.of("type", "MOCK",
|
||||
"requestTemplates", Map.of("application/json", "{\"statusCode\":200}")))
|
||||
.put(methodPath(resourceId) + "/integration").then().statusCode(201);
|
||||
given().contentType(ContentType.JSON).body(Map.of())
|
||||
.put(methodPath(resourceId) + "/responses/200").then().statusCode(201);
|
||||
given().contentType(ContentType.JSON).body(Map.of("responseTemplates", Map.of("application/json",
|
||||
"{\"principal\":\"$context.authorizer.principalId\","
|
||||
+ "\"claims\":\"$context.authorizer.userClaims\"}")))
|
||||
.put(methodPath(resourceId) + "/integration/responses/200").then().statusCode(201);
|
||||
}
|
||||
deploy("test");
|
||||
}
|
||||
|
||||
private void deploy(String stage) {
|
||||
given().contentType(ContentType.JSON).body(Map.of("stageName", stage))
|
||||
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
|
||||
}
|
||||
|
||||
private void allowAll() throws Exception {
|
||||
respond(Map.of("principalId", "verified", "policyDocument",
|
||||
policy(List.of(statement("Allow", "execute-api:Invoke", "*")))));
|
||||
}
|
||||
|
||||
private void respond(Map<String, Object> output) throws Exception {
|
||||
byte[] payload = new ObjectMapper().writeValueAsBytes(output);
|
||||
when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(new InvokeResult(200, null, payload, null, "lambda-request"));
|
||||
}
|
||||
|
||||
private void verifyInvocation(int count) {
|
||||
if (count == 0) {
|
||||
verify(lambdaService, never()).invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
} else {
|
||||
verify(lambdaService, times(count)).invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, String> statement(String effect, String action, String resource) {
|
||||
return Map.of("Effect", effect, "Action", action, "Resource", resource);
|
||||
}
|
||||
|
||||
private static Map<String, Object> policy(List<Map<String, String>> statements) {
|
||||
return Map.of("Version", "2012-10-17", "Statement", statements);
|
||||
}
|
||||
|
||||
private String methodPath(String resourceId) {
|
||||
return "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";
|
||||
}
|
||||
|
||||
private String methodArn(String path) {
|
||||
return "arn:aws:execute-api:us-east-1:000000000000:" + apiId + "/test/GET/" + path;
|
||||
}
|
||||
|
||||
private String execute(String path) {
|
||||
return "/execute-api/" + apiId + "/test/" + path;
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RestLambdaAuthorizerTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final Clock clock = mock(Clock.class);
|
||||
private final Instant now = Instant.parse("2026-10-03T00:00:00Z");
|
||||
private RestLambdaAuthorizer authorizer;
|
||||
|
||||
@BeforeEach
|
||||
void createAuthorizer() {
|
||||
when(clock.instant()).thenReturn(now);
|
||||
authorizer = new RestLambdaAuthorizer(mapper, new IamPolicyEvaluator(mapper), clock);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiresAtTtlBoundaryAndZeroTtlDoesNotCache() {
|
||||
RestLambdaAuthorizer.Result result = new RestLambdaAuthorizer.Result("principal", "{}", Map.of("claims", "trusted"));
|
||||
RestLambdaAuthorizer.CacheKey key = key("account", "region", "api", "stage", "deployment", "token", 10);
|
||||
cache(key, result);
|
||||
when(clock.instant()).thenReturn(now.plusSeconds(9));
|
||||
assertSame(result, authorizer.get(key));
|
||||
when(clock.instant()).thenReturn(now.plusSeconds(10));
|
||||
assertNull(authorizer.get(key));
|
||||
RestLambdaAuthorizer.CacheKey disabled = key("account", "region", "api", "stage", "deployment", "token", 0);
|
||||
cache(disabled, result);
|
||||
assertNull(authorizer.get(disabled));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cacheIsScopedAndFlushOnlyRemovesTargetStage() {
|
||||
RestLambdaAuthorizer.CacheKey target = key("account", "region", "api", "stage", "deployment", "token", 300);
|
||||
List<RestLambdaAuthorizer.CacheKey> others = List.of(
|
||||
key("other", "region", "api", "stage", "deployment", "token", 300),
|
||||
key("account", "other", "api", "stage", "deployment", "token", 300),
|
||||
key("account", "region", "other", "stage", "deployment", "token", 300),
|
||||
key("account", "region", "api", "other", "deployment", "token", 300));
|
||||
RestLambdaAuthorizer.Result result = new RestLambdaAuthorizer.Result("principal", "{}", Map.of());
|
||||
cache(target, result);
|
||||
others.forEach(key -> cache(key, result));
|
||||
assertNull(authorizer.get(key("account", "region", "api", "stage", "new-deployment", "token", 300)));
|
||||
assertNull(authorizer.get(key("account", "region", "api", "stage", "deployment", "other-token", 300)));
|
||||
authorizer.flush(target.scope());
|
||||
assertNull(authorizer.get(target));
|
||||
others.forEach(key -> assertSame(result, authorizer.get(key)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void policyArraysWildcardsAndConditionsUseIamEvaluation() throws Exception {
|
||||
byte[] payload = mapper.writeValueAsBytes(Map.of("principalId", "principal", "policyDocument", Map.of(
|
||||
"Version", "2012-10-17", "Statement", List.of(Map.of("Effect", "Allow",
|
||||
"Action", List.of("execute-api:Invoke"), "Resource", List.of("*/GET/allowed/*"),
|
||||
"Condition", Map.of("IpAddress", Map.of("aws:SourceIp", "192.0.2.0/24")))))));
|
||||
RestLambdaAuthorizer.Result result = authorizer.parse(payload);
|
||||
assertTrue(authorizer.permits(result, "api/stage/GET/allowed/child", Map.of("aws:SourceIp", List.of("192.0.2.10"))));
|
||||
assertFalse(authorizer.permits(result, "api/stage/GET/other/child", Map.of("aws:SourceIp", List.of("192.0.2.10"))));
|
||||
assertFalse(authorizer.permits(result, "api/stage/GET/allowed/child", Map.of("aws:SourceIp", List.of("198.51.100.10"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scalarContextRetainsTypesAndIsImmutable() throws Exception {
|
||||
byte[] payload = mapper.writeValueAsBytes(Map.of("principalId", "principal", "context",
|
||||
Map.of("tenant-id", "trusted", "number", 2, "boolean", true), "policyDocument",
|
||||
Map.of("Statement", Map.of("Effect", "Allow", "Action", "execute-api:Invoke", "Resource", "*"))));
|
||||
RestLambdaAuthorizer.Result result = authorizer.parse(payload);
|
||||
assertEquals(Map.of("tenant-id", "trusted", "number", 2, "boolean", true), result.context());
|
||||
assertThrows(UnsupportedOperationException.class, () -> result.context().put("claims", "forged"));
|
||||
assertTrue(authorizer.permits(result, "method", Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void flushInvalidatesOnlyPendingInvocationsInItsScope() {
|
||||
RestLambdaAuthorizer.CacheKey target = key("account", "region", "api", "stage", "deployment", "token", 300);
|
||||
RestLambdaAuthorizer.CacheKey other = key("account", "region", "api", "other", "deployment", "token", 300);
|
||||
RestLambdaAuthorizer.Result result = new RestLambdaAuthorizer.Result("principal", "{}", Map.of());
|
||||
try (RestLambdaAuthorizer.Invocation beforeFlush = authorizer.beginInvocation(target);
|
||||
RestLambdaAuthorizer.Invocation unaffected = authorizer.beginInvocation(other)) {
|
||||
authorizer.flush(target.scope());
|
||||
cache(target, result);
|
||||
beforeFlush.cache(new RestLambdaAuthorizer.Result("stale", "{}", Map.of()));
|
||||
unaffected.cache(result);
|
||||
assertSame(result, authorizer.get(target));
|
||||
assertSame(result, authorizer.get(other));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void closedInvocationCannotInsertResult() {
|
||||
RestLambdaAuthorizer.CacheKey key = key("account", "region", "api", "stage", "deployment", "token", 300);
|
||||
RestLambdaAuthorizer.Invocation invocation = authorizer.beginInvocation(key);
|
||||
invocation.close();
|
||||
invocation.cache(new RestLambdaAuthorizer.Result("principal", "{}", Map.of()));
|
||||
assertNull(authorizer.get(key));
|
||||
}
|
||||
|
||||
private void cache(RestLambdaAuthorizer.CacheKey key, RestLambdaAuthorizer.Result result) {
|
||||
try (RestLambdaAuthorizer.Invocation invocation = authorizer.beginInvocation(key)) {
|
||||
invocation.cache(result);
|
||||
}
|
||||
}
|
||||
|
||||
private static RestLambdaAuthorizer.CacheKey key(String account, String region, String api, String stage,
|
||||
String deployment, String token, int ttl) {
|
||||
return new RestLambdaAuthorizer.CacheKey(new RestLambdaAuthorizer.Scope(account, region, api, stage),
|
||||
deployment, "authorizer", "uri", "TOKEN", "method.request.header.Authorization", ttl, List.of(token));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user