feat(ec2): support standalone network interface create/attach/detach (#2843)

* feat(ec2): support standalone network interface create/attach/detach

CreateNetworkInterface returned UnsupportedOperation unconditionally,
blocking every root that attaches a standalone ENI: the attach-eni and
override-default-eni examples in terraform-aws-server, the with-elb
example in terraform-aws-asg, and vpc-blackhole-routes in
terraform-aws-service-catalog (floci-kt9 in the floci-harness compat
survey).

Adds CreateNetworkInterface, DeleteNetworkInterface,
AttachNetworkInterface and DetachNetworkInterface, backed by a new
standalone ENI store separate from the implicit primary interface each
instance already carries. DescribeNetworkInterfaces now merges both
without double-counting. RunInstances also accepts a pre-existing
standalone ENI as an instance's primary interface via
NetworkInterface.1.NetworkInterfaceId, the shape Terraform's
network_interface { network_interface_id = ... } block sends for
override-default-eni.

* fix(ec2): keep a standalone ENI's own record when it is attached

Review found two ways the attachment state ended up recorded on only one side.

AttachNetworkInterface updated the standalone ENI and stopped there, so
DescribeNetworkInterfaces reported an attachment that DescribeInstances denied —
and the device-index conflict check, which reads the instance's own interface
list, could never see anything this operation had attached: two interfaces could
take device index 1 on the same instance. The instance now carries the interface
too, and DetachNetworkInterface removes it again.

RunInstances took the opposite approach and deleted the standalone record,
leaving the interface represented only inside the instance. Terminating that
instance then made a caller-created ENI vanish -- InvalidNetworkInterfaceID.
NotFound rather than returning to "available" -- so it could not be reused. AWS
attaches a pre-existing interface with deleteOnTermination false precisely so it
outlives the instance. The standalone record is now kept and marked attached,
and terminate releases it; describeNetworkInterfaces skips the instance-side
copy of any id the standalone store owns, so it is still reported exactly once,
from the side that knows its real attach time and its deleteOnTermination.

Also braces a single-line conditional, per AGENTS.md.

* fix(ec2): release an ENI whose instance died without TerminateInstances

TerminateInstances is not the only way an instance reaches "terminated": a
container-backed launch that fails or is cancelled ends there asynchronously,
inside Ec2ContainerManager, which has no access to the interface store. An ENI
the launch had already marked in-use therefore stayed pinned to an instance that
no longer runs, and every later attempt to reuse it failed with
InvalidNetworkInterface.InUse.

Rather than chase each terminal transition, the attachment is reconciled when
the interface is next read: an attachment naming an instance that is gone or
terminated is cleared, and the interface reports "available" again. That covers
attach, launch, delete and describe through the one path they share.

* fix(ec2): let a dead instance release its copy of a reclaimed ENI

Releasing the standalone record alone left the terminated instance still
reporting the interface, so once the ENI was reused two instance records claimed
it and nothing in DescribeInstances picks a winner. Reclaiming now clears both
sides, and the unit test asserts the instance no longer lists it.

Also drops the em-dashes from the comments and docs this branch adds, per
AGENTS.md.

* fix(ec2): drop the instance's copy on the TerminateInstances path too

The previous commit fixed only the reclaim-on-read path. TerminateInstances
released the standalone record while leaving the mirrored interface on the
terminated instance, so reusing the ENI still produced two instance records
claiming it. Both paths now clear the instance's copy, and the integration test
asserts DescribeInstances no longer mentions the interface before the same ENI
is handed to a second launch.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-01 18:21:57 -04:00
1 parent 7828ab2430
commit 906af8c632
6 files changed
+1092 -66

No files matched your search

+9 -1
View File
@@ -569,7 +569,15 @@ prefix lists, `EnaSrdSpecification`, `ConnectionTrackingSpecification`, `Primary
| Action | Description |
|--------|-------------|
| DescribeNetworkInterfaces | Lists network interfaces known to the local EC2 service. |
| CreateNetworkInterface | Creates a standalone elastic network interface (ENI) in a subnet, unattached. |
| DescribeNetworkInterfaces | Lists network interfaces known to the local EC2 service, both an instance's implicit primary interface and standalone ENIs created via `CreateNetworkInterface`. |
| AttachNetworkInterface | Attaches an available standalone ENI to a running or stopped instance at a device index. |
| DetachNetworkInterface | Detaches a standalone ENI by attachment ID, returning it to `available`. |
| DeleteNetworkInterface | Deletes a standalone ENI. Fails while the ENI is still attached, matching AWS. |
A standalone ENI created via `CreateNetworkInterface` can also be handed to `RunInstances` as an instance's primary interface (`NetworkInterface.1.NetworkInterfaceId` / `NetworkInterface.1.DeviceIndex`) instead of letting the instance create its own implicit one, the pattern Terraform's `aws_instance` resource uses for `network_interface { network_interface_id = ... }`. AWS only allows this for a single instance per launch call; `RunInstances` rejects it otherwise with `InvalidParameterCombination`.
`ModifyNetworkInterfaceAttribute` is not implemented: no example in the corpus that needed `CreateNetworkInterface` was found to need it. A route table's `CreateRoute` with a `NetworkInterfaceId` target is accepted but not recorded, since `Route` does not yet model an ENI target; a subsequent `plan` against such a route may show drift.
### Volumes
@@ -232,6 +232,10 @@ public class Ec2QueryHandler {
case "DeleteLaunchTemplate" -> handleDeleteLaunchTemplate(params, region);
// Network Interfaces
case "DescribeNetworkInterfaces" -> handleDescribeNetworkInterfaces(params, region);
case "CreateNetworkInterface" -> handleCreateNetworkInterface(params, region);
case "DeleteNetworkInterface" -> handleDeleteNetworkInterface(params, region);
case "AttachNetworkInterface" -> handleAttachNetworkInterface(params, region);
case "DetachNetworkInterface" -> handleDetachNetworkInterface(params, region);
// Volumes
case "CreateVolume" -> handleCreateVolume(params, region);
case "DescribeVolumes" -> handleDescribeVolumes(params, region);
@@ -609,6 +613,10 @@ public class Ec2QueryHandler {
if (subnetId == null) {
subnetId = p.getFirst("NetworkInterface.1.SubnetId");
}
// 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");
int networkInterfaceDeviceIndex = parseIntParam(p, "NetworkInterface.1.DeviceIndex", 0);
String clientToken = p.getFirst("ClientToken");
List<String> sgIds = getList(p, "SecurityGroupId");
@@ -665,7 +673,7 @@ public class Ec2QueryHandler {
Reservation res = service.runInstances(region, imageId, instanceType, minCount, maxCount,
keyName, sgIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn,
associatePublicIp);
associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex);
if (!networkInterfaceTags.isEmpty()) {
List<String> eniIds = new ArrayList<>();
@@ -3499,61 +3507,7 @@ public class Ec2QueryHandler {
.elem("requestId", UUID.randomUUID().toString())
.start("networkInterfaceSet");
for (NetworkInterface ni : nis) {
xml.start("item")
.elem("networkInterfaceId", ni.getNetworkInterfaceId())
.elem("subnetId", ni.getSubnetId())
.elem("vpcId", ni.getVpcId())
.elem("availabilityZone", ni.getAvailabilityZone())
.elem("description", ni.getDescription())
.elem("ownerId", ni.getOwnerId())
.elem("status", ni.getStatus())
.elem("interfaceType", ni.getInterfaceType())
.elem("macAddress", ni.getMacAddress())
.elem("privateIpAddress", ni.getPrivateIpAddress())
.elem("privateDnsName", ni.getPrivateDnsName())
.elem("sourceDestCheck", String.valueOf(ni.isSourceDestCheck()))
.start("groupSet");
for (GroupIdentifier gi : ni.getGroups()) {
xml.start("item")
.elem("groupId", gi.getGroupId())
.elem("groupName", gi.getGroupName())
.end("item");
}
xml.end("groupSet");
// Phase 3: tagSet from instance tags
xml.raw(tagSetXml(ni.getTagSet()));
if (ni.getAttachment() != null) {
xml.start("attachment")
.elem("attachmentId", ni.getAttachment().getAttachmentId())
.elem("deviceIndex", String.valueOf(ni.getAttachment().getDeviceIndex()))
.elem("status", ni.getAttachment().getStatus())
.elem("attachTime", ni.getAttachment().getAttachTime())
.elem("deleteOnTermination", String.valueOf(ni.getAttachment().isDeleteOnTermination()))
.elem("instanceId", ni.getAttachment().getInstanceId())
.elem("instanceOwnerId", ni.getAttachment().getInstanceOwnerId())
.end("attachment");
}
// Phase 3: privateIpAddressesSet with association
if (!ni.getPrivateIpAddresses().isEmpty()) {
xml.start("privateIpAddressesSet");
for (NetworkInterfacePrivateIpAddress ip : ni.getPrivateIpAddresses()) {
xml.start("item")
.elem("privateIpAddress", ip.getPrivateIpAddress())
.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.end("item");
}
xml.end("privateIpAddressesSet");
}
xml.end("item");
xml.start("item").raw(networkInterfaceXml(ni)).end("item");
}
xml.end("networkInterfaceSet");
if (result.nextToken() != null) {
@@ -3563,6 +3517,118 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
/** Shared field emission for a {@code networkInterface} item, used by Describe and Create. */
private String networkInterfaceXml(NetworkInterface ni) {
XmlBuilder xml = new XmlBuilder()
.elem("networkInterfaceId", ni.getNetworkInterfaceId())
.elem("subnetId", ni.getSubnetId())
.elem("vpcId", ni.getVpcId())
.elem("availabilityZone", ni.getAvailabilityZone())
.elem("description", ni.getDescription())
.elem("ownerId", ni.getOwnerId())
.elem("status", ni.getStatus())
.elem("interfaceType", ni.getInterfaceType())
.elem("macAddress", ni.getMacAddress())
.elem("privateIpAddress", ni.getPrivateIpAddress())
.elem("privateDnsName", ni.getPrivateDnsName())
.elem("sourceDestCheck", String.valueOf(ni.isSourceDestCheck()))
.start("groupSet");
for (GroupIdentifier gi : ni.getGroups()) {
xml.start("item")
.elem("groupId", gi.getGroupId())
.elem("groupName", gi.getGroupName())
.end("item");
}
xml.end("groupSet");
xml.raw(tagSetXml(ni.getTagSet()));
if (ni.getAttachment() != null) {
xml.start("attachment")
.elem("attachmentId", ni.getAttachment().getAttachmentId())
.elem("deviceIndex", String.valueOf(ni.getAttachment().getDeviceIndex()))
.elem("status", ni.getAttachment().getStatus())
.elem("attachTime", ni.getAttachment().getAttachTime())
.elem("deleteOnTermination", String.valueOf(ni.getAttachment().isDeleteOnTermination()))
.elem("instanceId", ni.getAttachment().getInstanceId())
.elem("instanceOwnerId", ni.getAttachment().getInstanceOwnerId())
.end("attachment");
}
if (!ni.getPrivateIpAddresses().isEmpty()) {
xml.start("privateIpAddressesSet");
for (NetworkInterfacePrivateIpAddress ip : ni.getPrivateIpAddresses()) {
xml.start("item")
.elem("privateIpAddress", ip.getPrivateIpAddress())
.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.end("item");
}
xml.end("privateIpAddressesSet");
}
return xml.build();
}
private Response handleCreateNetworkInterface(MultivaluedMap<String, String> p, String region) {
String subnetId = p.getFirst("SubnetId");
String description = p.getFirst("Description");
String privateIpAddress = p.getFirst("PrivateIpAddress");
List<String> privateIpAddresses = new ArrayList<>();
for (int i = 1; ; i++) {
String addr = p.getFirst("PrivateIpAddresses." + i + ".PrivateIpAddress");
if (addr == null) {
break;
}
privateIpAddresses.add(addr);
}
List<String> securityGroupIds = getList(p, "SecurityGroupId");
if (securityGroupIds.isEmpty()) {
securityGroupIds = getList(p, "Groups.SecurityGroupId");
}
List<Tag> tagList = parseTagsForResource(p, "network-interface");
NetworkInterface ni = service.createNetworkInterface(region, subnetId, description,
privateIpAddress, privateIpAddresses, securityGroupIds, tagList);
XmlBuilder xml = new XmlBuilder()
.start("CreateNetworkInterfaceResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("networkInterface").raw(networkInterfaceXml(ni)).end("networkInterface")
.end("CreateNetworkInterfaceResponse");
return xmlResponse(xml.build());
}
private Response handleDeleteNetworkInterface(MultivaluedMap<String, String> p, String region) {
service.deleteNetworkInterface(region, p.getFirst("NetworkInterfaceId"));
return booleanResponse("DeleteNetworkInterface");
}
private Response handleAttachNetworkInterface(MultivaluedMap<String, String> p, String region) {
String networkInterfaceId = p.getFirst("NetworkInterfaceId");
String instanceId = p.getFirst("InstanceId");
int deviceIndex = parseIntParam(p, "DeviceIndex", 0);
NetworkInterfaceAttachment attachment =
service.attachNetworkInterface(region, networkInterfaceId, instanceId, deviceIndex);
XmlBuilder xml = new XmlBuilder()
.start("AttachNetworkInterfaceResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.elem("attachmentId", attachment.getAttachmentId())
.end("AttachNetworkInterfaceResponse");
return xmlResponse(xml.build());
}
private Response handleDetachNetworkInterface(MultivaluedMap<String, String> p, String region) {
String attachmentId = p.getFirst("AttachmentId");
boolean force = "true".equalsIgnoreCase(p.getFirst("Force"));
service.detachNetworkInterface(region, attachmentId, force);
return booleanResponse("DetachNetworkInterface");
}
// ─── XML fragment builders ────────────────────────────────────────────────
private String instanceXml(Instance inst) {
@@ -174,6 +174,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
private final StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes;
// Keyed by id alone, not region::id — see VpcPeeringConnection's class Javadoc.
private final StorageBackend<String, VpcPeeringConnection> vpcPeeringConnections;
// Standalone (non-primary) ENIs created via CreateNetworkInterface, see #floci-kt9.
// Primary/implicit per-instance ENIs remain embedded in Instance#networkInterfaces.
private final StorageBackend<String, NetworkInterface> networkInterfaces;
// resourceId → List<Tag>
private final StorageBackend<String, List<Tag>> tags;
private final Set<String> seededRegions = ConcurrentHashMap.newKeySet();
@@ -227,6 +230,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
new TypeReference<Map<String, TransitGatewayRoute>>() {}),
storageFactory.create("ec2", "ec2-vpc-peering-connections.json",
new TypeReference<Map<String, VpcPeeringConnection>>() {}),
storageFactory.create("ec2", "ec2-network-interfaces.json",
new TypeReference<Map<String, NetworkInterface>>() {}),
requestContextInstance);
}
@@ -259,7 +264,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), null);
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), null);
}
// Package-private for hermetic tests, transit-gateway-aware. The shorter overload above keeps its
@@ -298,7 +304,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
transitGateways, transitGatewayRouteTables, transitGatewayVpcAttachments,
transitGatewayPropagations, transitGatewayRoutes, vpcPeeringConnections, null);
transitGatewayPropagations, transitGatewayRoutes, vpcPeeringConnections,
new InMemoryStorage<>(), null);
}
// Package-private for hermetic tests that also need to control which account a caller resolves
@@ -332,6 +339,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
StorageBackend<String, TransitGatewayRouteTablePropagation> transitGatewayPropagations,
StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes,
StorageBackend<String, VpcPeeringConnection> vpcPeeringConnections,
StorageBackend<String, NetworkInterface> networkInterfaces,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance) {
this.accountId = config.defaultAccountId();
this.requestContextInstance = requestContextInstance;
@@ -366,6 +374,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
this.transitGatewayPropagations = transitGatewayPropagations;
this.transitGatewayRoutes = transitGatewayRoutes;
this.vpcPeeringConnections = vpcPeeringConnections;
this.networkInterfaces = networkInterfaces;
}
@PostConstruct
@@ -1043,6 +1052,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return sb.toString();
}
/** Synthesizes a locally-administered unicast MAC (AWS never discloses how it derives its own). */
private String randomMac() {
Random rand = new Random();
StringBuilder sb = new StringBuilder("02");
for (int i = 0; i < 5; i++) {
sb.append(':').append(String.format("%02x", rand.nextInt(256)));
}
return sb.toString();
}
// ─── Transit Gateways ──────────────────────────────────────────────────────
/**
@@ -2188,11 +2207,41 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String clientToken, List<Tag> instanceTags,
String userData, String iamInstanceProfileArn,
Boolean associatePublicIp) {
return runInstances(region, imageId, instanceType, minCount, maxCount, keyName,
securityGroupIds, subnetId, clientToken, instanceTags, userData,
iamInstanceProfileArn, associatePublicIp, null, 0);
}
/**
* @param networkInterfaceId a pre-existing standalone ENI (from {@link #createNetworkInterface})
* to use as the instance's primary interface instead of creating a
* new implicit one, the override-default-eni pattern (floci-kt9).
* AWS requires {@code subnetId} be omitted when this is set; the
* interface's own subnet/VPC/security-groups govern the launch.
*/
public Reservation runInstances(String region, String imageId, String instanceType,
int minCount, int maxCount, String keyName,
List<String> securityGroupIds, String subnetId,
String clientToken, List<Tag> instanceTags,
String userData, String iamInstanceProfileArn,
Boolean associatePublicIp, String networkInterfaceId, int networkInterfaceDeviceIndex) {
if (imageId == null || imageId.isBlank()) {
throw new AwsException("MissingParameter", "The request must contain the parameter ImageId", 400);
}
ensureDefaultResources(region);
// floci-kt9: a caller-supplied primary ENI (override-default-eni) governs its own
// subnet/VPC/security-groups and can only ever back a single instance.
NetworkInterface suppliedEni = null;
if (networkInterfaceId != null && !networkInterfaceId.isBlank()) {
if (Math.max(minCount, 1) > 1) {
throw new AwsException("InvalidParameterCombination",
"Network interfaces may only be specified for a single instance.", 400);
}
suppliedEni = takeNetworkInterfaceForLaunch(region, networkInterfaceId);
subnetId = suppliedEni.getSubnetId();
}
// Resolve subnet
Subnet subnet = null;
if (subnetId != null && !subnetId.isEmpty()) {
@@ -2211,7 +2260,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
// Resolve security groups
List<GroupIdentifier> sgIdentifiers = new ArrayList<>();
if (securityGroupIds != null && !securityGroupIds.isEmpty()) {
if (suppliedEni != null) {
// AWS ignores instance-level SecurityGroupId when a network interface is supplied;
// the interface's own groups win (module main.tf sets vpc_security_group_ids = null
// in this case, so there is nothing to conflict with in practice).
sgIdentifiers.addAll(suppliedEni.getGroups());
} else if (securityGroupIds != null && !securityGroupIds.isEmpty()) {
for (String sgId : securityGroupIds) {
SecurityGroup sg = getRequiredSecurityGroup(region, sgId);
sgIdentifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
@@ -2235,7 +2289,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String architecture = architectureFor(imageId, effectiveInstanceType);
for (int i = 0; i < count; i++) {
String instanceId = "i-" + randomHex(17);
String privateIp = assignPrivateIp(region, finalSubnetId);
String privateIp = suppliedEni != null
? suppliedEni.getPrivateIpAddress()
: assignPrivateIp(region, finalSubnetId);
Instance inst = new Instance();
inst.setInstanceId(instanceId);
@@ -2267,21 +2323,43 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
tags.put(instanceId, new ArrayList<>(instanceTags));
}
// Network interface
// Network interface, either the caller-supplied standalone ENI (override-default-eni,
// floci-kt9) or a freshly-minted implicit primary interface.
InstanceNetworkInterface eni = new InstanceNetworkInterface();
eni.setNetworkInterfaceId("eni-" + randomHex(17));
eni.setNetworkInterfaceId(suppliedEni != null ? suppliedEni.getNetworkInterfaceId() : "eni-" + randomHex(17));
eni.setSubnetId(finalSubnetId);
eni.setVpcId(vpcId);
eni.setOwnerId(accountId);
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
eni.setPrivateIpAddress(privateIp);
eni.setPrivateDnsName(inst.getPrivateDnsName());
eni.setGroups(new ArrayList<>(sgIdentifiers));
eni.setAttachmentId("eni-attach-" + randomHex(17));
eni.setDeviceIndex(0);
eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0);
if (inst.getLaunchTime() != null) {
eni.setAttachTime(ISO_FMT.format(inst.getLaunchTime()));
}
inst.getNetworkInterfaces().add(eni);
if (suppliedEni != null) {
// The standalone record stays authoritative rather than being folded into the
// instance: AWS defaults deleteOnTermination to false for an interface the caller
// created and handed to a launch, so it outlives the instance and returns to
// "available" on termination instead of vanishing with it. Double-counting is
// avoided in describeNetworkInterfaces, which skips the instance-side copy of any
// id the standalone store owns.
NetworkInterfaceAttachment launchAttachment = new NetworkInterfaceAttachment();
launchAttachment.setAttachmentId(eni.getAttachmentId());
launchAttachment.setDeviceIndex(eni.getDeviceIndex());
launchAttachment.setStatus("attached");
launchAttachment.setInstanceId(instanceId);
launchAttachment.setInstanceOwnerId(accountId);
launchAttachment.setAttachTime(eni.getAttachTime());
launchAttachment.setDeleteOnTermination(false);
suppliedEni.setAttachment(launchAttachment);
suppliedEni.setStatus("in-use");
networkInterfaces.put(key(region, suppliedEni.getNetworkInterfaceId()), suppliedEni);
}
// Root EBS volume
String rootVolId = "vol-" + randomHex(17);
@@ -2529,6 +2607,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
if (inst.getRootVolumeId() != null) {
volumes.delete(key(region, inst.getRootVolumeId()));
}
releaseStandaloneInterfacesOnTermination(region, inst);
instances.put(key(region, id), inst);
Map<String, String> entry = new LinkedHashMap<>();
entry.put("instanceId", id);
@@ -6141,6 +6220,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
&& !networkInterfaceIds.contains(eni.getNetworkInterfaceId())) {
continue;
}
// A standalone ENI attached to this instance is reported from its own record
// below, which is the side that knows its real attach time and its
// deleteOnTermination, both of which the instance-side copy would guess wrong.
if (networkInterfaces.get(key(region, eni.getNetworkInterfaceId())).isPresent()) {
continue;
}
foundIds.add(eni.getNetworkInterfaceId());
NetworkInterface ni = new NetworkInterface();
ni.setNetworkInterfaceId(eni.getNetworkInterfaceId());
@@ -6207,6 +6292,25 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
}
}
// floci-kt9: standalone ENIs created via CreateNetworkInterface. Only added when not
// already surfaced above, an ENI used as an instance's launch-time interface (e.g. via
// RunInstances' NetworkInterface.1.NetworkInterfaceId, the override-default-eni pattern)
// is represented on the instance and would otherwise be double-counted here.
for (NetworkInterface standalone : networkInterfaces.scan(k -> k.startsWith(region + "::"))) {
NetworkInterface ni = releaseIfHostIsGone(region, standalone);
if (foundIds.contains(ni.getNetworkInterfaceId())) {
continue;
}
if (!networkInterfaceIds.isEmpty() && !networkInterfaceIds.contains(ni.getNetworkInterfaceId())) {
continue;
}
foundIds.add(ni.getNetworkInterfaceId());
if (!matchesFilters(ni, filters, region)) {
continue;
}
result.add(ni);
}
// Phase 6: validate requested IDs exist
for (String id : networkInterfaceIds) {
if (!foundIds.contains(id)) {
@@ -6231,6 +6335,262 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return new NetworkInterfaceListResult(result, null);
}
/**
* Creates a standalone (not-yet-attached) elastic network interface, floci-kt9. Covers the
* {@code aws_network_interface} resource: an ENI created independently of an instance and
* either attached later (the attach-eni pattern) or handed to an instance at launch time as
* its primary interface (the override-default-eni pattern, see {@link #runInstances}).
*/
public NetworkInterface createNetworkInterface(String region, String subnetId, String description,
String privateIpAddress, List<String> privateIpAddresses,
List<String> securityGroupIds, List<Tag> tagList) {
if (subnetId == null || subnetId.isBlank()) {
throw new AwsException("MissingParameter",
"The request must contain the parameter SubnetId", 400);
}
ensureDefaultResources(region);
Subnet subnet = requireSubnet(region, subnetId);
List<GroupIdentifier> sgIdentifiers = new ArrayList<>();
if (securityGroupIds != null && !securityGroupIds.isEmpty()) {
for (String sgId : securityGroupIds) {
SecurityGroup sg = getRequiredSecurityGroup(region, sgId);
sgIdentifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
}
} else {
SecurityGroup defaultSg = securityGroups.get(key(region, resolveDefaultSecurityGroupId(region))).orElse(null);
if (defaultSg != null) {
sgIdentifiers.add(new GroupIdentifier(defaultSg.getGroupId(), defaultSg.getGroupName()));
}
}
String eniId = "eni-" + randomHex(17);
String primaryIp = (privateIpAddress != null && !privateIpAddress.isBlank())
? privateIpAddress : assignPrivateIp(region, subnetId);
String primaryDns = "ip-" + primaryIp.replace('.', '-') + ".ec2.internal";
NetworkInterface ni = new NetworkInterface();
ni.setNetworkInterfaceId(eniId);
ni.setSubnetId(subnetId);
ni.setVpcId(subnet.getVpcId());
ni.setAvailabilityZone(subnet.getAvailabilityZone());
ni.setDescription(description);
ni.setOwnerId(accountId);
ni.setStatus("available");
ni.setMacAddress(randomMac());
ni.setPrivateIpAddress(primaryIp);
ni.setPrivateDnsName(primaryDns);
ni.setGroups(sgIdentifiers);
if (tagList != null) {
ni.getTagSet().addAll(tagList);
}
List<NetworkInterfacePrivateIpAddress> ipList = new ArrayList<>();
NetworkInterfacePrivateIpAddress primary = new NetworkInterfacePrivateIpAddress();
primary.setPrivateIpAddress(primaryIp);
primary.setPrivateDnsName(primaryDns);
primary.setPrimary(true);
ipList.add(primary);
if (privateIpAddresses != null) {
for (String extra : privateIpAddresses) {
if (extra == null || extra.isBlank() || extra.equals(primaryIp)) {
continue;
}
NetworkInterfacePrivateIpAddress secondary = new NetworkInterfacePrivateIpAddress();
secondary.setPrivateIpAddress(extra);
secondary.setPrivateDnsName("ip-" + extra.replace('.', '-') + ".ec2.internal");
secondary.setPrimary(false);
ipList.add(secondary);
}
}
ni.setPrivateIpAddresses(ipList);
networkInterfaces.put(key(region, eniId), ni);
return ni;
}
/** Deletes a standalone ENI. AWS refuses while it is still attached, floci-kt9. */
public void deleteNetworkInterface(String region, String networkInterfaceId) {
NetworkInterface ni = requireStandaloneNetworkInterface(region, networkInterfaceId);
if (ni.getAttachment() != null) {
throw new AwsException("InvalidParameterValue",
"Network interface '" + networkInterfaceId + "' is currently in use", 400);
}
networkInterfaces.delete(key(region, networkInterfaceId));
}
/**
* Attaches a standalone ENI to a running/stopped instance at the given device index,
* the attach-eni example's runtime pattern (its user-data script calls this via the AWS CLI
* after boot, rather than through the Terraform provider itself). floci-kt9.
*/
public NetworkInterfaceAttachment attachNetworkInterface(String region, String networkInterfaceId,
String instanceId, int deviceIndex) {
NetworkInterface ni = requireStandaloneNetworkInterface(region, networkInterfaceId);
if (ni.getAttachment() != null) {
throw new AwsException("InvalidNetworkInterface.InUse",
"Interface: '" + networkInterfaceId + "' is currently in use.", 400);
}
Instance inst = getRequiredInstance(region, instanceId);
if (!List.of("running", "stopped").contains(inst.getState().getName())) {
throw new AwsException("IncorrectInstanceState",
"The instance '" + instanceId + "' is not in a state from which an interface can be attached", 400);
}
boolean indexTaken = inst.getNetworkInterfaces().stream()
.anyMatch(eni -> eni.getDeviceIndex() == deviceIndex);
if (indexTaken) {
throw new AwsException("InvalidParameterValue",
"Device index " + deviceIndex + " is already in use on instance '" + instanceId + "'", 400);
}
NetworkInterfaceAttachment attachment = new NetworkInterfaceAttachment();
attachment.setAttachmentId("eni-attach-" + randomHex(17));
attachment.setDeviceIndex(deviceIndex);
attachment.setStatus("attached");
attachment.setInstanceId(instanceId);
attachment.setInstanceOwnerId(accountId);
attachment.setAttachTime(ISO_FMT.format(Instant.now()));
attachment.setDeleteOnTermination(false);
ni.setAttachment(attachment);
ni.setStatus("in-use");
networkInterfaces.put(key(region, networkInterfaceId), ni);
// The instance must carry it as well, or DescribeInstances would deny an attachment
// DescribeNetworkInterfaces reports, and the device-index check above, which reads this
// very list, would never see an interface attached by this method.
InstanceNetworkInterface attached = new InstanceNetworkInterface();
attached.setNetworkInterfaceId(ni.getNetworkInterfaceId());
attached.setSubnetId(ni.getSubnetId());
attached.setVpcId(ni.getVpcId());
attached.setDescription(ni.getDescription());
attached.setOwnerId(ni.getOwnerId());
attached.setStatus("in-use");
attached.setMacAddress(ni.getMacAddress());
attached.setPrivateIpAddress(ni.getPrivateIpAddress());
attached.setPrivateDnsName(ni.getPrivateDnsName());
attached.setGroups(new ArrayList<>(ni.getGroups()));
attached.setAttachmentId(attachment.getAttachmentId());
attached.setDeviceIndex(deviceIndex);
attached.setAttachTime(attachment.getAttachTime());
inst.getNetworkInterfaces().add(attached);
instances.put(key(region, instanceId), inst);
return attachment;
}
/** Detaches a standalone ENI by attachment id, floci-kt9. */
public NetworkInterfaceAttachment detachNetworkInterface(String region, String attachmentId, boolean force) {
if (attachmentId == null || attachmentId.isBlank()) {
throw new AwsException("MissingParameter", "The request must contain the parameter AttachmentId", 400);
}
NetworkInterface ni = networkInterfaces.scan(k -> k.startsWith(region + "::")).stream()
.filter(n -> n.getAttachment() != null && attachmentId.equals(n.getAttachment().getAttachmentId()))
.findFirst()
.orElseThrow(() -> new AwsException("InvalidAttachmentID.NotFound",
"The attachment ID '" + attachmentId + "' does not exist", 400));
NetworkInterfaceAttachment detached = ni.getAttachment();
ni.setAttachment(null);
ni.setStatus("available");
networkInterfaces.put(key(region, ni.getNetworkInterfaceId()), ni);
detachFromInstance(region, detached.getInstanceId(), ni.getNetworkInterfaceId());
return detached;
}
/** Removes an interface from an instance's own list, the mirror of attaching it. */
private void detachFromInstance(String region, String instanceId, String networkInterfaceId) {
if (instanceId == null) {
return;
}
Instance inst = instances.get(key(region, instanceId)).orElse(null);
if (inst == null) {
return;
}
if (inst.getNetworkInterfaces().removeIf(
e -> networkInterfaceId.equals(e.getNetworkInterfaceId()))) {
instances.put(key(region, instanceId), inst);
}
}
/**
* Releases the standalone ENIs an instance holds when it is terminated. An interface the
* caller created is not the instance's to destroy unless it was attached with
* deleteOnTermination, AWS returns it to "available", and only a launch-created interface
* dies with its instance.
*/
private void releaseStandaloneInterfacesOnTermination(String region, Instance inst) {
for (InstanceNetworkInterface e : List.copyOf(inst.getNetworkInterfaces())) {
NetworkInterface ni = networkInterfaces.get(key(region, e.getNetworkInterfaceId())).orElse(null);
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()) {
networkInterfaces.delete(key(region, ni.getNetworkInterfaceId()));
continue;
}
ni.setAttachment(null);
ni.setStatus("available");
networkInterfaces.put(key(region, ni.getNetworkInterfaceId()), ni);
}
}
private NetworkInterface requireStandaloneNetworkInterface(String region, String networkInterfaceId) {
NetworkInterface ni = networkInterfaces.get(key(region, networkInterfaceId)).orElseThrow(() ->
new AwsException("InvalidNetworkInterfaceID.NotFound",
"The network interface ID '" + networkInterfaceId + "' does not exist", 400));
return releaseIfHostIsGone(region, ni);
}
/**
* Clears an attachment whose instance no longer exists. TerminateInstances is not the only way
* an instance reaches "terminated": a container-backed launch that fails or is cancelled ends
* there asynchronously, inside the container manager, which has no access to this store. An
* interface must not stay pinned to an instance that is gone, in AWS an ENI outlives its
* instance as "available", it does not outlive it stuck "in-use" and unusable. Reconciling on
* read covers every such path at once, rather than chasing each terminal transition.
*/
private NetworkInterface releaseIfHostIsGone(String region, NetworkInterface ni) {
NetworkInterfaceAttachment attachment = ni.getAttachment();
if (attachment == null || attachment.getInstanceId() == null) {
return ni;
}
Instance host = instances.get(key(region, attachment.getInstanceId())).orElse(null);
boolean hostIsGone = host == null || host.getState() == null
|| "terminated".equals(host.getState().getName());
if (!hostIsGone) {
return ni;
}
ni.setAttachment(null);
ni.setStatus("available");
networkInterfaces.put(key(region, ni.getNetworkInterfaceId()), ni);
// The dead instance has to let go of its copy as well. Releasing only the standalone
// record would leave the terminated instance still reporting the interface, so once it is
// reused two instance records would claim it, and a real one is not the winner by any
// rule DescribeInstances applies.
detachFromInstance(region, attachment.getInstanceId(), ni.getNetworkInterfaceId());
return ni;
}
/**
* Looks up a standalone ENI for use as an instance's launch-time primary interface (the
* override-default-eni pattern, RunInstances' {@code NetworkInterface.1.NetworkInterfaceId}).
* Package-private: called from {@link #runInstances} only.
*/
NetworkInterface takeNetworkInterfaceForLaunch(String region, String networkInterfaceId) {
NetworkInterface ni = requireStandaloneNetworkInterface(region, networkInterfaceId);
if (ni.getAttachment() != null) {
throw new AwsException("InvalidNetworkInterface.InUse",
"Interface: '" + networkInterfaceId + "' is currently in use.", 400);
}
return ni;
}
// ─── Pagination token encoding / decoding ──────────────────────────────────
private String encodeToken(int offset) {
@@ -0,0 +1,547 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.containsString;
/**
* Integration tests for standalone elastic network interfaces over the EC2 Query protocol,
* floci-kt9: {@code CreateNetworkInterface} previously returned {@code UnsupportedOperation}
* unconditionally, blocking every root that attaches a standalone ENI (the attach-eni and
* override-default-eni patterns in terraform-aws-server/terraform-aws-asg/
* terraform-aws-service-catalog).
*
* <p>Covers the full lifecycle the blocked roots exercise: create, describe (including the
* pagination/filter surface DescribeNetworkInterfaces already had), attach to a running instance,
* detach, and delete, plus RunInstances accepting a pre-existing standalone ENI as an instance's
* primary interface (override-default-eni).
*
* <p>Ordered because the cases build on one ENI and one instance, mirroring how a client drives
* the resources through their lifecycle. Runs in mock mode (floci.services.ec2.mock=true in test
* application.yml) so no real Docker is required.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class Ec2NetworkInterfaceIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static String subnetId;
private static String securityGroupId;
private static String eniId;
private static String instanceId;
private static String attachmentId;
@Test
@Order(1)
void discoverDefaultSubnetAndSecurityGroup() {
subnetId = given()
.formParam("Action", "DescribeSubnets")
.formParam("Filter.1.Name", "default-for-az")
.formParam("Filter.1.Value.1", "true")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("DescribeSubnetsResponse.subnetSet.item[0].subnetId");
securityGroupId = given()
.formParam("Action", "DescribeSecurityGroups")
.formParam("Filter.1.Name", "group-name")
.formParam("Filter.1.Value.1", "default")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("DescribeSecurityGroupsResponse.securityGroupInfo.item[0].groupId");
org.junit.jupiter.api.Assertions.assertTrue(subnetId.startsWith("subnet-"));
org.junit.jupiter.api.Assertions.assertTrue(securityGroupId.startsWith("sg-"));
}
// ─── Create ────────────────────────────────────────────────────────────────
@Test
@Order(2)
void createNetworkInterface() {
eniId = given()
.formParam("Action", "CreateNetworkInterface")
.formParam("SubnetId", subnetId)
.formParam("Description", "attach-eni example ENI")
.formParam("SecurityGroupId.1", securityGroupId)
.formParam("TagSpecification.1.ResourceType", "network-interface")
.formParam("TagSpecification.1.Tag.1.Key", "Name")
.formParam("TagSpecification.1.Tag.1.Value", "example")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateNetworkInterfaceResponse.networkInterface.subnetId", equalTo(subnetId))
.body("CreateNetworkInterfaceResponse.networkInterface.status", equalTo("available"))
.body("CreateNetworkInterfaceResponse.networkInterface.description", equalTo("attach-eni example ENI"))
.body("CreateNetworkInterfaceResponse.networkInterface.privateIpAddress", not(emptyOrNullString()))
.body("CreateNetworkInterfaceResponse.networkInterface.macAddress", not(emptyOrNullString()))
.body("CreateNetworkInterfaceResponse.networkInterface.groupSet.item.groupId", equalTo(securityGroupId))
.body("CreateNetworkInterfaceResponse.networkInterface.tagSet.item.value", equalTo("example"))
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
org.junit.jupiter.api.Assertions.assertTrue(eniId.startsWith("eni-"));
}
@Test
@Order(3)
void describeReturnsTheCreatedInterfaceAsAvailable() {
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("NetworkInterfaceId.1", eniId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.networkInterfaceId", equalTo(eniId))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.status", equalTo("available"));
}
@Test
@Order(4)
void describeFiltersByNetworkInterfaceId() {
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("Filter.1.Name", "network-interface-id")
.formParam("Filter.1.Value.1", eniId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.networkInterfaceId", equalTo(eniId));
}
// ─── Attach / Detach (the attach-eni pattern) ────────────────────────────────
@Test
@Order(5)
void launchAnInstanceToAttachTo() {
instanceId = given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t2.micro")
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.formParam("SubnetId", subnetId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
org.junit.jupiter.api.Assertions.assertTrue(instanceId.startsWith("i-"));
// Mock mode settles a pending instance to "running" on the next describe (see
// Ec2Service#describeInstances), AttachNetworkInterface requires running/stopped.
given()
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", instanceId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name",
equalTo("running"));
}
@Test
@Order(6)
void attachNetworkInterfaceToInstance() {
attachmentId = given()
.formParam("Action", "AttachNetworkInterface")
.formParam("NetworkInterfaceId", eniId)
.formParam("InstanceId", instanceId)
.formParam("DeviceIndex", "1")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("AttachNetworkInterfaceResponse.attachmentId", not(emptyOrNullString()))
.extract().path("AttachNetworkInterfaceResponse.attachmentId");
}
@Test
@Order(7)
void describeShowsTheInterfaceAsInUseAndAttached() {
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("NetworkInterfaceId.1", eniId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.status", equalTo("in-use"))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.attachment.attachmentId", equalTo(attachmentId))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.attachment.instanceId", equalTo(instanceId))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.attachment.deviceIndex", equalTo("1"));
}
@Test
@Order(8)
void attachingAnAlreadyAttachedInterfaceFails() {
given()
.formParam("Action", "AttachNetworkInterface")
.formParam("NetworkInterfaceId", eniId)
.formParam("InstanceId", instanceId)
.formParam("DeviceIndex", "2")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidNetworkInterface.InUse"));
}
@Test
@Order(9)
void deletingAnAttachedInterfaceFails() {
given()
.formParam("Action", "DeleteNetworkInterface")
.formParam("NetworkInterfaceId", eniId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
}
@Test
@Order(10)
void detachNetworkInterface() {
given()
.formParam("Action", "DetachNetworkInterface")
.formParam("AttachmentId", attachmentId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DetachNetworkInterfaceResponse.return", equalTo("true"));
}
@Test
@Order(11)
void describeShowsTheInterfaceAvailableAgainAfterDetach() {
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("NetworkInterfaceId.1", eniId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.status", equalTo("available"))
.body(not(containsString("<attachment>")));
}
// ─── Delete ────────────────────────────────────────────────────────────────
@Test
@Order(12)
void deleteNetworkInterface() {
given()
.formParam("Action", "DeleteNetworkInterface")
.formParam("NetworkInterfaceId", eniId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DeleteNetworkInterfaceResponse.return", equalTo("true"));
}
@Test
@Order(13)
void describeAfterDeleteReturnsNotFound() {
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("NetworkInterfaceId.1", eniId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidNetworkInterfaceID.NotFound"));
}
// ─── RunInstances with a pre-existing ENI (the override-default-eni pattern) ─
@Test
@Order(14)
void runInstancesAcceptsAPreExistingNetworkInterfaceAsThePrimary() {
String overrideEniId = given()
.formParam("Action", "CreateNetworkInterface")
.formParam("SubnetId", subnetId)
.formParam("SecurityGroupId.1", securityGroupId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
String overrideInstanceId = given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t2.micro")
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.formParam("NetworkInterface.1.NetworkInterfaceId", overrideEniId)
.formParam("NetworkInterface.1.DeviceIndex", "0")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("RunInstancesResponse.instancesSet.item.networkInterfaceSet.item.networkInterfaceId",
equalTo(overrideEniId))
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
org.junit.jupiter.api.Assertions.assertTrue(overrideInstanceId.startsWith("i-"));
// The interface keeps its own standalone record, that is the side that knows its real
// attach time and its deleteOnTermination, while the instance carries a copy. Describe
// reports it exactly once regardless, from the standalone record.
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("NetworkInterfaceId.1", overrideEniId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()", equalTo(1))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.attachment.instanceId",
equalTo(overrideInstanceId));
}
@Test
@Order(15)
void runInstancesRejectsAPreExistingInterfaceWithMoreThanOneInstance() {
String eni = given()
.formParam("Action", "CreateNetworkInterface")
.formParam("SubnetId", subnetId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t2.micro")
.formParam("MinCount", "2")
.formParam("MaxCount", "2")
.formParam("NetworkInterface.1.NetworkInterfaceId", eni)
.formParam("NetworkInterface.1.DeviceIndex", "0")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"));
}
/**
* An attachment has to be visible from both ends. Recording it only on the standalone ENI let
* DescribeNetworkInterfaces report an attachment DescribeInstances denied, and left the
* device-index conflict check, which reads the instance's own list, unable to see anything
* this operation had attached.
*/
@Test
@Order(16)
void attachingAnInterfaceAlsoRecordsItOnTheInstance() {
String eni = given()
.formParam("Action", "CreateNetworkInterface")
.formParam("SubnetId", subnetId)
.formParam("SecurityGroupId.1", securityGroupId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
String host = given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t2.micro")
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.formParam("SubnetId", subnetId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
// Mock mode settles a pending instance to "running" on the next describe; attach needs it.
given()
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", host)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "AttachNetworkInterface")
.formParam("NetworkInterfaceId", eni)
.formParam("InstanceId", host)
.formParam("DeviceIndex", "1")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", host)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item."
+ "networkInterfaceSet.item.networkInterfaceId", hasItem(eni));
// ... and the device index it now occupies is refused to a second interface.
String second = given()
.formParam("Action", "CreateNetworkInterface")
.formParam("SubnetId", subnetId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
given()
.formParam("Action", "AttachNetworkInterface")
.formParam("NetworkInterfaceId", second)
.formParam("InstanceId", host)
.formParam("DeviceIndex", "1")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
}
/**
* An interface the caller created is not the instance's to destroy. AWS attaches it with
* deleteOnTermination false, so terminating the instance returns it to "available" rather
* than making it disappear, which is what a client that reuses one ENI across successive
* instances depends on.
*/
@Test
@Order(17)
void terminatingTheInstanceReturnsAPreExistingInterfaceToAvailable() {
String eni = given()
.formParam("Action", "CreateNetworkInterface")
.formParam("SubnetId", subnetId)
.formParam("SecurityGroupId.1", securityGroupId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
String host = given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t2.micro")
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.formParam("NetworkInterface.1.NetworkInterfaceId", eni)
.formParam("NetworkInterface.1.DeviceIndex", "0")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
given()
.formParam("Action", "TerminateInstances")
.formParam("InstanceId.1", host)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
// The terminated instance lets go of it too. Leaving it on that record would have two
// instances claiming the interface once it is reused below.
given()
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", host)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString(eni)));
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("NetworkInterfaceId.1", eni)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.status",
equalTo("available"));
// Free again, so it can be attached to a new instance, and this is the assertion that
// proves the attachment is really gone, not just the status text: RunInstances resolves
// the interface through takeNetworkInterfaceForLaunch, which refuses one that still
// carries an attachment with InvalidNetworkInterface.InUse.
String replacement = given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t2.micro")
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.formParam("NetworkInterface.1.NetworkInterfaceId", eni)
.formParam("NetworkInterface.1.DeviceIndex", "0")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
org.junit.jupiter.api.Assertions.assertTrue(replacement.startsWith("i-"));
}
}
@@ -57,7 +57,7 @@ class Ec2RunInstancesPublicIpParamTest {
when(service.runInstances(anyString(), nullable(String.class), nullable(String.class),
anyInt(), anyInt(), nullable(String.class), anyList(), nullable(String.class),
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
nullable(Boolean.class))).thenReturn(new Reservation());
nullable(Boolean.class), nullable(String.class), anyInt())).thenReturn(new Reservation());
Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class),
mock(FlowLogService.class), mock(Ec2EbsEncryptionService.class),
@@ -68,7 +68,7 @@ class Ec2RunInstancesPublicIpParamTest {
verify(service).runInstances(anyString(), nullable(String.class), nullable(String.class),
anyInt(), anyInt(), nullable(String.class), anyList(), nullable(String.class),
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
associatePublicIp.capture());
associatePublicIp.capture(), nullable(String.class), anyInt());
if (expected == null) {
assertNull(associatePublicIp.getValue(),
"an absent override must stay null so the subnet default decides");
@@ -117,6 +117,51 @@ class Ec2ServiceTest {
verify(containerManager).cancelLaunch(instance);
}
/**
* A container-backed launch that fails or is cancelled terminates the instance inside the
* container manager, never passing through TerminateInstances, so an ENI the launch had
* already marked in-use would stay pinned to an instance that no longer runs, and could
* never be reused. The attachment is reconciled when the interface is next read instead.
*/
@Test
void anInterfaceIsReleasedWhenItsInstanceDiedWithoutTerminateInstances() {
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());
Reservation reservation = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), null, null, List.of(), null, null, null,
eni.getNetworkInterfaceId(), 0);
Instance instance = reservation.getInstances().getFirst();
assertEquals("in-use", service.describeNetworkInterfaces("us-east-1",
List.of(eni.getNetworkInterfaceId()), Map.of(), 0, null)
.networkInterfaces().getFirst().getStatus());
// What a failed launch leaves behind: terminated, with no TerminateInstances call.
instance.setState(InstanceState.terminated());
NetworkInterface afterFailure = service.describeNetworkInterfaces("us-east-1",
List.of(eni.getNetworkInterfaceId()), Map.of(), 0, null)
.networkInterfaces().getFirst();
assertEquals("available", afterFailure.getStatus());
assertNull(afterFailure.getAttachment());
// The dead instance lets go of its copy too. Leaving it there would have the terminated
// instance still reporting an interface that a later launch is free to take, so two
// instance records would claim it.
assertTrue(instance.getNetworkInterfaces().stream()
.noneMatch(e -> eni.getNetworkInterfaceId().equals(e.getNetworkInterfaceId())));
// And it really is free: a second launch can take it, which the in-use check would refuse.
Reservation retry = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), null, null, List.of(), null, null, null,
eni.getNetworkInterfaceId(), 0);
assertEquals(1, retry.getInstances().size());
}
@Test
void runInstancesRequiresImageIdInsteadOfDefaulting() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),