feat(ec2): support egress-only internet gateways (#5822)

* feat(ec2): support egress-only internet gateways

CreateEgressOnlyInternetGateway fell through to UnsupportedOperation, so
aws_egress_only_internet_gateway could not be created, and
DescribeEgressOnlyInternetGateways always answered an empty set.

Egress-only gateways are now stored (ec2-egress-only-internet-gateways.json,
through StorageFactory) and created attached to an existing VPC, with
TagSpecification and CreateTags applied. Describe filters by ID,
egress-only-internet-gateway-id, attachment.vpc-id, attachment.state and
tags; Delete returns returnCode. DeleteVpc reports DependencyViolation
while one is attached. The three actions are added to EC2 query routing,
which removes DescribeEgressOnlyInternetGateways from the known gaps.

* fix(ec2): settle Qodo findings on egress-only internet gateways

- CreateEgressOnlyInternetGateway validates TagSpecification tags before it
  creates anything, so an aws: key no longer leaves an attached gateway behind.
  Tags are applied with the gateway, under the topology lock.
- A ClientToken replay compares the creation tags as well as VpcId: changed tags
  fail with IdempotentParameterMismatch, and a matching replay returns the
  gateway unchanged instead of re-tagging it.
- DescribeEgressOnlyInternetGateways honours MaxResults (5 to 255 in the EC2
  model) and NextToken, ordered by ID, using the service's existing token codec.
- DeleteEgressOnlyInternetGateway takes the resource lock createSystemTags
  takes, and leaves routes that targeted the gateway in place as blackhole, the
  state AWS documents for a route whose target is gone.

* fix(ec2): DeleteEgressOnlyInternetGateway without an id is MissingParameter

The EC2 model marks EgressOnlyInternetGatewayId required. A request
without it answered InvalidGatewayID.NotFound for 'null'; it now gets
the same MissingParameter the other EC2 handlers return. An unknown id
still fails with InvalidGatewayID.NotFound.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-16 22:25:09 -04:00
1 parent f031e4052d
commit 708dc32fa1
10 files changed
+802 -39

No files matched your search

@@ -202,6 +202,8 @@ public class AwsQueryController {
"CreateTags", "DeleteTags", "DescribeTags",
"CreateInternetGateway", "DescribeInternetGateways", "DeleteInternetGateway",
"AttachInternetGateway", "DetachInternetGateway",
"CreateEgressOnlyInternetGateway", "DescribeEgressOnlyInternetGateways",
"DeleteEgressOnlyInternetGateway",
"CreateRouteTable", "DescribeRouteTables", "DeleteRouteTable",
"AssociateRouteTable", "DisassociateRouteTable", "CreateRoute", "ReplaceRoute", "DeleteRoute",
"CreateNetworkAcl", "DescribeNetworkAcls", "DeleteNetworkAcl",
@@ -167,8 +167,10 @@ public class Ec2QueryHandler {
case "ReplaceTransitGatewayRoute" -> handleReplaceTransitGatewayRoute(params, region);
case "SearchTransitGatewayRoutes" -> handleSearchTransitGatewayRoutes(params, region);
case "ExportTransitGatewayRoutes" -> handleExportTransitGatewayRoutes(params, region);
case "CreateEgressOnlyInternetGateway" -> handleCreateEgressOnlyInternetGateway(params, region);
case "DescribeEgressOnlyInternetGateways" ->
handleDescribeEgressOnlyInternetGateways(params);
handleDescribeEgressOnlyInternetGateways(params, region);
case "DeleteEgressOnlyInternetGateway" -> handleDeleteEgressOnlyInternetGateway(params, region);
case "CreateDefaultVpc" -> handleCreateDefaultVpc(params, region);
case "AssociateVpcCidrBlock" -> handleAssociateVpcCidrBlock(params, region);
case "DisassociateVpcCidrBlock" -> handleDisassociateVpcCidrBlock(params, region);
@@ -2947,25 +2949,50 @@ public class Ec2QueryHandler {
}
}
private Response handleDescribeEgressOnlyInternetGateways(MultivaluedMap<String, String> p) {
validateEmptyDiscoveryPagination(p, 255);
service.describeEgressOnlyInternetGatewayIds(getFilters(p));
return emptyDescribeResponse(
"DescribeEgressOnlyInternetGateways", "egressOnlyInternetGatewaySet");
private Response handleCreateEgressOnlyInternetGateway(MultivaluedMap<String, String> p, String region) {
// Tags are validated before anything is created, so a rejected tag leaves no gateway behind.
List<Tag> resourceTags = parseTagsForResource(p, "egress-only-internet-gateway");
EgressOnlyInternetGateway eigw = service.createEgressOnlyInternetGateway(
region, p.getFirst("VpcId"), p.getFirst("ClientToken"), resourceTags);
XmlBuilder xml = new XmlBuilder()
.start("CreateEgressOnlyInternetGatewayResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString());
if (p.getFirst("ClientToken") != null) {
xml.elem("clientToken", p.getFirst("ClientToken"));
}
xml.start("egressOnlyInternetGateway").raw(eigwXml(eigw)).end("egressOnlyInternetGateway")
.end("CreateEgressOnlyInternetGatewayResponse");
return xmlResponse(xml.build());
}
private void validateEmptyDiscoveryPagination(MultivaluedMap<String, String> p, int maximum) {
String rawMaxResults = p.getFirst("MaxResults");
if (rawMaxResults != null) {
int maxResults = parseIntParam(p, "MaxResults", 0);
if (maxResults < 5 || maxResults > maximum) {
throw new AwsException("InvalidMaxResults",
"The specified value for MaxResults is not valid.", 400);
}
private Response handleDescribeEgressOnlyInternetGateways(MultivaluedMap<String, String> p, String region) {
EgressOnlyInternetGatewayListResult result = service.describeEgressOnlyInternetGateways(
region, getList(p, "EgressOnlyInternetGatewayId"), getFilters(p),
p.getFirst("MaxResults") == null ? null : parseIntParam(p, "MaxResults", 0),
p.getFirst("NextToken"));
XmlBuilder xml = new XmlBuilder()
.start("DescribeEgressOnlyInternetGatewaysResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("egressOnlyInternetGatewaySet");
for (EgressOnlyInternetGateway eigw : result.egressOnlyInternetGateways()) {
xml.start("item").raw(eigwXml(eigw)).end("item");
}
if (p.getFirst("NextToken") != null) {
throw new AwsException("InvalidParameterValue", "Invalid NextToken", 400);
xml.end("egressOnlyInternetGatewaySet");
if (result.nextToken() != null) {
xml.elem("nextToken", result.nextToken());
}
xml.end("DescribeEgressOnlyInternetGatewaysResponse");
return xmlResponse(xml.build());
}
private Response handleDeleteEgressOnlyInternetGateway(MultivaluedMap<String, String> p, String region) {
service.deleteEgressOnlyInternetGateway(region, requiredParam(p, "EgressOnlyInternetGatewayId"));
return xmlResponse(new XmlBuilder()
.start("DeleteEgressOnlyInternetGatewayResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.elem("returnCode", "true")
.end("DeleteEgressOnlyInternetGatewayResponse")
.build());
}
private Response emptyDescribeResponse(String action, String resultSet) {
@@ -3806,9 +3833,8 @@ public class Ec2QueryHandler {
String destPrefixList = p.getFirst("DestinationPrefixListId");
String gwId = p.getFirst("GatewayId");
String natGwId = p.getFirst("NatGatewayId");
// The gateway itself is not modelled (CreateEgressOnlyInternetGateway is still
// unimplemented), but the id the caller sent is stored and reported back so an IPv6
// egress route is not silently rewritten into a targetless one.
// The gateway id is stored as sent, not checked against the egress-only gateways that
// exist, so an IPv6 egress route is not silently rewritten into a targetless one.
String eigwId = p.getFirst("EgressOnlyInternetGatewayId");
String pcxId = p.getFirst("VpcPeeringConnectionId");
String instanceId = p.getFirst("InstanceId");
@@ -5039,6 +5065,21 @@ public class Ec2QueryHandler {
return xml.build();
}
private String eigwXml(EgressOnlyInternetGateway eigw) {
XmlBuilder xml = new XmlBuilder()
.elem("egressOnlyInternetGatewayId", eigw.getEgressOnlyInternetGatewayId())
.start("attachmentSet");
for (InternetGatewayAttachment att : eigw.getAttachments()) {
xml.start("item")
.elem("state", att.getState())
.elem("vpcId", att.getVpcId())
.end("item");
}
xml.end("attachmentSet")
.raw(tagSetXml(eigw.getTags()));
return xml.build();
}
private String routeTableXml(RouteTable rt) {
XmlBuilder xml = new XmlBuilder()
.elem("routeTableId", rt.getRouteTableId())
@@ -25,6 +25,8 @@ import io.github.hectorvent.floci.services.ec2.model.Address;
import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
import io.github.hectorvent.floci.services.ec2.model.CapacityReservation;
import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.EgressOnlyInternetGateway;
import io.github.hectorvent.floci.services.ec2.model.EgressOnlyInternetGatewayListResult;
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
import io.github.hectorvent.floci.services.ec2.model.Host;
import io.github.hectorvent.floci.services.ec2.model.IamInstanceProfileAssociation;
@@ -277,6 +279,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
private final StorageBackend<String, List<Tag>> tags;
private final StorageBackend<String, CapacityReservation> capacityReservations;
private final StorageBackend<String, Host> hosts;
private final StorageBackend<String, EgressOnlyInternetGateway> egressOnlyInternetGateways;
// Serialises a launch onto a host against ModifyHosts/ReleaseHosts, so a host cannot be
// released between the launch's availability check and the store of its instance.
private final Object hostLock = new Object();
@@ -514,7 +517,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
requestContextInstance, iamService, volumeBlockDeviceManager,
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>>() {}));
new TypeReference<Map<String, TransitGatewayPeeringAttachment>>() {}),
storageFactory.create("ec2", "ec2-egress-only-internet-gateways.json",
new TypeReference<Map<String, EgressOnlyInternetGateway>>() {}));
}
// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).
@@ -722,11 +727,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
transitGatewayPropagations, transitGatewayRoutes, vpcPeeringConnections,
networkInterfaces, capacityReservations, volumeModifications,
requestContextInstance, iamService, volumeBlockDeviceManager, new InMemoryStorage<>(),
new InMemoryStorage<>());
new InMemoryStorage<>(), new InMemoryStorage<>());
}
// 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.
// The terminal constructor. Dedicated Hosts, transit gateway peering attachments and egress-only
// internet gateways 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,
@@ -763,8 +769,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
IamService iamService,
Ec2VolumeBlockDeviceManager volumeBlockDeviceManager,
StorageBackend<String, Host> hosts,
StorageBackend<String, TransitGatewayPeeringAttachment> transitGatewayPeeringAttachments) {
StorageBackend<String, TransitGatewayPeeringAttachment> transitGatewayPeeringAttachments,
StorageBackend<String, EgressOnlyInternetGateway> egressOnlyInternetGateways) {
this.hosts = hosts;
this.egressOnlyInternetGateways = egressOnlyInternetGateways;
this.transitGatewayPeeringAttachments = transitGatewayPeeringAttachments;
this.iamService = iamService;
this.volumeBlockDeviceManager = volumeBlockDeviceManager;
@@ -4788,11 +4796,120 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return List.of();
}
// ─── Egress-only Internet Gateways ─────────────────────────────────────────
// Created already attached: AWS has no attach/detach call for this gateway, the VPC is fixed at creation.
// ClientToken replays return the gateway the first call made, unchanged; a reused token with
// another VpcId or other creation tags fails with IdempotentParameterMismatch, as the EC2
// idempotency guide documents. Tags are applied here, with the gateway, so a replay never re-tags.
public EgressOnlyInternetGateway createEgressOnlyInternetGateway(String region, String vpcId,
String clientToken, List<Tag> tagList) {
ensureDefaultResources(region);
if (vpcId == null || vpcId.isBlank()) {
throw new AwsException("MissingParameter",
"The request must contain the parameter vpcId", 400);
}
String token = clientToken != null && !clientToken.isBlank() ? clientToken : null;
synchronized (attachmentTopologyLock(region)) {
if (token != null) {
for (EgressOnlyInternetGateway existing : egressOnlyInternetGateways.scan(
k -> k.startsWith(region + "::"))) {
if (token.equals(existing.getClientToken())) {
if (!vpcId.equals(existing.getAttachments().get(0).getVpcId())
|| !tagMap(tagList).equals(tagMap(existing.getCreationTags()))) {
throw new AwsException("IdempotentParameterMismatch",
"The client token '" + token + "' was already used with different parameters", 400);
}
return existing;
}
}
}
getRequiredVpc(region, vpcId);
EgressOnlyInternetGateway eigw = new EgressOnlyInternetGateway();
eigw.setEgressOnlyInternetGatewayId("eigw-" + randomHex(17));
eigw.setRegion(region);
eigw.setClientToken(token);
eigw.getAttachments().add(new InternetGatewayAttachment(vpcId, "attached"));
eigw.setCreationTags(new ArrayList<>(tagList));
eigw.setTags(new ArrayList<>(tagList));
if (!tagList.isEmpty()) {
tags.put(eigw.getEgressOnlyInternetGatewayId(), new ArrayList<>(tagList));
}
egressOnlyInternetGateways.put(key(region, eigw.getEgressOnlyInternetGatewayId()), eigw);
return eigw;
}
}
// AWS answers an unknown egress-only gateway ID with an empty set, not an error; callers such as
// the Terraform provider treat the empty result as "not found".
public List<String> describeEgressOnlyInternetGatewayIds(Map<String, List<String>> filters) {
public List<EgressOnlyInternetGateway> describeEgressOnlyInternetGateways(String region, List<String> ids,
Map<String, List<String>> filters) {
requireSupportedFilters(filters.keySet(), EGRESS_ONLY_INTERNET_GATEWAY_FILTERS);
return List.of();
return egressOnlyInternetGateways.scan(k -> k.startsWith(region + "::")).stream()
.filter(eigw -> ids.isEmpty() || ids.contains(eigw.getEgressOnlyInternetGatewayId()))
.filter(eigw -> matchesFilters(eigw, filters, region))
.sorted(Comparator.comparing(EgressOnlyInternetGateway::getEgressOnlyInternetGatewayId))
.collect(Collectors.toList());
}
/**
* The paginated form. MaxResults is 5 to 255 in the EC2 model; null means the request left it
* out and gets every match in one page.
*/
public EgressOnlyInternetGatewayListResult describeEgressOnlyInternetGateways(
String region, List<String> ids, Map<String, List<String>> filters, Integer maxResults,
String nextToken) {
if (maxResults != null && (maxResults < 5 || maxResults > 255)) {
throw new AwsException("InvalidMaxResults",
"Value (" + maxResults + ") for parameter MaxResults is invalid. "
+ "Expecting a value between 5 and 255.", 400);
}
int offset = decodeToken(nextToken);
List<EgressOnlyInternetGateway> all = describeEgressOnlyInternetGateways(region, ids, filters);
int total = all.size();
int toIndex = maxResults != null ? Math.min(offset + maxResults, total) : total;
List<EgressOnlyInternetGateway> page = offset < total
? new ArrayList<>(all.subList(offset, toIndex))
: new ArrayList<>();
return new EgressOnlyInternetGatewayListResult(page, toIndex < total ? encodeToken(toIndex) : null);
}
private static Map<String, String> tagMap(List<Tag> tagList) {
Map<String, String> map = new HashMap<>();
for (Tag tag : tagList == null ? List.<Tag>of() : tagList) {
map.put(tag.getKey(), tag.getValue());
}
return map;
}
// Under the gateway's resource lock, the one createSystemTags takes, so a concurrent tag write
// cannot put the gateway back after it is gone. A route that targeted the gateway stays in its
// table as a blackhole: AWS documents that state for a route whose target is no longer available.
public void deleteEgressOnlyInternetGateway(String region, String eigwId) {
synchronized (lockFor(key(region, eigwId))) {
if (egressOnlyInternetGateways.get(key(region, eigwId)).isEmpty()) {
throw new AwsException("InvalidGatewayID.NotFound",
"The eigw ID '" + eigwId + "' does not exist", 400);
}
egressOnlyInternetGateways.delete(key(region, eigwId));
tags.delete(eigwId);
}
for (RouteTable table : routeTables.scan(k -> k.startsWith(region + "::"))) {
if (table.getRoutes().stream().noneMatch(r -> eigwId.equals(r.getEgressOnlyInternetGatewayId()))) {
continue;
}
synchronized (lockFor(key(region, table.getRouteTableId()))) {
RouteTable current = routeTables.get(key(region, table.getRouteTableId())).orElse(null);
if (current == null) {
continue;
}
current.getRoutes().stream()
.filter(r -> eigwId.equals(r.getEgressOnlyInternetGatewayId()))
.forEach(r -> r.setState("blackhole"));
routeTables.put(key(region, current.getRouteTableId()), current);
notifyRouteTableUpdated(region, current);
}
}
}
private void requireSupportedFilters(Collection<String> filterNames, Set<String> supportedFilters) {
@@ -4847,6 +4964,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|| internetGateways.scan(k -> k.startsWith(region + "::")).stream()
.anyMatch(igw -> igw.getAttachments().stream()
.anyMatch(attachment -> vpcId.equals(attachment.getVpcId())))
|| egressOnlyInternetGateways.scan(k -> k.startsWith(region + "::")).stream()
.anyMatch(eigw -> eigw.getAttachments().stream()
.anyMatch(attachment -> vpcId.equals(attachment.getVpcId())))
|| vpcEndpoints.scan(k -> k.startsWith(region + "::")).stream()
.anyMatch(endpoint -> vpcId.equals(endpoint.getVpcId()));
if (hasDependents) {
@@ -8091,6 +8211,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (sgRule != null) { sgRule.setTags(new ArrayList<>(tagList)); securityGroupRules.put(storeKey, sgRule); return; }
InternetGateway igw = internetGateways.get(storeKey).orElse(null);
if (igw != null) { igw.setTags(new ArrayList<>(tagList)); internetGateways.put(storeKey, igw); return; }
EgressOnlyInternetGateway eigw = egressOnlyInternetGateways.get(storeKey).orElse(null);
if (eigw != null) {
eigw.setTags(new ArrayList<>(tagList));
egressOnlyInternetGateways.put(storeKey, eigw);
return;
}
RouteTable rt = routeTables.get(storeKey).orElse(null);
if (rt != null) { rt.setTags(new ArrayList<>(tagList)); routeTables.put(storeKey, rt); return; }
KeyPair kp = keyPairs.get(storeKey).orElse(null);
@@ -8232,6 +8358,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (resourceId.startsWith("igw-")) {
return "internet-gateway";
}
if (resourceId.startsWith("eigw-")) {
return "egress-only-internet-gateway";
}
if (resourceId.startsWith("rtb-")) {
return "route-table";
}
@@ -10282,6 +10411,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
default -> true;
};
}
if (resource instanceof EgressOnlyInternetGateway eigw) {
return switch (filterName) {
case "egress-only-internet-gateway-id" -> matchesValue(values, eigw.getEgressOnlyInternetGatewayId());
case "attachment.vpc-id" -> eigw.getAttachments().stream()
.anyMatch(a -> matchesValue(values, a.getVpcId()));
case "attachment.state" -> eigw.getAttachments().stream()
.anyMatch(a -> matchesValue(values, a.getState()));
default -> true;
};
}
if (resource instanceof RouteTable rt) {
return switch (filterName) {
case "route-table-id" -> matchesValue(values, rt.getRouteTableId());
@@ -10471,6 +10610,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (resource instanceof Subnet subnet) return subnet.getTags();
if (resource instanceof SecurityGroup sg) return sg.getTags();
if (resource instanceof InternetGateway igw) return igw.getTags();
if (resource instanceof EgressOnlyInternetGateway eigw) return eigw.getTags();
if (resource instanceof RouteTable rt) return rt.getTags();
if (resource instanceof KeyPair kp) return kp.getTags();
if (resource instanceof Address addr) return addr.getTags();
@@ -0,0 +1,43 @@
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 EgressOnlyInternetGateway {
private String egressOnlyInternetGatewayId;
private String region;
private String clientToken;
private List<InternetGatewayAttachment> attachments = new ArrayList<>();
private List<Tag> tags = new ArrayList<>();
// The tags the create request carried, kept apart from later tag changes so a ClientToken
// replay is compared with the original request rather than the gateway's current tags.
private List<Tag> creationTags = new ArrayList<>();
public EgressOnlyInternetGateway() {}
public String getEgressOnlyInternetGatewayId() { return egressOnlyInternetGatewayId; }
public void setEgressOnlyInternetGatewayId(String egressOnlyInternetGatewayId) {
this.egressOnlyInternetGatewayId = egressOnlyInternetGatewayId;
}
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public String getClientToken() { return clientToken; }
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
public List<InternetGatewayAttachment> getAttachments() { return attachments; }
public void setAttachments(List<InternetGatewayAttachment> attachments) { this.attachments = attachments; }
public List<Tag> getTags() { return tags; }
public void setTags(List<Tag> tags) { this.tags = tags; }
public List<Tag> getCreationTags() { return creationTags; }
public void setCreationTags(List<Tag> creationTags) { this.creationTags = creationTags; }
}
@@ -0,0 +1,12 @@
package io.github.hectorvent.floci.services.ec2.model;
import java.util.List;
/**
* One page of {@code DescribeEgressOnlyInternetGateways}, with the cursor for the next page or
* {@code null} when there is none.
*/
public record EgressOnlyInternetGatewayListResult(
List<EgressOnlyInternetGateway> egressOnlyInternetGateways,
String nextToken
) {}