Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): reject more than one endpoint type on a RestApi update (#4728)
Hyun Lee9c3593f4d101
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 6fa68a8322..019f0014f4 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@@ -275,6 +275,12 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {}String description = ctx.resolveOptional(props, "Description");JsonNode endpoint = props != null ? props.get("EndpointConfiguration") : null;+ List<String> endpointTypes = endpoint != null ? ctx.resolveStringList(endpoint, "Types") : List.of();+ // CreateRestApi rejects more than one type. An update rejects them too, before anything changes.+ if (endpointTypes.size() > 1) {+ throw new AwsException("BadRequestException",+ "Endpoint configuration types must contain exactly one value.", 400);+ }// 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@@ -287,9 +293,9 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {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")));+ endpointTypes.isEmpty() ? null : endpointTypes.getFirst(),+ ctx.resolveStringList(endpoint, "VpcEndpointIds")));}api = apiGatewayService.updateRestApi(region, existing.getId(), operations);} else {@@ -298,7 +304,7 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {req.put("description", description);if (endpoint != null) {Map<String, Object> epReq = new HashMap<>();- epReq.put("types", ctx.resolveStringList(endpoint, "Types"));+ epReq.put("types", endpointTypes);epReq.put("vpcEndpointIds", ctx.resolveStringList(endpoint, "VpcEndpointIds"));req.put("endpointConfiguration", epReq);}@@ -318,6 +324,8 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {} catch (RuntimeException failure) {if (existing != null) {unwind(r, failure);+ } else if (ctx.isUpdate()) {+ discard(r, api.getId(), region, failure);}throw failure;}@@ -422,6 +430,26 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {}}+ /**+ * Deletes the API an update created in place of one removed out of band, when putRestApi+ * rejected its OpenAPI document. CloudFormationService restores the resource the stack held+ * before the attempt, so nothing else tracks the new API. An API that cannot be deleted is+ * listed for the next cleanup, which the restored resource inherits, and the update reports a+ * rollback failure. {@code failure} stays the reported error.+ */+ private void discard(StackResource r, String apiId, String region, RuntimeException failure) {+ try {+ delete(REST_API, apiId, region);+ } catch (RuntimeException deleteFailure) {+ failure.addSuppressed(deleteFailure);+ LOG.warnv("Could not remove REST API {0}, created for {1} by a failed update: {2}",+ apiId, r.getLogicalId(), deleteFailure.getMessage());+ r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, "Could not remove REST API " + apiId+ + ", created for " + r.getLogicalId() + " by a failed update: " + deleteFailure.getMessage());+ ReplacementCleanup.recordOrphan(r, apiId, REST_API, region);+ }+ }+/*** A {@code replace} patch operation for {@link ApiGatewayService#updateRestApi}, allowing a* {@code null} value ({@code Map.of} rejects one) so an undeclared property can still bediff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayRestApiCfnUpdateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayRestApiCfnUpdateIntegrationTest.javaindex 491ab9a6c3..702cdd09e7 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayRestApiCfnUpdateIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayRestApiCfnUpdateIntegrationTest.java@@ -18,7 +18,8 @@ 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.+ * kept API, and an update that fails puts the API back as it was. An update that declares more+ * than one endpoint type is rejected, as CreateRestApi rejects it.*/@QuarkusTestclass ApiGatewayRestApiCfnUpdateIntegrationTest {@@ -71,6 +72,16 @@ class ApiGatewayRestApiCfnUpdateIntegrationTest {"Outputs":{"ApiId":{"Value":{"Ref":"Api"}}}}""";+ /** The API's description, then its endpoint types as a JSON list. */+ private static final String TYPES_TEMPLATE = """+ {+ "Resources": {+ "Api": {"Type":"AWS::ApiGateway::RestApi", "Properties":{"Name":"cfn-restapi-types",+ "Description":"%s", "EndpointConfiguration":{"Types":%s}}}+ },+ "Outputs":{"ApiId":{"Value":{"Ref":"Api"}}}+ }+ """;/** Fails after the API has been patched: its parent does not exist. */private static final String FAILING_RESOURCE = """,@@ -129,6 +140,25 @@ class ApiGatewayRestApiCfnUpdateIntegrationTest {}}+ @Test+ void updateWithMoreThanOneEndpointTypeIsRejected() {+ String stack = "apigw-cfn-restapi-types-it";+ try {+ stackAction(stack, "CreateStack", TYPES_TEMPLATE.formatted("first", "[\"REGIONAL\"]"));+ String apiId = outputsOnceStatusIs(stack, "CREATE_COMPLETE").get("ApiId");++ // CreateRestApi rejects more than one type, so an update does too.+ stackAction(stack, "UpdateStack", TYPES_TEMPLATE.formatted("second", "[\"REGIONAL\", \"EDGE\"]"));+ 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"));+ } 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));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 0435372ceb..d56ff53aff 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@@ -99,6 +99,21 @@ class ApiGatewayRestApiCfnProvisionerTest {op("add", "/endpointConfiguration/vpcEndpointIds", "vpce-1")));}+ @Test+ void restApiUpdateRejectsMoreThanOneEndpointTypeBeforeChangingAnything() throws Exception {+ existingApi(restApi("api-1", "shop", "v1", "REGIONAL"));+ StackResource r = resource("AWS::ApiGateway::RestApi", "Api");++ // CreateRestApi rejects the same list.+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""+ {"Name": "shop", "Description": "v2", "EndpointConfiguration": {"Types": ["REGIONAL", "EDGE"]}}+ """), ctx("api-1")));++ assertEquals("BadRequestException", e.getErrorCode());+ verify(api, never()).updateRestApi(anyString(), anyString(), any());+ assertFalse(r.getAttributes().containsKey(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR));+ }+@Testvoid restApiRollbackPutsBackWhatTheUpdatePatched() throws Exception {existingApi(restApi("api-1", "shop", "v1", "REGIONAL"));@@ -166,6 +181,47 @@ class ApiGatewayRestApiCfnProvisionerTest {verify(api).deleteRestApi("us-east-1", "api-2");}+ @Test+ void restApiUpdateDeletesTheRecreatedApiWhenItsBodyIsRejected() 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"));+ when(api.putRestApi(eq("us-east-1"), eq("api-2"), 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", "Body": {"openapi": "3.0.1", "paths": {}}}+ """), ctx("api-1")));++ // The failed update leaves the stack with its previous resource, so nothing else would delete it.+ verify(api).deleteRestApi("us-east-1", "api-2");+ }++ @Test+ void restApiUpdateListsARecreatedApiItCannotDeleteAndReportsTheRollbackFailure() 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"));+ when(api.putRestApi(eq("us-east-1"), eq("api-2"), eq("overwrite"), anyString()))+ .thenThrow(new AwsException("BadRequestException", "Invalid OpenAPI input", 400));+ doThrow(new AwsException("TooManyRequestsException", "Too Many Requests", 429))+ .when(api).deleteRestApi("us-east-1", "api-2");+ StackResource r = resource("AWS::ApiGateway::RestApi", "Api");++ AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""+ {"Name": "shop", "Body": {"openapi": "3.0.1", "paths": {}}}+ """), ctx("api-1")));++ assertEquals("BadRequestException", failure.getErrorCode());+ assertEquals(1, failure.getSuppressed().length);+ assertTrue(r.getAttributes().getOrDefault(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, "").contains("api-2"));+ // Listed for the next cleanup, which the resource the engine restores inherits.+ assertTrue(r.getAttributes().getOrDefault(CfnRollback.REPLACEMENT_CLEANUP_ATTR, "").contains("\"api-2\""));+ }+@Testvoid resourcePublishesResourceId() throws Exception {ApiGatewayResource res = new ApiGatewayResource();