feat(cloudformation): provision AWS::ApiGatewayV2::VpcLink (#5008)

* feat(apigatewayv2): implement UpdateVpcLink and VPC link tagging

* feat(cloudformation): provision AWS::ApiGatewayV2::VpcLink

* fix(cloudformation): keep VPC link and integration connection state on updates

* fix(cloudformation): restore the integration connection when its own update fails
This commit is contained in:
Aymen JAMAAOUI authored and GitHub committed 2026-10-04 09:09:18 -04:00
1 parent db40361a3c
commit 2c544fdb9f
12 files changed
+927 -14

No files matched your search

@@ -82,6 +82,94 @@ class ApiGatewayV2VpcLinkRestTest {
.statusCode(404);
}
@Test
@Order(5)
void updateVpcLinkRenamesTheLinkOnly() {
given()
.contentType(ContentType.JSON)
.body("""
{"name":"renamed-vpc-link"}
""")
.when().patch("/v2/vpclinks/" + vpcLinkId)
.then()
.statusCode(200)
.body("vpcLinkId", equalTo(vpcLinkId))
.body("name", equalTo("renamed-vpc-link"))
.body("subnetIds", hasItems("subnet-aaaa1111", "subnet-bbbb2222"))
.body("securityGroupIds", hasItem("sg-cccc3333"))
.body("tags.Env", equalTo("test"));
given()
.when().get("/v2/vpclinks/" + vpcLinkId)
.then()
.statusCode(200)
.body("name", equalTo("renamed-vpc-link"));
}
@Test
@Order(6)
void updateNonexistentVpcLinkReturns404() {
given()
.contentType(ContentType.JSON)
.body("""
{"name":"missing"}
""")
.when().patch("/v2/vpclinks/does-not-exist")
.then()
.statusCode(404)
.body("message", containsString("VpcLink not found"));
}
@Test
@Order(7)
void tagResourceAddsTagsToTheVpcLink() {
given()
.contentType(ContentType.JSON)
.body("""
{"tags":{"Team":"platform"}}
""")
.when().post("/v2/tags/" + vpcLinkArn())
.then()
.statusCode(201);
given()
.when().get("/v2/tags/" + vpcLinkArn())
.then()
.statusCode(200)
.body("tags.Env", equalTo("test"))
.body("tags.Team", equalTo("platform"));
}
@Test
@Order(8)
void untagResourceRemovesTagsFromTheVpcLink() {
given()
.queryParam("tagKeys", "Env")
.when().delete("/v2/tags/" + vpcLinkArn())
.then()
.statusCode(204);
given()
.when().get("/v2/vpclinks/" + vpcLinkId)
.then()
.statusCode(200)
.body("tags.Env", nullValue())
.body("tags.Team", equalTo("platform"));
}
@Test
@Order(9)
void tagResourceOnUnknownVpcLinkReturns404() {
given()
.contentType(ContentType.JSON)
.body("""
{"tags":{"Team":"platform"}}
""")
.when().post("/v2/tags/arn:aws:apigateway:us-east-1::/vpclinks/does-not-exist")
.then()
.statusCode(404);
}
@Test
@Order(10)
void createApi() {
@@ -216,6 +304,10 @@ class ApiGatewayV2VpcLinkRestTest {
.statusCode(404);
}
private static String vpcLinkArn() {
return "arn:aws:apigateway:us-east-1::/vpclinks/" + vpcLinkId;
}
@Test
@Order(99)
void cleanup() {
@@ -6,7 +6,9 @@ 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.Authorizer;
import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
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;
@@ -14,19 +16,24 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudForm
import io.github.hectorvent.floci.services.s3.S3Service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
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.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -530,12 +537,227 @@ class ApiGatewayV2CfnProvisionerTest {
verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldTwo, List.of());
}
@Test
void vpcLinkCreatesTheLinkAndPublishesItsId() throws Exception {
when(apiGatewayV2Service.createVpcLink(eq(REGION), anyMap())).thenReturn(vpcLink("vl-1", List.of("subnet-a")));
StackResource link = provisionVpcLink("""
{"Name":"my-link","SubnetIds":["subnet-a"],"SecurityGroupIds":["sg-1"],"Tags":{"Env":"test"}}
""", null, Map.of());
assertEquals("CREATE_COMPLETE", link.getStatus());
assertEquals("vl-1", link.getPhysicalId());
assertEquals("vl-1", link.getAttributes().get("VpcLinkId"));
verify(apiGatewayV2Service).createVpcLink(eq(REGION), argThat(req -> "my-link".equals(req.get("name"))
&& List.of("subnet-a").equals(req.get("subnetIds"))
&& List.of("sg-1").equals(req.get("securityGroupIds"))
&& Map.of("Env", "test").equals(req.get("tags"))));
}
@Test
void vpcLinkNameChangeUpdatesTheLinkInPlace() throws Exception {
VpcLink prior = vpcLink("vl-1", List.of("subnet-a"));
prior.setName("old-name");
when(apiGatewayV2Service.getVpcLink(REGION, "vl-1")).thenReturn(prior);
StackResource link = provisionVpcLink("""
{"Name":"new-name","SubnetIds":["subnet-a"]}
""", "vl-1", Map.of("VpcLinkId", "vl-1"));
assertEquals("vl-1", link.getPhysicalId());
verify(apiGatewayV2Service).updateVpcLink(REGION, "vl-1", Map.of("name", "new-name"));
verify(apiGatewayV2Service, never()).createVpcLink(anyString(), anyMap());
assertFalse(provisioner.hasReplacementUpdate(link));
}
@Test
void vpcLinkSubnetChangeReplacesTheLink() throws Exception {
when(apiGatewayV2Service.getVpcLink(REGION, "vl-1")).thenReturn(vpcLink("vl-1", List.of("subnet-a")));
when(apiGatewayV2Service.createVpcLink(eq(REGION), anyMap())).thenReturn(vpcLink("vl-2", List.of("subnet-b")));
StackResource link = provisionVpcLink("""
{"Name":"my-link","SubnetIds":["subnet-b"]}
""", "vl-1", Map.of("VpcLinkId", "vl-1"));
assertEquals("vl-2", link.getPhysicalId());
assertEquals("vl-2", link.getAttributes().get("VpcLinkId"));
verify(apiGatewayV2Service, never()).updateVpcLink(anyString(), anyString(), anyMap());
assertTrue(provisioner.hasReplacementUpdate(link), "the displaced link is deleted after the update");
}
@Test
void vpcLinkWithoutSubnetIdsFailsBeforeCallingTheService() throws Exception {
StackResource link = provisionVpcLink("""
{"Name":"my-link"}
""", null, Map.of());
assertEquals("CREATE_FAILED", link.getStatus());
assertTrue(link.getStatusReason().contains("requires SubnetIds"), link.getStatusReason());
verify(apiGatewayV2Service, never()).createVpcLink(anyString(), anyMap());
}
@Test
void rollbackOfAnInPlaceVpcLinkUpdateRestoresNameAndTags() throws Exception {
VpcLink prior = vpcLink("vl-1", List.of("subnet-a"));
prior.setName("old-name");
prior.setTags(new HashMap<>(Map.of("Env", "old")));
when(apiGatewayV2Service.getVpcLink(REGION, "vl-1")).thenReturn(prior);
when(apiGatewayV2Service.getTags(anyString())).thenReturn(Map.of("Env", "new"));
StackResource link = provisionVpcLink("""
{"Name":"new-name","SubnetIds":["subnet-a"],"Tags":{"Env":"new"}}
""", "vl-1", Map.of("VpcLinkId", "vl-1"));
assertTrue(provisioner.rollbackUpdate(link));
verify(apiGatewayV2Service).updateVpcLink(REGION, "vl-1", Map.of("name", "old-name"));
verify(apiGatewayV2Service).tagResource("arn:aws:apigateway:us-east-1::/vpclinks/vl-1", Map.of("Env", "old"));
assertFalse(link.getAttributes().containsKey("__FlociVpcLinkUpdateSnapshot"));
}
@Test
void integrationPassesItsVpcLinkConnection() throws Exception {
Integration integration = new Integration();
integration.setIntegrationId("int-1");
when(apiGatewayV2Service.createIntegration(eq(REGION), eq(API_ID), anyMap())).thenReturn(integration);
provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", mapper.readTree("""
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY",
"IntegrationUri":"arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/alb/1/2",
"ConnectionType":"VPC_LINK","ConnectionId":"vl-1"}
"""),
engine(), REGION, "000000000000", "test-stack", null, Map.of());
verify(apiGatewayV2Service).createIntegration(eq(REGION), eq(API_ID),
argThat(req -> "VPC_LINK".equals(req.get("connectionType")) && "vl-1".equals(req.get("connectionId"))));
}
@Test
void failedInPlaceVpcLinkUpdateRestoresTagsAndSendsOnlyChangedTags() throws Exception {
String arn = "arn:aws:apigateway:us-east-1::/vpclinks/vl-1";
VpcLink prior = vpcLink("vl-1", List.of("subnet-a"));
prior.setName("old-name");
prior.setTags(new HashMap<>(Map.of("floci:override-id", "vl-1", "Env", "old")));
when(apiGatewayV2Service.getVpcLink(REGION, "vl-1")).thenReturn(prior);
when(apiGatewayV2Service.getTags(arn)).thenReturn(
Map.of("floci:override-id", "vl-1", "Env", "old"),
Map.of("floci:override-id", "vl-1", "Env", "new"));
when(apiGatewayV2Service.updateVpcLink(REGION, "vl-1", Map.of("name", "new-name")))
.thenThrow(new AwsException("BadRequestException", "rename failed", 400));
StackResource link = provisionVpcLink("""
{"Name":"new-name","SubnetIds":["subnet-a"],"Tags":{"floci:override-id":"vl-1","Env":"new"}}
""", "vl-1", Map.of("VpcLinkId", "vl-1"));
assertTrue(link.getStatus().endsWith("_FAILED"), link.getStatus());
verify(apiGatewayV2Service).tagResource(arn, Map.of("Env", "new"));
verify(apiGatewayV2Service).tagResource(arn, Map.of("Env", "old"));
verify(apiGatewayV2Service).updateVpcLink(REGION, "vl-1", Map.of("name", "old-name"));
assertFalse(link.getAttributes().containsKey("__FlociUpdateRollbackFailure"));
assertFalse(link.getAttributes().containsKey("__FlociVpcLinkUpdateSnapshot"));
}
@Test
void integrationUpdateWithoutConnectionResetsItToInternet() throws Exception {
stubIntegrationUpdate(priorVpcLinkIntegration());
StackResource integration = provisionIntegration("""
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend"}
""");
assertTrue(integration.getStatus().endsWith("_COMPLETE"), integration.getStatus());
verify(apiGatewayV2Service).replaceIntegrationConnection(REGION, API_ID, "int-1", "INTERNET", null);
}
@Test
void rollbackOfAnIntegrationUpdateRestoresItsConnection() throws Exception {
stubIntegrationUpdate(priorVpcLinkIntegration());
StackResource integration = provisionIntegration("""
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend",
"ConnectionType":"VPC_LINK","ConnectionId":"vl-2"}
""");
assertTrue(provisioner.rollbackUpdate(integration));
verify(apiGatewayV2Service).replaceIntegrationConnection(REGION, API_ID, "int-1", "VPC_LINK", "vl-1");
assertFalse(integration.getAttributes().containsKey("__FlociIntegrationConnectionSnapshot"));
}
@Test
void rollbackOfAnIntegrationUpdateWithOtherChangesRestoresConnectionButReportsFailure() throws Exception {
stubIntegrationUpdate(priorVpcLinkIntegration());
StackResource integration = provisionIntegration("""
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://other-backend",
"ConnectionType":"VPC_LINK","ConnectionId":"vl-2"}
""");
assertFalse(provisioner.rollbackUpdate(integration), "the IntegrationUri change has no rollback");
verify(apiGatewayV2Service).replaceIntegrationConnection(REGION, API_ID, "int-1", "VPC_LINK", "vl-1");
}
@Test
void failedIntegrationUpdateRestoresItsConnection() throws Exception {
stubIntegrationUpdate(priorVpcLinkIntegration());
when(apiGatewayV2Service.updateIntegration(eq(REGION), eq(API_ID), eq("int-1"), anyMap()))
.thenThrow(new AwsException("NotFoundException", "Integration not found", 404));
StackResource integration = provisionIntegration("""
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend",
"ConnectionType":"VPC_LINK","ConnectionId":"vl-2"}
""");
assertTrue(integration.getStatus().endsWith("_FAILED"), integration.getStatus());
InOrder order = inOrder(apiGatewayV2Service);
order.verify(apiGatewayV2Service).replaceIntegrationConnection(REGION, API_ID, "int-1", "VPC_LINK", "vl-2");
order.verify(apiGatewayV2Service).updateIntegration(eq(REGION), eq(API_ID), eq("int-1"), anyMap());
order.verify(apiGatewayV2Service).replaceIntegrationConnection(REGION, API_ID, "int-1", "VPC_LINK", "vl-1");
assertFalse(integration.getAttributes().containsKey("__FlociUpdateRollbackFailure"));
assertFalse(integration.getAttributes().containsKey("__FlociIntegrationConnectionSnapshot"));
}
private static Integration priorVpcLinkIntegration() {
Integration prior = new Integration();
prior.setIntegrationId("int-1");
prior.setIntegrationType("HTTP_PROXY");
prior.setIntegrationUri("http://backend");
prior.setPayloadFormatVersion("2.0");
prior.setConnectionType("VPC_LINK");
prior.setConnectionId("vl-1");
return prior;
}
private void stubIntegrationUpdate(Integration prior) {
when(apiGatewayV2Service.getIntegration(REGION, API_ID, "int-1")).thenReturn(prior);
when(apiGatewayV2Service.updateIntegration(eq(REGION), eq(API_ID), eq("int-1"), anyMap())).thenReturn(prior);
when(apiGatewayV2Service.replaceIntegrationConnection(eq(REGION), eq(API_ID), eq("int-1"), anyString(), any()))
.thenReturn(prior);
}
private StackResource provisionIntegration(String properties) throws Exception {
return provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", mapper.readTree(properties),
engine(), REGION, "000000000000", "test-stack", "int-1", Map.of("IntegrationId", "int-1"));
}
private StackResource provision(JsonNode properties, String existingPhysicalId,
Map<String, String> existingAttributes) {
return provisioner.provision("HttpApi", "AWS::ApiGatewayV2::Api", properties, engine(), REGION,
"000000000000", "test-stack", existingPhysicalId, existingAttributes);
}
private StackResource provisionVpcLink(String properties, String existingPhysicalId,
Map<String, String> existingAttributes) throws Exception {
return provisioner.provision("VpcLink", "AWS::ApiGatewayV2::VpcLink", mapper.readTree(properties),
engine(), REGION, "000000000000", "test-stack", existingPhysicalId, existingAttributes);
}
private static VpcLink vpcLink(String id, List<String> subnetIds) {
VpcLink link = new VpcLink();
link.setVpcLinkId(id);
link.setName("my-link");
link.setSubnetIds(subnetIds);
return link;
}
private JsonNode body(String body) throws Exception {
return mapper.readTree("""
{"Name":"test-api","ProtocolType":"HTTP","Body":%s}
@@ -27,6 +27,14 @@ class CfnCreateOnlyPropertiesTest {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::S3::Bucket", "VersioningConfiguration"));
}
@Test
void isCreateOnly_vpcLinkReplacesOnlyForSubnetsAndSecurityGroups() {
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGatewayV2::VpcLink", "SubnetIds"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGatewayV2::VpcLink", "SecurityGroupIds"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGatewayV2::VpcLink", "Name"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGatewayV2::VpcLink", "Tags"));
}
@Test
void isCreateOnly_treatsEmptySchemaListAsAuthoritative() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name"));
@@ -0,0 +1,226 @@
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.Integration;
import io.github.hectorvent.floci.services.apigatewayv2.model.VpcLink;
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* AWS::ApiGatewayV2::VpcLink through a real stack: Ref and Fn::GetAtt VpcLinkId resolve to the
* real link, an integration can use it through ConnectionId, a Name change updates the link in
* place, a SubnetIds change replaces it, and DeleteStack removes it. A failed update puts the link
* and the integration connection back.
*/
@QuarkusTest
class CloudFormationApiGatewayV2VpcLinkIntegrationTest {
private static final String REGION = "us-east-1";
private static final String STACK_NAME = "vpclink-stack";
private static final String VPC_LINK_CONNECTION =
",\"ConnectionType\":\"VPC_LINK\",\"ConnectionId\":{\"Ref\":\"VpcLink\"}";
private static final String FAILING_RESOURCE =
",\"Broken\":{\"Type\":\"AWS::ApiGatewayV2::VpcLink\",\"DependsOn\":\"Integration\","
+ "\"Properties\":{\"Name\":\"broken\"}}";
@Inject
ApiGatewayV2Service apiGatewayV2Service;
@Inject
CloudFormationService cloudFormationService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void vpcLinkLifecycleFollowsTheCloudFormationUpdateRules() {
stackAction("CreateStack", STACK_NAME, template("first-name", "subnet-aaaa1111"));
waitForStackStatus(STACK_NAME, "CREATE_COMPLETE");
Stack created = stack(STACK_NAME);
String vpcLinkId = created.getOutputs().get("VpcLinkRef");
assertEquals(vpcLinkId, created.getOutputs().get("VpcLinkIdAttr"));
VpcLink link = apiGatewayV2Service.getVpcLink(REGION, vpcLinkId);
assertEquals("first-name", link.getName());
assertEquals(List.of("subnet-aaaa1111"), link.getSubnetIds());
assertEquals(Map.of("Env", "test"), link.getTags());
Integration integration = integration(created);
assertEquals("VPC_LINK", integration.getConnectionType());
assertEquals(vpcLinkId, integration.getConnectionId());
stackAction("UpdateStack", STACK_NAME, template("second-name", "subnet-aaaa1111"));
waitForStackStatus(STACK_NAME, "UPDATE_COMPLETE");
assertEquals(vpcLinkId, stack(STACK_NAME).getOutputs().get("VpcLinkRef"), "a Name change keeps the same link");
assertEquals("second-name", apiGatewayV2Service.getVpcLink(REGION, vpcLinkId).getName());
stackAction("UpdateStack", STACK_NAME, template("second-name", "subnet-bbbb2222"));
waitForStackStatus(STACK_NAME, "UPDATE_COMPLETE");
Stack replaced = stack(STACK_NAME);
String newVpcLinkId = replaced.getOutputs().get("VpcLinkRef");
assertNotEquals(vpcLinkId, newVpcLinkId, "a SubnetIds change replaces the link");
assertEquals(List.of("subnet-bbbb2222"), apiGatewayV2Service.getVpcLink(REGION, newVpcLinkId).getSubnetIds());
assertNotFound(vpcLinkId);
assertEquals(newVpcLinkId, integration(replaced).getConnectionId());
stackAction("DeleteStack", STACK_NAME, null);
waitForStackStatus(STACK_NAME, "DELETE_COMPLETE");
assertNotFound(newVpcLinkId);
}
@Test
void failedUpdateRestoresTheIntegrationConnectionAndDeletesTheNewLink() {
String stackName = "vpclink-rollback-stack";
stackAction("CreateStack", stackName,
template("rollback-link", "subnet-aaaa1111", "{}", VPC_LINK_CONNECTION, ""));
waitForStackStatus(stackName, "CREATE_COMPLETE");
String vpcLinkId = stack(stackName).getOutputs().get("VpcLinkRef");
stackAction("UpdateStack", stackName,
template("rollback-link", "subnet-bbbb2222", "{}", VPC_LINK_CONNECTION, FAILING_RESOURCE));
waitForStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
Stack rolledBack = stack(stackName);
assertEquals(vpcLinkId, rolledBack.getOutputs().get("VpcLinkRef"));
assertEquals(List.of("subnet-aaaa1111"), apiGatewayV2Service.getVpcLink(REGION, vpcLinkId).getSubnetIds());
Integration integration = integration(rolledBack);
assertEquals("VPC_LINK", integration.getConnectionType());
assertEquals(vpcLinkId, integration.getConnectionId());
assertEquals(1, apiGatewayV2Service.getVpcLinks(REGION).stream()
.filter(link -> "rollback-link".equals(link.getName()))
.count(), "the link created by the failed update is deleted");
}
@Test
void removingTheConnectionFromTheTemplateResetsTheIntegrationToInternet() {
String stackName = "vpclink-connection-stack";
stackAction("CreateStack", stackName,
template("connection-link", "subnet-aaaa1111", "{}", VPC_LINK_CONNECTION, ""));
waitForStackStatus(stackName, "CREATE_COMPLETE");
stackAction("UpdateStack", stackName, template("connection-link", "subnet-aaaa1111", "{}", "", ""));
waitForStackStatus(stackName, "UPDATE_COMPLETE");
Integration integration = integration(stack(stackName));
assertEquals("INTERNET", integration.getConnectionType());
assertNull(integration.getConnectionId());
}
@Test
void renamingALinkKeepsAReservedTagSetAtCreation() {
String stackName = "vpclink-reserved-tag-stack";
String tags = "{\"floci:note\":\"kept\",\"Env\":\"test\"}";
stackAction("CreateStack", stackName, template("reserved-v1", "subnet-aaaa1111", tags, "", ""));
waitForStackStatus(stackName, "CREATE_COMPLETE");
String vpcLinkId = stack(stackName).getOutputs().get("VpcLinkRef");
stackAction("UpdateStack", stackName, template("reserved-v2", "subnet-aaaa1111", tags, "", ""));
waitForStackStatus(stackName, "UPDATE_COMPLETE");
VpcLink link = apiGatewayV2Service.getVpcLink(REGION, vpcLinkId);
assertEquals("reserved-v2", link.getName());
assertEquals(Map.of("floci:note", "kept", "Env", "test"), link.getTags());
}
private void assertNotFound(String vpcLinkId) {
AwsException e = assertThrows(AwsException.class, () -> apiGatewayV2Service.getVpcLink(REGION, vpcLinkId));
assertEquals("NotFoundException", e.getErrorCode());
}
private Integration integration(Stack stack) {
StackResource api = stack.getResources().get("HttpApi");
StackResource integration = stack.getResources().get("Integration");
return apiGatewayV2Service.getIntegration(REGION, api.getPhysicalId(), integration.getPhysicalId());
}
private Stack stack(String stackName) {
return cloudFormationService.describeStacks(stackName, REGION).getFirst();
}
private static void stackAction(String action, String stackName, String template) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", action)
.formParam("StackName", stackName);
if (template != null) {
request.formParam("TemplateBody", template);
}
request.when().post("/").then().statusCode(200);
}
private void waitForStackStatus(String stackName, String expected) {
String status = null;
for (int attempt = 0; attempt < 200; attempt++) {
try {
status = cloudFormationService.describeStacks(stackName, REGION).getFirst().getStatus();
} catch (AwsException e) {
// A deleted stack can no longer be described by name.
status = "DELETE_COMPLETE";
}
if (expected.equals(status)) {
return;
}
try {
Thread.sleep(25);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError("Interrupted while waiting for stack status", e);
}
}
throw new AssertionError("Stack did not reach " + expected + ", last status " + status);
}
private static String template(String linkName, String subnetId) {
return """
{"Resources":{
"VpcLink":{"Type":"AWS::ApiGatewayV2::VpcLink","Properties":{
"Name":"%s","SubnetIds":["%s"],"SecurityGroupIds":["sg-cccc3333"],"Tags":{"Env":"test"}}},
"HttpApi":{"Type":"AWS::ApiGatewayV2::Api","Properties":{
"Name":"vpclink-api","ProtocolType":"HTTP"}},
"Integration":{"Type":"AWS::ApiGatewayV2::Integration","Properties":{
"ApiId":{"Ref":"HttpApi"},"IntegrationType":"HTTP_PROXY","IntegrationMethod":"ANY",
"IntegrationUri":"arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/alb/1/2",
"ConnectionType":"VPC_LINK","ConnectionId":{"Ref":"VpcLink"},
"PayloadFormatVersion":"1.0"}}},
"Outputs":{
"VpcLinkRef":{"Value":{"Ref":"VpcLink"}},
"VpcLinkIdAttr":{"Value":{"Fn::GetAtt":["VpcLink","VpcLinkId"]}}}}
""".formatted(linkName, subnetId);
}
/**
* A link, an HTTP API and an integration. {@code connection} adds integration properties and
* {@code extraResources} adds resources, both as JSON fragments that start with a comma.
*/
private static String template(String linkName, String subnetId, String tags, String connection,
String extraResources) {
return """
{"Resources":{
"VpcLink":{"Type":"AWS::ApiGatewayV2::VpcLink","Properties":{
"Name":"%s","SubnetIds":["%s"],"Tags":%s}},
"HttpApi":{"Type":"AWS::ApiGatewayV2::Api","Properties":{
"Name":"vpclink-api","ProtocolType":"HTTP"}},
"Integration":{"Type":"AWS::ApiGatewayV2::Integration","Properties":{
"ApiId":{"Ref":"HttpApi"},"IntegrationType":"HTTP_PROXY","IntegrationMethod":"ANY",
"IntegrationUri":"http://backend.example","PayloadFormatVersion":"1.0"%s}}%s},
"Outputs":{"VpcLinkRef":{"Value":{"Ref":"VpcLink"}}}}
""".formatted(linkName, subnetId, tags, connection, extraResources);
}
}