diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2RunInstancesPrivateIpTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2RunInstancesPrivateIpTest.java new file mode 100644 index 0000000000..a9ec7aa4b1 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2RunInstancesPrivateIpTest.java @@ -0,0 +1,234 @@ +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.Ec2Exception; +import software.amazon.awssdk.services.ec2.model.Instance; +import software.amazon.awssdk.services.ec2.model.InstanceType; +import software.amazon.awssdk.services.ec2.model.LaunchTemplateSpecification; +import software.amazon.awssdk.services.ec2.model.PrivateIpAddressSpecification; +import software.amazon.awssdk.services.ec2.model.RequestLaunchTemplateData; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class Ec2RunInstancesPrivateIpTest { + private static final String COMBINATION_MESSAGE = + "Network interfaces and an instance-level private IP address may not be specified on the same request"; + + @Test + @DisplayName("RunInstances gives the instance the PrivateIpAddress it asked for and refuses one in use") + void launchesAtTheRequestedPrivateIp() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.76.0.0/16")).vpc().vpcId(); + String subnetId = null; + List instanceIds = new ArrayList<>(); + try { + subnetId = ec2.createSubnet(r -> r.vpcId(vpcId).cidrBlock("10.76.1.0/24")) + .subnet().subnetId(); + String subnet = subnetId; + + for (String requested : List.of("10.76.1.50", "10.76.1.60")) { + Instance launched = ec2.runInstances(r -> r.imageId("ami-0abcdef1234567890") + .instanceType(InstanceType.T3_MICRO).minCount(1).maxCount(1) + .subnetId(subnet).privateIpAddress(requested)).instances().get(0); + instanceIds.add(launched.instanceId()); + assertThat(launched.privateIpAddress()).isEqualTo(requested); + + Instance described = ec2.describeInstances(r -> r.instanceIds(launched.instanceId())) + .reservations().get(0).instances().get(0); + assertThat(described.privateIpAddress()).isEqualTo(requested); + assertThat(described.networkInterfaces()).singleElement() + .satisfies(eni -> assertThat(eni.privateIpAddress()).isEqualTo(requested)); + } + + Ec2Exception inUse = assertThrows(Ec2Exception.class, () -> ec2.runInstances(r -> + r.imageId("ami-0abcdef1234567890").instanceType(InstanceType.T3_MICRO) + .minCount(1).maxCount(1).subnetId(subnet).privateIpAddress("10.76.1.50"))); + assertThat(inUse.statusCode()).isEqualTo(400); + assertThat(inUse.awsErrorDetails().errorCode()).isEqualTo("InvalidIPAddress.InUse"); + + Ec2Exception outside = assertThrows(Ec2Exception.class, () -> ec2.runInstances(r -> + r.imageId("ami-0abcdef1234567890").instanceType(InstanceType.T3_MICRO) + .minCount(1).maxCount(1).subnetId(subnet).privateIpAddress("10.76.2.50"))); + assertThat(outside.statusCode()).isEqualTo(400); + assertThat(outside.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterValue"); + + // Neither refusal leaves an instance behind in the subnet. + assertThat(instanceIdsInSubnet(ec2, subnet)).containsExactlyInAnyOrderElementsOf(instanceIds); + } finally { + if (!instanceIds.isEmpty()) { + ec2.terminateInstances(r -> r.instanceIds(instanceIds)); + } + if (subnetId != null) { + String cleanup = subnetId; + ec2.deleteSubnet(r -> r.subnetId(cleanup)); + } + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + @Test + @DisplayName("RunInstances takes the address of the Primary PrivateIpAddresses entry on the interface spec") + void launchesAtThePrimaryEntryOfTheInterfaceSpec() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.78.0.0/16")).vpc().vpcId(); + String subnetId = null; + String instanceId = null; + try { + subnetId = ec2.createSubnet(r -> r.vpcId(vpcId).cidrBlock("10.78.1.0/24")) + .subnet().subnetId(); + String subnet = subnetId; + String requested = "10.78.1.50"; + + // The shape the AWS CLI sends for --private-ip-address with --associate-public-ip-address. + Instance launched = ec2.runInstances(r -> r.imageId("ami-0abcdef1234567890") + .instanceType(InstanceType.T3_MICRO).minCount(1).maxCount(1) + .networkInterfaces(n -> n.deviceIndex(0).subnetId(subnet).associatePublicIpAddress(true) + .privateIpAddresses(PrivateIpAddressSpecification.builder() + .primary(true).privateIpAddress(requested).build()))) + .instances().get(0); + instanceId = launched.instanceId(); + assertThat(launched.privateIpAddress()).isEqualTo(requested); + + Instance described = ec2.describeInstances(r -> r.instanceIds(launched.instanceId())) + .reservations().get(0).instances().get(0); + assertThat(described.privateIpAddress()).isEqualTo(requested); + assertThat(described.networkInterfaces()).singleElement() + .satisfies(eni -> assertThat(eni.privateIpAddress()).isEqualTo(requested)); + } finally { + if (instanceId != null) { + String cleanupInstance = instanceId; + ec2.terminateInstances(r -> r.instanceIds(cleanupInstance)); + } + if (subnetId != null) { + String cleanup = subnetId; + ec2.deleteSubnet(r -> r.subnetId(cleanup)); + } + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + @Test + @DisplayName("RunInstances from a launch template gives the instance its primary interface's PrivateIpAddress") + void launchesAtTheLaunchTemplateInterfaceAddress() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.79.0.0/16")).vpc().vpcId(); + String subnetId = null; + String templateId = null; + String instanceId = null; + try { + subnetId = ec2.createSubnet(r -> r.vpcId(vpcId).cidrBlock("10.79.1.0/24")) + .subnet().subnetId(); + String subnet = subnetId; + String requested = "10.79.1.70"; + + templateId = ec2.createLaunchTemplate(r -> r.launchTemplateName("fixed-ip-" + UUID.randomUUID()) + .launchTemplateData(RequestLaunchTemplateData.builder() + .imageId("ami-0abcdef1234567890").instanceType(InstanceType.T3_MICRO) + .networkInterfaces(n -> n.deviceIndex(0).subnetId(subnet).privateIpAddress(requested)) + .build())) + .launchTemplate().launchTemplateId(); + LaunchTemplateSpecification template = LaunchTemplateSpecification.builder() + .launchTemplateId(templateId).build(); + + Instance launched = ec2.runInstances(r -> r.launchTemplate(template).minCount(1).maxCount(1)) + .instances().get(0); + instanceId = launched.instanceId(); + assertThat(launched.privateIpAddress()).isEqualTo(requested); + + Instance described = ec2.describeInstances(r -> r.instanceIds(launched.instanceId())) + .reservations().get(0).instances().get(0); + assertThat(described.privateIpAddress()).isEqualTo(requested); + assertThat(described.networkInterfaces()).singleElement() + .satisfies(eni -> assertThat(eni.privateIpAddress()).isEqualTo(requested)); + } finally { + if (instanceId != null) { + String cleanupInstance = instanceId; + ec2.terminateInstances(r -> r.instanceIds(cleanupInstance)); + } + if (templateId != null) { + String cleanupTemplate = templateId; + ec2.deleteLaunchTemplate(r -> r.launchTemplateId(cleanupTemplate)); + } + if (subnetId != null) { + String cleanup = subnetId; + ec2.deleteSubnet(r -> r.subnetId(cleanup)); + } + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + @Test + @DisplayName("RunInstances refuses an instance-level PrivateIpAddress together with network interfaces") + void refusesAnInstanceLevelPrivateIpWithNetworkInterfaces() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.74.0.0/16")).vpc().vpcId(); + String subnetId = null; + String templateId = null; + try { + subnetId = ec2.createSubnet(r -> r.vpcId(vpcId).cidrBlock("10.74.1.0/24")) + .subnet().subnetId(); + String subnet = subnetId; + + Ec2Exception onRequest = assertThrows(Ec2Exception.class, () -> ec2.runInstances(r -> + r.imageId("ami-0abcdef1234567890").instanceType(InstanceType.T3_MICRO) + .minCount(1).maxCount(1).privateIpAddress("10.74.1.80") + .networkInterfaces(n -> n.deviceIndex(0).subnetId(subnet)))); + assertThat(onRequest.statusCode()).isEqualTo(400); + assertThat(onRequest.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterCombination"); + assertThat(onRequest.awsErrorDetails().errorMessage()).isEqualTo(COMBINATION_MESSAGE); + + templateId = ec2.createLaunchTemplate(r -> r.launchTemplateName("fixed-ip-" + UUID.randomUUID()) + .launchTemplateData(RequestLaunchTemplateData.builder() + .imageId("ami-0abcdef1234567890").instanceType(InstanceType.T3_MICRO) + .networkInterfaces(n -> n.deviceIndex(0).subnetId(subnet)) + .build())) + .launchTemplate().launchTemplateId(); + LaunchTemplateSpecification template = LaunchTemplateSpecification.builder() + .launchTemplateId(templateId).build(); + + Ec2Exception onTemplate = assertThrows(Ec2Exception.class, () -> ec2.runInstances(r -> + r.launchTemplate(template).minCount(1).maxCount(1).privateIpAddress("10.74.1.81"))); + assertThat(onTemplate.statusCode()).isEqualTo(400); + assertThat(onTemplate.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterCombination"); + assertThat(onTemplate.awsErrorDetails().errorMessage()).isEqualTo(COMBINATION_MESSAGE); + + assertThat(instanceIdsInSubnet(ec2, subnet)).isEmpty(); + } finally { + // A launch the refusal failed to stop would otherwise block the subnet delete. + if (subnetId != null) { + List launched = instanceIdsInSubnet(ec2, subnetId); + if (!launched.isEmpty()) { + ec2.terminateInstances(r -> r.instanceIds(launched)); + } + } + if (templateId != null) { + String cleanupTemplate = templateId; + ec2.deleteLaunchTemplate(r -> r.launchTemplateId(cleanupTemplate)); + } + if (subnetId != null) { + String cleanup = subnetId; + ec2.deleteSubnet(r -> r.subnetId(cleanup)); + } + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + private static List instanceIdsInSubnet(Ec2Client ec2, String subnetId) { + return ec2.describeInstances(r -> r.filters(f -> f.name("subnet-id").values(subnetId))) + .reservations().stream() + .flatMap(reservation -> reservation.instances().stream()) + .map(Instance::instanceId) + .toList(); + } +} diff --git a/docs/services/ec2.md b/docs/services/ec2.md index e36729d50f..6ce811abc7 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -1117,6 +1117,25 @@ and the last one as AWS reserves them, and skipping every address a persisted in interface or NAT gateway in the subnet still holds, so a restart does not hand one out twice. A subnet with no free address left fails the request with `InsufficientFreeAddressesInSubnet`. +`RunInstances` with `PrivateIpAddress`, or `NetworkInterface.1.PrivateIpAddress` (the shape +Terraform's `aws_instance` sends for `private_ip` with a `subnet_id`), gives the instance and its +primary network interface that address instead of the next free one. So does the +`NetworkInterface.1.PrivateIpAddresses` entry marked `Primary`, the shape the AWS CLI sends for +`--private-ip-address` together with `--associate-public-ip-address` or the secondary-address +options, and the `PrivateIpAddress` of a launch template's primary interface. Secondary addresses, +from `PrivateIpAddresses` entries not marked `Primary` or from `SecondaryPrivateIpAddressCount`, are +not applied. 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`. In a Docker-backed default subnet, whose +network every account shares, that includes an address another account's instance, network interface +or NAT gateway holds. As on AWS it applies only to a single instance that creates its own primary +interface: with more than one instance, or with `NetworkInterface.1.NetworkInterfaceId`, the call +fails with `InvalidParameterCombination`, and so does a top-level `PrivateIpAddress` sent with +network interfaces, from the request or the launch template. In a Docker-backed subnet the container +joins the VPC network at that address. In a subnet whose CIDR was substituted the address lies +outside the network's range, so the container cannot hold it, and the instance reports its bridge +address unless `FLOCI_SERVICES_EC2_AWS_FAITHFUL_PRIVATE_IP` is true, as for a synthesised address. + `CreateSubnet` derives `AvailableIpAddressCount` from the IPv4 CIDR, excluding the five AWS-reserved addresses. `DescribeSubnets` subtracts addresses currently held by instances, network interfaces, NAT gateways and interface endpoints. ASG diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java index 907b831ae0..0331f604c9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java @@ -17,7 +17,9 @@ import io.github.hectorvent.floci.services.ec2.model.Tag; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Base64; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -35,9 +37,10 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner { private static final String INSTANCE = "AWS::EC2::Instance"; - // Declared values of createOnly properties the launch does not apply to the instance, recorded - // so a later update can tell a genuine change from the instance's auto-assigned value. The - // __Floci prefix keeps them off the published Fn::GetAtt attributes. + // Declared values of createOnly properties, recorded so a later update compares against what + // the template declared rather than what the instance carries: the launch does not apply + // AvailabilityZone, and an instance a stack launched before PrivateIpAddress was applied holds + // an auto-assigned address. The __Floci prefix keeps them off the published Fn::GetAtt attributes. private static final String DECLARED_PRIVATE_IP_ATTR = "__FlociDeclaredPrivateIpAddress"; private static final String DECLARED_AZ_ATTR = "__FlociDeclaredAvailabilityZone"; // The instance profile the template declared last time, so an update that drops the property @@ -132,12 +135,12 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner { // On update, keep the existing instance unless a createOnly property changed: a changed // ImageId, SubnetId or KeyName replaces it (compared against the instance, which carries // them), as does a changed PrivateIpAddress or AvailabilityZone (compared against the value - // declared last time, since the launch does not apply those to the instance). A mutable-only - // change (tags, and the like) reuses it. Launching unconditionally would leak the prior - // instance every update. A changed LaunchTemplate reuses it too, where AWS replaces the - // instance: the change-set preview and the template's own versioning would have to agree on - // that property first. What the template declares is reconciled in place instead, unless - // the ImageId or KeyName it supplies changed, which replaces the instance as above. + // declared last time, see DECLARED_PRIVATE_IP_ATTR). A mutable-only change (tags, and the + // like) reuses it. Launching unconditionally would leak the prior instance every update. A + // changed LaunchTemplate reuses it too, where AWS replaces the instance: the change-set + // preview and the template's own versioning would have to agree on that property first. + // What the template declares is reconciled in place instead, unless the ImageId or KeyName + // it supplies changed, which replaces the instance as above. Instance prior = ctx.isUpdate() ? findInstance(region, ctx.priorPhysicalId()) : null; if (prior != null && !createOnlyChanged(prior, imageId, subnetId, keyName) && !declaredCreateOnlyChanged(attributesBefore, privateIpAddress, availabilityZone)) { @@ -190,9 +193,15 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner { if (ctx.isUpdate()) { r.getAttributes().put(PRIOR_DECLARATIONS_ATTR, declarations(attributesBefore)); } + // The options a template cannot set keep the defaults the shorter runInstances overloads + // give them. A replacement that keeps its PrivateIpAddress fails with InvalidIPAddress.InUse + // while the prior instance still holds it, as on AWS, which creates the replacement first. + String encodedUserData = userData == null ? null + : Base64.getEncoder().encodeToString(userData.getBytes(StandardCharsets.UTF_8)); Reservation reservation = ec2Service.runInstances(region, imageId, instanceType, 1, 1, keyName, securityGroupIds, subnetId, null, tags, userData, iamInstanceProfileArn, - associatePublicIp, null, 0, null, metadataOptions); + associatePublicIp, null, 0, null, metadataOptions, null, encodedUserData, false, null, null, null, + false, privateIpAddress); Instance instance = reservation.getInstances().get(0); r.setPhysicalId(instance.getInstanceId()); r.getAttributes().put("InstanceId", instance.getInstanceId()); @@ -353,12 +362,12 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner { } /** - * Whether a createOnly property the launch does not apply to the instance (PrivateIpAddress, - * AvailabilityZone) changed since the last provision. It is compared against the value declared - * then and recorded on the resource, not the instance's auto-assigned value, which never matches - * a declared one. A property with no recorded prior value is not treated as changed, so adopting - * this behavior does not replace instances whose template did not actually change; the value is - * recorded from this provision on, and a later change to it then forces replacement. + * Whether a createOnly property recorded as declared (PrivateIpAddress, AvailabilityZone) changed + * since the last provision. It is compared against the value declared then and recorded on the + * resource, not the instance's own, for the reasons given at {@link #DECLARED_PRIVATE_IP_ATTR}. + * A property with no recorded prior value is not treated as changed, so adopting this behavior + * does not replace instances whose template did not actually change; the value is recorded from + * this provision on, and a later change to it then forces replacement. */ private static boolean declaredCreateOnlyChanged(Map priorAttributes, String privateIpAddress, String availabilityZone) { 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 88397d0c63..01c7718a40 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 @@ -770,6 +770,18 @@ public class Ec2QueryHandler { if (subnetId == null) { subnetId = p.getFirst("NetworkInterface.1.SubnetId"); } + // The primary private address arrives in three shapes. Terraform's aws_instance moves + // private_ip onto the interface spec whenever it sends one, and the AWS CLI moves + // --private-ip-address there too, as the primary PrivateIpAddresses entry, once an + // interface-only option such as --associate-public-ip-address builds the spec. The + // top-level form together with any interface spec is refused below. + String privateIpAddress = p.getFirst("NetworkInterface.1.PrivateIpAddress"); + if (!isSet(privateIpAddress)) { + privateIpAddress = primaryPrivateIpAddress(p, "NetworkInterface.1"); + } + if (!isSet(privateIpAddress)) { + privateIpAddress = p.getFirst("PrivateIpAddress"); + } // floci-kt9: override-default-eni hands RunInstances a pre-existing standalone ENI as // the instance's primary interface (network_interface { network_interface_id = ... }). String networkInterfaceId = p.getFirst("NetworkInterface.1.NetworkInterfaceId"); @@ -804,11 +816,16 @@ public class Ec2QueryHandler { LaunchTemplateData launchTemplateData = resolveRunInstancesLaunchTemplateData( p, region, userDataEncoded == null || userDataEncoded.isBlank()); boolean suppliedInterfaces = p.keySet().stream().anyMatch(name -> name.startsWith("NetworkInterface.")); - if (p.getFirst("SubnetId") != null && (suppliedInterfaces - || launchTemplateData != null && !launchTemplateData.getNetworkInterfaces().isEmpty())) { + boolean anyInterfaces = suppliedInterfaces + || launchTemplateData != null && !launchTemplateData.getNetworkInterfaces().isEmpty(); + if (p.getFirst("SubnetId") != null && anyInterfaces) { throw new AwsException("InvalidParameterCombination", "Network interfaces and an instance-level subnet ID may not be specified on the same request", 400); } + if (p.getFirst("PrivateIpAddress") != null && anyInterfaces) { + throw new AwsException("InvalidParameterCombination", + "Network interfaces and an instance-level private IP address may not be specified on the same request", 400); + } if (launchTemplateData != null) { if (marketType == null && launchTemplateData.getInstanceMarketOptions() != null) { marketType = launchTemplateData.getInstanceMarketOptions().getMarketType(); @@ -816,11 +833,12 @@ public class Ec2QueryHandler { blockDeviceMappings = LaunchTemplateData.BlockDeviceMapping.merge( launchTemplateData.getBlockDeviceMappings(), blockDeviceMappings); if (!suppliedInterfaces) { - // With neither request interfaces nor, after the check above, a request SubnetId, - // the template's primary interface places the launch. + // With neither request interfaces nor, after the checks above, a request SubnetId + // or PrivateIpAddress, the template's primary interface places the launch. LaunchTemplateData.NetworkInterface primary = launchTemplateData.primaryNetworkInterface(); if (primary != null) { subnetId = primary.getSubnetId(); + privateIpAddress = primary.getPrivateIpAddress(); if (associatePublicIp == null) { associatePublicIp = primary.getAssociatePublicIpAddress(); } @@ -866,7 +884,7 @@ public class Ec2QueryHandler { associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, null, metadataOptions, creditSpecificationCpuCredits, userDataEncoded, Boolean.parseBoolean(p.getFirst("DryRun")), p.getFirst("Placement.HostId"), p.getFirst("Placement.Tenancy"), blockDeviceMappings, - "spot".equals(marketType)); + "spot".equals(marketType), privateIpAddress); if (!networkInterfaceTags.isEmpty()) { List eniIds = new ArrayList<>(); @@ -909,6 +927,23 @@ public class Ec2QueryHandler { throw new AwsException("InvalidParameterValue", name + " must be a positive integer", 400); } + /** + * The address of the {@code PrivateIpAddresses} entry an interface spec marks {@code Primary}, + * or null when it marks none. Secondary entries are not applied. + */ + private static String primaryPrivateIpAddress(MultivaluedMap p, String interfacePrefix) { + for (int i = 1; ; i++) { + String entry = interfacePrefix + ".PrivateIpAddresses." + i; + String address = p.getFirst(entry + ".PrivateIpAddress"); + if (address == null) { + return null; + } + if (Boolean.parseBoolean(p.getFirst(entry + ".Primary"))) { + return address; + } + } + } + private LaunchTemplateData resolveRunInstancesLaunchTemplateData(MultivaluedMap p, String region, boolean decodeUserData) { String id = p.getFirst("LaunchTemplate.LaunchTemplateId"); 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 8a079251db..cacaf47e71 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 @@ -3539,7 +3539,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab securityGroupIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn, associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, availabilityZone, metadataOptions, creditSpecificationCpuCredits, encodedUserData, dryRun, hostId, tenancy, - blockDeviceMappings, false); + blockDeviceMappings, false, null); } Reservation runInstances(String region, String imageId, String instanceType, @@ -3553,6 +3553,35 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab String creditSpecificationCpuCredits, String encodedUserData, boolean dryRun, String hostId, String tenancy, List blockDeviceMappings, boolean spot) { + return runInstances(region, imageId, instanceType, minCount, maxCount, keyName, + securityGroupIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn, + associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, availabilityZone, + metadataOptions, creditSpecificationCpuCredits, encodedUserData, dryRun, hostId, tenancy, + blockDeviceMappings, spot, null); + } + + /** + * @param privateIpAddress PrivateIpAddress: the primary private address of the interface the + * launch creates, or null to let the subnet pick one. It must be an + * assignable address of the subnet that no other resource holds, and + * AWS accepts it only for a single instance launched without an + * existing network interface. + */ + public Reservation runInstances(String region, String imageId, String instanceType, + int minCount, int maxCount, String keyName, + List securityGroupIds, String subnetId, + String clientToken, List instanceTags, + String userData, String iamInstanceProfileArn, + Boolean associatePublicIp, String networkInterfaceId, + int networkInterfaceDeviceIndex, String availabilityZone, + LaunchTemplateData.MetadataOptions metadataOptions, + String creditSpecificationCpuCredits, String encodedUserData, boolean dryRun, + String hostId, String tenancy, + List blockDeviceMappings, boolean spot, + String privateIpAddress) { + if (privateIpAddress != null && privateIpAddress.isBlank()) { + privateIpAddress = null; + } if (hostId != null && !hostId.isBlank()) { Host host = getRequiredAvailableHost(region, hostId); if ((availabilityZone == null || availabilityZone.isBlank()) @@ -3649,6 +3678,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } validateArchitectureCompatibility(region, imageId, effectiveInstanceType); int count = Math.min(maxCount, Math.max(minCount, 1)); + if (privateIpAddress != null) { + privateIpAddress = validateRequestedPrivateIp(privateIpAddress, subnet, suppliedEni, maxCount); + } String architecture = architectureFor(region, imageId, effectiveInstanceType); // An entry with NoDevice set removes its device whatever else it names, as on AWS. List mappedDevices = blockDeviceMappings == null ? List.of() @@ -3699,7 +3731,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // since the unlocked check above. validateHostPlacement(getRequiredAvailableHost(region, hostId), az, effectiveInstanceType, tenancy); } - List privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni, admitted); + List privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni, + privateIpAddress, admitted); for (int i = 0; i < admitted; i++) { String instanceId = "i-" + randomHex(17); String privateIp = privateIps.get(i); @@ -4060,9 +4093,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab * Every private address a launch needs, allocated before any of its instances is stored, so * a subnet without room for the whole launch fails it without leaving the instances that did * fit behind. Callers must hold {@link #privateIpAllocationLock}. + * + * @param requestedPrivateIp the launch's PrivateIpAddress, already checked by + * {@link #validateRequestedPrivateIp}, or null */ private List allocateLaunchAddresses(String region, String subnetId, NetworkInterface suppliedEni, - int count) { + String requestedPrivateIp, int count) { List addresses = new ArrayList<>(count); if (suppliedEni != null) { for (int i = 0; i < count; i++) { @@ -4070,6 +4106,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } return addresses; } + if (requestedPrivateIp != null) { + claimRequestedPrivateIp(region, subnetId, requestedPrivateIp); + addresses.add(requestedPrivateIp); + return addresses; + } try { for (int i = 0; i < count; i++) { addresses.add(assignPrivateIp(region, subnetId, addresses)); @@ -4117,12 +4158,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab synchronized (privateIpAllocationLock) { // The addresses persisted resources already hold, so a restart, which forgets the // cursor, never hands out an address that is still in use. - Set persistedInUse = privateIpsInUse(region, subnetId); - Set inUse = new HashSet<>(persistedInUse); - // Interface endpoint interfaces are derived, not stored, so the scan above misses them. - if (subnetId != null) { - inUse.addAll(endpointPrivateIpsIn(region, subnetId, persistedInUse)); - } + Set inUse = privateIpsTaken(region, subnetId); inUse.addAll(pending); long start = Math.clamp(subnetIpCursors.getOrDefault(cursorKey, SYNTHETIC_FIRST_OFFSET), first, last); long span = last - first + 1; @@ -4138,6 +4174,91 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab throw insufficientFreeAddresses(subnetId); } + /** + * Checks a launch's PrivateIpAddress before anything is stored. AWS applies it to the primary + * interface the launch creates, so it cannot be combined with an existing interface or with + * more than one instance, and it has to be an address the subnet can assign. Whether another + * resource holds it is checked under the allocation lock, by {@link #claimRequestedPrivateIp}. + * + * @param subnet the launch's subnet, or null when the region has no default subnet to place + * it in, in which case there is no range to check the address against + * @param maxCount the launch's MaxCount. A request that may launch more than one instance is + * refused even when fewer would be launched. + * @return the address in its canonical dotted form. The in-use check, the VPC network's lease + * table and Docker all compare addresses as text, so a zero-padded octet must not make + * one address look like two. + */ + private static String validateRequestedPrivateIp(String privateIpAddress, Subnet subnet, + NetworkInterface suppliedEni, int maxCount) { + if (suppliedEni != null) { + throw new AwsException("InvalidParameterCombination", + "A private IP address may not be specified with an existing network interface.", 400); + } + if (maxCount > 1) { + throw new AwsException("InvalidParameterCombination", + "A private IP address may only be specified for a single instance.", 400); + } + String address = canonicalIpv4(privateIpAddress) + .orElseThrow(() -> new AwsException("InvalidParameterValue", + "Invalid IPv4 address: " + privateIpAddress, 400)); + if (subnet != null) { + requireAssignableSubnetAddress(subnet, address); + } + return address; + } + + /** + * Claims the address a launch named, which {@link #validateRequestedPrivateIp} has already + * placed inside the subnet. Callers must hold {@link #privateIpAllocationLock}. + * + *

