fix(cloudformation): report and continue a failed REST API update rollback (#6568)

This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-25 21:30:47 -04:00
1 parent 6b21aebdc3
commit e1726e8394
7 files changed
+421 -48

No files matched your search

@@ -9,16 +9,18 @@ import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* A stack whose AWS::ApiGateway::RestApi declares a Body that PutRestApi rejects fails to create.
* The REST API was created before the import ran, and the rollback removes it, so neither
* ROLLBACK_COMPLETE nor DeleteStack leaves it behind. A REST API of the same name that the stack
* did not create is left alone.
* The provisioner created the REST API before the import ran and deletes it when the import fails,
* so neither ROLLBACK_COMPLETE nor DeleteStack leaves it behind. A REST API of the same name that
* the stack did not create is left alone.
*/
@QuarkusTest
class ApiGatewayRestApiCfnImportRollbackIntegrationTest {
@@ -43,7 +45,7 @@ class ApiGatewayRestApiCfnImportRollbackIntegrationTest {
}
@Test
void rollbackRemovesTheRestApiWhoseBodyWasRejected() {
void aCreateWhoseBodyIsRejectedLeavesNoRestApiBehind() {
String stack = "apigw-cfn-restapi-import-rollback-it";
String outsideId = given().contentType("application/json")
.body("{\"name\":\"" + API_NAME + "\",\"description\":\"outside the stack\"}")
@@ -56,15 +58,16 @@ class ApiGatewayRestApiCfnImportRollbackIntegrationTest {
assertEquals("ROLLBACK_COMPLETE", state.status(), state.reason());
assertThat(CfnStackWaits.failedResourceReason(stack), containsString("authorizerResultTtlInSeconds"));
createdId = physicalId(stack, "Api");
assertNotNull(createdId, "the failed RestApi resource carries the id of the API it created");
assertNotEquals(outsideId, createdId);
given().when().get("/restapis/" + createdId).then().statusCode(404);
assertOutsideApiIntact(outsideId);
assertOnlyTheOutsideApiIsLeft(outsideId);
deleteStack(stack);
stackDeleted = true;
given().when().get("/restapis/" + createdId).then().statusCode(404);
assertOutsideApiIntact(outsideId);
assertOnlyTheOutsideApiIsLeft(outsideId);
} finally {
try {
if (!stackDeleted) {
@@ -79,9 +82,11 @@ class ApiGatewayRestApiCfnImportRollbackIntegrationTest {
}
}
private static void assertOutsideApiIntact(String apiId) {
given().when().get("/restapis/" + apiId).then().statusCode(200)
.body("name", equalTo(API_NAME))
/** Of the REST APIs named {@link #API_NAME}, only the one created outside the stack is left, unchanged. */
private static void assertOnlyTheOutsideApiIsLeft(String outsideId) {
given().when().get("/restapis").then().statusCode(200)
.body("item.findAll { it.name == '" + API_NAME + "' }.id", contains(outsideId));
given().when().get("/restapis/" + outsideId).then().statusCode(200)
.body("description", equalTo("outside the stack"));
}
@@ -0,0 +1,177 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
/**
* An in-place update of an AWS::ApiGateway::RestApi whose own undo cannot complete leaves the stack
* in UPDATE_ROLLBACK_FAILED, and ContinueUpdateRollback takes that undo up again: a restore that
* failed is tried again, and an update whose OpenAPI document replaced the API's definition fails
* again until the API is skipped. Each test injects one failure into ApiGatewayService, at the call
* it is about.
*/
@QuarkusTest
class ApiGatewayRestApiCfnUpdateRollbackRetryIntegrationTest {
/** The stack's template: the API's name, its description and endpoint type, then its Body. */
private static final String TEMPLATE = """
{"Resources":{"Api":{"Type":"AWS::ApiGateway::RestApi","Properties":{
"Name":"%s","Description":"%s","EndpointConfiguration":{"Types":["%s"]}%s}}}}
""";
private static final String ACCEPTED_BODY = """
,"Body":{"openapi":"3.0.1","info":{"title":"replacing-document","version":"1"},
"paths":{"/items":{"get":{"responses":{"200":{"description":"ok"}}}}}}""";
/** A token authorizer whose cache TTL is above the 3600-second maximum, which the import rejects. */
private static final String REJECTED_BODY = """
,"Body":{"openapi":"3.0.1","info":{"title":"rejected-document","version":"1"},
"components":{"securitySchemes":{"token":{"type":"apiKey","name":"Authorization","in":"header",
"x-amazon-apigateway-authtype":"custom",
"x-amazon-apigateway-authorizer":{"type":"token","authorizerResultTtlInSeconds":3601,
"authorizerUri":{"Fn::Sub":"arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:authorizer/invocations"}}}}},
"paths":{"/items":{"get":{"security":[{"token":[]}],"responses":{"200":{"description":"ok"}}}}}}""";
@InjectSpy
ApiGatewayService apiGatewayService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aRetryFailsAgainOnceTheUpdatesDocumentReplacedTheApi() {
String stack = "apigw-cfn-restapi-retry-document-it";
String name = "cfn-restapi-retry-document";
try {
stackAction(stack, "CreateStack", TEMPLATE.formatted(name, "first", "REGIONAL", ""));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
String apiId = physicalId(stack);
// After putRestApi accepted the document, applying the declared name and description
// again (just those two operations) fails once.
Mockito.doThrow(new AwsException("TooManyRequestsException", "Too Many Requests", 429))
.doCallRealMethod()
.when(apiGatewayService).updateRestApi(anyString(), eq(apiId),
argThat(onlyNameAndDescription(name, "second")));
stackAction(stack, "UpdateStack", TEMPLATE.formatted(name, "second", "EDGE", ACCEPTED_BODY));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack);
assertEquals("UPDATE_ROLLBACK_FAILED", state.status(), state.reason());
assertThat(apiResourceReason(stack), containsString("OpenAPI document was already applied"));
// The patch is put back; the definition the document replaced is not.
given().when().get("/restapis/" + apiId).then().statusCode(200)
.body("name", equalTo(name))
.body("description", equalTo("first"))
.body("endpointConfiguration.types", contains("REGIONAL"));
assertPaths(apiId, "/", "/items");
cfn("ContinueUpdateRollback", stack).when().post("/").then().statusCode(200);
state = CfnStackWaits.awaitTerminal(stack);
assertEquals("UPDATE_ROLLBACK_FAILED", state.status(), state.reason());
assertEquals("Rollback is not implemented for AWS::ApiGateway::RestApi", apiResourceReason(stack));
cfn("ContinueUpdateRollback", stack).formParam("ResourcesToSkip.member.1", "Api")
.when().post("/").then().statusCode(200);
state = CfnStackWaits.awaitTerminal(stack);
assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason());
} finally {
deleteStack(stack);
}
}
@Test
void aRetryPutsBackThePatchWhoseFirstRestoreFailed() {
String stack = "apigw-cfn-restapi-retry-restore-it";
String name = "cfn-restapi-retry-restore";
try {
stackAction(stack, "CreateStack", TEMPLATE.formatted(name, "first", "REGIONAL", ""));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
String apiId = physicalId(stack);
// The import rejects the document, and the first restore of the patch fails.
ArgumentMatcher<List<Map<String, String>>> restore =
operations -> operations != null && operations.contains(replace("/description", "first"));
Mockito.doThrow(new AwsException("TooManyRequestsException", "Too Many Requests", 429))
.doCallRealMethod()
.when(apiGatewayService).updateRestApi(anyString(), eq(apiId), argThat(restore));
stackAction(stack, "UpdateStack", TEMPLATE.formatted(name, "second", "EDGE", REJECTED_BODY));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack);
assertEquals("UPDATE_ROLLBACK_FAILED", state.status(), state.reason());
given().when().get("/restapis/" + apiId).then().statusCode(200)
.body("description", equalTo("second"))
.body("endpointConfiguration.types", contains("EDGE"));
cfn("ContinueUpdateRollback", stack).when().post("/").then().statusCode(200);
state = CfnStackWaits.awaitTerminal(stack);
assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason());
given().when().get("/restapis/" + apiId).then().statusCode(200)
.body("name", equalTo(name))
.body("description", equalTo("first"))
.body("endpointConfiguration.types", contains("REGIONAL"));
assertPaths(apiId, "/");
} finally {
deleteStack(stack);
}
}
/** The re-apply of the declared name and description: exactly those two operations. */
private static ArgumentMatcher<List<Map<String, String>>> onlyNameAndDescription(String name, String description) {
return operations -> operations != null && operations.size() == 2
&& operations.contains(replace("/name", name))
&& operations.contains(replace("/description", description));
}
private static Map<String, String> replace(String path, String value) {
return Map.of("op", "replace", "path", path, "value", value);
}
private static void assertPaths(String apiId, String... paths) {
given().when().get("/restapis/" + apiId + "/resources").then().statusCode(200)
.body("item.path", containsInAnyOrder(paths));
}
private static String physicalId(String stack) {
return XmlParser.extractFirst(apiResource(stack), "PhysicalResourceId", null);
}
private static String apiResourceReason(String stack) {
return XmlParser.extractFirst(apiResource(stack), "ResourceStatusReason", null);
}
private static String apiResource(String stack) {
return cfn("DescribeStackResource", stack).formParam("LogicalResourceId", "Api")
.when().post("/").then().statusCode(200).extract().asString();
}
private static void stackAction(String stack, String action, String template) {
cfn(action, stack).formParam("TemplateBody", template).when().post("/").then().statusCode(200);
}
private static void deleteStack(String stack) {
cfn("DeleteStack", stack).when().post("/").then().statusCode(200);
CfnStackWaits.awaitStackDeleted(stack);
}
}
@@ -229,6 +229,107 @@ class ApiGatewayRestApiCfnProvisionerTest {
verify(api, never()).deleteRestApi(anyString(), anyString());
}
@Test
void restApiUpdateReportsARollbackFailureWhenItsPatchCannotBePutBack() throws Exception {
RestApi existing = restApi("api-1", "shop", "v1", "REGIONAL");
existingApi(existing);
when(api.putRestApi(eq("us-east-1"), eq("api-1"), eq("overwrite"), anyString()))
.thenThrow(new AwsException("BadRequestException", "Invalid OpenAPI input", 400));
AwsException restoreFailure = new AwsException("TooManyRequestsException", "Too Many Requests", 429);
when(api.updateRestApi(eq("us-east-1"), eq("api-1"), any())).thenReturn(existing).thenThrow(restoreFailure);
StackResource r = resource("AWS::ApiGateway::RestApi", "Api");
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"Name": "shop", "Description": "v2", "Body": {"openapi": "3.0.1", "paths": {}}}
"""), ctx("api-1")));
assertEquals("BadRequestException", failure.getErrorCode());
assertSame(restoreFailure, failure.getSuppressed()[0]);
assertTrue(r.getAttributes().getOrDefault(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, "").contains("api-1"));
verify(api, never()).deleteRestApi(anyString(), anyString());
}
@Test
void restApiUpdateReportsARollbackFailureOnceItsDocumentWasApplied() throws Exception {
StackResource r = updateWhoseReapplyFailsAfterItsDocumentWasApplied();
// The patch is put back, but the definition the document replaced cannot be, which is
// reported rather than claimed restored.
verify(api).updateRestApi("us-east-1", "api-1", List.of(
op("replace", "/name", "shop"), op("replace", "/description", "v1")));
assertTrue(r.getAttributes().getOrDefault(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, "")
.contains("OpenAPI document was already applied"));
verify(api, never()).deleteRestApi(anyString(), anyString());
}
@Test
void restApiRetriedRollbackFailsAgainOnceTheDocumentWasApplied() throws Exception {
StackResource attempted = updateWhoseReapplyFailsAfterItsDocumentWasApplied();
StackResource previous = committedRestApi("api-1");
provisioner.mergeFailedUpdateResourceTracking(previous, attempted);
// ContinueUpdateRollback asks again, and is told again that this rollback cannot be done.
assertTrue(previous.getAttributes().containsKey(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR));
assertFalse(provisioner.rollbackUpdate(previous));
assertFalse(provisioner.rollbackUpdate(previous));
}
@Test
void restApiRetriedRollbackPutsBackThePatchWhoseFirstRestoreFailed() throws Exception {
RestApi existing = restApi("api-1", "shop", "v1", "REGIONAL");
existingApi(existing);
when(api.putRestApi(eq("us-east-1"), eq("api-1"), eq("overwrite"), anyString()))
.thenThrow(new AwsException("BadRequestException", "Invalid OpenAPI input", 400));
when(api.updateRestApi(eq("us-east-1"), eq("api-1"), any())).thenReturn(existing)
.thenThrow(new AwsException("TooManyRequestsException", "Too Many Requests", 429))
.thenReturn(existing);
StackResource attempted = resource("AWS::ApiGateway::RestApi", "Api");
assertThrows(AwsException.class, () -> provisioner.provision(attempted, props("""
{"Name": "shop", "Description": "v2", "Body": {"openapi": "3.0.1", "paths": {}}}
"""), ctx("api-1")));
StackResource previous = committedRestApi("api-1");
provisioner.mergeFailedUpdateResourceTracking(previous, attempted);
assertTrue(provisioner.rollbackUpdate(previous));
verify(api, times(2)).updateRestApi("us-east-1", "api-1", List.of(
op("replace", "/name", "shop"), op("replace", "/description", "v1")));
assertFalse(previous.getAttributes().containsKey(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR));
}
@Test
void restApiFailedUpdateWhoseOwnUndoCompletedLeavesNoSnapshotForARetry() 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 attempted = resource("AWS::ApiGateway::RestApi", "Api");
assertThrows(AwsException.class, () -> provisioner.provision(attempted, props("""
{"Name": "shop", "Description": "v2", "Body": {"openapi": "3.0.1", "paths": {}}}
"""), ctx("api-1")));
StackResource previous = committedRestApi("api-1");
provisioner.mergeFailedUpdateResourceTracking(previous, attempted);
// The patch was already put back, so the restored resource owes no rollback.
assertFalse(previous.getAttributes().containsKey(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR));
}
@Test
void restApiUpdatePutsThePatchBackWhenTheRootResourceIsMissing() throws Exception {
existingApi(restApi("api-1", "shop", "v1", "REGIONAL"));
when(api.findRootResourceId("us-east-1", "api-1")).thenReturn(Optional.empty());
StackResource r = resource("AWS::ApiGateway::RestApi", "Api");
assertThrows(RuntimeException.class, () -> provisioner.provision(r, props("""
{"Name": "shop", "Description": "v2"}
"""), ctx("api-1")));
verify(api).updateRestApi("us-east-1", "api-1", List.of(
op("replace", "/name", "shop"), op("replace", "/description", "v1")));
verify(api, never()).deleteRestApi(anyString(), anyString());
}
@Test
void restApiUpdateRecreatesAnApiRemovedOutOfBandAndItsRollbackDeletesIt() throws Exception {
when(api.getRestApi("us-east-1", "api-1"))
@@ -264,6 +365,25 @@ class ApiGatewayRestApiCfnProvisionerTest {
verify(api).deleteRestApi("us-east-1", "api-2");
}
@Test
void restApiUpdateDeletesTheRecreatedApiWhenReapplyingItsNameFails() 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"));
AwsException reapplyFailure = new AwsException("TooManyRequestsException", "Too Many Requests", 429);
when(api.updateRestApi(eq("us-east-1"), eq("api-2"), any())).thenThrow(reapplyFailure);
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")));
assertSame(reapplyFailure, failure);
verify(api).deleteRestApi("us-east-1", "api-2");
assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
@Test
void restApiUpdateListsARecreatedApiItCannotDeleteAndReportsTheRollbackFailure() throws Exception {
when(api.getRestApi("us-east-1", "api-1"))
@@ -598,6 +718,37 @@ class ApiGatewayRestApiCfnProvisionerTest {
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
}
/**
* Runs an in-place update of api-1 that putRestApi accepts and whose re-applied name and
* description then fail, and returns the attempted resource it leaves.
*/
private StackResource updateWhoseReapplyFailsAfterItsDocumentWasApplied() throws Exception {
RestApi existing = restApi("api-1", "shop", "v1", "REGIONAL");
existingApi(existing);
AwsException reapplyFailure = new AwsException("NotFoundException", "Invalid API id specified", 404);
// The update's patch, the re-apply that fails, then the restore of the patch.
when(api.updateRestApi(eq("us-east-1"), eq("api-1"), any()))
.thenReturn(existing).thenThrow(reapplyFailure).thenReturn(existing);
StackResource r = resource("AWS::ApiGateway::RestApi", "Api");
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"Name": "shop", "Description": "v2", "Body": {"openapi": "3.0.1", "info": {"title": "other"}, "paths": {}}}
"""), ctx("api-1")));
assertSame(reapplyFailure, failure);
verify(api).putRestApi(eq("us-east-1"), eq("api-1"), eq("overwrite"), anyString());
return r;
}
/** The resource a stack held for api-1 before the update, as the engine restores it. */
private static StackResource committedRestApi(String apiId) {
StackResource r = resource("AWS::ApiGateway::RestApi", "Api");
r.setPhysicalId(apiId);
r.getAttributes().put("RestApiId", apiId);
r.getAttributes().put("RootResourceId", "root-1");
return r;
}
/** 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);