fix(ec2): report NAT gateways as zonal and honor PrivateIpAddress (#7059)

* fix(ec2): report NAT gateways as zonal and honor PrivateIpAddress

The Terraform AWS provider reads network_interface_id, private_ip and
public_ip from a NAT gateway only when it is reported with
availabilityMode zonal. Floci never sent availabilityMode, so all three
stayed null. Every gateway Floci creates sits in one subnet, so the
responses now say zonal.

Floci has no regional NAT gateways. A regional request that named only
its VPC failed on the missing subnet, and one that also named a subnet
got a zonal gateway, through both CreateNatGateway and
AWS::EC2::NatGateway. Both now refuse AvailabilityMode regional with
UnsupportedOperation. Any other value except zonal, such as Regional,
fails with InvalidParameterValue instead of creating a zonal gateway.

Once Terraform reads private_ip back, the gateway has to hold the
address it was asked for. private_ip forces a new gateway, and
CreateNatGateway ignored PrivateIpAddress, so a config that set it
would plan a replacement on every run. CreateNatGateway and
AWS::EC2::NatGateway now give the gateway's interface the requested
address, checked by the same rules as RunInstances: inside the subnet,
not reserved and not in use. A changed PrivateIpAddress replaces the
CloudFormation resource, as it is createOnly. A gateway has its primary
address only, so SecondaryAllocationIds, SecondaryPrivateIpAddresses
and SecondaryPrivateIpAddressCount are refused with
UnsupportedOperation instead of being dropped.

AWS::EC2::NatGateway also sets EniId, the gateway's primary interface,
which Fn::GetAtt resolved to the literal "Nat.EniId" although the
gateway has had a real interface since #5622.

Closes #6767

* fix(ec2): take no VPC network lease for a NAT gateway's requested address

DeleteNatGateway never returns a lease, so the one CreateNatGateway took
for its PrivateIpAddress kept the address from automatic allocation
after the gateway was gone. Check that the address is free the way
CreateNetworkInterface does, without the lease; automatic allocation
already steps around addresses a stored NAT gateway holds.

Ec2NatGatewayAddressIntegrationTest now sends its requests through the
shared Ec2Requests.ec2 instead of its own copy.
This commit is contained in:
Suja Shaj authored and GitHub committed 2026-10-31 05:32:32 -04:00
1 parent 2ad35bba1d
commit dcf8ec7430
13 files changed
+519 -244

No files matched your search

@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.ec2.model.Address;
import io.github.hectorvent.floci.services.ec2.model.InternetGateway;
import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;
import io.github.hectorvent.floci.services.ec2.model.NatGateway;
import io.github.hectorvent.floci.services.ec2.model.NatGatewayAddress;
import io.github.hectorvent.floci.services.ec2.model.PrefixListEntry;
import io.github.hectorvent.floci.services.ec2.model.Route;
import io.github.hectorvent.floci.services.ec2.model.RouteTable;
@@ -374,6 +375,15 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
.findFirst().orElse(null), "NatGatewayNotFound", natGatewayId);
}
/** Whether the gateway's primary address is {@code privateIpAddress}, both in canonical form. */
private static boolean holdsPrivateIp(NatGateway nat, String privateIpAddress) {
return nat.getNatGatewayAddresses().stream()
.filter(NatGatewayAddress::isPrimary)
.map(NatGatewayAddress::getPrivateIp)
.filter(Objects::nonNull)
.anyMatch(ip -> CidrCanonicalizer.sameBlock(ip + "/32", privateIpAddress + "/32"));
}
private ManagedPrefixList findPrefixList(String prefixListId, String region) {
return tolerateNotFound(() -> ec2Service.describeManagedPrefixLists(region, List.of(prefixListId), Map.of())
.stream().findFirst().orElse(null), "InvalidPrefixListID.NotFound", prefixListId);
@@ -587,8 +597,13 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
}
private void provisionNatGateway(StackResource r, JsonNode props, ProvisionContext ctx) {
Ec2Service.requireZonalNatGateway(ctx.resolveOptional(props, "AvailabilityMode"));
Ec2Service.requireNoSecondaryNatGatewayAddresses(ctx.resolveStringList(props, "SecondaryAllocationIds"),
ctx.resolveStringList(props, "SecondaryPrivateIpAddresses"),
ctx.resolveOptional(props, "SecondaryPrivateIpAddressCount"));
String subnetId = ctx.resolveOptional(props, "SubnetId");
String allocationId = ctx.resolveOptional(props, "AllocationId");
String privateIpAddress = ctx.resolveOrDefault(props, "PrivateIpAddress", null);
require(NAT_GATEWAY, "SubnetId", subnetId);
// ConnectivityType defaults to public in the schema; a public gateway needs an EIP, a
// private one must not have one, as AWS validates.
@@ -600,14 +615,17 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
if ("private".equals(connectivityType) && allocationId != null && !allocationId.isBlank()) {
throw new AwsException("ValidationError", "AWS::EC2::NatGateway with ConnectivityType private cannot have an AllocationId", 400);
}
// SubnetId, AllocationId and ConnectivityType are createOnly: the same triple keeps the
// gateway, a change replaces it.
// SubnetId, AllocationId, ConnectivityType and PrivateIpAddress are createOnly: the same
// values keep the gateway, a change replaces it. With no PrivateIpAddress the gateway keeps
// the address it was given.
NatGateway existing = ctx.isUpdate() ? findNatGateway(ctx.priorPhysicalId(), ctx.region()) : null;
boolean reuse = existing != null && Objects.equals(subnetId, existing.getSubnetId())
&& Objects.equals(allocationId, existing.getAllocationId())
&& connectivityType.equalsIgnoreCase(existing.getConnectivityType() == null ? "public" : existing.getConnectivityType());
&& connectivityType.equalsIgnoreCase(existing.getConnectivityType() == null ? "public" : existing.getConnectivityType())
&& (privateIpAddress == null || holdsPrivateIp(existing, privateIpAddress));
NatGateway nat = reuse ? existing
: ec2Service.createNatGateway(ctx.region(), subnetId, allocationId, connectivityType, tagList(props, ctx));
: ec2Service.createNatGateway(ctx.region(), subnetId, allocationId, connectivityType, privateIpAddress,
tagList(props, ctx));
if ("failed".equals(nat.getState())) {
// The resource fails and its failed gateway is not left behind.
ec2Service.deleteNatGateway(ctx.region(), nat.getNatGatewayId());
@@ -618,6 +636,12 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
}
r.setPhysicalId(nat.getNatGatewayId());
r.getAttributes().put("NatGatewayId", nat.getNatGatewayId());
nat.getNatGatewayAddresses().stream()
.filter(NatGatewayAddress::isPrimary)
.map(NatGatewayAddress::getNetworkInterfaceId)
.filter(Objects::nonNull)
.findFirst()
.ifPresent(eniId -> r.getAttributes().put("EniId", eniId));
// The gateway holds its subnet and Elastic IP until it is deleted; an EIP's physical id is
// its public IP.
if (nat.getSubnetId() != null) {
@@ -4451,11 +4451,15 @@ public class Ec2QueryHandler {
// ─── NAT Gateway handlers ─────────────────────────────────────────────────
private Response handleCreateNatGateway(MultivaluedMap<String, String> p, String region) {
Ec2Service.requireZonalNatGateway(p.getFirst("AvailabilityMode"));
Ec2Service.requireNoSecondaryNatGatewayAddresses(getList(p, "SecondaryAllocationId"),
getList(p, "SecondaryPrivateIpAddress"), p.getFirst("SecondaryPrivateIpAddressCount"));
NatGateway natGateway = service.createNatGateway(
region,
p.getFirst("SubnetId"),
p.getFirst("AllocationId"),
p.getFirst("ConnectivityType"),
p.getFirst("PrivateIpAddress"),
parseTagsForResource(p, "natgateway"));
XmlBuilder xml = new XmlBuilder()
.start("CreateNatGatewayResponse", AwsNamespaces.EC2)
@@ -5614,7 +5618,10 @@ public class Ec2QueryHandler {
.elem("state", natGateway.getState())
.elem("failureCode", natGateway.getFailureCode())
.elem("failureMessage", natGateway.getFailureMessage())
.elem("connectivityType", natGateway.getConnectivityType());
.elem("connectivityType", natGateway.getConnectivityType())
// Every gateway Floci creates sits in one subnet. The Terraform AWS provider reads
// network_interface_id, private_ip and public_ip only from a gateway reported as zonal.
.elem("availabilityMode", "zonal");
if (natGateway.getCreateTime() != null) {
xml.elem("createTime", ISO_FMT.format(natGateway.getCreateTime()));
}
@@ -4669,10 +4669,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
/**
* The in-use half of {@link #claimRequestedPrivateIp}, without the lease. CreateNetworkInterface
* uses it alone: an interface has no container to hold the address on the VPC network, and
* DeleteNetworkInterface returns no lease, so one taken here would keep the address from
* automatic allocation after the interface is gone. {@link #assignPrivateIp} already steps
* around addresses stored interfaces hold. Callers must hold {@link #privateIpAllocationLock}.
* and CreateNatGateway use it alone: neither an interface nor a NAT gateway has a container to
* hold the address on the VPC network, and DeleteNetworkInterface and DeleteNatGateway return
* no lease, so one taken here would keep the address from automatic allocation after its
* holder is gone. {@link #assignPrivateIp} already steps around addresses stored interfaces and
* NAT gateways hold. Callers must hold {@link #privateIpAllocationLock}.
*
* @return whether the address lies in a Docker-backed range, where a lease could be taken
*/
@@ -12308,8 +12309,49 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// ─── NAT Gateways ─────────────────────────────────────────────────────────
/**
* Refuses a regional NAT gateway, which spans its VPC instead of sitting in one subnet. Floci
* creates only zonal gateways, so it refuses the request before looking at the subnet, which a
* regional request does not name. A value that is neither mode fails as AWS fails it, rather
* than creating a zonal gateway.
*/
public static void requireZonalNatGateway(String availabilityMode) {
requireParameterValue("AvailabilityMode", isSet(availabilityMode) ? availabilityMode : null,
"zonal", "regional");
if ("regional".equals(availabilityMode)) {
throw new AwsException("UnsupportedOperation",
"NAT gateways with AvailabilityMode regional are not supported.", 400);
}
}
/**
* Refuses the secondary-address parameters. Floci gives a NAT gateway its primary address only,
* so a gateway created with them would report fewer addresses than it was asked for.
*/
public static void requireNoSecondaryNatGatewayAddresses(List<String> secondaryAllocationIds,
List<String> secondaryPrivateIpAddresses,
String secondaryPrivateIpAddressCount) {
if (!secondaryAllocationIds.isEmpty() || !secondaryPrivateIpAddresses.isEmpty()
|| isSet(secondaryPrivateIpAddressCount)) {
throw new AwsException("UnsupportedOperation",
"NAT gateways with secondary addresses are not supported.", 400);
}
}
public NatGateway createNatGateway(String region, String subnetId, String allocationId,
String connectivityType, List<Tag> natGatewayTags) {
return createNatGateway(region, subnetId, allocationId, connectivityType, null, natGatewayTags);
}
/**
* @param privateIpAddress PrivateIpAddress: the private address of the gateway's interface, or
* null to let the subnet pick one. It is checked as RunInstances checks
* its own: an assignable address of the subnet that no other resource
* holds.
*/
public NatGateway createNatGateway(String region, String subnetId, String allocationId,
String connectivityType, String privateIpAddress,
List<Tag> natGatewayTags) {
ensureDefaultResources(region);
Subnet subnet = requireSubnet(region, subnetId);
boolean privateGateway = "private".equalsIgnoreCase(connectivityType);
@@ -12323,6 +12365,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (isSet(allocationId)) {
getRequiredAddress(region, allocationId);
}
String requestedPrivateIp = isSet(privateIpAddress)
? validateRequestedPrivateIp(privateIpAddress, subnet, null, 1) : null;
NatGateway natGateway = new NatGateway();
natGateway.setNatGatewayId("nat-" + randomHex(17));
@@ -12348,8 +12392,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
if (!"failed".equals(natGateway.getState())) {
NatGatewayAddress gatewayAddress =
natGatewayAddress(region, natGateway.getNatGatewayId(), subnetId, allocationId);
NatGatewayAddress gatewayAddress = natGatewayAddress(region, natGateway.getNatGatewayId(),
subnetId, allocationId, requestedPrivateIp);
natGateway.getNatGatewayAddresses().add(gatewayAddress);
// The Elastic IP is now held by the gateway's interface, so DescribeAddresses has to
// say so: an allocation that looks free is one Terraform and the console would offer
@@ -12378,12 +12422,22 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
* aws_nat_gateway exposes all three as resource outputs (public_ip, private_ip,
* network_interface_id), and Gruntwork's VPC modules re-export nat_gateway_public_ips, so an
* address carrying only an allocation id propagates empty values into dependent modules.
* Callers must hold {@link #privateIpAllocationLock}.
*
* @param requestedPrivateIp the request's PrivateIpAddress, already checked by
* {@link #validateRequestedPrivateIp}, or null. It takes no lease on
* the VPC network (see {@link #requireRequestedPrivateIpFree}).
*/
private NatGatewayAddress natGatewayAddress(String region, String natGatewayId, String subnetId,
String allocationId) {
String allocationId, String requestedPrivateIp) {
NatGatewayAddress address = new NatGatewayAddress();
address.setNetworkInterfaceId(eniIdFromSeed("nat|" + natGatewayId));
address.setPrivateIp(assignPrivateIp(region, subnetId));
if (requestedPrivateIp != null) {
requireRequestedPrivateIpFree(region, subnetId, requestedPrivateIp);
address.setPrivateIp(requestedPrivateIp);
} else {
address.setPrivateIp(assignPrivateIp(region, subnetId));
}
if (isSet(allocationId)) {
address.setAllocationId(allocationId);
address.setAssociationId("eipassoc-" + randomHex(17));