diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index aa94dcae3f..54f07c22bd 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -231,7 +231,7 @@ cross-resource references. | Application Auto Scaling | `ScalableTarget` (`ScheduledActions` are accepted and not run; Floci has no scheduled scaling), `ScalingPolicy` | | Route 53 | `HostedZone`, `RecordSet`, `RecordSetGroup` (written in one change batch, so a record set that cannot be written leaves the zone unchanged; every record set must be in the group's hosted zone), `HealthCheck` | | Cloud Map | `HttpNamespace`, `PrivateDnsNamespace`, `PublicDnsNamespace`, `Service` | -| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer` (created with `Name`, `Type`, `AuthorizerUri`, `IdentitySource`, `AuthorizerResultTtlInSeconds` and `ProviderARNs`; updated in place for those, keeping the id; a template that drops `AuthorizerResultTtlInSeconds`, `IdentitySource` or `ProviderARNs` restores the TTL of 300 and clears the identity source and the pools, a dropped `AuthorizerUri` keeps the current one, and dropping `IdentitySource` from a `TOKEN` or `COGNITO_USER_POOLS` authorizer fails the resource, as AWS requires it there; a change to `RestApiId` replaces the authorizer, as the registry marks it create-only, and deletes the old one once the update commits; `AuthorizerCredentials`, `AuthType` and `IdentityValidationExpression` are not stored), `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `GatewayResponse`, `ApiKey`, `UsagePlan`, `UsagePlanKey` | +| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer` (created with `Name`, `Type`, `AuthorizerUri`, `IdentitySource`, `AuthorizerResultTtlInSeconds` and `ProviderARNs`; updated in place for those, keeping the id; a template that drops `AuthorizerResultTtlInSeconds`, `IdentitySource` or `ProviderARNs` restores the TTL of 300 and clears the identity source and the pools, a dropped `AuthorizerUri` keeps the current one, and dropping `IdentitySource` from a `TOKEN` or `COGNITO_USER_POOLS` authorizer fails the resource, as AWS requires it there; a change to `RestApiId` replaces the authorizer, as the registry marks it create-only, and deletes the old one once the update commits; `AuthorizerCredentials`, `AuthType` and `IdentityValidationExpression` are not stored), `Method`, `Deployment`, `Stage` (created with `RestApiId`, `StageName`, `DeploymentId` and `Description`; updated in place for `DeploymentId` and `Description`, keeping the stage variables and method settings set outside the stack; a template that drops `Description` clears it, and a dropped `DeploymentId` keeps the current one; a change to `RestApiId` or `StageName` replaces the stage, as the registry marks them create-only, and deletes the old one once the update commits unless `UpdateReplacePolicy: Retain` keeps it, a name already taken on the API fails the update; `AccessLogSetting`, `CacheClusterEnabled`, `CacheClusterSize`, `CanarySetting`, `ClientCertificateId`, `DocumentationVersion`, `MethodSettings`, `Tags`, `TracingEnabled` and `Variables` are accepted and not stored), `Account`, `DomainName`, `BasePathMapping`, `GatewayResponse`, `ApiKey`, `UsagePlan`, `UsagePlanKey` | | API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment`, `DomainName`, `ApiMapping`, `VpcLink` | | AppSync | `GraphQLApi`, `GraphQLSchema`, `DataSource`, `FunctionConfiguration`, `Resolver`, `ApiKey`. `Ref` on `GraphQLApi` and `ApiKey` returns the id where AWS returns the ARN. See [AppSync](appsync.md#cloudformation) for `Ref` and `Fn::GetAtt` compared with AWS. | | AppConfig | `Application`, `Environment` (`Tags` and `DeletionProtectionCheck` are accepted and not stored), `ConfigurationProfile` (`Tags`, `KmsKeyIdentifier`, `RetrievalRoleArn`, `Validators` and `DeletionProtectionCheck` are accepted and not stored), `DeploymentStrategy` (`Tags` are accepted and not stored; `ReplicateTo: SSM_DOCUMENT` writes no SSM document). `Ref` returns the AppConfig ID of each. See [AppConfig](appconfig.md#cloudformation) for updates and replacement. | diff --git a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java index 9a6672231b..7ba77a7581 100644 --- a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java +++ b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java @@ -1111,7 +1111,8 @@ public class ApiGatewayService implements ResourceProvider, Resettable { if (!"replace" .equals(opType) && !"add" .equals(opType)) continue; if ("/description" .equals(path)) { - stage.setDescription(value); + // UpdateStage has no remove for the description, so an empty value clears it. + stage.setDescription(value == null || value.isEmpty() ? null : value); } else if ("/deploymentId" .equals(path)) { stage.setDeploymentId(value); } else if ("/tracingEnabled" .equals(path)) { @@ -1136,6 +1137,18 @@ public class ApiGatewayService implements ResourceProvider, Resettable { return stage; } + /** + * Writes back the deployment id and description of a stage as a stack update's snapshot held + * them, a null description included, which a patch cannot express. For the stack rollback only. + */ + public void restoreStage(String region, String apiId, Stage snapshot) { + Stage stage = getStage(region, apiId, snapshot.getStageName()); + stage.setDeploymentId(snapshot.getDeploymentId()); + stage.setDescription(snapshot.getDescription()); + stage.setLastUpdatedDate(System.currentTimeMillis() / 1000L); + stageStore.put(stageKey(region, apiId, snapshot.getStageName()), stage); + } + private static final List METHOD_SETTING_KEYS = List.of( "metrics/enabled", "logging/loglevel", diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java index 28bebeaf9d..32fa6b7f43 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java @@ -60,6 +60,11 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { /** Where a {@link Location} names an authorizer, in place of the HTTP method. */ private static final String AUTHORIZER_KIND = "AUTHORIZER"; private static final String AUTHORIZER_SNAPSHOT_ATTR = CfnRollback.APIGW_AUTHORIZER_UPDATE_SNAPSHOT_ATTR; + /** Where a {@link Location} names a stage: the stage name in place of the resource id. */ + private static final String STAGE_KIND = "STAGE"; + private static final String STAGE_SNAPSHOT_ATTR = CfnRollback.APIGW_STAGE_UPDATE_SNAPSHOT_ATTR; + /** The stage a RestApiId change left on the old API, owed a delete once the update commits. */ + private static final String STAGE_CLEANUP_ATTR = "__FlociApiGatewayStageCleanup"; private static final String VPC_ENDPOINT_IDS_PATH = "/endpointConfiguration/vpcEndpointIds"; private final ApiGatewayService apiGatewayService; @@ -94,12 +99,13 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { /** * A Resource or Method can sit on an API outside the stack, where no RestApi delete cascades to - * it, so each removes its own entity, found through the location recorded for it. Deployment - * and Stage have no delete of their own yet. An Authorizer is deleted at the API recorded for it; one + * it, so each removes its own entity, found through the location recorded for it. A Deployment + * has no delete of its own yet. An Authorizer or Stage is deleted at the API recorded for it; one * created before its location was recorded is not deleted. */ @Override public void delete(StackResource resource, String region) { + deletePendingStage(resource); deleteEntity(resource, resource.getPhysicalId(), region); } @@ -133,7 +139,10 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { } private void deleteLocation(String physicalId, Location location, String region) { - if (location.authorizer()) { + if (location.stage()) { + CfnDeletes.safeDelete("API stage", physicalId, () -> apiGatewayService.deleteStage( + region, location.restApiId(), location.resourceId()), "NotFoundException"); + } else if (location.authorizer()) { CfnDeletes.safeDelete("API authorizer", physicalId, () -> apiGatewayService.deleteAuthorizer( region, location.restApiId(), location.resourceId()), "NotFoundException"); } else if (location.httpMethod() == null) { @@ -162,12 +171,31 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { @Override public boolean hasReplacementUpdate(StackResource resource) { - return ReplacementCleanup.hasReplacement(resource); + return resource.getAttributes().containsKey(STAGE_CLEANUP_ATTR) || ReplacementCleanup.hasReplacement(resource); } @Override public String updateCleanupPhysicalId(StackResource resource) { - return ReplacementCleanup.cleanupPhysicalId(resource); + ObjectNode movedStage = readStageCleanup(resource); + return movedStage != null ? CfnLifecycleRecords.cleanupPhysicalId(resource, movedStage) + : ReplacementCleanup.cleanupPhysicalId(resource); + } + + private void deleteMovedStage(ObjectNode record) { + String name = record.path("name").asText(); + deleteLocation(name, new Location(record.path("restApiId").asText(), name, STAGE_KIND), + record.path("region").asText()); + } + + /** Deletes the old stage a failed or unfinished cleanup still owes, {@code Retain} honoured. */ + private void deletePendingStage(StackResource resource) { + CfnLifecycleRecords.deletePending(resource, STAGE_CLEANUP_ATTR, readStageCleanup(resource), true, + this::deleteMovedStage); + } + + private static ObjectNode readStageCleanup(StackResource resource) { + return CfnLifecycleRecords.read(resource, STAGE_CLEANUP_ATTR, + "Invalid API Gateway stage cleanup record", "API Gateway stage cleanup record must be an object"); } /** @@ -177,14 +205,23 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { @Override public UpdateCleanupResult completeUpdate(StackResource resource) { resource.getAttributes().remove(AUTHORIZER_SNAPSHOT_ATTR); - return ReplacementCleanup.complete(resource, + ObjectNode pendingStage = readStageCleanup(resource); + UpdateCleanupResult movedStage = pendingStage == null ? UpdateCleanupResult.notApplicable() + : CfnLifecycleRecords.completePending(resource, STAGE_CLEANUP_ATTR, STAGE_SNAPSHOT_ATTR, + pendingStage, true, this::deleteMovedStage); + if (!resource.getAttributes().containsKey(STAGE_CLEANUP_ATTR)) { + resource.getAttributes().remove(STAGE_SNAPSHOT_ATTR); + } + UpdateCleanupResult displaced = ReplacementCleanup.complete(resource, (type, physicalId, region) -> deleteEntity(resource, physicalId, region)); + return movedStage.applicable() && (!displaced.applicable() || displaced.complete()) ? movedStage : displaced; } @Override public void clearUpdate(StackResource resource) { resource.getAttributes().remove(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR); resource.getAttributes().remove(AUTHORIZER_SNAPSHOT_ATTR); + resource.getAttributes().remove(STAGE_SNAPSHOT_ATTR); ReplacementCleanup.clear(resource); } @@ -204,9 +241,10 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { } /** - * Puts a replaced RestApi, Resource, Method or Authorizer back when a later resource fails the + * Puts a replaced RestApi, Resource, Method, Authorizer or Stage back when a later resource fails the * update, a RestApi patched in place back to its snapshot, and an Authorizer patched in place, or - * created because the prior was gone, back through its own snapshot. Without a replacement, a Resource update + * created because the prior was gone, back through its own snapshot, and the same for a Stage. + * Without a replacement, a Resource update * changed nothing, since all its properties are createOnly, so there is nothing to undo. A * Method the update kept was written in place, with no snapshot to put back. */ @@ -217,6 +255,11 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { if (authorizerSnapshot != null) { return rollbackAuthorizerUpdate(resource, authorizerSnapshot); } + JsonNode stageSnapshot = STAGE.equals(resource.getResourceType()) + ? CfnRollback.updateSnapshot(resource, STAGE_SNAPSHOT_ATTR) : null; + if (stageSnapshot != null) { + return rollbackStageUpdate(resource, stageSnapshot); + } if (ReplacementCleanup.rollback(resource, (type, physicalId, region) -> deleteEntity(resource, physicalId, region))) { return true; @@ -256,6 +299,11 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { boolean authorizer() { return AUTHORIZER_KIND.equals(httpMethod); } + + /** A stage, recorded with {@link #STAGE_KIND} and its name as the resource id. */ + boolean stage() { + return STAGE_KIND.equals(httpMethod); + } } private Map locations(StackResource r) { @@ -803,18 +851,144 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { } } + /** + * RestApiId and StageName are create-only: a change to either replaces the stage. Any other + * change patches it in place, keeping the settings the template does not model. A change to + * RestApiId that keeps the name leaves the physical id as it was, so the stage on the old API + * is recorded through {@link CfnLifecycleRecords} and deleted once the update commits, unless + * {@code UpdateReplacePolicy: Retain} keeps it ({@link ReplacementCleanup} lists one entity per + * physical id, so it cannot hold this one). A new stage is refused when its name is already + * taken on the API, so a rollback never deletes a stage the update did not create. A stage provisioned before its location was + * recorded is not deleted, and is not deleted as the old stage of a move either. + */ private void provisionStage(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(STAGE_SNAPSHOT_ATTR); + deletePendingStage(r); + if (ctx.isUpdate()) { + ReplacementCleanup.endRollbackRetry(r); + } + Map attributesBefore = new HashMap<>(r.getAttributes()); + String region = ctx.region(); String apiId = ctx.resolveOptional(props, "RestApiId"); String stageName = ctx.resolveOptional(props, "StageName"); - String deploymentId = ctx.resolveOptional(props, "DeploymentId"); - + PropertyChanges changes = ctx.isUpdate() ? ctx.changes(STAGE, props) : null; + boolean replaces = changes != null && changes.requiresReplacement(); + Stage live = ctx.isUpdate() && !replaces + ? findPrior("API stage", ctx.priorPhysicalId(), + () -> apiGatewayService.getStage(region, apiId, ctx.priorPhysicalId())) + : null; + if (live != null) { + updateStageInPlace(r, props, ctx, apiId, live); + return; + } + Location prior = ctx.isUpdate() ? locations(r).get(ctx.priorPhysicalId()) : null; + if (ctx.isUpdate()) { + requireStageNameFree(region, apiId, stageName); + } Map req = new HashMap<>(); req.put("stageName", stageName); - req.put("deploymentId", deploymentId); + req.put("deploymentId", ctx.resolveOptional(props, "DeploymentId")); req.put("description", ctx.resolveOptional(props, "Description")); - apiGatewayService.createStage(ctx.region(), apiId, req); + apiGatewayService.createStage(region, apiId, req); r.setPhysicalId(stageName); + recordLocation(r, ctx, new Location(apiId, stageName, STAGE_KIND)); + if (ctx.isUpdate() && !replaces) { + // The stage the update started from is gone, so this one is the update's to undo. + CfnRollback.recordCreatedByUpdate(r, ctx, STAGE_SNAPSHOT_ATTR); + } else if (replaces && stageName.equals(ctx.priorPhysicalId()) && prior != null + && prior.stage() && !apiId.equals(prior.restApiId())) { + ObjectNode moved = objectMapper.createObjectNode(); + moved.put("region", region); + moved.put("apiId", apiId); + moved.put("stageName", stageName); + moved.put("movedFromApiId", prior.restApiId()); + r.getAttributes().put(STAGE_SNAPSHOT_ATTR, moved.toString()); + CfnLifecycleRecords.setCleanup(r, STAGE_CLEANUP_ATTR, objectMapper.createObjectNode() + .put("name", stageName).put("restApiId", prior.restApiId()).put("region", region), true); + } + if (ctx.isUpdate()) { + ReplacementCleanup.record(r, ctx, attributesBefore, replaces); + } + } + + /** + * Patches the stage to the template: a declared DeploymentId or Description is set, a dropped + * Description is cleared (the patch has no remove, so an empty value, which the service reads as + * cleared) and a dropped DeploymentId is kept, since the patch has no remove for + * it. Stage variables, method settings and the other fields are not touched. + */ + private void updateStageInPlace(StackResource r, JsonNode props, ProvisionContext ctx, String apiId, + Stage live) { + ObjectNode snapshot = objectMapper.createObjectNode(); + snapshot.put("region", ctx.region()); + snapshot.put("apiId", apiId); + snapshot.put("stageName", live.getStageName()); + snapshot.put("deploymentId", live.getDeploymentId()); + snapshot.put("description", live.getDescription()); + r.getAttributes().put(STAGE_SNAPSHOT_ATTR, snapshot.toString()); + + String deploymentId = ctx.resolveOptional(props, "DeploymentId"); + String description = ctx.resolveOptional(props, "Description"); + String desiredDescription = description != null ? description + : ctx.droppedProperties(props).contains("Description") ? null : live.getDescription(); + List> ops = new ArrayList<>(); + if (deploymentId != null && !deploymentId.equals(live.getDeploymentId())) { + ops.add(replacePatchOp("/deploymentId", deploymentId)); + } + if (!Objects.equals(live.getDescription(), desiredDescription)) { + ops.add(replacePatchOp("/description", desiredDescription == null ? "" : desiredDescription)); + } + if (!ops.isEmpty()) { + apiGatewayService.updateStage(ctx.region(), apiId, live.getStageName(), ops); + } + r.setPhysicalId(live.getStageName()); + recordLocation(r, ctx, new Location(apiId, live.getStageName(), STAGE_KIND)); + } + + /** + * CreateStage here overwrites a stage of the same name, which would make a rollback delete one + * the update did not create, so an update refuses a name already on the API. + */ + private void requireStageNameFree(String region, String apiId, String stageName) { + if (stageName != null && findPrior("API stage", stageName, + () -> apiGatewayService.getStage(region, apiId, stageName)) != null) { + throw new AwsException("ConflictException", "Stage already exists", 409); + } + } + + /** + * Puts the stage back after a failed stack update: deletes the one the update created because + * the prior was gone, or the one a RestApiId change made on the new API (the stage on the old API + * was never touched), or writes the snapshot of a patched stage back whole. Spent only once it + * succeeded, so a failure can be retried. + */ + private boolean rollbackStageUpdate(StackResource resource, JsonNode snapshot) { + if (CfnRollback.undoCreatedByUpdate(resource, snapshot, STAGE_SNAPSHOT_ATTR, null, + (createdId, region) -> deleteEntity(resource, createdId, region))) { + return true; + } + String region = snapshot.path("region").asText(); + String apiId = snapshot.path("apiId").asText(); + String stageName = snapshot.path("stageName").asText(); + String movedFrom = CfnRollback.snapshotText(snapshot, "movedFromApiId"); + if (movedFrom != null) { + deleteLocation(stageName, new Location(apiId, stageName, STAGE_KIND), region); + ObjectNode recorded = objectMapper.createObjectNode(); + recorded.set(stageName, locationNode(new Location(movedFrom, stageName, STAGE_KIND))); + resource.getAttributes().put(LOCATIONS_ATTR, recorded.toString()); + ReplacementCleanup.rollback(resource, (type, physicalId, regionName) -> { }); + } else { + Stage prior = new Stage(); + prior.setStageName(stageName); + prior.setDeploymentId(CfnRollback.snapshotText(snapshot, "deploymentId")); + prior.setDescription(CfnRollback.snapshotText(snapshot, "description")); + apiGatewayService.restoreStage(region, apiId, prior); + } + resource.getAttributes().remove(STAGE_SNAPSHOT_ATTR); + resource.getAttributes().remove(STAGE_CLEANUP_ATTR); + return true; } /** Resolves an optional property, falling back to {@code defaultValue} when absent or blank. */ diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java index 4c376d55e3..248914e6d5 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java @@ -198,6 +198,14 @@ public final class CfnRollback { */ public static final String APIGW_AUTHORIZER_UPDATE_SNAPSHOT_ATTR = "__FlociApiGatewayAuthorizerUpdateSnapshot"; + /** + * The deployment id and description an API Gateway stage carried before an in-place update, the + * stage an update created because the prior was gone, or the old API of a stage a RestApiId change + * moved, so a failed stack update can undo each. Written and spent by + * {@code ApiGatewayRestApiCfnProvisioner}. + */ + public static final String APIGW_STAGE_UPDATE_SNAPSHOT_ATTR = "__FlociApiGatewayStageUpdateSnapshot"; + public static final String STACK_SET_UPDATE_SNAPSHOT_ATTR = "__FlociStackSetUpdateSnapshot"; /** diff --git a/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayStageCfnUpdateIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayStageCfnUpdateIntegrationTest.java new file mode 100644 index 0000000000..6e4deaf075 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayStageCfnUpdateIntegrationTest.java @@ -0,0 +1,165 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.CfnStackWaits; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.StackEvent; + +import java.util.List; + +import static io.floci.aws.services.cloudformation.CfnStackTestSupport.physicalId; +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; + +/** An AWS::ApiGateway::Stage updated through a stack: in place, rolled back, moved by a new name or API, deleted. */ +@QuarkusTest +class ApiGatewayStageCfnUpdateIntegrationTest { + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + @Test + void anInPlaceUpdateKeepsOutOfBandVariablesAndRollsBackAndDropsDescription() { + String stack = "apigw-cfn-stage-inplace-it"; + CloudFormationClient cf = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1); + try { + CfnStackWaits.createStack(cf, stack, inStack("D1", "\"Description\":\"a\"", ""), "CREATE_COMPLETE"); + String apiId = physicalId(cf, stack, "Api"); + String d2 = physicalId(cf, stack, "D2"); + given().contentType("application/json") + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/variables/k\",\"value\":\"v\"}]}") + .when().patch("/restapis/" + apiId + "/stages/prod").then().statusCode(200); + + CfnStackWaits.updateStack(cf, stack, inStack("D2", "\"Description\":\"b\"", ""), "UPDATE_COMPLETE"); + given().when().get("/restapis/" + apiId + "/stages/prod").then().statusCode(200) + .body("deploymentId", equalTo(d2)).body("description", equalTo("b")) + .body("variables.k", equalTo("v")); + + CfnStackWaits.updateStack(cf, stack, inStack("D1", "\"Description\":\"c\"", + CfnStackWaits.failingResourceAfter("Stage")), "UPDATE_ROLLBACK_COMPLETE"); + given().when().get("/restapis/" + apiId + "/stages/prod").then().statusCode(200) + .body("deploymentId", equalTo(d2)).body("description", equalTo("b")); + + CfnStackWaits.updateStack(cf, stack, inStack("D2", "", ""), "UPDATE_COMPLETE"); + given().when().get("/restapis/" + apiId + "/stages/prod").then().statusCode(200) + .body("deploymentId", equalTo(d2)).body("description", nullValue()); + } finally { + CfnStackWaits.deleteStack(cf, stack); + cf.close(); + } + } + + @Test + void aChangedStageNameOrRestApiIdMovesTheStageAndDeleteRemovesIt() { + String stack = "apigw-cfn-stage-replace-it"; + CloudFormationClient cf = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1); + String stackId = stack; + try { + String[] a = outsideApi("stage-a"); + String[] b = outsideApi("stage-b"); + stackId = CfnStackWaits.createStack(cf, stack, outside(a, "prod"), "CREATE_COMPLETE").stackId(); + + CfnStackWaits.updateStack(cf, stack, outside(a, "beta"), "UPDATE_COMPLETE"); + given().when().get("/restapis/" + a[0] + "/stages/beta").then().statusCode(200); + given().when().get("/restapis/" + a[0] + "/stages/prod").then().statusCode(404); + String oldId = physicalId(cf, stack, "Stage"); + CfnStackWaits.updateStack(cf, stack, outside(b, "beta"), "UPDATE_COMPLETE"); + given().when().get("/restapis/" + b[0] + "/stages/beta").then().statusCode(200); + given().when().get("/restapis/" + a[0] + "/stages/beta").then().statusCode(404); + List stageEvents = cf.describeStackEvents(r -> r.stackName(stack)).stackEvents().reversed() + .stream().filter(e -> "Stage".equals(e.logicalResourceId())).toList(); + List tail = stageEvents.subList(stageEvents.size() - 3, stageEvents.size()); + assertEquals(List.of("UPDATE_COMPLETE", "DELETE_IN_PROGRESS", "DELETE_COMPLETE"), + tail.stream().map(StackEvent::resourceStatusAsString).toList()); + assertEquals(oldId, tail.get(2).physicalResourceId()); + + CfnStackWaits.deleteStack(cf, stackId); + given().when().get("/restapis/" + b[0] + "/stages/beta").then().statusCode(404); + } finally { + CfnStackWaits.deleteStack(cf, stackId); + cf.close(); + } + } + + @Test + void aMovedStageIsRetainedByUpdateReplacePolicyAndRolledBackWhenTheUpdateFails() { + String stack = "apigw-cfn-stage-retain-it"; + CloudFormationClient cf = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1); + String retain = "\"UpdateReplacePolicy\":\"Retain\","; + try { + String[] a = outsideApi("stage-ra"); + String[] b = outsideApi("stage-rb"); + CfnStackWaits.createStack(cf, stack, outside(a, "prod", retain, "\"Description\":\"old\",", ""), + "CREATE_COMPLETE"); + CfnStackWaits.updateStack(cf, stack, outside(b, "prod", retain, "\"Description\":\"old\",", ""), + "UPDATE_COMPLETE"); + given().when().get("/restapis/" + a[0] + "/stages/prod").then().statusCode(200); + given().when().get("/restapis/" + b[0] + "/stages/prod").then().statusCode(200); + + CfnStackWaits.updateStack(cf, stack, outside(a, "prod", retain, "", ""), + "UPDATE_ROLLBACK_COMPLETE"); + assertEquals("Stage already exists", CfnStackWaits.failedResourceReason(stack)); + + given().when().delete("/restapis/" + a[0] + "/stages/prod").then().statusCode(202); + CfnStackWaits.updateStack(cf, stack, outside(a, "prod", "", "", CfnStackWaits.failingResourceAfter("Stage")), + "UPDATE_ROLLBACK_COMPLETE"); + given().when().get("/restapis/" + b[0] + "/stages/prod").then().statusCode(200) + .body("description", equalTo("old")); + given().when().get("/restapis/" + a[0] + "/stages/prod").then().statusCode(404); + } finally { + CfnStackWaits.deleteStack(cf, stack); + cf.close(); + } + } + + /** An API made outside any stack with a method and a deployment: its id and the deployment id. */ + private static String[] outsideApi(String name) { + String apiId = given().contentType("application/json").body("{\"name\":\"" + name + "\"}") + .when().post("/restapis").then().statusCode(201).extract().path("id"); + String rootId = given().when().get("/restapis/" + apiId + "/resources").then().extract().path("item[0].id"); + String method = "/restapis/" + apiId + "/resources/" + rootId + "/methods/GET"; + given().contentType("application/json").body("{\"authorizationType\":\"NONE\"}") + .when().put(method).then().statusCode(201); + given().contentType("application/json").body("{\"type\":\"MOCK\"}") + .when().put(method + "/integration").then().statusCode(201); + String deploymentId = given().contentType("application/json").body("{}") + .when().post("/restapis/" + apiId + "/deployments").then().statusCode(201).extract().path("id"); + return new String[] {apiId, deploymentId}; + } + + private static String outside(String[] api, String stageName) { + return outside(api, stageName, "", "", ""); + } + + /** {@code attributes} sit on the stage resource itself, {@code properties} (each ending in a comma) lead its properties. */ + private static String outside(String[] api, String stageName, String attributes, String properties, + String later) { + return """ + {"Resources":{"Stage":{"Type":"AWS::ApiGateway::Stage",%s"Properties":{%s + "RestApiId":"%s","StageName":"%s","DeploymentId":"%s"}}%s}} + """.formatted(attributes, properties, api[0], stageName, api[1], later); + } + + /** One API with a method, deployments D1 and D2 and a stage prod on {@code deployment}; {@code extra} are its properties. */ + private static String inStack(String deployment, String extra, String later) { + return """ + {"Resources":{ + "Api":{"Type":"AWS::ApiGateway::RestApi","Properties":{"Name":"cfn-stage"}}, + "M":{"Type":"AWS::ApiGateway::Method","Properties":{"RestApiId":{"Ref":"Api"}, + "ResourceId":{"Fn::GetAtt":["Api","RootResourceId"]},"HttpMethod":"GET", + "AuthorizationType":"NONE","Integration":{"Type":"MOCK"}}}, + "D1":{"Type":"AWS::ApiGateway::Deployment","DependsOn":"M","Properties":{"RestApiId":{"Ref":"Api"}}}, + "D2":{"Type":"AWS::ApiGateway::Deployment","DependsOn":"M","Properties":{"RestApiId":{"Ref":"Api"}}}, + "Stage":{"Type":"AWS::ApiGateway::Stage","Properties":{"RestApiId":{"Ref":"Api"}, + "StageName":"prod","DeploymentId":{"Ref":"%s"}%s}}%s}} + """.formatted(deployment, extra.isEmpty() ? "" : "," + extra, later); + } +} diff --git a/src/test/resources/cloudformation/drop-policy.tsv b/src/test/resources/cloudformation/drop-policy.tsv index 70e485fa88..1ebbe217e5 100644 --- a/src/test/resources/cloudformation/drop-policy.tsv +++ b/src/test/resources/cloudformation/drop-policy.tsv @@ -5,6 +5,10 @@ AWS::ApiGateway::Authorizer Name keep:required by AWS AWS::ApiGateway::Authorizer ProviderARNs clear the field reads back empty AWS::ApiGateway::Authorizer RestApiId create-only a drop fails: the rest api is not found AWS::ApiGateway::Authorizer Type keep:required by AWS +AWS::ApiGateway::Stage DeploymentId keep:the patch cannot remove it +AWS::ApiGateway::Stage Description clear the field reads back absent +AWS::ApiGateway::Stage RestApiId create-only a drop fails: the rest api is not found +AWS::ApiGateway::Stage StageName create-only a drop fails: the stage name is required 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 diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 46e2d72719..afabdef12d 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -228,6 +228,7 @@ notes: AWS::EKS::Nodegroup: 'created with `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets` and `Tags`; updated in place for `Tags`, keeping tags added outside the stack; a change to `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets`, `AmiType`, `CapacityType`, `DiskSize`, `InstanceTypes` or `RemoteAccess` replaces the nodegroup, as the registry marks them create-only, and deletes the old one once the update commits; `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `Version`, `ReleaseVersion`, `ForceUpdateEnabled`, `LaunchTemplate`, `NodeRepairConfig` and `WarmPoolConfig` are accepted and not applied, whether changed or dropped, with a warning, as the emulator cannot update a nodegroup in place' AWS::IAM::User: 'template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete' AWS::ApiGateway::Authorizer: 'created with `Name`, `Type`, `AuthorizerUri`, `IdentitySource`, `AuthorizerResultTtlInSeconds` and `ProviderARNs`; updated in place for those, keeping the id; a template that drops `AuthorizerResultTtlInSeconds`, `IdentitySource` or `ProviderARNs` restores the TTL of 300 and clears the identity source and the pools, a dropped `AuthorizerUri` keeps the current one, and dropping `IdentitySource` from a `TOKEN` or `COGNITO_USER_POOLS` authorizer fails the resource, as AWS requires it there; a change to `RestApiId` replaces the authorizer, as the registry marks it create-only, and deletes the old one once the update commits; `AuthorizerCredentials`, `AuthType` and `IdentityValidationExpression` are not stored' + AWS::ApiGateway::Stage: 'created with `RestApiId`, `StageName`, `DeploymentId` and `Description`; updated in place for `DeploymentId` and `Description`, keeping the stage variables and method settings set outside the stack; a template that drops `Description` clears it, and a dropped `DeploymentId` keeps the current one; a change to `RestApiId` or `StageName` replaces the stage, as the registry marks them create-only, and deletes the old one once the update commits unless `UpdateReplacePolicy: Retain` keeps it, a name already taken on the API fails the update; `AccessLogSetting`, `CacheClusterEnabled`, `CacheClusterSize`, `CanarySetting`, `ClientCertificateId`, `DocumentationVersion`, `MethodSettings`, `Tags`, `TracingEnabled` and `Variables` are accepted and not stored' AWS::KMS::Key: 'created with `Description`, `KeyPolicy`, `KeySpec`, `KeyUsage`, `Origin`, `MultiRegion`, `Enabled`, `EnableKeyRotation` and `Tags`; updated in place for `Description`, `KeyPolicy`, `Enabled`, `EnableKeyRotation` and `Tags`, keeping tags added outside the stack; a template that drops `Description`, `Enabled` or `EnableKeyRotation` clears the description, enables the key and turns rotation off, a dropped `KeyPolicy` keeps the current policy, and one the stack never declared keeps the value set outside it; a rotation change on a key that stays disabled fails, as AWS raises `DisabledException`; a change to `KeySpec`, `KeyUsage`, `Origin` or `MultiRegion` fails the update, as on AWS, and the stack rolls back' AWS::IoT::DomainConfiguration: '`ServerCertificates` resolves to a JSON string' AWS::IoT::Policy: 'deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached'