diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 2fbb7b44bb..975655dd97 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -765,9 +765,11 @@ regenerates it from AWS's published schemas, and `cfn-schema-drift.yml` compares A property the previous template declared and the new template drops is cleared on `UpdateStack`, goes back to its create default, or is kept, on the AppSync resources, the EC2 networking types (`Subnet`, `InternetGateway`, `RouteTable`, `NatGateway`, `EIP`, `PrefixList`), an -`AWS::ApiGatewayV2::Stage`, an `AWS::EC2::Instance`, an `AWS::ECS::Service`, an `AWS::Lambda::Alias`, an -`AWS::SecretsManager::Secret`, an `AWS::Cognito::UserPoolGroup` and an `AWS::CloudTrail::Trail`. Kept: required members -(`AuthenticationType`, `Type`, a function's `DataSourceName`), a data source's and a function's `Name`, +`AWS::ApiGatewayV2::Stage`, `Route` and `Authorizer`, an `AWS::EC2::Instance`, an `AWS::ECS::Service`, an +`AWS::Lambda::Alias`, an `AWS::SecretsManager::Secret`, an `AWS::Cognito::UserPoolGroup` and an +`AWS::CloudTrail::Trail`. Kept: required members (`AuthenticationType`, `Type`, a function's +`DataSourceName`, a `Route`'s `RouteKey`, an authorizer's `Name` and `AuthorizerType`), a data source's +and a function's `Name`, an API key's `Expires`, a GraphQL API's `ApiType` and `Visibility`, a UNIT resolver's `DataSourceName`, a `NatGateway`'s `PrivateIpAddress`, a `PrefixList`'s `MaxEntries`, a `Stage`'s `StageName` and an `Instance`'s `SecurityGroupIds`, `NetworkInterfaces` and `LaunchTemplate`. A dropped `LaunchTemplate` keeps @@ -777,17 +779,22 @@ their defaults, and the instance profile it supplied is disassociated. A service `ServiceRegistries` are kept, and its `DesiredCount` goes back to 1. A service's dropped `DeploymentConfiguration` is cleared. An empty `CapacityProviderStrategy` or `ServiceRegistries` in the template clears it; a failed stabilisation puts the prior values back, and a deployment configuration -the service did not have goes back to none. A `Stage`'s dropped `StageVariables` become empty. An `Instance`'s dropped `UserData` is +the service did not have goes back to none. A `Stage`'s dropped `StageVariables` become empty. A `Route`'s +dropped `Target` and `AuthorizerId`, and an `Authorizer`'s dropped `AuthorizerUri`, +`AuthorizerPayloadFormatVersion`, `JwtConfiguration`, `AuthorizerResultTtlInSeconds` and +`EnableSimpleResponses`, read back absent, as on a create without them. A dropped `AuthorizerId` is kept +while the route's authorization type stays `JWT` or `CUSTOM`. An `Instance`'s dropped `UserData` is cleared: a running instance is stopped for the rewrite and started again, and a stopped one stays stopped. An `Alias`'s, a `Secret`'s and a `UserPoolGroup`'s dropped `Description` and a `Trail`'s dropped `S3KeyPrefix` are cleared. A dropped `RoutingConfig` removes the alias weights. The other members of those four types are kept or create-only when dropped, as the drop policy table lists them, except a `Secret`'s `Tags`, which every update drives to the template. -An update that drops a `PrefixList`'s `AddressFamily` or `PrefixListName` fails. Create-only members are -not cleared either. +An update that drops a `PrefixList`'s `AddressFamily` or `PrefixListName`, or a `Route`'s or +`Authorizer`'s `ApiId`, fails. Create-only members are not cleared either. A property the stack never declared keeps the value set outside it, with these exceptions, which every -update drives to the template: a GraphQL API's `Tags` and `EnvironmentVariables`, a Secret's `Tags` and -a Lambda alias's `RoutingConfig`. The table says so on those rows. The three `NatGateway` `Secondary*` properties count as one +update drives to the template: a GraphQL API's `Tags` and `EnvironmentVariables`, a Secret's `Tags`, a +Lambda alias's `RoutingConfig`, a `Route`'s `AuthorizationScopes` and an `Authorizer`'s +`IdentitySource`. The table says so on those rows. The three `NatGateway` `Secondary*` properties count as one address set: when the new or the previous template declares any of them, an update brings all three to the template. diff --git a/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2Service.java b/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2Service.java index ef3fe09922..2810182a40 100644 --- a/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2Service.java +++ b/src/main/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2Service.java @@ -494,6 +494,26 @@ public class ApiGatewayV2Service { return auth; } + /** + * Sets the URI, payload format version, JWT configuration, result TTL and simple-responses flag + * exactly as given, null included. UpdateAuthorizer keeps a field the request leaves out, so it + * cannot remove one that CloudFormation dropped. + */ + public Authorizer replaceAuthorizerSettings(String region, String apiId, String authorizerId, + String authorizerUri, String authorizerPayloadFormatVersion, + Authorizer.JwtConfiguration jwtConfiguration, + Integer authorizerResultTtlInSeconds, + Boolean enableSimpleResponses) { + Authorizer auth = getAuthorizer(region, apiId, authorizerId); + auth.setAuthorizerUri(authorizerUri); + auth.setAuthorizerPayloadFormatVersion(authorizerPayloadFormatVersion); + auth.setJwtConfiguration(jwtConfiguration); + auth.setAuthorizerResultTtlInSeconds(authorizerResultTtlInSeconds); + auth.setEnableSimpleResponses(enableSimpleResponses); + authorizerStore.put(authorizerKey(region, apiId, authorizerId), auth); + return auth; + } + // AuthorizerResultTtlInSeconds is modeled as an integer in [0, 3600]. doubleValue() keeps the // bounds check exact for a Long or BigInteger body value that intValue() would wrap into range. static Integer authorizerResultTtl(Object value) { @@ -609,6 +629,19 @@ public class ApiGatewayV2Service { return route; } + /** + * Sets the authorizer id and the target exactly as given, null included. UpdateRoute keeps a + * field the request leaves out, so it cannot remove one that CloudFormation dropped. + */ + public Route replaceRouteLinks(String region, String apiId, String routeId, String authorizerId, + String target) { + Route route = getRoute(region, apiId, routeId); + route.setAuthorizerId(authorizerId); + route.setTarget(target); + routeStore.put(routeKey(region, apiId, routeId), route); + return route; + } + private void ensureRouteKeyAvailable(String region, String apiId, String requestedRouteKey, String currentRouteId) { if (requestedRouteKey == null) { diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java index 1ff1108cea..6b35b311cb 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java @@ -855,6 +855,22 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { authorizer = apiGatewayV2Service.createAuthorizer(region, apiId, req); } else { authorizer = apiGatewayV2Service.updateAuthorizer(region, apiId, r.getPhysicalId(), req); + Set dropped = ctx.droppedProperties(props); + if (dropped.contains("AuthorizerUri") || dropped.contains("AuthorizerPayloadFormatVersion") + || dropped.contains("JwtConfiguration") || dropped.contains("AuthorizerResultTtlInSeconds") + || dropped.contains("EnableSimpleResponses")) { + // UpdateAuthorizer keeps a field it is not given, so a dropped one is cleared here and + // the others keep what the update left, a value set outside the stack included. + authorizer = apiGatewayV2Service.replaceAuthorizerSettings(region, apiId, r.getPhysicalId(), + dropped.contains("AuthorizerUri") ? null : authorizer.getAuthorizerUri(), + dropped.contains("AuthorizerPayloadFormatVersion") + ? null : authorizer.getAuthorizerPayloadFormatVersion(), + dropped.contains("JwtConfiguration") ? null : authorizer.getJwtConfiguration(), + dropped.contains("AuthorizerResultTtlInSeconds") + ? null : authorizer.getAuthorizerResultTtlInSeconds(), + dropped.contains("EnableSimpleResponses") + ? null : authorizer.getEnableSimpleResponses()); + } } r.setPhysicalId(authorizer.getAuthorizerId()); r.getAttributes().put("AuthorizerId", authorizer.getAuthorizerId()); @@ -881,6 +897,18 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { route = apiGatewayV2Service.createRoute(region, apiId, req); } else { route = apiGatewayV2Service.updateRoute(region, apiId, r.getPhysicalId(), req); + Set dropped = ctx.droppedProperties(props); + if (dropped.contains("AuthorizerId") || dropped.contains("Target")) { + // UpdateRoute keeps a field it is not given, so a dropped one is cleared here and the + // other keeps what the update left, a value set outside the stack included. + // A route that stays JWT or CUSTOM keeps its authorizer: without it the route would be + // served without any authorizer. + String type = route.getAuthorizationType(); + boolean protectedRoute = "JWT".equalsIgnoreCase(type) || "CUSTOM".equalsIgnoreCase(type); + route = apiGatewayV2Service.replaceRouteLinks(region, apiId, r.getPhysicalId(), + dropped.contains("AuthorizerId") && !protectedRoute ? null : route.getAuthorizerId(), + dropped.contains("Target") ? null : route.getTarget()); + } } r.setPhysicalId(route.getRouteId()); r.getAttributes().put("RouteId", route.getRouteId()); diff --git a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayV2ApiMappingServiceTest.java b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayV2ApiMappingServiceTest.java index 308508e78c..fe15ecac36 100644 --- a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayV2ApiMappingServiceTest.java +++ b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayV2ApiMappingServiceTest.java @@ -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, diff --git a/src/test/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2ServiceFixture.java b/src/test/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2ServiceFixture.java new file mode 100644 index 0000000000..0ca01bc489 --- /dev/null +++ b/src/test/java/io/floci/aws/services/apigatewayv2/ApiGatewayV2ServiceFixture.java @@ -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)); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java index 4bfb755b92..2d3a50c5de 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java @@ -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 conditions) { - return new CloudFormationTemplateEngine("000000000000", REGION, "test-stack", "stack/id", - Map.of(), Map.of(), Map.of(), conditions, Map.of(), mapper, - (Function) name -> null); + return CfnProvisionerFixture.engine(mapper, REGION, conditions); } private static Route route(String id, String routeKey) { diff --git a/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2RouteAuthorizerDropTest.java b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2RouteAuthorizerDropTest.java new file mode 100644 index 0000000000..42c39d25a4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2RouteAuthorizerDropTest.java @@ -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()); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2StackTestSupport.java b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2StackTestSupport.java index 662b4eaf96..9a339635e0 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2StackTestSupport.java +++ b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayV2StackTestSupport.java @@ -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"); diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java index 62218ee4aa..1ea6aee03c 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java @@ -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 conditions) { + return new CloudFormationTemplateEngine("000000000000", region, "test-stack", "stack/id", + Map.of(), Map.of(), Map.of(), conditions, Map.of(), mapper, + (Function) name -> null); + } + static Builder builder() { return new Builder(); } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationApiGatewayV2RouteAuthorizerDropIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationApiGatewayV2RouteAuthorizerDropIntegrationTest.java new file mode 100644 index 0000000000..1843559a74 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationApiGatewayV2RouteAuthorizerDropIntegrationTest.java @@ -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 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 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); + } +} diff --git a/src/test/resources/cloudformation/drop-policy.tsv b/src/test/resources/cloudformation/drop-policy.tsv index 5f9c6ab4c5..952abccb5b 100644 --- a/src/test/resources/cloudformation/drop-policy.tsv +++ b/src/test/resources/cloudformation/drop-policy.tsv @@ -1,3 +1,18 @@ +AWS::ApiGatewayV2::Authorizer ApiId create-only a drop fails: the authorizer is not found +AWS::ApiGatewayV2::Authorizer AuthorizerPayloadFormatVersion clear a create without it accepts the authorizer +AWS::ApiGatewayV2::Authorizer AuthorizerResultTtlInSeconds clear the field reads back absent +AWS::ApiGatewayV2::Authorizer AuthorizerType keep:required by AWS +AWS::ApiGatewayV2::Authorizer AuthorizerUri clear a create without it accepts the authorizer +AWS::ApiGatewayV2::Authorizer EnableSimpleResponses clear the field reads back absent +AWS::ApiGatewayV2::Authorizer IdentitySource clear an update also clears it when the stack never declared it, so a value set outside the stack is lost +AWS::ApiGatewayV2::Authorizer JwtConfiguration clear a create without it accepts the authorizer +AWS::ApiGatewayV2::Authorizer Name keep:required by AWS +AWS::ApiGatewayV2::Route ApiId create-only a drop fails: the route is not found +AWS::ApiGatewayV2::Route AuthorizationScopes clear an update also clears it when the stack never declared it, so a value set outside the stack is lost +AWS::ApiGatewayV2::Route AuthorizationType default:NONE +AWS::ApiGatewayV2::Route AuthorizerId clear the field reads back absent, except that a route that stays JWT or CUSTOM keeps it +AWS::ApiGatewayV2::Route RouteKey keep:required by AWS +AWS::ApiGatewayV2::Route Target clear the field reads back absent AWS::ApiGatewayV2::Stage ApiId create-only a drop fails: the stage is not found AWS::ApiGatewayV2::Stage AutoDeploy default:false AWS::ApiGatewayV2::Stage StageName keep:the stage is found by its physical id