Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): keep AWS::ApiGateway::RestApi on stack updates (#4512)
Hyun Leea66e2a131dfb
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.javaindex 2d7a5aec2c..cdfc45bdd2 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java@@ -121,6 +121,8 @@ public class ApiGatewayService implements ResourceProvider {private static final String EPC_KEY = "endpointConfiguration";private static final String EPC_TYPES_KEY = "types";private static final String EPC_VPC_IDS_KEY = "vpcEndpointIds";+ private static final String EPC_TYPES_PATH = "/endpointConfiguration/types/";+ private static final String EPC_VPC_IDS_PATH = "/endpointConfiguration/vpcEndpointIds";ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config,TlsCertificateManager certificateManager) {@@ -273,15 +275,7 @@ public class ApiGatewayService implements ResourceProvider {List<EndpointType> types = list.stream().filter(String.class::isInstance).map(String.class::cast)- .map(String::toUpperCase)- .map(typeStr -> {- try {- return EndpointType.valueOf(typeStr);- } catch (IllegalArgumentException e) {- throw new AwsException("BadRequestException",- "Endpoint configuration type must be REGIONAL, EDGE, or PRIVATE.", 400);- }- })+ .map(ApiGatewayService::endpointType).toList();endpointConfiguration.setTypes(types);} else if (EPC_VPC_IDS_KEY.equals(ks)) {@@ -306,18 +300,8 @@ public class ApiGatewayService implements ResourceProvider {"Endpoint configuration types must contain exactly one value.", 400);}- EndpointType type = endpointConfiguration.getTypes().getFirst();- if (EndpointType.PRIVATE.equals(type)) {- if (endpointConfiguration.getVpcEndpointIds().isEmpty()) {- throw new AwsException("BadRequestException",- "At least one vpcEndpointId is required for PRIVATE APIs.", 400);- }- } else {- // Reject/ignore vpcEndpointIds for REGIONAL and EDGE- endpointConfiguration.setVpcEndpointIds(new ArrayList<>());- }-- api.setEndpointConfiguration(endpointConfiguration);+ api.setEndpointConfiguration(endpointConfigurationOf(endpointConfiguration.getTypes().getFirst(),+ endpointConfiguration.getVpcEndpointIds()));// Create root resource "/"ApiGatewayResource root = new ApiGatewayResource();@@ -332,6 +316,30 @@ public class ApiGatewayService implements ResourceProvider {return api;}+ /** The endpoint type {@code value} names, in any case. */+ private static EndpointType endpointType(String value) {+ try {+ return EndpointType.valueOf(value.toUpperCase());+ } catch (IllegalArgumentException e) {+ throw new AwsException("BadRequestException",+ "Endpoint configuration type must be REGIONAL, EDGE, or PRIVATE.", 400);+ }+ }++ /** An endpoint configuration of {@code type}: a PRIVATE API needs a VPC endpoint, the other types take none. */+ private static EndpointConfiguration endpointConfigurationOf(EndpointType type, List<String> vpcEndpointIds) {+ EndpointConfiguration endpointConfiguration = new EndpointConfiguration();+ endpointConfiguration.setTypes(new ArrayList<>(List.of(type)));+ if (EndpointType.PRIVATE.equals(type)) {+ if (vpcEndpointIds.isEmpty()) {+ throw new AwsException("BadRequestException",+ "At least one vpcEndpointId is required for PRIVATE APIs.", 400);+ }+ endpointConfiguration.setVpcEndpointIds(new ArrayList<>(vpcEndpointIds));+ }+ return endpointConfiguration;+ }+public RestApi getRestApi(String region, String apiId) {return apiStore.get(apiKey(region, apiId)).orElseThrow(() -> new AwsException("NotFoundException", "Invalid API id specified", 404));@@ -2404,6 +2412,9 @@ public class ApiGatewayService implements ResourceProvider {public RestApi updateRestApi(String region, String apiId, List<Map<String, String>> patchOperations) {RestApi api = getRestApi(region, apiId);if (patchOperations != null) {+ // Worked out before anything is set: the store hands back the live API, and a rejected+ // endpoint change must leave it as it was.+ EndpointConfiguration endpointConfiguration = patchEndpointConfiguration(api, patchOperations);for (Map<String, String> op : patchOperations) {if (!"replace" .equals(op.get("op"))) continue;String path = op.getOrDefault("path", "");@@ -2414,11 +2425,58 @@ public class ApiGatewayService implements ResourceProvider {// replacing it with an empty string.else if ("/policy" .equals(path)) api.setPolicy(value == null || value.isEmpty() ? null : value);}+ if (endpointConfiguration != null) {+ api.setEndpointConfiguration(endpointConfiguration);+ }}apiStore.put(apiKey(region, apiId), api);return api;}+ /**+ * The endpoint configuration {@code patchOperations} leave {@code api} with, or null when none of+ * them touches it. {@code replace /endpointConfiguration/types/<type>} changes the type: the path+ * names the type the API has now, as for a domain name, or its index, {@code 0}, which is what+ * Terraform sends. {@code add} and {@code remove /endpointConfiguration/vpcEndpointIds} associate+ * and disassociate a VPC endpoint.+ */+ private static EndpointConfiguration patchEndpointConfiguration(RestApi api,+ List<Map<String, String>> patchOperations) {+ EndpointConfiguration current = api.getEndpointConfiguration();+ // An API stored without one is REGIONAL, which is also what GetRestApi reports for it.+ EndpointType type = current == null || current.getTypes().isEmpty()+ ? EndpointType.REGIONAL : current.getTypes().getFirst();+ List<String> vpcEndpointIds = new ArrayList<>(current == null ? List.of() : current.getVpcEndpointIds());+ boolean patched = false;+ for (Map<String, String> op : patchOperations) {+ String operation = op.get("op");+ String path = op.getOrDefault("path", "");+ String value = op.get("value");+ if ("replace".equals(operation) && path.startsWith(EPC_TYPES_PATH)) {+ // An API has exactly one type, so its index is always 0.+ String typeRef = path.substring(EPC_TYPES_PATH.length());+ if (!typeRef.equals(type.name()) && !typeRef.equals("0")) {+ throw new AwsException("BadRequestException", "Invalid patch path " + path+ + ": the path must name the API's current endpoint type, " + type+ + ", or its index, 0", 400);+ }+ type = endpointType(Objects.toString(value, ""));+ patched = true;+ } else if (EPC_VPC_IDS_PATH.equals(path) && value != null) {+ if ("add".equals(operation)) {+ if (!vpcEndpointIds.contains(value)) {+ vpcEndpointIds.add(value);+ }+ patched = true;+ } else if ("remove".equals(operation)) {+ vpcEndpointIds.remove(value);+ patched = true;+ }+ }+ }+ return patched ? endpointConfigurationOf(type, vpcEndpointIds) : null;+ }+public ApiGatewayResource updateResource(String region, String apiId, String resourceId, List<Map<String, String>> patchOperations) {if (patchOperations == null) {throw new AwsException("BadRequestException", "Invalid patch operation", 400);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 1e44e181fc..6fa68a8322 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@@ -10,6 +10,8 @@ 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;import io.github.hectorvent.floci.services.apigateway.model.Deployment;+import io.github.hectorvent.floci.services.apigateway.model.EndpointConfiguration;+import io.github.hectorvent.floci.services.apigateway.model.EndpointType;import io.github.hectorvent.floci.services.apigateway.model.RestApi;import io.github.hectorvent.floci.services.apigateway.model.Stage;import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;@@ -19,6 +21,7 @@ import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;+import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;@@ -54,6 +57,7 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {* after the update commits, or a rollback, deletes the right one.*/private static final String LOCATIONS_ATTR = "__FlociApiGatewayLocations";+ private static final String VPC_ENDPOINT_IDS_PATH = "/endpointConfiguration/vpcEndpointIds";private final ApiGatewayService apiGatewayService;private final S3Service s3Service;@@ -171,20 +175,45 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {@Overridepublic void clearUpdate(StackResource resource) {+ resource.getAttributes().remove(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR);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.+ * Puts a replaced RestApi, Resource or Method back when a later resource fails the update, and a+ * RestApi patched in place back to its snapshot. 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.*/@Overridepublic boolean rollbackUpdate(StackResource resource) {- return ReplacementCleanup.rollback(resource,- (type, physicalId, region) -> deleteEntity(resource, physicalId, region))- || RESOURCE.equals(resource.getResourceType());+ if (ReplacementCleanup.rollback(resource,+ (type, physicalId, region) -> deleteEntity(resource, physicalId, region))) {+ return true;+ }+ if (REST_API.equals(resource.getResourceType())) {+ return rollbackRestApiUpdate(resource);+ }+ return RESOURCE.equals(resource.getResourceType());+ }++ /**+ * Patches the API back from the snapshot taken before its in-place update. An update that also+ * re-applied an OpenAPI document replaced the API's resources, methods and models, which the+ * snapshot does not hold, so its rollback is not implemented. With no snapshot, nothing changed.+ */+ private boolean rollbackRestApiUpdate(StackResource resource) {+ if (!resource.getAttributes().containsKey(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR)) {+ return true;+ }+ JsonNode snapshot = readSnapshot(resource);+ if (snapshot.path("body").asBoolean(false)) {+ return false;+ }+ // Spent only once the restore succeeded, so a restore that throws can be tried again.+ restore(resource.getPhysicalId(), snapshot);+ resource.getAttributes().remove(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR);+ return true;}/** A resource of a REST API, or with an HTTP method, one of that resource's methods. */@@ -227,42 +256,170 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {}private void provisionRestApi(StackResource r, JsonNode props, ProvisionContext ctx) {+ // A snapshot describes the update in flight; one an earlier update left behind is stale.+ r.getAttributes().remove(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR);+ Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());String region = ctx.region();CloudFormationTemplateEngine engine = ctx.engine();+ // No RestApi property requires replacement, so an update keeps the API, and with it the id+ // and the invoke URL. An API removed out of band is created again.+ RestApi existing = ctx.isUpdate()+ ? findPrior("REST API", ctx.priorPhysicalId(),+ () -> apiGatewayService.getRestApi(region, ctx.priorPhysicalId()))+ : null;String name = ctx.resolveOptional(props, "Name");if (name == null || name.isBlank()) {- name = ctx.generatePhysicalName(r.getLogicalId(), 255, false);+ name = existing != null+ ? existing.getName()+ : ctx.generatePhysicalName(r.getLogicalId(), 255, false);}String description = ctx.resolveOptional(props, "Description");- Map<String, Object> req = new HashMap<>();- req.put("name", name);- req.put("description", description);-- if (props != null && props.has("EndpointConfiguration")) {- JsonNode epNode = props.get("EndpointConfiguration");- Map<String, Object> epReq = new HashMap<>();- epReq.put("types", ctx.resolveStringList(epNode, "Types"));- epReq.put("vpcEndpointIds", ctx.resolveStringList(epNode, "VpcEndpointIds"));- req.put("endpointConfiguration", epReq);- }+ JsonNode endpoint = props != null ? props.get("EndpointConfiguration") : null;+ // A declared Body or BodyS3Location is the whole OpenAPI document. Measured on real AWS+ // it becomes the RestApi's Body with no synthesized Resource or Method, so putRestApi plus+ // applyOpenApiSpec is the only place that turns it into resources and methods. Resolved+ // before anything changes, so a document that cannot be read leaves the API as it was.+ JsonNode openApiDocument = OpenApiDocuments.resolve(props, engine, s3Service, objectMapper);- RestApi api = apiGatewayService.createRestApi(region, req);+ RestApi api;+ if (existing != null) {+ snapshotBeforeUpdate(r, existing, region, openApiDocument != null);+ List<Map<String, String>> operations = new ArrayList<>(List.of(+ replacePatchOp("/name", name), replacePatchOp("/description", description)));+ if (endpoint != null) {+ List<String> types = ctx.resolveStringList(endpoint, "Types");+ operations.addAll(endpointPatchOps(existing.getEndpointConfiguration(),+ types.isEmpty() ? null : types.getFirst(), ctx.resolveStringList(endpoint, "VpcEndpointIds")));+ }+ api = apiGatewayService.updateRestApi(region, existing.getId(), operations);+ } else {+ Map<String, Object> req = new HashMap<>();+ req.put("name", name);+ req.put("description", description);+ if (endpoint != null) {+ Map<String, Object> epReq = new HashMap<>();+ epReq.put("types", ctx.resolveStringList(endpoint, "Types"));+ epReq.put("vpcEndpointIds", ctx.resolveStringList(endpoint, "VpcEndpointIds"));+ req.put("endpointConfiguration", epReq);+ }+ api = apiGatewayService.createRestApi(region, req);+ }r.setPhysicalId(api.getId());r.getAttributes().put("RestApiId", api.getId());+ // Not the first of getResources, which is the root only on a freshly created API.r.getAttributes().put("RootResourceId",- apiGatewayService.getResources(region, api.getId()).get(0).getId());+ apiGatewayService.findRootResourceId(region, api.getId()).orElseThrow());- // A declared Body or BodyS3Location is the whole OpenAPI document. Measured on real AWS- // it becomes the RestApi's Body with no synthesized Resource or Method, so putRestApi plus- // applyOpenApiSpec is the only place that turns it into resources and methods. putRestApi- // overwrites Name and Description from the document's info, so the declared Name and- // Description (null clearing an undeclared Description) are re-applied immediately after.- JsonNode openApiDocument = OpenApiDocuments.resolve(props, engine, s3Service, objectMapper);+ // putRestApi overwrites Name and Description from the document's info, so the declared Name+ // and Description (null clearing an undeclared Description) are re-applied immediately after.if (openApiDocument != null) {- apiGatewayService.putRestApi(region, api.getId(), "overwrite", openApiDocument.toString());+ try {+ apiGatewayService.putRestApi(region, api.getId(), "overwrite", openApiDocument.toString());+ } catch (RuntimeException failure) {+ if (existing != null) {+ unwind(r, failure);+ }+ throw failure;+ }apiGatewayService.updateRestApi(region, api.getId(),List.of(replacePatchOp("/name", name), replacePatchOp("/description", description)));}+ // An API created in place of one removed out of band is a replacement: a rollback deletes it.+ ReplacementCleanup.record(r, ctx, attributesBefore);+ }++ /**+ * The patch operations that take the endpoint configuration {@code current} to {@code type} and+ * {@code vpcEndpointIds}: the type through the path that names the one the API has now, as+ * UpdateRestApi requires, then each VPC endpoint to associate or disassociate. A null+ * {@code type} keeps the current one.+ */+ private List<Map<String, String>> endpointPatchOps(EndpointConfiguration current, String type,+ List<String> vpcEndpointIds) {+ String currentType = endpointType(current);+ List<String> currentIds = current == null ? List.of() : current.getVpcEndpointIds();+ List<Map<String, String>> operations = new ArrayList<>();+ if (type != null && !type.equalsIgnoreCase(currentType)) {+ operations.add(replacePatchOp("/endpointConfiguration/types/" + currentType, type));+ }+ for (String id : vpcEndpointIds) {+ if (!currentIds.contains(id)) {+ operations.add(Map.of("op", "add", "path", VPC_ENDPOINT_IDS_PATH, "value", id));+ }+ }+ for (String id : currentIds) {+ if (!vpcEndpointIds.contains(id)) {+ operations.add(Map.of("op", "remove", "path", VPC_ENDPOINT_IDS_PATH, "value", id));+ }+ }+ return operations;+ }++ /** The API's endpoint type; one stored without an endpoint configuration is REGIONAL. */+ private static String endpointType(EndpointConfiguration endpoint) {+ return endpoint == null || endpoint.getTypes().isEmpty()+ ? EndpointType.REGIONAL.name()+ : endpoint.getTypes().getFirst().name();+ }++ /**+ * Keeps what an in-place update is about to patch, the name, description and endpoint+ * configuration the API has now, so {@link #rollbackUpdate} can put them back, and whether the+ * update also re-applies an OpenAPI document.+ */+ private void snapshotBeforeUpdate(StackResource r, RestApi existing, String region, boolean body) {+ ObjectNode snapshot = objectMapper.createObjectNode();+ snapshot.put("region", region);+ snapshot.put("name", existing.getName());+ snapshot.put("description", existing.getDescription());+ snapshot.put("endpointType", endpointType(existing.getEndpointConfiguration()));+ ArrayNode vpcEndpointIds = snapshot.putArray("vpcEndpointIds");+ if (existing.getEndpointConfiguration() != null) {+ existing.getEndpointConfiguration().getVpcEndpointIds().forEach(vpcEndpointIds::add);+ }+ snapshot.put("body", body);+ r.getAttributes().put(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR, snapshot.toString());+ }++ private JsonNode readSnapshot(StackResource r) {+ try {+ return objectMapper.readTree(r.getAttributes().get(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR));+ } catch (JsonProcessingException e) {+ throw new IllegalStateException("Could not read the REST API update snapshot for "+ + r.getLogicalId(), e);+ }+ }++ /** Patches the API back to the name, description and endpoint configuration {@code snapshot} holds. */+ private void restore(String apiId, JsonNode snapshot) {+ String region = snapshot.path("region").asText();+ List<String> vpcEndpointIds = new ArrayList<>();+ snapshot.path("vpcEndpointIds").forEach(id -> vpcEndpointIds.add(id.asText()));+ List<Map<String, String>> operations = new ArrayList<>(List.of(+ replacePatchOp("/name", snapshot.path("name").asText(null)),+ replacePatchOp("/description", snapshot.path("description").asText(null))));+ operations.addAll(endpointPatchOps(apiGatewayService.getRestApi(region, apiId).getEndpointConfiguration(),+ snapshot.path("endpointType").asText(), vpcEndpointIds));+ apiGatewayService.updateRestApi(region, apiId, operations);+ }++ /**+ * An in-place update whose OpenAPI document putRestApi rejected puts back the name, description+ * and endpoint configuration it had already patched; putRestApi left the definition as it was.+ * CloudFormationService restores the resource the stack held before the attempt, which never+ * carried the snapshot, so the rollback walker would leave the patch in place. A restore that+ * fails is recorded as a rollback failure, so the stack ends in UPDATE_ROLLBACK_FAILED instead+ * of reporting the API intact.+ */+ private void unwind(StackResource r, RuntimeException failure) {+ try {+ restore(r.getPhysicalId(), readSnapshot(r));+ } catch (RuntimeException unwindFailure) {+ r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,+ "Could not roll back the update of REST API " + r.getPhysicalId() + ": "+ + unwindFailure.getMessage());+ failure.addSuppressed(unwindFailure);+ }}/**diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.javaindex 1565b62a33..508abaa136 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java@@ -78,6 +78,14 @@ public final class CfnRollback {*/public static final String DASHBOARD_UPDATE_SNAPSHOT_ATTR = "__FlociDashboardUpdateSnapshot";+ /**+ * Holds the name, description and endpoint configuration a REST API had before an in-place+ * update patched them, and whether the update also re-applied an OpenAPI document, so a failed+ * stack update can put them back. Written by {@code ApiGatewayRestApiCfnProvisioner} before its+ * update call and spent by its {@code rollbackUpdate}.+ */+ public static final String REST_API_UPDATE_SNAPSHOT_ATTR = "__FlociRestApiUpdateSnapshot";+/*** Holds the customer id, description, enabled flag and tags an API key carried before an* in-place update changed them, or the key an update created because the one the stack helddiff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateRestApiIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateRestApiIntegrationTest.javaindex 9e032baa4a..53247269d6 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateRestApiIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateRestApiIntegrationTest.java@@ -1,9 +1,12 @@package io.github.hectorvent.floci.services.apigateway;import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.ValidatableResponse;import org.junit.jupiter.api.Test;import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.contains;+import static org.hamcrest.Matchers.empty;import static org.hamcrest.Matchers.equalTo;@QuarkusTest@@ -37,4 +40,77 @@ public class ApiGatewayUpdateRestApiIntegrationTest {.statusCode(200).body("description", equalTo("updated description"));}++ @Test+ public void updateRestApiChangesTheEndpointType() {+ String id = createApi("rest-api-endpoint-type");++ patch(id, """+ [{"op":"replace","path":"/endpointConfiguration/types/REGIONAL","value":"EDGE"}]""")+ .statusCode(200)+ .body("endpointConfiguration.types", contains("EDGE"));++ // The path names the type the API has now, and a rejected patch changes nothing.+ patch(id, """+ [{"op":"replace","path":"/endpointConfiguration/types/REGIONAL","value":"PRIVATE"}]""")+ .statusCode(400);+ given().get("/restapis/" + id).then().statusCode(200)+ .body("endpointConfiguration.types", contains("EDGE"));++ // Terraform names the type by its index instead; an API has only the one at 0.+ patch(id, """+ [{"op":"replace","path":"/endpointConfiguration/types/0","value":"REGIONAL"}]""")+ .statusCode(200)+ .body("endpointConfiguration.types", contains("REGIONAL"));+ patch(id, """+ [{"op":"replace","path":"/endpointConfiguration/types/1","value":"EDGE"}]""")+ .statusCode(400);+ }++ @Test+ public void updateRestApiAssociatesAndDisassociatesVpcEndpoints() {+ String id = createApi("rest-api-vpc-endpoints");++ // A PRIVATE API needs a VPC endpoint, so the patch that makes it one associates one too.+ patch(id, """+ [{"op":"replace","path":"/endpointConfiguration/types/REGIONAL","value":"PRIVATE"},+ {"op":"add","path":"/endpointConfiguration/vpcEndpointIds","value":"vpce-1"},+ {"op":"add","path":"/endpointConfiguration/vpcEndpointIds","value":"vpce-2"}]""")+ .statusCode(200)+ .body("endpointConfiguration.types", contains("PRIVATE"))+ .body("endpointConfiguration.vpcEndpointIds", contains("vpce-1", "vpce-2"));++ patch(id, """+ [{"op":"remove","path":"/endpointConfiguration/vpcEndpointIds","value":"vpce-1"}]""")+ .statusCode(200)+ .body("endpointConfiguration.vpcEndpointIds", contains("vpce-2"));+ patch(id, """+ [{"op":"remove","path":"/endpointConfiguration/vpcEndpointIds","value":"vpce-2"}]""")+ .statusCode(400);++ patch(id, """+ [{"op":"replace","path":"/endpointConfiguration/types/PRIVATE","value":"REGIONAL"}]""")+ .statusCode(200)+ .body("endpointConfiguration.types", contains("REGIONAL"))+ .body("endpointConfiguration.vpcEndpointIds", empty());+ }++ private static String createApi(String name) {+ return given()+ .contentType("application/json")+ .body("{\"name\":\"" + name + "\"}")+ .post("/restapis")+ .then()+ .statusCode(201)+ .extract()+ .path("id");+ }++ private static ValidatableResponse patch(String id, String operations) {+ return given()+ .contentType("application/json")+ .body("{\"patchOperations\":" + operations + "}")+ .patch("/restapis/" + id)+ .then();+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayRestApiCfnUpdateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayRestApiCfnUpdateIntegrationTest.javanew file mode 100644index 0000000000..491ab9a6c3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayRestApiCfnUpdateIntegrationTest.java@@ -0,0 +1,163 @@+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 org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.contains;+import static org.hamcrest.Matchers.containsInAnyOrder;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;++/**+ * UpdateStack keeps an AWS::ApiGateway::RestApi and the AWS::ApiGateway::Resource under it, in the+ * redeploy shape the Serverless Framework produces: only the Deployment's logical id changes. The+ * API's description and endpoint type change in place, a resource the template drops goes from the+ * kept API, and an update that fails puts the API back as it was.+ */+@QuarkusTest+class ApiGatewayRestApiCfnUpdateIntegrationTest {++ private static final String API_NAME = "cfn-restapi-update";+ /** The API's description and endpoint type, and the suffix of the Deployment's logical id. */+ private static final String TEMPLATE = """+ {+ "Resources": {+ "Api": {"Type":"AWS::ApiGateway::RestApi", "Properties":{"Name":"cfn-restapi-update",+ "Description":"%s", "EndpointConfiguration":{"Types":["%s"]}}},+ "Items": {"Type":"AWS::ApiGateway::Resource", "Properties":{+ "RestApiId":{"Ref":"Api"},+ "ParentId":{"Fn::GetAtt":["Api","RootResourceId"]},+ "PathPart":"items"}},+ "Options": {"Type":"AWS::ApiGateway::Method", "Properties":{+ "RestApiId":{"Ref":"Api"}, "ResourceId":{"Ref":"Items"},+ "HttpMethod":"OPTIONS", "AuthorizationType":"NONE",+ "Integration":{"Type":"MOCK"}}},+ "Deployment%s": {"Type":"AWS::ApiGateway::Deployment", "DependsOn":"Options",+ "Properties":{"RestApiId":{"Ref":"Api"}, "StageName":"local"}}+ },+ "Outputs":{"ApiId":{"Value":{"Ref":"Api"}},+ "ResourceId":{"Value":{"Ref":"Items"}}}+ }+ """;+ private static final String API_ONLY_TEMPLATE = """+ {+ "Resources": {+ "Api": {"Type":"AWS::ApiGateway::RestApi", "Properties":{"Name":"cfn-restapi-update",+ "Description":"second", "EndpointConfiguration":{"Types":["EDGE"]}}}+ },+ "Outputs":{"ApiId":{"Value":{"Ref":"Api"}}}+ }+ """;+ /**+ * The API's description and endpoint type, then any extra resources. No Method or Deployment:+ * their in-place updates have no rollback yet, so a failed update could not roll back cleanly.+ */+ private static final String ROLLBACK_TEMPLATE = """+ {+ "Resources": {+ "Api": {"Type":"AWS::ApiGateway::RestApi", "Properties":{"Name":"cfn-restapi-rollback",+ "Description":"%s", "EndpointConfiguration":{"Types":["%s"]}}},+ "Items": {"Type":"AWS::ApiGateway::Resource", "Properties":{+ "RestApiId":{"Ref":"Api"},+ "ParentId":{"Fn::GetAtt":["Api","RootResourceId"]},+ "PathPart":"items"}}%s+ },+ "Outputs":{"ApiId":{"Value":{"Ref":"Api"}}}+ }+ """;+ /** Fails after the API has been patched: its parent does not exist. */+ private static final String FAILING_RESOURCE = """+ ,+ "Broken": {"Type":"AWS::ApiGateway::Resource", "DependsOn":"Items", "Properties":{+ "RestApiId":{"Ref":"Api"}, "ParentId":"missing0", "PathPart":"broken"}}""";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void updateKeepsTheRestApiAndRemovesTheResourcesItDrops() {+ String stack = "apigw-cfn-restapi-update-it";+ try {+ stackAction(stack, "CreateStack", TEMPLATE.formatted("first", "REGIONAL", "1"));+ Map<String, String> created = outputsOnceStatusIs(stack, "CREATE_COMPLETE");++ stackAction(stack, "UpdateStack", TEMPLATE.formatted("second", "EDGE", "2"));+ Map<String, String> updated = outputsOnceStatusIs(stack, "UPDATE_COMPLETE");++ String apiId = created.get("ApiId");+ assertEquals(apiId, updated.get("ApiId"));+ assertEquals(created.get("ResourceId"), updated.get("ResourceId"));+ given().when().get("/restapis").then().statusCode(200)+ .body("item.findAll { it.name == '" + API_NAME + "' }.size()", equalTo(1));+ given().when().get("/restapis/" + apiId).then().statusCode(200)+ .body("description", equalTo("second"))+ .body("endpointConfiguration.types", contains("EDGE"));+ assertPaths(apiId, "/", "/items");++ stackAction(stack, "UpdateStack", API_ONLY_TEMPLATE);+ assertEquals(apiId, outputsOnceStatusIs(stack, "UPDATE_COMPLETE").get("ApiId"));+ assertPaths(apiId, "/");+ } finally {+ deleteStack(stack);+ }+ }++ @Test+ void failedUpdatePutsTheRestApiBack() {+ String stack = "apigw-cfn-restapi-rollback-it";+ try {+ stackAction(stack, "CreateStack", ROLLBACK_TEMPLATE.formatted("first", "REGIONAL", ""));+ String apiId = outputsOnceStatusIs(stack, "CREATE_COMPLETE").get("ApiId");++ stackAction(stack, "UpdateStack", ROLLBACK_TEMPLATE.formatted("second", "EDGE", FAILING_RESOURCE));+ assertEquals(apiId, outputsOnceStatusIs(stack, "UPDATE_ROLLBACK_COMPLETE").get("ApiId"));++ given().when().get("/restapis/" + apiId).then().statusCode(200)+ .body("description", equalTo("first"))+ .body("endpointConfiguration.types", contains("REGIONAL"));+ assertPaths(apiId, "/", "/items");+ } finally {+ deleteStack(stack);+ }+ }++ 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 Map<String, String> outputsOnceStatusIs(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");+ }++ 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/provisioners/ApiGatewayRestApiCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.javaindex 8a828df6f2..0435372ceb 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@@ -7,15 +7,19 @@ 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;import io.github.hectorvent.floci.services.apigateway.model.Deployment;+import io.github.hectorvent.floci.services.apigateway.model.EndpointConfiguration;+import io.github.hectorvent.floci.services.apigateway.model.EndpointType;import io.github.hectorvent.floci.services.apigateway.model.RestApi;import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;import io.github.hectorvent.floci.services.s3.S3Service;import org.junit.jupiter.api.Test;+import java.util.ArrayList;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.assertDoesNotThrow;@@ -51,9 +55,7 @@ class ApiGatewayRestApiCfnProvisionerTest {RestApi created = new RestApi();created.setId("api-1");when(api.createRestApi(eq("us-east-1"), anyMap())).thenReturn(created);- ApiGatewayResource root = new ApiGatewayResource();- root.setId("root-1");- when(api.getResources("us-east-1", "api-1")).thenReturn(List.of(root));+ when(api.findRootResourceId("us-east-1", "api-1")).thenReturn(Optional.of("root-1"));StackResource r = resource("AWS::ApiGateway::RestApi", "Api");provisioner.provision(r, props("{\"Name\": \"shop\"}"), ctx());@@ -65,6 +67,105 @@ class ApiGatewayRestApiCfnProvisionerTest {verify(api, never()).putRestApi(anyString(), anyString(), anyString(), anyString());}+ @Test+ void restApiUpdateKeepsTheApiAndPatchesItInPlace() throws Exception {+ existingApi(restApi("api-1", "shop", "v1", "REGIONAL"));++ StackResource r = resource("AWS::ApiGateway::RestApi", "Api");+ provisioner.provision(r, props("{\"Description\": \"v2\"}"), ctx("api-1"));++ assertEquals("api-1", r.getPhysicalId());+ assertEquals("root-1", r.getAttributes().get("RootResourceId"));+ verify(api, never()).createRestApi(anyString(), anyMap());+ // An undeclared Name keeps the API's own rather than a newly generated one, and an+ // undeclared EndpointConfiguration is left alone.+ verify(api).updateRestApi("us-east-1", "api-1", List.of(+ op("replace", "/name", "shop"), op("replace", "/description", "v2")));+ assertFalse(provisioner.hasReplacementUpdate(r));+ }++ @Test+ void restApiUpdateAppliesAChangedEndpointConfiguration() throws Exception {+ existingApi(restApi("api-1", "shop", null, "REGIONAL"));++ provisioner.provision(resource("AWS::ApiGateway::RestApi", "Api"), props("""+ {"Name": "shop", "EndpointConfiguration": {"Types": ["PRIVATE"], "VpcEndpointIds": ["vpce-1"]}}+ """), ctx("api-1"));++ // The type's path names the type the API has now.+ verify(api).updateRestApi("us-east-1", "api-1", List.of(+ op("replace", "/name", "shop"), op("replace", "/description", null),+ op("replace", "/endpointConfiguration/types/REGIONAL", "PRIVATE"),+ op("add", "/endpointConfiguration/vpcEndpointIds", "vpce-1")));+ }++ @Test+ void restApiRollbackPutsBackWhatTheUpdatePatched() throws Exception {+ existingApi(restApi("api-1", "shop", "v1", "REGIONAL"));+ StackResource r = resource("AWS::ApiGateway::RestApi", "Api");+ provisioner.provision(r, props("""+ {"Name": "shop", "Description": "v2",+ "EndpointConfiguration": {"Types": ["PRIVATE"], "VpcEndpointIds": ["vpce-1"]}}+ """), ctx("api-1"));+ when(api.getRestApi("us-east-1", "api-1")).thenReturn(restApi("api-1", "shop", "v2", "PRIVATE", "vpce-1"));++ assertTrue(provisioner.rollbackUpdate(r));++ verify(api).updateRestApi("us-east-1", "api-1", List.of(+ op("replace", "/name", "shop"), op("replace", "/description", "v1"),+ op("replace", "/endpointConfiguration/types/PRIVATE", "REGIONAL"),+ op("remove", "/endpointConfiguration/vpcEndpointIds", "vpce-1")));+ assertFalse(r.getAttributes().containsKey(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR));+ }++ @Test+ void restApiRollbackOfAnUpdateThatAppliedABodyIsNotImplemented() throws Exception {+ existingApi(restApi("api-1", "shop", "v1", "REGIONAL"));+ StackResource r = resource("AWS::ApiGateway::RestApi", "Api");+ provisioner.provision(r, props("""+ {"Name": "shop", "Body": {"openapi": "3.0.1", "info": {"title": "shop"}, "paths": {}}}+ """), ctx("api-1"));+ verify(api).putRestApi(eq("us-east-1"), eq("api-1"), eq("overwrite"), anyString());++ // PutRestApi replaced the API's resources, methods and models, which the snapshot does not hold.+ assertFalse(provisioner.rollbackUpdate(r));+ }++ @Test+ void restApiUpdateWhoseBodyIsRejectedPutsThePatchBack() throws Exception {+ existingApi(restApi("api-1", "shop", "v1", "REGIONAL"));+ when(api.putRestApi(eq("us-east-1"), eq("api-1"), eq("overwrite"), anyString()))+ .thenThrow(new AwsException("BadRequestException", "Invalid OpenAPI input", 400));+ StackResource r = resource("AWS::ApiGateway::RestApi", "Api");++ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""+ {"Name": "shop", "Description": "v2", "Body": {"openapi": "3.0.1", "paths": {}}}+ """), ctx("api-1")));++ verify(api).updateRestApi("us-east-1", "api-1", List.of(+ op("replace", "/name", "shop"), op("replace", "/description", "v2")));+ verify(api).updateRestApi("us-east-1", "api-1", List.of(+ op("replace", "/name", "shop"), op("replace", "/description", "v1")));+ assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));+ }++ @Test+ void restApiUpdateRecreatesAnApiRemovedOutOfBandAndItsRollbackDeletesIt() throws Exception {+ when(api.getRestApi("us-east-1", "api-1"))+ .thenThrow(new AwsException("NotFoundException", "Invalid API id specified", 404));+ when(api.createRestApi(eq("us-east-1"), anyMap())).thenReturn(restApi("api-2", "shop", null, "REGIONAL"));+ when(api.findRootResourceId("us-east-1", "api-2")).thenReturn(Optional.of("root-2"));+ StackResource r = resource("AWS::ApiGateway::RestApi", "Api");++ provisioner.provision(r, props("{\"Name\": \"shop\"}"), ctx("api-1"));+ assertEquals("api-2", r.getPhysicalId());+ assertEquals("root-2", r.getAttributes().get("RootResourceId"));++ assertTrue(provisioner.rollbackUpdate(r));+ assertEquals("api-1", r.getPhysicalId());+ verify(api).deleteRestApi("us-east-1", "api-2");+ }+@Testvoid resourcePublishesResourceId() throws Exception {ApiGatewayResource res = new ApiGatewayResource();@@ -344,9 +445,43 @@ class ApiGatewayRestApiCfnProvisionerTest {return node == null ? null : node.asText();});when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));+ when(engine.resolveStringList(any())).thenAnswer(inv -> {+ List<String> values = new ArrayList<>();+ ((JsonNode) inv.getArgument(0)).forEach(value -> values.add(value.asText()));+ return values;+ });return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);}+ /** Stubs what an in-place update of {@code existing} looks up and patches. */+ private void existingApi(RestApi existing) {+ when(api.getRestApi("us-east-1", existing.getId())).thenReturn(existing);+ when(api.updateRestApi(eq("us-east-1"), eq(existing.getId()), any())).thenReturn(existing);+ when(api.findRootResourceId("us-east-1", existing.getId())).thenReturn(Optional.of("root-1"));+ }++ private static RestApi restApi(String id, String name, String description, String endpointType,+ String... vpcEndpointIds) {+ RestApi restApi = new RestApi();+ restApi.setId(id);+ restApi.setName(name);+ restApi.setDescription(description);+ EndpointConfiguration endpoint = new EndpointConfiguration();+ endpoint.setTypes(List.of(EndpointType.valueOf(endpointType)));+ endpoint.setVpcEndpointIds(List.of(vpcEndpointIds));+ restApi.setEndpointConfiguration(endpoint);+ return restApi;+ }++ /** A patch operation as the provisioner builds one; unlike {@code Map.of}, it takes a null value. */+ private static Map<String, String> op(String op, String path, String value) {+ Map<String, String> operation = new HashMap<>();+ operation.put("op", op);+ operation.put("path", path);+ operation.put("value", value);+ return operation;+ }+/** 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()))