The caller's stored resources decide whether the address is in use. A Docker-backed + * subnet also leases it, so the network's own allocator never hands it to a later launch. + * + *

Inside a Docker-backed range, what every account holds counts as well. Default VPC and + * subnet ids are the same in every account, so their Docker network is shared, and another + * account's instance, network interface or NAT gateway there may hold the address with no + * lease to show for it: an interface created with its own address never takes one, and a + * restart re-leases only instances. Any other subnet id belongs to one account, so for it the + * wider scan finds nothing more. A lease with nothing in any account behind it is stale + * (DeleteNetworkInterface and DeleteNatGateway never return theirs) and does not fail the + * launch, and an address outside a substituted subnet's effective range is never leased at + * all, in which case the instance keeps it the way it keeps a synthesised address. + */ + private void claimRequestedPrivateIp(String region, String subnetId, String address) { + if (privateIpsTaken(region, subnetId).contains(address)) { + throw new AwsException("InvalidIPAddress.InUse", "Address " + address + " is in use.", 400); + } + if (vpcNetworkManager == null || subnetId == null) { + return; + } + boolean leasable = vpcNetworkManager.effectiveSubnetCidr(region, subnetId) + .filter(cidr -> Ipv4Cidrs.contains(cidr, address + "/32")) + .isPresent(); + if (!leasable) { + return; + } + if (privateIpsInUseInEveryAccount(region, subnetId).contains(address)) { + throw new AwsException("InvalidIPAddress.InUse", "Address " + address + " is in use.", 400); + } + vpcNetworkManager.claimPrivateIp(region, subnetId, address); + } + + /** {@link #privateIpsInUse}, across every account rather than only the caller's. */ + private Set privateIpsInUseInEveryAccount(String region, String subnetId) { + String regionPrefix = region + "::"; + return privateIpsBySubnet(valuesOfEveryAccount(networkInterfaces, regionPrefix), + valuesOfEveryAccount(instances, regionPrefix), + valuesOfEveryAccount(natGateways, regionPrefix)) + .getOrDefault(subnetId, Set.of()); + } + + private static List valuesOfEveryAccount(StorageBackend store, String keyPrefix) { + return entriesOfEveryAccount(store).stream() + .filter(entry -> entry.key().startsWith(keyPrefix)) + .map(AccountAwareStorageBackend.AccountEntry::value) + .toList(); + } + private static AwsException insufficientFreeAddresses(String subnetId) { return new AwsException("InsufficientFreeAddressesInSubnet", "There are not enough free addresses in subnet '" + subnetId + "' to satisfy the requested number of instances.", @@ -4149,17 +4270,36 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return new HashSet<>(privateIpsBySubnet(region).getOrDefault(subnetId, Set.of())); } + /** {@link #privateIpsInUse}, plus the addresses of the subnet's interface endpoint interfaces. */ + private Set privateIpsTaken(String region, String subnetId) { + Set persistedInUse = privateIpsInUse(region, subnetId); + Set taken = new HashSet<>(persistedInUse); + // Interface endpoint interfaces are derived, not stored, so the scan above misses them. + if (subnetId != null) { + taken.addAll(endpointPrivateIpsIn(region, subnetId, persistedInUse)); + } + return taken; + } + private Map> privateIpsBySubnet(String region) { String regionPrefix = region + "::"; + return privateIpsBySubnet(networkInterfaces.scan(k -> k.startsWith(regionPrefix)), + instances.scan(k -> k.startsWith(regionPrefix)), + natGateways.scan(k -> k.startsWith(regionPrefix))); + } + + private static Map> privateIpsBySubnet(List regionInterfaces, + List regionInstances, + List regionNatGateways) { Map> bySubnet = new HashMap<>(); - for (NetworkInterface ni : networkInterfaces.scan(k -> k.startsWith(regionPrefix))) { + for (NetworkInterface ni : regionInterfaces) { Set inUse = bySubnet.computeIfAbsent(ni.getSubnetId(), ignored -> new HashSet<>()); addIfSet(inUse, ni.getPrivateIpAddress()); for (NetworkInterfacePrivateIpAddress ip : nullToEmpty(ni.getPrivateIpAddresses())) { addIfSet(inUse, ip.getPrivateIpAddress()); } } - for (Instance instance : instances.scan(k -> k.startsWith(regionPrefix))) { + for (Instance instance : regionInstances) { String state = instance.getState() == null ? null : instance.getState().getName(); if ("terminated".equals(state)) { continue; @@ -4171,7 +4311,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab ni.getPrivateIpAddress()); } } - for (NatGateway natGateway : natGateways.scan(k -> k.startsWith(regionPrefix))) { + for (NatGateway natGateway : regionNatGateways) { if ("deleted".equals(natGateway.getState())) { continue; } @@ -4189,10 +4329,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab private static void addIfSet(Set addresses, String address) { if (address != null && !address.isBlank()) { - addresses.add(address); + // CreateNetworkInterface keeps its address as given, so a zero-padded octet has to be + // folded here for the in-use checks to see one address rather than two. + addresses.add(canonicalIpv4(address).orElse(address)); } } + /** {@code address} in canonical dotted form, or empty when it is not an IPv4 address. */ + private static Optional canonicalIpv4(String address) { + return Cidr4.parse(address + "/32").map(host -> Cidr4.format(host.network())); + } + public List describeInstances(String region, List instanceIds, Map> filters) { ensureDefaultResources(region); if (!instanceIds.isEmpty()) { @@ -6019,21 +6166,30 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (ipv4 == null || ipv4.isBlank()) { continue; } - String host = ipv4 + "/32"; - if (!Ipv4Cidrs.isIpv4(host)) { - throw new AwsException("InvalidParameterValue", - "Invalid IPv4 address: " + ipv4, 400); - } - if (subnet.getCidrBlock() == null || !Ipv4Cidrs.contains(subnet.getCidrBlock(), host)) { - throw new AwsException("InvalidParameterValue", - "Address " + ipv4 + " does not fall within the address range of subnet " - + subnet.getSubnetId(), 400); - } - if (Ipv4Cidrs.isSubnetReserved(subnet.getCidrBlock(), host)) { - throw new AwsException("InvalidParameterValue", - "Address " + ipv4 + " is reserved by AWS in subnet " + subnet.getSubnetId() - + " and cannot be assigned", 400); - } + requireAssignableSubnetAddress(subnet, ipv4); + } + } + + /** + * Rejects an IPv4 address an interface in {@code subnet} could not take: one that does not + * parse, one outside the subnet's CIDR, or one of the five addresses AWS reserves in every + * subnet (see {@link Ipv4Cidrs#isSubnetReserved}). + */ + private static void requireAssignableSubnetAddress(Subnet subnet, String ipv4) { + String host = ipv4 + "/32"; + if (!Ipv4Cidrs.isIpv4(host)) { + throw new AwsException("InvalidParameterValue", + "Invalid IPv4 address: " + ipv4, 400); + } + if (subnet.getCidrBlock() == null || !Ipv4Cidrs.contains(subnet.getCidrBlock(), host)) { + throw new AwsException("InvalidParameterValue", + "Address " + ipv4 + " does not fall within the address range of subnet " + + subnet.getSubnetId(), 400); + } + if (Ipv4Cidrs.isSubnetReserved(subnet.getCidrBlock(), host)) { + throw new AwsException("InvalidParameterValue", + "Address " + ipv4 + " is reserved by AWS in subnet " + subnet.getSubnetId() + + " and cannot be assigned", 400); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java index 0292c5b8e2..a822047605 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java @@ -467,6 +467,29 @@ public class VpcNetworkManager { * range, the address is unparseable or outside that range, or it is already leased */ public boolean reservePrivateIp(String region, String subnetId, String address) { + return lease(region, subnetId, address, true); + } + + /** + * Leases the address a launch named for itself (RunInstances {@code PrivateIpAddress}), so + * the next {@link #allocatePrivateIp} never hands it to another instance. + * + *

Unlike {@link #reservePrivateIp}, it leaves the allocation cursor where it is, so the + * addresses the subnet picks on its own keep their order, and it logs no refusal: the caller + * has already found the address free, so a lease it meets is one its holder never returned. + * + * @return true when the address is now leased; false when the subnet has no Docker-backed + * range, the address is unparseable or outside that range, or it is already leased + */ + public boolean claimPrivateIp(String region, String subnetId, String address) { + return lease(region, subnetId, address, false); + } + + /** + * @param restoring whether a restart is re-reserving an address a persisted instance holds, + * which warns on refusal and moves the cursor past the address + */ + private boolean lease(String region, String subnetId, String address, boolean restoring) { if (!enabled() || subnetId == null || address == null) { return false; } @@ -476,20 +499,24 @@ public class VpcNetworkManager { } Optional parsed = Cidr4.parse(address + "/32"); if (parsed.isEmpty() || !subnet.effective.containsAddress(parsed.get().network())) { - LOG.warnv("Cannot reserve {0} in subnet {1}: it is outside the subnet''s effective range {2}. " - + "Its holder keeps it, and this manager will not hand it out either, since " - + "it is not an address it allocates from.", - String.valueOf(address), subnetId, String.valueOf(subnet.effective)); + if (restoring) { + LOG.warnv("Cannot reserve {0} in subnet {1}: it is outside the subnet''s effective range {2}. " + + "Its holder keeps it, and this manager will not hand it out either, since " + + "it is not an address it allocates from.", + String.valueOf(address), subnetId, String.valueOf(subnet.effective)); + } return false; } synchronized (subnet) { if (!subnet.leased.add(address)) { - LOG.warnv("Address {0} in subnet {1} is claimed by more than one instance; the later " - + "claim is ignored.", address, subnetId); + if (restoring) { + LOG.warnv("Address {0} in subnet {1} is claimed by more than one instance; the later " + + "claim is ignored.", address, subnetId); + } return false; } long offset = parsed.get().network() - subnet.effective.network(); - if (offset >= subnet.nextOffset) { + if (restoring && offset >= subnet.nextOffset) { subnet.nextOffset = offset + 1; } return true; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2InstanceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2InstanceIntegrationTest.java index b605052866..dda19c2953 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2InstanceIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2InstanceIntegrationTest.java @@ -6,6 +6,7 @@ import io.quarkus.test.junit.QuarkusTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Test; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -15,6 +16,7 @@ import java.util.regex.Pattern; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -317,6 +319,32 @@ class CloudFormationEc2InstanceIntegrationTest { .when().post("/").then().statusCode(200); } + @Test + void createStackLaunchesTheInstanceAtItsDeclaredPrivateIpAddress() { + String stackName = "cfn-ec2-private-ip-" + Long.toString(System.nanoTime(), 36); + String template = """ + {"Resources": { + "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.194.0.0/16"}}, + "Subnet": {"Type": "AWS::EC2::Subnet", "Properties": { + "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.194.1.0/24"}}, + "Server": {"Type": "AWS::EC2::Instance", "Properties": { + "ImageId": "ami-12345678", "InstanceType": "t3.micro", + "SubnetId": {"Ref": "Subnet"}, "PrivateIpAddress": "10.194.1.50"}} + }, "Outputs": { + "InstanceId": {"Value": {"Ref": "Server"}}, + "PrivateIp": {"Value": {"Fn::GetAtt": ["Server", "PrivateIp"]}} + }} + """; + cfn("CreateStack", stackName, template); + try { + String stack = describeStacks(stackName, "CREATE_COMPLETE"); + assertEquals("10.194.1.50", output(stack, "PrivateIp")); + assertPrivateIpAddress(output(stack, "InstanceId"), "10.194.1.50"); + } finally { + deleteStack(stackName); + } + } + @Test void changingPrivateIpAddressReplacesTheInstance() { String suffix = Long.toString(System.nanoTime(), 36); @@ -324,10 +352,13 @@ class CloudFormationEc2InstanceIntegrationTest { String template = """ { "Resources": { + "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.195.0.0/16"}}, + "Subnet": {"Type": "AWS::EC2::Subnet", "Properties": { + "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.195.1.0/24"}}, "Server": { "Type": "AWS::EC2::Instance", "Properties": {"ImageId": "ami-12345678", "InstanceType": "t3.micro", - "PrivateIpAddress": "%s"} + "SubnetId": {"Ref": "Subnet"}, "PrivateIpAddress": "%s"} } }, "Outputs": { @@ -336,23 +367,75 @@ class CloudFormationEc2InstanceIntegrationTest { } """; - cfn("CreateStack", stackName, template.formatted("10.0.0.5")); + cfn("CreateStack", stackName, template.formatted("10.195.1.50")); String firstId = instanceIdFrom(describeStacks(stackName, "CREATE_COMPLETE")); // PrivateIpAddress is createOnly, so changing it replaces the instance rather than reusing it. - cfn("UpdateStack", stackName, template.formatted("10.0.0.6")); + cfn("UpdateStack", stackName, template.formatted("10.195.1.60")); String secondId = instanceIdFrom(describeStacks(stackName, "UPDATE_COMPLETE")); assertNotEquals(firstId, secondId, "PrivateIpAddress changed, so the instance must be replaced"); - // The replacement instance really exists in EC2. - given() + // The replacement instance really exists in EC2, at the new address. + assertPrivateIpAddress(secondId, "10.195.1.60"); + } + + @Test + void replacingAnInstanceThatKeepsItsPrivateIpAddressRollsTheUpdateBack() { + String stackName = "cfn-ec2-keep-ip-" + Long.toString(System.nanoTime(), 36); + String template = """ + {"Resources": { + "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.196.0.0/16"}}, + "Subnet": {"Type": "AWS::EC2::Subnet", "Properties": { + "VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.196.1.0/24"}}, + "Server": {"Type": "AWS::EC2::Instance", "Properties": { + "ImageId": "%s", "InstanceType": "t3.micro", + "SubnetId": {"Ref": "Subnet"}, "PrivateIpAddress": "10.196.1.50"}} + }, "Outputs": { + "InstanceId": {"Value": {"Ref": "Server"}} + }} + """; + cfn("CreateStack", stackName, template.formatted("ami-12345678")); + try { + String firstId = instanceIdFrom(describeStacks(stackName, "CREATE_COMPLETE")); + + // A changed ImageId replaces the instance, and CloudFormation creates the replacement + // before it deletes the original, so the address is still in use, as on AWS. + cfn("UpdateStack", stackName, template.formatted("ami-87654321")); + String rolledBack = describeStacks(stackName, "UPDATE_ROLLBACK_COMPLETE"); + + assertEquals(firstId, instanceIdFrom(rolledBack)); + assertPrivateIpAddress(firstId, "10.196.1.50"); + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStackEvents") + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200) + .body(containsString("Address 10.196.1.50 is in use.")); + } finally { + deleteStack(stackName); + } + } + + /** Every address DescribeInstances reports for the instance and its interface is {@code expected}. */ + private static void assertPrivateIpAddress(String instanceId, String expected) { + String describeInstances = given() .contentType("application/x-www-form-urlencoded") .header("Authorization", EC2_AUTH) .formParam("Action", "DescribeInstances") - .formParam("InstanceId.1", secondId) + .formParam("InstanceId.1", instanceId) .when().post("/").then().statusCode(200) - .body(containsString(secondId)); + .body(containsString(instanceId)) + .extract().asString(); + Matcher m = Pattern.compile("([^<]*)").matcher(describeInstances); + List reported = new ArrayList<>(); + while (m.find()) { + reported.add(m.group(1)); + } + assertFalse(reported.isEmpty(), "expected a private address in " + describeInstances); + assertTrue(reported.stream().allMatch(expected::equals), + "expected every reported private address to be " + expected + ", got " + reported); } private static void cfn(String action, String stackName, String template) { @@ -365,6 +448,15 @@ class CloudFormationEc2InstanceIntegrationTest { .when().post("/").then().statusCode(200); } + private static void deleteStack(String stackName) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200); + } + private static String describeStacks(String stackName, String expectedStatus) { return given() .contentType("application/x-www-form-urlencoded") diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java index 01eca0e123..ab685e1f5e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java @@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; @@ -51,7 +52,9 @@ class CloudFormationEc2ProvisionerTest { Reservation reservation = new Reservation(); reservation.getInstances().add(instance); when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation); + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any())) + .thenReturn(reservation); doThrow(new AwsException("InternalError", "EC2 instance i-launch-failed failed to launch because its container terminated during launch", 500)) .when(ec2Service).awaitContainerLaunch(instance); @@ -73,7 +76,9 @@ class CloudFormationEc2ProvisionerTest { Reservation reservation = new Reservation(); reservation.getInstances().add(instance); when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation); + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any())) + .thenReturn(reservation); doThrow(new AwsException("InternalError", "EC2 instance i-launch-timed-out failed to launch because it did not reach running state before the launch timeout", 500)).when(ec2Service).awaitContainerLaunch(instance); @@ -96,7 +101,9 @@ class CloudFormationEc2ProvisionerTest { Reservation reservation = new Reservation(); reservation.getInstances().add(instance); when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation); + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any())) + .thenReturn(reservation); StackResource resource = provisioner.provision("Server", "AWS::EC2::Instance", properties(), engine(), "us-east-1", "000000000000", "test-stack"); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java index 33d469f5f0..71fcb5b17c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java @@ -31,10 +31,12 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -120,6 +122,39 @@ class Ec2InstanceCfnProvisionerTest { assertEquals(Set.of("InstanceId"), r.getAttributes().keySet()); } + @Test + void launchAppliesTheDeclaredPrivateIpAddress() throws Exception { + Instance instance = new Instance(); + instance.setInstanceId("i-1"); + stubLaunch(instance); + + provisioner.provision(resource("Server"), props(""" + {"ImageId": "ami-1", "SubnetId": "subnet-1", "UserData": "boot", + "PrivateIpAddress": "10.0.1.50"} + """), ctx()); + + // Every other launch option keeps the value the shorter overloads default it to. + ArgumentCaptor privateIp = ArgumentCaptor.forClass(String.class); + verify(ec2).runInstances(eq("us-east-1"), eq("ami-1"), eq("t3.micro"), eq(1), eq(1), isNull(), + anyList(), eq("subnet-1"), isNull(), anyList(), eq("boot"), isNull(), isNull(), isNull(), + eq(0), isNull(), isNull(), isNull(), eq("Ym9vdA=="), eq(false), isNull(), isNull(), isNull(), + eq(false), privateIp.capture()); + assertEquals("10.0.1.50", privateIp.getValue()); + } + + @Test + void launchWithoutAPrivateIpAddressLeavesItToTheSubnet() throws Exception { + Instance instance = new Instance(); + instance.setInstanceId("i-1"); + stubLaunch(instance); + + provisioner.provision(resource("Server"), props("{\"ImageId\": \"ami-1\"}"), ctx()); + + verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), + any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), + anyBoolean(), any(), any(), any(), anyBoolean(), isNull()); + } + @Test void launchTemplateFillsWhatThePropertiesLeaveUnset() throws Exception { LaunchTemplateData data = new LaunchTemplateData(); @@ -136,7 +171,8 @@ class Ec2InstanceCfnProvisionerTest { """), ctx()); verify(ec2).runInstances(eq("us-east-1"), eq("ami-from-template"), eq("m5.large"), eq(1), eq(1), - eq("template-key"), anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()); + eq("template-key"), anyList(), any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); } @Test @@ -167,7 +203,8 @@ class Ec2InstanceCfnProvisionerTest { assertEquals("i-nolt", r.getPhysicalId()); verify(ec2).runInstances(eq("us-east-1"), any(), eq("t3.micro"), eq(1), eq(1), any(), - anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()); + anyList(), any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); } @Test @@ -271,7 +308,8 @@ class Ec2InstanceCfnProvisionerTest { assertEquals("i-1", r.getPhysicalId()); verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), - anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()); + anyList(), any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); } @Test @@ -380,7 +418,8 @@ class Ec2InstanceCfnProvisionerTest { ArgumentCaptor profile = ArgumentCaptor.forClass(String.class); verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), profile.capture(), any(), any(), anyInt(), any(), any()); + any(), any(), anyList(), any(), profile.capture(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); assertEquals(PROFILE_A, profile.getValue()); assertEquals(PROFILE_A, r.getAttributes().get("__FlociDeclaredIamInstanceProfile")); } @@ -404,7 +443,8 @@ class Ec2InstanceCfnProvisionerTest { i2.setInstanceId("i-2"); i2.setImageId("ami-2"); when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())) + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any())) .thenReturn(reservationOf(i1), reservationOf(i2)); StackResource r = resource("Server"); provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx(null)); @@ -428,7 +468,8 @@ class Ec2InstanceCfnProvisionerTest { i2.setInstanceId("i-2"); i2.setImageId("ami-1"); when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())) + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any())) .thenReturn(reservationOf(i1), reservationOf(i2)); StackResource r = resource("Server"); provisioner.provision(r, props("{\"ImageId\": \"ami-1\", \"PrivateIpAddress\": \"10.0.0.5\"}"), ctx(null)); @@ -452,7 +493,8 @@ class Ec2InstanceCfnProvisionerTest { i2.setInstanceId("i-2"); i2.setImageId("ami-1"); when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())) + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any())) .thenReturn(reservationOf(i1), reservationOf(i2)); StackResource r = resource("Server"); provisioner.provision(r, props("{\"ImageId\": \"ami-1\", \"AvailabilityZone\": \"us-east-1a\"}"), ctx(null)); @@ -482,7 +524,8 @@ class Ec2InstanceCfnProvisionerTest { assertEquals("i-1", r.getPhysicalId()); verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), - anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()); + anyList(), any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); } @Test @@ -502,7 +545,8 @@ class Ec2InstanceCfnProvisionerTest { assertEquals("i-1", r.getPhysicalId()); verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), - anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()); + anyList(), any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); } @Test @@ -546,7 +590,8 @@ class Ec2InstanceCfnProvisionerTest { ArgumentCaptor launched = ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class); verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), launched.capture()); + any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), launched.capture(), + any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); assertEquals("required", launched.getValue().getHttpTokens()); LaunchTemplateData.MetadataOptions applied = LaunchTemplateData.MetadataOptions.launchDefaults(); @@ -567,7 +612,8 @@ class Ec2InstanceCfnProvisionerTest { verify(ec2).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), modified.capture()); assertEquals("optional", modified.getValue().getHttpTokens()); verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()); + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); } @Test @@ -634,7 +680,8 @@ class Ec2InstanceCfnProvisionerTest { verify(ec2).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), reset.capture()); assertEquals("optional", reset.getValue().getHttpTokens()); verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()); + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); } /** @@ -912,7 +959,8 @@ class Ec2InstanceCfnProvisionerTest { assertEquals("InvalidParameterValue", failure.getErrorCode()); verify(ec2, never()).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()); + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); } @Test @@ -1145,7 +1193,8 @@ class Ec2InstanceCfnProvisionerTest { assertEquals("i-9", r.getPhysicalId()); verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), - anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()); + anyList(), any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); } @Test @@ -1166,7 +1215,8 @@ class Ec2InstanceCfnProvisionerTest { assertEquals("i-9", r.getPhysicalId()); verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), - anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()); + anyList(), any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()); } @Test @@ -1179,7 +1229,8 @@ class Ec2InstanceCfnProvisionerTest { withoutPublicIp.setInstanceId("i-2"); withoutPublicIp.setImageId("ami-2"); when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())) + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any())) .thenReturn(reservationOf(withPublicIp), reservationOf(withoutPublicIp)); StackResource r = resource("Server"); provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx(null)); @@ -1219,7 +1270,8 @@ class Ec2InstanceCfnProvisionerTest { .thenReturn(List.of(reservationOf(instance))); } when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())) + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any())) .thenReturn(reservations.get(0), reservations.subList(1, reservations.size()).toArray(Reservation[]::new)); return instances; } @@ -1236,7 +1288,9 @@ class Ec2InstanceCfnProvisionerTest { Reservation reservation = new Reservation(); reservation.getInstances().add(instance); when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), - any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation); + any(), any(), anyList(), any(), any(), any(), + any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any())) + .thenReturn(reservation); } private ProvisionContext ctx() { diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPrivateIpIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPrivateIpIntegrationTest.java new file mode 100644 index 0000000000..d052f2bd86 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPrivateIpIntegrationTest.java @@ -0,0 +1,254 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.concurrent.atomic.AtomicLong; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class Ec2RunInstancesPrivateIpIntegrationTest { + // A fresh account per test, so what one test launches never holds an address another asks for. + private static final AtomicLong ACCOUNTS = new AtomicLong(725000000000L); + private static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item."; + + @Test + void topLevelPrivateIpAddressIsTheAddressTheInstanceGets() { + String owner = Long.toString(ACCOUNTS.incrementAndGet()); + Network network = createSubnet(owner, "10.51.0.0/16", "10.51.1.0/24"); + + String id = runInstance(owner) + .formParam("SubnetId", network.subnetId()) + .formParam("PrivateIpAddress", "10.51.1.50") + .post("/").then().statusCode(200) + .body("RunInstancesResponse.instancesSet.item.privateIpAddress", equalTo("10.51.1.50")) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + + assertDescribedAddress(owner, id, "10.51.1.50"); + terminate(owner, id); + delete(owner, network); + } + + @Test + void networkInterfacePrivateIpAddressIsTheAddressTheInstanceGets() { + // The shape Terraform's aws_instance sends for private_ip together with subnet_id. + String owner = Long.toString(ACCOUNTS.incrementAndGet()); + Network network = createSubnet(owner, "10.52.0.0/16", "10.52.1.0/24"); + + String id = runInstance(owner) + .formParam("NetworkInterface.1.DeviceIndex", "0") + .formParam("NetworkInterface.1.SubnetId", network.subnetId()) + .formParam("NetworkInterface.1.PrivateIpAddress", "10.52.1.60") + .post("/").then().statusCode(200) + .body("RunInstancesResponse.instancesSet.item.privateIpAddress", equalTo("10.52.1.60")) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + + assertDescribedAddress(owner, id, "10.52.1.60"); + terminate(owner, id); + delete(owner, network); + } + + @Test + void primaryPrivateIpAddressesEntryIsTheAddressTheInstanceGets() { + // The shape AWS CLI v2 sends for --private-ip-address with --associate-public-ip-address. + String owner = Long.toString(ACCOUNTS.incrementAndGet()); + Network network = createSubnet(owner, "10.56.0.0/16", "10.56.1.0/24"); + + String id = runInstance(owner) + .formParam("NetworkInterface.1.DeviceIndex", "0") + .formParam("NetworkInterface.1.SubnetId", network.subnetId()) + .formParam("NetworkInterface.1.AssociatePublicIpAddress", "true") + .formParam("NetworkInterface.1.PrivateIpAddresses.1.PrivateIpAddress", "10.56.1.60") + .formParam("NetworkInterface.1.PrivateIpAddresses.1.Primary", "true") + .post("/").then().statusCode(200) + .body("RunInstancesResponse.instancesSet.item.privateIpAddress", equalTo("10.56.1.60")) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + + assertDescribedAddress(owner, id, "10.56.1.60"); + terminate(owner, id); + delete(owner, network); + } + + @Test + void aSecondaryPrivateIpAddressesEntryDoesNotPlaceTheInstance() { + String owner = Long.toString(ACCOUNTS.incrementAndGet()); + Network network = createSubnet(owner, "10.57.0.0/16", "10.57.1.0/24"); + + String id = runInstance(owner) + .formParam("NetworkInterface.1.DeviceIndex", "0") + .formParam("NetworkInterface.1.SubnetId", network.subnetId()) + .formParam("NetworkInterface.1.PrivateIpAddresses.1.PrivateIpAddress", "10.57.1.70") + .formParam("NetworkInterface.1.PrivateIpAddresses.1.Primary", "false") + .formParam("NetworkInterface.1.PrivateIpAddresses.2.PrivateIpAddress", "10.57.1.60") + .formParam("NetworkInterface.1.PrivateIpAddresses.2.Primary", "true") + .post("/").then().statusCode(200) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + + assertDescribedAddress(owner, id, "10.57.1.60"); + terminate(owner, id); + delete(owner, network); + } + + @Test + void launchTemplatePrimaryInterfacePrivateIpAddressIsTheAddressTheInstanceGets() { + String owner = Long.toString(ACCOUNTS.incrementAndGet()); + Network network = createSubnet(owner, "10.58.0.0/16", "10.58.1.0/24"); + String template = request("CreateLaunchTemplate", owner) + .formParam("LaunchTemplateName", "fixed-private-address") + .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890") + .formParam("LaunchTemplateData.InstanceType", "t3.micro") + .formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", 0) + .formParam("LaunchTemplateData.NetworkInterface.1.SubnetId", network.subnetId()) + .formParam("LaunchTemplateData.NetworkInterface.1.PrivateIpAddress", "10.58.1.80") + .post("/").then().statusCode(200) + .extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId"); + + String id = request("RunInstances", owner).formParam("MinCount", 1).formParam("MaxCount", 1) + .formParam("LaunchTemplate.LaunchTemplateId", template) + .post("/").then().statusCode(200) + .body("RunInstancesResponse.instancesSet.item.privateIpAddress", equalTo("10.58.1.80")) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + + assertDescribedAddress(owner, id, "10.58.1.80"); + terminate(owner, id); + request("DeleteLaunchTemplate", owner).formParam("LaunchTemplateId", template).post("/").then().statusCode(200); + delete(owner, network); + } + + @Test + void privateIpAddressOutsideTheSubnetIsRejected() { + String owner = Long.toString(ACCOUNTS.incrementAndGet()); + Network network = createSubnet(owner, "10.53.0.0/16", "10.53.1.0/24"); + + runInstance(owner).formParam("SubnetId", network.subnetId()).formParam("PrivateIpAddress", "10.53.2.50") + .post("/").then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")); + + assertInstancesIn(owner, network.subnetId(), 0); + delete(owner, network); + } + + @Test + void privateIpAddressAnotherInstanceHoldsIsRejected() { + String owner = Long.toString(ACCOUNTS.incrementAndGet()); + Network network = createSubnet(owner, "10.54.0.0/16", "10.54.1.0/24"); + String holder = runInstance(owner).formParam("SubnetId", network.subnetId()) + .formParam("PrivateIpAddress", "10.54.1.50") + .post("/").then().statusCode(200) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + + runInstance(owner).formParam("SubnetId", network.subnetId()).formParam("PrivateIpAddress", "10.54.1.50") + .post("/").then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidIPAddress.InUse")) + .body("Response.Errors.Error.Message", equalTo("Address 10.54.1.50 is in use.")); + + assertInstancesIn(owner, network.subnetId(), 1); + terminate(owner, holder); + delete(owner, network); + } + + @Test + void privateIpAddressForMoreThanOneInstanceIsRejected() { + String owner = Long.toString(ACCOUNTS.incrementAndGet()); + Network network = createSubnet(owner, "10.55.0.0/16", "10.55.1.0/24"); + + request("RunInstances", owner) + .formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro") + .formParam("MinCount", "2").formParam("MaxCount", "2") + .formParam("SubnetId", network.subnetId()).formParam("PrivateIpAddress", "10.55.1.50") + .post("/").then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination")); + + assertInstancesIn(owner, network.subnetId(), 0); + delete(owner, network); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void networkInterfacesRejectAnInstanceLevelPrivateIpAddress(boolean fromTemplate) { + String owner = Long.toString(ACCOUNTS.incrementAndGet()); + Network network = createSubnet(owner, "10.59.0.0/16", "10.59.1.0/24"); + RequestSpecification launch = request("RunInstances", owner).formParam("MinCount", 1) + .formParam("MaxCount", 1).formParam("PrivateIpAddress", "10.59.1.50"); + String template = null; + if (fromTemplate) { + template = request("CreateLaunchTemplate", owner) + .formParam("LaunchTemplateName", "invalid-private-address-combination") + .formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890") + .formParam("LaunchTemplateData.InstanceType", "t3.micro") + .formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", 0) + .formParam("LaunchTemplateData.NetworkInterface.1.SubnetId", network.subnetId()) + .post("/").then().statusCode(200) + .extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId"); + launch.formParam("LaunchTemplate.LaunchTemplateId", template); + } else { + launch.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro") + .formParam("NetworkInterface.1.DeviceIndex", 0) + .formParam("NetworkInterface.1.SubnetId", network.subnetId()); + } + + launch.post("/").then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination")) + .body("Response.Errors.Error.Message", equalTo("Network interfaces and an instance-level " + + "private IP address may not be specified on the same request")); + + assertInstancesIn(owner, network.subnetId(), 0); + if (template != null) { + request("DeleteLaunchTemplate", owner).formParam("LaunchTemplateId", template) + .post("/").then().statusCode(200); + } + delete(owner, network); + } + + private record Network(String vpcId, String subnetId) {} + + private static RequestSpecification runInstance(String owner) { + return request("RunInstances", owner) + .formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro") + .formParam("MinCount", "1").formParam("MaxCount", "1"); + } + + private static RequestSpecification request(String action, String owner) { + return given().formParam("Action", action).header("Authorization", EnforcementFixtures.auth(owner, "ec2")); + } + + private static void assertDescribedAddress(String owner, String instanceId, String address) { + request("DescribeInstances", owner).formParam("InstanceId.1", instanceId) + .post("/").then().statusCode(200) + .body(INSTANCE + "privateIpAddress", equalTo(address)) + .body(INSTANCE + "networkInterfaceSet.item.privateIpAddress", equalTo(address)); + } + + /** A rejected launch must not leave an instance behind in the subnet it named. */ + private static void assertInstancesIn(String owner, String subnetId, int expected) { + request("DescribeInstances", owner) + .formParam("Filter.1.Name", "subnet-id").formParam("Filter.1.Value.1", subnetId) + .post("/").then().statusCode(200) + .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.size()", equalTo(expected)); + } + + private static void terminate(String owner, String instanceId) { + request("TerminateInstances", owner).formParam("InstanceId.1", instanceId).post("/").then().statusCode(200); + } + + private static Network createSubnet(String owner, String vpcCidr, String subnetCidr) { + String vpcId = request("CreateVpc", owner).formParam("CidrBlock", vpcCidr) + .post("/").then().statusCode(200) + .extract().path("CreateVpcResponse.vpc.vpcId"); + String subnetId = request("CreateSubnet", owner).formParam("VpcId", vpcId).formParam("CidrBlock", subnetCidr) + .post("/").then().statusCode(200) + .extract().path("CreateSubnetResponse.subnet.subnetId"); + return new Network(vpcId, subnetId); + } + + private static void delete(String owner, Network network) { + request("DeleteSubnet", owner).formParam("SubnetId", network.subnetId()).post("/").then().statusCode(200); + request("DeleteVpc", owner).formParam("VpcId", network.vpcId()).post("/").then().statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java index 9fbdd1fb92..996e937d14 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java @@ -64,7 +64,7 @@ class Ec2RunInstancesPublicIpParamTest { nullable(String.class), anyList(), nullable(String.class), nullable(String.class), nullable(Boolean.class), nullable(String.class), anyInt(), nullable(String.class), nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false), - nullable(String.class), nullable(String.class), nullable(List.class), eq(false))) + nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class))) .thenReturn(new Reservation()); Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class), @@ -79,7 +79,7 @@ class Ec2RunInstancesPublicIpParamTest { nullable(String.class), anyList(), nullable(String.class), nullable(String.class), associatePublicIp.capture(), nullable(String.class), anyInt(), nullable(String.class), nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false), - nullable(String.class), nullable(String.class), nullable(List.class), eq(false)); + nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class)); if (expected == null) { assertNull(associatePublicIp.getValue(), "an absent override must stay null so the subnet default decides"); 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 5633277087..bb9554ea8c 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 @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ec2; import com.fasterxml.jackson.core.type.TypeReference; import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.ListNetworksCmd; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RequestContext; @@ -106,6 +107,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -3738,6 +3740,381 @@ class Ec2ServiceTest { assertFalse(Ipv4Cidrs.isSubnetReserved(cidr, address + "/32"), address + " is reserved in " + cidr); } + @Test + void runInstancesGivesTheInstanceAndItsInterfaceTheRequestedPrivateIp() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String subnetId = privateIpSubnet(service); + + for (String requested : List.of("10.50.1.50", "10.50.1.60")) { + String id = launchWithPrivateIp(service, subnetId, 1, requested).getInstances().getFirst().getInstanceId(); + + Instance described = service.describeInstances("us-east-1", List.of(id), Map.of()) + .getFirst().getInstances().getFirst(); + assertEquals(requested, described.getPrivateIpAddress()); + assertEquals("ip-" + requested.replace('.', '-') + ".ec2.internal", described.getPrivateDnsName()); + assertEquals(requested, described.getNetworkInterfaces().getFirst().getPrivateIpAddress()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"10.50.2.50", "10.50.1.0", "10.50.1.3", "10.50.1.255", "10.50.1.256", "not-an-ip"}) + void runInstancesRejectsARequestedPrivateIpTheSubnetCannotAssign(String requested) { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String subnetId = privateIpSubnet(service); + + AwsException error = assertThrows(AwsException.class, + () -> launchWithPrivateIp(service, subnetId, 1, requested)); + + assertEquals("InvalidParameterValue", error.getErrorCode()); + assertTrue(instancesIn(service, subnetId).isEmpty(), "a rejected launch must store nothing"); + } + + @Test + void runInstancesRejectsARequestedPrivateIpAnotherResourceHolds() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String vpcId = service.createVpc("us-east-1", "10.50.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet("us-east-1", vpcId, "10.50.1.0/24", "us-east-1a").getSubnetId(); + launchWithPrivateIp(service, subnetId, 1, "10.50.1.50"); + String assigned = launchAddresses(service, subnetId, 1).getFirst(); + service.createNetworkInterface("us-east-1", subnetId, "holder", "10.50.1.70", + List.of(), List.of(), List.of()); + service.createVpcEndpoint("us-east-1", vpcId, "com.amazonaws.us-east-1.ecs", + "Interface", List.of(), List.of(subnetId), List.of(), null, null, List.of()); + String endpointAddress = endpointAddressesBySubnet(service).get(subnetId); + assertNotNull(endpointAddress); + + for (String taken : List.of("10.50.1.50", assigned, "10.50.1.70", endpointAddress)) { + AwsException error = assertThrows(AwsException.class, + () -> launchWithPrivateIp(service, subnetId, 1, taken)); + assertEquals("InvalidIPAddress.InUse", error.getErrorCode()); + assertEquals("Address " + taken + " is in use.", error.getMessage()); + } + assertEquals(2, instancesIn(service, subnetId).size()); + } + + @Test + void aTerminatedInstancesPrivateIpCanBeRequestedAgain() { + // Terraform replaces an aws_instance whose private_ip is fixed by terminating the old one + // and launching its successor at the same address. + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String subnetId = privateIpSubnet(service); + String first = launchWithPrivateIp(service, subnetId, 1, "10.50.1.50").getInstances().getFirst().getInstanceId(); + + service.terminateInstances("us-east-1", List.of(first)); + + assertEquals("10.50.1.50", launchWithPrivateIp(service, subnetId, 1, "10.50.1.50") + .getInstances().getFirst().getPrivateIpAddress()); + } + + @Test + void anAddressPickedByTheSubnetStepsAroundARequestedOne() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String subnetId = privateIpSubnet(service); + // A fresh subnet hands out .10, .11, .12 on its own, so .11 is the next one but the first. + launchWithPrivateIp(service, subnetId, 1, "10.50.1.11"); + + assertEquals(List.of("10.50.1.10"), launchAddresses(service, subnetId, 1)); + assertEquals(List.of("10.50.1.12"), launchAddresses(service, subnetId, 1)); + } + + @Test + void aZeroPaddedRequestedPrivateIpIsStoredCanonicallySoItStillConflicts() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String subnetId = privateIpSubnet(service); + + assertEquals("10.50.1.50", launchWithPrivateIp(service, subnetId, 1, "10.50.1.050") + .getInstances().getFirst().getPrivateIpAddress()); + assertEquals("InvalidIPAddress.InUse", assertThrows(AwsException.class, + () -> launchWithPrivateIp(service, subnetId, 1, "10.50.1.50")).getErrorCode()); + } + + @Test + void aZeroPaddedAddressAnInterfaceWasCreatedWithStillHoldsTheRequestedPrivateIp() { + // CreateNetworkInterface keeps its address as given, so the in-use check compares + // canonical forms or a zero-padded octet would make one address look like two. + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String subnetId = privateIpSubnet(service); + NetworkInterface padded = service.createNetworkInterface("us-east-1", subnetId, "padded", "10.50.1.050", + List.of(), List.of(), List.of()); + + AwsException error = assertThrows(AwsException.class, + () -> launchWithPrivateIp(service, subnetId, 1, "10.50.1.50")); + + assertEquals("InvalidIPAddress.InUse", error.getErrorCode()); + assertEquals("10.50.1.050", padded.getPrivateIpAddress()); + assertTrue(instancesIn(service, subnetId).isEmpty(), "a rejected launch must store nothing"); + } + + @Test + void aRequestedPrivateIpNeedsASingleInstanceThatCreatesItsOwnInterface() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String subnetId = privateIpSubnet(service); + String eniId = service.createNetworkInterface("us-east-1", subnetId, "primary", null, + List.of(), List.of(), List.of()).getNetworkInterfaceId(); + + AwsException twoInstances = assertThrows(AwsException.class, + () -> launchWithPrivateIp(service, subnetId, 2, "10.50.1.50")); + AwsException upToTwoInstances = assertThrows(AwsException.class, + () -> service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro", 1, 2, null, + List.of(), subnetId, null, List.of(), null, null, null, null, 0, null, null, null, null, + false, null, null, null, false, "10.50.1.50")); + AwsException existingInterface = assertThrows(AwsException.class, + () -> service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro", 1, 1, null, + List.of(), null, null, List.of(), null, null, null, eniId, 0, null, null, null, null, + false, null, null, null, false, "10.50.1.50")); + + assertEquals("InvalidParameterCombination", twoInstances.getErrorCode()); + assertEquals("InvalidParameterCombination", upToTwoInstances.getErrorCode()); + assertEquals("InvalidParameterCombination", existingInterface.getErrorCode()); + assertTrue(instancesIn(service, subnetId).isEmpty()); + } + + @Test + void aRequestedPrivateIpIsLeasedOnTheVpcNetworkInsteadOfTheNextFreeAddress() { + VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class); + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(), vpcNetworks); + String subnetId = privateIpSubnet(service); + when(vpcNetworks.effectiveSubnetCidr("us-east-1", subnetId)).thenReturn(Optional.of("10.50.1.0/24")); + when(vpcNetworks.claimPrivateIp("us-east-1", subnetId, "10.50.1.50")).thenReturn(true); + + assertEquals("10.50.1.50", launchWithPrivateIp(service, subnetId, 1, "10.50.1.50") + .getInstances().getFirst().getPrivateIpAddress()); + + verify(vpcNetworks).claimPrivateIp("us-east-1", subnetId, "10.50.1.50"); + verify(vpcNetworks, never()).reservePrivateIp(anyString(), anyString(), anyString()); + verify(vpcNetworks, never()).allocatePrivateIp(anyString(), anyString()); + } + + @Test + void aRefusedLeaseDoesNotTurnAFreeAddressIntoOneInUse() { + // DeleteNetworkInterface does not return its lease, so the lease table can outlive the + // resource that took one. With nothing in any account holding the address any more, the + // stale lease must not fail the launch. + RequestContext context = new RequestContext(); + Ec2Service service = realVpcNetworkService(context); + String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a"); + context.setAccountId("111122223333"); + service.describeSubnets("us-east-1", List.of(), Map.of()); + NetworkInterface deleted = service.createNetworkInterface("us-east-1", subnetId, "deleted", null, + List.of(), List.of(), List.of()); + service.deleteNetworkInterface("us-east-1", deleted.getNetworkInterfaceId()); + String stale = deleted.getPrivateIpAddress(); + + context.setAccountId("000000000000"); + + assertEquals(stale, launchWithPrivateIp(service, subnetId, 1, stale) + .getInstances().getFirst().getPrivateIpAddress()); + } + + @ParameterizedTest + @ValueSource(strings = {"instance", "network-interface", "nat-gateway"}) + void aRequestedPrivateIpAnotherAccountHoldsOnASharedVpcNetworkIsInUse(String holder) { + // Default VPC and subnet ids are the same in every account, so their Docker network and + // lease table are shared while the stored-resource check sees only the caller's account. + // Claiming the address anyway would give the other account's lease away. + RequestContext context = new RequestContext(); + Ec2Service service = realVpcNetworkService(context); + String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a"); + context.setAccountId("111122223333"); + service.describeSubnets("us-east-1", List.of(), Map.of()); + String held = switch (holder) { + case "instance" -> launchAddresses(service, subnetId, 1).getFirst(); + case "network-interface" -> service.createNetworkInterface("us-east-1", subnetId, "holder", null, + List.of(), List.of(), List.of()).getPrivateIpAddress(); + default -> service.createNatGateway("us-east-1", subnetId, null, "private", List.of()) + .getNatGatewayAddresses().getFirst().getPrivateIp(); + }; + assertEquals("172.31.0.10", held, "the shared network's first address, leased by the other account"); + + context.setAccountId("000000000000"); + AwsException error = assertThrows(AwsException.class, + () -> launchWithPrivateIp(service, subnetId, 1, held)); + + assertEquals("InvalidIPAddress.InUse", error.getErrorCode()); + assertEquals("Address " + held + " is in use.", error.getMessage()); + assertTrue(instancesIn(service, subnetId).isEmpty(), "a rejected launch must store nothing"); + } + + @Test + void anAddressAnotherAccountsInterfaceWasCreatedWithIsInUseOnASharedVpcNetwork() { + // CreateNetworkInterface with its own address takes no lease, so only the stored + // interface says the shared network's address is held. + RequestContext context = new RequestContext(); + Ec2Service service = realVpcNetworkService(context); + String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a"); + context.setAccountId("111122223333"); + service.describeSubnets("us-east-1", List.of(), Map.of()); + service.createNetworkInterface("us-east-1", subnetId, "holder", "172.31.0.50", + List.of(), List.of(), List.of()); + + context.setAccountId("000000000000"); + AwsException error = assertThrows(AwsException.class, + () -> launchWithPrivateIp(service, subnetId, 1, "172.31.0.50")); + + assertEquals("InvalidIPAddress.InUse", error.getErrorCode()); + assertTrue(instancesIn(service, subnetId).isEmpty(), "a rejected launch must store nothing"); + } + + @Test + void anotherAccountsNatGatewayStillHoldsItsAddressAfterARestartEmptiesTheLeaseTable() { + // A restart re-leases only instances' addresses, so a persisted NAT gateway's address is + // held by the stored gateway alone. + String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a"); + NatGatewayAddress address = new NatGatewayAddress(); + address.setPrivateIp("172.31.0.10"); + NatGateway natGateway = new NatGateway(); + natGateway.setNatGatewayId("nat-other"); + natGateway.setSubnetId(subnetId); + natGateway.setState("available"); + natGateway.setNatGatewayAddresses(List.of(address)); + AccountAwareStorageBackend natGatewayStore = AccountAwareStorageBackend.inMemory("000000000000"); + natGatewayStore.putForAccount("111122223333", "us-east-1::nat-other", natGateway); + RequestContext context = new RequestContext(); + context.setAccountId("000000000000"); + Ec2Service service = realVpcNetworkService(context, Map.of("ec2-nat-gateways.json", natGatewayStore)); + + AwsException error = assertThrows(AwsException.class, + () -> launchWithPrivateIp(service, subnetId, 1, "172.31.0.10")); + + assertEquals("InvalidIPAddress.InUse", error.getErrorCode()); + assertTrue(instancesIn(service, subnetId).isEmpty(), "a rejected launch must store nothing"); + } + + @Test + void anotherAccountsInstanceOutsideASubstitutedRangeDoesNotHoldTheRequestedPrivateIp() { + // A substituted subnet never leases an address outside its effective range, so no + // container holds it on the shared network and each account keeps it as it would on AWS. + String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a"); + AccountAwareStorageBackend instanceStore = AccountAwareStorageBackend.inMemory("000000000000"); + instanceStore.putForAccount("111122223333", "us-east-1::i-other", + defaultSubnetInstance("i-other", "172.31.0.50", InstanceState.running())); + VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class); + when(vpcNetworks.effectiveSubnetCidr("us-east-1", subnetId)).thenReturn(Optional.of("10.240.0.0/20")); + 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-instances.json", instanceStore)), vpcNetworks); + + assertEquals("172.31.0.50", launchWithPrivateIp(service, subnetId, 1, "172.31.0.50") + .getInstances().getFirst().getPrivateIpAddress()); + } + + @Test + void aRequestedPrivateIpIsLeasedSoTheRealVpcNetworkDoesNotHandItOutAgain() { + // The manager's allocator consults only its own lease table. Without the lease it would + // hand a fresh /24's first address, offset 10, to the next launch as well. + Ec2Service service = realVpcNetworkService(new RequestContext()); + String subnetId = privateIpSubnet(service); + + assertEquals("10.50.1.10", launchWithPrivateIp(service, subnetId, 1, "10.50.1.10") + .getInstances().getFirst().getPrivateIpAddress()); + + assertEquals(List.of("10.50.1.11"), launchAddresses(service, subnetId, 1)); + } + + @Test + void aRequestedPrivateIpLeavesTheRealVpcNetworksAllocationOrderAlone() { + // Claiming a high address must not move the network's cursor past it, or the next + // automatic address would be .251 instead of a fresh /24's first one. + Ec2Service service = realVpcNetworkService(new RequestContext()); + String subnetId = privateIpSubnet(service); + + launchWithPrivateIp(service, subnetId, 1, "10.50.1.250"); + + assertEquals(List.of("10.50.1.10"), launchAddresses(service, subnetId, 1)); + } + + @Test + void aDryRunWithARequestedPrivateIpLeasesNothing() { + VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class); + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(), vpcNetworks); + String subnetId = privateIpSubnet(service); + + AwsException dryRun = assertThrows(AwsException.class, + () -> service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro", 1, 1, null, + List.of(), subnetId, null, List.of(), null, null, null, null, 0, null, null, null, null, + true, null, null, null, false, "10.50.1.50")); + + assertEquals("DryRunOperation", dryRun.getErrorCode()); + verify(vpcNetworks, never()).claimPrivateIp(anyString(), anyString(), anyString()); + assertTrue(instancesIn(service, subnetId).isEmpty()); + } + + private static String privateIpSubnet(Ec2Service service) { + String vpcId = service.createVpc("us-east-1", "10.50.0.0/16", false).getVpcId(); + return service.createSubnet("us-east-1", vpcId, "10.50.1.0/24", "us-east-1a").getSubnetId(); + } + + private static Reservation launchWithPrivateIp(Ec2Service service, String subnetId, int count, + String privateIp) { + return service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro", count, count, null, + List.of(), subnetId, null, List.of(), null, null, null, null, 0, null, null, null, null, + false, null, null, null, false, privateIp); + } + + private static Ec2Service realVpcNetworkService(RequestContext context) { + return realVpcNetworkService(context, Map.of()); + } + + /** + * Ec2Service in container mode over a real VpcNetworkManager, whose Docker daemon has no + * networks yet, with the caller's account taken from {@code context} and {@code stores} + * standing in for what a previous run persisted. + */ + private static Ec2Service realVpcNetworkService(RequestContext context, + Map> stores) { + EmulatorConfig config = mockConfig(false); + EmulatorConfig.VpcNetworksConfig networks = mock(EmulatorConfig.VpcNetworksConfig.class); + when(config.services().ec2().vpcNetworks()).thenReturn(networks); + when(networks.enabled()).thenReturn(true); + DockerClient docker = mock(DockerClient.class); + ListNetworksCmd listNetworks = mock(ListNetworksCmd.class, RETURNS_SELF); + when(listNetworks.exec()).thenReturn(List.of()); + when(docker.listNetworksCmd()).thenReturn(listNetworks); + AmiImageResolver images = mock(AmiImageResolver.class); + when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest")); + @SuppressWarnings("unchecked") + jakarta.enterprise.inject.Instance contexts = mock(jakarta.enterprise.inject.Instance.class); + when(contexts.isResolvable()).thenReturn(true); + when(contexts.get()).thenReturn(context); + return new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class), images, + mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(stores, contexts), + contexts, new VpcNetworkManager(config, docker, null), null, null, null); + } + + private static Instance defaultSubnetInstance(String instanceId, String privateIp, InstanceState state) { + Instance instance = persistedInstance(instanceId, privateIp, state); + instance.setVpcId(Ec2Service.defaultVpcId("us-east-1")); + instance.setSubnetId(Ec2Service.defaultSubnetId("us-east-1", "a")); + return instance; + } + + private static List instancesIn(Ec2Service service, String subnetId) { + return service.describeInstances("us-east-1", List.of(), Map.of("subnet-id", List.of(subnetId))).stream() + .flatMap(reservation -> reservation.getInstances().stream()) + .toList(); + } + private static EndpointAddressFixture endpointAddressFixture(String firstCidr, String secondCidr) { AccountAwareStorageBackend subnetStore = AccountAwareStorageBackend.inMemory("000000000000"); Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java index 0a9a1548c4..864db6a27a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java @@ -328,6 +328,37 @@ class VpcNetworkManagerTest { "a terminated restored instance's address must return to circulation"); } + // ─── Launch: an address RunInstances names for itself ──────────────────── + + @Test + void aClaimedAddressIsNeverHandedOutAndLeavesTheAllocationOrderAlone() { + manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16"); + manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24"); + + assertTrue(manager.claimPrivateIp(REGION, "subnet-a", "10.0.1.250")); + + assertEquals("10.0.1.10", manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow(), + "a claimed address must not move the cursor past it"); + List allocated = new ArrayList<>(); + Optional next; + while ((next = manager.allocatePrivateIp(REGION, "subnet-a")).isPresent()) { + allocated.add(next.get()); + } + assertFalse(allocated.contains("10.0.1.250"), "the claimed address must never be handed out"); + assertTrue(allocated.contains("10.0.1.254"), "the addresses after it are still handed out"); + } + + @Test + void claimingALeasedOrOutOfRangeAddressRefusesWithoutThrowing() { + manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16"); + manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24"); + String leased = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow(); + + assertFalse(manager.claimPrivateIp(REGION, "subnet-a", leased)); + assertFalse(manager.claimPrivateIp(REGION, "subnet-a", "172.31.4.9")); + assertFalse(manager.claimPrivateIp(REGION, "subnet-unknown", "10.0.1.20")); + } + @Test void subnetsInTheSameVpcGetDisjointRangesOnOneNetwork() { manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");