Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ec2): support transit gateway VPC attachments (#2347)
Michal Schreiber74e43a46320c
diff --git a/compatibility-tests/sdk-test-awscli/test/ec2.bats b/compatibility-tests/sdk-test-awscli/test/ec2.batsindex be5a9b4b65..f56a6c65e9 100644--- a/compatibility-tests/sdk-test-awscli/test/ec2.bats+++ b/compatibility-tests/sdk-test-awscli/test/ec2.bats@@ -9,15 +9,24 @@ setup() {SG_SOURCE_ID=""SG_TARGET_ID=""TRANSIT_GATEWAY_ID=""+ TGW_ATTACHMENT_ID=""+ TGW_VPC_ID=""}teardown() {if [ -n "$PREFIX_LIST_ID" ]; thenaws_cmd ec2 delete-managed-prefix-list --prefix-list-id "$PREFIX_LIST_ID" >/dev/null 2>&1 || truefi+ if [ -n "$TGW_ATTACHMENT_ID" ]; then+ aws_cmd ec2 delete-transit-gateway-vpc-attachment \+ --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" >/dev/null 2>&1 || true+ fiif [ -n "$TRANSIT_GATEWAY_ID" ]; thenaws_cmd ec2 delete-transit-gateway --transit-gateway-id "$TRANSIT_GATEWAY_ID" >/dev/null 2>&1 || truefi+ if [ -n "$TGW_VPC_ID" ]; then+ aws_cmd ec2 delete-vpc --vpc-id "$TGW_VPC_ID" >/dev/null 2>&1 || true+ fifor sg in "$SG_TARGET_ID" "$SG_SOURCE_ID"; doif [ -n "$sg" ]; thenaws_cmd ec2 delete-security-group --group-id "$sg" >/dev/null 2>&1 || true@@ -339,3 +348,96 @@ create_sg_pair() {assert_failureassert_output --partial "InvalidTransitGatewayID.NotFound"}++# ─── transit gateway VPC attachments ────────────────────────────────────────++# Creates a gateway, a VPC and one subnet, setting TRANSIT_GATEWAY_ID, TGW_VPC_ID and TGW_SUBNET_ID.+create_attachment_fixture() {+ local out+ out=$(aws_cmd ec2 create-transit-gateway --description "bats attachment host")+ TRANSIT_GATEWAY_ID=$(json_get "$out" '.TransitGateway.TransitGatewayId')+ out=$(aws_cmd ec2 create-vpc --cidr-block 10.80.0.0/16)+ TGW_VPC_ID=$(json_get "$out" '.Vpc.VpcId')+ out=$(aws_cmd ec2 create-subnet --vpc-id "$TGW_VPC_ID" --cidr-block 10.80.1.0/24 \+ --availability-zone "${AWS_DEFAULT_REGION}a")+ TGW_SUBNET_ID=$(json_get "$out" '.Subnet.SubnetId')+}++@test "EC2: attach a VPC to a transit gateway and read it back both ways" {+ create_attachment_fixture++ run aws_cmd ec2 create-transit-gateway-vpc-attachment \+ --transit-gateway-id "$TRANSIT_GATEWAY_ID" \+ --vpc-id "$TGW_VPC_ID" \+ --subnet-ids "$TGW_SUBNET_ID" \+ --tag-specifications 'ResourceType=transit-gateway-attachment,Tags=[{Key=Name,Value=bats-attach}]'+ assert_success+ TGW_ATTACHMENT_ID=$(json_get "$output" '.TransitGatewayVpcAttachment.TransitGatewayAttachmentId')+ [ "$(json_get "$output" '.TransitGatewayVpcAttachment.State')" = "available" ]+ [ "$(json_get "$output" '.TransitGatewayVpcAttachment.SubnetIds[0]')" = "$TGW_SUBNET_ID" ]+ # The attachment's own default, which differs from the gateway's.+ [ "$(json_get "$output" '.TransitGatewayVpcAttachment.Options.SecurityGroupReferencingSupport')" = "enable" ]++ run aws_cmd ec2 describe-transit-gateway-vpc-attachments \+ --transit-gateway-attachment-ids "$TGW_ATTACHMENT_ID"+ assert_success+ [ "$(json_get "$output" '.TransitGatewayVpcAttachments[0].VpcId')" = "$TGW_VPC_ID" ]+ [ "$(json_get "$output" '.TransitGatewayVpcAttachments[0].Tags[0].Value')" = "bats-attach" ]++ # The resource-agnostic form is a different shape: typed resource plus the association.+ run aws_cmd ec2 describe-transit-gateway-attachments \+ --transit-gateway-attachment-ids "$TGW_ATTACHMENT_ID"+ assert_success+ [ "$(json_get "$output" '.TransitGatewayAttachments[0].ResourceType')" = "vpc" ]+ [ "$(json_get "$output" '.TransitGatewayAttachments[0].ResourceId')" = "$TGW_VPC_ID" ]+ [ "$(json_get "$output" '.TransitGatewayAttachments[0].Association.State')" = "associated" ]+ rtb=$(json_get "$output" '.TransitGatewayAttachments[0].Association.TransitGatewayRouteTableId')+ case "$rtb" in tgw-rtb-*) ;; *) return 1 ;; esac+}++@test "EC2: modify a transit gateway VPC attachment" {+ create_attachment_fixture+ local out subnet_b+ out=$(aws_cmd ec2 create-transit-gateway-vpc-attachment --transit-gateway-id "$TRANSIT_GATEWAY_ID" \+ --vpc-id "$TGW_VPC_ID" --subnet-ids "$TGW_SUBNET_ID")+ TGW_ATTACHMENT_ID=$(json_get "$out" '.TransitGatewayVpcAttachment.TransitGatewayAttachmentId')+ out=$(aws_cmd ec2 create-subnet --vpc-id "$TGW_VPC_ID" --cidr-block 10.80.2.0/24 \+ --availability-zone "${AWS_DEFAULT_REGION}b")+ subnet_b=$(json_get "$out" '.Subnet.SubnetId')++ run aws_cmd ec2 modify-transit-gateway-vpc-attachment \+ --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" \+ --add-subnet-ids "$subnet_b" \+ --options 'DnsSupport=disable'+ assert_success+ [ "$(json_get "$output" '.TransitGatewayVpcAttachment.Options.DnsSupport')" = "disable" ]+ count=$(json_get "$output" '.TransitGatewayVpcAttachment.SubnetIds | length')+ [ "$count" = "2" ]++ run aws_cmd ec2 modify-transit-gateway-vpc-attachment \+ --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" \+ --remove-subnet-ids "$TGW_SUBNET_ID" "$subnet_b"+ assert_failure+ assert_output --partial "InsufficientSubnetsException"+}++@test "EC2: a transit gateway with an attachment cannot be deleted" {+ create_attachment_fixture+ local out+ out=$(aws_cmd ec2 create-transit-gateway-vpc-attachment --transit-gateway-id "$TRANSIT_GATEWAY_ID" \+ --vpc-id "$TGW_VPC_ID" --subnet-ids "$TGW_SUBNET_ID")+ TGW_ATTACHMENT_ID=$(json_get "$out" '.TransitGatewayVpcAttachment.TransitGatewayAttachmentId')++ run aws_cmd ec2 delete-transit-gateway --transit-gateway-id "$TRANSIT_GATEWAY_ID"+ assert_failure+ assert_output --partial "IncorrectState"++ run aws_cmd ec2 delete-transit-gateway-vpc-attachment \+ --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID"+ assert_success+ TGW_ATTACHMENT_ID=""++ run aws_cmd ec2 delete-transit-gateway --transit-gateway-id "$TRANSIT_GATEWAY_ID"+ assert_success+ TRANSIT_GATEWAY_ID=""+}diff --git a/docs/services/ec2.md b/docs/services/ec2.mdindex 1a591eefac..4d4b39e6d6 100644--- a/docs/services/ec2.md+++ b/docs/services/ec2.md@@ -340,6 +340,38 @@ is slow, so callers see `available` and `deleted` immediately. `ModifyTransitGat`DeleteTransitGateway` echo the gateway without its `tagSet`, matching AWS; `CreateTransitGateway`and `DescribeTransitGateways` include it.+### Transit Gateway VPC Attachments++| Action | Description |+|--------|-------------|+| CreateTransitGatewayVpcAttachment | Attaches a VPC to a transit gateway through one subnet per availability zone. |+| DescribeTransitGatewayVpcAttachments | Lists or returns VPC attachments with their subnets and options. |+| DescribeTransitGatewayAttachments | Returns the same attachments in the resource-agnostic shape, including the route table association. |+| ModifyTransitGatewayVpcAttachment | Adds or removes attachment subnets and updates its options. |+| DeleteTransitGatewayVpcAttachment | Deletes a VPC attachment. |++An attachment's option defaults are its own rather than the gateway's: `dnsSupport` and+`securityGroupReferencingSupport` enabled, `ipv6Support` and `applianceModeSupport` disabled. Note+that `securityGroupReferencingSupport` is enabled here while a transit gateway defaults it to+disabled.++The attachment is associated with the gateway's default route table only when the gateway carries+`defaultRouteTableAssociation` enabled; a gateway created without it produces an attachment with no+association. That association is reported by `DescribeTransitGatewayAttachments` alone — the+VPC-specific describe does not carry it, and the resource-agnostic one carries neither the subnets+nor the options in exchange.++Subnets must belong to the VPC being attached and no two may share an availability zone; one from+another VPC is reported as `InvalidSubnetID.NotFound` rather than as a mismatch. A VPC can be+attached to a given gateway once, so a second attempt returns `DuplicateTransitGatewayAttachment`.+Removing every subnet returns `InsufficientSubnetsException`, and a gateway with a live attachment+cannot be deleted — `IncorrectState`, naming the attachments.++As with the gateway itself, state is reported settled rather than transitional, and the echoes are+trimmed the way AWS trims them: modify omits the `tagSet`, and delete omits both the `tagSet` and+the subnets. `Ipv6Support` is accepted without checking that the subnets carry IPv6 CIDRs, which+real AWS rejects; Floci does not model subnet IPv6 allocation.+### NAT Gateways| Action | Description |diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.javaindex 9c74d417d8..f8582c4efd 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java@@ -89,6 +89,16 @@ public class Ec2QueryHandler {case "DescribeTransitGateways" -> handleDescribeTransitGateways(params, region);case "ModifyTransitGateway" -> handleModifyTransitGateway(params, region);case "DeleteTransitGateway" -> handleDeleteTransitGateway(params, region);+ case "CreateTransitGatewayVpcAttachment" ->+ handleCreateTransitGatewayVpcAttachment(params, region);+ case "DescribeTransitGatewayVpcAttachments" ->+ handleDescribeTransitGatewayVpcAttachments(params, region);+ case "DescribeTransitGatewayAttachments" ->+ handleDescribeTransitGatewayAttachments(params, region);+ case "ModifyTransitGatewayVpcAttachment" ->+ handleModifyTransitGatewayVpcAttachment(params, region);+ case "DeleteTransitGatewayVpcAttachment" ->+ handleDeleteTransitGatewayVpcAttachment(params, region);case "CreateDefaultVpc" -> handleCreateDefaultVpc(params, region);case "AssociateVpcCidrBlock" -> handleAssociateVpcCidrBlock(params, region);case "DisassociateVpcCidrBlock" -> handleDisassociateVpcCidrBlock(params, region);@@ -404,17 +414,25 @@ public class Ec2QueryHandler {return perms;}+ /**+ * Reads a request's tag specifications. Most EC2 actions carry them under the wire name+ * {@code TagSpecification}, but a handful — {@code CreateTransitGatewayVpcAttachment} among+ * them — declare no {@code locationName} and so serialize as {@code TagSpecifications}. Both+ * spellings are read, because an action that used the plural silently lost every tag.+ */private List<Tag> parseTagsForResource(MultivaluedMap<String, String> p, String resourceType) {List<Tag> tags = new ArrayList<>();- for (int i = 1; ; i++) {- String resType = p.getFirst("TagSpecification." + i + ".ResourceType");- if (resType == null) break;- if (resourceType.equals(resType)) {- for (int j = 1; ; j++) {- String key = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");- if (key == null) break;- String value = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");- tags.add(new Tag(key, value));+ for (String prefix : new String[] {"TagSpecification", "TagSpecifications"}) {+ for (int i = 1; ; i++) {+ String resType = p.getFirst(prefix + "." + i + ".ResourceType");+ if (resType == null) break;+ if (resourceType.equals(resType)) {+ for (int j = 1; ; j++) {+ String key = p.getFirst(prefix + "." + i + ".Tag." + j + ".Key");+ if (key == null) break;+ String value = p.getFirst(prefix + "." + i + ".Tag." + j + ".Value");+ tags.add(new Tag(key, value));+ }}}}@@ -1258,6 +1276,139 @@ public class Ec2QueryHandler {return options;}+ private Response handleCreateTransitGatewayVpcAttachment(MultivaluedMap<String, String> p, String region) {+ TransitGatewayVpcAttachment attachment = service.createTransitGatewayVpcAttachment(+ region,+ p.getFirst("TransitGatewayId"),+ p.getFirst("VpcId"),+ getList(p, "SubnetIds"),+ parseVpcAttachmentOptions(p),+ parseTagsForResource(p, "transit-gateway-attachment"));+ XmlBuilder xml = new XmlBuilder()+ .start("CreateTransitGatewayVpcAttachmentResponse", AwsNamespaces.EC2)+ .elem("requestId", UUID.randomUUID().toString())+ .start("transitGatewayVpcAttachment").raw(vpcAttachmentXml(attachment, true, true))+ .end("transitGatewayVpcAttachment")+ .end("CreateTransitGatewayVpcAttachmentResponse");+ return xmlResponse(xml.build());+ }++ private Response handleDescribeTransitGatewayVpcAttachments(MultivaluedMap<String, String> p, String region) {+ List<TransitGatewayVpcAttachment> attachments = service.describeTransitGatewayVpcAttachments(+ region, getList(p, "TransitGatewayAttachmentIds"), getFilters(p));+ XmlBuilder xml = new XmlBuilder()+ .start("DescribeTransitGatewayVpcAttachmentsResponse", AwsNamespaces.EC2)+ .elem("requestId", UUID.randomUUID().toString())+ .start("transitGatewayVpcAttachments");+ for (TransitGatewayVpcAttachment attachment : attachments) {+ xml.start("item").raw(vpcAttachmentXml(attachment, true, true)).end("item");+ }+ xml.end("transitGatewayVpcAttachments").end("DescribeTransitGatewayVpcAttachmentsResponse");+ return xmlResponse(xml.build());+ }++ /**+ * The resource-agnostic view of the same attachments. It is a different shape rather than a+ * superset: the subnets and options are gone, the VPC appears as a typed resource, and the+ * route table association shows up here and nowhere else.+ */+ private Response handleDescribeTransitGatewayAttachments(MultivaluedMap<String, String> p, String region) {+ List<TransitGatewayVpcAttachment> attachments = service.describeTransitGatewayVpcAttachments(+ region, getList(p, "TransitGatewayAttachmentIds"), getFilters(p));+ XmlBuilder xml = new XmlBuilder()+ .start("DescribeTransitGatewayAttachmentsResponse", AwsNamespaces.EC2)+ .elem("requestId", UUID.randomUUID().toString())+ .start("transitGatewayAttachments");+ for (TransitGatewayVpcAttachment attachment : attachments) {+ XmlBuilder item = new XmlBuilder()+ .elem("transitGatewayAttachmentId", attachment.getTransitGatewayAttachmentId())+ .elem("transitGatewayId", attachment.getTransitGatewayId())+ .elem("transitGatewayOwnerId", attachment.getTransitGatewayOwnerId())+ .elem("resourceOwnerId", attachment.getVpcOwnerId())+ .elem("resourceType", "vpc")+ .elem("resourceId", attachment.getVpcId())+ .elem("state", attachment.getState());+ if (attachment.getAssociationRouteTableId() != null) {+ item.start("association")+ .elem("transitGatewayRouteTableId", attachment.getAssociationRouteTableId())+ .elem("state", attachment.getAssociationState())+ .end("association");+ }+ item.elem("creationTime", attachment.getCreationTime())+ .raw(tagSetXml(attachment.getTags()));+ xml.start("item").raw(item.build()).end("item");+ }+ xml.end("transitGatewayAttachments").end("DescribeTransitGatewayAttachmentsResponse");+ return xmlResponse(xml.build());+ }++ private Response handleModifyTransitGatewayVpcAttachment(MultivaluedMap<String, String> p, String region) {+ TransitGatewayVpcAttachment attachment = service.modifyTransitGatewayVpcAttachment(+ region,+ p.getFirst("TransitGatewayAttachmentId"),+ getList(p, "AddSubnetIds"),+ getList(p, "RemoveSubnetIds"),+ parseVpcAttachmentOptions(p));+ XmlBuilder xml = new XmlBuilder()+ .start("ModifyTransitGatewayVpcAttachmentResponse", AwsNamespaces.EC2)+ .elem("requestId", UUID.randomUUID().toString())+ // Verified live: modify echoes the attachment without its tagSet.+ .start("transitGatewayVpcAttachment").raw(vpcAttachmentXml(attachment, true, false))+ .end("transitGatewayVpcAttachment")+ .end("ModifyTransitGatewayVpcAttachmentResponse");+ return xmlResponse(xml.build());+ }++ private Response handleDeleteTransitGatewayVpcAttachment(MultivaluedMap<String, String> p, String region) {+ TransitGatewayVpcAttachment attachment = service.deleteTransitGatewayVpcAttachment(+ region, p.getFirst("TransitGatewayAttachmentId"));+ XmlBuilder xml = new XmlBuilder()+ .start("DeleteTransitGatewayVpcAttachmentResponse", AwsNamespaces.EC2)+ .elem("requestId", UUID.randomUUID().toString())+ // Verified live: delete drops the subnets and the tagSet from the echo.+ .start("transitGatewayVpcAttachment").raw(vpcAttachmentXml(attachment, false, false))+ .end("transitGatewayVpcAttachment")+ .end("DeleteTransitGatewayVpcAttachmentResponse");+ return xmlResponse(xml.build());+ }++ private TransitGatewayVpcAttachmentOptions parseVpcAttachmentOptions(MultivaluedMap<String, String> p) {+ TransitGatewayVpcAttachmentOptions options = new TransitGatewayVpcAttachmentOptions();+ options.setDnsSupport(p.getFirst("Options.DnsSupport"));+ options.setSecurityGroupReferencingSupport(p.getFirst("Options.SecurityGroupReferencingSupport"));+ options.setIpv6Support(p.getFirst("Options.Ipv6Support"));+ options.setApplianceModeSupport(p.getFirst("Options.ApplianceModeSupport"));+ return options;+ }++ private String vpcAttachmentXml(TransitGatewayVpcAttachment attachment, boolean includeSubnets,+ boolean includeTags) {+ XmlBuilder xml = new XmlBuilder()+ .elem("transitGatewayAttachmentId", attachment.getTransitGatewayAttachmentId())+ .elem("transitGatewayId", attachment.getTransitGatewayId())+ .elem("vpcId", attachment.getVpcId())+ .elem("vpcOwnerId", attachment.getVpcOwnerId())+ .elem("state", attachment.getState());+ if (includeSubnets) {+ xml.start("subnetIds");+ for (String subnetId : attachment.getSubnetIds()) {+ xml.elem("item", subnetId);+ }+ xml.end("subnetIds");+ }+ xml.elem("creationTime", attachment.getCreationTime())+ .start("options")+ .elem("dnsSupport", attachment.getOptions().getDnsSupport())+ .elem("securityGroupReferencingSupport", attachment.getOptions().getSecurityGroupReferencingSupport())+ .elem("ipv6Support", attachment.getOptions().getIpv6Support())+ .elem("applianceModeSupport", attachment.getOptions().getApplianceModeSupport())+ .end("options");+ if (includeTags) {+ xml.raw(tagSetXml(attachment.getTags()));+ }+ return xml.build();+ }+private String transitGatewayXml(TransitGateway gateway) {return transitGatewayXml(gateway, true);}diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.javaindex f359e18304..5825b34522 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java@@ -76,6 +76,8 @@ import io.github.hectorvent.floci.services.ec2.model.Tag;import io.github.hectorvent.floci.services.ec2.model.TransitGateway;import io.github.hectorvent.floci.services.ec2.model.TransitGatewayOptions;import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRouteTable;+import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachment;+import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachmentOptions;import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;import io.github.hectorvent.floci.services.ec2.model.Volume;import io.github.hectorvent.floci.services.ec2.model.VolumeAttachment;@@ -102,6 +104,8 @@ public class Ec2Service implements ContainerTeardown {// The ASN AWS assigns when CreateTransitGateway omits Options.AmazonSideAsn.private static final long DEFAULT_AMAZON_SIDE_ASN = 64512L;private static final Pattern TRANSIT_GATEWAY_ID_PATTERN = Pattern.compile("^tgw-[0-9a-f]{8}([0-9a-f]{9})?$");+ private static final Pattern TRANSIT_GATEWAY_ATTACHMENT_ID_PATTERN =+ Pattern.compile("^tgw-attach-[0-9a-f]{8}([0-9a-f]{9})?$");private final String accountId;private final EmulatorConfig config;@@ -134,6 +138,7 @@ public class Ec2Service implements ContainerTeardown {private final StorageBackend<String, ManagedPrefixList> managedPrefixLists;private final StorageBackend<String, TransitGateway> transitGateways;private final StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables;+ private final StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments;// resourceId → List<Tag>private final StorageBackend<String, List<Tag>> tags;private final Set<String> seededRegions = ConcurrentHashMap.newKeySet();@@ -167,7 +172,9 @@ public class Ec2Service implements ContainerTeardown {storageFactory.create("ec2", "ec2-tags.json", new TypeReference<Map<String, List<Tag>>>() {}),storageFactory.create("ec2", "ec2-transit-gateways.json", new TypeReference<Map<String, TransitGateway>>() {}),storageFactory.create("ec2", "ec2-transit-gateway-route-tables.json",- new TypeReference<Map<String, TransitGatewayRouteTable>>() {}));+ new TypeReference<Map<String, TransitGatewayRouteTable>>() {}),+ storageFactory.create("ec2", "ec2-transit-gateway-vpc-attachments.json",+ new TypeReference<Map<String, TransitGatewayVpcAttachment>>() {}));}// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).@@ -198,7 +205,7 @@ public class Ec2Service implements ContainerTeardown {vpcs, subnets, securityGroups, securityGroupRules, internetGateways, routeTables, keyPairs,addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,- new InMemoryStorage<>(), new InMemoryStorage<>());+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());}// Package-private for hermetic tests, transit-gateway-aware. The shorter overload above keeps its@@ -227,7 +234,8 @@ public class Ec2Service implements ContainerTeardown {StorageBackend<String, ManagedPrefixList> managedPrefixLists,StorageBackend<String, List<Tag>> tags,StorageBackend<String, TransitGateway> transitGateways,- StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables) {+ StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables,+ StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments) {this.accountId = config.defaultAccountId();this.config = config;this.containerManager = containerManager;@@ -256,6 +264,7 @@ public class Ec2Service implements ContainerTeardown {this.tags = tags;this.transitGateways = transitGateways;this.transitGatewayRouteTables = transitGatewayRouteTables;+ this.transitGatewayVpcAttachments = transitGatewayVpcAttachments;}@PostConstruct@@ -1211,8 +1220,21 @@ public class Ec2Service implements ContainerTeardown {* the returned object carries the settled state for the same reason creation does.*/public TransitGateway deleteTransitGateway(String region, String transitGatewayId) {+ // Outermost first: the attachment check below and a concurrent attachment create have to+ // agree on who goes first.+ synchronized (attachmentTopologyLock(region)) {synchronized (lockFor(key(region, transitGatewayId))) {TransitGateway gateway = getRequiredTransitGateway(region, transitGatewayId);+ // AWS refuses while anything is still attached, naming the attachments in the message.+ List<String> attached = transitGatewayVpcAttachments.scan(k -> true).stream()+ .filter(attachment -> region.equals(attachment.getRegion()))+ .filter(attachment -> transitGatewayId.equals(attachment.getTransitGatewayId()))+ .map(TransitGatewayVpcAttachment::getTransitGatewayAttachmentId)+ .toList();+ if (!attached.isEmpty()) {+ throw new AwsException("IncorrectState", transitGatewayId+ + " has non-deleted VPC Attachments: " + String.join(", ", attached) + ".", 400);+ }transitGatewayRouteTables.scan(k -> true).stream().filter(routeTable -> region.equals(routeTable.getRegion())).filter(routeTable -> transitGatewayId.equals(routeTable.getTransitGatewayId()))@@ -1224,6 +1246,7 @@ public class Ec2Service implements ContainerTeardown {gateway.setState("deleted");return gateway;}+ }}private TransitGateway getRequiredTransitGateway(String region, String transitGatewayId) {@@ -1244,6 +1267,222 @@ public class Ec2Service implements ContainerTeardown {}}+ // ─── Transit Gateway VPC Attachments ───────────────────────────────────────++ /**+ * Attaches a VPC to a transit gateway. The option defaults are the attachment's own and not+ * the gateway's: verified against a live account, {@code securityGroupReferencingSupport} is+ * enabled here where it is disabled on the gateway that owns the attachment.+ *+ * <p>An attachment is associated with the gateway's default route table only when the gateway+ * asks for that, so a gateway created with {@code DefaultRouteTableAssociation} disabled+ * produces an attachment carrying no association at all.+ */+ public TransitGatewayVpcAttachment createTransitGatewayVpcAttachment(+ String region, String transitGatewayId, String vpcId, List<String> subnetIds,+ TransitGatewayVpcAttachmentOptions requested, List<Tag> attachmentTags) {+ // Everything an attachment depends on is resolved and written under one lock: the gateway+ // it hangs off, the VPC and subnets it names, and the uniqueness rule. Resolving any of+ // them outside it lets a concurrent delete land in between, leaving an attachment that+ // names a gateway, VPC or subnet which no longer exists.+ synchronized (attachmentTopologyLock(region)) {+ TransitGateway gateway = getRequiredTransitGateway(region, transitGatewayId);+ getRequiredVpc(region, vpcId);+ // SubnetIds is required on the request, and modify refuses to leave an attachment+ // without any, so creation must not be a way to produce what modify forbids.+ if (subnetIds == null || subnetIds.isEmpty()) {+ throw new AwsException("MissingParameter",+ "The request must contain the parameter SubnetIds.", 400);+ }+ requireAttachableSubnets(region, vpcId, subnetIds, List.of());+ boolean alreadyAttached = transitGatewayVpcAttachments.scan(k -> true).stream()+ .filter(existing -> region.equals(existing.getRegion()))+ .filter(existing -> transitGatewayId.equals(existing.getTransitGatewayId()))+ .anyMatch(existing -> vpcId.equals(existing.getVpcId()));+ if (alreadyAttached) {+ throw new AwsException("DuplicateTransitGatewayAttachment",+ transitGatewayId + " has non-deleted Transit Gateway Attachments with same VPC ID.", 400);+ }+ return storeNewAttachment(region, gateway, vpcId, subnetIds, requested, attachmentTags);+ }+ }++ private TransitGatewayVpcAttachment storeNewAttachment(+ String region, TransitGateway gateway, String vpcId, List<String> subnetIds,+ TransitGatewayVpcAttachmentOptions requested, List<Tag> attachmentTags) {+ TransitGatewayVpcAttachment attachment = new TransitGatewayVpcAttachment();+ String attachmentId = "tgw-attach-" + randomHex(17);+ attachment.setTransitGatewayAttachmentId(attachmentId);+ attachment.setTransitGatewayId(gateway.getTransitGatewayId());+ attachment.setVpcId(vpcId);+ attachment.setVpcOwnerId(accountId);+ attachment.setTransitGatewayOwnerId(gateway.getOwnerId());+ // AWS reports pending and settles on available; nothing is slow locally, the same+ // compression createTransitGateway applies.+ attachment.setState("available");+ attachment.setSubnetIds(new ArrayList<>(subnetIds));+ attachment.setCreationTime(ISO_FMT.format(Instant.now()));+ attachment.setRegion(region);+ attachment.setOptions(resolveAttachmentOptions(requested));+ // Both halves together: an association state without a table would be a shape AWS never+ // serves, and the gateway's own validation keeps the pair in step.+ if ("enable".equals(gateway.getOptions().getDefaultRouteTableAssociation())+ && gateway.getOptions().getAssociationDefaultRouteTableId() != null) {+ attachment.setAssociationRouteTableId(gateway.getOptions().getAssociationDefaultRouteTableId());+ attachment.setAssociationState("associated");+ }+ if (attachmentTags != null && !attachmentTags.isEmpty()) {+ attachment.setTags(new ArrayList<>(attachmentTags));+ tags.put(attachmentId, new ArrayList<>(attachmentTags));+ }+ transitGatewayVpcAttachments.put(key(region, attachmentId), attachment);+ return attachment;+ }++ /**+ * One region-wide monitor for every operation that creates an attachment, removes one, or+ * removes something an attachment depends on. Held outermost wherever a gateway lock is also+ * taken, so the two never interleave in opposite orders. Per-resource striped locks cannot+ * serve here: the dependency spans a gateway, a VPC and its subnets, which stripe separately.+ */+ private Object attachmentTopologyLock(String region) {+ return lockFor(key(region, "transit-gateway-attachments"));+ }++ private TransitGatewayVpcAttachmentOptions resolveAttachmentOptions(+ TransitGatewayVpcAttachmentOptions requested) {+ TransitGatewayVpcAttachmentOptions options = new TransitGatewayVpcAttachmentOptions();+ options.setDnsSupport("enable");+ options.setSecurityGroupReferencingSupport("enable");+ options.setIpv6Support("disable");+ options.setApplianceModeSupport("disable");+ applyAttachmentOptionChanges(options, requested);+ return options;+ }++ /**+ * Every subnet has to exist in the VPC being attached, and no two may share an availability+ * zone. A subnet belonging to another VPC is reported missing rather than mismatched, which is+ * what the live API does.+ */+ private void requireAttachableSubnets(String region, String vpcId, List<String> subnetIds,+ List<String> alreadyAttached) {+ List<String> zones = new ArrayList<>();+ for (String subnetId : alreadyAttached) {+ subnets.get(key(region, subnetId)).ifPresent(subnet -> zones.add(subnet.getAvailabilityZone()));+ }+ for (String subnetId : subnetIds) {+ Subnet subnet = subnets.get(key(region, subnetId)).orElse(null);+ if (subnet == null || !vpcId.equals(subnet.getVpcId())) {+ throw new AwsException("InvalidSubnetID.NotFound",+ "Subnet " + subnetId + " was deleted or does not exist.", 400);+ }+ if (zones.contains(subnet.getAvailabilityZone())) {+ throw new AwsException("DuplicateSubnetsInSameZone", "Duplicate Subnets for same AZ", 400);+ }+ zones.add(subnet.getAvailabilityZone());+ }+ }++ public List<TransitGatewayVpcAttachment> describeTransitGatewayVpcAttachments(+ String region, List<String> attachmentIds, Map<String, List<String>> filters) {+ attachmentIds.forEach(Ec2Service::requireWellFormedAttachmentId);+ List<TransitGatewayVpcAttachment> all = transitGatewayVpcAttachments.scan(k -> true).stream()+ .filter(attachment -> region.equals(attachment.getRegion()))+ .collect(Collectors.toList());+ for (String attachmentId : attachmentIds) {+ if (all.stream().noneMatch(a -> a.getTransitGatewayAttachmentId().equals(attachmentId))) {+ throw new AwsException("InvalidTransitGatewayAttachmentID.NotFound",+ "Transit Gateway Attachment " + attachmentId + " was deleted or does not exist.", 400);+ }+ }+ return all.stream()+ .filter(a -> attachmentIds.isEmpty() || attachmentIds.contains(a.getTransitGatewayAttachmentId()))+ .filter(a -> matchesFilters(a, filters, region))+ .collect(Collectors.toList());+ }++ public TransitGatewayVpcAttachment modifyTransitGatewayVpcAttachment(+ String region, String attachmentId, List<String> addSubnetIds, List<String> removeSubnetIds,+ TransitGatewayVpcAttachmentOptions changes) {+ synchronized (attachmentTopologyLock(region)) {+ TransitGatewayVpcAttachment attachment = getRequiredVpcAttachment(region, attachmentId);+ List<String> subnetIds = new ArrayList<>(attachment.getSubnetIds());+ if (removeSubnetIds != null) {+ for (String subnetId : removeSubnetIds) {+ if (!subnetIds.remove(subnetId)) {+ throw new AwsException("InvalidSubnetID.NotFound",+ subnetId + " is not attached but supplied in RemoveSubnets", 400);+ }+ }+ }+ if (addSubnetIds != null && !addSubnetIds.isEmpty()) {+ requireAttachableSubnets(region, attachment.getVpcId(), addSubnetIds, subnetIds);+ subnetIds.addAll(addSubnetIds);+ }+ // Removals are applied first, so an attachment cannot be left with nothing to attach+ // through even when the same request adds subnets back.+ if (subnetIds.isEmpty()) {+ throw new AwsException("InsufficientSubnetsException", "Insufficient Subnets", 400);+ }+ attachment.setSubnetIds(subnetIds);+ applyAttachmentOptionChanges(attachment.getOptions(), changes);+ transitGatewayVpcAttachments.put(key(region, attachmentId), attachment);+ return attachment;+ }+ }++ private void applyAttachmentOptionChanges(TransitGatewayVpcAttachmentOptions options,+ TransitGatewayVpcAttachmentOptions changes) {+ if (changes == null) {+ return;+ }+ if (changes.getDnsSupport() != null) {+ options.setDnsSupport(changes.getDnsSupport());+ }+ if (changes.getSecurityGroupReferencingSupport() != null) {+ options.setSecurityGroupReferencingSupport(changes.getSecurityGroupReferencingSupport());+ }+ if (changes.getIpv6Support() != null) {+ options.setIpv6Support(changes.getIpv6Support());+ }+ if (changes.getApplianceModeSupport() != null) {+ options.setApplianceModeSupport(changes.getApplianceModeSupport());+ }+ }++ public TransitGatewayVpcAttachment deleteTransitGatewayVpcAttachment(String region, String attachmentId) {+ synchronized (attachmentTopologyLock(region)) {+ TransitGatewayVpcAttachment attachment = getRequiredVpcAttachment(region, attachmentId);+ transitGatewayVpcAttachments.delete(key(region, attachmentId));+ tags.delete(attachmentId);+ attachment.setState("deleted");+ return attachment;+ }+ }++ /**+ * Verified live: an id of the wrong shape is rejected before any lookup, and the message does+ * not echo it back, unlike the transit gateway's equivalent.+ */+ private static void requireWellFormedAttachmentId(String attachmentId) {+ if (!TRANSIT_GATEWAY_ATTACHMENT_ID_PATTERN.matcher(attachmentId).matches()) {+ throw new AwsException("InvalidTransitGatewayAttachmentID.Malformed",+ "Invalid Transit Gateway Attachment id.", 400);+ }+ }++ private TransitGatewayVpcAttachment getRequiredVpcAttachment(String region, String attachmentId) {+ if (attachmentId == null || attachmentId.isBlank()) {+ throw new AwsException("MissingParameter",+ "The request must contain the parameter TransitGatewayAttachmentId.", 400);+ }+ requireWellFormedAttachmentId(attachmentId);+ return transitGatewayVpcAttachments.get(key(region, attachmentId))+ .orElseThrow(() -> new AwsException("InvalidTransitGatewayAttachmentID.NotFound",+ "Transit Gateway Attachment " + attachmentId + " was deleted or does not exist.", 400));+ }+// ─── Instances ─────────────────────────────────────────────────────────────public Reservation runInstances(String region, String imageId, String instanceType,@@ -1788,8 +2027,12 @@ public class Ec2Service implements ContainerTeardown {public void deleteVpc(String region, String vpcId) {ensureDefaultResources(region);getRequiredVpc(region, vpcId);-- vpcs.delete(key(region, vpcId));+ synchronized (attachmentTopologyLock(region)) {+ requireNoTransitGatewayAttachment(region,+ attachment -> vpcId.equals(attachment.getVpcId()),+ "The vpc '" + vpcId + "' has dependencies and cannot be deleted.");+ vpcs.delete(key(region, vpcId));+ }}public void modifyVpcAttribute(String region, String vpcId, String attribute, String value) {@@ -2014,7 +2257,27 @@ public class Ec2Service implements ContainerTeardown {if (subnets.get(key(region, subnetId)).isEmpty()) {throw new AwsException("InvalidSubnetID.NotFound", "The subnet ID '" + subnetId + "' does not exist", 400);}- subnets.delete(key(region, subnetId));+ synchronized (attachmentTopologyLock(region)) {+ requireNoTransitGatewayAttachment(region,+ attachment -> attachment.getSubnetIds().contains(subnetId),+ "The subnet '" + subnetId + "' has dependencies and cannot be deleted.");+ subnets.delete(key(region, subnetId));+ }+ }++ /**+ * A VPC or subnet carrying a transit gateway attachment cannot be deleted out from under it.+ * Verified on a live account: both report {@code DependencyViolation} with the same wording,+ * rather than leaving the attachment pointing at something that no longer exists.+ */+ private void requireNoTransitGatewayAttachment(+ String region, java.util.function.Predicate<TransitGatewayVpcAttachment> dependsOnIt, String message) {+ boolean attached = transitGatewayVpcAttachments.scan(k -> true).stream()+ .filter(attachment -> region.equals(attachment.getRegion()))+ .anyMatch(dependsOnIt);+ if (attached) {+ throw new AwsException("DependencyViolation", message, 400);+ }}public void modifySubnetAttribute(String region, String subnetId, String attribute, String value) {@@ -3152,22 +3415,41 @@ public class Ec2Service implements ContainerTeardown {public void createTags(String region, List<String> resourceIds, List<Tag> tagList) {ensureDefaultResources(region);for (String resourceId : resourceIds) {- synchronized (lockFor(key(region, resourceId))) {- List<Tag> existing = new ArrayList<>(tags.get(resourceId).orElse(List.of()));- for (Tag tag : tagList) {- existing.removeIf(t -> t.getKey().equals(tag.getKey()));- existing.add(tag);+ withTopologyLockIfNeeded(region, resourceId, () -> {+ synchronized (lockFor(key(region, resourceId))) {+ List<Tag> existing = new ArrayList<>(tags.get(resourceId).orElse(List.of()));+ for (Tag tag : tagList) {+ existing.removeIf(t -> t.getKey().equals(tag.getKey()));+ existing.add(tag);+ }+ tags.put(resourceId, existing);+ // Update resource objects+ updateResourceTags(region, resourceId, existing);}- tags.put(resourceId, existing);- // Update resource objects- updateResourceTags(region, resourceId, existing);+ });+ }+ }++ /**+ * Runs a tag change with the topology lock already held when the resource is one a transit+ * gateway delete can remove. Order matters as much as the lock does: the deletes take the+ * topology lock and then a striped resource lock, so tagging has to take them the same way+ * round or the two deadlock.+ */+ private void withTopologyLockIfNeeded(String region, String resourceId, Runnable change) {+ if (resourceId != null && resourceId.startsWith("tgw-")) {+ synchronized (attachmentTopologyLock(region)) {+ change.run();}+ return;}+ change.run();}public void deleteTags(String region, List<String> resourceIds, List<Tag> tagList) {ensureDefaultResources(region);for (String resourceId : resourceIds) {+ withTopologyLockIfNeeded(region, resourceId, () -> {synchronized (lockFor(key(region, resourceId))) {List<Tag> stored = tags.get(resourceId).orElse(null);if (stored != null) {@@ -3180,6 +3462,7 @@ public class Ec2Service implements ContainerTeardown {updateResourceTags(region, resourceId, existing);}}+ });}}@@ -3217,16 +3500,26 @@ public class Ec2Service implements ContainerTeardown {managedPrefixLists.put(storeKey, prefixList);return;}- TransitGateway gateway = transitGateways.get(storeKey).orElse(null);- if (gateway != null) {- gateway.setTags(new ArrayList<>(tagList));- transitGateways.put(storeKey, gateway);- return;- }- TransitGatewayRouteTable routeTable = transitGatewayRouteTables.get(storeKey).orElse(null);- if (routeTable != null) {- routeTable.setTags(new ArrayList<>(tagList));- transitGatewayRouteTables.put(storeKey, routeTable);+ // Reached with the topology lock already held for tgw- resources, so the read-modify-write+ // below cannot put back something a concurrent delete has just removed.+ {+ TransitGateway gateway = transitGateways.get(storeKey).orElse(null);+ if (gateway != null) {+ gateway.setTags(new ArrayList<>(tagList));+ transitGateways.put(storeKey, gateway);+ return;+ }+ TransitGatewayRouteTable routeTable = transitGatewayRouteTables.get(storeKey).orElse(null);+ if (routeTable != null) {+ routeTable.setTags(new ArrayList<>(tagList));+ transitGatewayRouteTables.put(storeKey, routeTable);+ return;+ }+ TransitGatewayVpcAttachment attachment = transitGatewayVpcAttachments.get(storeKey).orElse(null);+ if (attachment != null) {+ attachment.setTags(new ArrayList<>(tagList));+ transitGatewayVpcAttachments.put(storeKey, attachment);+ }}}@@ -3305,7 +3598,10 @@ public class Ec2Service implements ContainerTeardown {if (resourceId.startsWith("pl-")) {return "prefix-list";}- // Checked before the gateway prefix, which it starts with.+ // Both checked before the gateway prefix, which they start with.+ if (resourceId.startsWith("tgw-attach-")) {+ return "transit-gateway-attachment";+ }if (resourceId.startsWith("tgw-rtb-")) {return "transit-gateway-route-table";}@@ -3821,6 +4117,18 @@ public class Ec2Service implements ContainerTeardown {default -> true;};}+ if (resource instanceof TransitGatewayVpcAttachment attachment) {+ return switch (filterName) {+ case "transit-gateway-attachment-id" -> matchesValue(values, attachment.getTransitGatewayAttachmentId());+ case "transit-gateway-id" -> matchesValue(values, attachment.getTransitGatewayId());+ case "vpc-id" -> matchesValue(values, attachment.getVpcId());+ case "vpc-owner-id" -> matchesValue(values, attachment.getVpcOwnerId());+ case "state" -> matchesValue(values, attachment.getState());+ case "resource-id" -> matchesValue(values, attachment.getVpcId());+ case "resource-type" -> matchesValue(values, "vpc");+ default -> true;+ };+ }if (resource instanceof TransitGateway gateway) {return switch (filterName) {case "transit-gateway-id" -> matchesValue(values, gateway.getTransitGatewayId());@@ -3969,6 +4277,7 @@ public class Ec2Service implements ContainerTeardown {if (resource instanceof SpotInstanceRequest sir) return sir.getTags();if (resource instanceof TransitGateway gateway) return gateway.getTags();if (resource instanceof TransitGatewayRouteTable routeTable) return routeTable.getTags();+ if (resource instanceof TransitGatewayVpcAttachment attachment) return attachment.getTags();return Collections.emptyList();}diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayVpcAttachment.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayVpcAttachment.javanew file mode 100644index 0000000000..380ced20eb--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayVpcAttachment.java@@ -0,0 +1,80 @@+package io.github.hectorvent.floci.services.ec2.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.ArrayList;+import java.util.List;++/**+ * A transit gateway's attachment to a VPC. {@code DescribeTransitGatewayVpcAttachments} serves+ * this shape directly; {@code DescribeTransitGatewayAttachments} serves the resource-agnostic view+ * of the same record, which is where the route table association appears.+ */+@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class TransitGatewayVpcAttachment {++ private String transitGatewayAttachmentId;+ private String transitGatewayId;+ private String vpcId;+ private String vpcOwnerId;+ /** The gateway's owner, which is a different field from the VPC's even when they agree. */+ private String transitGatewayOwnerId;+ private String state;+ private List<String> subnetIds = new ArrayList<>();+ private String creationTime;+ private String region;+ private TransitGatewayVpcAttachmentOptions options = new TransitGatewayVpcAttachmentOptions();+ /** Set when the gateway associates attachments with its default route table. */+ private String associationRouteTableId;+ private String associationState;+ private List<Tag> tags = new ArrayList<>();++ public TransitGatewayVpcAttachment() {}++ public String getTransitGatewayAttachmentId() { return transitGatewayAttachmentId; }+ public void setTransitGatewayAttachmentId(String transitGatewayAttachmentId) {+ this.transitGatewayAttachmentId = transitGatewayAttachmentId;+ }++ public String getTransitGatewayId() { return transitGatewayId; }+ public void setTransitGatewayId(String transitGatewayId) { this.transitGatewayId = transitGatewayId; }++ public String getVpcId() { return vpcId; }+ public void setVpcId(String vpcId) { this.vpcId = vpcId; }++ public String getVpcOwnerId() { return vpcOwnerId; }+ public void setVpcOwnerId(String vpcOwnerId) { this.vpcOwnerId = vpcOwnerId; }++ public String getTransitGatewayOwnerId() { return transitGatewayOwnerId; }+ public void setTransitGatewayOwnerId(String transitGatewayOwnerId) {+ this.transitGatewayOwnerId = transitGatewayOwnerId;+ }++ public String getState() { return state; }+ public void setState(String state) { this.state = state; }++ public List<String> getSubnetIds() { return subnetIds; }+ public void setSubnetIds(List<String> subnetIds) { this.subnetIds = subnetIds; }++ public String getCreationTime() { return creationTime; }+ public void setCreationTime(String creationTime) { this.creationTime = creationTime; }++ public String getRegion() { return region; }+ public void setRegion(String region) { this.region = region; }++ public TransitGatewayVpcAttachmentOptions getOptions() { return options; }+ public void setOptions(TransitGatewayVpcAttachmentOptions options) { this.options = options; }++ public String getAssociationRouteTableId() { return associationRouteTableId; }+ public void setAssociationRouteTableId(String associationRouteTableId) {+ this.associationRouteTableId = associationRouteTableId;+ }++ public String getAssociationState() { return associationState; }+ public void setAssociationState(String associationState) { this.associationState = associationState; }++ public List<Tag> getTags() { return tags; }+ public void setTags(List<Tag> tags) { this.tags = tags; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayVpcAttachmentOptions.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayVpcAttachmentOptions.javanew file mode 100644index 0000000000..c4193cfdee--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayVpcAttachmentOptions.java@@ -0,0 +1,32 @@+package io.github.hectorvent.floci.services.ec2.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class TransitGatewayVpcAttachmentOptions {++ private String dnsSupport;+ private String securityGroupReferencingSupport;+ private String ipv6Support;+ private String applianceModeSupport;++ public TransitGatewayVpcAttachmentOptions() {}++ public String getDnsSupport() { return dnsSupport; }+ public void setDnsSupport(String dnsSupport) { this.dnsSupport = dnsSupport; }++ public String getSecurityGroupReferencingSupport() { return securityGroupReferencingSupport; }+ public void setSecurityGroupReferencingSupport(String securityGroupReferencingSupport) {+ this.securityGroupReferencingSupport = securityGroupReferencingSupport;+ }++ public String getIpv6Support() { return ipv6Support; }+ public void setIpv6Support(String ipv6Support) { this.ipv6Support = ipv6Support; }++ public String getApplianceModeSupport() { return applianceModeSupport; }+ public void setApplianceModeSupport(String applianceModeSupport) {+ this.applianceModeSupport = applianceModeSupport;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.javaindex 1a3f27bdb2..2eeae3b1e2 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java@@ -26,6 +26,8 @@ import io.github.hectorvent.floci.services.ec2.model.Tag;import io.github.hectorvent.floci.services.ec2.model.TransitGateway;import io.github.hectorvent.floci.services.ec2.model.TransitGatewayOptions;import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRouteTable;+import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachment;+import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachmentOptions;import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;import io.github.hectorvent.floci.services.ec2.model.Volume;@@ -1666,6 +1668,432 @@ class Ec2ServiceTest {Map.of("resource-type", List.of("transit-gateway"))).size());}+ // =========================================================================+ // Transit gateway VPC attachments+ // =========================================================================++ /** A gateway, a VPC and one subnet per zone, which is what an attachment needs. */+ private static String[] attachmentFixture(Ec2Service service) {+ String transitGatewayId = service.createTransitGateway("us-east-1", "hub", null, List.of())+ .getTransitGatewayId();+ String vpcId = service.createVpc("us-east-1", "10.90.0.0/16", false).getVpcId();+ String subnetA = service.createSubnet("us-east-1", vpcId, "10.90.1.0/24", "us-east-1a").getSubnetId();+ String subnetB = service.createSubnet("us-east-1", vpcId, "10.90.2.0/24", "us-east-1b").getSubnetId();+ return new String[] {transitGatewayId, vpcId, subnetA, subnetB};+ }++ /**+ * The attachment's option defaults are its own, not the gateway's. Verified on a live account:+ * securityGroupReferencingSupport is enabled here and disabled on the gateway that owns it.+ */+ @Test+ void createVpcAttachmentAppliesTheAttachmentsOwnDefaults() {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);++ TransitGatewayVpcAttachment attachment = service.createTransitGatewayVpcAttachment(+ "us-east-1", fixture[0], fixture[1], List.of(fixture[2]), null, List.of());++ assertTrue(attachment.getTransitGatewayAttachmentId().startsWith("tgw-attach-"));+ assertEquals("available", attachment.getState());+ assertEquals("000000000000", attachment.getVpcOwnerId());+ assertEquals(List.of(fixture[2]), attachment.getSubnetIds());+ assertEquals("enable", attachment.getOptions().getDnsSupport());+ assertEquals("enable", attachment.getOptions().getSecurityGroupReferencingSupport());+ assertEquals("disable", attachment.getOptions().getIpv6Support());+ assertEquals("disable", attachment.getOptions().getApplianceModeSupport());+ }++ /** The association follows the gateway's own default-association setting. */+ @Test+ void anAttachmentAssociatesOnlyWhenTheGatewayAsksForIt() {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);+ TransitGateway gateway = service.describeTransitGateways("us-east-1", List.of(fixture[0]), Map.of())+ .getFirst();++ TransitGatewayVpcAttachment associated = service.createTransitGatewayVpcAttachment(+ "us-east-1", fixture[0], fixture[1], List.of(fixture[2]), null, List.of());+ assertEquals(gateway.getOptions().getAssociationDefaultRouteTableId(),+ associated.getAssociationRouteTableId());+ assertEquals("associated", associated.getAssociationState());++ TransitGatewayOptions defaultsOff = new TransitGatewayOptions();+ defaultsOff.setDefaultRouteTableAssociation("disable");+ defaultsOff.setDefaultRouteTablePropagation("disable");+ String bareGateway = service.createTransitGateway("us-east-1", "bare", defaultsOff, List.of())+ .getTransitGatewayId();+ String otherVpc = service.createVpc("us-east-1", "10.95.0.0/16", false).getVpcId();+ String otherSubnet = service.createSubnet("us-east-1", otherVpc, "10.95.1.0/24", "us-east-1a")+ .getSubnetId();++ TransitGatewayVpcAttachment unassociated = service.createTransitGatewayVpcAttachment(+ "us-east-1", bareGateway, otherVpc, List.of(otherSubnet), null, List.of());+ assertNull(unassociated.getAssociationRouteTableId());+ assertNull(unassociated.getAssociationState());+ }++ /**+ * One attachment per VPC is a uniqueness rule, so the duplicate check and the write have to be+ * one step. Reproduces the race: with the two unsynchronized, concurrent creates for the same+ * VPC both find nothing and both store.+ */+ @Test+ void concurrentAttachmentsForOneVpcLeaveExactlyOne() throws Exception {+ // Kept deliberately small: without the lock the race shows on the first trial, and this+ // suite has thread-timing-sensitive tests elsewhere that a heavier harness disturbs.+ for (int trial = 0; trial < 10; trial++) {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);+ int threads = 6;+ java.util.concurrent.CountDownLatch start = new java.util.concurrent.CountDownLatch(1);+ java.util.concurrent.ExecutorService pool =+ java.util.concurrent.Executors.newFixedThreadPool(threads);+ List<String> created = java.util.Collections.synchronizedList(new java.util.ArrayList<>());+ List<String> errors = java.util.Collections.synchronizedList(new java.util.ArrayList<>());++ for (int i = 0; i < threads; i++) {+ pool.submit(() -> {+ try {+ start.await();+ created.add(service.createTransitGatewayVpcAttachment("us-east-1", fixture[0],+ fixture[1], List.of(fixture[2]), null, List.of())+ .getTransitGatewayAttachmentId());+ } catch (AwsException expected) {+ errors.add(expected.getErrorCode());+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ }+ });+ }+ start.countDown();+ pool.shutdown();+ assertTrue(pool.awaitTermination(30, java.util.concurrent.TimeUnit.SECONDS));++ assertEquals(1, created.size(), "trial " + trial + ": exactly one create may win");+ assertEquals(threads - 1, errors.size(), "every loser is told the VPC is already attached");+ assertTrue(errors.stream().allMatch("DuplicateTransitGatewayAttachment"::equals), errors.toString());+ assertEquals(1, service.describeTransitGatewayVpcAttachments("us-east-1", List.of(), Map.of()).size(),+ "and only one attachment is stored");+ }+ }++ /**+ * Attaching races deleting the thing being attached to. Whoever wins, the store may never end+ * up holding an attachment that names a gateway, VPC or subnet which is gone: resolving those+ * outside the lock that guards the write is what allows exactly that.+ */+ @Test+ void attachingNeverRacesAheadOfDeletingWhatItAttachesTo() throws Exception {+ record Race(String name, boolean deleteGateway) {}+ for (Race race : List.of(new Race("gateway", true), new Race("vpc", false))) {+ for (int trial = 0; trial < 10; trial++) {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);+ java.util.concurrent.CountDownLatch start = new java.util.concurrent.CountDownLatch(1);+ java.util.concurrent.ExecutorService pool =+ java.util.concurrent.Executors.newFixedThreadPool(2);++ pool.submit(() -> {+ try {+ start.await();+ service.createTransitGatewayVpcAttachment("us-east-1", fixture[0], fixture[1],+ List.of(fixture[2]), null, List.of());+ } catch (AwsException | InterruptedException ignored) {+ // Losing the race is a legitimate outcome; the invariant is checked below.+ }+ });+ pool.submit(() -> {+ try {+ start.await();+ if (race.deleteGateway()) {+ service.deleteTransitGateway("us-east-1", fixture[0]);+ } else {+ service.deleteSubnet("us-east-1", fixture[2]);+ service.deleteVpc("us-east-1", fixture[1]);+ }+ } catch (AwsException | InterruptedException ignored) {+ // Same.+ }+ });+ start.countDown();+ pool.shutdown();+ assertTrue(pool.awaitTermination(30, java.util.concurrent.TimeUnit.SECONDS));++ List<TransitGatewayVpcAttachment> attachments =+ service.describeTransitGatewayVpcAttachments("us-east-1", List.of(), Map.of());+ for (TransitGatewayVpcAttachment attachment : attachments) {+ assertFalse(service.describeTransitGateways("us-east-1", List.of(), Map.of()).isEmpty(),+ race.name() + " trial " + trial + ": attachment outlived its gateway");+ assertTrue(service.describeVpcs("us-east-1", List.of(), Map.of()).stream()+ .anyMatch(vpc -> vpc.getVpcId().equals(attachment.getVpcId())),+ race.name() + " trial " + trial + ": attachment names a deleted VPC");+ for (String subnetId : attachment.getSubnetIds()) {+ assertTrue(service.describeSubnets("us-east-1", List.of(subnetId), Map.of()).stream()+ .anyMatch(subnet -> subnet.getSubnetId().equals(subnetId)),+ race.name() + " trial " + trial + ": attachment names a deleted subnet");+ }+ }+ }+ }+ }++ /**+ * Tagging is a read-modify-write, so a tag call racing a delete must not put the record back.+ * A resurrected attachment would keep blocking the VPC and subnets it names, and a resurrected+ * gateway would keep blocking its own deletion, with nothing left to delete either of them.+ */+ @Test+ void taggingCannotResurrectSomethingBeingDeleted() throws Exception {+ for (boolean attachment : List.of(true, false)) {+ for (int trial = 0; trial < 10; trial++) {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);+ String attachmentId = service.createTransitGatewayVpcAttachment("us-east-1", fixture[0],+ fixture[1], List.of(fixture[2]), null, List.of()).getTransitGatewayAttachmentId();+ String target = attachment ? attachmentId : fixture[0];+ if (!attachment) {+ service.deleteTransitGatewayVpcAttachment("us-east-1", attachmentId);+ }+ java.util.concurrent.CountDownLatch start = new java.util.concurrent.CountDownLatch(1);+ java.util.concurrent.ExecutorService pool =+ java.util.concurrent.Executors.newFixedThreadPool(2);++ pool.submit(() -> {+ try {+ start.await();+ service.createTags("us-east-1", List.of(target), List.of(new Tag("env", "prod")));+ } catch (AwsException | InterruptedException ignored) {+ // Losing the race is fine; the invariant is below.+ }+ });+ pool.submit(() -> {+ try {+ start.await();+ if (attachment) {+ service.deleteTransitGatewayVpcAttachment("us-east-1", target);+ } else {+ service.deleteTransitGateway("us-east-1", target);+ }+ } catch (AwsException | InterruptedException ignored) {+ // Same.+ }+ });+ start.countDown();+ pool.shutdown();+ assertTrue(pool.awaitTermination(30, java.util.concurrent.TimeUnit.SECONDS));++ String what = attachment ? "attachment" : "gateway";+ if (attachment) {+ assertTrue(service.describeTransitGatewayVpcAttachments("us-east-1", List.of(), Map.of())+ .isEmpty(), what + " trial " + trial + ": tagging put the deleted record back");+ } else {+ assertTrue(service.describeTransitGateways("us-east-1", List.of(), Map.of()).stream()+ .noneMatch(g -> g.getTransitGatewayId().equals(target)),+ what + " trial " + trial + ": tagging put the deleted record back");+ }+ }+ }+ }++ /**+ * Verified on a live account: an attached VPC or subnet cannot be deleted out from under the+ * attachment, and both report the same {@code DependencyViolation}. Without this the stored+ * attachment would go on naming resources that no longer exist, and a later modify would fail+ * on a subnet the caller never touched.+ */+ @Test+ void anAttachedVpcOrSubnetCannotBeDeleted() {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);+ String attachmentId = service.createTransitGatewayVpcAttachment("us-east-1", fixture[0],+ fixture[1], List.of(fixture[2]), null, List.of()).getTransitGatewayAttachmentId();++ assertEquals("DependencyViolation", assertThrows(AwsException.class,+ () -> service.deleteSubnet("us-east-1", fixture[2])).getErrorCode());+ assertEquals("DependencyViolation", assertThrows(AwsException.class,+ () -> service.deleteVpc("us-east-1", fixture[1])).getErrorCode());++ // A subnet of the same VPC that the attachment does not use is free to go.+ service.deleteSubnet("us-east-1", fixture[3]);++ service.deleteTransitGatewayVpcAttachment("us-east-1", attachmentId);+ service.deleteSubnet("us-east-1", fixture[2]);+ service.deleteVpc("us-east-1", fixture[1]);+ }++ /**+ * An attachment must be created with at least one subnet. Modify refuses to leave one without+ * any, so creation must not be a back door into the state modify forbids.+ */+ @Test+ void anAttachmentCannotBeCreatedWithoutSubnets() {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);++ assertEquals("MissingParameter", assertThrows(AwsException.class,+ () -> service.createTransitGatewayVpcAttachment("us-east-1", fixture[0], fixture[1],+ List.of(), null, List.of())).getErrorCode());+ }++ /**+ * Verified on a live account: disabling the gateway's default association clears the id on the+ * gateway but leaves an existing attachment associated. The association was made when the+ * attachment was created, and only later attachments are affected.+ */+ @Test+ void anExistingAssociationSurvivesTheGatewayDisablingItsDefault() {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);+ TransitGatewayVpcAttachment attachment = service.createTransitGatewayVpcAttachment(+ "us-east-1", fixture[0], fixture[1], List.of(fixture[2]), null, List.of());+ String routeTableId = attachment.getAssociationRouteTableId();++ TransitGatewayOptions disable = new TransitGatewayOptions();+ disable.setDefaultRouteTableAssociation("disable");+ TransitGateway gateway = service.modifyTransitGateway("us-east-1", fixture[0], null, disable,+ List.of(), List.of());++ assertNull(gateway.getOptions().getAssociationDefaultRouteTableId(), "the gateway drops its id");+ TransitGatewayVpcAttachment after = service.describeTransitGatewayVpcAttachments("us-east-1",+ List.of(attachment.getTransitGatewayAttachmentId()), Map.of()).getFirst();+ assertEquals(routeTableId, after.getAssociationRouteTableId(),+ "the attachment keeps the association it was created with");+ assertEquals("associated", after.getAssociationState());+ }++ /**+ * Verified live: an attachment id of the wrong shape is rejected before the lookup, under the+ * attachment's own malformed code, matching how a malformed gateway id behaves.+ */+ @Test+ void aMalformedAttachmentIdIsRejectedBeforeTheLookup() {+ Ec2Service service = prefixListService();++ for (String malformed : List.of("tgw-attach-nope", "vpc-0123456789abcdef0")) {+ assertEquals("InvalidTransitGatewayAttachmentID.Malformed", assertThrows(AwsException.class,+ () -> service.describeTransitGatewayVpcAttachments("us-east-1", List.of(malformed), Map.of()))+ .getErrorCode(), malformed);+ }+ assertEquals("InvalidTransitGatewayAttachmentID.NotFound", assertThrows(AwsException.class,+ () -> service.describeTransitGatewayVpcAttachments("us-east-1",+ List.of("tgw-attach-0123456789abcdef0"), Map.of())).getErrorCode(),+ "a well-formed id that does not exist is a different failure");+ }++ /** The gateway's owner is its own field, sourced from the gateway rather than from the VPC. */+ @Test+ void anAttachmentRecordsBothOwnersSeparately() {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);++ TransitGatewayVpcAttachment attachment = service.createTransitGatewayVpcAttachment(+ "us-east-1", fixture[0], fixture[1], List.of(fixture[2]), null, List.of());++ TransitGateway gateway = service.describeTransitGateways("us-east-1", List.of(fixture[0]), Map.of())+ .getFirst();+ assertEquals(gateway.getOwnerId(), attachment.getTransitGatewayOwnerId());+ assertEquals("000000000000", attachment.getVpcOwnerId());+ }++ @Test+ void aVpcCanOnlyBeAttachedToAGatewayOnce() {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);+ service.createTransitGatewayVpcAttachment("us-east-1", fixture[0], fixture[1],+ List.of(fixture[2]), null, List.of());++ AwsException error = assertThrows(AwsException.class, () -> service.createTransitGatewayVpcAttachment(+ "us-east-1", fixture[0], fixture[1], List.of(fixture[3]), null, List.of()));+ assertEquals("DuplicateTransitGatewayAttachment", error.getErrorCode());+ }++ /** Verified live: a subnet from another VPC is reported missing rather than mismatched. */+ @Test+ void subnetsMustBelongToTheAttachedVpcAndBeOnePerZone() {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);+ String otherVpc = service.createVpc("us-east-1", "10.96.0.0/16", false).getVpcId();+ String foreignSubnet = service.createSubnet("us-east-1", otherVpc, "10.96.1.0/24", "us-east-1a")+ .getSubnetId();++ assertEquals("InvalidSubnetID.NotFound", assertThrows(AwsException.class,+ () -> service.createTransitGatewayVpcAttachment("us-east-1", fixture[0], fixture[1],+ List.of(foreignSubnet), null, List.of())).getErrorCode());++ String sameZoneSubnet = service.createSubnet("us-east-1", fixture[1], "10.90.9.0/24", "us-east-1a")+ .getSubnetId();+ assertEquals("DuplicateSubnetsInSameZone", assertThrows(AwsException.class,+ () -> service.createTransitGatewayVpcAttachment("us-east-1", fixture[0], fixture[1],+ List.of(fixture[2], sameZoneSubnet), null, List.of())).getErrorCode());+ }++ @Test+ void modifyVpcAttachmentAddsAndRemovesSubnetsAndOptions() {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);+ String attachmentId = service.createTransitGatewayVpcAttachment("us-east-1", fixture[0],+ fixture[1], List.of(fixture[2]), null, List.of()).getTransitGatewayAttachmentId();+ TransitGatewayVpcAttachmentOptions changes = new TransitGatewayVpcAttachmentOptions();+ changes.setDnsSupport("disable");++ TransitGatewayVpcAttachment widened = service.modifyTransitGatewayVpcAttachment("us-east-1",+ attachmentId, List.of(fixture[3]), List.of(), changes);+ assertEquals(List.of(fixture[2], fixture[3]), widened.getSubnetIds());+ assertEquals("disable", widened.getOptions().getDnsSupport());+ assertEquals("enable", widened.getOptions().getSecurityGroupReferencingSupport(),+ "an untouched option keeps its value");++ TransitGatewayVpcAttachment narrowed = service.modifyTransitGatewayVpcAttachment("us-east-1",+ attachmentId, List.of(), List.of(fixture[2]), null);+ assertEquals(List.of(fixture[3]), narrowed.getSubnetIds());++ assertEquals("InvalidSubnetID.NotFound", assertThrows(AwsException.class,+ () -> service.modifyTransitGatewayVpcAttachment("us-east-1", attachmentId,+ List.of(), List.of(fixture[2]), null)).getErrorCode(),+ "removing a subnet that is not attached");++ assertEquals("InsufficientSubnetsException", assertThrows(AwsException.class,+ () -> service.modifyTransitGatewayVpcAttachment("us-east-1", attachmentId,+ List.of(), List.of(fixture[3]), null)).getErrorCode(),+ "an attachment cannot be left with no subnets");+ }++ /** Verified live: the gateway refuses to go while anything is still attached to it. */+ @Test+ void aGatewayWithAnAttachmentCannotBeDeleted() {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);+ String attachmentId = service.createTransitGatewayVpcAttachment("us-east-1", fixture[0],+ fixture[1], List.of(fixture[2]), null, List.of()).getTransitGatewayAttachmentId();++ AwsException error = assertThrows(AwsException.class,+ () -> service.deleteTransitGateway("us-east-1", fixture[0]));+ assertEquals("IncorrectState", error.getErrorCode());+ assertTrue(error.getMessage().contains(attachmentId), "the message names the attachment");++ service.deleteTransitGatewayVpcAttachment("us-east-1", attachmentId);+ assertEquals("deleted", service.deleteTransitGateway("us-east-1", fixture[0]).getState(),+ "the gateway goes once the attachment has");+ }++ @Test+ void tagsOnAnAttachmentAreTypedAsTransitGatewayAttachment() {+ Ec2Service service = prefixListService();+ String[] fixture = attachmentFixture(service);+ String attachmentId = service.createTransitGatewayVpcAttachment("us-east-1", fixture[0],+ fixture[1], List.of(fixture[2]), null, List.of(new Tag("Name", "hub-attach")))+ .getTransitGatewayAttachmentId();++ assertEquals("transit-gateway-attachment", service.describeTags("us-east-1",+ Map.of("resource-id", List.of(attachmentId))).getFirst().get("resourceType"));++ service.createTags("us-east-1", List.of(attachmentId), List.of(new Tag("env", "prod")));+ assertEquals(2, service.describeTransitGatewayVpcAttachments("us-east-1",+ List.of(attachmentId), Map.of()).getFirst().getTags().size(),+ "describe serves tags added after creation");+ }+private static EmulatorConfig mockConfig(boolean ec2Mock) {EmulatorConfig config = mock(EmulatorConfig.class);EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TransitGatewayVpcAttachmentIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TransitGatewayVpcAttachmentIntegrationTest.javanew file mode 100644index 0000000000..8d5820e1ed--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TransitGatewayVpcAttachmentIntegrationTest.java@@ -0,0 +1,208 @@+package io.github.hectorvent.floci.services.ec2;++import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++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;++/**+ * VPC attachments over the EC2 Query protocol.+ *+ * <p>The two describes are deliberately both covered: the VPC-specific one carries the subnets and+ * options, while the resource-agnostic one drops those, types the VPC as a resource, and is the+ * only place the route table association appears. The shapes were captured from a live account,+ * including modify omitting the tagSet and delete omitting the subnets as well.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class Ec2TransitGatewayVpcAttachmentIntegrationTest {++ private static final String AUTH_HEADER =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";++ private static String transitGatewayId;+ private static String vpcId;+ private static String subnetA;+ private static String subnetB;+ private static String attachmentId;++ @Test+ @Order(1)+ void createTheGatewayVpcAndSubnets() {+ transitGatewayId = given()+ .formParam("Action", "CreateTransitGateway")+ .formParam("Description", "attachment host")+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200)+ .extract().path("CreateTransitGatewayResponse.transitGateway.transitGatewayId");++ vpcId = given()+ .formParam("Action", "CreateVpc")+ .formParam("CidrBlock", "10.80.0.0/16")+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200)+ .extract().path("CreateVpcResponse.vpc.vpcId");++ subnetA = createSubnet("10.80.1.0/24", "us-east-1a");+ subnetB = createSubnet("10.80.2.0/24", "us-east-1b");+ }++ private String createSubnet(String cidr, String zone) {+ return given()+ .formParam("Action", "CreateSubnet")+ .formParam("VpcId", vpcId)+ .formParam("CidrBlock", cidr)+ .formParam("AvailabilityZone", zone)+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200)+ .extract().path("CreateSubnetResponse.subnet.subnetId");+ }++ @Test+ @Order(2)+ void createAttachmentReturnsItsOwnOptionDefaults() {+ attachmentId = given()+ .formParam("Action", "CreateTransitGatewayVpcAttachment")+ .formParam("TransitGatewayId", transitGatewayId)+ .formParam("VpcId", vpcId)+ .formParam("SubnetIds.1", subnetA)+ // The CLI sends the plural wire name for this action: its TagSpecifications member+ // carries no locationName, unlike every neighbouring create.+ .formParam("TagSpecifications.1.ResourceType", "transit-gateway-attachment")+ .formParam("TagSpecifications.1.Tag.1.Key", "Name")+ .formParam("TagSpecifications.1.Tag.1.Value", "hub-attach")+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200)+ .body("CreateTransitGatewayVpcAttachmentResponse.transitGatewayVpcAttachment.state",+ equalTo("available"))+ .body("CreateTransitGatewayVpcAttachmentResponse.transitGatewayVpcAttachment.vpcId", equalTo(vpcId))+ .body("CreateTransitGatewayVpcAttachmentResponse.transitGatewayVpcAttachment.subnetIds.item",+ equalTo(subnetA))+ // The attachment's default, not the gateway's, which is disabled.+ .body("CreateTransitGatewayVpcAttachmentResponse.transitGatewayVpcAttachment.options"+ + ".securityGroupReferencingSupport", equalTo("enable"))+ .body("CreateTransitGatewayVpcAttachmentResponse.transitGatewayVpcAttachment.options.ipv6Support",+ equalTo("disable"))+ .body("CreateTransitGatewayVpcAttachmentResponse.transitGatewayVpcAttachment.tagSet.item.value",+ equalTo("hub-attach"))+ .extract()+ .path("CreateTransitGatewayVpcAttachmentResponse.transitGatewayVpcAttachment"+ + ".transitGatewayAttachmentId");+ }++ @Test+ @Order(3)+ void theTwoDescribesServeDifferentShapesOfTheSameAttachment() {+ given()+ .formParam("Action", "DescribeTransitGatewayVpcAttachments")+ .formParam("TransitGatewayAttachmentIds.1", attachmentId)+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200)+ .body("DescribeTransitGatewayVpcAttachmentsResponse.transitGatewayVpcAttachments.item.vpcId",+ equalTo(vpcId))+ .body("DescribeTransitGatewayVpcAttachmentsResponse.transitGatewayVpcAttachments.item"+ + ".subnetIds.item", equalTo(subnetA));++ // The resource-agnostic form: no subnets or options, the VPC as a typed resource, and the+ // association with the gateway's default route table.+ String generic = given()+ .formParam("Action", "DescribeTransitGatewayAttachments")+ .formParam("TransitGatewayAttachmentIds.1", attachmentId)+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200)+ .body("DescribeTransitGatewayAttachmentsResponse.transitGatewayAttachments.item.resourceType",+ equalTo("vpc"))+ .body("DescribeTransitGatewayAttachmentsResponse.transitGatewayAttachments.item.resourceId",+ equalTo(vpcId))+ .body("DescribeTransitGatewayAttachmentsResponse.transitGatewayAttachments.item.association.state",+ equalTo("associated"))+ .body("DescribeTransitGatewayAttachmentsResponse.transitGatewayAttachments.item"+ + ".transitGatewayOwnerId", equalTo("000000000000"))+ .body("DescribeTransitGatewayAttachmentsResponse.transitGatewayAttachments.item.resourceOwnerId",+ equalTo("000000000000"))+ .extract().asString();++ assertThat(generic, containsString("tgw-rtb-"));+ assertThat(generic, not(containsString("subnetIds")));+ }++ @Test+ @Order(4)+ void modifyAddsASubnetAndOmitsTheTagSet() {+ String body = given()+ .formParam("Action", "ModifyTransitGatewayVpcAttachment")+ .formParam("TransitGatewayAttachmentId", attachmentId)+ .formParam("AddSubnetIds.1", subnetB)+ .formParam("Options.DnsSupport", "disable")+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200)+ .body("ModifyTransitGatewayVpcAttachmentResponse.transitGatewayVpcAttachment.options.dnsSupport",+ equalTo("disable"))+ .extract().asString();++ assertThat(body, containsString(subnetB));+ assertThat(body, not(containsString("tagSet")));+ }++ @Test+ @Order(5)+ void aSecondAttachmentForTheSameVpcIsRejected() {+ given()+ .formParam("Action", "CreateTransitGatewayVpcAttachment")+ .formParam("TransitGatewayId", transitGatewayId)+ .formParam("VpcId", vpcId)+ .formParam("SubnetIds.1", subnetA)+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("DuplicateTransitGatewayAttachment"));+ }++ @Test+ @Order(6)+ void theGatewayCannotBeDeletedWhileAttachedAndTheAttachmentDeletesCleanly() {+ given()+ .formParam("Action", "DeleteTransitGateway")+ .formParam("TransitGatewayId", transitGatewayId)+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("IncorrectState"));++ String body = given()+ .formParam("Action", "DeleteTransitGatewayVpcAttachment")+ .formParam("TransitGatewayAttachmentId", attachmentId)+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200)+ .body("DeleteTransitGatewayVpcAttachmentResponse.transitGatewayVpcAttachment.state",+ equalTo("deleted"))+ .extract().asString();++ // Delete drops both the subnets and the tags from the echo.+ assertThat(body, not(containsString("subnetIds")));+ assertThat(body, not(containsString("tagSet")));++ given()+ .formParam("Action", "DeleteTransitGateway")+ .formParam("TransitGatewayId", transitGatewayId)+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200)+ .body("DeleteTransitGatewayResponse.transitGateway.state", equalTo("deleted"));+ }+}