diff --git a/compatibility-tests/sdk-test-python/tests/test_ec2_eni_association_filters.py b/compatibility-tests/sdk-test-python/tests/test_ec2_eni_association_filters.py index 8488379f2a..349204f03f 100644 --- a/compatibility-tests/sdk-test-python/tests/test_ec2_eni_association_filters.py +++ b/compatibility-tests/sdk-test-python/tests/test_ec2_eni_association_filters.py @@ -1,4 +1,4 @@ -"""Primary ENI filters and VPC-dependent EIP release verified against live EC2.""" +"""Network interface association filters and Elastic IP lifecycle.""" import uuid from contextlib import ExitStack @@ -41,7 +41,10 @@ def test_default_subnet_filter_excludes_custom_subnets(ec2_client, filter_name): @pytest.mark.parametrize("supplied_interface", [False, True]) @pytest.mark.parametrize("default_vpc", [False, True]) -def test_network_interface_association_filters(ec2_client, supplied_interface, default_vpc): +@pytest.mark.parametrize("by_interface_id", [False, True]) +def test_network_interface_association_filters( + ec2_client, supplied_interface, default_vpc, by_interface_id +): with ExitStack() as cleanup: if default_vpc: subnet = ec2_client.describe_subnets( @@ -64,18 +67,23 @@ def test_network_interface_association_filters(ec2_client, supplied_interface, d instances = ec2_client.run_instances( ImageId=image, InstanceType="t3.nano", MinCount=1, MaxCount=1, **placement)["Instances"] - instances += ec2_client.run_instances( + cleanup.callback(terminate_and_wait, ec2_client, + [instance["InstanceId"] for instance in instances]) + other_instances = ec2_client.run_instances( ImageId=image, InstanceType="t3.nano", MinCount=1, MaxCount=1, SubnetId=subnet)["Instances"] cleanup.callback(terminate_and_wait, ec2_client, - [instance["InstanceId"] for instance in instances]) + [instance["InstanceId"] for instance in other_instances]) + instances += other_instances eni_ids = [instance["NetworkInterfaces"][0]["NetworkInterfaceId"] for instance in instances] allocation = ec2_client.allocate_address(Domain="vpc")["AllocationId"] allocation_cleanup = cleanup.enter_context(ExitStack()) allocation_cleanup.callback(ec2_client.release_address, AllocationId=allocation) + target = ({"NetworkInterfaceId": eni_ids[0]} if by_interface_id + else {"InstanceId": instances[0]["InstanceId"]}) association = ec2_client.associate_address( - AllocationId=allocation, InstanceId=instances[0]["InstanceId"])["AssociationId"] + AllocationId=allocation, **target)["AssociationId"] association_cleanup = cleanup.enter_context(ExitStack()) association_cleanup.callback(ec2_client.disassociate_address, AssociationId=association) # Floci resolves a reachable address on association; read the actual association. @@ -117,6 +125,135 @@ def test_network_interface_association_filters(ec2_client, supplied_interface, d NetworkInterfaceIds=[eni_ids[0]])["NetworkInterfaces"][0] +def _release_address(ec2_client, allocation_id): + address = ec2_client.describe_addresses(AllocationIds=[allocation_id])["Addresses"][0] + if address.get("AssociationId"): + ec2_client.disassociate_address(AssociationId=address["AssociationId"]) + ec2_client.release_address(AllocationId=allocation_id) + + +@pytest.mark.parametrize("secondary", [False, True]) +def test_detached_interface_address_association(ec2_client, secondary): + with ExitStack() as cleanup: + vpc = ec2_client.create_vpc(CidrBlock="10.237.0.0/24")["Vpc"]["VpcId"] + cleanup.callback(ec2_client.delete_vpc, VpcId=vpc) + subnet = ec2_client.create_subnet( + VpcId=vpc, CidrBlock="10.237.0.0/26")["Subnet"]["SubnetId"] + cleanup.callback(ec2_client.delete_subnet, SubnetId=subnet) + interface = ec2_client.create_network_interface( + SubnetId=subnet, PrivateIpAddresses=[ + {"PrivateIpAddress": "10.237.0.4", "Primary": True}, + {"PrivateIpAddress": "10.237.0.5", "Primary": False}, + ])["NetworkInterface"] + eni_id = interface["NetworkInterfaceId"] + cleanup.callback(ec2_client.delete_network_interface, NetworkInterfaceId=eni_id) + private_ip = next(ip["PrivateIpAddress"] for ip in interface["PrivateIpAddresses"] + if ip["Primary"] != secondary) + allocations = [] + for _ in range(2): + allocation = ec2_client.allocate_address(Domain="vpc")["AllocationId"] + cleanup.callback(_release_address, ec2_client, allocation) + allocations.append(allocation) + + def read_interface(): + return ec2_client.describe_network_interfaces(NetworkInterfaceIds=[eni_id])["NetworkInterfaces"][0] + + for allocation in allocations: + arguments = {"PrivateIpAddress": private_ip} if secondary else {} + association = ec2_client.associate_address( + AllocationId=allocation, NetworkInterfaceId=eni_id, **arguments)["AssociationId"] + observed = read_interface() + address = ec2_client.describe_addresses(AllocationIds=[allocation])["Addresses"][0] + assert address["AssociationId"] == association + assert address["NetworkInterfaceId"] == eni_id + assert address["PrivateIpAddress"] == private_ip + assert not address.get("InstanceId") + private = next(ip for ip in observed["PrivateIpAddresses"] if ip["PrivateIpAddress"] == private_ip) + assert private["Association"]["AssociationId"] == association + assert private["Association"]["AllocationId"] == allocation + assert private["Association"]["IpOwnerId"] == observed["OwnerId"] + if secondary: + assert "Association" not in observed + else: + assert observed["Association"] == private["Association"] + filtered = ec2_client.describe_network_interfaces(Filters=[ + {"Name": "association.public-ip", "Values": [address["PublicIp"]]}, + {"Name": "association.ip-owner-id", "Values": [observed["OwnerId"]]}, + ])["NetworkInterfaces"] + assert [item["NetworkInterfaceId"] for item in filtered] == [eni_id] + + previous = ec2_client.describe_addresses(AllocationIds=[allocations[0]])["Addresses"][0] + assert not previous.get("AssociationId") + assert not previous.get("NetworkInterfaceId") + before = ec2_client.describe_addresses(AllocationIds=allocations)["Addresses"] + for invalid, code in [ + ({}, "MissingParameter"), + ({"NetworkInterfaceId": "eni-00000000000000000"}, "InvalidNetworkInterfaceID.NotFound"), + ({"NetworkInterfaceId": eni_id, "PrivateIpAddress": "10.237.0.61"}, "InvalidParameterValue"), + ({"NetworkInterfaceId": eni_id, "InstanceId": "i-00000000000000000"}, + "InvalidParameterCombination"), + ]: + with pytest.raises(ClientError) as error: + ec2_client.associate_address(AllocationId=allocations[1], **invalid) + assert error.value.response["Error"]["Code"] == code + assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400 + assert ec2_client.describe_addresses(AllocationIds=allocations)["Addresses"] == before + + ec2_client.disassociate_address(AssociationId=association) + observed = read_interface() + assert "Association" not in observed + assert all("Association" not in ip for ip in observed["PrivateIpAddresses"]) + + +def _delete_nat_gateway(ec2_client, nat_gateway_id): + ec2_client.delete_nat_gateway(NatGatewayId=nat_gateway_id) + ec2_client.get_waiter("nat_gateway_deleted").wait( + NatGatewayIds=[nat_gateway_id], WaiterConfig={"Delay": 1, "MaxAttempts": 120}) + + +@pytest.mark.parametrize("managed_by", ["nat_gateway", "vpc_endpoint"]) +def test_service_managed_interface_association_is_unsupported(ec2_client, managed_by): + """Known service interfaces are unsupported, and rejection preserves the EIP.""" + with ExitStack() as cleanup: + vpc = ec2_client.create_vpc(CidrBlock="10.237.0.0/24")["Vpc"]["VpcId"] + cleanup.callback(ec2_client.delete_vpc, VpcId=vpc) + subnet = ec2_client.create_subnet( + VpcId=vpc, CidrBlock="10.237.0.0/26")["Subnet"]["SubnetId"] + cleanup.callback(ec2_client.delete_subnet, SubnetId=subnet) + if managed_by == "nat_gateway": + gateway = ec2_client.create_nat_gateway( + SubnetId=subnet, ConnectivityType="private")["NatGateway"] + cleanup.callback(_delete_nat_gateway, ec2_client, gateway["NatGatewayId"]) + ec2_client.get_waiter("nat_gateway_available").wait( + NatGatewayIds=[gateway["NatGatewayId"]], WaiterConfig={"Delay": 1, "MaxAttempts": 120}) + gateway = ec2_client.describe_nat_gateways( + NatGatewayIds=[gateway["NatGatewayId"]])["NatGateways"][0] + interface_id = gateway["NatGatewayAddresses"][0]["NetworkInterfaceId"] + else: + endpoint = ec2_client.create_vpc_endpoint( + VpcId=vpc, VpcEndpointType="Interface", SubnetIds=[subnet], + ServiceName=f"com.amazonaws.{ec2_client.meta.region_name}.ssm")["VpcEndpoint"] + cleanup.callback(ec2_client.delete_vpc_endpoints, VpcEndpointIds=[endpoint["VpcEndpointId"]]) + interface_id = endpoint["NetworkInterfaceIds"][0] + interface = ec2_client.describe_network_interfaces( + NetworkInterfaceIds=[interface_id])["NetworkInterfaces"][0] + assert interface["RequesterManaged"] + + original = ec2_client.create_network_interface(SubnetId=subnet)["NetworkInterface"]["NetworkInterfaceId"] + cleanup.callback(ec2_client.delete_network_interface, NetworkInterfaceId=original) + allocation = ec2_client.allocate_address(Domain="vpc")["AllocationId"] + cleanup.callback(_release_address, ec2_client, allocation) + ec2_client.associate_address(AllocationId=allocation, NetworkInterfaceId=original) + before = ec2_client.describe_addresses(AllocationIds=[allocation])["Addresses"] + with pytest.raises(ClientError) as error: + ec2_client.associate_address(AllocationId=allocation, NetworkInterfaceId=interface_id) + assert error.value.response["Error"]["Code"] == "Unsupported" + assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400 + assert ec2_client.describe_addresses(AllocationIds=[allocation])["Addresses"] == before + assert ec2_client.describe_network_interfaces( + NetworkInterfaceIds=[interface_id])["NetworkInterfaces"][0] == interface + + @pytest.mark.parametrize("supplied_interface", [False, True]) @pytest.mark.parametrize("default_vpc", [False, True]) def test_termination_preserves_only_retained_interface_associations( diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 984967d286..25789574c9 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -934,9 +934,19 @@ any other `PrivateIpAddress` fails with `InvalidParameterValue` and changes no a exception is container mode without AWS-faithful private addresses: the instance reports its Docker bridge address there, so any value means its primary address. +`AssociateAddress` accepts `NetworkInterfaceId` for a detached interface or an instance's +primary interface. A detached interface records the association on its selected private +address; omitting `PrivateIpAddress` selects the primary address. Supplying both +`InstanceId` and `NetworkInterfaceId`, a missing interface, or a private address the +interface does not own fails before changing an existing association. Association to a +nonprimary attached interface or a service-managed interface, including NAT gateway +and VPC endpoint interfaces, is not implemented and returns `Unsupported`. + Deleting an interface, including deletion on instance termination, disassociates its -Elastic IP without releasing the allocation. A retained interface keeps its association -after termination; release still follows that interface's VPC rules. +Elastic IP without releasing the allocation. Concurrent `AssociateAddress` and +`DeleteNetworkInterface` requests cannot leave an association pointing to a deleted +interface. A retained interface keeps its association after termination; release still +follows that interface's VPC rules. AllocateAddress draws Elastic IPs from `203.0.113.0/24`, a range reserved for documentation that no host answers on, in every mode, so a client never reaches someone else's host through one. An 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 d7f9eef748..87516e2bf6 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 @@ -4855,7 +4855,8 @@ public class Ec2QueryHandler { private Response handleAssociateAddress(MultivaluedMap p, String region) { String allocationId = p.getFirst("AllocationId"); String instanceId = p.getFirst("InstanceId"); - Address addr = service.associateAddress(region, allocationId, instanceId, p.getFirst("PrivateIpAddress")); + Address addr = service.associateAddress(region, allocationId, instanceId, + p.getFirst("NetworkInterfaceId"), p.getFirst("PrivateIpAddress")); XmlBuilder xml = new XmlBuilder() .start("AssociateAddressResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()) 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 b0fbe43333..1893dfefc3 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 @@ -13193,6 +13193,71 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return associateAddress(region, allocationId, instanceId, null); } + public Address associateAddress(String region, String allocationId, String instanceId, + String networkInterfaceId, String privateIpAddress) { + if (!isSet(networkInterfaceId)) { + if (!isSet(instanceId)) { + throw new AwsException("MissingParameter", + "Specify either InstanceId or NetworkInterfaceId.", 400); + } + return associateAddress(region, allocationId, instanceId, privateIpAddress); + } + if (isSet(instanceId)) { + throw new AwsException("InvalidParameterCombination", + "Specify either InstanceId or NetworkInterfaceId, but not both.", 400); + } + ensureDefaultResources(region); + synchronized (privateIpAllocationLock) { + NetworkInterface networkInterface = networkInterfaces.get(key(region, networkInterfaceId)).orElse(null); + if (networkInterface == null) { + networkInterface = describeNetworkInterfaces(region, List.of(networkInterfaceId), Map.of()) + .networkInterfaces().getFirst(); + } + networkInterface = releaseIfHostIsGone(region, networkInterface); + NetworkInterfaceAttachment attachment = networkInterface.getAttachment(); + if (attachment != null) { + if (attachment.getDeviceIndex() != 0) { + throw new AwsException("Unsupported", + "Elastic IP association to a non-primary attached interface is not supported.", 400); + } + return associateAddress(region, allocationId, attachment.getInstanceId(), privateIpAddress); + } + if (!"available".equals(networkInterface.getStatus())) { + throw new AwsException("Unsupported", + "Elastic IP association to a service-managed interface is not supported.", 400); + } + String selectedPrivateIp = isSet(privateIpAddress) + ? privateIpAddress : networkInterface.getPrivateIpAddress(); + if (networkInterface.getPrivateIpAddresses().stream() + .noneMatch(ip -> selectedPrivateIp.equals(ip.getPrivateIpAddress()))) { + throw new AwsException("InvalidParameterValue", + "The private IP address is not assigned to the selected network interface.", 400); + } + Address address = getRequiredAddress(region, allocationId); + if (isHeldByNatGateway(region, allocationId)) { + throw new AwsException("Resource.AlreadyAssociated", + "The Elastic IP address is already associated with a NAT gateway.", 400); + } + if (address.getAssociationId() != null) { + disassociateAddress(region, address.getAssociationId()); + } + for (Address previous : addresses.scan(k -> k.startsWith(region + "::"))) { + if (previous.getAssociationId() != null + && networkInterfaceId.equals(previous.getNetworkInterfaceId()) + && selectedPrivateIp.equals(previous.getPrivateIpAddress())) { + disassociateAddress(region, previous.getAssociationId()); + } + } + address.setInstanceId(null); + address.setNetworkInterfaceId(networkInterfaceId); + address.setPrivateIpAddress(selectedPrivateIp); + address.setAssociationId("eipassoc-" + randomHex(17)); + updateStoredAddressAssociation(address); + addresses.put(key(region, allocationId), address); + return address; + } + } + /** * Associates the Elastic IP with one private address of the instance. * @@ -15182,13 +15247,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab * behind, so the status is what says the interface is spoken for. */ public void deleteNetworkInterface(String region, String networkInterfaceId) { - NetworkInterface ni = requireStandaloneNetworkInterface(region, networkInterfaceId); - if (ni.getAttachment() != null || "in-use".equals(ni.getStatus())) { - throw new AwsException("InvalidParameterValue", - "Network interface '" + networkInterfaceId + "' is currently in use", 400); + synchronized (privateIpAllocationLock) { + NetworkInterface ni = requireStandaloneNetworkInterface(region, networkInterfaceId); + if (ni.getAttachment() != null || "in-use".equals(ni.getStatus())) { + throw new AwsException("InvalidParameterValue", + "Network interface '" + networkInterfaceId + "' is currently in use", 400); + } + releaseInterfaceAddresses(region, networkInterfaceId, true); + networkInterfaces.delete(key(region, networkInterfaceId)); } - releaseInterfaceAddresses(region, networkInterfaceId, true); - networkInterfaces.delete(key(region, networkInterfaceId)); } /** 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 74a302c5d2..e0c47f6aba 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 @@ -2600,6 +2600,65 @@ class Ec2ServiceTest { .getFirst().getAssociationId(), "a failed gateway must not claim the allocation"); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void deletingAnInterfaceSerializesWithAddressAssociation(boolean associateFirst) throws Exception { + ParkingStore parking = new ParkingStore<>(); + AccountAwareStorageBackend interfaceStore = + new AccountAwareStorageBackend<>(parking, null, "000000000000"); + 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-network-interfaces.json", interfaceStore))); + String region = "us-east-1"; + String subnetId = service.describeSubnets(region, List.of(), Map.of()).getFirst().getSubnetId(); + String interfaceId = service.createNetworkInterface(region, subnetId, null, null, + List.of(), List.of(), List.of()).getNetworkInterfaceId(); + String allocationId = service.allocateAddress(region).getAllocationId(); + Runnable associate = () -> service.associateAddress(region, allocationId, null, interfaceId, null); + Runnable delete = () -> service.deleteNetworkInterface(region, interfaceId); + AtomicReference firstWorker = new AtomicReference<>(); + AtomicReference secondWorker = new AtomicReference<>(); + parking.parkNextRead(); + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + Future first = workers.submit(() -> { + firstWorker.set(Thread.currentThread()); + (associateFirst ? associate : delete).run(); + }); + assertTrue(parking.awaitParked(), "the first request never read the interface"); + Future second = workers.submit(() -> { + secondWorker.set(Thread.currentThread()); + (associateFirst ? delete : associate).run(); + }); + String secondMethod = associateFirst ? "deleteNetworkInterface" : "associateAddress"; + Awaitility.await().atMost(Duration.ofSeconds(10)).until(() -> second.isDone() + || isBlockedIn(secondWorker.get(), secondMethod, firstWorker.get())); + parking.release(); + first.get(10, TimeUnit.SECONDS); + if (associateFirst) { + second.get(10, TimeUnit.SECONDS); + } else { + ExecutionException refusal = assertThrows(ExecutionException.class, + () -> second.get(10, TimeUnit.SECONDS)); + AwsException missing = assertInstanceOf(AwsException.class, refusal.getCause()); + assertEquals("InvalidNetworkInterfaceID.NotFound", missing.getErrorCode()); + assertEquals(400, missing.getHttpStatus()); + } + AwsException missing = assertThrows(AwsException.class, + () -> service.describeNetworkInterfaces(region, List.of(interfaceId), Map.of())); + assertEquals("InvalidNetworkInterfaceID.NotFound", missing.getErrorCode()); + Address address = service.describeAddresses(region, List.of(allocationId), Map.of()).getFirst(); + assertNull(address.getAssociationId(), "the allocation must not remain associated with a deleted interface"); + assertNull(address.getNetworkInterfaceId()); + assertNull(address.getPrivateIpAddress()); + } finally { + parking.release(); + workers.shutdownNow(); + assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS)); + } + } + /** AssociateAddress refuses an allocation a NAT gateway holds; the gateway keeps it. */ @Test void associateAddressRefusesANatGatewaysElasticIp() {