Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudformation): provision AWS::EC2::VPCGatewayAttachment (#1972)
lex001a99721ae046
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcGatewayAttachmentCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcGatewayAttachmentCfnProvisioner.javanew file mode 100644index 0000000000..8e020b2018--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcGatewayAttachmentCfnProvisioner.java@@ -0,0 +1,103 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.ec2.Ec2Service;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.util.Set;++/**+ * CloudFormation provisioning for {@code AWS::EC2::VPCGatewayAttachment} (issue #1970).+ *+ * <p>The physical id is {@code igw|<vpcId>|<gatewayId>}. The leading kind tag records how the+ * attachment was declared rather than inferring it from the gateway id's prefix, so a template+ * that puts an {@code igw-*} value in {@code VpnGatewayId} can never make {@link #delete} tear+ * down an internet-gateway attachment this stack never created.+ */+@ApplicationScoped+public class Ec2VpcGatewayAttachmentCfnProvisioner implements CfnResourceProvisioner {++ private static final Logger LOG = Logger.getLogger(Ec2VpcGatewayAttachmentCfnProvisioner.class);++ /** Kind tag for the internet-gateway form — the only form with a backing model. */+ private static final String IGW_KIND = "igw";++ private final Ec2Service ec2Service;++ @Inject+ public Ec2VpcGatewayAttachmentCfnProvisioner(Ec2Service ec2Service) {+ this.ec2Service = ec2Service;+ }++ @Override+ public Set<String> resourceTypes() {+ return Set.of("AWS::EC2::VPCGatewayAttachment");+ }++ @Override+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {+ String vpcId = ctx.resolveOptional(props, "VpcId");+ if (vpcId == null || vpcId.isBlank()) {+ // Without this the attachment lands with a null VpcId, which both shows up in+ // DescribeInternetGateways and makes every later detach on that gateway throw.+ throw new AwsException("ValidationError",+ "Property VpcId is required for AWS::EC2::VPCGatewayAttachment", 400);+ }++ String igwId = ctx.resolveOptional(props, "InternetGatewayId");+ String vgwId = ctx.resolveOptional(props, "VpnGatewayId");+ boolean hasIgw = igwId != null && !igwId.isBlank();+ boolean hasVgw = vgwId != null && !vgwId.isBlank();+ if (hasIgw == hasVgw) {+ throw new AwsException("ValidationError",+ "AWS::EC2::VPCGatewayAttachment requires exactly one of "+ + "InternetGatewayId or VpnGatewayId", 400);+ }+ if (hasVgw) {+ // There is no VPN gateway model to attach to and nothing DescribeVpnGateways+ // could report afterwards, so recording a physical id would report+ // CREATE_COMPLETE for an attachment that does not exist. Fail instead.+ throw new AwsException("ValidationError",+ "AWS::EC2::VPCGatewayAttachment with VpnGatewayId is not supported: "+ + "this emulator has no VPN gateway model", 400);+ }++ String physicalId = IGW_KIND + "|" + vpcId + "|" + igwId;+ String prior = r.getPhysicalId();+ if (physicalId.equals(prior)) {+ // Unchanged on update — re-attaching would duplicate the attachment.+ return;+ }++ ec2Service.attachInternetGateway(ctx.region(), igwId, vpcId);+ // Only after the new pair is attached, so a failed update leaves the previous+ // attachment in place instead of orphaning it.+ detachAttachment(prior, ctx.region());+ r.setPhysicalId(physicalId);+ }++ @Override+ public void delete(String resourceType, String physicalId, String region) {+ detachAttachment(physicalId, region);+ }++ /** Detaches the pair encoded in a physical id, ignoring ids this provisioner did not write. */+ private void detachAttachment(String physicalId, String region) {+ if (physicalId == null || physicalId.isBlank()) {+ return;+ }+ String[] parts = physicalId.split("\\|", 3);+ if (parts.length != 3 || !IGW_KIND.equals(parts[0])) {+ return;+ }+ try {+ ec2Service.detachInternetGateway(region, parts[2], parts[1]);+ } catch (Exception e) {+ LOG.debugv("Could not detach VPC gateway attachment {0}: {1}", physicalId, e.getMessage());+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationVpcGatewayAttachmentIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationVpcGatewayAttachmentIntegrationTest.javanew file mode 100644index 0000000000..c3270d0021--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationVpcGatewayAttachmentIntegrationTest.java@@ -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);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcGatewayAttachmentCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcGatewayAttachmentCfnProvisionerTest.javanew file mode 100644index 0000000000..b95a344e31--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcGatewayAttachmentCfnProvisionerTest.java@@ -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;+ }+}