feat(ec2): support transit gateways (#2329)

* feat(ec2): support transit gateways

CreateTransitGateway, DescribeTransitGateways, ModifyTransitGateway and
DeleteTransitGateway, as EC2 Query actions alongside the existing VPC and
route table ones. Metadata only: nothing routes packets, and the value is
in ids later resources can reference and describes that round-trip so
plans converge.

Option defaults come from a live AWS account rather than the reference:
amazonSideAsn 64512, dnsSupport, vpnEcmpSupport and both default route
table options enabled, autoAcceptSharedAttachments,
securityGroupReferencingSupport and multicastSupport disabled. The last
of those is the one worth stating, since disable is easy to assume the
other way round. transitGatewayCidrBlocks is omitted entirely when unset
rather than sent empty.

Creating a gateway with either default route table option enabled also
mints the route table AWS mints, and reports its id as both
associationDefaultRouteTableId and propagationDefaultRouteTableId. Both
name the same table, and it is already on the create response rather than
appearing later, so a caller reading either id sees what AWS shows. The
actions that operate on route tables directly are not implemented; nor
are attachments.

State is reported settled rather than transitional. AWS returns a new
gateway as pending and reaches available in about 50 seconds, and reports
deleting for about a minute before deleted; nothing here is slow, so the
settled state is what the caller sees, matching how
createManagedPrefixList already compresses create-in-progress.

Modify and delete echo the gateway without its tagSet while create and
describe include it, which is what the live API does.

Part one of #2308.

* fix(ec2): keep a transit gateway's default route table options coherent

ModifyTransitGateway changed the DefaultRouteTableAssociation and
DefaultRouteTablePropagation flags without touching their route table
ids, so a gateway created with both disabled could be modified into
reporting an option enabled while carrying no id for it.

AWS does not create a route table on that request; it rejects it unless
an existing table is named, and rejects an id supplied alongside a
disable. An unknown table comes back as InvalidRouteTableID.NotFound
rather than a transit-gateway-specific code. Checked on a live account:

  enable DefaultRouteTableAssociation conflicts with
  AssociationDefaultRouteTableId null

  disable DefaultRouteTableAssociation conflicts with
  AssociationDefaultRouteTableId tgw-rtb-0123456789abcdef0

  Transit Gateway Route Table tgw-rtb-0123456789abcdef0 was deleted or
  does not exist.

Validate instead: the flag and its id have to move together in both
directions, and a named table has to exist. The divergent state is now
unreachable and a rejected call leaves the gateway untouched.

* fix(ec2): carry a default route table change through to what it governs

Disabling DefaultRouteTableAssociation or DefaultRouteTablePropagation
changed the flag alone, leaving the id it governs on the gateway and the
matching marker on the route table. A describe then reported the option
disabled while still naming a table, and the table still claimed to be
the default for it.

Checked on a live account. Disabling association on a gateway created
with both defaults enabled drops AssociationDefaultRouteTableId from the
options entirely rather than blanking it, clears DefaultAssociationRouteTable
on the table, and leaves the table itself in place with its propagation
marker and the gateway's PropagationDefaultRouteTableId untouched:

  DefaultRouteTableAssociation  disable      (no AssociationDefaultRouteTableId)
  DefaultRouteTablePropagation  enable       PropagationDefaultRouteTableId tgw-rtb-…
  tgw-rtb-…  available  defAssoc False  defProp True

Apply the same: the id follows its flag, the table's marker follows with
it, and the table survives. Enabling with a named table marks that table
instead.

* fix(ec2): require a default route table to belong to the gateway naming it

The route table named on a ModifyTransitGateway request was only checked
for existence in the region, so a gateway could take another gateway's
table as its default. Worse than a bad reference: applying the change
then rewrote the foreign table's own default marker, leaving the gateway
that actually owns it describing a table that no longer claims to be its
default.

AWS rejects this, under the same code as a table that exists nowhere but
with the gateway named in the message. Checked on a live account, gateway
A naming gateway B's default table:

  Transit Gateway Route Table tgw-rtb-0381f… was deleted or does not
  exist in Transit Gateway tgw-0438f…

Both wordings are now reproduced: unqualified when the table exists
nowhere, gateway-qualified when it exists but belongs elsewhere.

The three rules governing these options - flag and id agreeing in both
directions, and the named table existing and belonging to the gateway -
now sit in one validation block rather than accumulating as separate
guards.

* fix(ec2): judge a default route table change against the stored gateway

Validation looked only at the request, so a route table id arriving
without its flag skipped the coherence check entirely: the id was stored
while the table's default marker was left alone, and a disabled option
could end up naming a table.

AWS judges the pair against the gateway as it stands. Probed the whole
combination surface on a live account rather than the one case reported:

  id alone, option enabled     accepted
  id alone, option disabled    InvalidParameterCombination, and the
                               message quotes the stored flag, not the request
  enable alone, table named    accepted, keeps that table
  enable alone, no table       InvalidParameterCombination
  disable with an id           InvalidParameterCombination
  disable with an unknown id   the combination is reported, not the lookup

So the flag defaults to the stored one when the request omits it, enabling
without an id keeps the table already named rather than dropping it, and an
id on its own marks its table. The lookup still runs after the combination
check, which is the order AWS reports them in.

Two other behaviours from the same pass, both already correct and now
covered: removals apply before additions, so a CIDR added and removed in
one call survives, and removing a CIDR that is not present is accepted.

* fix(ec2): serialize transit gateway CIDR blocks as the string list they are

transitGatewayCidrBlocks is a plain string list, so each item carries the
CIDR as its own text. The items wrapped it in a cidrBlock element
instead, which the AWS CLI parsed as an empty string: a caller that added
a block got it back as "" from create, describe and modify alike.

Caught by the CLI compatibility suite, not by the integration test, which
asserted the same wrong shape the handler produced and so agreed with it.
The bats case now reads the list back through describe as well as modify,
since one helper serializes all three responses.

* fix(ec2): apply tag changes to a transit gateway, not just to the tag store

CreateTags and DeleteTags on a tgw- id updated the tag store but left the
gateway object alone, because updateResourceTags had no branch for it.
DescribeTags saw the change and DescribeTransitGateways did not, so a
gateway kept serving whatever tags its TagSpecification carried at
creation.

That is the path a Terraform tag update takes: the provider sends
CreateTags, then re-reads with DescribeTransitGateways and compares. With
the two disagreeing, aws_ec2_transit_gateway would never converge.

Route tables get the same branch, so their tags behave once part three
can create them.

The AWS CLI cases now cover the tag round trip and CIDR blocks supplied
at creation, both of which were only asserted against shapes this branch
produced itself.
This commit is contained in:
Michal Schreiber authored and GitHub committed 2026-08-15 18:11:24 -04:00
1 parent 4e6e6df06d
commit 20470b7f4a
9 files changed
+1435 -1

No files matched your search

@@ -8,12 +8,16 @@ setup() {
SG_VPC_ID=""
SG_SOURCE_ID=""
SG_TARGET_ID=""
TRANSIT_GATEWAY_ID=""
}
teardown() {
if [ -n "$PREFIX_LIST_ID" ]; then
aws_cmd ec2 delete-managed-prefix-list --prefix-list-id "$PREFIX_LIST_ID" >/dev/null 2>&1 || true
fi
if [ -n "$TRANSIT_GATEWAY_ID" ]; then
aws_cmd ec2 delete-transit-gateway --transit-gateway-id "$TRANSIT_GATEWAY_ID" >/dev/null 2>&1 || true
fi
for sg in "$SG_TARGET_ID" "$SG_SOURCE_ID"; do
if [ -n "$sg" ]; then
aws_cmd ec2 delete-security-group --group-id "$sg" >/dev/null 2>&1 || true
@@ -235,3 +239,103 @@ create_sg_pair() {
cidr=$(json_get "$output" '.SecurityGroupRules[] | select(.FromPort==8443) | .CidrIpv4')
[ "$cidr" = "10.0.0.0/8" ]
}
# ─── transit gateways ───────────────────────────────────────────────────────
@test "EC2: create a transit gateway and read it back" {
run aws_cmd ec2 create-transit-gateway \
--description "bats hub" \
--tag-specifications 'ResourceType=transit-gateway,Tags=[{Key=Name,Value=bats-tgw}]'
assert_success
TRANSIT_GATEWAY_ID=$(json_get "$output" '.TransitGateway.TransitGatewayId')
[ "$(json_get "$output" '.TransitGateway.State')" = "available" ]
[ "$(json_get "$output" '.TransitGateway.Options.AmazonSideAsn')" = "64512" ]
[ "$(json_get "$output" '.TransitGateway.Options.SecurityGroupReferencingSupport')" = "disable" ]
# The default route table is minted with the gateway, so both ids are already set and equal.
assoc=$(json_get "$output" '.TransitGateway.Options.AssociationDefaultRouteTableId')
prop=$(json_get "$output" '.TransitGateway.Options.PropagationDefaultRouteTableId')
[ "$assoc" = "$prop" ]
case "$assoc" in tgw-rtb-*) ;; *) return 1 ;; esac
run aws_cmd ec2 describe-transit-gateways --transit-gateway-ids "$TRANSIT_GATEWAY_ID"
assert_success
[ "$(json_get "$output" '.TransitGateways[0].TransitGatewayId')" = "$TRANSIT_GATEWAY_ID" ]
[ "$(json_get "$output" '.TransitGateways[0].Tags[0].Value')" = "bats-tgw" ]
}
@test "EC2: create a transit gateway with CIDR blocks" {
run aws_cmd ec2 create-transit-gateway \
--options 'TransitGatewayCidrBlocks=[10.99.0.0/16]'
assert_success
TRANSIT_GATEWAY_ID=$(json_get "$output" '.TransitGateway.TransitGatewayId')
[ "$(json_get "$output" '.TransitGateway.Options.TransitGatewayCidrBlocks[0]')" = "10.99.0.0/16" ]
run aws_cmd ec2 describe-transit-gateways --transit-gateway-ids "$TRANSIT_GATEWAY_ID"
assert_success
[ "$(json_get "$output" '.TransitGateways[0].Options.TransitGatewayCidrBlocks[0]')" = "10.99.0.0/16" ]
}
# Tags are changed after creation with create-tags rather than a tag specification, and read back
# from describe-transit-gateways, which is how a Terraform tag update converges.
@test "EC2: transit gateway tags changed after creation are visible on describe" {
local out
out=$(aws_cmd ec2 create-transit-gateway --tag-specifications \
'ResourceType=transit-gateway,Tags=[{Key=Name,Value=bats-tgw-tags}]')
TRANSIT_GATEWAY_ID=$(json_get "$out" '.TransitGateway.TransitGatewayId')
aws_cmd ec2 create-tags --resources "$TRANSIT_GATEWAY_ID" --tags 'Key=env,Value=prod' >/dev/null
run aws_cmd ec2 describe-transit-gateways --transit-gateway-ids "$TRANSIT_GATEWAY_ID"
assert_success
count=$(json_get "$output" '.TransitGateways[0].Tags | length')
[ "$count" = "2" ]
env_value=$(json_get "$output" '.TransitGateways[0].Tags[] | select(.Key=="env") | .Value')
[ "$env_value" = "prod" ]
aws_cmd ec2 delete-tags --resources "$TRANSIT_GATEWAY_ID" --tags 'Key=env' >/dev/null
run aws_cmd ec2 describe-transit-gateways --transit-gateway-ids "$TRANSIT_GATEWAY_ID"
assert_success
count=$(json_get "$output" '.TransitGateways[0].Tags | length')
[ "$count" = "1" ]
}
@test "EC2: modify a transit gateway" {
local out
out=$(aws_cmd ec2 create-transit-gateway --description "before")
TRANSIT_GATEWAY_ID=$(json_get "$out" '.TransitGateway.TransitGatewayId')
run aws_cmd ec2 modify-transit-gateway \
--transit-gateway-id "$TRANSIT_GATEWAY_ID" \
--description "after" \
--options 'DnsSupport=disable,AddTransitGatewayCidrBlocks=[10.100.0.0/16]'
assert_success
[ "$(json_get "$output" '.TransitGateway.Description')" = "after" ]
[ "$(json_get "$output" '.TransitGateway.Options.DnsSupport')" = "disable" ]
[ "$(json_get "$output" '.TransitGateway.Options.TransitGatewayCidrBlocks[0]')" = "10.100.0.0/16" ]
# Describe serializes the same list, so read it back through the CLI's own parser too.
run aws_cmd ec2 describe-transit-gateways --transit-gateway-ids "$TRANSIT_GATEWAY_ID"
assert_success
[ "$(json_get "$output" '.TransitGateways[0].Options.TransitGatewayCidrBlocks[0]')" = "10.100.0.0/16" ]
}
@test "EC2: delete a transit gateway" {
local out tgw
out=$(aws_cmd ec2 create-transit-gateway --description "short lived")
tgw=$(json_get "$out" '.TransitGateway.TransitGatewayId')
run aws_cmd ec2 delete-transit-gateway --transit-gateway-id "$tgw"
assert_success
run aws_cmd ec2 describe-transit-gateways --transit-gateway-ids "$tgw"
assert_failure
assert_output --partial "InvalidTransitGatewayID.NotFound"
}
@test "EC2: describing an unknown transit gateway is rejected" {
run aws_cmd ec2 describe-transit-gateways --transit-gateway-ids tgw-0123456789abcdef0
assert_failure
assert_output --partial "InvalidTransitGatewayID.NotFound"
}
+30
View File
@@ -310,6 +310,36 @@ resulting rule carries `prefixListId` in place of `cidrIpv4`, and `DescribeSecur
the reference under the permission as `prefixListIds`. Authorizing against a list that does not
exist returns `InvalidPrefixListID.NotFound`, so a typo cannot leave a rule pointing at nothing.
### Transit Gateways
| Action | Description |
|--------|-------------|
| CreateTransitGateway | Creates a transit gateway, applying AWS's option defaults and minting its default route table. |
| DescribeTransitGateways | Lists or returns stored transit gateways. |
| ModifyTransitGateway | Updates a transit gateway's description, options and CIDR blocks. |
| DeleteTransitGateway | Deletes a transit gateway and the default route table created with it. |
Transit gateway metadata only: nothing routes packets, and the value is in ids that later
resources can reference and describes that round-trip so plans converge.
Options left out of `CreateTransitGateway` take the same defaults AWS applies — `amazonSideAsn`
64512, `dnsSupport`, `vpnEcmpSupport`, `defaultRouteTableAssociation` and
`defaultRouteTablePropagation` enabled, and `autoAcceptSharedAttachments`,
`securityGroupReferencingSupport` and `multicastSupport` disabled. `transitGatewayCidrBlocks` is
omitted from the response entirely when no blocks are set, rather than sent empty.
Creating a gateway with either default-route-table option enabled also creates the route table
AWS creates, and reports its id as `associationDefaultRouteTableId` and
`propagationDefaultRouteTableId`. Both name the same table. Disabling both leaves the ids absent.
The actions that operate on transit gateway route tables directly — creating them, associating
attachments, enabling propagation — are not implemented yet, and neither are attachments.
State is reported settled rather than transitional: AWS returns a new gateway as `pending` and
reaches `available` roughly a minute later, and reports `deleting` before `deleted`. Nothing here
is slow, so callers see `available` and `deleted` immediately. `ModifyTransitGateway` and
`DeleteTransitGateway` echo the gateway without its `tagSet`, matching AWS; `CreateTransitGateway`
and `DescribeTransitGateways` include it.
### NAT Gateways
| Action | Description |
@@ -84,6 +84,11 @@ public class Ec2QueryHandler {
case "GetManagedPrefixListEntries" -> handleGetManagedPrefixListEntries(params, region);
case "ModifyManagedPrefixList" -> handleModifyManagedPrefixList(params, region);
case "DeleteManagedPrefixList" -> handleDeleteManagedPrefixList(params, region);
// Transit Gateways
case "CreateTransitGateway" -> handleCreateTransitGateway(params, region);
case "DescribeTransitGateways" -> handleDescribeTransitGateways(params, region);
case "ModifyTransitGateway" -> handleModifyTransitGateway(params, region);
case "DeleteTransitGateway" -> handleDeleteTransitGateway(params, region);
case "CreateDefaultVpc" -> handleCreateDefaultVpc(params, region);
case "AssociateVpcCidrBlock" -> handleAssociateVpcCidrBlock(params, region);
case "DisassociateVpcCidrBlock" -> handleDisassociateVpcCidrBlock(params, region);
@@ -1181,6 +1186,119 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
private Response handleCreateTransitGateway(MultivaluedMap<String, String> p, String region) {
TransitGateway gateway = service.createTransitGateway(
region,
p.getFirst("Description"),
parseTransitGatewayOptions(p, "Options"),
parseTagsForResource(p, "transit-gateway"));
XmlBuilder xml = new XmlBuilder()
.start("CreateTransitGatewayResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("transitGateway").raw(transitGatewayXml(gateway)).end("transitGateway")
.end("CreateTransitGatewayResponse");
return xmlResponse(xml.build());
}
private Response handleDescribeTransitGateways(MultivaluedMap<String, String> p, String region) {
List<TransitGateway> gateways = service.describeTransitGateways(
region, getList(p, "TransitGatewayIds"), getFilters(p));
XmlBuilder xml = new XmlBuilder()
.start("DescribeTransitGatewaysResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("transitGatewaySet");
for (TransitGateway gateway : gateways) {
xml.start("item").raw(transitGatewayXml(gateway)).end("item");
}
xml.end("transitGatewaySet").end("DescribeTransitGatewaysResponse");
return xmlResponse(xml.build());
}
private Response handleModifyTransitGateway(MultivaluedMap<String, String> p, String region) {
TransitGateway gateway = service.modifyTransitGateway(
region,
p.getFirst("TransitGatewayId"),
p.getFirst("Description"),
parseTransitGatewayOptions(p, "Options"),
getList(p, "Options.AddTransitGatewayCidrBlocks"),
getList(p, "Options.RemoveTransitGatewayCidrBlocks"));
XmlBuilder xml = new XmlBuilder()
.start("ModifyTransitGatewayResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
// Verified against a live account: modify echoes the gateway without its tagSet,
// unlike create and describe.
.start("transitGateway").raw(transitGatewayXml(gateway, false)).end("transitGateway")
.end("ModifyTransitGatewayResponse");
return xmlResponse(xml.build());
}
private Response handleDeleteTransitGateway(MultivaluedMap<String, String> p, String region) {
TransitGateway gateway = service.deleteTransitGateway(region, p.getFirst("TransitGatewayId"));
XmlBuilder xml = new XmlBuilder()
.start("DeleteTransitGatewayResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("transitGateway").raw(transitGatewayXml(gateway, false)).end("transitGateway")
.end("DeleteTransitGatewayResponse");
return xmlResponse(xml.build());
}
private TransitGatewayOptions parseTransitGatewayOptions(MultivaluedMap<String, String> p, String prefix) {
TransitGatewayOptions options = new TransitGatewayOptions();
options.setAmazonSideAsn(longOrNull(p, prefix + ".AmazonSideAsn"));
options.setAutoAcceptSharedAttachments(p.getFirst(prefix + ".AutoAcceptSharedAttachments"));
options.setDefaultRouteTableAssociation(p.getFirst(prefix + ".DefaultRouteTableAssociation"));
options.setAssociationDefaultRouteTableId(p.getFirst(prefix + ".AssociationDefaultRouteTableId"));
options.setDefaultRouteTablePropagation(p.getFirst(prefix + ".DefaultRouteTablePropagation"));
options.setPropagationDefaultRouteTableId(p.getFirst(prefix + ".PropagationDefaultRouteTableId"));
options.setVpnEcmpSupport(p.getFirst(prefix + ".VpnEcmpSupport"));
options.setDnsSupport(p.getFirst(prefix + ".DnsSupport"));
options.setSecurityGroupReferencingSupport(p.getFirst(prefix + ".SecurityGroupReferencingSupport"));
options.setMulticastSupport(p.getFirst(prefix + ".MulticastSupport"));
options.setTransitGatewayCidrBlocks(getList(p, prefix + ".TransitGatewayCidrBlocks"));
return options;
}
private String transitGatewayXml(TransitGateway gateway) {
return transitGatewayXml(gateway, true);
}
private String transitGatewayXml(TransitGateway gateway, boolean includeTags) {
XmlBuilder xml = new XmlBuilder()
.elem("transitGatewayId", gateway.getTransitGatewayId())
.elem("transitGatewayArn", gateway.getTransitGatewayArn())
.elem("state", gateway.getState())
.elem("ownerId", gateway.getOwnerId())
.elem("description", gateway.getDescription())
.elem("creationTime", gateway.getCreationTime())
.start("options")
.elem("amazonSideAsn", String.valueOf(gateway.getOptions().getAmazonSideAsn()));
List<String> cidrBlocks = gateway.getOptions().getTransitGatewayCidrBlocks();
// AWS omits the member entirely rather than sending an empty set.
if (cidrBlocks != null && !cidrBlocks.isEmpty()) {
// A plain string list (ValueStringList), so each item carries the CIDR as its own text
// rather than wrapping it in an element.
xml.start("transitGatewayCidrBlocks");
for (String cidr : cidrBlocks) {
xml.elem("item", cidr);
}
xml.end("transitGatewayCidrBlocks");
}
xml.elem("autoAcceptSharedAttachments", gateway.getOptions().getAutoAcceptSharedAttachments())
.elem("defaultRouteTableAssociation", gateway.getOptions().getDefaultRouteTableAssociation())
.elem("associationDefaultRouteTableId", gateway.getOptions().getAssociationDefaultRouteTableId())
.elem("defaultRouteTablePropagation", gateway.getOptions().getDefaultRouteTablePropagation())
.elem("propagationDefaultRouteTableId", gateway.getOptions().getPropagationDefaultRouteTableId())
.elem("vpnEcmpSupport", gateway.getOptions().getVpnEcmpSupport())
.elem("dnsSupport", gateway.getOptions().getDnsSupport())
.elem("securityGroupReferencingSupport", gateway.getOptions().getSecurityGroupReferencingSupport())
.elem("multicastSupport", gateway.getOptions().getMulticastSupport())
.end("options");
if (includeTags) {
xml.raw(tagSetXml(gateway.getTags()));
}
return xml.build();
}
private String managedPrefixListXml(ManagedPrefixList list) {
XmlBuilder xml = new XmlBuilder()
.elem("prefixListId", list.getPrefixListId())
@@ -18,6 +18,7 @@ import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.jboss.logging.Logger;
@@ -28,6 +29,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.model.Address;
@@ -71,6 +73,9 @@ import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
import io.github.hectorvent.floci.services.ec2.model.Snapshot;
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.TransitGatewayRouteTable;
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;
@@ -91,6 +96,9 @@ public class Ec2Service implements ContainerTeardown {
.withZone(ZoneOffset.UTC);
private static final int DEFAULT_ROOT_VOLUME_SIZE_GIB = 8;
private static final String DEFAULT_ROOT_VOLUME_TYPE = "gp3";
// 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 final String accountId;
private final EmulatorConfig config;
@@ -121,6 +129,8 @@ public class Ec2Service implements ContainerTeardown {
private final StorageBackend<String, SpotInstanceRequest> spotInstanceRequests;
private final StorageBackend<String, NetworkAcl> networkAcls;
private final StorageBackend<String, ManagedPrefixList> managedPrefixLists;
private final StorageBackend<String, TransitGateway> transitGateways;
private final StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables;
// resourceId → List<Tag>
private final StorageBackend<String, List<Tag>> tags;
private final Set<String> seededRegions = ConcurrentHashMap.newKeySet();
@@ -151,7 +161,10 @@ public class Ec2Service implements ContainerTeardown {
storageFactory.create("ec2", "ec2-spot-instance-requests.json", new TypeReference<Map<String, SpotInstanceRequest>>() {}),
storageFactory.create("ec2", "ec2-network-acls.json", new TypeReference<Map<String, NetworkAcl>>() {}),
storageFactory.create("ec2", "ec2-managed-prefix-lists.json", new TypeReference<Map<String, ManagedPrefixList>>() {}),
storageFactory.create("ec2", "ec2-tags.json", new TypeReference<Map<String, List<Tag>>>() {}));
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>>() {}));
}
// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).
@@ -178,6 +191,40 @@ public class Ec2Service implements ContainerTeardown {
StorageBackend<String, NetworkAcl> networkAcls,
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
StorageBackend<String, List<Tag>> tags) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
vpcs, subnets, securityGroups, securityGroupRules, internetGateways, routeTables, keyPairs,
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
new InMemoryStorage<>(), new InMemoryStorage<>());
}
// Package-private for hermetic tests, transit-gateway-aware. The shorter overload above keeps its
// arity so existing fixtures still resolve it (#2103 and #2106 both broke CI by moving it).
Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
Ec2PortForwardManager portForwardManager,
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog,
StorageBackend<String, Vpc> vpcs,
StorageBackend<String, Subnet> subnets,
StorageBackend<String, SecurityGroup> securityGroups,
StorageBackend<String, SecurityGroupRule> securityGroupRules,
StorageBackend<String, InternetGateway> internetGateways,
StorageBackend<String, RouteTable> routeTables,
StorageBackend<String, KeyPair> keyPairs,
StorageBackend<String, Address> addresses,
StorageBackend<String, Instance> instances,
StorageBackend<String, Volume> volumes,
StorageBackend<String, Image> registeredImages,
StorageBackend<String, Snapshot> snapshots,
StorageBackend<String, LaunchTemplate> launchTemplates,
StorageBackend<String, VpcEndpoint> vpcEndpoints,
StorageBackend<String, NatGateway> natGateways,
StorageBackend<String, SpotInstanceRequest> spotInstanceRequests,
StorageBackend<String, NetworkAcl> networkAcls,
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
StorageBackend<String, List<Tag>> tags,
StorageBackend<String, TransitGateway> transitGateways,
StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables) {
this.accountId = config.defaultAccountId();
this.config = config;
this.containerManager = containerManager;
@@ -204,6 +251,8 @@ public class Ec2Service implements ContainerTeardown {
this.networkAcls = networkAcls;
this.managedPrefixLists = managedPrefixLists;
this.tags = tags;
this.transitGateways = transitGateways;
this.transitGatewayRouteTables = transitGatewayRouteTables;
}
@PostConstruct
@@ -837,6 +886,361 @@ public class Ec2Service implements ContainerTeardown {
return sb.toString();
}
// ─── Transit Gateways ──────────────────────────────────────────────────────
/**
* Creates a transit gateway. Option defaults, and the fact that the default route table is
* minted during creation rather than afterwards, were taken from a live AWS account rather
* than the documentation.
*
* <p>AWS returns the gateway as {@code pending} and reaches {@code available} about 50
* seconds later. Nothing here is slow, so the settled state is what the caller sees, the
* same compression {@code createManagedPrefixList} applies.
*/
public TransitGateway createTransitGateway(String region, String description,
TransitGatewayOptions requested, List<Tag> gatewayTags) {
String transitGatewayId = "tgw-" + randomHex(17);
TransitGateway gateway = new TransitGateway();
gateway.setTransitGatewayId(transitGatewayId);
gateway.setTransitGatewayArn(AwsArnUtils.Arn
.of("ec2", region, accountId, "transit-gateway/" + transitGatewayId).toString());
gateway.setState("available");
gateway.setOwnerId(accountId);
gateway.setDescription(description);
gateway.setCreationTime(ISO_FMT.format(Instant.now()));
gateway.setRegion(region);
gateway.setOptions(resolveTransitGatewayOptions(requested));
TransitGatewayOptions options = gateway.getOptions();
if ("enable".equals(options.getDefaultRouteTableAssociation())
|| "enable".equals(options.getDefaultRouteTablePropagation())) {
TransitGatewayRouteTable defaultRouteTable = createDefaultTransitGatewayRouteTable(region, gateway);
if ("enable".equals(options.getDefaultRouteTableAssociation())) {
options.setAssociationDefaultRouteTableId(defaultRouteTable.getTransitGatewayRouteTableId());
}
if ("enable".equals(options.getDefaultRouteTablePropagation())) {
options.setPropagationDefaultRouteTableId(defaultRouteTable.getTransitGatewayRouteTableId());
}
}
if (gatewayTags != null && !gatewayTags.isEmpty()) {
gateway.setTags(new ArrayList<>(gatewayTags));
tags.put(transitGatewayId, new ArrayList<>(gatewayTags));
}
transitGateways.put(key(region, transitGatewayId), gateway);
return gateway;
}
private TransitGatewayOptions resolveTransitGatewayOptions(TransitGatewayOptions requested) {
TransitGatewayOptions options = new TransitGatewayOptions();
options.setAmazonSideAsn(DEFAULT_AMAZON_SIDE_ASN);
options.setAutoAcceptSharedAttachments("disable");
options.setDefaultRouteTableAssociation("enable");
options.setDefaultRouteTablePropagation("enable");
options.setVpnEcmpSupport("enable");
options.setDnsSupport("enable");
options.setSecurityGroupReferencingSupport("disable");
options.setMulticastSupport("disable");
if (requested == null) {
return options;
}
if (requested.getAmazonSideAsn() != null) {
options.setAmazonSideAsn(requested.getAmazonSideAsn());
}
if (requested.getAutoAcceptSharedAttachments() != null) {
options.setAutoAcceptSharedAttachments(requested.getAutoAcceptSharedAttachments());
}
if (requested.getDefaultRouteTableAssociation() != null) {
options.setDefaultRouteTableAssociation(requested.getDefaultRouteTableAssociation());
}
if (requested.getDefaultRouteTablePropagation() != null) {
options.setDefaultRouteTablePropagation(requested.getDefaultRouteTablePropagation());
}
if (requested.getVpnEcmpSupport() != null) {
options.setVpnEcmpSupport(requested.getVpnEcmpSupport());
}
if (requested.getDnsSupport() != null) {
options.setDnsSupport(requested.getDnsSupport());
}
if (requested.getSecurityGroupReferencingSupport() != null) {
options.setSecurityGroupReferencingSupport(requested.getSecurityGroupReferencingSupport());
}
if (requested.getMulticastSupport() != null) {
options.setMulticastSupport(requested.getMulticastSupport());
}
if (requested.getTransitGatewayCidrBlocks() != null) {
options.setTransitGatewayCidrBlocks(new ArrayList<>(requested.getTransitGatewayCidrBlocks()));
}
return options;
}
private TransitGatewayRouteTable createDefaultTransitGatewayRouteTable(String region, TransitGateway gateway) {
TransitGatewayRouteTable routeTable = new TransitGatewayRouteTable();
String routeTableId = "tgw-rtb-" + randomHex(17);
routeTable.setTransitGatewayRouteTableId(routeTableId);
routeTable.setTransitGatewayId(gateway.getTransitGatewayId());
routeTable.setState("available");
routeTable.setDefaultAssociationRouteTable("enable".equals(gateway.getOptions().getDefaultRouteTableAssociation()));
routeTable.setDefaultPropagationRouteTable("enable".equals(gateway.getOptions().getDefaultRouteTablePropagation()));
routeTable.setCreationTime(ISO_FMT.format(Instant.now()));
routeTable.setRegion(region);
transitGatewayRouteTables.put(key(region, routeTableId), routeTable);
return routeTable;
}
public List<TransitGateway> describeTransitGateways(String region, List<String> transitGatewayIds,
Map<String, List<String>> filters) {
transitGatewayIds.forEach(Ec2Service::requireWellFormedTransitGatewayId);
List<TransitGateway> all = transitGateways.scan(k -> true).stream()
.filter(gateway -> region.equals(gateway.getRegion()))
.collect(Collectors.toList());
for (String transitGatewayId : transitGatewayIds) {
if (all.stream().noneMatch(gateway -> gateway.getTransitGatewayId().equals(transitGatewayId))) {
throw new AwsException("InvalidTransitGatewayID.NotFound",
"Transit Gateway " + transitGatewayId + " was deleted or does not exist.", 400);
}
}
return all.stream()
.filter(gateway -> transitGatewayIds.isEmpty()
|| transitGatewayIds.contains(gateway.getTransitGatewayId()))
.filter(gateway -> matchesFilters(gateway, filters, region))
.collect(Collectors.toList());
}
public TransitGateway modifyTransitGateway(String region, String transitGatewayId, String description,
TransitGatewayOptions changes, List<String> addCidrBlocks,
List<String> removeCidrBlocks) {
synchronized (lockFor(key(region, transitGatewayId))) {
TransitGateway gateway = getRequiredTransitGateway(region, transitGatewayId);
requireCoherentDefaultRouteTableChange(region, gateway, changes);
if (description != null) {
gateway.setDescription(description);
}
applyTransitGatewayOptionChanges(gateway.getOptions(), changes);
applyDefaultRouteTableChanges(region, gateway, changes);
if (removeCidrBlocks != null && !removeCidrBlocks.isEmpty()) {
gateway.getOptions().getTransitGatewayCidrBlocks().removeIf(removeCidrBlocks::contains);
}
if (addCidrBlocks != null) {
for (String cidr : addCidrBlocks) {
if (!gateway.getOptions().getTransitGatewayCidrBlocks().contains(cidr)) {
gateway.getOptions().getTransitGatewayCidrBlocks().add(cidr);
}
}
}
transitGateways.put(key(region, transitGatewayId), gateway);
return gateway;
}
}
/**
* Carries a default route table flag change through to the id it governs and to the table
* itself. Verified against a live account: disabling drops the id from the options entirely
* rather than blanking it, and clears that table's own default marker while leaving the table
* in place — the other default, if still enabled, keeps both its id and its marker.
*/
private void applyDefaultRouteTableChanges(String region, TransitGateway gateway,
TransitGatewayOptions changes) {
if (changes == null) {
return;
}
TransitGatewayOptions options = gateway.getOptions();
// The id on the options already carries any id the request supplied, so enabling without
// one keeps the table the gateway already names rather than dropping it.
if (changes.getDefaultRouteTableAssociation() != null) {
if ("enable".equals(changes.getDefaultRouteTableAssociation())) {
markDefaultRouteTable(region, options.getAssociationDefaultRouteTableId(), true, true);
} else {
String previous = options.getAssociationDefaultRouteTableId();
options.setAssociationDefaultRouteTableId(null);
markDefaultRouteTable(region, previous, true, false);
}
} else if (changes.getAssociationDefaultRouteTableId() != null) {
markDefaultRouteTable(region, changes.getAssociationDefaultRouteTableId(), true, true);
}
if (changes.getDefaultRouteTablePropagation() != null) {
if ("enable".equals(changes.getDefaultRouteTablePropagation())) {
markDefaultRouteTable(region, options.getPropagationDefaultRouteTableId(), false, true);
} else {
String previous = options.getPropagationDefaultRouteTableId();
options.setPropagationDefaultRouteTableId(null);
markDefaultRouteTable(region, previous, false, false);
}
} else if (changes.getPropagationDefaultRouteTableId() != null) {
markDefaultRouteTable(region, changes.getPropagationDefaultRouteTableId(), false, true);
}
}
private void markDefaultRouteTable(String region, String routeTableId, boolean association, boolean isDefault) {
if (routeTableId == null) {
return;
}
transitGatewayRouteTables.get(key(region, routeTableId)).ifPresent(routeTable -> {
if (association) {
routeTable.setDefaultAssociationRouteTable(isDefault);
} else {
routeTable.setDefaultPropagationRouteTable(isDefault);
}
transitGatewayRouteTables.put(key(region, routeTableId), routeTable);
});
}
/**
* A default route table flag and its id have to move together, which is what stops the two
* from diverging: AWS will not enable association or propagation without being told which
* existing route table to use, and will not accept an id alongside a disable. Verified against
* a live account, including that an unknown table is reported as
* {@code InvalidRouteTableID.NotFound} rather than a transit-gateway-specific code.
*/
private void requireCoherentDefaultRouteTableChange(String region, TransitGateway gateway,
TransitGatewayOptions changes) {
if (changes == null) {
return;
}
TransitGatewayOptions current = gateway.getOptions();
requireFlagAndRouteTableAgree(changes.getDefaultRouteTableAssociation(),
changes.getAssociationDefaultRouteTableId(),
current.getDefaultRouteTableAssociation(), current.getAssociationDefaultRouteTableId(),
"DefaultRouteTableAssociation", "AssociationDefaultRouteTableId");
requireFlagAndRouteTableAgree(changes.getDefaultRouteTablePropagation(),
changes.getPropagationDefaultRouteTableId(),
current.getDefaultRouteTablePropagation(), current.getPropagationDefaultRouteTableId(),
"DefaultRouteTablePropagation", "PropagationDefaultRouteTableId");
requireRouteTableOfGateway(region, gateway, changes.getAssociationDefaultRouteTableId());
requireRouteTableOfGateway(region, gateway, changes.getPropagationDefaultRouteTableId());
}
/**
* The flag and its route table id are judged against the gateway as it stands, not against the
* request alone — which is why an id may arrive on its own. Verified against a live account:
*
* <ul>
* <li>an id on its own is accepted while the option is enabled, and rejected while it is
* disabled, with the message quoting the stored flag rather than the request</li>
* <li>{@code enable} on its own is accepted when the gateway already names a table, and
* rejected when it does not</li>
* <li>{@code disable} may not carry an id at all</li>
* </ul>
*
* <p>This runs before the table is looked up, matching AWS: a disabled option paired with an
* id that does not exist reports the combination rather than the missing table.
*/
private void requireFlagAndRouteTableAgree(String flag, String routeTableId,
String currentFlag, String currentRouteTableId,
String flagName, String routeTableIdName) {
String effectiveFlag = flag != null ? flag : currentFlag;
if (!"enable".equals(effectiveFlag)) {
if (routeTableId != null) {
throw new AwsException("InvalidParameterCombination",
"disable " + flagName + " conflicts with " + routeTableIdName + " " + routeTableId, 400);
}
return;
}
if (flag != null && routeTableId == null && currentRouteTableId == null) {
throw new AwsException("InvalidParameterCombination",
"enable " + flagName + " conflicts with " + routeTableIdName + " null", 400);
}
}
/**
* A default route table has to belong to the gateway naming it. AWS reports a table owned by
* another gateway under the same {@code InvalidRouteTableID.NotFound} code as one that exists
* nowhere, but qualifies the message with the gateway; both wordings are reproduced here.
*/
private void requireRouteTableOfGateway(String region, TransitGateway gateway, String routeTableId) {
if (routeTableId == null) {
return;
}
TransitGatewayRouteTable routeTable = transitGatewayRouteTables.get(key(region, routeTableId)).orElse(null);
if (routeTable == null) {
throw new AwsException("InvalidRouteTableID.NotFound",
"Transit Gateway Route Table " + routeTableId + " was deleted or does not exist.", 400);
}
if (!gateway.getTransitGatewayId().equals(routeTable.getTransitGatewayId())) {
throw new AwsException("InvalidRouteTableID.NotFound",
"Transit Gateway Route Table " + routeTableId + " was deleted or does not exist in Transit Gateway "
+ gateway.getTransitGatewayId() + ".", 400);
}
}
private void applyTransitGatewayOptionChanges(TransitGatewayOptions options, TransitGatewayOptions changes) {
if (changes == null) {
return;
}
if (changes.getAmazonSideAsn() != null) {
options.setAmazonSideAsn(changes.getAmazonSideAsn());
}
if (changes.getAutoAcceptSharedAttachments() != null) {
options.setAutoAcceptSharedAttachments(changes.getAutoAcceptSharedAttachments());
}
if (changes.getDefaultRouteTableAssociation() != null) {
options.setDefaultRouteTableAssociation(changes.getDefaultRouteTableAssociation());
}
if (changes.getAssociationDefaultRouteTableId() != null) {
options.setAssociationDefaultRouteTableId(changes.getAssociationDefaultRouteTableId());
}
if (changes.getDefaultRouteTablePropagation() != null) {
options.setDefaultRouteTablePropagation(changes.getDefaultRouteTablePropagation());
}
if (changes.getPropagationDefaultRouteTableId() != null) {
options.setPropagationDefaultRouteTableId(changes.getPropagationDefaultRouteTableId());
}
if (changes.getVpnEcmpSupport() != null) {
options.setVpnEcmpSupport(changes.getVpnEcmpSupport());
}
if (changes.getDnsSupport() != null) {
options.setDnsSupport(changes.getDnsSupport());
}
if (changes.getSecurityGroupReferencingSupport() != null) {
options.setSecurityGroupReferencingSupport(changes.getSecurityGroupReferencingSupport());
}
if (changes.getMulticastSupport() != null) {
options.setMulticastSupport(changes.getMulticastSupport());
}
}
/**
* Deletes a transit gateway and the default route table created with it, which is what the
* live API does — the route table disappears alongside the gateway rather than outliving it.
*
* <p>AWS reports {@code deleting} here and settles on {@code deleted} about a minute later;
* the returned object carries the settled state for the same reason creation does.
*/
public TransitGateway deleteTransitGateway(String region, String transitGatewayId) {
synchronized (lockFor(key(region, transitGatewayId))) {
TransitGateway gateway = getRequiredTransitGateway(region, transitGatewayId);
transitGatewayRouteTables.scan(k -> true).stream()
.filter(routeTable -> region.equals(routeTable.getRegion()))
.filter(routeTable -> transitGatewayId.equals(routeTable.getTransitGatewayId()))
.toList()
.forEach(routeTable -> transitGatewayRouteTables
.delete(key(region, routeTable.getTransitGatewayRouteTableId())));
transitGateways.delete(key(region, transitGatewayId));
tags.delete(transitGatewayId);
gateway.setState("deleted");
return gateway;
}
}
private TransitGateway getRequiredTransitGateway(String region, String transitGatewayId) {
if (transitGatewayId == null || transitGatewayId.isBlank()) {
throw new AwsException("MissingParameter",
"The request must contain the parameter TransitGatewayId.", 400);
}
return describeTransitGateways(region, List.of(transitGatewayId), Map.of()).stream()
.findFirst()
.orElseThrow(() -> new AwsException("InvalidTransitGatewayID.NotFound",
"Transit Gateway " + transitGatewayId + " was deleted or does not exist.", 400));
}
private static void requireWellFormedTransitGatewayId(String transitGatewayId) {
if (!TRANSIT_GATEWAY_ID_PATTERN.matcher(transitGatewayId).matches()) {
throw new AwsException("InvalidTransitGatewayID.Malformed",
"Invalid Transit Gateway id " + transitGatewayId + ".", 400);
}
}
// ─── Instances ─────────────────────────────────────────────────────────────
public Reservation runInstances(String region, String imageId, String instanceType,
@@ -2770,6 +3174,18 @@ public class Ec2Service implements ContainerTeardown {
if (prefixList != null) {
prefixList.setTags(new ArrayList<>(tagList));
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);
}
}
@@ -2848,6 +3264,13 @@ public class Ec2Service implements ContainerTeardown {
if (resourceId.startsWith("pl-")) {
return "prefix-list";
}
// Checked before the gateway prefix, which it starts with.
if (resourceId.startsWith("tgw-rtb-")) {
return "transit-gateway-route-table";
}
if (resourceId.startsWith("tgw-")) {
return "transit-gateway";
}
return "unknown";
}
@@ -3357,6 +3780,22 @@ public class Ec2Service implements ContainerTeardown {
default -> true;
};
}
if (resource instanceof TransitGateway gateway) {
return switch (filterName) {
case "transit-gateway-id" -> matchesValue(values, gateway.getTransitGatewayId());
case "state" -> matchesValue(values, gateway.getState());
case "owner-id" -> matchesValue(values, gateway.getOwnerId());
case "options.amazon-side-asn" ->
matchesValue(values, String.valueOf(gateway.getOptions().getAmazonSideAsn()));
case "options.association-default-route-table-id" ->
matchesValue(values, gateway.getOptions().getAssociationDefaultRouteTableId());
case "options.propagation-default-route-table-id" ->
matchesValue(values, gateway.getOptions().getPropagationDefaultRouteTableId());
case "options.dns-support" -> matchesValue(values, gateway.getOptions().getDnsSupport());
case "options.vpn-ecmp-support" -> matchesValue(values, gateway.getOptions().getVpnEcmpSupport());
default -> true;
};
}
if (resource instanceof SecurityGroup sg) {
return switch (filterName) {
case "group-id" -> matchesValue(values, sg.getGroupId());
@@ -3487,6 +3926,8 @@ public class Ec2Service implements ContainerTeardown {
if (resource instanceof VpcEndpoint endpoint) return endpoint.getTags();
if (resource instanceof NatGateway natGateway) return natGateway.getTags();
if (resource instanceof SpotInstanceRequest sir) return sir.getTags();
if (resource instanceof TransitGateway gateway) return gateway.getTags();
if (resource instanceof TransitGatewayRouteTable routeTable) return routeTable.getTags();
return Collections.emptyList();
}
@@ -0,0 +1,51 @@
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;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class TransitGateway {
private String transitGatewayId;
private String transitGatewayArn;
private String state;
private String ownerId;
private String description;
private String creationTime;
private String region;
private TransitGatewayOptions options = new TransitGatewayOptions();
private List<Tag> tags = new ArrayList<>();
public TransitGateway() {}
public String getTransitGatewayId() { return transitGatewayId; }
public void setTransitGatewayId(String transitGatewayId) { this.transitGatewayId = transitGatewayId; }
public String getTransitGatewayArn() { return transitGatewayArn; }
public void setTransitGatewayArn(String transitGatewayArn) { this.transitGatewayArn = transitGatewayArn; }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
public String getOwnerId() { return ownerId; }
public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
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 TransitGatewayOptions getOptions() { return options; }
public void setOptions(TransitGatewayOptions options) { this.options = options; }
public List<Tag> getTags() { return tags; }
public void setTags(List<Tag> tags) { this.tags = tags; }
}
@@ -0,0 +1,73 @@
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;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class TransitGatewayOptions {
private Long amazonSideAsn;
private List<String> transitGatewayCidrBlocks = new ArrayList<>();
private String autoAcceptSharedAttachments;
private String defaultRouteTableAssociation;
private String associationDefaultRouteTableId;
private String defaultRouteTablePropagation;
private String propagationDefaultRouteTableId;
private String vpnEcmpSupport;
private String dnsSupport;
private String securityGroupReferencingSupport;
private String multicastSupport;
public TransitGatewayOptions() {}
public Long getAmazonSideAsn() { return amazonSideAsn; }
public void setAmazonSideAsn(Long amazonSideAsn) { this.amazonSideAsn = amazonSideAsn; }
public List<String> getTransitGatewayCidrBlocks() { return transitGatewayCidrBlocks; }
public void setTransitGatewayCidrBlocks(List<String> transitGatewayCidrBlocks) {
this.transitGatewayCidrBlocks = transitGatewayCidrBlocks;
}
public String getAutoAcceptSharedAttachments() { return autoAcceptSharedAttachments; }
public void setAutoAcceptSharedAttachments(String autoAcceptSharedAttachments) {
this.autoAcceptSharedAttachments = autoAcceptSharedAttachments;
}
public String getDefaultRouteTableAssociation() { return defaultRouteTableAssociation; }
public void setDefaultRouteTableAssociation(String defaultRouteTableAssociation) {
this.defaultRouteTableAssociation = defaultRouteTableAssociation;
}
public String getAssociationDefaultRouteTableId() { return associationDefaultRouteTableId; }
public void setAssociationDefaultRouteTableId(String associationDefaultRouteTableId) {
this.associationDefaultRouteTableId = associationDefaultRouteTableId;
}
public String getDefaultRouteTablePropagation() { return defaultRouteTablePropagation; }
public void setDefaultRouteTablePropagation(String defaultRouteTablePropagation) {
this.defaultRouteTablePropagation = defaultRouteTablePropagation;
}
public String getPropagationDefaultRouteTableId() { return propagationDefaultRouteTableId; }
public void setPropagationDefaultRouteTableId(String propagationDefaultRouteTableId) {
this.propagationDefaultRouteTableId = propagationDefaultRouteTableId;
}
public String getVpnEcmpSupport() { return vpnEcmpSupport; }
public void setVpnEcmpSupport(String vpnEcmpSupport) { this.vpnEcmpSupport = vpnEcmpSupport; }
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 getMulticastSupport() { return multicastSupport; }
public void setMulticastSupport(String multicastSupport) { this.multicastSupport = multicastSupport; }
}
@@ -0,0 +1,60 @@
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 route table. Creating a transit gateway with
* {@code DefaultRouteTableAssociation} or {@code DefaultRouteTablePropagation} enabled makes AWS
* mint one of these immediately, and its id is reported back on the gateway's options, so the
* record exists here from part one. The actions that operate on route tables directly
* (create, associate, propagate, describe) are not implemented yet.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class TransitGatewayRouteTable {
private String transitGatewayRouteTableId;
private String transitGatewayId;
private String state;
private boolean defaultAssociationRouteTable;
private boolean defaultPropagationRouteTable;
private String creationTime;
private String region;
private List<Tag> tags = new ArrayList<>();
public TransitGatewayRouteTable() {}
public String getTransitGatewayRouteTableId() { return transitGatewayRouteTableId; }
public void setTransitGatewayRouteTableId(String transitGatewayRouteTableId) {
this.transitGatewayRouteTableId = transitGatewayRouteTableId;
}
public String getTransitGatewayId() { return transitGatewayId; }
public void setTransitGatewayId(String transitGatewayId) { this.transitGatewayId = transitGatewayId; }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
public boolean isDefaultAssociationRouteTable() { return defaultAssociationRouteTable; }
public void setDefaultAssociationRouteTable(boolean defaultAssociationRouteTable) {
this.defaultAssociationRouteTable = defaultAssociationRouteTable;
}
public boolean isDefaultPropagationRouteTable() { return defaultPropagationRouteTable; }
public void setDefaultPropagationRouteTable(boolean defaultPropagationRouteTable) {
this.defaultPropagationRouteTable = defaultPropagationRouteTable;
}
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 List<Tag> getTags() { return tags; }
public void setTags(List<Tag> tags) { this.tags = tags; }
}
@@ -23,6 +23,9 @@ import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.Snapshot;
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.UserIdGroupPair;
import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;
import io.github.hectorvent.floci.services.ec2.model.Volume;
@@ -1279,6 +1282,390 @@ class Ec2ServiceTest {
Map.of("resource-type", List.of("security-group"))).size());
}
// =========================================================================
// Transit gateways
// =========================================================================
/**
* Every default here was read off a live AWS account rather than the documentation, including
* the one that is easy to assume the other way: {@code securityGroupReferencingSupport} is
* {@code disable} on a new gateway.
*/
@Test
void createTransitGatewayAppliesTheDefaultsAwsApplies() {
Ec2Service service = prefixListService();
TransitGateway gateway = service.createTransitGateway("us-east-1", "hub", null, List.of());
assertTrue(gateway.getTransitGatewayId().startsWith("tgw-"));
assertEquals("arn:aws:ec2:us-east-1:000000000000:transit-gateway/" + gateway.getTransitGatewayId(),
gateway.getTransitGatewayArn());
assertEquals("available", gateway.getState());
assertEquals("000000000000", gateway.getOwnerId());
assertEquals("hub", gateway.getDescription());
TransitGatewayOptions options = gateway.getOptions();
assertEquals(64512L, options.getAmazonSideAsn());
assertEquals("disable", options.getAutoAcceptSharedAttachments());
assertEquals("enable", options.getDefaultRouteTableAssociation());
assertEquals("enable", options.getDefaultRouteTablePropagation());
assertEquals("enable", options.getVpnEcmpSupport());
assertEquals("enable", options.getDnsSupport());
assertEquals("disable", options.getSecurityGroupReferencingSupport());
assertEquals("disable", options.getMulticastSupport());
assertTrue(options.getTransitGatewayCidrBlocks().isEmpty());
}
/**
* AWS mints the default route table during creation, so both ids are already on the create
* response and both name the same table.
*/
@Test
void createTransitGatewayMintsTheDefaultRouteTableAndReportsItsId() {
Ec2Service service = prefixListService();
TransitGatewayOptions options =
service.createTransitGateway("us-east-1", null, null, List.of()).getOptions();
assertNotNull(options.getAssociationDefaultRouteTableId());
assertTrue(options.getAssociationDefaultRouteTableId().startsWith("tgw-rtb-"));
assertEquals(options.getAssociationDefaultRouteTableId(), options.getPropagationDefaultRouteTableId(),
"association and propagation point at the same default table");
}
@Test
void aGatewayThatOptsOutOfBothDefaultsGetsNoRouteTable() {
Ec2Service service = prefixListService();
TransitGatewayOptions requested = new TransitGatewayOptions();
requested.setDefaultRouteTableAssociation("disable");
requested.setDefaultRouteTablePropagation("disable");
TransitGatewayOptions options =
service.createTransitGateway("us-east-1", null, requested, List.of()).getOptions();
assertNull(options.getAssociationDefaultRouteTableId());
assertNull(options.getPropagationDefaultRouteTableId());
}
@Test
void requestedOptionsOverrideTheDefaults() {
Ec2Service service = prefixListService();
TransitGatewayOptions requested = new TransitGatewayOptions();
requested.setAmazonSideAsn(65001L);
requested.setDnsSupport("disable");
requested.setAutoAcceptSharedAttachments("enable");
TransitGatewayOptions options =
service.createTransitGateway("us-east-1", null, requested, List.of()).getOptions();
assertEquals(65001L, options.getAmazonSideAsn());
assertEquals("disable", options.getDnsSupport());
assertEquals("enable", options.getAutoAcceptSharedAttachments());
// Untouched options keep their defaults.
assertEquals("enable", options.getVpnEcmpSupport());
}
@Test
void describeTransitGatewaysFiltersAndRejectsUnknownIds() {
Ec2Service service = prefixListService();
TransitGateway gateway = service.createTransitGateway("us-east-1", "hub", null,
List.of(new Tag("env", "prod")));
service.createTransitGateway("us-east-1", "spoke", null, List.of());
assertEquals(2, service.describeTransitGateways("us-east-1", List.of(), Map.of()).size());
assertEquals(1, service.describeTransitGateways("us-east-1", List.of(),
Map.of("tag:env", List.of("prod"))).size());
assertEquals(gateway.getTransitGatewayId(), service.describeTransitGateways("us-east-1",
List.of(gateway.getTransitGatewayId()), Map.of()).getFirst().getTransitGatewayId());
// Another region cannot see it.
assertTrue(service.describeTransitGateways("eu-west-1", List.of(), Map.of()).isEmpty());
AwsException notFound = assertThrows(AwsException.class, () -> service.describeTransitGateways(
"us-east-1", List.of("tgw-0123456789abcdef0"), Map.of()));
assertEquals("InvalidTransitGatewayID.NotFound", notFound.getErrorCode());
AwsException malformed = assertThrows(AwsException.class, () -> service.describeTransitGateways(
"us-east-1", List.of("tgw-nope"), Map.of()));
assertEquals("InvalidTransitGatewayID.Malformed", malformed.getErrorCode());
}
@Test
void modifyTransitGatewayUpdatesDescriptionOptionsAndCidrBlocks() {
Ec2Service service = prefixListService();
String id = service.createTransitGateway("us-east-1", "before", null, List.of()).getTransitGatewayId();
TransitGatewayOptions changes = new TransitGatewayOptions();
changes.setDnsSupport("disable");
TransitGateway modified = service.modifyTransitGateway("us-east-1", id, "after", changes,
List.of("10.100.0.0/16", "10.101.0.0/16"), List.of());
assertEquals("after", modified.getDescription());
assertEquals("disable", modified.getOptions().getDnsSupport());
assertEquals(List.of("10.100.0.0/16", "10.101.0.0/16"),
modified.getOptions().getTransitGatewayCidrBlocks());
TransitGateway shrunk = service.modifyTransitGateway("us-east-1", id, null, null,
List.of(), List.of("10.100.0.0/16"));
assertEquals(List.of("10.101.0.0/16"), shrunk.getOptions().getTransitGatewayCidrBlocks());
assertEquals("after", shrunk.getDescription(), "a null description leaves the stored one alone");
}
/**
* The flag and its route table id have to move together. Verified against a live account: AWS
* refuses to enable association or propagation without being told which existing table to use,
* refuses an id alongside a disable, and reports an unknown table as
* {@code InvalidRouteTableID.NotFound}. Without this a gateway could report the option enabled
* while carrying no id at all.
*/
@Test
void enablingADefaultRouteTableOptionRequiresAnExistingRouteTable() {
Ec2Service service = prefixListService();
TransitGatewayOptions createdWithout = new TransitGatewayOptions();
createdWithout.setDefaultRouteTableAssociation("disable");
createdWithout.setDefaultRouteTablePropagation("disable");
String id = service.createTransitGateway("us-east-1", null, createdWithout, List.of())
.getTransitGatewayId();
TransitGatewayOptions enableOnly = new TransitGatewayOptions();
enableOnly.setDefaultRouteTableAssociation("enable");
AwsException noId = assertThrows(AwsException.class, () -> service.modifyTransitGateway(
"us-east-1", id, null, enableOnly, List.of(), List.of()));
assertEquals("InvalidParameterCombination", noId.getErrorCode());
TransitGatewayOptions propagationOnly = new TransitGatewayOptions();
propagationOnly.setDefaultRouteTablePropagation("enable");
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
() -> service.modifyTransitGateway("us-east-1", id, null, propagationOnly,
List.of(), List.of())).getErrorCode());
TransitGatewayOptions disableWithId = new TransitGatewayOptions();
disableWithId.setDefaultRouteTableAssociation("disable");
disableWithId.setAssociationDefaultRouteTableId("tgw-rtb-0123456789abcdef0");
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
() -> service.modifyTransitGateway("us-east-1", id, null, disableWithId,
List.of(), List.of())).getErrorCode());
TransitGatewayOptions unknownTable = new TransitGatewayOptions();
unknownTable.setDefaultRouteTableAssociation("enable");
unknownTable.setAssociationDefaultRouteTableId("tgw-rtb-0123456789abcdef0");
assertEquals("InvalidRouteTableID.NotFound", assertThrows(AwsException.class,
() -> service.modifyTransitGateway("us-east-1", id, null, unknownTable,
List.of(), List.of())).getErrorCode());
// The rejected calls left the gateway as it was, rather than half-applied.
TransitGatewayOptions after = service.describeTransitGateways("us-east-1", List.of(id), Map.of())
.getFirst().getOptions();
assertEquals("disable", after.getDefaultRouteTableAssociation());
assertNull(after.getAssociationDefaultRouteTableId());
}
/**
* Verified against a live account: a route table belonging to another gateway is rejected
* under the same code as one that exists nowhere, with the gateway named in the message.
* Without the ownership check the foreign table's own default markers would be rewritten.
*/
@Test
void aRouteTableBelongingToAnotherGatewayIsRejected() {
AccountAwareStorageBackend<TransitGatewayRouteTable> routeTables =
AccountAwareStorageBackend.inMemory("000000000000");
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory(Map.of("ec2-transit-gateway-route-tables.json", routeTables)));
TransitGatewayOptions defaultsOff = new TransitGatewayOptions();
defaultsOff.setDefaultRouteTableAssociation("disable");
defaultsOff.setDefaultRouteTablePropagation("disable");
String borrower = service.createTransitGateway("us-east-1", "borrower", defaultsOff, List.of())
.getTransitGatewayId();
TransitGateway owner = service.createTransitGateway("us-east-1", "owner", null, List.of());
String ownersRouteTable = owner.getOptions().getAssociationDefaultRouteTableId();
TransitGatewayOptions changes = new TransitGatewayOptions();
changes.setDefaultRouteTableAssociation("enable");
changes.setAssociationDefaultRouteTableId(ownersRouteTable);
AwsException error = assertThrows(AwsException.class, () -> service.modifyTransitGateway(
"us-east-1", borrower, null, changes, List.of(), List.of()));
assertEquals("InvalidRouteTableID.NotFound", error.getErrorCode());
assertTrue(error.getMessage().contains(borrower),
"the message names the gateway the table is missing from");
// The owner's table kept its markers, and the borrower stayed disabled.
TransitGatewayRouteTable stored = routeTables.get("us-east-1::" + ownersRouteTable).orElseThrow();
assertTrue(stored.isDefaultAssociationRouteTable());
assertNull(service.describeTransitGateways("us-east-1", List.of(borrower), Map.of())
.getFirst().getOptions().getAssociationDefaultRouteTableId());
}
/**
* The whole flag/id contract, as observed on a live account. The pair is judged against the
* gateway as it stands rather than against the request alone, which is what makes an id on its
* own legal while the option is enabled and a conflict while it is disabled.
*/
@Test
void aRouteTableIdOnItsOwnFollowsTheStoredFlag() {
Ec2Service service = prefixListService();
TransitGateway gateway = service.createTransitGateway("us-east-1", "hub", null, List.of());
String id = gateway.getTransitGatewayId();
String routeTableId = gateway.getOptions().getAssociationDefaultRouteTableId();
// Enabled: an id on its own is accepted, and enable on its own keeps the stored table.
TransitGatewayOptions idOnly = new TransitGatewayOptions();
idOnly.setAssociationDefaultRouteTableId(routeTableId);
assertEquals(routeTableId, service.modifyTransitGateway("us-east-1", id, null, idOnly,
List.of(), List.of()).getOptions().getAssociationDefaultRouteTableId());
TransitGatewayOptions flagOnly = new TransitGatewayOptions();
flagOnly.setDefaultRouteTableAssociation("enable");
assertEquals(routeTableId, service.modifyTransitGateway("us-east-1", id, null, flagOnly,
List.of(), List.of()).getOptions().getAssociationDefaultRouteTableId(),
"enable on its own keeps the table already named");
// Disabled: the same id-only request now conflicts, and the message quotes the stored flag.
TransitGatewayOptions disable = new TransitGatewayOptions();
disable.setDefaultRouteTableAssociation("disable");
service.modifyTransitGateway("us-east-1", id, null, disable, List.of(), List.of());
AwsException conflict = assertThrows(AwsException.class, () -> service.modifyTransitGateway(
"us-east-1", id, null, idOnly, List.of(), List.of()));
assertEquals("InvalidParameterCombination", conflict.getErrorCode());
assertTrue(conflict.getMessage().startsWith("disable DefaultRouteTableAssociation"),
"the stored flag is what the message reports, got: " + conflict.getMessage());
// A disabled option paired with an unknown table reports the combination, not the lookup.
TransitGatewayOptions unknownIdOnly = new TransitGatewayOptions();
unknownIdOnly.setAssociationDefaultRouteTableId("tgw-rtb-0123456789abcdef0");
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
() -> service.modifyTransitGateway("us-east-1", id, null, unknownIdOnly,
List.of(), List.of())).getErrorCode());
// And enable on its own is a conflict once there is no table left to keep.
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
() -> service.modifyTransitGateway("us-east-1", id, null, flagOnly,
List.of(), List.of())).getErrorCode());
}
/** Removals apply before additions, so a CIDR added and removed in one call survives. */
@Test
void aCidrBlockAddedAndRemovedInOneCallSurvives() {
Ec2Service service = prefixListService();
String id = service.createTransitGateway("us-east-1", null, null, List.of()).getTransitGatewayId();
TransitGatewayOptions after = service.modifyTransitGateway("us-east-1", id, null, null,
List.of("10.200.0.0/16"), List.of("10.200.0.0/16")).getOptions();
assertEquals(List.of("10.200.0.0/16"), after.getTransitGatewayCidrBlocks());
}
/** Repointing the default route table at the gateway's own table is accepted. */
@Test
void aDefaultRouteTableOptionCanBeSetWhenItsRouteTableIsNamed() {
Ec2Service service = prefixListService();
TransitGateway gateway = service.createTransitGateway("us-east-1", null, null, List.of());
String routeTableId = gateway.getOptions().getAssociationDefaultRouteTableId();
TransitGatewayOptions changes = new TransitGatewayOptions();
changes.setDefaultRouteTableAssociation("enable");
changes.setAssociationDefaultRouteTableId(routeTableId);
TransitGatewayOptions after = service.modifyTransitGateway("us-east-1",
gateway.getTransitGatewayId(), null, changes, List.of(), List.of()).getOptions();
assertEquals("enable", after.getDefaultRouteTableAssociation());
assertEquals(routeTableId, after.getAssociationDefaultRouteTableId());
}
/**
* Verified against a live account: disabling one default drops its id from the options
* entirely and clears that marker on the route table, while the other default keeps both its
* id and its marker, and the table itself survives.
*/
@Test
void disablingADefaultDropsItsIdAndClearsOnlyThatMarker() {
AccountAwareStorageBackend<TransitGatewayRouteTable> routeTables =
AccountAwareStorageBackend.inMemory("000000000000");
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory(Map.of("ec2-transit-gateway-route-tables.json", routeTables)));
TransitGateway gateway = service.createTransitGateway("us-east-1", "hub", null, List.of());
String routeTableId = gateway.getOptions().getAssociationDefaultRouteTableId();
TransitGatewayOptions changes = new TransitGatewayOptions();
changes.setDefaultRouteTableAssociation("disable");
TransitGatewayOptions after = service.modifyTransitGateway("us-east-1",
gateway.getTransitGatewayId(), null, changes, List.of(), List.of()).getOptions();
assertEquals("disable", after.getDefaultRouteTableAssociation());
assertNull(after.getAssociationDefaultRouteTableId(), "the id goes with the flag");
assertEquals("enable", after.getDefaultRouteTablePropagation());
assertEquals(routeTableId, after.getPropagationDefaultRouteTableId(),
"the other default is untouched");
TransitGatewayRouteTable stored = routeTables.scan(k -> true).getFirst();
assertFalse(stored.isDefaultAssociationRouteTable(), "association marker cleared");
assertTrue(stored.isDefaultPropagationRouteTable(), "propagation marker kept");
assertEquals(routeTableId, stored.getTransitGatewayRouteTableId(), "the table itself survives");
}
@Test
void deleteTransitGatewayRemovesTheGatewayAndItsDefaultRouteTable() {
AccountAwareStorageBackend<TransitGatewayRouteTable> routeTables =
AccountAwareStorageBackend.inMemory("000000000000");
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory(Map.of("ec2-transit-gateway-route-tables.json", routeTables)));
String id = service.createTransitGateway("us-east-1", "hub", null, List.of()).getTransitGatewayId();
assertEquals(1, routeTables.scan(k -> true).size(), "creation mints the default route table");
TransitGateway deleted = service.deleteTransitGateway("us-east-1", id);
assertEquals("deleted", deleted.getState());
assertTrue(routeTables.scan(k -> true).isEmpty(), "the default route table goes with the gateway");
AwsException gone = assertThrows(AwsException.class,
() -> service.describeTransitGateways("us-east-1", List.of(id), Map.of()));
assertEquals("InvalidTransitGatewayID.NotFound", gone.getErrorCode());
}
/**
* A provider changes tags after creation with CreateTags and DeleteTags rather than resending
* a TagSpecification, then re-reads them from DescribeTransitGateways. Those have to be the
* same tags, or the resource never converges.
*/
@Test
void tagsChangedAfterCreationAreVisibleOnDescribe() {
Ec2Service service = prefixListService();
String id = service.createTransitGateway("us-east-1", "hub", null,
List.of(new Tag("Name", "hub"))).getTransitGatewayId();
service.createTags("us-east-1", List.of(id), List.of(new Tag("env", "prod")));
List<Tag> afterCreate = service.describeTransitGateways("us-east-1", List.of(id), Map.of())
.getFirst().getTags();
assertEquals(2, afterCreate.size(), "describe serves the tags CreateTags stored");
assertTrue(afterCreate.stream().anyMatch(t -> "env".equals(t.getKey()) && "prod".equals(t.getValue())));
service.deleteTags("us-east-1", List.of(id), List.of(new Tag("env", null)));
List<Tag> afterDelete = service.describeTransitGateways("us-east-1", List.of(id), Map.of())
.getFirst().getTags();
assertEquals(1, afterDelete.size());
assertEquals("Name", afterDelete.getFirst().getKey());
}
@Test
void tagsOnATransitGatewayAreTypedAsTransitGateway() {
Ec2Service service = prefixListService();
String id = service.createTransitGateway("us-east-1", "hub", null,
List.of(new Tag("env", "prod"))).getTransitGatewayId();
assertEquals("transit-gateway", service.describeTags("us-east-1",
Map.of("resource-id", List.of(id))).getFirst().get("resourceType"));
assertEquals(1, service.describeTags("us-east-1",
Map.of("resource-type", List.of("transit-gateway"))).size());
}
private static EmulatorConfig mockConfig(boolean ec2Mock) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
@@ -0,0 +1,170 @@
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.emptyOrNullString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Transit gateways over the EC2 Query protocol: creation with and without options, the read-back
* shape, modification, and deletion.
*
* <p>The response shapes asserted here were captured from a live AWS account, including the one
* that is not obvious from the API reference: create and describe carry a {@code tagSet}, while
* modify and delete return the same gateway without one.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class Ec2TransitGatewayIntegrationTest {
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 defaultRouteTableId;
@Test
@Order(1)
void createReturnsTheGatewayWithAwsDefaultsAndItsTags() {
transitGatewayId = given()
.formParam("Action", "CreateTransitGateway")
.formParam("Description", "hub")
.formParam("TagSpecification.1.ResourceType", "transit-gateway")
.formParam("TagSpecification.1.Tag.1.Key", "env")
.formParam("TagSpecification.1.Tag.1.Value", "prod")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("CreateTransitGatewayResponse.transitGateway.state", equalTo("available"))
.body("CreateTransitGatewayResponse.transitGateway.description", equalTo("hub"))
.body("CreateTransitGatewayResponse.transitGateway.options.amazonSideAsn", equalTo("64512"))
.body("CreateTransitGatewayResponse.transitGateway.options.dnsSupport", equalTo("enable"))
.body("CreateTransitGatewayResponse.transitGateway.options.securityGroupReferencingSupport",
equalTo("disable"))
.body("CreateTransitGatewayResponse.transitGateway.tagSet.item.key", equalTo("env"))
.extract().path("CreateTransitGatewayResponse.transitGateway.transitGatewayId");
defaultRouteTableId = given()
.formParam("Action", "DescribeTransitGateways")
.formParam("TransitGatewayIds.1", transitGatewayId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("DescribeTransitGatewaysResponse.transitGatewaySet.item.transitGatewayArn",
startsWith("arn:aws:ec2:"))
.body("DescribeTransitGatewaysResponse.transitGatewaySet.item.tagSet.item.value", equalTo("prod"))
.extract()
.path("DescribeTransitGatewaysResponse.transitGatewaySet.item.options.associationDefaultRouteTableId");
// The default route table is minted during creation, so its id is already reported back.
assertTrue(defaultRouteTableId.startsWith("tgw-rtb-"),
"expected a default route table id, got " + defaultRouteTableId);
}
@Test
@Order(2)
void createHonoursExplicitOptions() {
String body = given()
.formParam("Action", "CreateTransitGateway")
.formParam("Options.AmazonSideAsn", "65001")
.formParam("Options.DnsSupport", "disable")
.formParam("Options.DefaultRouteTableAssociation", "disable")
.formParam("Options.DefaultRouteTablePropagation", "disable")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("CreateTransitGatewayResponse.transitGateway.options.amazonSideAsn", equalTo("65001"))
.body("CreateTransitGatewayResponse.transitGateway.options.dnsSupport", equalTo("disable"))
.extract().asString();
// Opting out of both defaults means there is no table to point at, and AWS omits the
// element rather than sending it empty. Asserted on the raw body because a missing path
// reads back as an empty node object rather than a null string.
assertThat(body, not(containsString("associationDefaultRouteTableId")));
assertThat(body, not(containsString("propagationDefaultRouteTableId")));
}
@Test
@Order(3)
void modifyAppliesOptionsAndReturnsNoTagSet() {
String body = given()
.formParam("Action", "ModifyTransitGateway")
.formParam("TransitGatewayId", transitGatewayId)
.formParam("Description", "hub-modified")
.formParam("Options.DnsSupport", "disable")
.formParam("Options.AddTransitGatewayCidrBlocks.1", "10.100.0.0/16")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("ModifyTransitGatewayResponse.transitGateway.description", equalTo("hub-modified"))
.body("ModifyTransitGatewayResponse.transitGateway.options.dnsSupport", equalTo("disable"))
// A plain string list: the CIDR is the item's own text, which is what the AWS CLI
// parses back into TransitGatewayCidrBlocks[0].
.body("ModifyTransitGatewayResponse.transitGateway.options.transitGatewayCidrBlocks.item",
equalTo("10.100.0.0/16"))
.extract().asString();
assertThat(body, not(containsString("tagSet")));
// The tags are still there; modify just does not echo them.
given()
.formParam("Action", "DescribeTransitGateways")
.formParam("TransitGatewayIds.1", transitGatewayId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("DescribeTransitGatewaysResponse.transitGatewaySet.item.tagSet.item.key", equalTo("env"));
}
@Test
@Order(4)
void describeRejectsAnUnknownGateway() {
given()
.formParam("Action", "DescribeTransitGateways")
.formParam("TransitGatewayIds.1", "tgw-0123456789abcdef0")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidTransitGatewayID.NotFound"));
}
@Test
@Order(5)
void deleteRemovesTheGateway() {
given()
.formParam("Action", "DeleteTransitGateway")
.formParam("TransitGatewayId", transitGatewayId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("DeleteTransitGatewayResponse.transitGateway.state", equalTo("deleted"))
.body("DeleteTransitGatewayResponse.transitGateway.transitGatewayId", equalTo(transitGatewayId));
given()
.formParam("Action", "DescribeTransitGateways")
.formParam("TransitGatewayIds.1", transitGatewayId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidTransitGatewayID.NotFound"));
// The gateway created in the options test is untouched by this delete.
given()
.formParam("Action", "DescribeTransitGateways")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("DescribeTransitGatewaysResponse.transitGatewaySet.item.options.amazonSideAsn",
not(emptyOrNullString()));
}
}