feat(cloudformation): provision AWS::EC2::VPCGatewayAttachment (#1972)

* feat(cloudformation): provision AWS::EC2::VPCGatewayAttachment

Attach the internet gateway to the VPC via Ec2Service so route tables
pointing at the IGW behave like AWS. The physical id encodes vpc|igw so
stack deletion can detach. The VpnGatewayId variant records the
attachment without an attach call (no VPN gateway model).

Fixes #1970

* refactor(cloudformation): move VPCGatewayAttachment into a per-service provisioner

The monolithic switch in CloudFormationResourceProvisioner is being split into
per-service CfnResourceProvisioner implementations, so AWS::EC2::VPCGatewayAttachment
lands in the new structure instead of growing the switch.

Ec2VpcGatewayAttachmentCfnProvisioner injects only Ec2Service and is picked up by
CloudFormationResourceRegistry through CDI, no registration needed. The provision
logic and the physical-id encoding (vpcId|gatewayId) carry over unchanged, and
delete() detaches the internet gateway so stack deletion no longer leaves the
attachment orphaned.

Removes the AWS::EC2::VPCGatewayAttachment arms from the provision and delete
switches along with provisionVpcGatewayAttachment and
detachVpcGatewayAttachmentSafe, leaving CloudFormationResourceProvisioner
identical to main.

* fix(cloudformation): validate VPCGatewayAttachment and make its delete type-safe

Four review findings on the attachment provisioner.

A template that omitted VpcId still reported CREATE_COMPLETE: the null went
into attachInternetGateway, so DescribeInternetGateways exposed an attachment
with no VPC and every later detach on that gateway threw on the null compare.
VpcId is now required, as is exactly one of InternetGatewayId or VpnGatewayId.

The VpnGatewayId form recorded a physical id and did nothing else, so
CloudFormation reported CREATE_COMPLETE for an attachment that does not exist
and cannot be observed — there is no VPN gateway model behind it. It now fails
the resource with an explicit message instead of claiming success.

Updates orphaned the previous pair. The new pair is attached first and the old
one detached only after that succeeds, so a failed update leaves the previous
attachment intact; an unchanged update no longer re-attaches and duplicates.

Deletion classified the gateway by the id's igw- prefix, so an igw-* value
supplied as VpnGatewayId could detach a gateway the stack never attached. The
physical id now carries a kind tag (igw|<vpcId>|<gatewayId>) and delete acts
only on ids this provisioner wrote.
This commit is contained in:
lex00 authored and GitHub committed 2026-08-04 22:24:36 -05:00
1 parent 5cb26ff117
commit 1a99721ae0
3 files changed
+383

No files matched your search

@@ -0,0 +1,130 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.quarkus.test.junit.QuarkusTest;
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.hamcrest.Matchers.not;
/**
* End-to-end check that CloudFormation provisions AWS::EC2::VPCGatewayAttachment for real
* (issue #1970): the internet gateway ends up attached to the VPC in Ec2Service, and
* DeleteStack detaches it. Metadata-only resources, so the test is Docker-free.
*/
@QuarkusTest
class CloudFormationVpcGatewayAttachmentIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
private static final String EC2_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
@Test
void createStackAttachesInternetGatewayToVpc() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-vpcgw-stack-" + suffix;
String template = """
{
"Resources": {
"Vpc": {
"Type": "AWS::EC2::VPC",
"Properties": {"CidrBlock": "10.42.0.0/16"}
},
"Igw": {"Type": "AWS::EC2::InternetGateway"},
"Attachment": {
"Type": "AWS::EC2::VPCGatewayAttachment",
"Properties": {
"VpcId": {"Ref": "Vpc"},
"InternetGatewayId": {"Ref": "Igw"}
}
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
String resourcesXml = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
String vpcId = physicalIdByLogicalId(resourcesXml, "Vpc");
String igwId = physicalIdByLogicalId(resourcesXml, "Igw");
// The gateway reports an attachment to the stack's VPC.
describeIgw(igwId)
.then()
.statusCode(200)
.body(containsString(vpcId));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
// Gateway (and with it the attachment) is gone after stack deletion.
String afterDelete = describeIgw(igwId).then().statusCode(200).extract().asString();
assertThat(afterDelete, not(containsString(vpcId)));
}
private static io.restassured.response.Response describeIgw(String igwId) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeInternetGateways")
.formParam("InternetGatewayId.1", igwId)
.formParam("Version", "2016-11-15")
.when()
.post("/");
}
private static String physicalIdByLogicalId(String xml, String logicalId) {
String logicalMarker = "<LogicalResourceId>" + logicalId + "</LogicalResourceId>";
int logicalIdx = xml.indexOf(logicalMarker);
assertThat("logical id '" + logicalId + "' present in DescribeStackResources output",
logicalIdx, not(equalTo(-1)));
int memberStart = xml.lastIndexOf("<member>", logicalIdx);
int memberEnd = xml.indexOf("</member>", logicalIdx);
String member = xml.substring(memberStart, memberEnd);
String physicalOpen = "<PhysicalResourceId>";
int pStart = member.indexOf(physicalOpen) + physicalOpen.length();
int pEnd = member.indexOf("</PhysicalResourceId>");
return member.substring(pStart, pEnd);
}
}
@@ -0,0 +1,150 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* The failure modes the internet-gateway happy path does not reach: a missing VpcId, the
* unbacked VPN form, an update that would orphan the previous pair, and a physical id whose
* gateway id looks like an internet gateway but was never declared as one.
*/
class Ec2VpcGatewayAttachmentCfnProvisionerTest {
private static final String REGION = "us-east-1";
private final Ec2Service ec2 = mock(Ec2Service.class);
private final Ec2VpcGatewayAttachmentCfnProvisioner provisioner =
new Ec2VpcGatewayAttachmentCfnProvisioner(ec2);
private final ObjectMapper mapper = new ObjectMapper();
@Test
void internetGatewayAttachmentRecordsAKindTaggedPhysicalId() {
StackResource r = resource();
provisioner.provision(r, props("vpc-1", "igw-1", null), ctx());
verify(ec2).attachInternetGateway(REGION, "igw-1", "vpc-1");
assertEquals("igw|vpc-1|igw-1", r.getPhysicalId());
}
@Test
void missingVpcIdIsRejectedInsteadOfAttachingNull() {
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource(), props(null, "igw-1", null), ctx()));
assertEquals("ValidationError", e.getErrorCode());
verifyNoInteractions(ec2);
}
@Test
void exactlyOneGatewayIsRequired() {
assertThrows(AwsException.class,
() -> provisioner.provision(resource(), props("vpc-1", null, null), ctx()));
assertThrows(AwsException.class,
() -> provisioner.provision(resource(), props("vpc-1", "igw-1", "vgw-1"), ctx()));
verifyNoInteractions(ec2);
}
@Test
void vpnGatewayAttachmentFailsRatherThanReportingSuccess() {
StackResource r = resource();
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(r, props("vpc-1", null, "vgw-1"), ctx()));
assertTrue(e.getMessage().contains("VpnGatewayId"), e.getMessage());
// No physical id, so nothing for delete to act on later.
assertEquals(null, r.getPhysicalId());
verifyNoInteractions(ec2);
}
@Test
void anInternetGatewayIdDeclaredAsAVpnGatewayNeverReachesDetach() {
// The template is malformed, but the danger is the delete path treating
// the value as an internet gateway and detaching one this stack never attached.
assertThrows(AwsException.class,
() -> provisioner.provision(resource(), props("vpc-1", null, "igw-existing"), ctx()));
provisioner.delete("AWS::EC2::VPCGatewayAttachment", "vgw|vpc-1|igw-existing", REGION);
provisioner.delete("AWS::EC2::VPCGatewayAttachment", "vpc-1|igw-existing", REGION);
verifyNoInteractions(ec2);
}
@Test
void updateAttachesTheNewPairBeforeDetachingTheOld() {
StackResource r = resource();
r.setPhysicalId("igw|vpc-old|igw-old");
provisioner.provision(r, props("vpc-new", "igw-new", null), ctx());
// Order matters: a failed attach must leave the previous attachment alone.
var order = inOrder(ec2);
order.verify(ec2).attachInternetGateway(REGION, "igw-new", "vpc-new");
order.verify(ec2).detachInternetGateway(REGION, "igw-old", "vpc-old");
assertEquals("igw|vpc-new|igw-new", r.getPhysicalId());
}
@Test
void unchangedUpdateDoesNotReattach() {
StackResource r = resource();
r.setPhysicalId("igw|vpc-1|igw-1");
provisioner.provision(r, props("vpc-1", "igw-1", null), ctx());
assertEquals("igw|vpc-1|igw-1", r.getPhysicalId());
verifyNoInteractions(ec2);
}
@Test
void deleteDetachesTheRecordedPair() {
provisioner.delete("AWS::EC2::VPCGatewayAttachment", "igw|vpc-1|igw-1", REGION);
verify(ec2).detachInternetGateway(REGION, "igw-1", "vpc-1");
verifyNoMoreInteractions(ec2);
}
private ProvisionContext ctx() {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
return new ProvisionContext(engine, REGION, "000000000000", "my-stack");
}
private StackResource resource() {
StackResource r = new StackResource();
r.setLogicalId("Attachment");
r.setResourceType("AWS::EC2::VPCGatewayAttachment");
r.setAttributes(new HashMap<>());
return r;
}
private ObjectNode props(String vpcId, String igwId, String vgwId) {
ObjectNode props = mapper.createObjectNode();
if (vpcId != null) { props.put("VpcId", vpcId); }
if (igwId != null) { props.put("InternetGatewayId", igwId); }
if (vgwId != null) { props.put("VpnGatewayId", vgwId); }
return props;
}
}