diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2NatGatewayTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2NatGatewayTest.java index 5c0cb3266d..a3ea5396c7 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2NatGatewayTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2NatGatewayTest.java @@ -11,7 +11,6 @@ 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; @@ -19,7 +18,6 @@ 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 { @@ -64,30 +62,57 @@ class Ec2NatGatewayTest { } @Test - @DisplayName("CreateNatGateway refuses secondary addresses rather than creating a gateway without them") - void secondaryAddressesAreRefused() { + @DisplayName("CreateNatGateway gives a gateway its secondary addresses, reported after the primary one") + void secondaryAddressesAreReported() { // 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"); + AllocateAddressResponse primaryEip = ec2.allocateAddress(AllocateAddressRequest.builder() + .domain(DomainType.VPC).build()); + AllocateAddressResponse secondaryEip = ec2.allocateAddress(AllocateAddressRequest.builder() + .domain(DomainType.VPC).build()); + String publicId = null; + String privateId = null; + try { + publicId = ec2.createNatGateway(CreateNatGatewayRequest.builder() + .subnetId(subnetId) + .allocationId(primaryEip.allocationId()) + .secondaryAllocationIds(secondaryEip.allocationId()) + .build()).natGateway().natGatewayId(); + List publicAddresses = describe(ec2, publicId).natGatewayAddresses(); + assertThat(publicAddresses).hasSize(2); + assertThat(publicAddresses.get(0).isPrimary()).isTrue(); + NatGatewayAddress secondary = publicAddresses.get(1); + assertThat(secondary.isPrimary()).isFalse(); + assertThat(secondary.allocationId()).isEqualTo(secondaryEip.allocationId()); + assertThat(secondary.publicIp()).isEqualTo(secondaryEip.publicIp()); + assertThat(secondary.privateIp()).isNotBlank().isNotEqualTo(publicAddresses.get(0).privateIp()); + assertThat(secondary.networkInterfaceId()).isEqualTo(publicAddresses.get(0).networkInterfaceId()); + + privateId = ec2.createNatGateway(CreateNatGatewayRequest.builder() + .subnetId(subnetId) + .connectivityType(ConnectivityType.PRIVATE) + .secondaryPrivateIpAddressCount(2) + .build()).natGateway().natGatewayId(); + List privateAddresses = describe(ec2, privateId).natGatewayAddresses(); + assertThat(privateAddresses).hasSize(3); + assertThat(privateAddresses).extracting(NatGatewayAddress::isPrimary).containsExactly(true, false, false); + assertThat(privateAddresses).extracting(NatGatewayAddress::privateIp).doesNotHaveDuplicates(); + assertThat(privateAddresses).extracting(NatGatewayAddress::publicIp).containsOnlyNulls(); + } finally { + for (String id : new String[] {publicId, privateId}) { + if (id != null) { + ec2.deleteNatGateway(DeleteNatGatewayRequest.builder().natGatewayId(id).build()); + } + } + ec2.releaseAddress(ReleaseAddressRequest.builder().allocationId(primaryEip.allocationId()).build()); + ec2.releaseAddress(ReleaseAddressRequest.builder().allocationId(secondaryEip.allocationId()).build()); } } } + + private static NatGateway describe(Ec2Client ec2, String natGatewayId) { + return ec2.describeNatGateways(DescribeNatGatewaysRequest.builder().natGatewayIds(natGatewayId).build()) + .natGateways().get(0); + } } diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index e95fc013da..d114aa08f4 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -197,7 +197,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` (zonal, primary address only; `AvailabilityMode` regional and the `Secondary*` address properties fail), `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog`, `KeyPair` (a created key's private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key), `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; `AvailabilityMode` regional fails; a change to the `Secondary*` address properties updates the gateway in place), `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog`, `KeyPair` (a created key's private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key), `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` | diff --git a/docs/services/ec2.md b/docs/services/ec2.md index c4f9003900..47f92c919d 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -767,9 +767,22 @@ are not supported.` `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. +`InvalidIPAddress.InUse`. + +Secondary addresses sit on the gateway's one interface and are listed after the primary address in +`natGatewayAddressSet`, with `isPrimary` `false`. On a public gateway each `SecondaryAllocationIds` +Elastic IP is paired with the `SecondaryPrivateIpAddresses` entry at the same position, or with the +next free address, and is held like the primary one: `DescribeAddresses` shows it associated, another +gateway given it is created `failed`, `ReleaseAddress` refuses it, and `DeleteNatGateway` hands it +back. A private gateway takes the listed `SecondaryPrivateIpAddresses` plus +`SecondaryPrivateIpAddressCount` more free addresses. Listed addresses follow the `PrivateIpAddress` +rules. `SecondaryPrivateIpAddressCount` on a public gateway, or a secondary Elastic IP on a private +one, fails with `InvalidParameterCombination`, and a count outside 1 to 31 with +`InvalidParameterValue`. `AssociateNatGatewayAddress`, `DisassociateNatGatewayAddress`, +`AssignPrivateNatGatewayAddress` and `UnassignPrivateNatGatewayAddress` are not implemented. An +`AWS::EC2::NatGateway` whose secondary addresses change is still updated in place, as on AWS: it +keeps its id, a secondary the template still names keeps its address, a dropped Elastic IP is handed +back, and a new address that is already held fails the update and leaves the gateway as it was. ### Capacity Reservations diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java index b00d35c9b2..c9d6443207 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java @@ -184,6 +184,14 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { ec2Service.createTags(region, List.of(entityId), toTagList(priorTags)); } } + if (prior.has("natSecondaries")) { + JsonNode before = prior.get("natSecondaries"); + List eips = new ArrayList<>(); + List ips = new ArrayList<>(); + before.path("allocationIds").forEach(id -> eips.add(id.asText())); + before.path("privateIps").forEach(ip -> ips.add(ip.asText())); + ec2Service.updateNatGatewaySecondaryAddresses(region, entityId, eips, ips, null); + } if (prior.has("mapPublicIpOnLaunch")) { ec2Service.modifySubnetAttribute(region, entityId, "mapPublicIpOnLaunch", prior.get("mapPublicIpOnLaunch").asText()); } @@ -386,6 +394,46 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { .anyMatch(ip -> CidrCanonicalizer.sameBlock(ip + "/32", privateIpAddress + "/32")); } + /** + * Whether the gateway's secondary addresses are the ones the template asks for: the same + * Elastic IPs in order, each listed private address at its position, and as many in all. + */ + private static boolean holdsSecondaries(NatGateway nat, List allocationIds, List privateIps, + int count) { + List secondaries = nat.getNatGatewayAddresses().stream() + .filter(a -> !a.isPrimary()) + .toList(); + if (secondaries.size() != Math.max(allocationIds.size(), privateIps.size()) + count + || !secondaries.stream().map(NatGatewayAddress::getAllocationId).filter(Objects::nonNull).toList() + .equals(allocationIds)) { + return false; + } + for (int i = 0; i < privateIps.size(); i++) { + String held = secondaries.get(i).getPrivateIp(); + if (held == null || !CidrCanonicalizer.sameBlock(held + "/32", privateIps.get(i) + "/32")) { + return false; + } + } + return true; + } + + /** + * The gateway's secondary addresses as the request that sets them back: the Elastic IPs in + * order (they come first, see {@link Ec2Service#createNatGateway}) and every private address. + */ + private static ObjectNode natSecondaries(NatGateway nat) { + ObjectNode node = MAPPER.createObjectNode(); + ArrayNode eips = node.putArray("allocationIds"); + ArrayNode ips = node.putArray("privateIps"); + nat.getNatGatewayAddresses().stream().filter(a -> !a.isPrimary()).forEach(a -> { + if (a.getAllocationId() != null) { + eips.add(a.getAllocationId()); + } + ips.add(a.getPrivateIp()); + }); + return node; + } + private ManagedPrefixList findPrefixList(String prefixListId, String region) { return tolerateNotFound(() -> ec2Service.describeManagedPrefixLists(region, List.of(prefixListId), Map.of()) .stream().findFirst().orElse(null), "InvalidPrefixListID.NotFound", prefixListId); @@ -603,9 +651,9 @@ 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")); + List secondaryAllocationIds = ctx.resolveStringList(props, "SecondaryAllocationIds"); + List secondaryPrivateIps = ctx.resolveStringList(props, "SecondaryPrivateIpAddresses"); + String secondaryCount = ctx.resolveOptional(props, "SecondaryPrivateIpAddressCount"); String subnetId = ctx.resolveOptional(props, "SubnetId"); String allocationId = ctx.resolveOptional(props, "AllocationId"); String privateIpAddress = ctx.resolveOrDefault(props, "PrivateIpAddress", null); @@ -622,7 +670,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { } // 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. + // the address it was given. The Secondary* properties are not createOnly: the gateway is + // kept and its secondary addresses are changed in place. NatGateway existing = ctx.isUpdate() ? findNatGateway(ctx.priorPhysicalId(), ctx.region()) : null; boolean reuse = existing != null && Objects.equals(subnetId, existing.getSubnetId()) && Objects.equals(allocationId, existing.getAllocationId()) @@ -630,14 +679,27 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { && (privateIpAddress == null || holdsPrivateIp(existing, privateIpAddress)); NatGateway nat = reuse ? existing : ec2Service.createNatGateway(ctx.region(), subnetId, allocationId, connectivityType, privateIpAddress, - tagList(props, ctx)); + secondaryAllocationIds, secondaryPrivateIps, secondaryCount, 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()); throw new AwsException(nat.getFailureCode(), nat.getFailureMessage(), 400); } + NatGateway[] current = {nat}; + int secondaryCountValue = Ec2Service.secondaryPrivateIpCount(secondaryCount, "private".equals(connectivityType)); if (reuse) { - CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> applyTags(r, true, nat.getNatGatewayId(), existing.getTags(), props, ctx)); + CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> { + if (!holdsSecondaries(existing, secondaryAllocationIds, secondaryPrivateIps, secondaryCountValue)) { + ObjectNode prior = inPlacePrior(r, existing.getNatGatewayId(), ctx); + if (!prior.has("natSecondaries")) { + prior.set("natSecondaries", natSecondaries(existing)); + writeInPlacePrior(r, prior); + } + current[0] = ec2Service.updateNatGatewaySecondaryAddresses(ctx.region(), existing.getNatGatewayId(), + secondaryAllocationIds, secondaryPrivateIps, secondaryCount); + } + applyTags(r, true, nat.getNatGatewayId(), existing.getTags(), props, ctx); + }); } r.setPhysicalId(nat.getNatGatewayId()); r.getAttributes().put("NatGatewayId", nat.getNatGatewayId()); @@ -652,6 +714,15 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { if (nat.getSubnetId() != null) { r.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "SubnetId", nat.getSubnetId()); } + // Each secondary Elastic IP is held as the primary one is. + r.getAttributes().keySet().removeIf(k -> k.startsWith(CfnRollback.USES_ATTR_PREFIX + "SecondaryPublicIp.")); + List secondaryPublicIps = current[0].getNatGatewayAddresses().stream() + .filter(a -> !a.isPrimary() && a.getPublicIp() != null) + .map(NatGatewayAddress::getPublicIp) + .toList(); + for (int i = 0; i < secondaryPublicIps.size(); i++) { + r.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "SecondaryPublicIp." + i, secondaryPublicIps.get(i)); + } Address eip = allocationId == null || allocationId.isBlank() ? null : findAddress(allocationId, null, ctx.region()); if (eip != null && eip.getPublicIp() != null) { r.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "PublicIp", eip.getPublicIp()); diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index abfe44f6be..77f7d9b2d5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -4481,14 +4481,15 @@ public class Ec2QueryHandler { private Response handleCreateNatGateway(MultivaluedMap 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"), + getList(p, "SecondaryAllocationId"), + getList(p, "SecondaryPrivateIpAddress"), + p.getFirst("SecondaryPrivateIpAddressCount"), parseTagsForResource(p, "natgateway")); XmlBuilder xml = new XmlBuilder() .start("CreateNatGatewayResponse", AwsNamespaces.EC2) diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 698c015b55..87df060a3e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -4568,6 +4568,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // failed launch is still giving it back keeps it without one. if (allocated.isPresent()) { held = privateIpsHeldOnVpcNetwork(region, subnetId); + held.addAll(pending); } List skipped = new ArrayList<>(); while (allocated.isPresent() && held.contains(allocated.get())) { @@ -12377,49 +12378,58 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } } - /** - * 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 secondaryAllocationIds, - List 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 natGatewayTags) { return createNatGateway(region, subnetId, allocationId, connectivityType, null, natGatewayTags); } + public NatGateway createNatGateway(String region, String subnetId, String allocationId, + String connectivityType, String privateIpAddress, + List natGatewayTags) { + return createNatGateway(region, subnetId, allocationId, connectivityType, privateIpAddress, + List.of(), List.of(), 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. + * @param secondaryAllocationIds SecondaryAllocationIds: extra Elastic IPs, public gateways only. + * Each is paired with the secondary private address at the same + * position, or one the subnet picks. + * @param secondaryPrivateIpAddresses SecondaryPrivateIpAddresses, checked as PrivateIpAddress is + * @param secondaryPrivateIpAddressCount SecondaryPrivateIpAddressCount, private gateways only, + * 1 to 31: that many more addresses the subnet picks */ public NatGateway createNatGateway(String region, String subnetId, String allocationId, String connectivityType, String privateIpAddress, + List secondaryAllocationIds, + List secondaryPrivateIpAddresses, + String secondaryPrivateIpAddressCount, List natGatewayTags) { ensureDefaultResources(region); Subnet subnet = requireSubnet(region, subnetId); boolean privateGateway = "private".equalsIgnoreCase(connectivityType); - if (privateGateway && isSet(allocationId)) { + List secondaryEips = secondaryAllocationIds == null ? List.of() : secondaryAllocationIds; + if (privateGateway && (isSet(allocationId) || !secondaryEips.isEmpty())) { // A private NAT gateway has no route to the internet and so nothing to attach an // Elastic IP to. Accepting the pair would have the response report a public address // on a gateway that cannot have one. throw new AwsException("InvalidParameterCombination", "Elastic IP addresses cannot be associated with private NAT gateways.", 400); } + int secondaryCount = secondaryPrivateIpCount(secondaryPrivateIpAddressCount, privateGateway); if (isSet(allocationId)) { getRequiredAddress(region, allocationId); } + secondaryEips.forEach(id -> getRequiredAddress(region, id)); String requestedPrivateIp = isSet(privateIpAddress) ? validateRequestedPrivateIp(privateIpAddress, subnet, null, 1) : null; + List requestedSecondaryIps = (secondaryPrivateIpAddresses == null ? List.of() + : secondaryPrivateIpAddresses).stream() + .map(ip -> validateRequestedPrivateIp(ip, subnet, null, 1)) + .toList(); NatGateway natGateway = new NatGateway(); natGateway.setNatGatewayId("nat-" + randomHex(17)); @@ -12434,31 +12444,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // cannot both see the allocation free. As on AWS, an allocation already held by an // instance or another gateway does not fail the call: the gateway is created in state // failed, with no interface, and the allocation is left with its holder. + List eips = new ArrayList<>(); if (isSet(allocationId)) { - Address held = getRequiredAddress(region, allocationId); - // The gateway scan covers gateways persisted before the Address record was marked. - if (isSet(held.getAssociationId()) || isSet(held.getInstanceId()) - || isHeldByNatGateway(region, allocationId)) { + eips.add(allocationId); + } + eips.addAll(secondaryEips); + Set seen = new HashSet<>(); + for (String eipId : eips) { + if (!seen.add(eipId) || isElasticIpTaken(region, eipId)) { natGateway.setState("failed"); natGateway.setFailureCode("Resource.AlreadyAssociated"); - natGateway.setFailureMessage("Elastic IP address " + allocationId + " is already associated"); + natGateway.setFailureMessage("Elastic IP address " + eipId + " is already associated"); + break; } } if (!"failed".equals(natGateway.getState())) { - 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 - // to reuse. No instanceId, a NAT gateway is not an instance. - if (isSet(allocationId)) { - addresses.get(key(region, allocationId)).ifPresent(eip -> { - eip.setAssociationId(gatewayAddress.getAssociationId()); - eip.setNetworkInterfaceId(gatewayAddress.getNetworkInterfaceId()); - eip.setPrivateIpAddress(gatewayAddress.getPrivateIp()); - addresses.put(key(region, allocationId), eip); - }); - } + natGateway.getNatGatewayAddresses().addAll(natGatewayAddresses(region, natGateway.getNatGatewayId(), + subnetId, allocationId, requestedPrivateIp, secondaryEips, requestedSecondaryIps, secondaryCount)); + natGateway.getNatGatewayAddresses().forEach(a -> holdNatGatewayEip(region, a)); } if (natGatewayTags != null && !natGatewayTags.isEmpty()) { natGateway.setTags(new ArrayList<>(natGatewayTags)); @@ -12469,28 +12472,115 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return natGateway; } + /** + * SecondaryPrivateIpAddressCount as a number, 0 when absent. The EC2 API reference marks it + * "[Private NAT gateway only]" with a valid range of 1 to 31. + */ + public static int secondaryPrivateIpCount(String value, boolean privateGateway) { + if (!isSet(value)) { + return 0; + } + if (!privateGateway) { + throw new AwsException("InvalidParameterCombination", + "SecondaryPrivateIpAddressCount is only valid for private NAT gateways.", 400); + } + int count; + try { + count = Integer.parseInt(value.trim()); + } catch (NumberFormatException e) { + count = 0; + } + if (count < 1 || count > 31) { + throw new AwsException("InvalidParameterValue", + "Value (" + value + ") for parameter SecondaryPrivateIpAddressCount is invalid. " + + "It must be between 1 and 31.", 400); + } + return count; + } + + /** + * The primary address, then each secondary one, all on the gateway's one interface. Every + * requested address is checked free before any is assigned, so a request that fails leaves no + * lease behind. Callers must hold {@link #privateIpAllocationLock}. + */ + private List natGatewayAddresses(String region, String natGatewayId, String subnetId, + String allocationId, String requestedPrivateIp, + List secondaryEips, List requestedSecondaryIps, + int secondaryCount) { + List requested = new ArrayList<>(requestedSecondaryIps); + if (requestedPrivateIp != null) { + requested.add(requestedPrivateIp); + } + Set pending = new HashSet<>(); + for (String ip : requested) { + if (!pending.add(ip)) { + throw new AwsException("InvalidIPAddress.InUse", "Address " + ip + " is in use.", 400); + } + requireRequestedPrivateIpFree(region, subnetId, ip); + } + List eips = new ArrayList<>(); + eips.add(allocationId); + eips.addAll(secondaryEips); + List ips = new ArrayList<>(); + ips.add(requestedPrivateIp); + ips.addAll(requestedSecondaryIps); + NatGatewayAddress[] slots = new NatGatewayAddress[ + 1 + Math.max(secondaryEips.size(), requestedSecondaryIps.size()) + secondaryCount]; + fillNatGatewaySlots(region, natGatewayId, subnetId, slots, eips, ips, pending); + slots[0].setPrimary(true); + return new ArrayList<>(List.of(slots)); + } + + /** + * Builds an address for every empty slot from the Elastic IP and private address at the same + * position of {@code eips} and {@code ips}, either of which may be shorter than {@code slots} + * or hold null. A slot with no private address takes the next free one; if any slot fails, the + * addresses taken here are given back. Every address built is secondary. Callers must hold + * {@link #privateIpAllocationLock} and have checked the requested addresses free. + * + * @param pending addresses already spoken for, which automatic assignment must not hand out + */ + private void fillNatGatewaySlots(String region, String natGatewayId, String subnetId, NatGatewayAddress[] slots, + List eips, List ips, Set pending) { + List assigned = new ArrayList<>(); + try { + for (int i = 0; i < slots.length; i++) { + if (slots[i] != null) { + continue; + } + String ip = i < ips.size() ? ips.get(i) : null; + if (ip == null) { + ip = assignPrivateIp(region, subnetId, pending); + pending.add(ip); + assigned.add(ip); + } + slots[i] = natGatewayAddress(region, natGatewayId, i < eips.size() ? eips.get(i) : null, ip); + slots[i].setPrimary(false); + } + } catch (AwsException e) { + if (vpcNetworkManager != null) { + assigned.forEach(ip -> vpcNetworkManager.releasePrivateIp(region, subnetId, ip)); + } + throw e; + } + } + /** * The address a NAT gateway reports. AWS gives every gateway an interface in its subnet with a * private address, and a public one additionally carries the Elastic IP it was created with, * 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}. + * Every address of one gateway shares its one interface. * - * @param requestedPrivateIp the request's PrivateIpAddress, already checked by - * {@link #validateRequestedPrivateIp}, or null. It takes no lease on - * the VPC network (see {@link #requireRequestedPrivateIpFree}). + * @param privateIp the address, already checked free. A requested one takes no lease on the + * VPC network (see {@link #requireRequestedPrivateIpFree}). */ - private NatGatewayAddress natGatewayAddress(String region, String natGatewayId, String subnetId, - String allocationId, String requestedPrivateIp) { + private NatGatewayAddress natGatewayAddress(String region, String natGatewayId, String allocationId, + String privateIp) { NatGatewayAddress address = new NatGatewayAddress(); address.setNetworkInterfaceId(eniIdFromSeed("nat|" + natGatewayId)); - if (requestedPrivateIp != null) { - requireRequestedPrivateIpFree(region, subnetId, requestedPrivateIp); - address.setPrivateIp(requestedPrivateIp); - } else { - address.setPrivateIp(assignPrivateIp(region, subnetId)); - } + address.setPrivateIp(privateIp); if (isSet(allocationId)) { address.setAllocationId(allocationId); address.setAssociationId("eipassoc-" + randomHex(17)); @@ -12515,11 +12605,28 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (subnet == null) { return List.of(); } - List result = new ArrayList<>(); + Map result = new LinkedHashMap<>(); for (NatGatewayAddress address : natGateway.getNatGatewayAddresses()) { if (address.getNetworkInterfaceId() == null) { continue; } + NetworkInterfacePrivateIpAddress ip = new NetworkInterfacePrivateIpAddress(); + ip.setPrivateIpAddress(address.getPrivateIp()); + ip.setPrimary(address.isPrimary()); + if (address.getPublicIp() != null) { + NetworkInterfaceAssociation assoc = new NetworkInterfaceAssociation(); + assoc.setPublicIp(address.getPublicIp()); + assoc.setAllocationId(address.getAllocationId()); + assoc.setAssociationId(address.getAssociationId()); + assoc.setIpOwnerId(ownerId); + ip.setAssociation(assoc); + } + // A secondary address sits on the primary address's interface. + NetworkInterface existing = result.get(address.getNetworkInterfaceId()); + if (existing != null) { + existing.getPrivateIpAddresses().add(ip); + continue; + } NetworkInterface ni = new NetworkInterface(); ni.setNetworkInterfaceId(address.getNetworkInterfaceId()); ni.setSubnetId(natGateway.getSubnetId()); @@ -12530,21 +12637,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab ni.setRequesterManaged(true); ni.setOwnerId(ownerId); ni.setPrivateIpAddress(address.getPrivateIp()); - NetworkInterfacePrivateIpAddress primaryIp = new NetworkInterfacePrivateIpAddress(); - primaryIp.setPrivateIpAddress(address.getPrivateIp()); - primaryIp.setPrimary(true); - if (address.getPublicIp() != null) { - NetworkInterfaceAssociation assoc = new NetworkInterfaceAssociation(); - assoc.setPublicIp(address.getPublicIp()); - assoc.setAllocationId(address.getAllocationId()); - assoc.setAssociationId(address.getAssociationId()); - assoc.setIpOwnerId(ownerId); - primaryIp.setAssociation(assoc); - } - ni.getPrivateIpAddresses().add(primaryIp); - result.add(ni); + ni.getPrivateIpAddresses().add(ip); + result.put(address.getNetworkInterfaceId(), ni); } - return result; + return new ArrayList<>(result.values()); } public List describeNatGateways(String region, List natGatewayIds, @@ -12575,20 +12671,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // the lock createNatGateway takes, so a concurrent create cannot have its association wiped. synchronized (privateIpAllocationLock) { natGateway.setState("deleted"); - for (NatGatewayAddress gatewayAddress : natGateway.getNatGatewayAddresses()) { - if (!isSet(gatewayAddress.getAllocationId())) { - continue; - } - addresses.get(key(region, gatewayAddress.getAllocationId())) - .filter(eip -> gatewayAddress.getAssociationId() != null - && gatewayAddress.getAssociationId().equals(eip.getAssociationId())) - .ifPresent(eip -> { - eip.setAssociationId(null); - eip.setNetworkInterfaceId(null); - eip.setPrivateIpAddress(null); - addresses.put(key(region, eip.getAllocationId()), eip); - }); - } + natGateway.getNatGatewayAddresses().forEach(a -> releaseNatGatewayEip(region, a)); natGateways.delete(key(region, natGatewayId)); removeTags(region, natGatewayId); natGateway.getNatGatewayAddresses().forEach(a -> removeTags(region, a.getNetworkInterfaceId())); @@ -12596,6 +12679,160 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return natGateway; } + /** + * Sets a gateway's secondary addresses to the ones given, as AssociateNatGatewayAddress, + * DisassociateNatGatewayAddress, AssignPrivateNatGatewayAddress and + * UnassignPrivateNatGatewayAddress together would, keeping the gateway and its id: a secondary + * the request still names is kept, one it no longer names is dropped and its Elastic IP handed + * back, and a new one is checked as {@link #createNatGateway} checks it. Every check runs before + * anything changes, so a refused request leaves the gateway as it was. The arguments mean what + * they mean to {@link #createNatGateway}. + */ + public NatGateway updateNatGatewaySecondaryAddresses(String region, String natGatewayId, + List secondaryAllocationIds, + List secondaryPrivateIpAddresses, + String secondaryPrivateIpAddressCount) { + ensureDefaultResources(region); + NatGateway requested = getRequiredNatGateway(region, natGatewayId); + String subnetId = requested.getSubnetId(); + Subnet subnet = requireSubnet(region, subnetId); + boolean privateGateway = "private".equalsIgnoreCase(requested.getConnectivityType()); + List eips = nullToEmpty(secondaryAllocationIds); + if (privateGateway && !eips.isEmpty()) { + throw new AwsException("InvalidParameterCombination", + "Elastic IP addresses cannot be associated with private NAT gateways.", 400); + } + int count = secondaryPrivateIpCount(secondaryPrivateIpAddressCount, privateGateway); + eips.forEach(id -> getRequiredAddress(region, id)); + List ips = nullToEmpty(secondaryPrivateIpAddresses).stream() + .map(ip -> validateRequestedPrivateIp(ip, subnet, null, 1)) + .toList(); + if (new HashSet<>(ips).size() != ips.size()) { + throw new AwsException("InvalidIPAddress.InUse", "A secondary address is listed twice.", 400); + } + int slots = Math.max(eips.size(), ips.size()) + count; + synchronized (privateIpAllocationLock) { + // Read again under the lock DeleteNatGateway takes, so a gateway deleted since the read + // above is refused rather than written back holding its Elastic IPs again. + NatGateway natGateway = getRequiredNatGateway(region, natGatewayId); + if ("deleted".equals(natGateway.getState())) { + throw new AwsException("NatGatewayNotFound", "NatGateway " + natGatewayId + " was not found", 400); + } + List dropped = new ArrayList<>(natGateway.getNatGatewayAddresses().stream() + .filter(a -> !a.isPrimary()).toList()); + NatGatewayAddress[] result = new NatGatewayAddress[slots]; + // A slot naming an Elastic IP or an address keeps the secondary that already matches it; + // the counted slots then keep the last of the other secondaries with neither. Slot + // position is the only record of where an address came from: counted addresses usually + // follow the listed ones, so the last are usually ones the subnet picked rather than + // listed ones the request dropped. Across updates an address once listed can move + // behind a picked one, and then it is the one kept. + for (int i = 0; i < slots; i++) { + String eip = i < eips.size() ? eips.get(i) : null; + String ip = i < ips.size() ? ips.get(i) : null; + if (eip != null || ip != null) { + result[i] = takeFirst(dropped, a -> Objects.equals(eip, a.getAllocationId()) + && (ip == null || ip.equals(a.getPrivateIp()))); + } + } + int listed = Math.max(eips.size(), ips.size()); + List unlisted = dropped.stream() + .filter(a -> a.getAllocationId() == null && !ips.contains(a.getPrivateIp())) + .toList(); + List counted = unlisted.subList(Math.max(0, unlisted.size() - count), unlisted.size()); + for (int i = 0; i < counted.size(); i++) { + result[listed + i] = counted.get(i); + dropped.remove(counted.get(i)); + } + Set droppedEips = new HashSet<>(); + Set droppedIps = new HashSet<>(); + dropped.forEach(a -> { + addIfSet(droppedEips, a.getAllocationId()); + addIfSet(droppedIps, a.getPrivateIp()); + }); + Set seen = new HashSet<>(); + for (int i = 0; i < slots; i++) { + if (result[i] != null) { + continue; + } + String eip = i < eips.size() ? eips.get(i) : null; + if (eip != null && (!seen.add(eip) || !droppedEips.contains(eip) && isElasticIpTaken(region, eip))) { + throw new AwsException("Resource.AlreadyAssociated", + "Elastic IP address " + eip + " is already associated", 400); + } + String ip = i < ips.size() ? ips.get(i) : null; + if (ip != null && !droppedIps.contains(ip)) { + requireRequestedPrivateIpFree(region, subnetId, ip); + } + } + fillNatGatewaySlots(region, natGatewayId, subnetId, result, eips, ips, new HashSet<>(ips)); + dropped.forEach(a -> releaseNatGatewayEip(region, a)); + List addresses = new ArrayList<>(natGateway.getNatGatewayAddresses().stream() + .filter(NatGatewayAddress::isPrimary).toList()); + addresses.addAll(List.of(result)); + addresses.forEach(a -> holdNatGatewayEip(region, a)); + natGateway.setNatGatewayAddresses(addresses); + natGateways.put(key(region, natGatewayId), natGateway); + return natGateway; + } + } + + private static T takeFirst(List from, Predicate matching) { + for (T item : from) { + if (matching.test(item)) { + from.remove(item); + return item; + } + } + return null; + } + + /** + * Whether an instance or a NAT gateway already holds the Elastic IP. The gateway scan covers + * gateways persisted before the Address record was marked. + */ + private boolean isElasticIpTaken(String region, String allocationId) { + Address held = getRequiredAddress(region, allocationId); + return isSet(held.getAssociationId()) || isSet(held.getInstanceId()) || isHeldByNatGateway(region, allocationId); + } + + /** + * Marks the address's Elastic IP held by the gateway's interface, so DescribeAddresses says so: + * an allocation that looks free is one Terraform and the console would offer to reuse. No + * instanceId, a NAT gateway is not an instance. Callers must hold {@link #privateIpAllocationLock}. + */ + private void holdNatGatewayEip(String region, NatGatewayAddress gatewayAddress) { + if (!isSet(gatewayAddress.getAllocationId())) { + return; + } + addresses.get(key(region, gatewayAddress.getAllocationId())).ifPresent(eip -> { + eip.setAssociationId(gatewayAddress.getAssociationId()); + eip.setNetworkInterfaceId(gatewayAddress.getNetworkInterfaceId()); + eip.setPrivateIpAddress(gatewayAddress.getPrivateIp()); + addresses.put(key(region, eip.getAllocationId()), eip); + }); + } + + /** + * Hands the address's Elastic IP back, but only if the association is still the gateway's own. + * Callers must hold {@link #privateIpAllocationLock}, so a concurrent create cannot have its + * association wiped. + */ + private void releaseNatGatewayEip(String region, NatGatewayAddress gatewayAddress) { + if (!isSet(gatewayAddress.getAllocationId())) { + return; + } + addresses.get(key(region, gatewayAddress.getAllocationId())) + .filter(eip -> gatewayAddress.getAssociationId() != null + && gatewayAddress.getAssociationId().equals(eip.getAssociationId())) + .ifPresent(eip -> { + eip.setAssociationId(null); + eip.setNetworkInterfaceId(null); + eip.setPrivateIpAddress(null); + addresses.put(key(region, eip.getAllocationId()), eip); + }); + } + private NatGateway getRequiredNatGateway(String region, String natGatewayId) { NatGateway natGateway = natGateways.get(key(region, natGatewayId)).orElse(null); if (natGateway == null) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java index 19434bd5ef..9b9a0d19e3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java @@ -158,6 +158,270 @@ class CloudFormationEc2NetworkingIntegrationTest { assertFalse(ec2("DescribeNatGateways").contains(vpcId), "no gateway, failed or not, is left behind"); } + /** + * A NAT gateway in its own subnet with three Elastic IPs to choose from. {@code natProps} are + * the gateway's properties after SubnetId; {@code failing} adds a resource that cannot be + * created once the gateway is done. + */ + private static String secondaryNatTemplate(String vpcId, String cidr, String natProps, boolean failing) { + String boom = failing + ? ",\n \"Boom\": {\"Type\": \"AWS::SecretsManager::Secret\", \"DependsOn\": \"Nat\"," + + " \"Properties\": {\"SecretString\": \"x\", \"GenerateSecretString\": {\"SecretStringTemplate\": \"{}\", \"GenerateStringKey\": \"p\"}}}" + : ""; + return """ + { + "Resources": { + "Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {"VpcId": "%1$s", "CidrBlock": "%2$s"}}, + "Eip": {"Type": "AWS::EC2::EIP", "Properties": {"Domain": "vpc"}}, + "Eip2": {"Type": "AWS::EC2::EIP", "Properties": {"Domain": "vpc"}}, + "Eip3": {"Type": "AWS::EC2::EIP", "Properties": {"Domain": "vpc"}}, + "Nat": {"Type": "AWS::EC2::NatGateway", "Properties": {"SubnetId": {"Ref": "Subnet"}%3$s}}%4$s + }, + "Outputs": { + "NatId": {"Value": {"Ref": "Nat"}}, + "SubnetId": {"Value": {"Ref": "Subnet"}}, + "Eip2Id": {"Value": {"Fn::GetAtt": ["Eip2", "AllocationId"]}}, + "Eip3Id": {"Value": {"Fn::GetAtt": ["Eip3", "AllocationId"]}} + } + } + """.formatted(vpcId, cidr, natProps, boom); + } + + private static final String PUBLIC_NAT = ", \"AllocationId\": {\"Fn::GetAtt\": [\"Eip\", \"AllocationId\"]}"; + + /** + * A NAT gateway's secondary addresses are not create-only, so AWS changes them in place and the + * gateway keeps its id. Replacing it instead would ask for the Elastic IP the old gateway still + * holds and fail with Resource.AlreadyAssociated. + */ + @Test + void aPublicNatGatewaysSecondaryElasticIpsChangeInPlace() { + String stack = "ec2-nat-secondary-public-it"; + String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.45.0.0/16")), "", ""); + cloudFormation(stack, "CreateStack", secondaryNatTemplate(vpcId, "10.45.0.0/24", + PUBLIC_NAT + ", \"SecondaryAllocationIds\": [{\"Fn::GetAtt\": [\"Eip2\", \"AllocationId\"]}]", false)); + Map out = XmlParser.extractPairs(describeStacks(stack, "CREATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue"); + String natId = out.get("NatId"); + String eip2 = out.get("Eip2Id"); + String eip3 = out.get("Eip3Id"); + assertTrue(natXml(natId).contains("" + eip2 + ""), natXml(natId)); + + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.45.0.0/24", + PUBLIC_NAT + ", \"SecondaryAllocationIds\": [{\"Fn::GetAtt\": [\"Eip3\", \"AllocationId\"]}]", false)); + assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId"), "the gateway is kept"); + String nat = natXml(natId); + assertTrue(nat.contains("" + eip3 + "") && !nat.contains(eip2), nat); + assertFalse(ec2("DescribeAddresses", Map.of("AllocationId.1", eip2)).contains(""), + "the dropped Elastic IP is free"); + assertTrue(ec2("DescribeAddresses", Map.of("AllocationId.1", eip3)).contains(""), + "the added Elastic IP is held"); + + // An Elastic IP another gateway holds fails the update and leaves the gateway as it was. + String held = between(ec2("AllocateAddress", Map.of("Domain", "vpc")), "", ""); + String otherNat = between(ec2("CreateNatGateway", Map.of("SubnetId", out.get("SubnetId"), "AllocationId", held)), + "", ""); + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.45.0.0/24", + PUBLIC_NAT + ", \"SecondaryAllocationIds\": [\"" + held + "\"]", false)); + describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE"); + String reason = CfnStackWaits.failedResourceReason(stack, CFN_AUTH); + assertTrue(reason.contains(held), reason); + nat = natXml(natId); + assertTrue(nat.contains("" + eip3 + "") && !nat.contains(held), nat); + assertTrue(natXml(otherNat).contains("" + held + "")); + + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.45.0.0/24", PUBLIC_NAT, false)); + assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId")); + nat = natXml(natId); + assertFalse(nat.contains(eip3) || !secondaryIps(nat).isEmpty(), "no secondary is left: " + nat); + assertFalse(ec2("DescribeAddresses", Map.of("AllocationId.1", eip3)).contains("")); + + ec2("DeleteNatGateway", Map.of("NatGatewayId", otherNat)); + ec2("ReleaseAddress", Map.of("AllocationId", held)); + cloudFormation(stack, "DeleteStack", null); + CfnStackWaits.awaitStackDeleted(stack); + ec2("DeleteVpc", Map.of("VpcId", vpcId)); + } + + @Test + void aPrivateNatGatewaysSecondaryAddressesChangeInPlace() { + String stack = "ec2-nat-secondary-private-it"; + String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.46.0.0/16")), "", ""); + String privateNat = ", \"ConnectivityType\": \"private\", \"PrivateIpAddress\": \"10.46.0.10\"," + + " \"SecondaryPrivateIpAddresses\": [%s]"; + cloudFormation(stack, "CreateStack", secondaryNatTemplate(vpcId, "10.46.0.0/24", + privateNat.formatted("\"10.46.0.20\""), false)); + Map out = XmlParser.extractPairs(describeStacks(stack, "CREATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue"); + String natId = out.get("NatId"); + + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.46.0.0/24", + privateNat.formatted("\"10.46.0.21\", \"10.46.0.22\""), false)); + assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId"), "the gateway is kept"); + String nat = natXml(natId); + assertTrue(nat.contains("10.46.0.10") && nat.contains("10.46.0.21") + && nat.contains("10.46.0.22") && !nat.contains("10.46.0.20"), nat); + + // A change next to a resource that fails is put back. + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.46.0.0/24", + privateNat.formatted("\"10.46.0.23\""), true)); + describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE"); + nat = natXml(natId); + assertTrue(nat.contains("10.46.0.21") && nat.contains("10.46.0.22") + && !nat.contains("10.46.0.23"), "the prior secondaries must be back: " + nat); + + // An address another resource holds fails the update and leaves the gateway as it was. + String eni = between(ec2("CreateNetworkInterface", Map.of("SubnetId", out.get("SubnetId"), + "PrivateIpAddress", "10.46.0.30")), "", ""); + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.46.0.0/24", + privateNat.formatted("\"10.46.0.30\""), false)); + describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE"); + String reason = CfnStackWaits.failedResourceReason(stack, CFN_AUTH); + assertTrue(reason.contains("10.46.0.30"), reason); + nat = natXml(natId); + assertTrue(nat.contains("10.46.0.21") && nat.contains("10.46.0.22") + && !nat.contains("10.46.0.30"), nat); + + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.46.0.0/24", + ", \"ConnectivityType\": \"private\", \"PrivateIpAddress\": \"10.46.0.10\"", false)); + assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId")); + nat = natXml(natId); + assertTrue(nat.contains("10.46.0.10") && secondaryIps(nat).isEmpty(), + "only the primary address is left: " + nat); + + ec2("DeleteNetworkInterface", Map.of("NetworkInterfaceId", eni)); + cloudFormation(stack, "DeleteStack", null); + CfnStackWaits.awaitStackDeleted(stack); + ec2("DeleteVpc", Map.of("VpcId", vpcId)); + } + + /** A counted secondary survives a count change and an unrelated update, and the gateway is kept. */ + @Test + void aPrivateNatGatewaysCountedSecondariesChangeInPlace() { + String stack = "ec2-nat-secondary-count-it"; + String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.47.0.0/16")), "", ""); + String counted = ", \"ConnectivityType\": \"private\", \"SecondaryPrivateIpAddressCount\": %d%s"; + cloudFormation(stack, "CreateStack", secondaryNatTemplate(vpcId, "10.47.0.0/24", counted.formatted(1, ""), false)); + String natId = XmlParser.extractPairs(describeStacks(stack, "CREATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId"); + List first = secondaryIps(natXml(natId)); + assertEquals(1, first.size(), natXml(natId)); + + // The count unchanged next to another change: the same address. + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.47.0.0/24", + counted.formatted(1, ", \"Tags\": [{\"Key\": \"k\", \"Value\": \"v\"}]"), false)); + assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId")); + assertEquals(first, secondaryIps(natXml(natId))); + + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.47.0.0/24", counted.formatted(2, ""), false)); + assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId")); + List two = secondaryIps(natXml(natId)); + assertEquals(2, two.size(), natXml(natId)); + assertEquals(first.get(0), two.get(0), "the counted address is kept: " + two); + assertTrue(!two.get(1).equals(two.get(0)) && two.get(1).startsWith("10.47.0."), "a new address in the subnet: " + two); + + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.47.0.0/24", counted.formatted(1, ""), false)); + assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId")); + List one = secondaryIps(natXml(natId)); + assertEquals(1, one.size(), natXml(natId)); + assertEquals(List.of(two.get(1)), one, "the last counted address is kept"); + + cloudFormation(stack, "DeleteStack", null); + CfnStackWaits.awaitStackDeleted(stack); + ec2("DeleteVpc", Map.of("VpcId", vpcId)); + } + + /** + * Listed addresses changing next to a count keep the address the subnet picked, not a listed + * one that the template dropped. + */ + @Test + void aCountedSecondaryKeepsItsAddressWhenTheListedOnesChange() { + String stack = "ec2-nat-secondary-mixed-it"; + String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.48.0.0/16")), "", ""); + String mixed = ", \"ConnectivityType\": \"private\", \"SecondaryPrivateIpAddresses\": [\"%s\"]," + + " \"SecondaryPrivateIpAddressCount\": 1"; + cloudFormation(stack, "CreateStack", secondaryNatTemplate(vpcId, "10.48.0.0/24", mixed.formatted("10.48.0.40"), false)); + String natId = XmlParser.extractPairs(describeStacks(stack, "CREATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId"); + List before = secondaryIps(natXml(natId)); + assertEquals("10.48.0.40", before.get(0), before.toString()); + String picked = before.get(1); + + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.48.0.0/24", mixed.formatted("10.48.0.41"), false)); + assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId")); + assertEquals(List.of("10.48.0.41", picked), secondaryIps(natXml(natId)), + "the listed address is swapped and the picked one kept"); + + cloudFormation(stack, "DeleteStack", null); + CfnStackWaits.awaitStackDeleted(stack); + ec2("DeleteVpc", Map.of("VpcId", vpcId)); + } + + /** Secondary Elastic IPs moved between listed addresses, and one moved to a new address, in one update each. */ + @Test + void aSecondaryElasticIpMovesToAnotherAddressInPlace() { + String stack = "ec2-nat-secondary-move-it"; + String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.49.0.0/16")), "", ""); + String moved = PUBLIC_NAT + ", \"SecondaryAllocationIds\": [{\"Fn::GetAtt\": [\"Eip2\", \"AllocationId\"]}," + + " {\"Fn::GetAtt\": [\"Eip3\", \"AllocationId\"]}], \"SecondaryPrivateIpAddresses\": [\"%s\", \"%s\"]"; + cloudFormation(stack, "CreateStack", secondaryNatTemplate(vpcId, "10.49.0.0/24", + moved.formatted("10.49.0.50", "10.49.0.51"), false)); + Map out = XmlParser.extractPairs(describeStacks(stack, "CREATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue"); + String natId = out.get("NatId"); + String eip2 = out.get("Eip2Id"); + String eip3 = out.get("Eip3Id"); + assertEquals("10.49.0.50", eipPrivateIp(eip2)); + + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.49.0.0/24", + moved.formatted("10.49.0.51", "10.49.0.50"), false)); + assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId")); + assertEquals(List.of("10.49.0.51", "10.49.0.50"), secondaryIps(natXml(natId))); + assertEquals("10.49.0.51", eipPrivateIp(eip2), "the swapped Elastic IP is held at its new address"); + assertEquals("10.49.0.50", eipPrivateIp(eip3)); + + cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.49.0.0/24", + moved.formatted("10.49.0.52", "10.49.0.50"), false)); + assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"), + "Outputs", "OutputKey", "OutputValue").get("NatId")); + assertEquals(List.of("10.49.0.52", "10.49.0.50"), secondaryIps(natXml(natId)), "10.49.0.51 is given up"); + assertEquals("10.49.0.52", eipPrivateIp(eip2), "the same Elastic IP is held at the new address"); + assertEquals("10.49.0.50", eipPrivateIp(eip3)); + + cloudFormation(stack, "DeleteStack", null); + CfnStackWaits.awaitStackDeleted(stack); + ec2("DeleteVpc", Map.of("VpcId", vpcId)); + } + + /** The gateway's secondary private addresses, in the order DescribeNatGateways lists them. */ + private static List secondaryIps(String natXml) { + return XmlParser.extractElementTree(natXml, "natGatewayAddressSet").children().stream() + .filter(item -> "false".equals(item.child("isPrimary").text())) + .map(item -> item.child("privateIp").text()) + .toList(); + } + + /** The private address an associated Elastic IP is held at. */ + private static String eipPrivateIp(String allocationId) { + String xml = ec2("DescribeAddresses", Map.of("AllocationId.1", allocationId)); + assertTrue(XmlParser.extractFirst(xml, "associationId", null) != null, "the Elastic IP is held: " + xml); + return XmlParser.extractFirst(xml, "privateIpAddress", null); + } + + private static String natXml(String natGatewayId) { + return ec2("DescribeNatGateways", Map.of("NatGatewayId.1", natGatewayId)); + } + private static String subnetXml(String subnetId) { return ec2("DescribeSubnets", Map.of("SubnetId.1", subnetId)); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisionerTest.java index bdeafc0fee..84ff85453a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisionerTest.java @@ -219,7 +219,7 @@ class Ec2NetworkCfnProvisionerTest { @Test void natGatewayIsCreatedPublicWithNoTags() { 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); + when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", null, List.of(), List.of(), 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()); @@ -238,7 +238,7 @@ class Ec2NetworkCfnProvisionerTest { void natGatewayRecordsTheSubnetAndElasticIpItUsesUnderHiddenKeys() { NatGateway nat = natGateway(NAT_ID); nat.setSubnetId(SUBNET_ID); - when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", null, List.of())).thenReturn(nat); + when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", null, List.of(), List.of(), null, List.of())).thenReturn(nat); Address addr = new Address(); addr.setAllocationId(ALLOC_ID); addr.setPublicIp(PUBLIC_IP); @@ -484,11 +484,11 @@ class Ec2NetworkCfnProvisionerTest { 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(), any()); + verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any(), any(), any(), any()); assertEquals(NAT_ID, same.getPhysicalId()); NatGateway replacement = natGateway("nat-replacement"); - when(ec2.createNatGateway(REGION, "subnet-other", ALLOC_ID, "public", null, List.of())).thenReturn(replacement); + when(ec2.createNatGateway(REGION, "subnet-other", ALLOC_ID, "public", null, List.of(), List.of(), 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()); @@ -622,7 +622,7 @@ class Ec2NetworkCfnProvisionerTest { @Test void aPrivateNatGatewayNeedsNoAllocationAndAPublicOneRequiresIt() { NatGateway nat = natGateway(NAT_ID); - when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), isNull(), any())).thenReturn(nat); + when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), isNull(), eq(List.of()), eq(List.of()), isNull(), any())).thenReturn(nat); StackResource r = resource("AWS::EC2::NatGateway", "Nat"); provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private"), ctx()); @@ -653,35 +653,80 @@ class Ec2NetworkCfnProvisionerTest { 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()); + verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any(), any(), any(), any()); + } + + /** + * The three secondary-address properties reach CreateNatGateway, each secondary Elastic IP is + * recorded as held, and the gateway is kept whether or not they change. + */ + @Test + void aNatGatewayIsCreatedWithItsSecondaryAddressesAndChangedOnesUpdateItInPlace() { + String secondaryAlloc = "eipalloc-0fedcba9876543210"; + NatGateway nat = natGateway(NAT_ID, "eni-0123456789abcdef0", "10.0.1.50"); + nat.setSubnetId(SUBNET_ID); + nat.setAllocationId(ALLOC_ID); + nat.setConnectivityType("public"); + nat.getNatGatewayAddresses().get(0).setAllocationId(ALLOC_ID); + NatGatewayAddress secondary = new NatGatewayAddress(); + secondary.setPrimary(false); + secondary.setNetworkInterfaceId("eni-0123456789abcdef0"); + secondary.setPrivateIp("10.0.1.70"); + secondary.setAllocationId(secondaryAlloc); + secondary.setPublicIp("203.0.113.70"); + nat.getNatGatewayAddresses().add(secondary); + when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", null, List.of(secondaryAlloc), + List.of("10.0.1.70"), null, List.of())).thenReturn(nat); + ObjectNode props = mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID); + props.putArray("SecondaryAllocationIds").add(secondaryAlloc); + props.putArray("SecondaryPrivateIpAddresses").add("10.0.1.70"); + StackResource r = resource("AWS::EC2::NatGateway", "Nat"); + + provisioner.provision(r, props, ctx()); + + assertEquals(NAT_ID, r.getPhysicalId()); + assertEquals("203.0.113.70", r.getAttributes().get(CfnRollback.USES_ATTR_PREFIX + "SecondaryPublicIp.0")); + + when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat)); + 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()).updateNatGatewaySecondaryAddresses(any(), any(), any(), any(), any()); + + when(ec2.updateNatGatewaySecondaryAddresses(REGION, NAT_ID, List.of(), List.of(), null)) + .thenReturn(natGateway(NAT_ID, "eni-0123456789abcdef0", "10.0.1.50")); + StackResource changed = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID)); + provisioner.provision(changed, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), + ctx(NAT_ID)); + verify(ec2).updateNatGatewaySecondaryAddresses(REGION, NAT_ID, List.of(), List.of(), null); + verify(ec2).createNatGateway(any(), any(), any(), any(), any(), any(), any(), any(), any()); + assertEquals(NAT_ID, changed.getPhysicalId(), "changed secondaries keep the gateway"); + assertFalse(changed.getAttributes().containsKey(CfnRollback.USES_ATTR_PREFIX + "SecondaryPublicIp.0")); } @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()); + void aPrivateNatGatewayPassesItsSecondaryAddressCount() { + when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", null, List.of(), List.of(), "2", 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("SecondaryPrivateIpAddressCount", 2), ctx()); + + assertEquals(NAT_ID, r.getPhysicalId()); } @Test void aNatGatewayIsCreatedWithThePrivateIpAddressTheTemplateNames() { - when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.50", List.of())) + when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.50", List.of(), List.of(), null, 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()); + verify(ec2).createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.50", List.of(), List.of(), null, List.of()); assertEquals(NAT_ID, r.getPhysicalId()); } @@ -702,9 +747,9 @@ class Ec2NetworkCfnProvisionerTest { provisioner.provision(kept, props, ctx(NAT_ID)); assertEquals(NAT_ID, kept.getPhysicalId()); } - verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any()); + verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any(), any(), any(), any()); - when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.60", List.of())) + when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.60", List.of(), List.of(), null, 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)); @@ -720,7 +765,7 @@ class Ec2NetworkCfnProvisionerTest { nat.setConnectivityType("public"); when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat)); 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); + when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), isNull(), eq(List.of()), eq(List.of()), isNull(), any())).thenReturn(replacement); StackResource r = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID, "EniId", "eni-0123456789abcdef0")); @@ -735,14 +780,14 @@ class Ec2NetworkCfnProvisionerTest { @Test void natGatewayTagsGoThroughItsCreateCall() { NatGateway nat = natGateway(NAT_ID); - when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), isNull(), any())).thenReturn(nat); + when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), isNull(), eq(List.of()), eq(List.of()), 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> tags = ArgumentCaptor.forClass(List.class); - verify(ec2).createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), isNull(), tags.capture()); + verify(ec2).createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), isNull(), eq(List.of()), eq(List.of()), isNull(), tags.capture()); assertEquals(List.of("Name=nat"), pairs(tags.getValue())); verify(ec2, never()).createTags(any(), any(), any()); } @@ -987,7 +1032,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(), any()); + verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any(), any(), any(), any()); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2NatGatewayAddressIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2NatGatewayAddressIntegrationTest.java index 9ba3acf5c4..f54d0f65fb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2NatGatewayAddressIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2NatGatewayAddressIntegrationTest.java @@ -8,11 +8,13 @@ import java.util.List; import java.util.Map; import static io.github.hectorvent.floci.testing.Ec2Requests.ec2; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.matchesRegex; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * A NAT gateway's natGatewayAddressSet carried only an allocation id. aws_nat_gateway exposes @@ -240,23 +242,138 @@ class Ec2NatGatewayAddressIntegrationTest { } /** - * 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. + * A public gateway's secondary Elastic IP is reported after the primary address, on the same + * interface, with the private address it was paired with. DescribeAddresses and + * DescribeNetworkInterfaces show it held, it cannot be released while the gateway holds it, + * and deleting the gateway hands it back. */ @Test - void theSecondaryAddressParametersAreRefused() { + void aPublicGatewayHoldsItsSecondaryElasticIpUntilDeleted() { String subnetId = subnetId(); - for (Map 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() + String primary = allocate(); + Response secondaryAllocation = allocation(); + String secondary = secondaryAllocation.path("AllocateAddressResponse.allocationId"); + String secondaryPublicIp = secondaryAllocation.path("AllocateAddressResponse.publicIp"); + + String natGatewayId = createNat(Map.of("SubnetId", subnetId, "AllocationId", primary, + "SecondaryAllocationId.1", secondary, "SecondaryPrivateIpAddress.1", "10.94.1.71")).then() + .statusCode(200) + .extract().path("CreateNatGatewayResponse.natGateway.natGatewayId"); + + Response described = ec2("DescribeNatGateways", ACCOUNT_ID, REGION) + .formParam("NatGatewayId.1", natGatewayId).post("/") + .then().statusCode(200) + .body(ADDRESSES + ".size()", equalTo(2)) + .body(ADDRESSES + "[0].allocationId", equalTo(primary)) + .body(ADDRESSES + "[0].isPrimary", equalTo("true")) + .body(ADDRESSES + "[1].allocationId", equalTo(secondary)) + .body(ADDRESSES + "[1].publicIp", equalTo(secondaryPublicIp)) + .body(ADDRESSES + "[1].privateIp", equalTo("10.94.1.71")) + .body(ADDRESSES + "[1].associationId", startsWith("eipassoc-")) + .body(ADDRESSES + "[1].isPrimary", equalTo("false")) + .body(ADDRESSES + "[1].status", equalTo("succeeded")) + .extract().response(); + String eniId = described.path(ADDRESSES + "[0].networkInterfaceId"); + String associationId = described.path(ADDRESSES + "[1].associationId"); + String secondaryEniId = described.path(ADDRESSES + "[1].networkInterfaceId"); + assertEquals(eniId, secondaryEniId); + + ec2("DescribeNetworkInterfaces", ACCOUNT_ID, REGION).formParam("NetworkInterfaceId.1", eniId).post("/") + .then().statusCode(200) + .body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()", equalTo(1)) + .body(ENI_IPS + ".size()", equalTo(2)) + .body(ENI_IPS + "[1].privateIpAddress", equalTo("10.94.1.71")) + .body(ENI_IPS + "[1].primary", equalTo("false")) + .body(ENI_IPS + "[1].association.allocationId", equalTo(secondary)); + ec2("DescribeAddresses", ACCOUNT_ID, REGION).formParam("AllocationId.1", secondary).post("/") + .then().statusCode(200) + .body("DescribeAddressesResponse.addressesSet.item.associationId", equalTo(associationId)) + .body("DescribeAddressesResponse.addressesSet.item.networkInterfaceId", equalTo(eniId)) + .body("DescribeAddressesResponse.addressesSet.item.privateIpAddress", equalTo("10.94.1.71")); + ec2("ReleaseAddress", ACCOUNT_ID, REGION).formParam("AllocationId", secondary).post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidIPAddress.InUse")); + // A second gateway cannot take the secondary Elastic IP either. + createNat(Map.of("SubnetId", subnetId, "AllocationId", allocate(), "SecondaryAllocationId.1", secondary)) + .then().statusCode(200) + .body("CreateNatGatewayResponse.natGateway.state", equalTo("failed")) + .body("CreateNatGatewayResponse.natGateway.failureCode", equalTo("Resource.AlreadyAssociated")); + + ec2("DeleteNatGateway", ACCOUNT_ID, REGION).formParam("NatGatewayId", natGatewayId).post("/") + .then().statusCode(200); + ec2("DescribeAddresses", ACCOUNT_ID, REGION).formParam("AllocationId.1", secondary).post("/") + .then().statusCode(200) + .body(not(containsString(""))) + .body(not(containsString(""))); + ec2("ReleaseAddress", ACCOUNT_ID, REGION).formParam("AllocationId", secondary).post("/") + .then().statusCode(200); + } + + /** + * A private gateway takes listed secondary private addresses and SecondaryPrivateIpAddressCount + * more that the subnet picks, every one distinct and none public. + */ + @Test + void aPrivateGatewayTakesListedAndCountedSecondaryAddresses() { + String subnetId = subnetId(); + String natGatewayId = createNat(Map.of("SubnetId", subnetId, "ConnectivityType", "private", + "SecondaryPrivateIpAddress.1", "10.94.1.80", "SecondaryPrivateIpAddressCount", "2")).then() + .statusCode(200) + .extract().path("CreateNatGatewayResponse.natGateway.natGatewayId"); + + Response described = ec2("DescribeNatGateways", ACCOUNT_ID, REGION) + .formParam("NatGatewayId.1", natGatewayId).post("/") + .then().statusCode(200) + .body(ADDRESSES + ".size()", equalTo(4)) + .body(ADDRESSES + ".isPrimary.list()", equalTo(List.of("true", "false", "false", "false"))) + .body(ADDRESSES + "[1].privateIp", equalTo("10.94.1.80")) + .body(not(containsString(""))) + .extract().response(); + List privateIps = described.path(ADDRESSES + ".privateIp.list()"); + assertEquals(4, privateIps.stream().distinct().count(), privateIps.toString()); + privateIps.forEach(ip -> assertThat(ip, matchesRegex("10\\.94\\.1\\.\\d+"))); + List enis = described.path(ADDRESSES + ".networkInterfaceId.list()"); + assertEquals(1, enis.stream().distinct().count(), enis.toString()); + + // The subnet now holds them: a later request for one of them fails. + createNat(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "PrivateIpAddress", privateIps.get(3))) + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidIPAddress.InUse")); + } + + /** + * The EC2 API reference marks SecondaryPrivateIpAddressCount "[Private NAT gateway only]" with + * a valid range of 1 to 31, and a private gateway takes no Elastic IP. A refused request + * creates nothing. + */ + @Test + void secondaryAddressesOutsideTheirRulesAreRefused() { + String subnetId = subnetId(); + for (Map.Entry, String> c : List.of( + Map.entry(Map.of("SubnetId", subnetId, "AllocationId", allocate(), "SecondaryPrivateIpAddressCount", "1"), + "InvalidParameterCombination"), + Map.entry(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryAllocationId.1", allocate()), + "InvalidParameterCombination"), + Map.entry(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryPrivateIpAddressCount", "0"), + "InvalidParameterValue"), + Map.entry(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryPrivateIpAddressCount", "32"), + "InvalidParameterValue"), + Map.entry(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryPrivateIpAddress.1", "10.94.2.9"), + "InvalidParameterValue"), + Map.entry(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "PrivateIpAddress", "10.94.1.90", + "SecondaryPrivateIpAddress.1", "10.94.1.90"), "InvalidIPAddress.InUse"), + Map.entry(Map.of("SubnetId", subnetId, "AllocationId", allocate(), + "SecondaryAllocationId.1", "eipalloc-0fedcba9876543210"), "InvalidAllocationID.NotFound"))) { + createNat(c.getKey()).then() .statusCode(400) - .body("Response.Errors.Error.Code", equalTo("UnsupportedOperation")); + .body("Response.Errors.Error.Code", equalTo(c.getValue())); } assertNatGatewaysIn(subnetId, 0); } + private static final String ADDRESSES = "DescribeNatGatewaysResponse.natGatewaySet.item.natGatewayAddressSet.item"; + private static final String ENI_IPS = "DescribeNetworkInterfacesResponse.networkInterfaceSet.item.privateIpAddressesSet.item"; + private static Response allocation() { return ec2("AllocateAddress", ACCOUNT_ID, REGION).formParam("Domain", "vpc").post("/") .then().statusCode(200).extract().response(); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index 6be072473e..358f1528bc 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -123,6 +123,7 @@ import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.ED25519 import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.RSA_FINGERPRINT; import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.RSA_KEY; import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.TRUNCATED_RSA_KEY; +import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -2622,6 +2623,154 @@ class Ec2ServiceTest { .getFirst().getAssociationId(), "delete must still release the gateway's Elastic IP"); } + /** + * A secondary-address update that read the gateway before a delete finished must not write it + * back: the delete runs while the update waits for the allocation lock, and another gateway + * takes the released primary Elastic IP meanwhile. + */ + @Test + void aSecondaryAddressUpdateDoesNotBringBackAGatewayDeletedUnderIt() throws Exception { + Ec2Service service = mockModeService(); + String region = "us-east-1"; + String subnetId = service.describeSubnets(region, List.of(), Map.of()).getFirst().getSubnetId(); + String primary = service.allocateAddress(region).getAllocationId(); + String secondary = service.allocateAddress(region).getAllocationId(); + String added = service.allocateAddress(region).getAllocationId(); + String natId = service.createNatGateway(region, subnetId, primary, "public", null, List.of(secondary), + List.of(), null, List.of()).getNatGatewayId(); + Field lockField = Ec2Service.class.getDeclaredField("privateIpAllocationLock"); + lockField.setAccessible(true); + Object lock = lockField.get(service); + AtomicReference updater = new AtomicReference<>(); + ExecutorService worker = Executors.newSingleThreadExecutor(); + try { + Future updating; + String other; + synchronized (lock) { + updating = worker.submit(() -> { + updater.set(Thread.currentThread()); + service.updateNatGatewaySecondaryAddresses(region, natId, List.of(added), List.of(), null); + }); + awaitBlockedOrDone(updater, updating); + assertFalse(updating.isDone(), "the update must wait for the allocation lock"); + service.deleteNatGateway(region, natId); + other = service.createNatGateway(region, subnetId, primary, "public", List.of()).getNatGatewayId(); + } + ExecutionException e = assertThrows(ExecutionException.class, () -> updating.get(5, TimeUnit.SECONDS)); + assertEquals("NatGatewayNotFound", ((AwsException) e.getCause()).getErrorCode()); + + assertTrue(service.describeNatGateways(region, List.of(), Map.of()).stream() + .noneMatch(g -> natId.equals(g.getNatGatewayId())), "the deleted gateway stays deleted"); + NatGateway taker = service.describeNatGateways(region, List.of(other), Map.of()).getFirst(); + assertEquals(taker.getNatGatewayAddresses().getFirst().getAssociationId(), + service.describeAddresses(region, List.of(primary), Map.of()).getFirst().getAssociationId(), + "the primary Elastic IP stays with the gateway that took it"); + for (String free : List.of(secondary, added)) { + assertNull(service.describeAddresses(region, List.of(free), Map.of()).getFirst().getAssociationId(), + free + " is not held again"); + } + } finally { + worker.shutdownNow(); + assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS)); + } + } + + /** + * A NAT gateway whose addresses run out part way gives back the lease it took on the VPC + * network. The subnet is a /28, eleven assignable addresses, and 31 more are asked for. + */ + @Test + void aNatGatewayCreateThatRunsOutOfAddressesGivesBackTheLeaseItTook() { + VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class); + Ec2Service service = mockedVpcNetworkService(vpcNetworks); + String subnetId = privateSubnet(service, "us-east-1", "10.60.0.0/28"); + when(vpcNetworks.allocatePrivateIp("us-east-1", subnetId)) + .thenReturn(Optional.of("10.60.0.5"), Optional.empty()); + + AwsException e = assertThrows(AwsException.class, () -> service.createNatGateway("us-east-1", subnetId, + null, "private", null, List.of(), List.of(), "31", List.of())); + assertEquals("InsufficientFreeAddressesInSubnet", e.getErrorCode()); + verify(vpcNetworks).releasePrivateIp("us-east-1", subnetId, "10.60.0.5"); + assertTrue(service.describeNatGateways("us-east-1", List.of(), Map.of()).isEmpty()); + } + + /** The same on a secondary-address update, which also leaves the gateway as it was. */ + @Test + void aNatGatewayUpdateThatRunsOutOfAddressesGivesBackTheLeaseItTook() { + VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class); + Ec2Service service = mockedVpcNetworkService(vpcNetworks); + String subnetId = privateSubnet(service, "us-east-1", "10.60.0.0/28"); + when(vpcNetworks.allocatePrivateIp("us-east-1", subnetId)) + .thenReturn(Optional.of("10.60.0.6"), Optional.of("10.60.0.7"), Optional.empty()); + NatGateway nat = service.createNatGateway("us-east-1", subnetId, null, "private", List.of()); + assertEquals("10.60.0.6", nat.getNatGatewayAddresses().getFirst().getPrivateIp()); + + AwsException e = assertThrows(AwsException.class, () -> service.updateNatGatewaySecondaryAddresses( + "us-east-1", nat.getNatGatewayId(), List.of(), List.of(), "31")); + assertEquals("InsufficientFreeAddressesInSubnet", e.getErrorCode()); + verify(vpcNetworks).releasePrivateIp("us-east-1", subnetId, "10.60.0.7"); + assertEquals(List.of("10.60.0.6"), service.describeNatGateways("us-east-1", List.of(nat.getNatGatewayId()), + Map.of()).getFirst().getNatGatewayAddresses().stream().map(NatGatewayAddress::getPrivateIp).toList(), + "the gateway keeps only its primary address"); + } + + /** + * CreateTags writes a NAT gateway back under the gateway's tag lock, which DeleteNatGateway + * does not take, so a tag write that read the gateway before a delete stores the record the + * delete marked deleted. A secondary-address update must refuse that record rather than hold + * Elastic IPs for it. + */ + @Test + void aSecondaryAddressUpdateRefusesAGatewayStoredAsDeleted() throws Exception { + CountDownLatch putReached = new CountDownLatch(1); + CountDownLatch deleteDone = new CountDownLatch(1); + AtomicReference pausePut = new AtomicReference<>(false); + InMemoryStorage rawGateways = new InMemoryStorage<>() { + @Override + public void put(String key, NatGateway value) { + if (pausePut.getAndSet(false)) { + putReached.countDown(); + try { + assertTrue(deleteDone.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + super.put(key, value); + } + }; + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(Map.of("ec2-nat-gateways.json", + new AccountAwareStorageBackend<>(rawGateways, null, "000000000000")))); + String region = "us-east-1"; + String subnetId = service.describeSubnets(region, List.of(), Map.of()).getFirst().getSubnetId(); + String primary = service.allocateAddress(region).getAllocationId(); + String added = service.allocateAddress(region).getAllocationId(); + String natId = service.createNatGateway(region, subnetId, primary, "public", List.of()).getNatGatewayId(); + ExecutorService worker = Executors.newSingleThreadExecutor(); + try { + pausePut.set(true); + Future tagging = worker.submit(() -> service.createTags(region, List.of(natId), + List.of(new Tag("k", "v")))); + assertTrue(putReached.await(5, TimeUnit.SECONDS), "the tag write reaches its put"); + service.deleteNatGateway(region, natId); + deleteDone.countDown(); + tagging.get(5, TimeUnit.SECONDS); + assertEquals("deleted", rawGateways.scan(k -> true).getFirst().getState(), + "the tag write stored the deleted gateway"); + + AwsException e = assertThrows(AwsException.class, () -> service.updateNatGatewaySecondaryAddresses( + region, natId, List.of(added), List.of(), null)); + assertEquals("NatGatewayNotFound", e.getErrorCode()); + assertNull(service.describeAddresses(region, List.of(added), Map.of()).getFirst().getAssociationId(), + "the requested Elastic IP is not held for the deleted gateway"); + } finally { + worker.shutdownNow(); + assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS)); + } + } + /** * A gateway persisted before account isolation (unprefixed key) still holds its Elastic IP: * a second gateway is created failed, and ReleaseAddress answers InvalidIPAddress.InUse. diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index e09f5e1805..b7b01587d1 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -190,7 +190,7 @@ notes: 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::KeyPair: 'a created key''s private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key' - AWS::EC2::NatGateway: 'zonal, primary address only; `AvailabilityMode` regional and the `Secondary*` address properties fail' + AWS::EC2::NatGateway: 'zonal; `AvailabilityMode` regional fails; a change to the `Secondary*` address properties updates the gateway in place' 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