Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(ec2): filter network interfaces by primary address association (#5531)

Andre Kurait04dd78d0f6e0
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
new file mode 100644
index 0000000000..de069a25cd
--- /dev/null
+++ b/compatibility-tests/sdk-test-python/tests/test_ec2_eni_association_filters.py
@@ -0,0 +1,144 @@
+"""Primary ENI filters and VPC-dependent EIP release verified against live EC2."""
+
+import uuid
+from contextlib import ExitStack
+
+import pytest
+from botocore.exceptions import ClientError
+
+
[email protected]("supplied_interface", [False, True])
[email protected]("default_vpc", [False, True])
+def test_network_interface_association_filters(ec2_client, supplied_interface, default_vpc):
+ with ExitStack() as cleanup:
+ if default_vpc:
+ subnet = ec2_client.describe_subnets(
+ Filters=[{"Name": "default-for-az", "Values": ["true"]}])["Subnets"][0]["SubnetId"]
+ else:
+ 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)
+ image = ec2_client.register_image(
+ Name="eni-filter-" + uuid.uuid4().hex, Architecture="x86_64",
+ RootDeviceName="/dev/sda1")["ImageId"]
+ cleanup.callback(ec2_client.deregister_image, ImageId=image)
+ placement = {"SubnetId": subnet}
+ if supplied_interface:
+ eni_id = ec2_client.create_network_interface(SubnetId=subnet)["NetworkInterface"]["NetworkInterfaceId"]
+ cleanup.callback(ec2_client.delete_network_interface, NetworkInterfaceId=eni_id)
+ placement = {"NetworkInterfaces": [{"NetworkInterfaceId": eni_id, "DeviceIndex": 0}]}
+ instances = ec2_client.run_instances(
+ ImageId=image, InstanceType="t3.nano", MinCount=1, MaxCount=1,
+ **placement)["Instances"]
+ instances += ec2_client.run_instances(
+ ImageId=image, InstanceType="t3.nano", MinCount=1, MaxCount=1,
+ SubnetId=subnet)["Instances"]
+ cleanup.callback(ec2_client.terminate_instances,
+ InstanceIds=[instance["InstanceId"] for instance in 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)
+ association = ec2_client.associate_address(
+ AllocationId=allocation, InstanceId=instances[0]["InstanceId"])["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.
+ interface = ec2_client.describe_network_interfaces(
+ NetworkInterfaceIds=[eni_ids[0]])["NetworkInterfaces"][0]
+ address = next(ip["Association"] for ip in interface["PrivateIpAddresses"] if ip["Primary"])
+ assert interface["Association"] == address
+ public_ip, owner = address["PublicIp"], address["IpOwnerId"]
+
+ def matched(**filters):
+ result = ec2_client.describe_network_interfaces(
+ NetworkInterfaceIds=eni_ids,
+ Filters=[{"Name": key, "Values": value} for key, value in filters.items()])
+ return [item["NetworkInterfaceId"] for item in result["NetworkInterfaces"]]
+
+ assert matched(**{"association.public-ip": [public_ip]}) == [eni_ids[0]]
+ assert matched(**{"association.public-ip": ["192.0.2.1"]}) == []
+ assert matched(**{"association.ip-owner-id": [owner]}) == [eni_ids[0]]
+ assert matched(**{"association.ip-owner-id": ["wrong-owner"]}) == []
+ assert matched(**{"association.public-ip": ["192.0.2.1", public_ip]}) == [eni_ids[0]]
+ assert matched(**{"association.public-ip": ["*"],
+ "association.ip-owner-id": ["wrong-owner"]}) == []
+ if not default_vpc:
+ with pytest.raises(ClientError) as error:
+ ec2_client.release_address(AllocationId=allocation)
+ assert error.value.response["Error"]["Code"] == "InvalidIPAddress.InUse"
+ assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert ec2_client.describe_addresses(
+ AllocationIds=[allocation])["Addresses"][0]["AssociationId"] == association
+ assert matched(**{"association.public-ip": [public_ip],
+ "association.ip-owner-id": [owner]}) == [eni_ids[0]]
+ association_cleanup.close()
+ ec2_client.release_address(AllocationId=allocation)
+ association_cleanup.pop_all()
+ allocation_cleanup.pop_all()
+ assert matched(**{"association.public-ip": [public_ip]}) == []
+ assert matched(**{"association.ip-owner-id": [owner]}) == []
+ assert "Association" not in ec2_client.describe_network_interfaces(
+ NetworkInterfaceIds=[eni_ids[0]])["NetworkInterfaces"][0]
+
+
[email protected]("supplied_interface", [False, True])
[email protected]("default_vpc", [False, True])
+def test_termination_preserves_only_retained_interface_associations(
+ ec2_client, supplied_interface, default_vpc
+):
+ with ExitStack() as cleanup:
+ if default_vpc:
+ subnet = ec2_client.describe_subnets(
+ Filters=[{"Name": "default-for-az", "Values": ["true"]}])["Subnets"][0]["SubnetId"]
+ else:
+ 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)
+ image = ec2_client.register_image(
+ Name="eni-termination-" + uuid.uuid4().hex, Architecture="x86_64",
+ RootDeviceName="/dev/sda1")["ImageId"]
+ cleanup.callback(ec2_client.deregister_image, ImageId=image)
+ placement = {"SubnetId": subnet}
+ interface_cleanup = cleanup.enter_context(ExitStack())
+ if supplied_interface:
+ eni = ec2_client.create_network_interface(SubnetId=subnet)["NetworkInterface"]["NetworkInterfaceId"]
+ interface_cleanup.callback(ec2_client.delete_network_interface, NetworkInterfaceId=eni)
+ placement = {"NetworkInterfaces": [{"NetworkInterfaceId": eni, "DeviceIndex": 0}]}
+ instance = ec2_client.run_instances(
+ ImageId=image, InstanceType="t3.nano", MinCount=1, MaxCount=1, **placement)["Instances"][0]
+ cleanup.callback(ec2_client.terminate_instances, InstanceIds=[instance["InstanceId"]])
+ allocation = ec2_client.allocate_address(Domain="vpc")["AllocationId"]
+ allocation_cleanup = cleanup.enter_context(ExitStack())
+ allocation_cleanup.callback(ec2_client.release_address, AllocationId=allocation)
+ association = ec2_client.associate_address(
+ AllocationId=allocation, InstanceId=instance["InstanceId"])["AssociationId"]
+ association_cleanup = cleanup.enter_context(ExitStack())
+ association_cleanup.callback(ec2_client.disassociate_address, AssociationId=association)
+ ec2_client.terminate_instances(InstanceIds=[instance["InstanceId"]])
+ address = ec2_client.describe_addresses(AllocationIds=[allocation])["Addresses"][0]
+ assert not address.get("InstanceId")
+ if supplied_interface:
+ assert address["AssociationId"] == association
+ interface = ec2_client.describe_network_interfaces(NetworkInterfaceIds=[eni])["NetworkInterfaces"][0]
+ assert interface["Status"] == "available"
+ assert not interface.get("Attachment")
+ assert interface["Association"]["AssociationId"] == association
+ if not default_vpc:
+ with pytest.raises(ClientError) as error:
+ ec2_client.release_address(AllocationId=allocation)
+ assert error.value.response["Error"]["Code"] == "InvalidIPAddress.InUse"
+ interface_cleanup.close()
+ address = ec2_client.describe_addresses(AllocationIds=[allocation])["Addresses"][0]
+ assert not address.get("AssociationId")
+ assert not address.get("NetworkInterfaceId")
+ else:
+ assert not address.get("AssociationId")
+ assert not address.get("NetworkInterfaceId")
+ ec2_client.release_address(AllocationId=allocation)
+ association_cleanup.pop_all()
+ allocation_cleanup.pop_all()
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
index 2f7fb729a5..223f7da30e 100644
--- a/docs/services/ec2.md
+++ b/docs/services/ec2.md
@@ -600,6 +600,15 @@ fixed socket/core/vCPU shape rather than one derived from the instance family.
| DisassociateAddress | Removes an Elastic IP address association. |
| ReleaseAddress | Releases an Elastic IP address record. |
+`ReleaseAddress` automatically disassociates an instance's Elastic IP only in the default VPC.
+In a nondefault VPC it returns `InvalidIPAddress.InUse` without changing the association;
+call `DisassociateAddress` first, as specified by the
+[EC2 API reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ReleaseAddress.html).
+
+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.
+
An allocated Elastic IP's `54.x.x.x` address is invented and routes nowhere, so associating
it re-points it at the address the instance is actually reachable on — the same value
DescribeInstances reports. This is a deliberate deviation from AWS, where an EIP's public IP
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 6040948193..cd2944ffb2 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
@@ -4678,6 +4678,10 @@ public class Ec2QueryHandler {
}
xml.end("groupSet");
xml.raw(tagSetXml(ni.getTagSet()));
+ ni.getPrivateIpAddresses().stream()
+ .filter(ip -> ip.isPrimary() && ip.getAssociation() != null)
+ .findFirst()
+ .ifPresent(ip -> xml.raw(networkInterfaceAssociationXml(ip.getAssociation())));
if (ni.getAttachment() != null) {
xml.start("attachment")
.elem("attachmentId", ni.getAttachment().getAttachmentId())
@@ -4697,12 +4701,7 @@ public class Ec2QueryHandler {
.elem("privateDnsName", ip.getPrivateDnsName())
.elem("primary", String.valueOf(ip.isPrimary()));
if (ip.getAssociation() != null) {
- xml.start("association")
- .elem("publicIp", ip.getAssociation().getPublicIp())
- .elem("allocationId", ip.getAssociation().getAllocationId())
- .elem("associationId", ip.getAssociation().getAssociationId())
- .elem("ipOwnerId", ip.getAssociation().getIpOwnerId())
- .end("association");
+ xml.raw(networkInterfaceAssociationXml(ip.getAssociation()));
}
xml.end("item");
}
@@ -4711,6 +4710,15 @@ public class Ec2QueryHandler {
return xml.build();
}
+ private static String networkInterfaceAssociationXml(NetworkInterfaceAssociation association) {
+ return new XmlBuilder().start("association")
+ .elem("publicIp", association.getPublicIp())
+ .elem("allocationId", association.getAllocationId())
+ .elem("associationId", association.getAssociationId())
+ .elem("ipOwnerId", association.getIpOwnerId())
+ .end("association").build();
+ }
+
private Response handleCreateNetworkInterface(MultivaluedMap<String, String> p, String region) {
String subnetId = p.getFirst("SubnetId");
String description = p.getFirst("Description");
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 e281836b1a..1766b24796 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
@@ -9273,6 +9273,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
ensureDefaultResources(region);
Address addr = getRequiredAddress(region, allocationId);
+ if (addr.getAssociationId() != null) {
+ disassociateAddress(region, addr.getAssociationId());
+ }
addr.setInstanceId(instanceId);
addr.setAssociationId("eipassoc-" + randomHex(17));
pointAddressAtInstance(addr, region, instanceId);
@@ -9324,6 +9327,37 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (inst.getNetworkInterfaces() != null && !inst.getNetworkInterfaces().isEmpty()) {
addr.setNetworkInterfaceId(inst.getNetworkInterfaces().get(0).getNetworkInterfaceId());
}
+ updateStoredAddressAssociation(addr);
+ }
+
+ private void updateStoredAddressAssociation(Address address) {
+ if (address.getNetworkInterfaceId() == null) {
+ return;
+ }
+ String interfaceKey = key(address.getRegion(), address.getNetworkInterfaceId());
+ networkInterfaces.get(interfaceKey).ifPresent(ni -> {
+ for (NetworkInterfacePrivateIpAddress ip : ni.getPrivateIpAddresses()) {
+ if (!ip.isPrimary()) {
+ continue;
+ }
+ if (address.getAssociationId() != null) {
+ ip.setAssociation(networkInterfaceAssociation(address, ni.getOwnerId()));
+ } else if (ip.getAssociation() != null
+ && address.getAllocationId().equals(ip.getAssociation().getAllocationId())) {
+ ip.setAssociation(null);
+ }
+ }
+ networkInterfaces.put(interfaceKey, ni);
+ });
+ }
+
+ private static NetworkInterfaceAssociation networkInterfaceAssociation(Address address, String ownerId) {
+ NetworkInterfaceAssociation association = new NetworkInterfaceAssociation();
+ association.setPublicIp(address.getPublicIp());
+ association.setAllocationId(address.getAllocationId());
+ association.setAssociationId(address.getAssociationId());
+ association.setIpOwnerId(ownerId);
+ return association;
}
private Address getRequiredAddress(String region, String allocationId) {
@@ -9340,6 +9374,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (addr.getRegion().equals(region) && associationId.equals(addr.getAssociationId())) {
addr.setInstanceId(null);
addr.setAssociationId(null);
+ updateStoredAddressAssociation(addr);
addr.setNetworkInterfaceId(null);
addr.setPrivateIpAddress(null);
// Hand the allocation back its allocated address: with no instance behind it,
@@ -9355,12 +9390,34 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public void releaseAddress(String region, String allocationId) {
ensureDefaultResources(region);
- if (addresses.get(key(region, allocationId)).isEmpty()) {
- throw new AwsException("InvalidAllocationID.NotFound", "The allocation ID '" + allocationId + "' does not exist", 400);
+ Address address = getRequiredAddress(region, allocationId);
+ if (address.getAssociationId() != null) {
+ NetworkInterface ni = networkInterfaces.get(key(region, address.getNetworkInterfaceId())).orElse(null);
+ String vpcId = ni != null ? ni.getVpcId()
+ : getRequiredInstance(region, address.getInstanceId()).getVpcId();
+ if (!getRequiredVpc(region, vpcId).isDefault()) {
+ throw new AwsException("InvalidIPAddress.InUse",
+ "Address " + address.getPublicIp() + " is in use.", 400);
+ }
+ disassociateAddress(region, address.getAssociationId());
}
addresses.delete(key(region, allocationId));
}
+ private void releaseInterfaceAddresses(String region, String networkInterfaceId, boolean deleted) {
+ for (Address address : addresses.scan(k -> k.startsWith(region + "::"))) {
+ if (!networkInterfaceId.equals(address.getNetworkInterfaceId())) {
+ continue;
+ }
+ if (deleted) {
+ disassociateAddress(region, address.getAssociationId());
+ } else {
+ address.setInstanceId(null);
+ addresses.put(key(region, address.getAllocationId()), address);
+ }
+ }
+ }
+
public List<Address> describeAddresses(String region, List<String> allocationIds, Map<String, List<String>> filters) {
ensureDefaultResources(region);
List<Address> candidates = addresses.scan(k -> true).stream()
@@ -9913,6 +9970,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
case "requester-managed" -> matchesValue(values, String.valueOf(ni.isRequesterManaged()));
case "attachment.instance-id" -> ni.getAttachment() != null
&& matchesValue(values, ni.getAttachment().getInstanceId());
+ case "association.ip-owner-id" -> ni.getPrivateIpAddresses().stream()
+ .anyMatch(ip -> ip.isPrimary() && ip.getAssociation() != null
+ && ip.getAssociation().getIpOwnerId() != null
+ && matchesValue(values, ip.getAssociation().getIpOwnerId()));
+ case "association.public-ip" -> ni.getPrivateIpAddresses().stream()
+ .anyMatch(ip -> ip.isPrimary() && ip.getAssociation() != null
+ && ip.getAssociation().getPublicIp() != null
+ && matchesValue(values, ip.getAssociation().getPublicIp()));
case "private-ip-address" ->
matchesValue(values, ni.getPrivateIpAddress()) ||
ni.getPrivateIpAddresses().stream()
@@ -10538,14 +10603,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
primaryIp.setPrivateDnsName(eni.getPrivateDnsName());
primaryIp.setPrimary(true);
// Look up EIP association for this instance
- addressForInstance(inst.getInstanceId()).ifPresent(addr -> {
- NetworkInterfaceAssociation assoc = new NetworkInterfaceAssociation();
- assoc.setPublicIp(addr.getPublicIp());
- assoc.setAllocationId(addr.getAllocationId());
- assoc.setAssociationId(addr.getAssociationId());
- assoc.setIpOwnerId(eni.getOwnerId());
- primaryIp.setAssociation(assoc);
- });
+ addressForInstance(inst.getInstanceId()).ifPresent(addr ->
+ primaryIp.setAssociation(networkInterfaceAssociation(addr, eni.getOwnerId())));
ni.getPrivateIpAddresses().add(primaryIp);
// Phase 4: apply filters
@@ -10749,6 +10808,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
throw new AwsException("InvalidParameterValue",
"Network interface '" + networkInterfaceId + "' is currently in use", 400);
}
+ releaseInterfaceAddresses(region, networkInterfaceId, true);
networkInterfaces.delete(key(region, networkInterfaceId));
}
@@ -10901,17 +10961,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
private void releaseStandaloneInterfacesOnTermination(String region, Instance inst) {
for (InstanceNetworkInterface e : List.copyOf(inst.getNetworkInterfaces())) {
NetworkInterface ni = networkInterfaces.get(key(region, e.getNetworkInterfaceId())).orElse(null);
+ NetworkInterfaceAttachment att = ni != null ? ni.getAttachment() : null;
+ boolean deleted = ni == null || (att != null && att.isDeleteOnTermination());
+ releaseInterfaceAddresses(region, e.getNetworkInterfaceId(), deleted);
+ inst.getNetworkInterfaces().remove(e);
if (ni == null) {
continue;
}
- NetworkInterfaceAttachment att = ni.getAttachment();
- // Either way the instance stops carrying it. A deleted interface obviously cannot stay
- // on the record, and a released one must not either: once it is attached to something
- // else, two instance records would claim it and DescribeInstances has no rule that
- // picks the live one.
- inst.getNetworkInterfaces().removeIf(
- carried -> ni.getNetworkInterfaceId().equals(carried.getNetworkInterfaceId()));
- if (att != null && att.isDeleteOnTermination()) {
+ if (deleted) {
networkInterfaces.delete(key(region, ni.getNetworkInterfaceId()));
continue;
}
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 cdfd6c8671..d557a38e1a 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
@@ -24,7 +24,9 @@ import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
+import io.github.hectorvent.floci.services.ec2.model.NetworkInterfaceAssociation;
import io.github.hectorvent.floci.services.ec2.model.NetworkInterfaceListResult;
+import io.github.hectorvent.floci.services.ec2.model.NetworkInterfacePrivateIpAddress;
import io.github.hectorvent.floci.services.ec2.model.Placement;
import io.github.hectorvent.floci.services.ec2.model.PrefixList;
import io.github.hectorvent.floci.services.ec2.model.PrefixListEntry;
@@ -57,6 +59,8 @@ import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
import java.io.StringReader;
import java.lang.reflect.Field;
@@ -515,6 +519,184 @@ class Ec2ServiceTest {
assertEquals(1, result.networkInterfaces().size());
}
+ @ParameterizedTest
+ @CsvSource({"false,false", "false,true", "true,false", "true,true"})
+ void describeNetworkInterfacesFiltersActualAddressAssociations(boolean suppliedInterface, boolean defaultVpc) {
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
+ new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
+ String subnetId = defaultVpc
+ ? service.describeSubnets("us-east-1", List.of(), Map.of()).getFirst().getSubnetId()
+ : service.createSubnet("us-east-1",
+ service.createVpc("us-east-1", "10.237.0.0/24", false).getVpcId(),
+ "10.237.0.0/26", "us-east-1a").getSubnetId();
+ String suppliedId = suppliedInterface
+ ? service.createNetworkInterface("us-east-1", subnetId,
+ null, null, List.of(), List.of(), List.of()).getNetworkInterfaceId() : null;
+ Instance associated = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
+ 1, 1, null, List.of(), subnetId, null, List.of(), null, null,
+ null, suppliedId, 0).getInstances().getFirst();
+ Instance other = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
+ 1, 1, null, List.of(), null, null, List.of(), null, null).getInstances().getFirst();
+ Address address = service.allocateAddress("us-east-1");
+ service.associateAddress("us-east-1", address.getAllocationId(), associated.getInstanceId());
+ String interfaceId = associated.getNetworkInterfaces().getFirst().getNetworkInterfaceId();
+ String ownerId = associated.getNetworkInterfaces().getFirst().getOwnerId();
+
+ assertEquals(List.of(interfaceId), service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of("association.ip-owner-id", List.of(ownerId)), 0, null).networkInterfaces().stream()
+ .map(NetworkInterface::getNetworkInterfaceId).toList());
+ assertEquals(List.of(interfaceId), service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of("association.public-ip", List.of(address.getPublicIp())), 0, null).networkInterfaces().stream()
+ .map(NetworkInterface::getNetworkInterfaceId).toList());
+ assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of("association.ip-owner-id", List.of("unmatched-owner")), 0, null).networkInterfaces().isEmpty());
+ assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of("association.public-ip", List.of("192.0.2.254")), 0, null).networkInterfaces().isEmpty());
+ assertEquals(1, service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of("association.ip-owner-id", List.of("unmatched-owner", ownerId),
+ "association.public-ip", List.of("*")), 0, null).networkInterfaces().size());
+ assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of("association.ip-owner-id", List.of(ownerId),
+ "association.public-ip", List.of("192.0.2.254")), 0, null).networkInterfaces().isEmpty());
+ service.associateAddress("us-east-1", address.getAllocationId(), other.getInstanceId());
+ assertEquals(List.of(other.getNetworkInterfaces().getFirst().getNetworkInterfaceId()),
+ service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of("association.public-ip", List.of(address.getPublicIp())), 0, null)
+ .networkInterfaces().stream().map(NetworkInterface::getNetworkInterfaceId).toList());
+ service.associateAddress("us-east-1", address.getAllocationId(), associated.getInstanceId());
+ NetworkInterface described = service.describeNetworkInterfaces("us-east-1", List.of(interfaceId),
+ Map.of(), 0, null).networkInterfaces().getFirst();
+ assertEquals(address.getAllocationId(), described.getPrivateIpAddresses().getFirst()
+ .getAssociation().getAllocationId());
+ service.disassociateAddress("us-east-1", address.getAssociationId());
+ for (String filter : List.of("association.ip-owner-id", "association.public-ip")) {
+ assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of(filter, List.of("*")), 0, null).networkInterfaces().isEmpty());
+ }
+ service.associateAddress("us-east-1", address.getAllocationId(), associated.getInstanceId());
+ if (!defaultVpc) {
+ String associationId = address.getAssociationId();
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.releaseAddress("us-east-1", address.getAllocationId()));
+ assertEquals("InvalidIPAddress.InUse", error.getErrorCode());
+ assertEquals(associationId, service.describeAddresses("us-east-1",
+ List.of(address.getAllocationId()), Map.of()).getFirst().getAssociationId());
+ NetworkInterface unchanged = service.describeNetworkInterfaces("us-east-1", List.of(interfaceId),
+ Map.of("association.public-ip", List.of(address.getPublicIp()),
+ "association.ip-owner-id", List.of(ownerId)), 0, null).networkInterfaces().getFirst();
+ assertEquals(associationId, unchanged.getPrivateIpAddresses().getFirst()
+ .getAssociation().getAssociationId());
+ service.disassociateAddress("us-east-1", associationId);
+ }
+ service.releaseAddress("us-east-1", address.getAllocationId());
+ assertTrue(service.describeAddresses("us-east-1", List.of(address.getAllocationId()), Map.of()).isEmpty());
+ assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of("association.public-ip", List.of("*")), 0, null).networkInterfaces().isEmpty());
+ assertEquals(2, service.describeNetworkInterfaces("us-east-1", List.of(), Map.of(), 0, null)
+ .networkInterfaces().size());
+ }
+
+ @ParameterizedTest
+ @CsvSource({"false,false,true", "false,true,true", "true,false,true",
+ "true,true,true", "true,false,false", "true,true,false"})
+ void terminationKeepsAddressesOnlyOnRetainedInterfaces(boolean suppliedInterface, boolean defaultVpc,
+ boolean deleteOnTermination) {
+ Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
+ when(containerManager.reachablePublicAddress(any())).thenReturn("192.0.2.10");
+ Ec2Service service = new Ec2Service(mockConfig(true), containerManager,
+ mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
+ new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
+ String region = "us-east-1";
+ String subnetId = defaultVpc
+ ? service.describeSubnets(region, List.of(), Map.of()).getFirst().getSubnetId()
+ : service.createSubnet(region, service.createVpc(region, "10.237.0.0/24", false).getVpcId(),
+ "10.237.0.0/26", region + "a").getSubnetId();
+ NetworkInterface supplied = suppliedInterface
+ ? service.createNetworkInterface(region, subnetId, null, null, List.of(), List.of(), List.of()) : null;
+ Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
+ 1, 1, null, List.of(), subnetId, null, List.of(), null, null,
+ null, supplied != null ? supplied.getNetworkInterfaceId() : null, 0).getInstances().getFirst();
+ String interfaceId = instance.getNetworkInterfaces().getFirst().getNetworkInterfaceId();
+ if (supplied != null) {
+ supplied.getAttachment().setDeleteOnTermination(deleteOnTermination);
+ }
+ Address address = service.allocateAddress(region);
+ service.associateAddress(region, address.getAllocationId(), instance.getInstanceId());
+ String associationId = address.getAssociationId();
+ service.terminateInstances(region, List.of(instance.getInstanceId()));
+ instance.setTerminatedAt(System.currentTimeMillis() - 3_600_001L);
+ service.pruneTerminatedInstances();
+
+ Address remaining = service.describeAddresses(region, List.of(address.getAllocationId()), Map.of()).getFirst();
+ assertNull(remaining.getInstanceId());
+ if (deleteOnTermination) {
+ assertNull(remaining.getAssociationId());
+ assertNull(remaining.getNetworkInterfaceId());
+ assertTrue(service.describeNetworkInterfaces(region, List.of(),
+ Map.of("association.public-ip", List.of("*")), 0, null).networkInterfaces().isEmpty());
+ } else {
+ assertEquals(associationId, remaining.getAssociationId());
+ assertEquals("192.0.2.10", remaining.getPublicIp());
+ assertEquals(interfaceId, remaining.getNetworkInterfaceId());
+ NetworkInterface retained = service.describeNetworkInterfaces(region, List.of(interfaceId),
+ Map.of("association.public-ip", List.of(remaining.getPublicIp())), 0, null)
+ .networkInterfaces().getFirst();
+ assertNull(retained.getAttachment());
+ assertEquals("available", retained.getStatus());
+ if (!defaultVpc) {
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.releaseAddress(region, address.getAllocationId()));
+ assertEquals("InvalidIPAddress.InUse", error.getErrorCode());
+ service.deleteNetworkInterface(region, interfaceId);
+ assertNull(service.describeAddresses(region, List.of(address.getAllocationId()), Map.of())
+ .getFirst().getAssociationId());
+ }
+ }
+ service.releaseAddress(region, address.getAllocationId());
+ assertTrue(service.describeAddresses(region, List.of(address.getAllocationId()), Map.of()).isEmpty());
+ }
+
+ @Test
+ void networkInterfaceAssociationFiltersExcludeSecondaryAddressAssociations() {
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
+ new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
+ String subnetId = service.describeSubnets("us-east-1", List.of(), Map.of()).getFirst().getSubnetId();
+ NetworkInterface eni = service.createNetworkInterface("us-east-1", subnetId, null,
+ null, List.of(), List.of(), List.of());
+ NetworkInterfacePrivateIpAddress primary = eni.getPrivateIpAddresses().getFirst();
+ NetworkInterfaceAssociation primaryAssociation = new NetworkInterfaceAssociation();
+ primaryAssociation.setIpOwnerId("primary-owner");
+ primaryAssociation.setPublicIp("192.0.2.10");
+ primary.setAssociation(primaryAssociation);
+ NetworkInterfacePrivateIpAddress secondary = new NetworkInterfacePrivateIpAddress();
+ secondary.setPrivateIpAddress("172.31.0.99");
+ NetworkInterfaceAssociation secondaryAssociation = new NetworkInterfaceAssociation();
+ secondaryAssociation.setIpOwnerId("secondary-owner");
+ secondaryAssociation.setPublicIp("192.0.2.20");
+ secondary.setAssociation(secondaryAssociation);
+ eni.getPrivateIpAddresses().add(secondary);
+
+ assertEquals(1, service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of("association.ip-owner-id", List.of("primary-owner"),
+ "association.public-ip", List.of("192.0.2.10")), 0, null).networkInterfaces().size());
+ assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of("association.ip-owner-id", List.of("secondary-owner")), 0, null).networkInterfaces().isEmpty());
+ assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of("association.public-ip", List.of("192.0.2.20")), 0, null).networkInterfaces().isEmpty());
+ primary.setAssociation(null);
+ for (String filter : List.of("association.ip-owner-id", "association.public-ip")) {
+ assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of(filter, List.of("*")), 0, null).networkInterfaces().isEmpty());
+ }
+ primary.setAssociation(new NetworkInterfaceAssociation());
+ for (String filter : List.of("association.ip-owner-id", "association.public-ip")) {
+ assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(),
+ Map.of(filter, List.of("*")), 0, null).networkInterfaces().isEmpty());
+ }
+ }
+
@Test
void awaitContainerLaunchReportsTerminatedContainer() {
Ec2Service service = new Ec2Service(mockConfig(false), mock(Ec2ContainerManager.class),