fix(cloudformation): clear dropped API Gateway v2 route and authorizer settings (#7992)

This commit is contained in:
Oleksandr Nikolaichuk authored and GitHub committed 2026-11-11 10:49:06 -04:00
1 parent 46207993fb
commit 195a036b63
11 files changed
+935 -25

No files matched your search

@@ -4,11 +4,11 @@ import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.TlsCertificateManager;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.apigateway.ApiGatewayService.StoredMapping;
import io.floci.aws.services.apigateway.model.CustomDomain;
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
import io.floci.aws.services.apigatewayv2.ApiGatewayV2ServiceFixture;
import io.floci.aws.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -16,18 +16,13 @@ import java.time.Clock;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The v2 custom domain and API mapping rules, over real services and in-memory stores: the id a
@@ -53,11 +48,8 @@ class ApiGatewayV2ApiMappingServiceTest {
@BeforeEach
void setUp() {
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any()))
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().cloudfront().domainSuffix()).thenReturn(Optional.empty());
InMemoryStorageFactory storageFactory = new InMemoryStorageFactory("000000000000");
EmulatorConfig config = ApiGatewayV2ServiceFixture.config();
RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
v2Service = new ApiGatewayV2Service(storageFactory, config, regionResolver);
service = new ApiGatewayService(storageFactory, config, mock(TlsCertificateManager.class), regionResolver,
@@ -0,0 +1,33 @@
package io.floci.aws.services.apigatewayv2;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.testing.InMemoryStorageFactory;
import java.util.Optional;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* What a unit test needs to build a real {@link ApiGatewayV2Service} over in-memory stores: the
* emulator config the service reads and the service itself.
*/
public final class ApiGatewayV2ServiceFixture {
private ApiGatewayV2ServiceFixture() {
}
/** An emulator config with no CloudFront domain suffix; every other setting is a deep stub. */
public static EmulatorConfig config() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().cloudfront().domainSuffix()).thenReturn(Optional.empty());
return config;
}
public static ApiGatewayV2Service service(InMemoryStorageFactory storageFactory, String region,
String accountId) {
return new ApiGatewayV2Service(storageFactory, config(), new RegionResolver(region, accountId));
}
}
@@ -26,7 +26,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -1224,9 +1223,7 @@ class ApiGatewayV2CfnProvisionerTest {
}
private CloudFormationTemplateEngine engine(Map<String, Boolean> conditions) {
return new CloudFormationTemplateEngine("000000000000", REGION, "test-stack", "stack/id",
Map.of(), Map.of(), Map.of(), conditions, Map.of(), mapper,
(Function<String, String>) name -> null);
return CfnProvisionerFixture.engine(mapper, REGION, conditions);
}
private static Route route(String id, String routeKey) {
@@ -0,0 +1,479 @@
package io.floci.aws.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
import io.floci.aws.services.apigatewayv2.ApiGatewayV2ServiceFixture;
import io.floci.aws.services.apigatewayv2.model.Authorizer;
import io.floci.aws.services.apigatewayv2.model.Route;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.cloudformation.provisioners.ApiGatewayV2CfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.CfnResourceDispatcher;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
import static io.floci.aws.services.cloudformation.CfnProvisionerFixture.engine;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
/**
* What an in-place update leaves on an AWS::ApiGatewayV2::Route and an AWS::ApiGatewayV2::Authorizer
* when the template drops a setting, over the real service and the real provisioner. A setting the
* previous template declared and the new one drops reads back as it does on a create without it. A
* setting the template never declared is left alone, so a value set through the API survives.
* The Route {@code RouteKey} and the Authorizer {@code Name}, {@code AuthorizerType},
* {@code AuthorizerUri}, {@code AuthorizerPayloadFormatVersion} and {@code JwtConfiguration} are
* required by AWS for the resource or its type, so a drop keeps them.
*/
class ApiGatewayV2RouteAuthorizerDropTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String ROUTE_BASE = "\"ApiId\":\"%s\",\"RouteKey\":\"GET /items\"";
private static final String LAMBDA_URI = "arn:aws:lambda:us-east-1:000000000000:function:auth";
private static final String LAMBDA_SETTINGS =
"\"AuthorizerUri\":\"" + LAMBDA_URI + "\",\"AuthorizerPayloadFormatVersion\":\"2.0\"";
private static final String JWT_CONFIGURATION =
",\"JwtConfiguration\":{\"Audience\":[\"aud\"],\"Issuer\":\"https://issuer.example\"}";
private static final String AUTHORIZER_BASE =
"\"ApiId\":\"%s\",\"Name\":\"auth\",\"AuthorizerType\":\"REQUEST\"," + LAMBDA_SETTINGS;
private final ObjectMapper mapper = new ObjectMapper();
private ApiGatewayV2Service service;
private CfnResourceDispatcher provisioner;
private String apiId;
@BeforeEach
void setUp() {
service = ApiGatewayV2ServiceFixture.service(new InMemoryStorageFactory(ACCOUNT), REGION, ACCOUNT);
provisioner = CfnProvisionerFixture.builder()
.apiGatewayV2(service)
.objectMapper(mapper)
.provisioners(new ApiGatewayV2CfnProvisioner(service, mock(S3Service.class), mapper))
.build();
apiId = service.createApi(REGION, Map.of("name", "drop-api", "protocolType", "HTTP")).getApiId();
}
// ── Route ────────────────────────────────────────────────────────────────
@Test
void routeTargetDroppedFromTheTemplateReadsBackAbsent() throws Exception {
StackResource created = createRoute(",\"Target\":\"integrations/int-1\"");
assertEquals("integrations/int-1", route(created).getTarget());
updateRoute(created, ",\"Target\":\"integrations/int-1\"", "");
assertNull(route(created).getTarget());
}
@Test
void routeTargetMadeNoValueByRefReadsBackAbsent() throws Exception {
StackResource created = createRoute(",\"Target\":\"integrations/int-1\"");
updateRoute(created, ",\"Target\":\"integrations/int-1\"", ",\"Target\":{\"Ref\":\"AWS::NoValue\"}");
assertNull(route(created).getTarget());
}
@Test
void routeTargetMadeNoValueByAWholeFnIfReadsBackAbsent() throws Exception {
StackResource created = createRoute(",\"Target\":\"integrations/int-1\"");
updateRoute(created, ",\"Target\":\"integrations/int-1\"",
",\"Target\":{\"Fn::If\":[\"Off\",{\"Ref\":\"AWS::NoValue\"},\"integrations/int-1\"]}");
assertNull(route(created).getTarget());
}
@Test
void routeAuthorizerIdDroppedFromTheTemplateReadsBackAbsent() throws Exception {
String authorizerId = createAuthorizerId();
String declared = ",\"AuthorizationType\":\"NONE\",\"AuthorizerId\":\"" + authorizerId + "\"";
StackResource created = createRoute(declared);
assertEquals(authorizerId, route(created).getAuthorizerId());
updateRoute(created, declared, ",\"AuthorizationType\":\"NONE\"");
assertNull(route(created).getAuthorizerId());
}
@ParameterizedTest
@ValueSource(strings = {"JWT", "CUSTOM"})
void routeAuthorizerIdDroppedWhileTheRouteStaysProtectedIsKeptAndTargetIsStillCleared(String type)
throws Exception {
String authorizerId = createAuthorizerId();
String declared = ",\"AuthorizationType\":\"" + type + "\",\"AuthorizerId\":\"" + authorizerId
+ "\",\"Target\":\"integrations/int-1\"";
StackResource created = createRoute(declared);
updateRoute(created, declared, ",\"AuthorizationType\":\"" + type + "\"");
Route route = route(created);
assertEquals(type, route.getAuthorizationType());
assertEquals(authorizerId, route.getAuthorizerId());
assertNull(route.getTarget());
}
@Test
void routeAuthorizerIdDroppedWhileTheTypeBecomesJwtIsKept() throws Exception {
String authorizerId = createAuthorizerId();
String before = ",\"AuthorizationType\":\"AWS_IAM\",\"AuthorizerId\":\"" + authorizerId + "\"";
StackResource created = createRoute(before);
updateRoute(created, before, ",\"AuthorizationType\":\"JWT\"");
Route route = route(created);
assertEquals("JWT", route.getAuthorizationType());
assertEquals(authorizerId, route.getAuthorizerId());
}
@ParameterizedTest
@ValueSource(strings = {",\"AuthorizationType\":\"NONE\"", ",\"AuthorizationType\":\"AWS_IAM\"", ""})
void routeAuthorizerIdDroppedWhileTheRouteBecomesOpenOrIamIsCleared(String after) throws Exception {
String authorizerId = createAuthorizerId();
String before = ",\"AuthorizationType\":\"JWT\",\"AuthorizerId\":\"" + authorizerId + "\"";
StackResource created = createRoute(before);
updateRoute(created, before, after);
assertNull(route(created).getAuthorizerId());
}
@Test
void routeAuthorizationScopesDroppedFromTheTemplateReadBackAsAnEmptyList() throws Exception {
String declared = ",\"AuthorizationType\":\"JWT\",\"AuthorizationScopes\":[\"read\",\"write\"]";
StackResource created = createRoute(declared);
assertEquals(List.of("read", "write"), route(created).getAuthorizationScopes());
updateRoute(created, declared, ",\"AuthorizationType\":\"JWT\"");
assertEquals(List.of(), route(created).getAuthorizationScopes());
}
@Test
void routeAuthorizationTypeDroppedFromTheTemplateReadsBackNone() throws Exception {
String declared = ",\"AuthorizationType\":\"AWS_IAM\"";
StackResource created = createRoute(declared);
assertEquals("AWS_IAM", route(created).getAuthorizationType());
updateRoute(created, declared, "");
assertEquals("NONE", route(created).getAuthorizationType());
}
@Test
void routeKeyDroppedFromTheTemplateIsKept() throws Exception {
StackResource created = createRoute("");
provisioner.provision("Route", "AWS::ApiGatewayV2::Route",
mapper.readTree("{\"ApiId\":\"" + apiId + "\"}"), engine(mapper, REGION, Map.of()), REGION, ACCOUNT, "test-stack",
created.getPhysicalId(), created.getAttributes(), event -> { },
mapper.readTree("{" + ROUTE_BASE.formatted(apiId) + "}"));
assertEquals("GET /items", route(created).getRouteKey());
}
@Test
void routeTargetAndAuthorizerIdSetOutsideTheStackSurviveAnUnrelatedUpdate() throws Exception {
StackResource created = createRoute("");
String authorizerId = createAuthorizerId();
service.updateRoute(REGION, apiId, created.getPhysicalId(),
Map.of("target", "integrations/outside", "authorizerId", authorizerId));
updateRoute(created, "", ",\"AuthorizationType\":\"AWS_IAM\"");
Route route = route(created);
assertEquals("AWS_IAM", route.getAuthorizationType());
assertEquals("integrations/outside", route.getTarget());
assertEquals(authorizerId, route.getAuthorizerId());
}
@Test
void changedRouteTargetAndAuthorizerIdStillApply() throws Exception {
String first = createAuthorizerId();
String second = createAuthorizerId();
String before = ",\"AuthorizationType\":\"CUSTOM\",\"AuthorizerId\":\"" + first
+ "\",\"Target\":\"integrations/int-1\"";
StackResource created = createRoute(before);
updateRoute(created, before, ",\"AuthorizationType\":\"CUSTOM\",\"AuthorizerId\":\"" + second
+ "\",\"Target\":\"integrations/int-2\"");
Route route = route(created);
assertEquals("integrations/int-2", route.getTarget());
assertEquals(second, route.getAuthorizerId());
}
@Test
void changingTheAuthorizationTypeToNoneTogetherWithDroppingTheAuthorizerIdLeavesNoAuthorizer() throws Exception {
String authorizerId = createAuthorizerId();
String declared = ",\"AuthorizationType\":\"JWT\",\"AuthorizerId\":\"" + authorizerId
+ "\",\"AuthorizationScopes\":[\"read\"]";
StackResource created = createRoute(declared);
updateRoute(created, declared, "");
Route route = route(created);
assertEquals("NONE", route.getAuthorizationType());
assertNull(route.getAuthorizerId());
assertEquals(List.of(), route.getAuthorizationScopes());
}
@Test
void aDeclaredEmptyTargetReadsBackAsACreateWithAnEmptyTargetDoes() throws Exception {
StackResource declaredOnCreate = provisioner.provision("Other", "AWS::ApiGatewayV2::Route",
mapper.readTree("{\"ApiId\":\"" + apiId + "\",\"RouteKey\":\"GET /other\",\"Target\":\"\"}"),
engine(mapper, REGION, Map.of()), REGION, ACCOUNT, "test-stack", null, Map.of());
assertEquals("", route(declaredOnCreate).getTarget());
StackResource created = createRoute(",\"Target\":\"integrations/int-1\"");
updateRoute(created, ",\"Target\":\"integrations/int-1\"", ",\"Target\":\"\"");
assertEquals("", route(created).getTarget());
}
@Test
void droppingTheApiIdFromARouteFailsTheUpdateAndLeavesTheRouteAsItWas() throws Exception {
StackResource created = createRoute(",\"Target\":\"integrations/int-1\"");
StackResource result = provisioner.provision("Route", "AWS::ApiGatewayV2::Route",
mapper.readTree("{\"RouteKey\":\"GET /items\"}"), engine(mapper, REGION, Map.of()), REGION, ACCOUNT,
"test-stack", created.getPhysicalId(), created.getAttributes(), event -> { },
mapper.readTree("{" + ROUTE_BASE.formatted(apiId) + ",\"Target\":\"integrations/int-1\"}"));
assertTrue(result.getStatus().endsWith("_FAILED"), result.getStatus());
assertEquals("Route not found", result.getStatusReason());
assertEquals(created.getPhysicalId(), result.getPhysicalId());
assertEquals("integrations/int-1", route(created).getTarget());
}
// ── Authorizer ───────────────────────────────────────────────────────────
@Test
void authorizerResultTtlDroppedFromTheTemplateReadsBackAbsent() throws Exception {
String declared = ",\"AuthorizerResultTtlInSeconds\":300";
StackResource created = createAuthorizer(declared);
assertEquals(300, authorizer(created).getAuthorizerResultTtlInSeconds());
updateAuthorizer(created, declared, "");
assertNull(authorizer(created).getAuthorizerResultTtlInSeconds());
}
@Test
void authorizerResultTtlMadeNoValueByAWholeFnIfReadsBackAbsent() throws Exception {
String declared = ",\"AuthorizerResultTtlInSeconds\":300";
StackResource created = createAuthorizer(declared);
updateAuthorizer(created, declared,
",\"AuthorizerResultTtlInSeconds\":{\"Fn::If\":[\"Off\",{\"Ref\":\"AWS::NoValue\"},300]}");
assertNull(authorizer(created).getAuthorizerResultTtlInSeconds());
}
@Test
void authorizerEnableSimpleResponsesDroppedFromTheTemplateReadsBackAbsent() throws Exception {
String declared = ",\"EnableSimpleResponses\":true";
StackResource created = createAuthorizer(declared);
assertEquals(Boolean.TRUE, authorizer(created).getEnableSimpleResponses());
updateAuthorizer(created, declared, "");
assertNull(authorizer(created).getEnableSimpleResponses());
}
@Test
void authorizerEnableSimpleResponsesMadeNoValueByRefReadsBackAbsent() throws Exception {
String declared = ",\"EnableSimpleResponses\":true";
StackResource created = createAuthorizer(declared);
updateAuthorizer(created, declared, ",\"EnableSimpleResponses\":{\"Ref\":\"AWS::NoValue\"}");
assertNull(authorizer(created).getEnableSimpleResponses());
}
@Test
void authorizerIdentitySourceDroppedFromTheTemplateReadsBackAsAnEmptyList() throws Exception {
String declared = ",\"IdentitySource\":[\"$request.header.Authorization\"]";
StackResource created = createAuthorizer(declared);
assertEquals(List.of("$request.header.Authorization"), authorizer(created).getIdentitySource());
updateAuthorizer(created, declared, "");
assertEquals(List.of(), authorizer(created).getIdentitySource());
}
@Test
void authorizerNameAndTypeDroppedFromTheTemplateAreKept() throws Exception {
StackResource created = createAuthorizer("");
updateAuthorizerFrom(created, "{" + AUTHORIZER_BASE.formatted(apiId) + "}",
"{\"ApiId\":\"" + apiId + "\"," + LAMBDA_SETTINGS + "}");
Authorizer authorizer = authorizer(created);
assertEquals("auth", authorizer.getName());
assertEquals("REQUEST", authorizer.getAuthorizerType());
}
@Test
void authorizerUriAndPayloadFormatVersionDroppedFromTheTemplateReadBackAbsent() throws Exception {
StackResource created = createAuthorizer("");
assertEquals(LAMBDA_URI, authorizer(created).getAuthorizerUri());
updateAuthorizerFrom(created, "{" + AUTHORIZER_BASE.formatted(apiId) + "}",
"{\"ApiId\":\"" + apiId + "\",\"Name\":\"auth\",\"AuthorizerType\":\"REQUEST\"}");
Authorizer authorizer = authorizer(created);
assertNull(authorizer.getAuthorizerUri());
assertNull(authorizer.getAuthorizerPayloadFormatVersion());
}
@Test
void authorizerJwtConfigurationDroppedFromTheTemplateReadsBackAbsent() throws Exception {
StackResource created = createJwtAuthorizer(JWT_CONFIGURATION);
assertEquals("https://issuer.example", authorizer(created).getJwtConfiguration().issuer());
updateAuthorizerFrom(created, jwtAuthorizer(JWT_CONFIGURATION), jwtAuthorizer(""));
assertNull(authorizer(created).getJwtConfiguration());
}
@Test
void changingAJwtAuthorizerToRequestWithoutJwtConfigurationLeavesNoJwtConfiguration() throws Exception {
StackResource created = createJwtAuthorizer(JWT_CONFIGURATION);
updateAuthorizerFrom(created, jwtAuthorizer(JWT_CONFIGURATION),
"{\"ApiId\":\"" + apiId + "\",\"Name\":\"jwt\",\"AuthorizerType\":\"REQUEST\","
+ LAMBDA_SETTINGS + "}");
Authorizer authorizer = authorizer(created);
assertEquals("REQUEST", authorizer.getAuthorizerType());
assertNull(authorizer.getJwtConfiguration());
assertEquals(LAMBDA_URI, authorizer.getAuthorizerUri());
}
@Test
void changingARequestAuthorizerToJwtWithoutUriAndPayloadVersionLeavesNeither() throws Exception {
StackResource created = createAuthorizer("");
updateAuthorizerFrom(created, "{" + AUTHORIZER_BASE.formatted(apiId) + "}", jwtAuthorizer(JWT_CONFIGURATION));
Authorizer authorizer = authorizer(created);
assertEquals("JWT", authorizer.getAuthorizerType());
assertNull(authorizer.getAuthorizerUri());
assertNull(authorizer.getAuthorizerPayloadFormatVersion());
assertEquals("https://issuer.example", authorizer.getJwtConfiguration().issuer());
}
@Test
void droppingTheApiIdFromAnAuthorizerFailsTheUpdateAndLeavesTheAuthorizerAsItWas() throws Exception {
StackResource created = createAuthorizer(",\"AuthorizerResultTtlInSeconds\":300");
StackResource result = updateAuthorizerFrom(created,
"{" + AUTHORIZER_BASE.formatted(apiId) + ",\"AuthorizerResultTtlInSeconds\":300}",
"{\"Name\":\"auth\",\"AuthorizerType\":\"REQUEST\"}");
assertTrue(result.getStatus().endsWith("_FAILED"), result.getStatus());
assertEquals("Authorizer not found", result.getStatusReason());
assertEquals(created.getPhysicalId(), result.getPhysicalId());
assertEquals(300, authorizer(created).getAuthorizerResultTtlInSeconds());
}
@Test
void authorizerSettingsSetOutsideTheStackSurviveAnUnrelatedUpdate() throws Exception {
StackResource created = createAuthorizer("");
service.updateAuthorizer(REGION, apiId, created.getPhysicalId(),
Map.of("authorizerResultTtlInSeconds", 120, "enableSimpleResponses", true));
updateAuthorizer(created, "", ",\"IdentitySource\":[\"$request.header.X-Key\"]");
Authorizer authorizer = authorizer(created);
assertEquals(List.of("$request.header.X-Key"), authorizer.getIdentitySource());
assertEquals(120, authorizer.getAuthorizerResultTtlInSeconds());
assertEquals(Boolean.TRUE, authorizer.getEnableSimpleResponses());
}
@Test
void changedAuthorizerResultTtlAndEnableSimpleResponsesStillApply() throws Exception {
String before = ",\"AuthorizerResultTtlInSeconds\":300,\"EnableSimpleResponses\":true";
StackResource created = createAuthorizer(before);
updateAuthorizer(created, before, ",\"AuthorizerResultTtlInSeconds\":60,\"EnableSimpleResponses\":false");
Authorizer authorizer = authorizer(created);
assertEquals(60, authorizer.getAuthorizerResultTtlInSeconds());
assertEquals(Boolean.FALSE, authorizer.getEnableSimpleResponses());
}
// ── helpers ──────────────────────────────────────────────────────────────
/** A route with the base properties plus {@code extra}, a JSON fragment that starts with a comma or is empty. */
private StackResource createRoute(String extra) throws Exception {
return provisioner.provision("Route", "AWS::ApiGatewayV2::Route",
mapper.readTree("{" + ROUTE_BASE.formatted(apiId) + extra + "}"), engine(mapper, REGION, Map.of()), REGION, ACCOUNT,
"test-stack", null, Map.of());
}
/** Updates the route from the template with {@code previousExtra} to the one with {@code currentExtra}. */
private void updateRoute(StackResource created, String previousExtra, String currentExtra) throws Exception {
CloudFormationTemplateEngine engine = engine(mapper, REGION, Map.of("Off", true));
// CloudFormationService omits NoValue before any provisioner runs, so the provisioner never sees it.
provisioner.provision("Route", "AWS::ApiGatewayV2::Route",
engine.omitNoValue(mapper.readTree("{" + ROUTE_BASE.formatted(apiId) + currentExtra + "}")), engine,
REGION, ACCOUNT, "test-stack", created.getPhysicalId(), created.getAttributes(), event -> { },
mapper.readTree("{" + ROUTE_BASE.formatted(apiId) + previousExtra + "}"));
}
private StackResource createAuthorizer(String extra) throws Exception {
return provisioner.provision("Authorizer", "AWS::ApiGatewayV2::Authorizer",
mapper.readTree("{" + AUTHORIZER_BASE.formatted(apiId) + extra + "}"), engine(mapper, REGION, Map.of()), REGION, ACCOUNT,
"test-stack", null, Map.of());
}
private void updateAuthorizer(StackResource created, String previousExtra, String currentExtra)
throws Exception {
updateAuthorizerFrom(created, "{" + AUTHORIZER_BASE.formatted(apiId) + previousExtra + "}",
"{" + AUTHORIZER_BASE.formatted(apiId) + currentExtra + "}");
}
/** Updates the authorizer from one full property object to another; NoValue is omitted as the service does. */
private StackResource updateAuthorizerFrom(StackResource created, String previous, String current)
throws Exception {
CloudFormationTemplateEngine engine = engine(mapper, REGION, Map.of("Off", true));
return provisioner.provision("Authorizer", "AWS::ApiGatewayV2::Authorizer",
engine.omitNoValue(mapper.readTree(current)), engine, REGION, ACCOUNT, "test-stack",
created.getPhysicalId(), created.getAttributes(), event -> { }, mapper.readTree(previous));
}
private String jwtAuthorizer(String jwtConfiguration) {
return "{\"ApiId\":\"" + apiId + "\",\"Name\":\"jwt\",\"AuthorizerType\":\"JWT\","
+ "\"IdentitySource\":[\"$request.header.Authorization\"]" + jwtConfiguration + "}";
}
private StackResource createJwtAuthorizer(String jwtConfiguration) throws Exception {
return provisioner.provision("Authorizer", "AWS::ApiGatewayV2::Authorizer",
mapper.readTree(jwtAuthorizer(jwtConfiguration)), engine(mapper, REGION, Map.of()), REGION, ACCOUNT,
"test-stack", null, Map.of());
}
private String createAuthorizerId() throws Exception {
return createAuthorizer("").getPhysicalId();
}
private Route route(StackResource resource) {
return service.getRoute(REGION, apiId, resource.getPhysicalId());
}
private Authorizer authorizer(StackResource resource) {
return service.getAuthorizer(REGION, apiId, resource.getPhysicalId());
}
}
@@ -1,7 +1,9 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
import io.floci.aws.services.apigatewayv2.model.Authorizer;
import io.floci.aws.services.apigatewayv2.model.Integration;
import io.floci.aws.services.apigatewayv2.model.Route;
import io.floci.aws.services.apigatewayv2.model.Stage;
import io.floci.aws.services.cloudformation.model.Stack;
import io.floci.aws.services.cloudformation.model.StackResource;
@@ -11,7 +13,8 @@ import static io.restassured.RestAssured.given;
/**
* What the AWS::ApiGatewayV2 stack integration tests share: driving a stack through the query API,
* and reading back the stack and its {@code Integration} resource.
* and reading back the stack and its {@code Integration}, {@code Route}, {@code Authorizer} and
* {@code Stage} resources.
*/
final class ApiGatewayV2StackTestSupport {
@@ -31,6 +34,18 @@ final class ApiGatewayV2StackTestSupport {
return apiGatewayV2Service.getIntegration(REGION, api.getPhysicalId(), integration.getPhysicalId());
}
static Route route(ApiGatewayV2Service apiGatewayV2Service, Stack stack) {
StackResource api = stack.getResources().get("HttpApi");
StackResource route = stack.getResources().get("Route");
return apiGatewayV2Service.getRoute(REGION, api.getPhysicalId(), route.getPhysicalId());
}
static Authorizer authorizer(ApiGatewayV2Service apiGatewayV2Service, Stack stack) {
StackResource api = stack.getResources().get("HttpApi");
StackResource authorizer = stack.getResources().get("Authorizer");
return apiGatewayV2Service.getAuthorizer(REGION, api.getPhysicalId(), authorizer.getPhysicalId());
}
static Stage stage(ApiGatewayV2Service apiGatewayV2Service, Stack stack) {
StackResource api = stack.getResources().get("HttpApi");
StackResource stage = stack.getResources().get("Stage");
@@ -183,6 +183,8 @@ import io.floci.aws.services.wafv2.WafV2Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* Builds {@link CfnResourceDispatcher} for tests without a wall of positional nulls.
@@ -203,6 +205,13 @@ final class CfnProvisionerFixture {
private CfnProvisionerFixture() {
}
/** The template engine a provisioner test hands to {@code provision}: fixed account and stack, no outputs. */
static CloudFormationTemplateEngine engine(ObjectMapper mapper, String region, Map<String, Boolean> conditions) {
return new CloudFormationTemplateEngine("000000000000", region, "test-stack", "stack/id",
Map.of(), Map.of(), Map.of(), conditions, Map.of(), mapper,
(Function<String, String>) name -> null);
}
static Builder builder() {
return new Builder();
}
@@ -0,0 +1,302 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
import io.floci.aws.services.apigatewayv2.model.Authorizer;
import io.floci.aws.services.apigatewayv2.model.Route;
import io.floci.aws.services.cloudformation.model.Stack;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.REGION;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.authorizer;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.route;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.stack;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.stackAction;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The settings of an AWS::ApiGatewayV2::Route and an AWS::ApiGatewayV2::Authorizer through a real
* stack: a setting the template drops on update reads back through GetRoute and GetAuthorizer as it
* does on a create without it, a setting set through the API on a member the template never declared
* survives an unrelated update, and a changed value is applied. The members AWS requires stay.
*/
@QuarkusTest
class CloudFormationApiGatewayV2RouteAuthorizerDropIntegrationTest {
private static final String LAMBDA_URI = "arn:aws:lambda:us-east-1:000000000000:function:auth";
private static final String ROUTE_SETTINGS =
",\"AuthorizationType\":\"CUSTOM\",\"AuthorizerId\":{\"Ref\":\"Authorizer\"},"
+ "\"Target\":\"integrations/int-1\"";
private static final String AUTHORIZER_SETTINGS =
",\"AuthorizerResultTtlInSeconds\":300,\"EnableSimpleResponses\":true";
@Inject
ApiGatewayV2Service apiGatewayV2Service;
@Inject
CloudFormationService cloudFormationService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void routeSettingsTheTemplateDropsReadBackAsOnACreateWithoutThem() {
String stackName = "route-drop-stack";
stackAction("CreateStack", stackName, template(ROUTE_SETTINGS, ""));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
Stack created = stack(cloudFormationService, stackName);
Route route = route(apiGatewayV2Service, created);
assertEquals("integrations/int-1", route.getTarget());
assertEquals(created.getResources().get("Authorizer").getPhysicalId(), route.getAuthorizerId());
stackAction("UpdateStack", stackName, template("", ""));
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
Stack updated = stack(cloudFormationService, stackName);
Route dropped = route(apiGatewayV2Service, updated);
assertNull(dropped.getTarget());
assertNull(dropped.getAuthorizerId());
assertEquals("NONE", dropped.getAuthorizationType());
assertEquals("GET /items", dropped.getRouteKey());
getRouteResponse(updated)
.body("target", nullValue())
.body("authorizerId", nullValue())
.body("authorizationType", equalTo("NONE"))
.body("routeKey", equalTo("GET /items"));
}
@Test
void routeSettingsMadeNoValueByAConditionReadBackAsOnACreateWithoutThem() {
String stackName = "route-novalue-stack";
stackAction("CreateStack", stackName, template(ROUTE_SETTINGS, ""));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
Stack created = stack(cloudFormationService, stackName);
stackAction("UpdateStack", stackName, template(
",\"AuthorizationType\":\"CUSTOM\","
+ "\"AuthorizerId\":{\"Ref\":\"AWS::NoValue\"},"
+ "\"Target\":{\"Fn::If\":[\"Off\",{\"Ref\":\"AWS::NoValue\"},\"integrations/int-1\"]}", ""));
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
Stack updated = stack(cloudFormationService, stackName);
Route route = route(apiGatewayV2Service, updated);
assertNull(route.getTarget());
assertEquals(created.getResources().get("Authorizer").getPhysicalId(), route.getAuthorizerId());
getRouteResponse(updated).body("target", nullValue())
.body("authorizerId", equalTo(created.getResources().get("Authorizer").getPhysicalId()));
}
@Test
void authorizationScopesTheTemplateDropsReadBackEmpty() {
String stackName = "route-scopes-drop-stack";
stackAction("CreateStack", stackName,
template(",\"AuthorizationType\":\"JWT\",\"AuthorizerId\":{\"Ref\":\"Authorizer\"},"
+ "\"AuthorizationScopes\":[\"read\"]", ""));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
assertEquals(List.of("read"), route(apiGatewayV2Service, stack(cloudFormationService, stackName))
.getAuthorizationScopes());
stackAction("UpdateStack", stackName,
template(",\"AuthorizationType\":\"JWT\",\"AuthorizerId\":{\"Ref\":\"Authorizer\"}", ""));
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
List<String> scopes = route(apiGatewayV2Service, stack(cloudFormationService, stackName))
.getAuthorizationScopes();
assertTrue(scopes == null || scopes.isEmpty(), "expected no scopes, got " + scopes);
}
@Test
void routeTargetAndAuthorizerIdSetOutsideTheStackSurviveAnUnrelatedUpdate() {
String stackName = "route-outside-stack";
stackAction("CreateStack", stackName, template("", ""));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
Stack created = stack(cloudFormationService, stackName);
String authorizerId = created.getResources().get("Authorizer").getPhysicalId();
apiGatewayV2Service.updateRoute(REGION, created.getResources().get("HttpApi").getPhysicalId(),
created.getResources().get("Route").getPhysicalId(),
Map.of("target", "integrations/outside", "authorizerId", authorizerId));
stackAction("UpdateStack", stackName, template(",\"AuthorizationType\":\"AWS_IAM\"", ""));
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
Stack updated = stack(cloudFormationService, stackName);
Route route = route(apiGatewayV2Service, updated);
assertEquals("AWS_IAM", route.getAuthorizationType());
assertEquals("integrations/outside", route.getTarget());
assertEquals(authorizerId, route.getAuthorizerId());
getRouteResponse(updated)
.body("target", equalTo("integrations/outside"))
.body("authorizerId", equalTo(authorizerId));
}
@Test
void aChangedRouteTargetIsApplied() {
String stackName = "route-changed-stack";
stackAction("CreateStack", stackName, template(",\"Target\":\"integrations/int-1\"", ""));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
stackAction("UpdateStack", stackName, template(",\"Target\":\"integrations/int-2\"", ""));
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
Stack updated = stack(cloudFormationService, stackName);
assertEquals("integrations/int-2", route(apiGatewayV2Service, updated).getTarget());
getRouteResponse(updated).body("target", equalTo("integrations/int-2"));
}
@Test
void authorizerSettingsTheTemplateDropsReadBackAsOnACreateWithoutThem() {
String stackName = "authorizer-drop-stack";
stackAction("CreateStack", stackName, template("", AUTHORIZER_SETTINGS));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
Authorizer created = authorizer(apiGatewayV2Service, stack(cloudFormationService, stackName));
assertEquals(300, created.getAuthorizerResultTtlInSeconds());
assertEquals(Boolean.TRUE, created.getEnableSimpleResponses());
stackAction("UpdateStack", stackName, template("", ""));
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
Stack updated = stack(cloudFormationService, stackName);
Authorizer dropped = authorizer(apiGatewayV2Service, updated);
assertNull(dropped.getAuthorizerResultTtlInSeconds());
assertNull(dropped.getEnableSimpleResponses());
assertEquals("auth", dropped.getName());
assertEquals("REQUEST", dropped.getAuthorizerType());
assertEquals(LAMBDA_URI, dropped.getAuthorizerUri());
assertEquals("2.0", dropped.getAuthorizerPayloadFormatVersion());
getAuthorizerResponse(updated)
.body("authorizerResultTtlInSeconds", nullValue())
.body("enableSimpleResponses", nullValue())
.body("name", equalTo("auth"))
.body("authorizerType", equalTo("REQUEST"))
.body("authorizerUri", equalTo(LAMBDA_URI))
.body("authorizerPayloadFormatVersion", equalTo("2.0"));
}
@Test
void authorizerSettingsMadeNoValueByAConditionReadBackAsOnACreateWithoutThem() {
String stackName = "authorizer-novalue-stack";
stackAction("CreateStack", stackName, template("", AUTHORIZER_SETTINGS));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
stackAction("UpdateStack", stackName, template("",
",\"AuthorizerResultTtlInSeconds\":{\"Fn::If\":[\"Off\",{\"Ref\":\"AWS::NoValue\"},300]},"
+ "\"EnableSimpleResponses\":{\"Ref\":\"AWS::NoValue\"}"));
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
Stack updated = stack(cloudFormationService, stackName);
Authorizer authorizer = authorizer(apiGatewayV2Service, updated);
assertNull(authorizer.getAuthorizerResultTtlInSeconds());
assertNull(authorizer.getEnableSimpleResponses());
getAuthorizerResponse(updated)
.body("authorizerResultTtlInSeconds", nullValue())
.body("enableSimpleResponses", nullValue());
}
@Test
void authorizerIdentitySourceTheTemplateDropsReadsBackEmpty() {
String stackName = "authorizer-identity-drop-stack";
stackAction("CreateStack", stackName,
template("", ",\"IdentitySource\":[\"$request.header.Authorization\"]"));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
assertEquals(List.of("$request.header.Authorization"),
authorizer(apiGatewayV2Service, stack(cloudFormationService, stackName)).getIdentitySource());
stackAction("UpdateStack", stackName, template("", ""));
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
List<String> source = authorizer(apiGatewayV2Service, stack(cloudFormationService, stackName))
.getIdentitySource();
assertTrue(source == null || source.isEmpty(), "expected no identity source, got " + source);
}
@Test
void authorizerSettingsSetOutsideTheStackSurviveAnUnrelatedUpdate() {
String stackName = "authorizer-outside-stack";
stackAction("CreateStack", stackName, template("", ""));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
Stack created = stack(cloudFormationService, stackName);
apiGatewayV2Service.updateAuthorizer(REGION, created.getResources().get("HttpApi").getPhysicalId(),
created.getResources().get("Authorizer").getPhysicalId(),
Map.of("authorizerResultTtlInSeconds", 120, "enableSimpleResponses", true));
stackAction("UpdateStack", stackName,
template("", ",\"IdentitySource\":[\"$request.header.X-Key\"]"));
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
Stack updated = stack(cloudFormationService, stackName);
Authorizer authorizer = authorizer(apiGatewayV2Service, updated);
assertEquals(List.of("$request.header.X-Key"), authorizer.getIdentitySource());
assertEquals(120, authorizer.getAuthorizerResultTtlInSeconds());
assertEquals(Boolean.TRUE, authorizer.getEnableSimpleResponses());
getAuthorizerResponse(updated)
.body("authorizerResultTtlInSeconds", equalTo(120))
.body("enableSimpleResponses", equalTo(true));
}
@Test
void changedAuthorizerSettingsAreApplied() {
String stackName = "authorizer-changed-stack";
stackAction("CreateStack", stackName, template("", AUTHORIZER_SETTINGS));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
stackAction("UpdateStack", stackName,
template("", ",\"AuthorizerResultTtlInSeconds\":60,\"EnableSimpleResponses\":false"));
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
Stack updated = stack(cloudFormationService, stackName);
Authorizer authorizer = authorizer(apiGatewayV2Service, updated);
assertEquals(60, authorizer.getAuthorizerResultTtlInSeconds());
assertEquals(Boolean.FALSE, authorizer.getEnableSimpleResponses());
getAuthorizerResponse(updated)
.body("authorizerResultTtlInSeconds", equalTo(60))
.body("enableSimpleResponses", equalTo(false));
}
private ValidatableResponse getRouteResponse(Stack stack) {
String apiId = stack.getResources().get("HttpApi").getPhysicalId();
String routeId = stack.getResources().get("Route").getPhysicalId();
return given().when().get("/v2/apis/" + apiId + "/routes/" + routeId)
.then().statusCode(200);
}
private ValidatableResponse getAuthorizerResponse(Stack stack) {
String apiId = stack.getResources().get("HttpApi").getPhysicalId();
String authorizerId = stack.getResources().get("Authorizer").getPhysicalId();
return given().when().get("/v2/apis/" + apiId + "/authorizers/" + authorizerId)
.then().statusCode(200);
}
/**
* An HTTP API, a REQUEST authorizer and a route, with no container involved. {@code routeSettings}
* and {@code authorizerSettings} add properties to the route and the authorizer, as JSON fragments
* that start with a comma.
*/
private static String template(String routeSettings, String authorizerSettings) {
return """
{"Conditions":{"Off":{"Fn::Equals":["a","a"]}},
"Resources":{
"HttpApi":{"Type":"AWS::ApiGatewayV2::Api","Properties":{
"Name":"route-authorizer-drop-api","ProtocolType":"HTTP"}},
"Authorizer":{"Type":"AWS::ApiGatewayV2::Authorizer","Properties":{
"ApiId":{"Ref":"HttpApi"},"Name":"auth","AuthorizerType":"REQUEST",
"AuthorizerUri":"%s","AuthorizerPayloadFormatVersion":"2.0"%s}},
"Route":{"Type":"AWS::ApiGatewayV2::Route","Properties":{
"ApiId":{"Ref":"HttpApi"},"RouteKey":"GET /items"%s}}}}
""".formatted(LAMBDA_URI, authorizerSettings, routeSettings);
}
}