Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): keep unchanged AWS::ApiGateway::Resource on update and remove it on delete (#4511)
Hyun Lee1ea5a865e3b1
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.javaindex f84d50a5e7..1e44e181fc 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java@@ -1,7 +1,11 @@package io.github.hectorvent.floci.services.cloudformation.provisioners;+import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;import io.github.hectorvent.floci.services.apigateway.model.Authorizer;@@ -13,12 +17,15 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackResource;import io.github.hectorvent.floci.services.s3.S3Service;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;+import org.jboss.logging.Logger;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;+import java.util.Objects;import java.util.Set;+import java.util.function.Supplier;/*** CloudFormation provisioning for the REST API Gateway core types. RestApi, Resource, Method,@@ -31,12 +38,22 @@ import java.util.Set;@ApplicationScopedpublic class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {+ private static final Logger LOG = Logger.getLogger(ApiGatewayRestApiCfnProvisioner.class);+private static final String REST_API = "AWS::ApiGateway::RestApi";private static final String RESOURCE = "AWS::ApiGateway::Resource";private static final String METHOD = "AWS::ApiGateway::Method";private static final String DEPLOYMENT = "AWS::ApiGateway::Deployment";private static final String STAGE = "AWS::ApiGateway::Stage";private static final String AUTHORIZER = "AWS::ApiGateway::Authorizer";+ /**+ * Where the entities a Resource or Method stack resource has named live, keyed by physical id:+ * the API of a Resource, and the API, resource and HTTP method of a Method. The physical id+ * cannot say it: a resource id does not name its API, and a method id joins parts that can+ * themselves contain the joining hyphen. The entry of a replaced entity stays, so the cleanup+ * after the update commits, or a rollback, deletes the right one.+ */+ private static final String LOCATIONS_ATTR = "__FlociApiGatewayLocations";private final ApiGatewayService apiGatewayService;private final S3Service s3Service;@@ -68,17 +85,145 @@ 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,+ * Stage and Authorizer have no delete of their own yet.+ */+ @Override+ public void delete(StackResource resource, String region) {+ deleteEntity(resource, resource.getPhysicalId(), region);+ }+@Overridepublic void delete(String resourceType, String physicalId, String region) {- // Only the RestApi has a backing delete; deleting it cascades to its resources, methods,- // deployments, stages and authorizers, so the child types own no separate delete, the same- // as the legacy switch (their delete fell through to a no-op).if (REST_API.equals(resourceType)) {// Tolerate an API already removed out of band so DeleteStack does not fail on it;// deleteRestApi resolves the id first and raises NotFoundException when it is gone.CfnDeletes.safeDelete("REST API", physicalId,() -> apiGatewayService.deleteRestApi(region, physicalId), "NotFoundException");+ } else if (METHOD.equals(resourceType)) {+ Location location = parseMethodId(physicalId);+ if (location != null) {+ deleteLocation(physicalId, location, region);+ }+ }+ }++ /**+ * Deletes the entity {@code physicalId} names, at the location recorded for it on+ * {@code resource}. A resource provisioned before locations were recorded has only its id to go+ * by, which names a method but not the API of a resource.+ */+ private void deleteEntity(StackResource resource, String physicalId, String region) {+ Location location = locations(resource).get(physicalId);+ if (location == null) {+ delete(resource.getResourceType(), physicalId, region);+ return;+ }+ deleteLocation(physicalId, location, region);+ }++ private void deleteLocation(String physicalId, Location location, String region) {+ if (location.httpMethod() == null) {+ CfnDeletes.safeDelete("API resource", physicalId, () -> apiGatewayService.deleteResource(+ region, location.restApiId(), location.resourceId()), "NotFoundException");+ } else {+ CfnDeletes.safeDelete("API method", physicalId, () -> apiGatewayService.deleteMethod(+ region, location.restApiId(), location.resourceId(), location.httpMethod()), "NotFoundException");+ }+ }++ /**+ * The location in a method's physical id, {@code <RestApiId>-<ResourceId>-<HttpMethod>}, for a+ * method provisioned before locations were recorded. Split from the right, which is right unless+ * the HTTP method has a hyphen: a custom API id can contain one, a resource id cannot.+ */+ private static Location parseMethodId(String physicalId) {+ int methodStart = physicalId == null ? -1 : physicalId.lastIndexOf('-');+ int resourceStart = methodStart > 0 ? physicalId.lastIndexOf('-', methodStart - 1) : -1;+ if (resourceStart <= 0) {+ return null;}+ return new Location(physicalId.substring(0, resourceStart),+ physicalId.substring(resourceStart + 1, methodStart), physicalId.substring(methodStart + 1));+ }++ @Override+ public boolean hasReplacementUpdate(StackResource resource) {+ return ReplacementCleanup.hasReplacement(resource);+ }++ @Override+ public String updateCleanupPhysicalId(StackResource resource) {+ return ReplacementCleanup.cleanupPhysicalId(resource);+ }++ /**+ * Deletes the Resource or Method a replacement displaced, once the stack update has committed.+ * {@link ReplacementCleanup} keeps it under {@code UpdateReplacePolicy: Retain}.+ */+ @Override+ public UpdateCleanupResult completeUpdate(StackResource resource) {+ return ReplacementCleanup.complete(resource,+ (type, physicalId, region) -> deleteEntity(resource, physicalId, region));+ }++ @Override+ public void clearUpdate(StackResource resource) {+ ReplacementCleanup.clear(resource);+ }++ /**+ * Puts a replaced Resource or Method back when a later resource fails the update. 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.+ */+ @Override+ public boolean rollbackUpdate(StackResource resource) {+ return ReplacementCleanup.rollback(resource,+ (type, physicalId, region) -> deleteEntity(resource, physicalId, region))+ || RESOURCE.equals(resource.getResourceType());+ }++ /** A resource of a REST API, or with an HTTP method, one of that resource's methods. */+ private record Location(String restApiId, String resourceId, String httpMethod) {+ }++ private Map<String, Location> locations(StackResource r) {+ Map<String, Location> locations = new HashMap<>();+ String recorded = r.getAttributes().get(LOCATIONS_ATTR);+ if (recorded == null) {+ return locations;+ }+ try {+ objectMapper.readTree(recorded).fields().forEachRemaining(entry -> locations.put(entry.getKey(),+ new Location(entry.getValue().path(0).asText(), entry.getValue().path(1).asText(),+ entry.getValue().path(2).asText(null))));+ } catch (JsonProcessingException e) {+ LOG.warnv("Unreadable API Gateway locations on {0}, ignoring them: {1}", r.getLogicalId(), e.getMessage());+ }+ return locations;+ }++ /**+ * Records where the entity {@code r} now names lives, keeping the entry of the one this update+ * replaced until the next provision.+ */+ private void recordLocation(StackResource r, ProvisionContext ctx, Location location) {+ ObjectNode recorded = objectMapper.createObjectNode();+ Location prior = ctx.isUpdate() ? locations(r).get(ctx.priorPhysicalId()) : null;+ if (prior != null && !ctx.priorPhysicalId().equals(r.getPhysicalId())) {+ recorded.set(ctx.priorPhysicalId(), locationNode(prior));+ }+ recorded.set(r.getPhysicalId(), locationNode(location));+ r.getAttributes().put(LOCATIONS_ATTR, recorded.toString());+ }++ private ArrayNode locationNode(Location location) {+ ArrayNode node = objectMapper.createArrayNode().add(location.restApiId()).add(location.resourceId());+ return location.httpMethod() == null ? node : node.add(location.httpMethod());}private void provisionRestApi(StackResource r, JsonNode props, ProvisionContext ctx) {@@ -134,16 +279,42 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {}private void provisionResource(StackResource r, JsonNode props, ProvisionContext ctx) {+ Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());+ String region = ctx.region();String apiId = ctx.resolveOptional(props, "RestApiId");String parentId = ctx.resolveOptional(props, "ParentId");String pathPart = ctx.resolveOptional(props, "PathPart");- Map<String, Object> req = new HashMap<>();- req.put("pathPart", pathPart);-- ApiGatewayResource res = apiGatewayService.createResource(ctx.region(), apiId, parentId, req);+ // RestApiId, ParentId and PathPart are all createOnly, so an update that keeps them keeps+ // the resource. Creating it again collides with itself under the same parent.+ ApiGatewayResource res = ctx.isUpdate()+ ? findPrior("API resource", ctx.priorPhysicalId(),+ () -> apiGatewayService.getResource(region, apiId, ctx.priorPhysicalId()))+ : null;+ if (res == null || !Objects.equals(res.getParentId(), parentId)+ || !Objects.equals(res.getPathPart(), pathPart)) {+ Map<String, Object> req = new HashMap<>();+ req.put("pathPart", pathPart);+ res = apiGatewayService.createResource(region, apiId, parentId, req);+ }r.setPhysicalId(res.getId());r.getAttributes().put("ResourceId", res.getId());+ recordLocation(r, ctx, new Location(apiId, res.getId(), null));+ // A replaced resource is deleted, with its methods, once the stack update commits.+ ReplacementCleanup.record(r, ctx, attributesBefore);+ }++ /** What {@code lookup} finds, or null when the entity from the previous provision is gone. */+ private static <T> T findPrior(String description, String id, Supplier<T> lookup) {+ try {+ return lookup.get();+ } catch (AwsException e) {+ if (!"NotFoundException".equals(e.getErrorCode())) {+ throw e;+ }+ LOG.debugv("{0} {1} from the previous provision is gone, creating a new one", description, id);+ return null;+ }}private void provisionAuthorizer(StackResource r, JsonNode props, ProvisionContext ctx) {@@ -163,6 +334,7 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {}private void provisionMethod(StackResource r, JsonNode props, ProvisionContext ctx) {+ Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());String region = ctx.region();CloudFormationTemplateEngine engine = ctx.engine();String apiId = ctx.resolveOptional(props, "RestApiId");@@ -178,7 +350,11 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {req.put("apiKeyRequired", Boolean.parseBoolean(ctx.resolveOrDefault(props, "ApiKeyRequired", "false")));apiGatewayService.putMethod(region, apiId, resourceId, httpMethod, req);- r.setPhysicalId(apiId + "-" + resourceId + "-" + httpMethod);+ // putMethod upper-cases the method, so a change of case alone names the same method. The+ // prior id stays, or the cleanup would delete the method as the one this update replaced.+ String physicalId = apiId + "-" + resourceId + "-" + httpMethod;+ r.setPhysicalId(ctx.isUpdate() && ctx.priorPhysicalId().equalsIgnoreCase(physicalId)+ ? ctx.priorPhysicalId() : physicalId);if (props != null && props.has("MethodResponses")) {JsonNode responses = engine.resolveNode(props.get("MethodResponses"));@@ -226,6 +402,11 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {}}}++ // RestApiId, ResourceId and HttpMethod are createOnly, so a different one is a new method,+ // and the one it replaced is deleted once the stack update commits.+ recordLocation(r, ctx, new Location(apiId, resourceId, httpMethod));+ ReplacementCleanup.record(r, ctx, attributesBefore);}private Map<String, String> resolveStringMap(JsonNode props, String name,diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayResourceCfnReplacementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayResourceCfnReplacementIntegrationTest.javanew file mode 100644index 0000000000..e9018feb5f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayResourceCfnReplacementIntegrationTest.java@@ -0,0 +1,175 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.core.common.XmlParser;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.ValidatableResponse;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsInAnyOrder;+import static org.hamcrest.Matchers.containsString;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;++/**+ * A new PathPart replaces an AWS::ApiGateway::Resource on an API outside the stack. The displaced+ * resource is deleted in the cleanup after the update commits, kept under UpdateReplacePolicy:+ * Retain, and still there when a later resource fails the update and it rolls back. A resource the+ * update kept has nothing to roll back.+ */+@QuarkusTest+class ApiGatewayResourceCfnReplacementIntegrationTest {++ /** The API, its root resource, the PathPart, the UpdateReplacePolicy and any extra resources. */+ private static final String TEMPLATE = """+ {+ "Resources": {+ "Res": {"Type":"AWS::ApiGateway::Resource", "UpdateReplacePolicy":"%4$s", "Properties":{+ "RestApiId":"%1$s", "ParentId":"%2$s", "PathPart":"%3$s"}}%5$s+ },+ "Outputs":{"ResourceId":{"Value":{"Ref":"Res"}}}+ }+ """;+ /** Fails after Res has been replaced: its parent does not exist. */+ private static final String FAILING_RESOURCE = """+ ,+ "Broken": {"Type":"AWS::ApiGateway::Resource", "DependsOn":"Res", "Properties":{+ "RestApiId":"%1$s", "ParentId":"missing0", "PathPart":"broken"}}""";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void displacedResourceIsDeletedOnceTheUpdateCommits() {+ String stack = "apigw-cfn-resource-replace-it";+ String[] api = createApi("cfn-resource-replace");+ try {+ stackAction(stack, "CreateStack", TEMPLATE.formatted(api[0], api[1], "infrastructures", "Delete", ""));+ String displaced = resourceIdOnceStatusIs(stack, "CREATE_COMPLETE");++ stackAction(stack, "UpdateStack", TEMPLATE.formatted(api[0], api[1], "renamed", "Delete", ""));+ assertNotEquals(displaced, resourceIdOnceStatusIs(stack, "UPDATE_COMPLETE"));++ assertPaths(api[0], "/", "/renamed");+ given().contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStackEvents")+ .formParam("StackName", stack)+ .when().post("/").then().statusCode(200)+ .body(containsString("<ResourceStatus>UPDATE_COMPLETE_CLEANUP_IN_PROGRESS</ResourceStatus>"))+ .body(containsString("<PhysicalResourceId>" + displaced + "</PhysicalResourceId>"))+ .body(containsString("<ResourceStatus>DELETE_COMPLETE</ResourceStatus>"));+ } finally {+ deleteStack(stack);+ deleteApi(api[0]);+ }+ }++ @Test+ void displacedResourceSurvivesAnUpdateThatRollsBack() {+ String stack = "apigw-cfn-resource-replace-rollback-it";+ String[] api = createApi("cfn-resource-replace-rollback");+ try {+ stackAction(stack, "CreateStack", TEMPLATE.formatted(api[0], api[1], "infrastructures", "Delete", ""));+ String displaced = resourceIdOnceStatusIs(stack, "CREATE_COMPLETE");++ stackAction(stack, "UpdateStack", TEMPLATE.formatted(api[0], api[1], "renamed", "Delete",+ FAILING_RESOURCE.formatted(api[0])));+ assertEquals(displaced, resourceIdOnceStatusIs(stack, "UPDATE_ROLLBACK_COMPLETE"));++ assertPaths(api[0], "/", "/infrastructures");++ deleteStack(stack);+ assertPaths(api[0], "/");+ } finally {+ deleteStack(stack);+ deleteApi(api[0]);+ }+ }++ @Test+ void keptResourceHasNothingToRollBack() {+ String stack = "apigw-cfn-resource-kept-rollback-it";+ String[] api = createApi("cfn-resource-kept-rollback");+ try {+ stackAction(stack, "CreateStack", TEMPLATE.formatted(api[0], api[1], "infrastructures", "Delete", ""));+ String kept = resourceIdOnceStatusIs(stack, "CREATE_COMPLETE");++ stackAction(stack, "UpdateStack", TEMPLATE.formatted(api[0], api[1], "infrastructures", "Delete",+ FAILING_RESOURCE.formatted(api[0])));+ assertEquals(kept, resourceIdOnceStatusIs(stack, "UPDATE_ROLLBACK_COMPLETE"));++ assertPaths(api[0], "/", "/infrastructures");+ } finally {+ deleteStack(stack);+ deleteApi(api[0]);+ }+ }++ @Test+ void retainKeepsTheDisplacedResource() {+ String stack = "apigw-cfn-resource-replace-retain-it";+ String[] api = createApi("cfn-resource-replace-retain");+ try {+ stackAction(stack, "CreateStack", TEMPLATE.formatted(api[0], api[1], "infrastructures", "Retain", ""));+ resourceIdOnceStatusIs(stack, "CREATE_COMPLETE");++ stackAction(stack, "UpdateStack", TEMPLATE.formatted(api[0], api[1], "renamed", "Retain", ""));+ resourceIdOnceStatusIs(stack, "UPDATE_COMPLETE");+ assertPaths(api[0], "/", "/infrastructures", "/renamed");++ deleteStack(stack);+ assertPaths(api[0], "/", "/infrastructures");+ } finally {+ deleteStack(stack);+ deleteApi(api[0]);+ }+ }++ /** Creates a REST API outside any stack and returns its id and root resource id. */+ private static String[] createApi(String name) {+ ValidatableResponse api = given().contentType("application/json")+ .body("{\"name\":\"" + name + "\"}")+ .when().post("/restapis").then().statusCode(201);+ return new String[]{api.extract().path("id"), api.extract().path("rootResourceId")};+ }++ private static void deleteApi(String apiId) {+ given().when().delete("/restapis/" + apiId).then().statusCode(202);+ }++ private static void assertPaths(String apiId, String... paths) {+ given().when().get("/restapis/" + apiId + "/resources").then().statusCode(200)+ .body("item.path", containsInAnyOrder(paths));+ }++ private static void stackAction(String stack, String action, String template) {+ given().contentType("application/x-www-form-urlencoded")+ .formParam("Action", action)+ .formParam("StackName", stack)+ .formParam("TemplateBody", template)+ .when().post("/").then().statusCode(200);+ }++ private static String resourceIdOnceStatusIs(String stack, String status) {+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack);+ assertEquals(status, state.status(), state.reason());+ String xml = given().contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stack)+ .when().post("/").then().statusCode(200)+ .extract().asString();+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get("ResourceId");+ }++ private static void deleteStack(String stack) {+ given().contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stack)+ .when().post("/").then().statusCode(200);+ CfnStackWaits.awaitStackDeleted(stack);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayResourceCfnUpdateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayResourceCfnUpdateIntegrationTest.javanew file mode 100644index 0000000000..0255044d3f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayResourceCfnUpdateIntegrationTest.java@@ -0,0 +1,109 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.core.common.XmlParser;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.ValidatableResponse;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.contains;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;++/**+ * A stack that adds an AWS::ApiGateway::Resource and its methods to a REST API living outside the+ * stack, the shape Serverless Framework deploys with {@code provider.apiGateway.restApiId}. The+ * redeploy only changes the Deployment's logical id.+ */+@QuarkusTest+class ApiGatewayResourceCfnUpdateIntegrationTest {++ private static final String STACK = "apigw-cfn-resource-update-it";+ private static final String TEMPLATE = """+ {+ "Resources": {+ "Res": {"Type":"AWS::ApiGateway::Resource", "Properties":{+ "RestApiId":"%1$s", "ParentId":"%2$s", "PathPart":"infrastructures"}},+ "Opt": {"Type":"AWS::ApiGateway::Method", "Properties":{+ "RestApiId":"%1$s", "ResourceId":{"Ref":"Res"},+ "HttpMethod":"OPTIONS", "AuthorizationType":"NONE", "Integration":{"Type":"MOCK"}}},+ "RootGet": {"Type":"AWS::ApiGateway::Method", "Properties":{+ "RestApiId":"%1$s", "ResourceId":"%2$s",+ "HttpMethod":"GET", "AuthorizationType":"NONE", "Integration":{"Type":"MOCK"}}},+ "RootCustom": {"Type":"AWS::ApiGateway::Method", "Properties":{+ "RestApiId":"%1$s", "ResourceId":"%2$s",+ "HttpMethod":"X-CUSTOM", "AuthorizationType":"NONE", "Integration":{"Type":"MOCK"}}},+ "Deployment%3$s": {"Type":"AWS::ApiGateway::Deployment", "DependsOn":["Opt","RootGet"],+ "Properties":{"RestApiId":"%1$s", "StageName":"local"}}+ },+ "Outputs":{"ResourceId":{"Value":{"Ref":"Res"}}}+ }+ """;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void updateKeepsTheResourceAndDeleteRemovesWhatTheStackAdded() {+ ValidatableResponse api = given().contentType("application/json")+ .body("{\"name\":\"cfn-resource-update\"}")+ .when().post("/restapis").then().statusCode(201);+ String apiId = api.extract().path("id");+ String rootId = api.extract().path("rootResourceId");+ try {+ stackAction("CreateStack", TEMPLATE.formatted(apiId, rootId, "1"));+ String resourceId = resourceIdOnceStatusIs("CREATE_COMPLETE");++ stackAction("UpdateStack", TEMPLATE.formatted(apiId, rootId, "2"));+ assertEquals(resourceId, resourceIdOnceStatusIs("UPDATE_COMPLETE"));+ given().when().get("/restapis/" + apiId + "/resources").then().statusCode(200)+ .body("item.findAll { it.path == '/infrastructures' }.size()", equalTo(1));++ deleteStack();+ given().when().get("/restapis/" + apiId + "/resources").then().statusCode(200)+ .body("item.path", contains("/"));+ given().when().get("/restapis/" + apiId + "/resources/" + rootId + "/methods/GET")+ .then().statusCode(404);+ // A hyphen in the method makes its physical id ambiguous; the recorded location is not.+ given().when().get("/restapis/" + apiId + "/resources/" + rootId + "/methods/X-CUSTOM")+ .then().statusCode(404);++ stackAction("CreateStack", TEMPLATE.formatted(apiId, rootId, "2"));+ resourceIdOnceStatusIs("CREATE_COMPLETE");+ } finally {+ deleteStack();+ given().when().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }++ private static void stackAction(String action, String template) {+ given().contentType("application/x-www-form-urlencoded")+ .formParam("Action", action)+ .formParam("StackName", STACK)+ .formParam("TemplateBody", template)+ .when().post("/").then().statusCode(200);+ }++ private static String resourceIdOnceStatusIs(String status) {+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(STACK);+ assertEquals(status, state.status(), state.reason());+ String xml = given().contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", STACK)+ .when().post("/").then().statusCode(200)+ .extract().asString();+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get("ResourceId");+ }++ private static void deleteStack() {+ given().contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteStack")+ .formParam("StackName", STACK)+ .when().post("/").then().statusCode(200);+ CfnStackWaits.awaitStackDeleted(STACK);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.javaindex 866bd27f54..8a828df6f2 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.java@@ -20,7 +20,9 @@ import java.util.Set;import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyMap;import static org.mockito.ArgumentMatchers.anyString;@@ -33,7 +35,8 @@ import static org.mockito.Mockito.when;/*** The REST API Gateway core types in isolation: the physical id and the exact Fn::GetAtt keys each- * publishes, the inline-stage shortcut on a Deployment, and that only the RestApi deletes.+ * publishes, the inline-stage shortcut on a Deployment, what an update keeps or replaces, and what+ * each type deletes.*/class ApiGatewayRestApiCfnProvisionerTest {@@ -77,6 +80,98 @@ class ApiGatewayRestApiCfnProvisionerTest {assertEquals("res-1", r.getAttributes().get("ResourceId"));}+ @Test+ void resourceUpdateKeepsAnUnchangedResource() throws Exception {+ when(api.getResource("us-east-1", "api-1", "res-1")).thenReturn(apiResource("res-1", "root-1", "orders"));++ StackResource r = resource("AWS::ApiGateway::Resource", "Res");+ provisioner.provision(r, props("""+ {"RestApiId": "api-1", "ParentId": "root-1", "PathPart": "orders"}+ """), ctx("res-1"));++ assertEquals("res-1", r.getPhysicalId());+ assertEquals("res-1", r.getAttributes().get("ResourceId"));+ verify(api, never()).createResource(anyString(), anyString(), anyString(), anyMap());+ verify(api, never()).deleteResource(anyString(), anyString(), anyString());+ }++ @Test+ void resourceReplacementDeletesTheDisplacedResourceOnlyOnceTheUpdateCommits() throws Exception {+ StackResource r = replacedResource();++ assertEquals("res-2", r.getPhysicalId());+ verify(api, never()).deleteResource(anyString(), anyString(), anyString());+ assertTrue(provisioner.hasReplacementUpdate(r));+ assertEquals("res-1", provisioner.updateCleanupPhysicalId(r));++ assertTrue(provisioner.completeUpdate(r).complete());+ verify(api).deleteResource("us-east-1", "api-1", "res-1");+ }++ @Test+ void resourceReplacementRollsBackToTheDisplacedResource() throws Exception {+ StackResource r = replacedResource();++ assertTrue(provisioner.rollbackUpdate(r));++ assertEquals("res-1", r.getPhysicalId());+ assertEquals("res-1", r.getAttributes().get("ResourceId"));+ verify(api).deleteResource("us-east-1", "api-1", "res-2");+ verify(api, never()).deleteResource("us-east-1", "api-1", "res-1");+ assertFalse(provisioner.hasReplacementUpdate(r));+ }++ @Test+ void rollbackOfAKeptResourceHasNothingToUndo() throws Exception {+ when(api.getResource("us-east-1", "api-1", "res-1")).thenReturn(apiResource("res-1", "root-1", "orders"));+ StackResource r = resource("AWS::ApiGateway::Resource", "Res");+ provisioner.provision(r, props("""+ {"RestApiId": "api-1", "ParentId": "root-1", "PathPart": "orders"}+ """), ctx("res-1"));++ assertTrue(provisioner.rollbackUpdate(r));++ assertEquals("res-1", r.getPhysicalId());+ verify(api, never()).createResource(anyString(), anyString(), anyString(), anyMap());+ verify(api, never()).deleteResource(anyString(), anyString(), anyString());+ }++ @Test+ void rollbackOfAKeptMethodIsNotImplemented() throws Exception {+ StackResource r = resource("AWS::ApiGateway::Method", "Get");+ provisioner.provision(r, props("""+ {"RestApiId": "a1b2c3", "ResourceId": "d4e5f6", "HttpMethod": "GET"}+ """), ctx("a1b2c3-d4e5f6-GET"));++ // putMethod rewrote the method in place, and nothing kept what it was before.+ assertFalse(provisioner.rollbackUpdate(r));+ verify(api, never()).deleteMethod(anyString(), anyString(), anyString(), anyString());+ }++ @Test+ void resourceReplacementKeepsTheDisplacedResourceUnderRetain() throws Exception {+ StackResource r = replacedResource();+ r.setUpdateReplacePolicy("Retain");++ provisioner.completeUpdate(r);++ verify(api, never()).deleteResource(anyString(), anyString(), anyString());+ }++ @Test+ void resourceDeleteRemovesItFromTheApiItWasCreatedOn() throws Exception {+ when(api.createResource(eq("us-east-1"), eq("api-1"), eq("root-1"), anyMap()))+ .thenReturn(apiResource("res-1", "root-1", "orders"));+ StackResource r = resource("AWS::ApiGateway::Resource", "Res");+ provisioner.provision(r, props("""+ {"RestApiId": "api-1", "ParentId": "root-1", "PathPart": "orders"}+ """), ctx());++ provisioner.delete(r, "us-east-1");++ verify(api).deleteResource("us-east-1", "api-1", "res-1");+ }+@Testvoid authorizerPublishesAuthorizerId() throws Exception {Authorizer authorizer = new Authorizer();@@ -105,6 +200,49 @@ class ApiGatewayRestApiCfnProvisionerTest {verify(api).putIntegration(eq("us-east-1"), eq("api-1"), eq("res-1"), eq("GET"), anyMap());}+ @Test+ void methodReplacementDeletesTheDisplacedMethodAtItsRecordedLocation() throws Exception {+ // Neither the API id nor the HTTP method can be told apart from the joining hyphens of+ // "my-api-d4e5f6-X-OLD", so only the recorded location names the method to delete.+ StackResource r = resource("AWS::ApiGateway::Method", "Custom");+ provisioner.provision(r, props("""+ {"RestApiId": "my-api", "ResourceId": "d4e5f6", "HttpMethod": "X-OLD"}+ """), ctx());+ provisioner.provision(r, props("""+ {"RestApiId": "my-api", "ResourceId": "d4e5f6", "HttpMethod": "POST"}+ """), ctx("my-api-d4e5f6-X-OLD"));++ assertEquals("my-api-d4e5f6-POST", r.getPhysicalId());+ verify(api, never()).deleteMethod(anyString(), anyString(), anyString(), anyString());++ provisioner.completeUpdate(r);+ verify(api).deleteMethod("us-east-1", "my-api", "d4e5f6", "X-OLD");+ }++ @Test+ void methodUpdateOfTheSameMethodDeletesNothing() throws Exception {+ StackResource r = resource("AWS::ApiGateway::Method", "Get");+ provisioner.provision(r, props("""+ {"RestApiId": "a1b2c3", "ResourceId": "d4e5f6", "HttpMethod": "GET"}+ """), ctx("a1b2c3-d4e5f6-get"));++ assertEquals("a1b2c3-d4e5f6-get", r.getPhysicalId());+ verify(api).putMethod(eq("us-east-1"), eq("a1b2c3"), eq("d4e5f6"), eq("GET"), anyMap());+ assertFalse(provisioner.hasReplacementUpdate(r));+ }++ @Test+ void methodDeleteUsesTheRecordedLocationOfAHyphenatedMethod() throws Exception {+ StackResource r = resource("AWS::ApiGateway::Method", "Custom");+ provisioner.provision(r, props("""+ {"RestApiId": "my-api", "ResourceId": "d4e5f6", "HttpMethod": "X-CUSTOM"}+ """), ctx());++ provisioner.delete(r, "us-east-1");++ verify(api).deleteMethod("us-east-1", "my-api", "d4e5f6", "X-CUSTOM");+ }+@Testvoid methodProvisionsMockTemplatesAndCorsResponses() throws Exception {StackResource r = resource("AWS::ApiGateway::Method", "Options");@@ -160,12 +298,22 @@ class ApiGatewayRestApiCfnProvisionerTest {}@Test- void deleteRemovesOnlyTheRestApi() {+ void deleteRemovesTheRestApi() {provisioner.delete("AWS::ApiGateway::RestApi", "api-1", "us-east-1");verify(api).deleteRestApi("us-east-1", "api-1");+ }- provisioner.delete("AWS::ApiGateway::Method", "api-1-res-1-GET", "us-east-1");- verify(api, never()).deleteRestApi("us-east-1", "api-1-res-1-GET");+ @Test+ void deleteOfAMethodWithNoRecordedLocationSplitsItsId() {+ // A method provisioned before locations were recorded has only its id. A custom API id can+ // contain hyphens, a resource id cannot.+ StackResource r = resource("AWS::ApiGateway::Method", "Get");+ r.setPhysicalId("my-api-d4e5f6-GET");++ provisioner.delete(r, "us-east-1");++ verify(api).deleteMethod("us-east-1", "my-api", "d4e5f6", "GET");+ verify(api, never()).deleteRestApi(anyString(), anyString());}@Test@@ -186,13 +334,40 @@ class ApiGatewayRestApiCfnProvisionerTest {}private ProvisionContext ctx() {+ return ctx(null);+ }++ private ProvisionContext ctx(String priorPhysicalId) {CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);when(engine.resolve(any())).thenAnswer(inv -> {JsonNode node = inv.getArgument(0);return node == null ? null : node.asText();});when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));- return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);+ }++ /** A Resource created as res-1 at /orders, then replaced by res-2 at /items. */+ private StackResource replacedResource() throws Exception {+ when(api.createResource(eq("us-east-1"), eq("api-1"), eq("root-1"), anyMap()))+ .thenReturn(apiResource("res-1", "root-1", "orders"), apiResource("res-2", "root-1", "items"));+ when(api.getResource("us-east-1", "api-1", "res-1")).thenReturn(apiResource("res-1", "root-1", "orders"));+ StackResource r = resource("AWS::ApiGateway::Resource", "Res");+ provisioner.provision(r, props("""+ {"RestApiId": "api-1", "ParentId": "root-1", "PathPart": "orders"}+ """), ctx());+ provisioner.provision(r, props("""+ {"RestApiId": "api-1", "ParentId": "root-1", "PathPart": "items"}+ """), ctx("res-1"));+ return r;+ }++ private static ApiGatewayResource apiResource(String id, String parentId, String pathPart) {+ ApiGatewayResource resource = new ApiGatewayResource();+ resource.setId(id);+ resource.setParentId(parentId);+ resource.setPathPart(pathPart);+ return resource;}private JsonNode props(String json) throws Exception {