mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(apigatewayv2): include authorizer identity sources (#6694)
This commit is contained in:
1 parent
a30e484dae
commit
825564a3d0
9 files changed
+415
-98
No files matched your search
+1
-1
@@ -767,7 +767,7 @@ class ApiGatewayExecuteControllerTest {
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
assertEnglishUtcTimeUnderNonUtcHost(() -> controller.buildRequestAuthorizerEventV2("GET", "/items",
|
||||
"GET /items", "api1", "$default", "us-east-1", emptyHeaders(),
|
||||
uriInfoFor("http://localhost/items"), null));
|
||||
uriInfoFor("http://localhost/items"), null).toString());
|
||||
}
|
||||
|
||||
private static HttpHeaders emptyHeaders() {
|
||||
|
||||
+1
-2
@@ -53,9 +53,8 @@ class BuildV2AuthorizerEventTrailingSlashTest {
|
||||
|
||||
private JsonNode buildEvent(String normalizedPath, String rawRequestUri) throws Exception {
|
||||
when(uriInfo.getRequestUri()).thenReturn(new URI(rawRequestUri));
|
||||
String json = controller.buildRequestAuthorizerEventV1(
|
||||
return controller.buildRequestAuthorizerEventV1(
|
||||
"GET", normalizedPath, "abc123", "test", "us-east-1", headers, uriInfo, null);
|
||||
return new ObjectMapper().readTree(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+15
-1
@@ -13,6 +13,7 @@ import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -65,7 +66,7 @@ class BuildV2ProxyEventMultiValueTest {
|
||||
"abc123", "us-east-1", "$default", headers, uriInfo, null, "req-1");
|
||||
case AUTHORIZER -> controller.buildRequestAuthorizerEventV2(
|
||||
"GET", "/echo", "GET /echo",
|
||||
"abc123", "$default", "us-east-1", headers, uriInfo, null);
|
||||
"abc123", "$default", "us-east-1", headers, uriInfo, null).toString();
|
||||
};
|
||||
return new ObjectMapper().readTree(json);
|
||||
}
|
||||
@@ -82,6 +83,19 @@ class BuildV2ProxyEventMultiValueTest {
|
||||
assertEquals("x", qsp.get("single").asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(Builder.class)
|
||||
void headerNamesUseLocaleIndependentCaseFolding(Builder builder) throws Exception {
|
||||
requestHeaders.add("X-Identity", "identity-value");
|
||||
Locale original = Locale.getDefault();
|
||||
try {
|
||||
Locale.setDefault(Locale.forLanguageTag("tr-TR"));
|
||||
assertEquals("identity-value", buildEvent(builder).path("headers").path("x-identity").asText());
|
||||
} finally {
|
||||
Locale.setDefault(original);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(Builder.class)
|
||||
void repeatedHeaderIsCommaJoined(Builder builder) throws Exception {
|
||||
|
||||
+4
-4
@@ -82,11 +82,11 @@ class BuildV2ProxyEventStageVariablesTest {
|
||||
|
||||
private List<JsonNode> buildAuthorizerEvents(Map<String, String> stageVariables) throws Exception {
|
||||
return List.of(
|
||||
MAPPER.readTree(controller.buildRequestAuthorizerEventV1(
|
||||
controller.buildRequestAuthorizerEventV1(
|
||||
"GET", "/echo", "abc123", "test", "us-east-1",
|
||||
headers, uriInfo, stageVariables)),
|
||||
MAPPER.readTree(controller.buildRequestAuthorizerEventV2(
|
||||
headers, uriInfo, stageVariables),
|
||||
controller.buildRequestAuthorizerEventV2(
|
||||
"GET", "/echo", "GET /echo", "abc123", "test", "us-east-1",
|
||||
headers, uriInfo, stageVariables)));
|
||||
headers, uriInfo, stageVariables));
|
||||
}
|
||||
}
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
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.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
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.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.AUTHORIZER;
|
||||
import static io.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.BACKEND;
|
||||
import static io.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.result;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@QuarkusTest
|
||||
class HttpApiAuthorizerIdentitySourceIntegrationTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@InjectMock
|
||||
LambdaService lambdaService;
|
||||
|
||||
private final AtomicReference<JsonNode> authorizerEvent = new AtomicReference<>();
|
||||
private String apiId;
|
||||
private String stageName = "test";
|
||||
private String payloadFormat = "2.0";
|
||||
private boolean allowed = true;
|
||||
|
||||
@BeforeEach
|
||||
void stubLambdaBoundary() {
|
||||
LambdaAuthorizerApiFixtures.stubAuthorizer(lambdaService, event -> {
|
||||
authorizerEvent.set(event);
|
||||
if ("1.0".equals(payloadFormat)) {
|
||||
return result("{\"principalId\":\"user\",\"policyDocument\":{\"Version\":\"2012-10-17\","
|
||||
+ "\"Statement\":[{\"Action\":\"execute-api:Invoke\",\"Effect\":\""
|
||||
+ (allowed ? "Allow" : "Deny") + "\",\"Resource\":\""
|
||||
+ event.path("methodArn").asText() + "\"}]}}");
|
||||
}
|
||||
return result("{\"isAuthorized\":" + allowed + "}");
|
||||
});
|
||||
LambdaAuthorizerApiFixtures.stubBackend(lambdaService);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteApi() {
|
||||
if (apiId != null) {
|
||||
given().delete("/v2/apis/" + apiId).then().statusCode(204);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void headerIdentityIsAnArrayAndKeepsTheBearerPrefix() {
|
||||
configureApi(List.of("$request.header.authorization"));
|
||||
given().header("Authorization", "Bearer opaque-token").get(path()).then().statusCode(200);
|
||||
assertIdentities(List.of("Bearer opaque-token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void multipleSourcesKeepConfiguredOrderAndResolveContextAndStageValues() {
|
||||
configureApi(List.of("$context.routeKey", "$stageVariables.tenant", "$request.querystring.Token",
|
||||
"$request.header.X-Identity", "$context.stage", "$context.requestId"));
|
||||
given().header("x-identity", "header-value").queryParam("Token", "query-value")
|
||||
.get(path()).then().statusCode(200);
|
||||
JsonNode event = authorizerEvent.get();
|
||||
assertNotNull(event);
|
||||
assertIdentities(List.of("GET /items", "stage-tenant", "query-value", "header-value", "test",
|
||||
event.path("requestContext").path("requestId").asText()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextAliasesUseTheValuesFromThisEvent() {
|
||||
configureApi(List.of("$context.httpMethod", "$context.protocol", "$context.identity.sourceIp",
|
||||
"$context.identity.userAgent", "$context.requestTime", "$context.requestTimeEpoch", "$context.extendedRequestId"));
|
||||
given().header("User-Agent", "identity-client").get(path()).then().statusCode(200);
|
||||
JsonNode context = authorizerEvent.get().path("requestContext");
|
||||
assertIdentities(List.of("GET", "HTTP/1.1", context.path("http").path("sourceIp").asText(),
|
||||
"identity-client", context.path("time").asText(), context.path("timeEpoch").asText(),
|
||||
context.path("requestId").asText()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"1.0,test", "1.0,$default", "2.0,test", "2.0,$default"})
|
||||
void contextPathIncludesOnlyANamedStage(String format, String stage) {
|
||||
payloadFormat = format;
|
||||
stageName = stage;
|
||||
configureApi(List.of("$context.path"));
|
||||
given().get(path()).then().statusCode(200);
|
||||
assertIdentities(List.of("$default".equals(stage) ? "/items" : "/test/items"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatedRequestValuesAreJoinedLikeTheEventFields() {
|
||||
configureApi(List.of("$request.querystring.Token", "$request.header.X-Identity", "$request.querystring.Token"));
|
||||
given().header("X-Identity", "first", "second").queryParam("Token", "one", "two")
|
||||
.get(path()).then().statusCode(200);
|
||||
assertIdentities(List.of("one,two", "first,second", "one,two"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"1.0", "2.0"})
|
||||
void noConfiguredSourcesProducesAnEmptyIdentityValue(String format) {
|
||||
payloadFormat = format;
|
||||
configureApi(List.of());
|
||||
given().get(path()).then().statusCode(200);
|
||||
assertIdentities(List.of());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"$request.header.Missing", "$request.querystring.Missing", "$request.querystring.Token",
|
||||
"$stageVariables.missing", "$context.missing", "$context.http"})
|
||||
void missingOrWrongCaseRequestSourceDoesNotInvokeLambda(String source) {
|
||||
configureApi(List.of(source));
|
||||
given().queryParam("token", "wrong-case").get(path()).then().statusCode(401);
|
||||
verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(AUTHORIZER), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(BACKEND), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyConfiguredValueDoesNotInvokeLambda() {
|
||||
configureApi(List.of("$request.querystring.Token"));
|
||||
given().queryParam("Token", "").get(path()).then().statusCode(401);
|
||||
verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(AUTHORIZER), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatOneResolvesSourcesAndRendersCommaSeparatedIdentityFields() {
|
||||
payloadFormat = "1.0";
|
||||
configureApi(List.of("$request.header.authorization", "$request.querystring.Token",
|
||||
"$stageVariables.tenant", "$context.routeKey", "$context.stage", "$context.requestId"));
|
||||
given().header("Authorization", "Bearer identity").queryParam("Token", "query-value")
|
||||
.get(path()).then().statusCode(200);
|
||||
String expected = "Bearer identity,query-value,stage-tenant,GET /items,test,"
|
||||
+ authorizerEvent.get().path("requestContext").path("requestId").asText();
|
||||
assertEquals(expected, authorizerEvent.get().path("identitySource").asText());
|
||||
assertEquals(expected, authorizerEvent.get().path("authorizationToken").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatOneContextAliasesUseTheValuesFromThisEvent() {
|
||||
payloadFormat = "1.0";
|
||||
configureApi(List.of("$context.httpMethod", "$context.protocol", "$context.identity.sourceIp",
|
||||
"$context.identity.userAgent", "$context.requestTime", "$context.requestTimeEpoch", "$context.extendedRequestId"));
|
||||
given().header("User-Agent", "identity-client").get(path()).then().statusCode(200);
|
||||
JsonNode context = authorizerEvent.get().path("requestContext");
|
||||
assertEquals(String.join(",", "GET", "HTTP/1.1", context.path("identity").path("sourceIp").asText(),
|
||||
"identity-client", context.path("requestTime").asText(), context.path("requestTimeEpoch").asText(),
|
||||
context.path("requestId").asText()), authorizerEvent.get().path("identitySource").asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"$request.header.Missing", "$request.querystring.Missing", "$request.querystring.Token",
|
||||
"$stageVariables.missing", "$context.missing", "$context.identity"})
|
||||
void formatOneMissingOrWrongCaseSourceDoesNotInvokeLambda(String source) {
|
||||
payloadFormat = "1.0";
|
||||
configureApi(List.of(source));
|
||||
given().queryParam("token", "wrong-case").get(path()).then().statusCode(401);
|
||||
verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(AUTHORIZER), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(BACKEND), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatOneRepeatedRequestValuesUseTheLastDeliveredValues() {
|
||||
payloadFormat = "1.0";
|
||||
configureApi(List.of("$request.querystring.Token", "$request.header.X-Identity", "$request.querystring.Token"));
|
||||
given().header("X-Identity", "first", "second").queryParam("Token", "one", "two")
|
||||
.get(path()).then().statusCode(200);
|
||||
assertIdentities(List.of("two", "second", "two"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatOneEmptyLastQueryValueDoesNotInvokeLambda() {
|
||||
payloadFormat = "1.0";
|
||||
configureApi(List.of("$request.querystring.Token"));
|
||||
given().queryParam("Token", "present", "").get(path()).then().statusCode(401);
|
||||
verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(AUTHORIZER), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"1.0", "2.0"})
|
||||
void anEarlierEmptyQueryValueDoesNotHideTheDeliveredValue(String format) {
|
||||
payloadFormat = format;
|
||||
configureApi(List.of("$request.querystring.Token"));
|
||||
given().queryParam("Token", "", "present").get(path()).then().statusCode(200);
|
||||
assertIdentities(List.of("1.0".equals(format) ? "present" : ",present"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void identityValuesDoNotBypassADenyResponse() {
|
||||
allowed = false;
|
||||
configureApi(List.of("$request.header.Authorization"));
|
||||
given().header("Authorization", "Bearer denied-token").get(path()).then().statusCode(403);
|
||||
assertIdentities(List.of("Bearer denied-token"));
|
||||
verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq(BACKEND), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
}
|
||||
|
||||
private void assertIdentities(List<String> expected) {
|
||||
assertNotNull(authorizerEvent.get());
|
||||
JsonNode identities = "1.0".equals(payloadFormat) ? MAPPER.valueToTree(String.join(",", expected)) : MAPPER.valueToTree(expected);
|
||||
assertEquals(identities, authorizerEvent.get().get("identitySource"));
|
||||
if ("1.0".equals(payloadFormat)) {
|
||||
assertEquals(identities, authorizerEvent.get().get("authorizationToken"));
|
||||
}
|
||||
}
|
||||
|
||||
private String path() {
|
||||
return "/execute-api/" + apiId + "/" + stageName + "/items";
|
||||
}
|
||||
|
||||
private void configureApi(List<String> sources) {
|
||||
apiId = LambdaAuthorizerApiFixtures.createApi("HTTP", stageName, Map.of("tenant", "stage-tenant"),
|
||||
Map.of("authorizerPayloadFormatVersion", payloadFormat, "enableSimpleResponses", "2.0".equals(payloadFormat),
|
||||
"identitySource", sources));
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
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.restassured.http.ContentType;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
final class LambdaAuthorizerApiFixtures {
|
||||
|
||||
static final String REGION = "us-east-1";
|
||||
static final String AUTHORIZER = "arn:aws:lambda:us-east-1:000000000000:function:fixture-authorizer";
|
||||
static final String BACKEND = "arn:aws:lambda:us-east-1:000000000000:function:fixture-backend";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private LambdaAuthorizerApiFixtures() {}
|
||||
|
||||
static String createApi(String protocol, String stageName, Map<String, String> stageVariables,
|
||||
Map<String, Object> authorizerFields) {
|
||||
String apiId = given().contentType(ContentType.JSON)
|
||||
.body(Map.of("name", "lambda-authorizer", "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", stageName, "stageVariables", stageVariables))
|
||||
.post(apiPath + "/stages").then().statusCode(201);
|
||||
Map<String, Object> authorizer = new LinkedHashMap<>(authorizerFields);
|
||||
authorizer.put("name", "fixture-authorizer");
|
||||
authorizer.put("authorizerType", "REQUEST");
|
||||
authorizer.put("authorizerUri", AUTHORIZER);
|
||||
String authorizerId = given().contentType(ContentType.JSON).body(authorizer)
|
||||
.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", BACKEND);
|
||||
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);
|
||||
return apiId;
|
||||
}
|
||||
|
||||
static void stubAuthorizer(LambdaService lambdaService, Function<JsonNode, InvokeResult> response) {
|
||||
when(lambdaService.invokeTarget(eq(REGION), eq(AUTHORIZER), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(invocation -> response.apply(MAPPER.readTree((byte[]) invocation.getArgument(2))));
|
||||
}
|
||||
|
||||
static void stubBackend(LambdaService lambdaService) {
|
||||
when(lambdaService.invokeTarget(eq(REGION), eq(BACKEND), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(result("{\"statusCode\":200,\"body\":\"allowed\"}"));
|
||||
}
|
||||
|
||||
static InvokeResult result(String payload) {
|
||||
return new InvokeResult(200, null, payload.getBytes(StandardCharsets.UTF_8), null, "request");
|
||||
}
|
||||
}
|
||||
+12
-46
@@ -1,14 +1,10 @@
|
||||
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;
|
||||
@@ -17,12 +13,13 @@ 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.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.BACKEND;
|
||||
import static io.github.hectorvent.floci.services.apigatewayv2.LambdaAuthorizerApiFixtures.result;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
@@ -31,10 +28,6 @@ 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;
|
||||
|
||||
@@ -55,12 +48,11 @@ class LambdaAuthorizerPolicyIntegrationTest {
|
||||
void httpRequestsEnforceAuthorizerPolicies(String scenario, String statements, int expectedStatus) {
|
||||
configureApi("HTTP");
|
||||
stubAuthorizer(statements);
|
||||
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + BACKEND_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(result("{\"statusCode\":200,\"body\":\"allowed\"}"));
|
||||
LambdaAuthorizerApiFixtures.stubBackend(lambdaService);
|
||||
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))
|
||||
.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + BACKEND_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
.invokeTarget(eq("us-east-1"), eq(BACKEND), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "WebSocket: {0}")
|
||||
@@ -98,42 +90,16 @@ class LambdaAuthorizerPolicyIntegrationTest {
|
||||
}
|
||||
|
||||
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);
|
||||
apiId = LambdaAuthorizerApiFixtures.createApi(protocol, "test", Map.of(), Map.of("authorizerPayloadFormatVersion", "2.0"));
|
||||
}
|
||||
|
||||
private void stubAuthorizer(String statements) {
|
||||
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + 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");
|
||||
LambdaAuthorizerApiFixtures.stubAuthorizer(lambdaService, event -> {
|
||||
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) + "}}");
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user