Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(ec2): support transit gateway peering attachments (#5122)

Allen Sanborne22bd2c59adc
diff --git a/compatibility-tests/sdk-test-awscli/test/ec2.bats b/compatibility-tests/sdk-test-awscli/test/ec2.bats
index e98591d4b4..afdb9655b8 100644
--- a/compatibility-tests/sdk-test-awscli/test/ec2.bats
+++ b/compatibility-tests/sdk-test-awscli/test/ec2.bats
@@ -451,6 +451,56 @@ create_attachment_fixture() {
TRANSIT_GATEWAY_ID=""
}
+# ─── transit gateway peering attachments ────────────────────────────────────
+
+@test "EC2: a transit gateway peering is accepted, holds its gateway, and is deleted" {
+ local out peer_tgw account id
+ out=$(aws_cmd ec2 create-transit-gateway --description "bats peering requester")
+ TRANSIT_GATEWAY_ID=$(json_get "$out" '.TransitGateway.TransitGatewayId')
+ out=$(aws_cmd ec2 create-transit-gateway --description "bats peering accepter")
+ peer_tgw=$(json_get "$out" '.TransitGateway.TransitGatewayId')
+ account=$(json_get "$out" '.TransitGateway.OwnerId')
+
+ run aws_cmd ec2 create-transit-gateway-peering-attachment \
+ --transit-gateway-id "$TRANSIT_GATEWAY_ID" \
+ --peer-transit-gateway-id "$peer_tgw" \
+ --peer-account-id "$account" \
+ --peer-region "$AWS_DEFAULT_REGION" \
+ --tag-specifications 'ResourceType=transit-gateway-attachment,Tags=[{Key=Name,Value=bats-peering}]'
+ assert_success
+ id=$(json_get "$output" '.TransitGatewayPeeringAttachment.TransitGatewayAttachmentId')
+ [ "$(json_get "$output" '.TransitGatewayPeeringAttachment.State')" = "pendingAcceptance" ]
+
+ # How the accepter module finds it: by its own gateway and the pending state.
+ run aws_cmd ec2 describe-transit-gateway-peering-attachments \
+ --filters "Name=transit-gateway-id,Values=$peer_tgw" "Name=state,Values=pendingAcceptance"
+ assert_success
+ [ "$(json_get "$output" '.TransitGatewayPeeringAttachments[0].TransitGatewayAttachmentId')" = "$id" ]
+ [ "$(json_get "$output" '.TransitGatewayPeeringAttachments[0].AccepterTgwInfo.TransitGatewayId')" = "$peer_tgw" ]
+ [ "$(json_get "$output" '.TransitGatewayPeeringAttachments[0].Tags[0].Value')" = "bats-peering" ]
+
+ run aws_cmd ec2 accept-transit-gateway-peering-attachment --transit-gateway-attachment-id "$id"
+ assert_success
+
+ run aws_cmd ec2 describe-transit-gateway-peering-attachments --transit-gateway-attachment-ids "$id"
+ assert_success
+ [ "$(json_get "$output" '.TransitGatewayPeeringAttachments[0].State')" = "available" ]
+
+ run aws_cmd ec2 delete-transit-gateway --transit-gateway-id "$peer_tgw"
+ assert_failure
+ assert_output --partial "IncorrectState"
+
+ run aws_cmd ec2 delete-transit-gateway-peering-attachment --transit-gateway-attachment-id "$id"
+ assert_success
+
+ run aws_cmd ec2 describe-transit-gateway-peering-attachments --transit-gateway-attachment-ids "$id"
+ assert_failure
+ assert_output --partial "InvalidTransitGatewayAttachmentID.NotFound"
+
+ run aws_cmd ec2 delete-transit-gateway --transit-gateway-id "$peer_tgw"
+ assert_success
+}
+
# ─── transit gateway route tables, associations, propagations and routes ────
@test "EC2: route table associations move between tables" {
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
index a72092b34f..ca236312e1 100644
--- a/docs/services/ec2.md
+++ b/docs/services/ec2.md
@@ -463,6 +463,27 @@ trimmed the way AWS trims them: modify omits the `tagSet`, and delete omits both
the subnets. `Ipv6Support` is accepted without checking that the subnets carry IPv6 CIDRs, which
real AWS rejects; Floci does not model subnet IPv6 allocation.
+### Transit Gateway Peering Attachments
+
+| Action | Description |
+|--------|-------------|
+| CreateTransitGatewayPeeringAttachment | Requests a peering between a local transit gateway and a peer one, pending acceptance. |
+| DescribeTransitGatewayPeeringAttachments | Lists or returns peering attachments, from either side's region. |
+| AcceptTransitGatewayPeeringAttachment | Accepts a pending peering attachment from the accepter's region. |
+| DeleteTransitGatewayPeeringAttachment | Deletes a peering attachment from either side. |
+
+The requester's gateway must exist; the peer gateway is recorded as given and not resolved, since
+it may belong to an account this emulator cannot see. One attachment id serves both sides, so a
+cross-region peering is visible from both regions, and the `transit-gateway-id` filter matches
+either side's gateway. Creation reports `pendingAcceptance` (AWS passes through
+`initiatingRequest` first), accepting moves it to `available`, and accepting anything but a pending
+attachment returns `IncorrectState`. Across accounts, only the peer account can see the attachment
+from its side and accept it, and accepting checks that the peer gateway exists in the accepter's
+account and region, returning `InvalidTransitGatewayID.NotFound` otherwise. Each account keeps its
+own tags on the attachment. A pending peering does not stop the peer gateway's owner deleting it;
+that rejects the peering instead. Peering attachments do not yet appear in
+`DescribeTransitGatewayAttachments` and cannot be associated with a route table.
+
### Transit Gateway Route Tables
| Action | Description |
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
index 80f184ed15..74e82b2085 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
@@ -205,6 +205,8 @@ public class AwsQueryController {
"CreateNetworkAclEntry", "ReplaceNetworkAclEntry", "DeleteNetworkAclEntry",
"ReplaceNetworkAclAssociation",
"CreateNatGateway", "DescribeNatGateways", "DeleteNatGateway",
+ "CreateTransitGatewayPeeringAttachment", "AcceptTransitGatewayPeeringAttachment",
+ "DeleteTransitGatewayPeeringAttachment", "DescribeTransitGatewayPeeringAttachments",
"CreateCapacityReservation", "DescribeCapacityReservations",
"ModifyCapacityReservation", "CancelCapacityReservation",
"AllocateAddress", "AssociateAddress", "DisassociateAddress", "ReleaseAddress", "DescribeAddresses",
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.java
index d5b26bf921..2b911c44f9 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
@@ -132,6 +132,16 @@ public class Ec2QueryHandler {
handleModifyTransitGatewayVpcAttachment(params, region);
case "DeleteTransitGatewayVpcAttachment" ->
handleDeleteTransitGatewayVpcAttachment(params, region);
+ case "CreateTransitGatewayPeeringAttachment" ->
+ handleCreateTransitGatewayPeeringAttachment(params, region);
+ case "DescribeTransitGatewayPeeringAttachments" ->
+ handleDescribeTransitGatewayPeeringAttachments(params, region);
+ case "AcceptTransitGatewayPeeringAttachment" -> peeringAttachmentResponse(
+ "AcceptTransitGatewayPeeringAttachmentResponse", service.acceptTransitGatewayPeeringAttachment(
+ region, params.getFirst("TransitGatewayAttachmentId")));
+ case "DeleteTransitGatewayPeeringAttachment" -> peeringAttachmentResponse(
+ "DeleteTransitGatewayPeeringAttachmentResponse", service.deleteTransitGatewayPeeringAttachment(
+ region, params.getFirst("TransitGatewayAttachmentId")));
// Transit Gateway route tables, associations, propagations and routes
case "CreateTransitGatewayRouteTable" -> handleCreateTransitGatewayRouteTable(params, region);
case "DescribeTransitGatewayRouteTables" ->
@@ -2507,6 +2517,63 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
+ private Response handleCreateTransitGatewayPeeringAttachment(MultivaluedMap<String, String> p, String region) {
+ return peeringAttachmentResponse("CreateTransitGatewayPeeringAttachmentResponse",
+ service.createTransitGatewayPeeringAttachment(region,
+ p.getFirst("TransitGatewayId"),
+ p.getFirst("PeerTransitGatewayId"),
+ p.getFirst("PeerAccountId"),
+ p.getFirst("PeerRegion"),
+ p.getFirst("Options.DynamicRouting"),
+ parseTagsForResource(p, "transit-gateway-attachment")));
+ }
+
+ private Response handleDescribeTransitGatewayPeeringAttachments(MultivaluedMap<String, String> p,
+ String region) {
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeTransitGatewayPeeringAttachmentsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("transitGatewayPeeringAttachments");
+ for (TransitGatewayPeeringAttachment attachment : service.describeTransitGatewayPeeringAttachments(
+ region, getList(p, "TransitGatewayAttachmentIds"), getFilters(p))) {
+ xml.start("item").raw(peeringAttachmentXml(attachment)).end("item");
+ }
+ xml.end("transitGatewayPeeringAttachments").end("DescribeTransitGatewayPeeringAttachmentsResponse");
+ return xmlResponse(xml.build());
+ }
+
+ /** Create, accept and delete all answer with the attachment under the same member name. */
+ private Response peeringAttachmentResponse(String responseName, TransitGatewayPeeringAttachment attachment) {
+ XmlBuilder xml = new XmlBuilder()
+ .start(responseName, AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("transitGatewayPeeringAttachment").raw(peeringAttachmentXml(attachment))
+ .end("transitGatewayPeeringAttachment")
+ .end(responseName);
+ return xmlResponse(xml.build());
+ }
+
+ private String peeringAttachmentXml(TransitGatewayPeeringAttachment attachment) {
+ XmlBuilder xml = new XmlBuilder()
+ .elem("transitGatewayAttachmentId", attachment.getTransitGatewayAttachmentId());
+ List<Map.Entry<String, TransitGatewayPeeringAttachment.TgwInfo>> sides = List.of(
+ Map.entry("requesterTgwInfo", attachment.getRequesterTgwInfo()),
+ Map.entry("accepterTgwInfo", attachment.getAccepterTgwInfo()));
+ for (Map.Entry<String, TransitGatewayPeeringAttachment.TgwInfo> side : sides) {
+ xml.start(side.getKey())
+ .elem("transitGatewayId", side.getValue().getTransitGatewayId())
+ .elem("ownerId", side.getValue().getOwnerId())
+ .elem("region", side.getValue().getRegion())
+ .end(side.getKey());
+ }
+ return xml.start("options").elem("dynamicRouting", attachment.getDynamicRouting()).end("options")
+ .start("status").elem("code", attachment.getState()).end("status")
+ .elem("state", attachment.getState())
+ .elem("creationTime", attachment.getCreationTime())
+ .raw(tagSetXml(attachment.getTags()))
+ .build();
+ }
+
private TransitGatewayVpcAttachmentOptions parseVpcAttachmentOptions(MultivaluedMap<String, String> p) {
TransitGatewayVpcAttachmentOptions options = new TransitGatewayVpcAttachmentOptions();
options.setDnsSupport(p.getFirst("Options.DnsSupport"));
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.java
index 26f7837f61..4ff3bab678 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
@@ -71,6 +71,7 @@ import io.github.hectorvent.floci.services.ec2.model.Subnet;
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.TransitGatewayPeeringAttachment;
import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRoute;
import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRouteTable;
import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRouteTablePropagation;
@@ -254,6 +255,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
private final StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments;
private final StorageBackend<String, TransitGatewayRouteTablePropagation> transitGatewayPropagations;
private final StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes;
+ // Keyed by id alone: one attachment serves both regions of a cross-region peering.
+ private final StorageBackend<String, TransitGatewayPeeringAttachment> transitGatewayPeeringAttachments;
// Keyed by id alone, not region::id — see VpcPeeringConnection's class Javadoc.
private final StorageBackend<String, VpcPeeringConnection> vpcPeeringConnections;
// Standalone (non-primary) ENIs created via CreateNetworkInterface, see #floci-kt9.
@@ -493,7 +496,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
storageFactory.create("ec2", "ec2-volume-modifications.json",
new TypeReference<Map<String, VolumeModification>>() {}),
requestContextInstance, iamService, volumeBlockDeviceManager,
- storageFactory.create("ec2", "ec2-hosts.json", new TypeReference<Map<String, Host>>() {}));
+ storageFactory.create("ec2", "ec2-hosts.json", new TypeReference<Map<String, Host>>() {}),
+ storageFactory.create("ec2", "ec2-transit-gateway-peering-attachments.json",
+ new TypeReference<Map<String, TransitGatewayPeeringAttachment>>() {}));
}
// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).
@@ -700,11 +705,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
transitGateways, transitGatewayRouteTables, transitGatewayVpcAttachments,
transitGatewayPropagations, transitGatewayRoutes, vpcPeeringConnections,
networkInterfaces, capacityReservations, volumeModifications,
- requestContextInstance, iamService, volumeBlockDeviceManager, new InMemoryStorage<>());
+ requestContextInstance, iamService, volumeBlockDeviceManager, new InMemoryStorage<>(),
+ new InMemoryStorage<>());
}
- // The terminal constructor. Dedicated Hosts ride on their own parameter so the shorter
- // overloads above keep their arity for existing fixtures.
+ // The terminal constructor. Dedicated Hosts and transit gateway peering attachments ride on
+ // their own parameters so the shorter overloads above keep their arity for existing fixtures.
Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
Ec2PortForwardManager portForwardManager,
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
@@ -740,8 +746,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,
IamService iamService,
Ec2VolumeBlockDeviceManager volumeBlockDeviceManager,
- StorageBackend<String, Host> hosts) {
+ StorageBackend<String, Host> hosts,
+ StorageBackend<String, TransitGatewayPeeringAttachment> transitGatewayPeeringAttachments) {
this.hosts = hosts;
+ this.transitGatewayPeeringAttachments = transitGatewayPeeringAttachments;
this.iamService = iamService;
this.volumeBlockDeviceManager = volumeBlockDeviceManager;
this.defaultAccountId = config.defaultAccountId();
@@ -2050,6 +2058,25 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
throw new AwsException("IncorrectState", transitGatewayId
+ " has non-deleted VPC Attachments: " + String.join(", ", attached) + ".", 400);
}
+ // An accepted peering holds the gateway at either end; a pending one only its requester's.
+ // The accepter never agreed to a pending peering, and anyone can name any gateway as the
+ // peer, so it must not pin that gateway: its owner deleting it declines the peering.
+ List<TransitGatewayPeeringAttachment> live = allPeeringAttachments().stream()
+ .filter(attachment -> !Set.of("deleted", "rejected").contains(attachment.getState()))
+ .toList();
+ List<String> peered = live.stream()
+ .filter(attachment -> isGateway(attachment.getRequesterTgwInfo(), region, transitGatewayId)
+ || !"pendingAcceptance".equals(attachment.getState())
+ && isGateway(attachment.getAccepterTgwInfo(), region, transitGatewayId))
+ .map(TransitGatewayPeeringAttachment::getTransitGatewayAttachmentId)
+ .toList();
+ if (!peered.isEmpty()) {
+ throw new AwsException("IncorrectState", transitGatewayId
+ + " has non-deleted Peering Attachments: " + String.join(", ", peered) + ".", 400);
+ }
+ live.stream()
+ .filter(attachment -> isGateway(attachment.getAccepterTgwInfo(), region, transitGatewayId))
+ .forEach(attachment -> rejectPendingPeering(attachment.getTransitGatewayAttachmentId()));
transitGatewayRouteTables.scan(k -> true).stream()
.filter(routeTable -> region.equals(routeTable.getRegion()))
.filter(routeTable -> transitGatewayId.equals(routeTable.getTransitGatewayId()))
@@ -2337,6 +2364,211 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
+ // ─── Transit Gateway Peering Attachments ───────────────────────────────────
+
+ /**
+ * Requests a peering between a local transit gateway and a peer one. The peer gateway is not
+ * resolved: it may live in another account this store cannot see, and AWS settles that
+ * asynchronously. AWS passes through {@code initiatingRequest}; nothing is slow locally, so
+ * the attachment is created already waiting for the peer.
+ */
+ public TransitGatewayPeeringAttachment createTransitGatewayPeeringAttachment(
+ String region, String transitGatewayId, String peerTransitGatewayId, String peerAccountId,
+ String peerRegion, String dynamicRouting, List<Tag> attachmentTags) {
+ for (String[] required : new String[][] {{"PeerTransitGatewayId", peerTransitGatewayId},
+ {"PeerAccountId", peerAccountId}, {"PeerRegion", peerRegion}}) {
+ if (!isSet(required[1])) {
+ throw new AwsException("MissingParameter",
+ "The request must contain the parameter " + required[0] + ".", 400);
+ }
+ }
+ // Under the lock DeleteTransitGateway checks peerings under, so neither lands in between.
+ synchronized (attachmentTopologyLock(region)) {
+ TransitGateway gateway = getRequiredTransitGateway(region, transitGatewayId);
+ TransitGatewayPeeringAttachment attachment = new TransitGatewayPeeringAttachment();
+ String attachmentId = "tgw-attach-" + randomHex(17);
+ attachment.setTransitGatewayAttachmentId(attachmentId);
+ attachment.setRequesterTgwInfo(new TransitGatewayPeeringAttachment.TgwInfo(
+ transitGatewayId, gateway.getOwnerId(), region));
+ attachment.setAccepterTgwInfo(new TransitGatewayPeeringAttachment.TgwInfo(
+ peerTransitGatewayId, peerAccountId, peerRegion));
+ attachment.setDynamicRouting(isSet(dynamicRouting) ? dynamicRouting : "disable");
+ attachment.setState("pendingAcceptance");
+ attachment.setCreationTime(ISO_FMT.format(Instant.now()));
+ transitGatewayPeeringAttachments.put(attachmentId, attachment);
+ if (attachmentTags != null && !attachmentTags.isEmpty()) {
+ tags.put(attachmentId, new ArrayList<>(attachmentTags));
+ }
+ return withStoredTags(attachment);
+ }
+ }
+
+ public List<TransitGatewayPeeringAttachment> describeTransitGatewayPeeringAttachments(
+ String region, List<String> attachmentIds, Map<String, List<String>> filters) {
+ attachmentIds.forEach(Ec2Service::requireWellFormedAttachmentId);
+ String account = callerAccountId();
+ List<TransitGatewayPeeringAttachment> visible = allPeeringAttachments().stream()
+ .filter(attachment -> isPartyTo(attachment, account, region))
+ .map(this::withStoredTags)
+ .toList();
+ for (String attachmentId : attachmentIds) {
+ if (visible.stream().noneMatch(a -> a.getTransitGatewayAttachmentId().equals(attachmentId))) {
+ throw peeringAttachmentNotFound(attachmentId);
+ }
+ }
+ return visible.stream()
+ .filter(a -> attachmentIds.isEmpty() || attachmentIds.contains(a.getTransitGatewayAttachmentId()))
+ .filter(a -> matchesFilters(a, filters, region))
+ .collect(Collectors.toList());
+ }
+
+ /**
+ * Only the accepter accepts (its account, in its region), and only while the attachment is
+ * still pending. A requester whose peer is another account cannot accept on the peer's behalf.
+ */
+ public TransitGatewayPeeringAttachment acceptTransitGatewayPeeringAttachment(String region, String attachmentId) {
+ // The accepter's DeleteTransitGateway declines pending peerings under this region's lock.
+ synchronized (attachmentTopologyLock(region)) {
+ synchronized (lockFor(attachmentId)) {
+ OwnedPeeringAttachment owned = getRequiredPeeringAttachment(region, attachmentId);
+ TransitGatewayPeeringAttachment attachment = owned.attachment();
+ if (!isGatewayOf(attachment.getAccepterTgwInfo(), callerAccountId(), region)) {
+ throw peeringAttachmentNotFound(attachmentId);
+ }
+ if (!"pendingAcceptance".equals(attachment.getState())) {
+ throw new AwsException("IncorrectState", "tgw-attach " + attachmentId
+ + " is in invalid state " + attachment.getState() + ".", 400);
+ }
+ // The peer gateway was recorded unresolved at create, so anyone could have named someone
+ // else's gateway with their own account as the peer. Accepting is where that is settled:
+ // the gateway has to be the caller's, the same lookup create makes for the requester's.
+ getRequiredTransitGateway(region, attachment.getAccepterTgwInfo().getTransitGatewayId());
+ attachment.setState("available");
+ savePeeringAttachment(owned);
+ return withStoredTags(attachment);
+ }
+ }
+ }
+
+ /** Re-read under the attachment's lock, so a concurrent delete or accept is not overwritten. */
+ private void rejectPendingPeering(String attachmentId) {
+ synchronized (lockFor(attachmentId)) {
+ findPeeringAttachment(attachmentId)
+ .filter(owned -> "pendingAcceptance".equals(owned.attachment().getState()))
+ .ifPresent(owned -> {
+ owned.attachment().setState("rejected");
+ savePeeringAttachment(owned);
+ });
+ }
+ }
+
+ private void savePeeringAttachment(OwnedPeeringAttachment owned) {
+ String attachmentId = owned.attachment().getTransitGatewayAttachmentId();
+ if (owned.storageAccountId() != null) {
+ peeringAttachmentsByAccount().putForAccount(owned.storageAccountId(), attachmentId, owned.attachment());
+ } else {
+ transitGatewayPeeringAttachments.put(attachmentId, owned.attachment());
+ }
+ }
+
+ /** Either side may delete. AWS reports {@code deleting} first; the settled state is returned. */
+ public TransitGatewayPeeringAttachment deleteTransitGatewayPeeringAttachment(String region, String attachmentId) {
+ synchronized (lockFor(attachmentId)) {
+ OwnedPeeringAttachment owned = getRequiredPeeringAttachment(region, attachmentId);
+ TransitGatewayPeeringAttachment attachment = withStoredTags(owned.attachment());
+ if (owned.storageAccountId() != null) {
+ peeringAttachmentsByAccount().deleteForAccount(owned.storageAccountId(), attachmentId);
+ } else {
+ transitGatewayPeeringAttachments.delete(attachmentId);
+ }
+ // Tags are per account, so each side keeps its own; both go with the attachment.
+ if (tags instanceof AccountAwareStorageBackend<?> tagsByAccount) {
+ tagsByAccount.deleteForAccount(attachment.getRequesterTgwInfo().getOwnerId(), attachmentId);
+ tagsByAccount.deleteForAccount(attachment.getAccepterTgwInfo().getOwnerId(), attachmentId);
+ } else {
+ tags.delete(attachmentId);
+ }
+ attachment.setState("deleted");
+ return attachment;
+ }
+ }
+
+ /** A peering attachment together with the account partition its storage entry lives under. */
+ private record OwnedPeeringAttachment(String storageAccountId, TransitGatewayPeeringAttachment attachment) {}
+
+ /**
+ * Stored under the requester's account, but the accepter may be another account, so lookups
+ * search every account's partition and then admit only the two parties, the same pattern
+ * {@link #allVpcPeeringConnections} uses.
+ */
+ private OwnedPeeringAttachment getRequiredPeeringAttachment(String region, String attachmentId) {
+ if (!isSet(attachmentId)) {
+ throw new AwsException("MissingParameter",
+ "The request must contain the parameter TransitGatewayAttachmentId.", 400);
+ }
+ requireWellFormedAttachmentId(attachmentId);
+ return findPeeringAttachment(attachmentId)
+ .filter(owned -> isPartyTo(owned.attachment(), callerAccountId(), region))
+ .orElseThrow(() -> peeringAttachmentNotFound(attachmentId));
+ }
+
+ private Optional<OwnedPeeringAttachment> findPeeringAttachment(String attachmentId) {
+ AccountAwareStorageBackend<TransitGatewayPeeringAttachment> byAccount = peeringAttachmentsByAccount();
+ return byAccount != null
+ ? byAccount.findAnyAccountEntry(attachmentId)
+ .map(entry -> new OwnedPeeringAttachment(entry.account(), entry.value()))
+ : transitGatewayPeeringAttachments.get(attachmentId)
+ .map(attachment -> new OwnedPeeringAttachment(null, attachment));
+ }
+
+ private List<TransitGatewayPeeringAttachment> allPeeringAttachments() {
+ AccountAwareStorageBackend<TransitGatewayPeeringAttachment> byAccount = peeringAttachmentsByAccount();
+ return byAccount != null ? byAccount.scanAllAccounts() : transitGatewayPeeringAttachments.scan(k -> true);
+ }
+
+ @SuppressWarnings("unchecked")
+ private AccountAwareStorageBackend<TransitGatewayPeeringAttachment> peeringAttachmentsByAccount() {
+ return transitGatewayPeeringAttachments instanceof AccountAwareStorageBackend<?> byAccount
+ ? (AccountAwareStorageBackend<TransitGatewayPeeringAttachment>) byAccount : null;
+ }
+
+ private static boolean isPartyTo(TransitGatewayPeeringAttachment attachment, String account, String region) {
+ return isGatewayOf(attachment.getRequesterTgwInfo(), account, region)
+ || isGatewayOf(attachment.getAccepterTgwInfo(), account, region);
+ }
+
+ /** Whether this end of a peering is the caller's: its account, seen from its region. */
+ private static boolean isGatewayOf(TransitGatewayPeeringAttachment.TgwInfo side, String account, String region) {
+ return account.equals(side.getOwnerId()) && region.equals(side.getRegion());
+ }
+
+ private static boolean isGateway(TransitGatewayPeeringAttachment.TgwInfo side, String region, String gatewayId) {
+ return region.equals(side.getRegion()) && gatewayId.equals(side.getTransitGatewayId());
+ }
+
+ /** The end the caller sees as local: the accepter's, when the caller is the accepter and not also the requester. */
+ private TransitGatewayPeeringAttachment.TgwInfo localSide(TransitGatewayPeeringAttachment attachment, String region) {
+ String account = callerAccountId();
+ return !isGatewayOf(attachment.getRequesterTgwInfo(), account, region)
+ && isGatewayOf(attachment.getAccepterTgwInfo(), account, region)
+ ? attachment.getAccepterTgwInfo() : attachment.getRequesterTgwInfo();
+ }
+
+ private TransitGatewayPeeringAttachment.TgwInfo remoteSide(TransitGatewayPeeringAttachment attachment, String region) {
+ return localSide(attachment, region) == attachment.getRequesterTgwInfo()
+ ? attachment.getAccepterTgwInfo() : attachment.getRequesterTgwInfo();
+ }
+
+ private TransitGatewayPeeringAttachment withStoredTags(TransitGatewayPeeringAttachment attachment) {
+ attachment.setTags(new ArrayList<>(tags.get(attachment.getTransitGatewayAttachmentId()).orElse(List.of())));
+ return attachment;
+ }
+
+ private static AwsException peeringAttachmentNotFound(String attachmentId) {
+ return new AwsException("InvalidTransitGatewayAttachmentID.NotFound",
+ "Transit Gateway Attachment " + attachmentId + " was deleted or does not exist.", 400);
+ }
+
// ─── Transit Gateway Route Tables, Associations, Propagations and Routes ───
/**
@@ -9017,6 +9249,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
default -> true;
};
}
+ if (resource instanceof TransitGatewayPeeringAttachment attachment) {
+ return switch (filterName) {
+ case "transit-gateway-attachment-id" -> matchesValue(values, attachment.getTransitGatewayAttachmentId());
+ // Either side's gateway: the accepter looks its attachment up by its own gateway.
+ case "transit-gateway-id" -> matchesValue(values, attachment.getRequesterTgwInfo().getTransitGatewayId())
+ || matchesValue(values, attachment.getAccepterTgwInfo().getTransitGatewayId());
+ // Local and remote are the viewer's: the accepter sees itself as local.
+ case "local-owner-id" -> matchesValue(values, localSide(attachment, region).getOwnerId());
+ case "remote-owner-id" -> matchesValue(values, remoteSide(attachment, region).getOwnerId());
+ case "state" -> matchesValue(values, attachment.getState());
+ default -> true;
+ };
+ }
if (resource instanceof TransitGatewayVpcAttachment attachment) {
return switch (filterName) {
case "transit-gateway-attachment-id" -> matchesValue(values, attachment.getTransitGatewayAttachmentId());
@@ -9295,6 +9540,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (resource instanceof TransitGateway gateway) return gateway.getTags();
if (resource instanceof TransitGatewayRouteTable routeTable) return routeTable.getTags();
if (resource instanceof TransitGatewayVpcAttachment attachment) return attachment.getTags();
+ if (resource instanceof TransitGatewayPeeringAttachment attachment) return attachment.getTags();
if (resource instanceof VpcPeeringConnection pcx) return pcx.getTags();
if (resource instanceof CapacityReservation cr) return cr.getTags();
if (resource instanceof Host host) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayPeeringAttachment.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayPeeringAttachment.java
new file mode 100644
index 0000000000..a935cb5bed
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayPeeringAttachment.java
@@ -0,0 +1,78 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A peering attachment between two transit gateways. One attachment id serves both sides, so a
+ * cross-region peering is visible from the requester's region and the accepter's alike.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class TransitGatewayPeeringAttachment {
+
+ private String transitGatewayAttachmentId;
+ private TgwInfo requesterTgwInfo = new TgwInfo();
+ private TgwInfo accepterTgwInfo = new TgwInfo();
+ private String dynamicRouting;
+ private String state;
+ private String creationTime;
+ /** Filled from the tag store on read; tags are not persisted on the record itself. */
+ @JsonIgnore
+ private List<Tag> tags = new ArrayList<>();
+
+ public TransitGatewayPeeringAttachment() {}
+
+ public String getTransitGatewayAttachmentId() { return transitGatewayAttachmentId; }
+ public void setTransitGatewayAttachmentId(String transitGatewayAttachmentId) {
+ this.transitGatewayAttachmentId = transitGatewayAttachmentId;
+ }
+
+ public TgwInfo getRequesterTgwInfo() { return requesterTgwInfo; }
+ public void setRequesterTgwInfo(TgwInfo requesterTgwInfo) { this.requesterTgwInfo = requesterTgwInfo; }
+
+ public TgwInfo getAccepterTgwInfo() { return accepterTgwInfo; }
+ public void setAccepterTgwInfo(TgwInfo accepterTgwInfo) { this.accepterTgwInfo = accepterTgwInfo; }
+
+ public String getDynamicRouting() { return dynamicRouting; }
+ public void setDynamicRouting(String dynamicRouting) { this.dynamicRouting = dynamicRouting; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+
+ public String getCreationTime() { return creationTime; }
+ public void setCreationTime(String creationTime) { this.creationTime = creationTime; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+
+ /** One side of the peering: the {@code PeeringTgwInfo} shape. */
+ @RegisterForReflection
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class TgwInfo {
+ private String transitGatewayId;
+ private String ownerId;
+ private String region;
+
+ public TgwInfo() {}
+
+ public TgwInfo(String transitGatewayId, String ownerId, String region) {
+ this.transitGatewayId = transitGatewayId;
+ this.ownerId = ownerId;
+ this.region = region;
+ }
+
+ public String getTransitGatewayId() { return transitGatewayId; }
+ public void setTransitGatewayId(String transitGatewayId) { this.transitGatewayId = transitGatewayId; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TransitGatewayPeeringAttachmentIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TransitGatewayPeeringAttachmentIntegrationTest.java
new file mode 100644
index 0000000000..fc251711c4
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TransitGatewayPeeringAttachmentIntegrationTest.java
@@ -0,0 +1,557 @@
+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.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.not;
+
+/**
+ * Transit gateway peering attachments over the EC2 Query protocol: the create, describe, accept,
+ * tag and delete calls the Terraform provider's {@code aws_ec2_transit_gateway_peering_attachment}
+ * and its {@code _accepter} make. Every state change is read back through a separate describe
+ * rather than trusted from the mutating call's own response.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class Ec2TransitGatewayPeeringAttachmentIntegrationTest {
+
+ private static final String EAST =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
+ private static final String WEST =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-west-2/ec2/aws4_request";
+ /** A second account, in the same region as {@link #EAST}. */
+ private static final String PEER_ACCOUNT =
+ "AWS4-HMAC-SHA256 Credential=000000000002/20260205/us-east-1/ec2/aws4_request";
+ private static final String ITEM =
+ "DescribeTransitGatewayPeeringAttachmentsResponse.transitGatewayPeeringAttachments.item";
+
+ private static String requesterTgw;
+ private static String accepterTgw;
+ private static String attachmentId;
+
+ @Test
+ @Order(1)
+ void createTheTwoGateways() {
+ requesterTgw = createTransitGateway(EAST);
+ accepterTgw = createTransitGateway(EAST);
+ }
+
+ private static String createTransitGateway(String auth) {
+ return given()
+ .formParam("Action", "CreateTransitGateway")
+ .header("Authorization", auth)
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().path("CreateTransitGatewayResponse.transitGateway.transitGatewayId");
+ }
+
+ @Test
+ @Order(2)
+ void createAwaitsAcceptance() {
+ attachmentId = given()
+ .formParam("Action", "CreateTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayId", requesterTgw)
+ .formParam("PeerTransitGatewayId", accepterTgw)
+ .formParam("PeerAccountId", "000000000000")
+ .formParam("PeerRegion", "us-east-1")
+ .formParam("TagSpecification.1.ResourceType", "transit-gateway-attachment")
+ .formParam("TagSpecification.1.Tag.1.Key", "side")
+ .formParam("TagSpecification.1.Tag.1.Value", "requester")
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body("CreateTransitGatewayPeeringAttachmentResponse.transitGatewayPeeringAttachment.state",
+ equalTo("pendingAcceptance"))
+ .extract().path("CreateTransitGatewayPeeringAttachmentResponse.transitGatewayPeeringAttachment"
+ + ".transitGatewayAttachmentId");
+
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("TransitGatewayAttachmentIds.1", attachmentId)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".state", equalTo("pendingAcceptance"))
+ .body(ITEM + ".requesterTgwInfo.transitGatewayId", equalTo(requesterTgw))
+ .body(ITEM + ".requesterTgwInfo.ownerId", equalTo("000000000000"))
+ .body(ITEM + ".requesterTgwInfo.region", equalTo("us-east-1"))
+ .body(ITEM + ".accepterTgwInfo.transitGatewayId", equalTo(accepterTgw))
+ .body(ITEM + ".accepterTgwInfo.ownerId", equalTo("000000000000"))
+ .body(ITEM + ".accepterTgwInfo.region", equalTo("us-east-1"))
+ .body(ITEM + ".options.dynamicRouting", equalTo("disable"))
+ .body(ITEM + ".tagSet.item.key", equalTo("side"))
+ .body(ITEM + ".tagSet.item.value", equalTo("requester"));
+ }
+
+ /** The accepter module finds the attachment this way, by the accepter's own gateway. */
+ @Test
+ @Order(3)
+ void theAccepterFindsItByItsGatewayAndState() {
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("Filter.1.Name", "transit-gateway-id")
+ .formParam("Filter.1.Value.1", accepterTgw)
+ .formParam("Filter.2.Name", "state")
+ .formParam("Filter.2.Value.1", "available")
+ .formParam("Filter.2.Value.2", "pendingAcceptance")
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".transitGatewayAttachmentId", equalTo(attachmentId));
+
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("Filter.1.Name", "state")
+ .formParam("Filter.1.Value.1", "available")
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".transitGatewayAttachmentId", not(hasItem(attachmentId)));
+ }
+
+ @Test
+ @Order(4)
+ void acceptMakesItAvailableAndTagsRoundTrip() {
+ given()
+ .formParam("Action", "AcceptTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", attachmentId)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .formParam("Action", "CreateTags")
+ .formParam("ResourceId.1", attachmentId)
+ .formParam("Tag.1.Key", "side")
+ .formParam("Tag.1.Value", "accepter")
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("TransitGatewayAttachmentIds.1", attachmentId)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".state", equalTo("available"))
+ .body(ITEM + ".tagSet.item.value", equalTo("accepter"));
+
+ // Only a pending attachment can be accepted.
+ given()
+ .formParam("Action", "AcceptTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", attachmentId)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("IncorrectState"));
+ }
+
+ @Test
+ @Order(5)
+ void deleteRemovesIt() {
+ given()
+ .formParam("Action", "DeleteTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", attachmentId)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body("DeleteTransitGatewayPeeringAttachmentResponse.transitGatewayPeeringAttachment.state",
+ equalTo("deleted"));
+
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("TransitGatewayAttachmentIds.1", attachmentId)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidTransitGatewayAttachmentID.NotFound"));
+ }
+
+ @Test
+ @Order(6)
+ void anUnknownRequesterGatewayIsRefused() {
+ given()
+ .formParam("Action", "CreateTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayId", "tgw-0123456789abcdef0")
+ .formParam("PeerTransitGatewayId", accepterTgw)
+ .formParam("PeerAccountId", "000000000000")
+ .formParam("PeerRegion", "us-east-1")
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidTransitGatewayID.NotFound"));
+ }
+
+ /**
+ * A cross-region peering is one attachment id seen from both regions, and only the accepter's
+ * region can accept it.
+ */
+ @Test
+ @Order(7)
+ void crossRegionIsVisibleFromBothSidesAndAcceptedOnlyByThePeer() {
+ String westTgw = createTransitGateway(WEST);
+ String id = given()
+ .formParam("Action", "CreateTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayId", requesterTgw)
+ .formParam("PeerTransitGatewayId", westTgw)
+ .formParam("PeerAccountId", "000000000000")
+ .formParam("PeerRegion", "us-west-2")
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().path("CreateTransitGatewayPeeringAttachmentResponse.transitGatewayPeeringAttachment"
+ + ".transitGatewayAttachmentId");
+
+ given()
+ .formParam("Action", "AcceptTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(400);
+
+ given()
+ .formParam("Action", "AcceptTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", WEST)
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("TransitGatewayAttachmentIds.1", id)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".state", equalTo("available"))
+ .body(ITEM + ".accepterTgwInfo.region", equalTo("us-west-2"));
+
+ given()
+ .formParam("Action", "DeleteTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", WEST)
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ /** Either end of an accepted peering holds its gateway, the same way a VPC attachment does. */
+ @Test
+ @Order(8)
+ void aPeeredGatewayCannotBeDeletedFromEitherEnd() {
+ String requester = createTransitGateway(EAST);
+ String accepter = createTransitGateway(EAST);
+ String id = createPeering(EAST, requester, accepter, "000000000000");
+ accept(EAST, id);
+
+ for (String gateway : new String[] {requester, accepter}) {
+ given()
+ .formParam("Action", "DeleteTransitGateway")
+ .formParam("TransitGatewayId", gateway)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("IncorrectState"));
+
+ given()
+ .formParam("Action", "DescribeTransitGateways")
+ .formParam("TransitGatewayIds.1", gateway)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body("DescribeTransitGatewaysResponse.transitGatewaySet.item.state", equalTo("available"));
+ }
+
+ given()
+ .formParam("Action", "DeleteTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .formParam("Action", "DeleteTransitGateway")
+ .formParam("TransitGatewayId", requester)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ /**
+ * Cross-account: the requester cannot accept on the peer's behalf, the peer account sees and
+ * accepts the attachment, and each side's owner filters are relative to itself.
+ */
+ @Test
+ @Order(9)
+ void crossAccountIsAcceptedOnlyByThePeerAccount() {
+ String peerTgw = createTransitGateway(PEER_ACCOUNT);
+ String id = createPeering(EAST, requesterTgw, peerTgw, "000000000002");
+
+ given()
+ .formParam("Action", "AcceptTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidTransitGatewayAttachmentID.NotFound"));
+
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("TransitGatewayAttachmentIds.1", id)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".state", equalTo("pendingAcceptance"));
+
+ // The peer sees itself as local and the requester as remote.
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("Filter.1.Name", "local-owner-id")
+ .formParam("Filter.1.Value.1", "000000000002")
+ .formParam("Filter.2.Name", "remote-owner-id")
+ .formParam("Filter.2.Value.1", "000000000000")
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".transitGatewayAttachmentId", equalTo(id));
+
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("Filter.1.Name", "local-owner-id")
+ .formParam("Filter.1.Value.1", "000000000000")
+ .formParam("Filter.2.Name", "remote-owner-id")
+ .formParam("Filter.2.Value.1", "000000000002")
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".transitGatewayAttachmentId", equalTo(id));
+
+ given()
+ .formParam("Action", "AcceptTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("TransitGatewayAttachmentIds.1", id)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".state", equalTo("available"));
+
+ // The peer's gateway is held by the requester's peering too.
+ given()
+ .formParam("Action", "DeleteTransitGateway")
+ .formParam("TransitGatewayId", peerTgw)
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("IncorrectState"));
+
+ given()
+ .formParam("Action", "DeleteTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("TransitGatewayAttachmentIds.1", id)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidTransitGatewayAttachmentID.NotFound"));
+ }
+
+ /**
+ * Anyone can name any gateway as their peer, so a pending peering must not stop the named
+ * gateway's owner deleting it. Deleting it declines the peering instead.
+ */
+ @Test
+ @Order(10)
+ void aPendingPeeringDoesNotPinTheAccepterGateway() {
+ String peerTgw = createTransitGateway(PEER_ACCOUNT);
+ String id = createPeering(EAST, requesterTgw, peerTgw, "000000000002");
+
+ given()
+ .formParam("Action", "DeleteTransitGateway")
+ .formParam("TransitGatewayId", peerTgw)
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("TransitGatewayAttachmentIds.1", id)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".state", equalTo("rejected"));
+
+ given()
+ .formParam("Action", "AcceptTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("IncorrectState"));
+
+ given()
+ .formParam("Action", "DeleteTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ /**
+ * Tags belong to the account that set them: each side of a cross-account peering sees its own,
+ * and deleting from either side removes both.
+ */
+ @Test
+ @Order(11)
+ void crossAccountTagsArePerSideAndGoWithTheAttachment() {
+ String peerTgw = createTransitGateway(PEER_ACCOUNT);
+ String id = given()
+ .formParam("Action", "CreateTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayId", requesterTgw)
+ .formParam("PeerTransitGatewayId", peerTgw)
+ .formParam("PeerAccountId", "000000000002")
+ .formParam("PeerRegion", "us-east-1")
+ .formParam("TagSpecification.1.ResourceType", "transit-gateway-attachment")
+ .formParam("TagSpecification.1.Tag.1.Key", "side")
+ .formParam("TagSpecification.1.Tag.1.Value", "requester")
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().path("CreateTransitGatewayPeeringAttachmentResponse.transitGatewayPeeringAttachment"
+ + ".transitGatewayAttachmentId");
+ accept(PEER_ACCOUNT, id);
+
+ given()
+ .formParam("Action", "CreateTags")
+ .formParam("ResourceId.1", id)
+ .formParam("Tag.1.Key", "side")
+ .formParam("Tag.1.Value", "accepter")
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(200);
+
+ for (String[] viewer : new String[][] {{EAST, "requester"}, {PEER_ACCOUNT, "accepter"}}) {
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("TransitGatewayAttachmentIds.1", id)
+ .header("Authorization", viewer[0])
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".tagSet.item.value", equalTo(viewer[1]));
+ }
+
+ given()
+ .formParam("Action", "DeleteTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(200);
+
+ for (String viewer : new String[] {EAST, PEER_ACCOUNT}) {
+ given()
+ .formParam("Action", "DescribeTags")
+ .formParam("Filter.1.Name", "resource-id")
+ .formParam("Filter.1.Value.1", id)
+ .header("Authorization", viewer)
+ .when().post("/")
+ .then().statusCode(200)
+ .body("DescribeTagsResponse.tagSet", equalTo(""));
+ }
+
+ given()
+ .formParam("Action", "DeleteTransitGateway")
+ .formParam("TransitGatewayId", peerTgw)
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ /**
+ * An account names someone else's gateway as the peer with itself as the peer account. It must
+ * not be able to accept that: an accepted peering pins the gateway, and its real owner could
+ * then never delete it.
+ */
+ @Test
+ @Order(12)
+ void anAccountCannotAcceptForAGatewayItDoesNotOwn() {
+ String victimTgw = createTransitGateway(EAST);
+ String attackerTgw = createTransitGateway(PEER_ACCOUNT);
+ String id = createPeering(PEER_ACCOUNT, attackerTgw, victimTgw, "000000000002");
+
+ given()
+ .formParam("Action", "AcceptTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidTransitGatewayID.NotFound"));
+
+ given()
+ .formParam("Action", "DescribeTransitGatewayPeeringAttachments")
+ .formParam("TransitGatewayAttachmentIds.1", id)
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(200)
+ .body(ITEM + ".state", equalTo("pendingAcceptance"));
+
+ given()
+ .formParam("Action", "DeleteTransitGateway")
+ .formParam("TransitGatewayId", victimTgw)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .formParam("Action", "DescribeTransitGateways")
+ .formParam("TransitGatewayIds.1", victimTgw)
+ .header("Authorization", EAST)
+ .when().post("/")
+ .then().statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidTransitGatewayID.NotFound"));
+
+ given()
+ .formParam("Action", "DeleteTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", id)
+ .header("Authorization", PEER_ACCOUNT)
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ private static void accept(String auth, String attachmentId) {
+ given()
+ .formParam("Action", "AcceptTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayAttachmentId", attachmentId)
+ .header("Authorization", auth)
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ private static String createPeering(String auth, String tgw, String peerTgw, String peerAccount) {
+ return given()
+ .formParam("Action", "CreateTransitGatewayPeeringAttachment")
+ .formParam("TransitGatewayId", tgw)
+ .formParam("PeerTransitGatewayId", peerTgw)
+ .formParam("PeerAccountId", peerAccount)
+ .formParam("PeerRegion", "us-east-1")
+ .header("Authorization", auth)
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().path("CreateTransitGatewayPeeringAttachmentResponse.transitGatewayPeeringAttachment"
+ + ".transitGatewayAttachmentId");
+ }
+}