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

@@ -0,0 +1,93 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.AllocateAddressRequest;
import software.amazon.awssdk.services.ec2.model.AllocateAddressResponse;
import software.amazon.awssdk.services.ec2.model.AvailabilityMode;
import software.amazon.awssdk.services.ec2.model.ConnectivityType;
import software.amazon.awssdk.services.ec2.model.CreateNatGatewayRequest;
import software.amazon.awssdk.services.ec2.model.DeleteNatGatewayRequest;
import software.amazon.awssdk.services.ec2.model.DescribeNatGatewaysRequest;
import software.amazon.awssdk.services.ec2.model.DomainType;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.NatGateway;
import software.amazon.awssdk.services.ec2.model.NatGatewayAddress;
import software.amazon.awssdk.services.ec2.model.ReleaseAddressRequest;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
class Ec2NatGatewayTest {
@Test
@DisplayName("CreateNatGateway and DescribeNatGateways report a zonal gateway with its primary address")
void natGatewayIsZonalWithItsPrimaryAddress() {
// The Terraform AWS provider reads network_interface_id, private_ip and public_ip only from
// a gateway whose AvailabilityMode is zonal, so an unset mode leaves all three null.
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
String subnetId = TestFixtures.defaultVpcSubnets().get(0);
AllocateAddressResponse address = ec2.allocateAddress(AllocateAddressRequest.builder()
.domain(DomainType.VPC)
.build());
String natGatewayId = null;
try {
NatGateway created = ec2.createNatGateway(CreateNatGatewayRequest.builder()
.subnetId(subnetId)
.allocationId(address.allocationId())
.build())
.natGateway();
natGatewayId = created.natGatewayId();
assertThat(created.availabilityMode()).isEqualTo(AvailabilityMode.ZONAL);
NatGateway described = ec2.describeNatGateways(DescribeNatGatewaysRequest.builder()
.natGatewayIds(natGatewayId)
.build())
.natGateways().get(0);
assertThat(described.availabilityMode()).isEqualTo(AvailabilityMode.ZONAL);
assertThat(described.natGatewayAddresses()).hasSize(1);
NatGatewayAddress primary = described.natGatewayAddresses().get(0);
assertThat(primary.isPrimary()).isTrue();
assertThat(primary.networkInterfaceId()).startsWith("eni-");
assertThat(primary.privateIp()).isNotBlank();
assertThat(primary.publicIp()).isEqualTo(address.publicIp());
} finally {
if (natGatewayId != null) {
ec2.deleteNatGateway(DeleteNatGatewayRequest.builder().natGatewayId(natGatewayId).build());
}
ec2.releaseAddress(ReleaseAddressRequest.builder().allocationId(address.allocationId()).build());
}
}
}
@Test
@DisplayName("CreateNatGateway refuses secondary addresses rather than creating a gateway without them")
void secondaryAddressesAreRefused() {
// SecondaryAllocationId.N and SecondaryPrivateIpAddress.N are the list names the SDK sends.
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
String subnetId = TestFixtures.defaultVpcSubnets().get(0);
for (CreateNatGatewayRequest request : List.of(
CreateNatGatewayRequest.builder()
.subnetId(subnetId)
.allocationId("eipalloc-0123456789abcdef0")
.secondaryAllocationIds("eipalloc-0fedcba9876543210")
.build(),
CreateNatGatewayRequest.builder()
.subnetId(subnetId)
.connectivityType(ConnectivityType.PRIVATE)
.secondaryPrivateIpAddresses("172.31.0.200")
.build(),
CreateNatGatewayRequest.builder()
.subnetId(subnetId)
.connectivityType(ConnectivityType.PRIVATE)
.secondaryPrivateIpAddressCount(2)
.build())) {
Ec2Exception error = assertThrows(Ec2Exception.class, () -> ec2.createNatGateway(request));
assertThat(error.awsErrorDetails().errorCode()).isEqualTo("UnsupportedOperation");
}
}
}
}
+1 -1
View File
@@ -189,7 +189,7 @@ cross-resource references.
| ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) |
| Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model), `EventSubscription` |
| Redshift Serverless | `Namespace` (Managed admin credentials use Secrets Manager; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) |
| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog`, `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) |
| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway` (zonal, primary address only; `AvailabilityMode` regional and the `Secondary*` address properties fail), `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog`, `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) |
| Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` |
| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` |
| Application Auto Scaling | `ScalableTarget` (`ScheduledActions` are accepted and not run; Floci has no scheduled scaling), `ScalingPolicy` |
+15
View File
@@ -749,6 +749,21 @@ Route table ids follow the live API's own inconsistency: an id that does not exi
| DescribeNatGateways | Lists or returns stored NAT gateways. |
| DeleteNatGateway | Deletes a NAT gateway record. |
Every NAT gateway Floci creates is zonal: it sits in the subnet it was created in, and responses
report `availabilityMode` as `zonal`. Regional NAT gateways are not supported: `CreateNatGateway` with
`AvailabilityMode=regional` fails with `UnsupportedOperation`, and an `AWS::EC2::NatGateway` whose
`AvailabilityMode` is `regional` fails with the reason `NAT gateways with AvailabilityMode regional
are not supported.`
`PrivateIpAddress` gives the gateway's interface that address instead of the next free one, on
`CreateNatGateway` and on `AWS::EC2::NatGateway`, and `DescribeNetworkInterfaces` and
`DescribeAddresses` report the same address. It follows the `RunInstances` rules: an address outside
the subnet's CIDR, or one of the five AWS reserves, fails with `InvalidParameterValue`, and one that
an instance, network interface, NAT gateway or interface endpoint already holds fails with
`InvalidIPAddress.InUse`. A gateway has its primary address only, so the secondary-address
parameters (`SecondaryAllocationIds`, `SecondaryPrivateIpAddresses` and
`SecondaryPrivateIpAddressCount`) fail with `UnsupportedOperation` before anything is created.
### Capacity Reservations
| Action | Description |
@@ -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));
@@ -380,7 +380,8 @@ class CloudFormationEc2NetworkingIntegrationTest {
"AssocId": {"Value": {"Ref": "PublicAssoc"}},
"EipRef": {"Value": {"Ref": "NatEip"}},
"EipAllocationId": {"Value": {"Fn::GetAtt": ["NatEip", "AllocationId"]}},
"NatId": {"Value": {"Ref": "Nat"}}
"NatId": {"Value": {"Ref": "Nat"}},
"NatEniId": {"Value": {"Fn::GetAtt": ["Nat", "EniId"]}}
}
}
""".formatted(vpcId, publicSubnetCidr, extraSubnetTag);
@@ -411,6 +412,7 @@ class CloudFormationEc2NetworkingIntegrationTest {
assertTrue(out.get("EipAllocationId").startsWith("eipalloc-"), out.get("EipAllocationId"));
assertFalse(out.get("EipRef").startsWith("eipalloc-"), "Ref of an EIP is its public IP: " + out.get("EipRef"));
assertTrue(out.get("NatId").startsWith("nat-"), out.get("NatId"));
assertTrue(out.get("NatEniId").startsWith("eni-"), out.get("NatEniId"));
String subnets = ec2("DescribeSubnets");
assertTrue(subnets.contains(out.get("SubnetId")));
@@ -419,7 +421,10 @@ class CloudFormationEc2NetworkingIntegrationTest {
assertTrue(routeTables.contains("<value>public-rt</value>"), "route table tags must reach EC2");
assertTrue(routeTables.contains(out.get("PublicRtId")) && routeTables.contains(out.get("AssocId")));
assertTrue(routeTables.contains(out.get("NatId")), "the private route must point at the NAT gateway");
assertTrue(ec2("DescribeNatGateways").contains(out.get("NatId")));
String natGateways = ec2("DescribeNatGateways");
assertTrue(natGateways.contains(out.get("NatId")));
assertTrue(natGateways.contains("<networkInterfaceId>" + out.get("NatEniId") + "</networkInterfaceId>"),
"EniId must be the gateway's own interface");
assertTrue(ec2("DescribeAddresses").contains(out.get("EipAllocationId")));
assertTrue(ec2("DescribeInternetGateways").contains(out.get("IgwId")));
@@ -452,6 +457,10 @@ class CloudFormationEc2NetworkingIntegrationTest {
Map<String, String> replaced = XmlParser.extractPairs(describeStacks("UPDATE_COMPLETE"), "Outputs", "OutputKey", "OutputValue");
assertFalse(out.get("SubnetId").equals(replaced.get("SubnetId")), "a changed CIDR must replace the subnet");
assertFalse(out.get("NatId").equals(replaced.get("NatId")), "the NAT gateway follows its subnet");
assertFalse(out.get("NatEniId").equals(replaced.get("NatEniId")), "EniId must not be the displaced gateway's");
assertTrue(ec2("DescribeNatGateways", Map.of("NatGatewayId.1", replaced.get("NatId")))
.contains("<networkInterfaceId>" + replaced.get("NatEniId") + "</networkInterfaceId>"),
"EniId must be the replacement gateway's own interface");
assertFalse(out.get("AssocId").equals(replaced.get("AssocId")), "the association follows its subnet");
assertEquals(out.get("IgwId"), replaced.get("IgwId"));
assertFalse(out.get("EipAllocationId").equals(replaced.get("EipAllocationId")), "the gateway takes the new EIP");
@@ -12,6 +12,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;
@@ -99,6 +100,22 @@ class Ec2NetworkCfnProvisionerTest {
return r;
}
private static NatGateway natGateway(String natGatewayId) {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(natGatewayId);
return nat;
}
/** A gateway with the one primary address CreateNatGateway gives it. */
private static NatGateway natGateway(String natGatewayId, String eniId, String privateIp) {
NatGateway nat = natGateway(natGatewayId);
NatGatewayAddress primary = new NatGatewayAddress();
primary.setNetworkInterfaceId(eniId);
primary.setPrivateIp(privateIp);
nat.getNatGatewayAddresses().add(primary);
return nat;
}
private static Subnet subnet() {
Subnet s = new Subnet();
s.setSubnetId(SUBNET_ID);
@@ -201,16 +218,16 @@ class Ec2NetworkCfnProvisionerTest {
@Test
void natGatewayIsCreatedPublicWithNoTags() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", List.of())).thenReturn(nat);
NatGateway nat = natGateway(NAT_ID, "eni-0123456789abcdef0", "10.0.1.10");
when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", null, List.of())).thenReturn(nat);
StackResource r = resource("AWS::EC2::NatGateway", "Nat");
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), ctx());
assertEquals(NAT_ID, r.getPhysicalId());
assertEquals(Set.of("NatGatewayId"), r.getAttributes().keySet().stream()
assertEquals(Set.of("NatGatewayId", "EniId"), r.getAttributes().keySet().stream()
.filter(key -> !key.startsWith("__Floci")).collect(Collectors.toSet()));
assertEquals("eni-0123456789abcdef0", r.getAttributes().get("EniId"));
}
/**
@@ -219,10 +236,9 @@ class Ec2NetworkCfnProvisionerTest {
*/
@Test
void natGatewayRecordsTheSubnetAndElasticIpItUsesUnderHiddenKeys() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
NatGateway nat = natGateway(NAT_ID);
nat.setSubnetId(SUBNET_ID);
when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", List.of())).thenReturn(nat);
when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", null, List.of())).thenReturn(nat);
Address addr = new Address();
addr.setAllocationId(ALLOC_ID);
addr.setPublicIp(PUBLIC_IP);
@@ -462,19 +478,17 @@ class Ec2NetworkCfnProvisionerTest {
@Test
void aNatGatewayWithTheSameSubnetAndAllocationIsKeptAndAChangedSubnetReplacesIt() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
NatGateway nat = natGateway(NAT_ID);
nat.setSubnetId(SUBNET_ID);
nat.setAllocationId(ALLOC_ID);
when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat));
StackResource same = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
provisioner.provision(same, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), ctx(NAT_ID));
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any());
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any());
assertEquals(NAT_ID, same.getPhysicalId());
NatGateway replacement = new NatGateway();
replacement.setNatGatewayId("nat-replacement");
when(ec2.createNatGateway(REGION, "subnet-other", ALLOC_ID, "public", List.of())).thenReturn(replacement);
NatGateway replacement = natGateway("nat-replacement");
when(ec2.createNatGateway(REGION, "subnet-other", ALLOC_ID, "public", null, List.of())).thenReturn(replacement);
StackResource moved = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
provisioner.provision(moved, mapper.createObjectNode().put("SubnetId", "subnet-other").put("AllocationId", ALLOC_ID), ctx(NAT_ID));
assertEquals("nat-replacement", moved.getPhysicalId());
@@ -607,9 +621,8 @@ class Ec2NetworkCfnProvisionerTest {
@Test
void aPrivateNatGatewayNeedsNoAllocationAndAPublicOneRequiresIt() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), any())).thenReturn(nat);
NatGateway nat = natGateway(NAT_ID);
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), isNull(), any())).thenReturn(nat);
StackResource r = resource("AWS::EC2::NatGateway", "Nat");
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private"), ctx());
@@ -623,37 +636,113 @@ class Ec2NetworkCfnProvisionerTest {
assertEquals("ValidationError", e2.getErrorCode());
}
@Test
void aRegionalNatGatewayIsRefusedRatherThanCreatedZonal() {
// A regional template names its VPC and no subnet; one that names a subnet as well must not
// quietly get a zonal gateway either.
for (ObjectNode props : List.of(
mapper.createObjectNode().put("AvailabilityMode", "regional").put("VpcId", VPC_ID),
mapper.createObjectNode().put("AvailabilityMode", "regional").put("SubnetId", SUBNET_ID)
.put("AllocationId", ALLOC_ID))) {
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::EC2::NatGateway", "Nat"), props, ctx()));
assertEquals("UnsupportedOperation", e.getErrorCode());
}
// The schema's enum is exact-case, so a value that is neither mode is invalid, not zonal.
AwsException invalid = assertThrows(AwsException.class, () -> provisioner.provision(resource("AWS::EC2::NatGateway", "Nat"),
mapper.createObjectNode().put("AvailabilityMode", "Regional").put("SubnetId", SUBNET_ID)
.put("ConnectivityType", "private"), ctx()));
assertEquals("InvalidParameterValue", invalid.getErrorCode());
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any());
}
@Test
void aNatGatewayWithSecondaryAddressesIsRefusedRatherThanCreatedWithoutThem() {
ObjectNode withAllocations = mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID);
withAllocations.putArray("SecondaryAllocationIds").add("eipalloc-0fedcba9876543210");
ObjectNode withAddresses = mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private");
withAddresses.putArray("SecondaryPrivateIpAddresses").add("10.0.1.70");
for (ObjectNode props : List.of(withAllocations, withAddresses,
mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private")
.put("SecondaryPrivateIpAddressCount", 2))) {
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::EC2::NatGateway", "Nat"), props, ctx()));
assertEquals("UnsupportedOperation", e.getErrorCode());
}
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any());
}
@Test
void aNatGatewayIsCreatedWithThePrivateIpAddressTheTemplateNames() {
when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.50", List.of()))
.thenReturn(natGateway(NAT_ID, "eni-0123456789abcdef0", "10.0.1.50"));
StackResource r = resource("AWS::EC2::NatGateway", "Nat");
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private")
.put("PrivateIpAddress", "10.0.1.50"), ctx());
verify(ec2).createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.50", List.of());
assertEquals(NAT_ID, r.getPhysicalId());
}
/**
* PrivateIpAddress is createOnly: the gateway's own address keeps it, in whatever form the
* template writes it, and so does a template that names none. A different address replaces it.
*/
@Test
void aNatGatewayKeepsItsPrivateIpAddressAndAChangedOneReplacesIt() {
NatGateway nat = natGateway(NAT_ID, "eni-0123456789abcdef0", "10.0.1.50");
nat.setSubnetId(SUBNET_ID);
nat.setConnectivityType("private");
when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat));
ObjectNode privateNat = mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private");
for (ObjectNode props : List.of(privateNat.deepCopy().put("PrivateIpAddress", "10.0.1.50"),
privateNat.deepCopy().put("PrivateIpAddress", "10.0.1.050"), privateNat)) {
StackResource kept = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
provisioner.provision(kept, props, ctx(NAT_ID));
assertEquals(NAT_ID, kept.getPhysicalId());
}
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any());
when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.60", List.of()))
.thenReturn(natGateway("nat-replacement", "eni-0fedcba9876543210", "10.0.1.60"));
StackResource moved = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
provisioner.provision(moved, privateNat.deepCopy().put("PrivateIpAddress", "10.0.1.60"), ctx(NAT_ID));
assertEquals("nat-replacement", moved.getPhysicalId());
assertEquals(NAT_ID, provisioner.updateCleanupPhysicalId(moved));
}
@Test
void aNatGatewayWhoseConnectivityTypeChangedIsReplaced() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
NatGateway nat = natGateway(NAT_ID);
nat.setSubnetId(SUBNET_ID);
nat.setAllocationId(ALLOC_ID);
nat.setConnectivityType("public");
when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat));
NatGateway replacement = new NatGateway();
replacement.setNatGatewayId("nat-private");
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), any())).thenReturn(replacement);
StackResource r = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
NatGateway replacement = natGateway("nat-private", "eni-0fedcba9876543210", "10.0.1.11");
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), isNull(), any())).thenReturn(replacement);
StackResource r = prior("AWS::EC2::NatGateway", "Nat", NAT_ID,
Map.of("NatGatewayId", NAT_ID, "EniId", "eni-0123456789abcdef0"));
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private"), ctx(NAT_ID));
assertEquals("nat-private", r.getPhysicalId());
assertEquals(NAT_ID, provisioner.updateCleanupPhysicalId(r));
// The update arrives with the displaced gateway's attributes; its interface goes with it.
assertEquals("eni-0fedcba9876543210", r.getAttributes().get("EniId"));
}
@Test
void natGatewayTagsGoThroughItsCreateCall() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), any())).thenReturn(nat);
NatGateway nat = natGateway(NAT_ID);
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), isNull(), any())).thenReturn(nat);
provisioner.provision(resource("AWS::EC2::NatGateway", "Nat"),
withTags(mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), "Name", "nat"), ctx());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.forClass(List.class);
verify(ec2).createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), tags.capture());
verify(ec2).createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), isNull(), tags.capture());
assertEquals(List.of("Name=nat"), pairs(tags.getValue()));
verify(ec2, never()).createTags(any(), any(), any());
}
@@ -766,7 +855,7 @@ class Ec2NetworkCfnProvisionerTest {
verify(ec2, never()).createRouteTable(any(), any());
verify(ec2, never()).associateRouteTable(any(), any(), any());
verify(ec2, never()).createRoute(any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any());
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any());
}
@Test
@@ -988,8 +1077,7 @@ class Ec2NetworkCfnProvisionerTest {
@Test
void aFailedNatGatewayTagChangePutsThePriorTagsBack() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
NatGateway nat = natGateway(NAT_ID);
nat.setSubnetId(SUBNET_ID);
nat.setAllocationId(ALLOC_ID);
nat.setTags(List.of(new Tag("Name", "old")));
@@ -4,7 +4,10 @@ import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.testing.Ec2Requests.ec2;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesRegex;
@@ -20,47 +23,27 @@ import static org.hamcrest.Matchers.startsWith;
@QuarkusTest
class Ec2NatGatewayAddressIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static final String ACCOUNT_ID = "000000000000";
private static final String REGION = "us-east-1";
private String subnetId() {
String vpcId = given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.94.0.0/16")
.header("Authorization", AUTH_HEADER)
.when().post("/")
String vpcId = ec2("CreateVpc", ACCOUNT_ID, REGION).formParam("CidrBlock", "10.94.0.0/16").post("/")
.then().statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
return given()
.formParam("Action", "CreateSubnet")
.formParam("VpcId", vpcId)
.formParam("CidrBlock", "10.94.1.0/24")
.header("Authorization", AUTH_HEADER)
.when().post("/")
return ec2("CreateSubnet", ACCOUNT_ID, REGION)
.formParam("VpcId", vpcId).formParam("CidrBlock", "10.94.1.0/24").post("/")
.then().statusCode(200)
.extract().path("CreateSubnetResponse.subnet.subnetId");
}
@Test
void aPublicGatewayReportsItsElasticIpPrivateIpAndInterface() {
String subnetId = subnetId();
Response allocation = given()
.formParam("Action", "AllocateAddress")
.formParam("Domain", "vpc")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200).extract().response();
Response allocation = allocation();
String allocationId = allocation.path("AllocateAddressResponse.allocationId");
String publicIp = allocation.path("AllocateAddressResponse.publicIp");
String natGatewayId = given()
.formParam("Action", "CreateNatGateway")
.formParam("SubnetId", subnetId)
.formParam("AllocationId", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then()
String natGatewayId = createNat(allocationId).then()
.statusCode(200)
.body("CreateNatGatewayResponse.natGateway.natGatewayAddressSet.item.allocationId",
equalTo(allocationId))
@@ -74,20 +57,18 @@ class Ec2NatGatewayAddressIntegrationTest {
startsWith("eipassoc-"))
.body("CreateNatGatewayResponse.natGateway.natGatewayAddressSet.item.status",
equalTo("succeeded"))
.body("CreateNatGatewayResponse.natGateway.availabilityMode", equalTo("zonal"))
.extract().path("CreateNatGatewayResponse.natGateway.natGatewayId");
// Describe is the read Terraform refreshes from, so it has to agree, not just Create.
given()
.formParam("Action", "DescribeNatGateways")
.formParam("NatGatewayId.1", natGatewayId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DescribeNatGateways", ACCOUNT_ID, REGION).formParam("NatGatewayId.1", natGatewayId).post("/")
.then()
.statusCode(200)
.body("DescribeNatGatewaysResponse.natGatewaySet.item.natGatewayAddressSet.item.publicIp",
equalTo(publicIp))
.body("DescribeNatGatewaysResponse.natGatewaySet.item.natGatewayAddressSet.item.networkInterfaceId",
startsWith("eni-"));
startsWith("eni-"))
.body("DescribeNatGatewaysResponse.natGatewaySet.item.availabilityMode", equalTo("zonal"));
}
/**
@@ -98,28 +79,14 @@ class Ec2NatGatewayAddressIntegrationTest {
@Test
void aGatewaysInterfaceResolvesAndItsElasticIpReadsAsAssociated() {
String subnetId = subnetId();
String allocationId = given()
.formParam("Action", "AllocateAddress")
.formParam("Domain", "vpc")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.extract().path("AllocateAddressResponse.allocationId");
String allocationId = allocate();
String natGatewayId = given()
.formParam("Action", "CreateNatGateway")
.formParam("SubnetId", subnetId)
.formParam("AllocationId", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
String natGatewayId = createNat(Map.of("SubnetId", subnetId, "AllocationId", allocationId)).then()
.statusCode(200)
.extract().path("CreateNatGatewayResponse.natGateway.natGatewayId");
Response described = given()
.formParam("Action", "DescribeNatGateways")
.formParam("NatGatewayId.1", natGatewayId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
Response described = ec2("DescribeNatGateways", ACCOUNT_ID, REGION)
.formParam("NatGatewayId.1", natGatewayId).post("/")
.then().statusCode(200).extract().response();
String prefix = "DescribeNatGatewaysResponse.natGatewaySet.item.";
String eniId = described.path(prefix + "natGatewayAddressSet.item.networkInterfaceId");
@@ -129,11 +96,7 @@ class Ec2NatGatewayAddressIntegrationTest {
// Twice: the id must be stable, not re-minted per read.
for (int i = 0; i < 2; i++) {
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("NetworkInterfaceId.1", eniId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DescribeNetworkInterfaces", ACCOUNT_ID, REGION).formParam("NetworkInterfaceId.1", eniId).post("/")
.then()
.statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.networkInterfaceId",
@@ -150,38 +113,22 @@ class Ec2NatGatewayAddressIntegrationTest {
+ ".privateIpAddressesSet.item.association.allocationId", equalTo(allocationId));
}
given()
.formParam("Action", "DescribeAddresses")
.formParam("AllocationId.1", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DescribeAddresses", ACCOUNT_ID, REGION).formParam("AllocationId.1", allocationId).post("/")
.then()
.statusCode(200)
.body("DescribeAddressesResponse.addressesSet.item.associationId", equalTo(associationId))
.body("DescribeAddressesResponse.addressesSet.item.networkInterfaceId", equalTo(eniId))
.body("DescribeAddressesResponse.addressesSet.item.privateIpAddress", equalTo(privateIp));
given()
.formParam("Action", "DeleteNatGateway")
.formParam("NatGatewayId", natGatewayId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DeleteNatGateway", ACCOUNT_ID, REGION).formParam("NatGatewayId", natGatewayId).post("/")
.then().statusCode(200);
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("NetworkInterfaceId.1", eniId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DescribeNetworkInterfaces", ACCOUNT_ID, REGION).formParam("NetworkInterfaceId.1", eniId).post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidNetworkInterfaceID.NotFound"));
given()
.formParam("Action", "DescribeAddresses")
.formParam("AllocationId.1", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DescribeAddresses", ACCOUNT_ID, REGION).formParam("AllocationId.1", allocationId).post("/")
.then()
.statusCode(200)
.body("DescribeAddressesResponse.addressesSet.item.allocationId", equalTo(allocationId))
@@ -191,15 +138,10 @@ class Ec2NatGatewayAddressIntegrationTest {
@Test
void aPrivateGatewayHasAPrivateAddressAndNoElasticIp() {
given()
.formParam("Action", "CreateNatGateway")
.formParam("SubnetId", subnetId())
.formParam("ConnectivityType", "private")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then()
createNat(Map.of("SubnetId", subnetId(), "ConnectivityType", "private")).then()
.statusCode(200)
.body("CreateNatGatewayResponse.natGateway.connectivityType", equalTo("private"))
.body("CreateNatGatewayResponse.natGateway.availabilityMode", equalTo("zonal"))
.body("CreateNatGatewayResponse.natGateway.natGatewayAddressSet.item.privateIp",
matchesRegex("10\\.94\\.1\\.\\d+"))
.body("CreateNatGatewayResponse.natGateway.natGatewayAddressSet.item.networkInterfaceId",
@@ -215,43 +157,129 @@ class Ec2NatGatewayAddressIntegrationTest {
*/
@Test
void aPrivateGatewayCannotBeGivenAnElasticIp() {
String allocationId = given()
.formParam("Action", "AllocateAddress")
.formParam("Domain", "vpc")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.extract().path("AllocateAddressResponse.allocationId");
given()
.formParam("Action", "CreateNatGateway")
.formParam("SubnetId", subnetId())
.formParam("ConnectivityType", "private")
.formParam("AllocationId", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then()
createNat(Map.of("SubnetId", subnetId(), "ConnectivityType", "private", "AllocationId", allocate())).then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"));
}
private String allocate() {
return given()
.formParam("Action", "AllocateAddress")
.formParam("Domain", "vpc")
.header("Authorization", AUTH_HEADER)
.when().post("/")
/**
* Every gateway Floci creates is zonal. A regional request names its VPC and no subnet, and
* is refused rather than failing on the missing subnet; one that names a subnet as well is
* refused rather than created as zonal. AWS's enum is exact-case, so a value that is neither
* mode is invalid rather than zonal.
*/
@Test
void aRegionalOrUnknownAvailabilityModeIsRefused() {
createNat(Map.of("AvailabilityMode", "regional", "VpcId", "vpc-0123456789abcdef0")).then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("UnsupportedOperation"));
String subnetId = subnetId();
createNat(Map.of("AvailabilityMode", "regional", "SubnetId", subnetId, "AllocationId", allocate())).then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("UnsupportedOperation"));
createNat(Map.of("AvailabilityMode", "Regional", "SubnetId", subnetId, "ConnectivityType", "private")).then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
assertNatGatewaysIn(subnetId, 0);
createNat(Map.of("AvailabilityMode", "zonal", "SubnetId", subnetId, "ConnectivityType", "private")).then()
.statusCode(200)
.body("CreateNatGatewayResponse.natGateway.availabilityMode", equalTo("zonal"));
}
/**
* PrivateIpAddress is the gateway's address, and every read that reports it has to agree. The
* Terraform AWS provider reads private_ip back, and it forces a new gateway, so a different
* address would replace the gateway on every plan.
*/
@Test
void aRequestedPrivateIpIsTheAddressEveryReadReports() {
String allocationId = allocate();
Response created = createNat(Map.of("SubnetId", subnetId(), "AllocationId", allocationId,
"PrivateIpAddress", "10.94.1.50")).then()
.statusCode(200)
.body("CreateNatGatewayResponse.natGateway.natGatewayAddressSet.item.privateIp", equalTo("10.94.1.50"))
.extract().response();
String natGatewayId = created.path("CreateNatGatewayResponse.natGateway.natGatewayId");
String eniId = created.path("CreateNatGatewayResponse.natGateway.natGatewayAddressSet.item.networkInterfaceId");
ec2("DescribeNatGateways", ACCOUNT_ID, REGION).formParam("NatGatewayId.1", natGatewayId).post("/")
.then().statusCode(200)
.extract().path("AllocateAddressResponse.allocationId");
.body("DescribeNatGatewaysResponse.natGatewaySet.item.natGatewayAddressSet.item.privateIp",
equalTo("10.94.1.50"));
ec2("DescribeNetworkInterfaces", ACCOUNT_ID, REGION).formParam("NetworkInterfaceId.1", eniId).post("/")
.then().statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.privateIpAddress",
equalTo("10.94.1.50"));
ec2("DescribeAddresses", ACCOUNT_ID, REGION).formParam("AllocationId.1", allocationId).post("/")
.then().statusCode(200)
.body("DescribeAddressesResponse.addressesSet.item.privateIpAddress", equalTo("10.94.1.50"));
}
/** The RunInstances rules: an assignable address of the subnet that nothing else holds. */
@Test
void aRequestedPrivateIpOutsideTheSubnetOrInUseIsRefused() {
String subnetId = subnetId();
for (String unassignable : List.of("10.95.1.50", "10.94.1.1")) {
createNat(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "PrivateIpAddress", unassignable))
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
}
assertNatGatewaysIn(subnetId, 0);
Map<String, String> request = Map.of("SubnetId", subnetId, "ConnectivityType", "private",
"PrivateIpAddress", "10.94.1.60");
createNat(request).then().statusCode(200);
createNat(request).then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidIPAddress.InUse"))
.body("Response.Errors.Error.Message", equalTo("Address 10.94.1.60 is in use."));
assertNatGatewaysIn(subnetId, 1);
}
/**
* A gateway gets its primary address only, so the secondary-address parameters are refused
* rather than answered with a gateway that has fewer addresses than it was asked for.
*/
@Test
void theSecondaryAddressParametersAreRefused() {
String subnetId = subnetId();
for (Map<String, String> request : List.of(
Map.of("SubnetId", subnetId, "AllocationId", allocate(), "SecondaryAllocationId.1", allocate()),
Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryPrivateIpAddress.1", "10.94.1.70"),
Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryPrivateIpAddressCount", "2"))) {
createNat(request).then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("UnsupportedOperation"));
}
assertNatGatewaysIn(subnetId, 0);
}
private static Response allocation() {
return ec2("AllocateAddress", ACCOUNT_ID, REGION).formParam("Domain", "vpc").post("/")
.then().statusCode(200).extract().response();
}
private static String allocate() {
return allocation().path("AllocateAddressResponse.allocationId");
}
private Response createNat(String allocationId) {
return given()
.formParam("Action", "CreateNatGateway")
.formParam("SubnetId", subnetId())
.formParam("AllocationId", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/");
return createNat(Map.of("SubnetId", subnetId(), "AllocationId", allocationId));
}
private static Response createNat(Map<String, String> params) {
return ec2("CreateNatGateway", ACCOUNT_ID, REGION).formParams(params).post("/");
}
/** A refused request must not leave a gateway behind in the subnet it named. */
private static void assertNatGatewaysIn(String subnetId, int expected) {
ec2("DescribeNatGateways", ACCOUNT_ID, REGION)
.formParam("Filter.1.Name", "subnet-id").formParam("Filter.1.Value.1", subnetId).post("/")
.then().statusCode(200)
.body("DescribeNatGatewaysResponse.natGatewaySet.item.size()", equalTo(expected));
}
/**
@@ -265,11 +293,7 @@ class Ec2NatGatewayAddressIntegrationTest {
String failedId = createNat(heldByGateway).then().statusCode(200)
.body("CreateNatGatewayResponse.natGateway.state", equalTo("failed"))
.extract().path("CreateNatGatewayResponse.natGateway.natGatewayId");
given()
.formParam("Action", "DescribeNatGateways")
.formParam("NatGatewayId.1", failedId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DescribeNatGateways", ACCOUNT_ID, REGION).formParam("NatGatewayId.1", failedId).post("/")
.then().statusCode(200)
.body("DescribeNatGatewaysResponse.natGatewaySet.item.state", equalTo("failed"))
.body("DescribeNatGatewaysResponse.natGatewaySet.item.failureCode",
@@ -279,58 +303,31 @@ class Ec2NatGatewayAddressIntegrationTest {
.body(not(containsString("<networkInterfaceId>")));
String heldByInstance = allocate();
given()
.formParam("Action", "AssociateAddress")
.formParam("AllocationId", heldByInstance)
.formParam("InstanceId", "i-0123456789abcdef0")
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("AssociateAddress", ACCOUNT_ID, REGION)
.formParam("AllocationId", heldByInstance).formParam("InstanceId", "i-0123456789abcdef0").post("/")
.then().statusCode(200);
createNat(heldByInstance).then().statusCode(200)
.body("CreateNatGatewayResponse.natGateway.state", equalTo("failed"))
.body("CreateNatGatewayResponse.natGateway.failureCode", equalTo("Resource.AlreadyAssociated"));
String instanceAssociation = given()
.formParam("Action", "DescribeAddresses")
.formParam("AllocationId.1", heldByInstance)
.header("Authorization", AUTH_HEADER)
.when().post("/")
String instanceAssociation = ec2("DescribeAddresses", ACCOUNT_ID, REGION)
.formParam("AllocationId.1", heldByInstance).post("/")
.then().statusCode(200)
.body("DescribeAddressesResponse.addressesSet.item.instanceId", equalTo("i-0123456789abcdef0"))
.extract().path("DescribeAddressesResponse.addressesSet.item.associationId");
// The failed gateway does not hold the address: once the instance lets go it can be released.
given()
.formParam("Action", "DisassociateAddress")
.formParam("AssociationId", instanceAssociation)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DisassociateAddress", ACCOUNT_ID, REGION).formParam("AssociationId", instanceAssociation).post("/")
.then().statusCode(200);
given()
.formParam("Action", "ReleaseAddress")
.formParam("AllocationId", heldByInstance)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("ReleaseAddress", ACCOUNT_ID, REGION).formParam("AllocationId", heldByInstance).post("/")
.then().statusCode(200);
// The failed gateway claimed nothing, and deleting it leaves the first gateway's association alone.
String held = given()
.formParam("Action", "DescribeAddresses")
.formParam("AllocationId.1", heldByGateway)
.header("Authorization", AUTH_HEADER)
.when().post("/")
String held = ec2("DescribeAddresses", ACCOUNT_ID, REGION).formParam("AllocationId.1", heldByGateway).post("/")
.then().statusCode(200)
.body("DescribeAddressesResponse.addressesSet.item.associationId", startsWith("eipassoc-"))
.extract().path("DescribeAddressesResponse.addressesSet.item.associationId");
given()
.formParam("Action", "DeleteNatGateway")
.formParam("NatGatewayId", failedId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DeleteNatGateway", ACCOUNT_ID, REGION).formParam("NatGatewayId", failedId).post("/")
.then().statusCode(200);
given()
.formParam("Action", "DescribeAddresses")
.formParam("AllocationId.1", heldByGateway)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DescribeAddresses", ACCOUNT_ID, REGION).formParam("AllocationId.1", heldByGateway).post("/")
.then().statusCode(200)
.body("DescribeAddressesResponse.addressesSet.item.associationId", equalTo(held));
}
@@ -341,57 +338,30 @@ class Ec2NatGatewayAddressIntegrationTest {
String allocationId = allocate();
String natGatewayId = createNat(allocationId).then().statusCode(200)
.extract().path("CreateNatGatewayResponse.natGateway.natGatewayId");
String associationId = given()
.formParam("Action", "DescribeAddresses")
.formParam("AllocationId.1", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
String associationId = ec2("DescribeAddresses", ACCOUNT_ID, REGION)
.formParam("AllocationId.1", allocationId).post("/")
.then().statusCode(200)
.extract().path("DescribeAddressesResponse.addressesSet.item.associationId");
given()
.formParam("Action", "DisassociateAddress")
.formParam("AssociationId", associationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DisassociateAddress", ACCOUNT_ID, REGION).formParam("AssociationId", associationId).post("/")
.then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
given()
.formParam("Action", "DescribeAddresses")
.formParam("AllocationId.1", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DescribeAddresses", ACCOUNT_ID, REGION).formParam("AllocationId.1", allocationId).post("/")
.then().statusCode(200)
.body("DescribeAddressesResponse.addressesSet.item.associationId", equalTo(associationId));
// Nor released out from under the gateway: AWS answers InvalidIPAddress.InUse.
given()
.formParam("Action", "ReleaseAddress")
.formParam("AllocationId", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("ReleaseAddress", ACCOUNT_ID, REGION).formParam("AllocationId", allocationId).post("/")
.then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidIPAddress.InUse"));
given()
.formParam("Action", "DescribeAddresses")
.formParam("AllocationId.1", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DescribeAddresses", ACCOUNT_ID, REGION).formParam("AllocationId.1", allocationId).post("/")
.then().statusCode(200)
.body("DescribeAddressesResponse.addressesSet.item.associationId", equalTo(associationId));
given()
.formParam("Action", "DeleteNatGateway")
.formParam("NatGatewayId", natGatewayId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("DeleteNatGateway", ACCOUNT_ID, REGION).formParam("NatGatewayId", natGatewayId).post("/")
.then().statusCode(200);
given()
.formParam("Action", "ReleaseAddress")
.formParam("AllocationId", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
ec2("ReleaseAddress", ACCOUNT_ID, REGION).formParam("AllocationId", allocationId).post("/")
.then().statusCode(200);
}
}
@@ -4559,6 +4559,26 @@ class Ec2ServiceTest {
assertEquals(List.of("10.50.1.11"), launchAddresses(service, subnetId, 1));
}
@Test
void aNatGatewaysRequestedPrivateIpTakesNoLeaseAndIsStillNotHandedOut() {
// DeleteNatGateway returns no lease, so one taken for the gateway's PrivateIpAddress would
// keep the address from the network's allocator after the gateway is gone. The walk steps
// around it while the stored gateway holds it.
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
Ec2Service service = mockedVpcNetworkService(vpcNetworks);
String subnetId = privateIpSubnet(service);
when(vpcNetworks.effectiveSubnetCidr("us-east-1", subnetId)).thenReturn(Optional.of("10.50.1.0/24"));
assertEquals("10.50.1.10", service.createNatGateway("us-east-1", subnetId, null, "private",
"10.50.1.10", List.of()).getNatGatewayAddresses().getFirst().getPrivateIp());
verify(vpcNetworks, never()).claimPrivateIp(anyString(), anyString(), anyString());
verify(vpcNetworks, never()).reservePrivateIp(anyString(), anyString(), anyString());
when(vpcNetworks.allocatePrivateIp("us-east-1", subnetId))
.thenReturn(Optional.of("10.50.1.10"), Optional.of("10.50.1.11"), Optional.empty());
assertEquals(List.of("10.50.1.11"), launchAddresses(service, subnetId, 1));
}
@Test
void anAddressAnotherAccountsInterfaceWasCreatedWithIsNotHandedOutOnASharedVpcNetwork() {
// Default subnet ids are the same in every account, so their Docker network is shared, and
@@ -5,10 +5,9 @@ AWS::CodePipeline::CustomActionType Id schema gives no description; the custom a
AWS::CodePipeline::Webhook Id schema gives no description; Floci keys webhooks by name
AWS::DSQL::Cluster EncryptionDetails an object, which attributes as Floci keeps them (text) cannot hold; on AWS an output naming it fails with "Every Value member must be a string", and EncryptionDetails.EncryptionStatus is refused as no attribute of the schema
AWS::EC2::Instance State the dotted State.Code and State.Name are set instead, the form AWS's GetAtt exposes for the nested State object
AWS::EC2::NatGateway AutoProvisionZones availability-mode NAT gateways are not emulated
AWS::EC2::NatGateway AutoScalingIps availability-mode NAT gateways are not emulated
AWS::EC2::NatGateway EniId the NAT gateway's network interface is not created
AWS::EC2::NatGateway RouteTableId availability-mode NAT gateways are not emulated
AWS::EC2::NatGateway AutoProvisionZones regional NAT gateways are not emulated
AWS::EC2::NatGateway AutoScalingIps regional NAT gateways are not emulated
AWS::EC2::NatGateway RouteTableId regional NAT gateways are not emulated
AWS::EC2::Subnet BlockPublicAccessStates VPC block public access is not emulated
AWS::EC2::Subnet Ipv6CidrBlocks IPv6 CIDR association is not emulated
AWS::EC2::Subnet NetworkAclAssociationId the subnet's default network ACL association is not created with the subnet
Can't render this file because it contains an unexpected character in line 6 and column 144.
@@ -220,13 +220,8 @@ AWS::EC2::Instance Tenancy accepted and ignored
AWS::EC2::Instance Volumes accepted and ignored
AWS::EC2::LaunchTemplate TagSpecifications accepted and ignored
AWS::EC2::LaunchTemplate VersionDescription accepted and ignored
AWS::EC2::NatGateway AvailabilityMode accepted and ignored
AWS::EC2::NatGateway AvailabilityZoneAddresses accepted and ignored
AWS::EC2::NatGateway MaxDrainDurationSeconds accepted and ignored
AWS::EC2::NatGateway PrivateIpAddress accepted and ignored
AWS::EC2::NatGateway SecondaryAllocationIds accepted and ignored
AWS::EC2::NatGateway SecondaryPrivateIpAddressCount accepted and ignored
AWS::EC2::NatGateway SecondaryPrivateIpAddresses accepted and ignored
AWS::EC2::NatGateway VpcId accepted and ignored
AWS::EC2::NetworkAcl Tags accepted and ignored
AWS::EC2::Route CarrierGatewayId accepted and ignored
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
220 AWS::EC2::Instance Volumes accepted and ignored
221 AWS::EC2::LaunchTemplate TagSpecifications accepted and ignored
222 AWS::EC2::LaunchTemplate VersionDescription accepted and ignored
AWS::EC2::NatGateway AvailabilityMode accepted and ignored
223 AWS::EC2::NatGateway AvailabilityZoneAddresses accepted and ignored
224 AWS::EC2::NatGateway MaxDrainDurationSeconds accepted and ignored
AWS::EC2::NatGateway PrivateIpAddress accepted and ignored
AWS::EC2::NatGateway SecondaryAllocationIds accepted and ignored
AWS::EC2::NatGateway SecondaryPrivateIpAddressCount accepted and ignored
AWS::EC2::NatGateway SecondaryPrivateIpAddresses accepted and ignored
225 AWS::EC2::NatGateway VpcId accepted and ignored
226 AWS::EC2::NetworkAcl Tags accepted and ignored
227 AWS::EC2::Route CarrierGatewayId accepted and ignored
+1
View File
@@ -189,6 +189,7 @@ notes:
AWS::Lambda::WebFunctionRevision: every property is createOnly, so a change mints a new revision
AWS::EC2::VPC: 'deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS'
AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported
AWS::EC2::NatGateway: 'zonal, primary address only; `AvailabilityMode` regional and the `Secondary*` address properties fail'
AWS::EC2::PrefixList: 'updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails'
AWS::ApplicationAutoScaling::ScalableTarget: '`ScheduledActions` are accepted and not run; Floci has no scheduled scaling'
AWS::RDS::DBInstance: starts a real container