fix(cloudformation): delete the HTTP API whose Body import fails on create (#6982)

AWS::ApiGatewayV2::Api creates the API before it turns its Body into
routes, integrations and authorizers. When the Body cannot be read or
materialized, the Body's own rollback removes what it generated, but the
API stays: the failed resource names it without the rollback-owned
marker, so neither the stack's rollback nor DeleteStack deletes it.

The Body is now read before the API is created or updated, so a document
that cannot be read changes nothing. The materialization after the
create runs through CfnRollback.guarded, as the REST API provisioner's
steps do: an API the provision created is deleted again, or left marked
for the stack's rollback when that delete fails. An API that an update
keeps is handled as before.

Deleting an Api now tolerates one already gone, as the REST API and VPC
link deletes do. Without that, an UpdateStack that adds such an Api
ended UPDATE_ROLLBACK_FAILED: the update rollback deletes the API the
provision had already deleted. It also lets an update remove an Api that
was deleted out of band, and makes Cloud Control DeleteResource answer
SUCCESS for a missing one, as it does for REST APIs.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-29 23:08:01 -04:00
1 parent 5cfb16a2f5
commit ec3bd3184f
3 files changed
+329 -9

No files matched your search

@@ -91,7 +91,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
@Override
public void delete(StackResource resource, String region) {
switch (resource.getResourceType()) {
case API -> apiGatewayV2Service.deleteApi(region, resource.getPhysicalId());
case API -> deleteApi(region, resource.getPhysicalId());
case AUTHORIZER -> {
// Deleting an authorizer needs the api id (a create-time attribute) as well as the
// authorizer id (the physical id), which the id-only delete path cannot supply.
@@ -120,6 +120,15 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
}
}
/**
* Deletes an api, and with it every child, tolerating one already gone: removed out of band, or
* deleted by a provision whose Body failed before the update rollback deletes the resource again.
*/
private void deleteApi(String region, String apiId) {
CfnDeletes.safeDelete("API Gateway V2 API", apiId, () -> apiGatewayV2Service.deleteApi(region, apiId),
"NotFoundException");
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
@@ -195,11 +204,15 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
req.put("corsConfiguration", cors);
}
// Read before anything changes, so a document that cannot be read leaves the API as it was.
JsonNode body = OpenApiDocuments.resolve(props, engine, s3Service, objectMapper);
boolean created = !ctx.isUpdate();
Api api;
if (r.getPhysicalId() == null) {
if (created) {
api = apiGatewayV2Service.createApi(region, req);
} else {
api = apiGatewayV2Service.updateApi(region, r.getPhysicalId(), req);
api = apiGatewayV2Service.updateApi(region, ctx.priorPhysicalId(), req);
}
r.setPhysicalId(api.getApiId());
r.getAttributes().put("ApiId", api.getApiId());
@@ -208,17 +221,23 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
// arn:<partition>:execute-api:<region>:<account>:<apiId> for this attribute.
r.getAttributes().put("ExecuteApiArn",
AwsArnUtils.Arn.of("execute-api", region, ctx.accountId(), api.getApiId()).toString());
reconcileBodyRoutes(r, region, api.getApiId(), props, engine);
// A Body that cannot be materialized fails the provision after the API exists. Its own
// rollback has already removed what it generated, or kept the ids of what it could not, and
// on a kept API put back the routes, integrations and authorizers it replaced; what
// UpdateApi changed stays. An API this provision created is then deleted too, with every
// child it still has, or left marked for the stack's rollback when that delete fails.
CfnRollback.guarded(r, ctx, created,
() -> deleteApi(region, api.getApiId()),
() -> { },
() -> reconcileBodyRoutes(r, region, api.getApiId(), body));
}
/**
* Reconciles the routes, integrations and authorizers materialized from an ApiGatewayV2 OpenAPI
* body. Only ids stored on this resource are removed, so separately declared V2 resources stay
* outside this generated-resource lifecycle.
* body, {@code null} when the resource declares none. Only ids stored on this resource are
* removed, so separately declared V2 resources stay outside this generated-resource lifecycle.
*/
private void reconcileBodyRoutes(StackResource r, String region, String apiId, JsonNode props,
CloudFormationTemplateEngine engine) {
JsonNode body = OpenApiDocuments.resolve(props, engine, s3Service, objectMapper);
private void reconcileBodyRoutes(StackResource r, String region, String apiId, JsonNode body) {
BodyResourceState previous = null;
try {
previous = snapshotBodyResources(r, region, apiId);
@@ -0,0 +1,206 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.apigatewayv2.model.Api;
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
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 jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.REGION;
import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.stack;
import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.stackAction;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doCallRealMethod;
/**
* A stack whose AWS::ApiGatewayV2::Api declares a Body the import refuses fails to create. The
* provisioner created the HTTP API before the Body was materialized and deletes it when that fails,
* so neither ROLLBACK_COMPLETE nor DeleteStack leaves it behind, and an HTTP API of the same name
* that the stack did not create is left alone. When that delete fails, the stack's rollback deletes
* the API instead. An update that adds such an Api rolls back cleanly, and one that refuses a kept
* API's new Body keeps the API with its routes.
*/
@QuarkusTest
class ApiGatewayV2CfnImportRollbackIntegrationTest {
/**
* Two JWT authorizers and the route of the first operation are materialized before the second
* operation, an AND of both schemes, is refused: a V2 route attaches only one authorizer.
*/
private static final String API = """
"Api":{"Type":"AWS::ApiGatewayV2::Api","Properties":{
"Name":"%1$s","ProtocolType":"HTTP",
"Body":{"openapi":"3.0.1","info":{"title":"%1$s","version":"1"},
"components":{"securitySchemes":{
"a":{"type":"oauth2","x-amazon-apigateway-authorizer":{"type":"jwt",
"identitySource":"$request.header.Authorization",
"jwtConfiguration":{"issuer":"https://issuer.example.com","audience":["a"]}}},
"b":{"type":"oauth2","x-amazon-apigateway-authorizer":{"type":"jwt",
"identitySource":"$request.header.Authorization",
"jwtConfiguration":{"issuer":"https://issuer.example.com","audience":["b"]}}}}},
"paths":{"/open":{"get":{"responses":{"200":{"description":"ok"}}}}%2$s}}}}
""";
private static final String REFUSED_OPERATION =
",\"/both\":{\"get\":{\"security\":[{\"a\":[],\"b\":[]}],\"responses\":{\"200\":{\"description\":\"ok\"}}}}";
@InjectSpy
ApiGatewayV2Service apiGatewayV2Service;
@Inject
CloudFormationService cloudFormationService;
/** The test's stack name, which also names its APIs. */
private String name;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
/** Removes what a test left, so a failed test leaves nothing for another to find. */
@AfterEach
void cleanUp() {
if (name == null) {
return;
}
doCallRealMethod().when(apiGatewayV2Service).deleteApi(anyString(), anyString());
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", name)
.when().post("/");
CfnStackWaits.awaitStackDeleted(name);
for (String apiName : List.of(name, name + "-keep")) {
apisNamed(apiName).forEach(apiId -> apiGatewayV2Service.deleteApi(REGION, apiId));
}
}
@Test
void aCreateWhoseBodyIsRefusedLeavesNoApiBehind() {
name = uniqueName("create");
String outsideId = apiGatewayV2Service.createApi(REGION, Map.of(
"name", name, "protocolType", "HTTP", "description", "outside the stack")).getApiId();
stackAction("CreateStack", name, template(refusedApi(name)));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(name);
assertEquals("ROLLBACK_COMPLETE", state.status(), state.reason());
assertThat(CfnStackWaits.failedResourceReason(name),
containsString("do not support AND security requirements"));
String createdId = stack(cloudFormationService, name).getResources().get("Api").getPhysicalId();
assertNotNull(createdId, "the failed Api resource carries the id of the API it created");
assertNotEquals(outsideId, createdId);
assertFalse(apiGatewayV2Service.hasApi(REGION, createdId), "the API the stack created is gone");
assertEquals(List.of(outsideId), apisNamed(name));
deleteStack(name);
assertEquals(List.of(outsideId), apisNamed(name));
assertEquals("outside the stack", apiGatewayV2Service.getApi(REGION, outsideId).getDescription());
}
@Test
void aCreateWhoseApiCannotBeDeletedLeavesItToTheStackRollback() {
name = uniqueName("undo");
AtomicInteger deletes = new AtomicInteger();
doAnswer(invocation -> {
if (deletes.getAndIncrement() == 0) {
throw new AwsException("TooManyRequestsException", "Too Many Requests", 429);
}
return invocation.callRealMethod();
}).when(apiGatewayV2Service).deleteApi(eq(REGION), anyString());
stackAction("CreateStack", name, template(refusedApi(name)));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(name);
assertEquals("ROLLBACK_COMPLETE", state.status(), state.reason());
assertEquals(2, deletes.get(), "the provision's delete was refused, and the stack's rollback deleted it");
assertEquals(List.of(), apisNamed(name));
}
@Test
void anUpdateThatAddsAnApiWhoseBodyIsRefusedRollsItBack() {
name = uniqueName("add");
String keep = """
"Keep":{"Type":"AWS::ApiGatewayV2::Api","Properties":{"Name":"%s-keep","ProtocolType":"HTTP"}}
""".formatted(name);
stackAction("CreateStack", name, template(keep));
CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE");
String keepId = stack(cloudFormationService, name).getResources().get("Keep").getPhysicalId();
stackAction("UpdateStack", name, template(keep + "," + refusedApi(name)));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(name);
assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason());
assertFalse(stack(cloudFormationService, name).getResources().containsKey("Api"));
assertEquals(List.of(), apisNamed(name), "the API the update created is gone");
assertTrue(apiGatewayV2Service.hasApi(REGION, keepId));
}
@Test
void anUpdateWhoseBodyIsRefusedKeepsTheApiAndItsRoutes() {
name = uniqueName("keep");
stackAction("CreateStack", name, template(API.formatted(name, "")));
CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE");
String keptId = stack(cloudFormationService, name).getResources().get("Api").getPhysicalId();
assertEquals(List.of("GET /open"), routeKeys(keptId));
stackAction("UpdateStack", name, template(refusedApi(name)));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(name);
assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason());
assertEquals(keptId, stack(cloudFormationService, name).getResources().get("Api").getPhysicalId());
assertTrue(apiGatewayV2Service.hasApi(REGION, keptId), "the stack still holds the API it kept");
assertEquals(List.of("GET /open"), routeKeys(keptId));
deleteStack(name);
assertFalse(apiGatewayV2Service.hasApi(REGION, keptId), "DeleteStack removes the kept API");
}
private static String uniqueName(String test) {
return "cfn-v2-import-rollback-" + test + "-" + Long.toString(System.nanoTime(), 36);
}
private static String refusedApi(String name) {
return API.formatted(name, REFUSED_OPERATION);
}
private List<String> apisNamed(String apiName) {
return apiGatewayV2Service.getApis(REGION).stream()
.filter(api -> apiName.equals(api.getName()))
.map(Api::getApiId)
.toList();
}
private List<String> routeKeys(String apiId) {
return apiGatewayV2Service.getRoutes(REGION, apiId).stream().map(Route::getRouteKey).sorted().toList();
}
private static String template(String resources) {
return "{\"Resources\":{" + resources + "}}";
}
private static void deleteStack(String stackName) {
stackAction("DeleteStack", stackName, null);
CfnStackWaits.awaitStackDeleted(stackName);
}
}
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.apigatewayv2.model.VpcLink;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.junit.jupiter.api.BeforeEach;
@@ -24,8 +25,12 @@ import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
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.assertNull;
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;
import static org.mockito.ArgumentMatchers.anyMap;
@@ -33,9 +38,11 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
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;
@@ -143,6 +150,94 @@ class ApiGatewayV2CfnProvisionerTest {
assertEquals("partial-route", failed.getAttributes().get("__FlociApiGatewayV2BodyRouteIds"));
}
@Test
void apiCreateDeletesTheApiItCreatedWhenItsBodyIsRefused() throws Exception {
when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap()))
.thenReturn(route("partial-route", "GET /first"));
StackResource failed = provision(body("""
{"paths":{"/first":{"get":{}},"/second":{"get":{"security":"not-an-array"}}}}
"""), null, Map.of());
assertEquals("CREATE_FAILED", failed.getStatus());
assertEquals("security must be an array", failed.getStatusReason());
// The Body's own cleanup runs first, then the API goes, with every child it still has.
InOrder order = inOrder(apiGatewayV2Service);
order.verify(apiGatewayV2Service).deleteRoute(REGION, API_ID, "partial-route");
order.verify(apiGatewayV2Service).deleteApi(REGION, API_ID);
// Already deleted, so the engine's create rollback has nothing left to delete.
assertFalse(failed.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
}
@Test
void apiCreateLeavesTheApiToTheStackRollbackWhenItCannotDeleteIt() throws Exception {
doThrow(new AwsException("TooManyRequestsException", "Too Many Requests", 429)).doNothing()
.when(apiGatewayV2Service).deleteApi(REGION, API_ID);
StackResource failed = provision(body("""
{"paths":{"/items":{"get":{"security":"not-an-array"}}}}
"""), null, Map.of());
assertEquals("CREATE_FAILED", failed.getStatus());
assertEquals("security must be an array", failed.getStatusReason());
// Marked as created by this stack, so the create rollback, or DeleteStack, deletes it again.
assertEquals(API_ID, failed.getPhysicalId());
assertEquals("true", failed.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
provisioner.delete(failed, REGION);
verify(apiGatewayV2Service, times(2)).deleteApi(REGION, API_ID);
}
@Test
void apiCreateWithABodyItCannotReadCreatesNoApi() throws Exception {
StackResource failed = provision(mapper.readTree("""
{"Name":"test-api","ProtocolType":"HTTP","BodyS3Location":"not-s3"}
"""), null, Map.of());
assertEquals("CREATE_FAILED", failed.getStatus());
assertEquals("BodyS3Location must resolve to a non-empty S3 location", failed.getStatusReason());
assertNull(failed.getPhysicalId());
verify(apiGatewayV2Service, never()).createApi(anyString(), anyMap());
verify(apiGatewayV2Service, never()).deleteApi(anyString(), anyString());
}
@Test
void apiUpdateWithABodyItCannotReadLeavesTheApiAsItWas() throws Exception {
StackResource failed = provision(mapper.readTree("""
{"Name":"renamed-api","ProtocolType":"HTTP","BodyS3Location":"not-s3"}
"""), API_ID, Map.of("ApiId", API_ID));
assertEquals("CREATE_FAILED", failed.getStatus());
verify(apiGatewayV2Service, never()).updateApi(anyString(), anyString(), anyMap());
verify(apiGatewayV2Service, never()).deleteApi(anyString(), anyString());
}
@Test
void apiUpdateKeepsTheApiWhenItsBodyIsRefused() throws Exception {
StackResource failed = provision(body("""
{"paths":{"/items":{"get":{"security":"not-an-array"}}}}
"""), API_ID, Map.of("ApiId", API_ID));
assertEquals("CREATE_FAILED", failed.getStatus());
verify(apiGatewayV2Service).updateApi(eq(REGION), eq(API_ID), anyMap());
verify(apiGatewayV2Service, never()).deleteApi(anyString(), anyString());
assertFalse(failed.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
}
@Test
void apiDeleteToleratesOnlyAnApiAlreadyGone() {
StackResource api = new StackResource();
api.setResourceType("AWS::ApiGatewayV2::Api");
api.setPhysicalId(API_ID);
doThrow(new AwsException("NotFoundException", "Invalid API id specified", 404))
.when(apiGatewayV2Service).deleteApi(REGION, API_ID);
assertDoesNotThrow(() -> provisioner.delete(api, REGION));
AwsException throttled = new AwsException("TooManyRequestsException", "Too Many Requests", 429);
doThrow(throttled).when(apiGatewayV2Service).deleteApi(REGION, API_ID);
assertSame(throttled, assertThrows(AwsException.class, () -> provisioner.delete(api, REGION)));
}
@Test
void restoresExistingRouteWhenReplacementCleanupKeepsAConflictingRoute() throws Exception {
Route oldRoute = route("old-route", "GET /same");