fix(cloudformation): delete the REST API whose Body import fails on create (#6472)

This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-25 08:10:19 -04:00
1 parent 73fc6fd0c1
commit 93f1904106
3 files changed
+205 -57

No files matched your search

@@ -0,0 +1,114 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.CfnStackWaits;
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 static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
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;
/**
* 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.
*/
@QuarkusTest
class ApiGatewayRestApiCfnImportRollbackIntegrationTest {
private static final String API_NAME = "cfn-restapi-import-rollback";
/** A token authorizer whose cache TTL is above the 3600-second maximum, which the import rejects. */
private static final String TEMPLATE = """
{"Resources":{"Api":{"Type":"AWS::ApiGateway::RestApi","Properties":{
"Name":"cfn-restapi-import-rollback",
"Body":{"openapi":"3.0.1","info":{"title":"cfn-restapi-import-rollback","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"}}}}}}}}}}
""";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void rollbackRemovesTheRestApiWhoseBodyWasRejected() {
String stack = "apigw-cfn-restapi-import-rollback-it";
String outsideId = given().contentType("application/json")
.body("{\"name\":\"" + API_NAME + "\",\"description\":\"outside the stack\"}")
.when().post("/restapis").then().statusCode(201).extract().path("id");
String createdId = null;
boolean stackDeleted = false;
try {
stackAction(stack, "CreateStack", TEMPLATE);
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack);
assertEquals("ROLLBACK_COMPLETE", state.status(), state.reason());
assertThat(CfnStackWaits.failedResourceReason(stack), containsString("authorizerResultTtlInSeconds"));
createdId = physicalId(stack, "Api");
assertNotEquals(outsideId, createdId);
given().when().get("/restapis/" + createdId).then().statusCode(404);
assertOutsideApiIntact(outsideId);
deleteStack(stack);
stackDeleted = true;
given().when().get("/restapis/" + createdId).then().statusCode(404);
assertOutsideApiIntact(outsideId);
} finally {
try {
if (!stackDeleted) {
deleteStack(stack);
}
} finally {
if (createdId != null) {
given().when().delete("/restapis/" + createdId);
}
given().when().delete("/restapis/" + outsideId);
}
}
}
private static void assertOutsideApiIntact(String apiId) {
given().when().get("/restapis/" + apiId).then().statusCode(200)
.body("name", equalTo(API_NAME))
.body("description", equalTo("outside the stack"));
}
private static String physicalId(String stack, String logicalId) {
String xml = given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200)
.extract().asString();
return XmlParser.extractGroups(xml, "member").stream()
.filter(resource -> logicalId.equals(resource.get("LogicalResourceId")))
.findFirst().orElseThrow().get("PhysicalResourceId");
}
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 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);
}
}
@@ -26,6 +26,7 @@ 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.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -35,6 +36,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -68,6 +70,66 @@ class ApiGatewayRestApiCfnProvisionerTest {
verify(api, never()).putRestApi(anyString(), anyString(), anyString(), anyString());
}
@Test
void restApiCreateDeletesTheApiItCreatedWhenItsBodyIsRejected() throws Exception {
when(api.createRestApi(eq("us-east-1"), anyMap())).thenReturn(restApi("api-1", "shop", null, "REGIONAL"));
when(api.findRootResourceId("us-east-1", "api-1")).thenReturn(Optional.of("root-1"));
AwsException rejected = new AwsException("BadRequestException", "Invalid OpenAPI input", 400);
when(api.putRestApi(eq("us-east-1"), eq("api-1"), eq("overwrite"), anyString())).thenThrow(rejected);
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()));
assertSame(rejected, failure);
verify(api).deleteRestApi("us-east-1", "api-1");
// Already deleted, so the engine's create rollback has nothing left to delete.
assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
}
@Test
void restApiCreateDeletesTheApiItCreatedWhenReapplyingItsNameFails() throws Exception {
when(api.createRestApi(eq("us-east-1"), anyMap())).thenReturn(restApi("api-1", "shop", null, "REGIONAL"));
when(api.findRootResourceId("us-east-1", "api-1")).thenReturn(Optional.of("root-1"));
AwsException rejected = new AwsException("TooManyRequestsException", "Too Many Requests", 429);
when(api.updateRestApi(eq("us-east-1"), eq("api-1"), any())).thenThrow(rejected);
StackResource r = resource("AWS::ApiGateway::RestApi", "Api");
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"Name": "shop", "Body": {"openapi": "3.0.1", "info": {"title": "other"}, "paths": {}}}
"""), ctx()));
assertSame(rejected, failure);
verify(api).putRestApi(eq("us-east-1"), eq("api-1"), eq("overwrite"), anyString());
verify(api).deleteRestApi("us-east-1", "api-1");
}
@Test
void restApiCreateLeavesTheApiToTheStackRollbackWhenItCannotDeleteIt() throws Exception {
when(api.createRestApi(eq("us-east-1"), anyMap())).thenReturn(restApi("api-1", "shop", null, "REGIONAL"));
when(api.findRootResourceId("us-east-1", "api-1")).thenReturn(Optional.of("root-1"));
AwsException rejected = new AwsException("BadRequestException", "Invalid OpenAPI input", 400);
when(api.putRestApi(eq("us-east-1"), eq("api-1"), eq("overwrite"), anyString())).thenThrow(rejected);
AwsException cleanupFailure = new AwsException("TooManyRequestsException", "Too Many Requests", 429);
doThrow(cleanupFailure).doNothing().when(api).deleteRestApi("us-east-1", "api-1");
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()));
assertSame(rejected, failure);
assertEquals(1, failure.getSuppressed().length);
assertSame(cleanupFailure, failure.getSuppressed()[0]);
// Marked as created by this stack, so the create rollback, or DeleteStack, deletes it again.
assertEquals("api-1", r.getPhysicalId());
assertEquals("true", r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
assertFalse(r.getAttributes().containsKey(CfnRollback.REPLACEMENT_CLEANUP_ATTR));
provisioner.delete(r, "us-east-1");
verify(api, times(2)).deleteRestApi("us-east-1", "api-1");
}
@Test
void restApiUpdateKeepsTheApiAndPatchesItInPlace() throws Exception {
existingApi(restApi("api-1", "shop", "v1", "REGIONAL"));
@@ -163,6 +225,8 @@ class ApiGatewayRestApiCfnProvisionerTest {
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));
// The stack still holds the API it kept.
verify(api, never()).deleteRestApi(anyString(), anyString());
}
@Test