mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): reject more than one endpoint type on a RestApi update (#4728)
* fix(cloudformation): keep AWS::ApiGateway::RestApi on stack updates UpdateStack runs provision again for every resource, and the RestApi arm called CreateRestApi unconditionally. Each update minted a new API, pointed the stack at it and left the previous one behind, so the API id and invoke URL changed on every deploy. No RestApi property requires replacement, so an update now keeps the API from the previous provision and patches it in place: - Name and Description go through UpdateRestApi, and a template without Name keeps the name the API has. - A changed EndpointConfiguration is applied through the UpdateRestApi paths AWS documents for it, replace /endpointConfiguration/types/<type> and add or remove /endpointConfiguration/vpcEndpointIds, which UpdateRestApi now accepts under the rules CreateRestApi applies. - A Body or BodyS3Location is resolved before anything changes and is still applied with PutRestApi in overwrite mode. - RootResourceId comes from the API's root rather than the first resource listed, which is the root only on a freshly created API. - An API removed out of band is created again, as a replacement that a rollback deletes. The name, description and endpoint configuration are snapshotted before the patch, so a later resource that fails the update puts them back, and so does a Body that PutRestApi rejects. An update that re-applied a Body still reports that rollback is not implemented: PutRestApi replaced the API's resources, methods and models, which the snapshot does not hold. The Resources and Methods on the kept API rely on the update and delete handling from #4511. * fix(apigateway): accept the index form of the endpoint type patch path UpdateRestApi took replace /endpointConfiguration/types/<type> only when the path named the API's current type, as the API Gateway guide writes it. Terraform sends /endpointConfiguration/types/0 instead, which AWS accepts too, and Floci answered it with a 400. An API has exactly one endpoint type, so index 0 is accepted as well. * fix(cloudformation): reject more than one endpoint type on a RestApi update CreateRestApi rejects an EndpointConfiguration with more than one type, but an in-place update of AWS::ApiGateway::RestApi used the first type and reported success. The provisioner now rejects the list before it changes anything, with the same BadRequestException as CreateRestApi, and the stack rolls back with the API unchanged. * fix(cloudformation): delete a recreated RestApi whose OpenAPI body is rejected An update that recreates an API removed out of band, and whose Body putRestApi rejects, left the new API behind. After the failed update the stack keeps its previous resource, so nothing tracked the new API. The provisioner now deletes it before it reports the failure. * fix(cloudformation): list a recreated RestApi that cannot be deleted for cleanup When the delete of an API recreated by a failed update also fails, list that API for the next cleanup, which the restored resource inherits, and report the rollback failure, as Ec2NetworkCfnProvisioner does for a failed undo. * refactor(cloudformation): log the failed RestApi cleanup with warnv Use JBoss Logging's parameterized form, as AGENTS.md requires.
This commit is contained in:
1 parent
cbc4cf9b91
commit
9c3593f4d1
3 files changed
+118
-4
No files matched your search
+31
-3
@@ -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 be
|
||||
|
||||
+31
-1
@@ -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.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class 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));
|
||||
|
||||
+56
@@ -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));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 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\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourcePublishesResourceId() throws Exception {
|
||||
ApiGatewayResource res = new ApiGatewayResource();
|
||||
|
||||
Reference in new issue
Block a user