feat(ec2): retain IPv6 launch metadata and allocation properties (#9418)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-25 06:50:02 -04:00
1 parent 0f5d2c8886
commit 87ff8135a9
11 files changed
+841 -2

No files matched your search

@@ -0,0 +1,38 @@
package io.floci.aws.services.ec2;
import io.floci.aws.services.ec2.model.InstanceNetworkInterface;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class Ec2InstanceNetworkInterfaceSnapshotTest {
@Test
void aSnapshotKeepsIpv4PrefixesAndIpv6MetadataWithoutSharingMutableLists() {
InstanceNetworkInterface original = new InstanceNetworkInterface();
original.setNetworkInterfaceId("eni-held");
original.setIpv4Prefixes(new ArrayList<>(List.of("10.0.1.0/28")));
original.setIpv6Addresses(new ArrayList<>(List.of("2001:db8:1::1")));
original.setSubnetIpv6CidrBlocks(new ArrayList<>(List.of("2001:db8:1::/64")));
original.setVpcIpv6CidrBlocks(new ArrayList<>(List.of("2001:db8:1::/56")));
InstanceNetworkInterface snapshot = original.copy();
assertEquals("eni-held", snapshot.getNetworkInterfaceId());
assertEquals(List.of("10.0.1.0/28"), snapshot.getIpv4Prefixes());
assertEquals(List.of("2001:db8:1::1"), snapshot.getIpv6Addresses());
assertEquals(List.of("2001:db8:1::/64"), snapshot.getSubnetIpv6CidrBlocks());
assertEquals(List.of("2001:db8:1::/56"), snapshot.getVpcIpv6CidrBlocks());
snapshot.getIpv4Prefixes().clear();
snapshot.getIpv6Addresses().clear();
snapshot.getSubnetIpv6CidrBlocks().clear();
original.getVpcIpv6CidrBlocks().clear();
assertEquals(List.of("10.0.1.0/28"), original.getIpv4Prefixes());
assertEquals(List.of("2001:db8:1::1"), original.getIpv6Addresses());
assertEquals(List.of("2001:db8:1::/64"), original.getSubnetIpv6CidrBlocks());
assertEquals(List.of("2001:db8:1::/56"), snapshot.getVpcIpv6CidrBlocks());
}
}
@@ -0,0 +1,122 @@
package io.floci.aws.services.ec2;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.InstanceIpv6Address;
import software.amazon.awssdk.services.ec2.model.NetworkInterface;
import java.math.BigInteger;
import java.net.InetAddress;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** The original launch allocator properties, exercised through the shared SDK allocation path. */
@QuarkusTest
class Ec2LaunchIpv6AddressTest {
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void addressesStayInsideTheBlockOutsideTheReservesAndAreCanonical() throws Exception {
Fixture fixture = fixture(64);
BigInteger network = new BigInteger(1, InetAddress.getByName(fixture.network()).getAddress());
BigInteger last = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE);
Set<String> seen = new HashSet<>();
for (int i = 0; i < 200; i++) {
String address = allocate(fixture).ipv6Addresses().getFirst().ipv6Address();
BigInteger value = new BigInteger(1, InetAddress.getByName(address).getAddress());
BigInteger host = value.subtract(network);
assertEquals(network, value.shiftRight(64).shiftLeft(64), address);
assertTrue(host.compareTo(BigInteger.valueOf(4)) >= 0, address);
assertTrue(host.compareTo(last) < 0, address);
assertEquals(address.toLowerCase(Locale.ROOT), address);
assertFalse(address.matches(".*:0[0-9a-f]+(:|$).*"), "leading zero in " + address);
assertTrue(seen.add(address), "handed out twice: " + address);
}
}
@Test
void anAddressAlreadyHeldIsNeverReturned() {
Fixture fixture = fixture(64);
String first = allocate(fixture).ipv6Addresses().getFirst().ipv6Address();
String uppercase = first.toUpperCase(Locale.ROOT);
Ec2Exception duplicate = assertThrows(Ec2Exception.class, () -> fixture.client()
.createNetworkInterface(request -> request.subnetId(fixture.subnet())
.ipv6Addresses(InstanceIpv6Address.builder().ipv6Address(uppercase).build())));
assertEquals("InvalidIPAddress.InUse", duplicate.awsErrorDetails().errorCode());
for (int i = 0; i < 100; i++) {
String address = allocate(fixture).ipv6Addresses().getFirst().ipv6Address();
assertFalse(first.equals(address), "held address handed out again: " + address);
}
}
@Test
void aSmallerBlockKeepsTheLastFreeHostAndRefusesReservedOrExhaustedAddresses() throws Exception {
Fixture fixture = fixture(124);
NetworkInterface held = fixture.client().createNetworkInterface(request -> request
.subnetId(fixture.subnet()).ipv6AddressCount(10)).networkInterface();
cleanup.register(() -> fixture.client().deleteNetworkInterface(request -> request
.networkInterfaceId(held.networkInterfaceId())));
Set<String> seen = new HashSet<>(held.ipv6Addresses().stream()
.map(address -> address.ipv6Address()).toList());
BigInteger network = new BigInteger(1, InetAddress.getByName(fixture.network()).getAddress());
assertEquals(10, seen.size());
for (String address : seen) {
BigInteger host = new BigInteger(1, InetAddress.getByName(address).getAddress()).subtract(network);
assertTrue(host.compareTo(BigInteger.valueOf(4)) >= 0, address);
assertTrue(host.compareTo(BigInteger.valueOf(14)) < 0, address);
}
String lastFree = allocate(fixture).ipv6Addresses().getFirst().ipv6Address();
assertEquals(network.add(BigInteger.valueOf(14)),
new BigInteger(1, InetAddress.getByName(lastFree).getAddress()));
assertTrue(seen.add(lastFree), "held address handed out twice: " + lastFree);
String reserved = fixture.network() + "f";
Ec2Exception reservedError = assertThrows(Ec2Exception.class, () -> fixture.client()
.createNetworkInterface(request -> request.subnetId(fixture.subnet())
.ipv6Addresses(InstanceIpv6Address.builder().ipv6Address(reserved).build())));
assertEquals("InvalidParameterValue", reservedError.awsErrorDetails().errorCode());
Ec2Exception exhausted = assertThrows(Ec2Exception.class, () -> allocate(fixture));
assertEquals("InsufficientFreeAddressesInSubnet", exhausted.awsErrorDetails().errorCode());
assertEquals(11, seen.size());
}
private NetworkInterface allocate(Fixture fixture) {
NetworkInterface created = fixture.client().createNetworkInterface(request -> request
.subnetId(fixture.subnet()).ipv6AddressCount(1)).networkInterface();
cleanup.register(() -> fixture.client().deleteNetworkInterface(request -> request
.networkInterfaceId(created.networkInterfaceId())));
assertEquals(1, created.ipv6Addresses().size());
return created;
}
private Fixture fixture(int prefixLength) {
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), "555566667791", Region.US_WEST_2);
cleanup.register(client::close);
String vpc = client.createVpc(request -> request.cidrBlock("10.234.0.0/16")
.amazonProvidedIpv6CidrBlock(true)).vpc().vpcId();
cleanup.register(() -> client.deleteVpc(request -> request.vpcId(vpc)));
String block = client.describeVpcs(request -> request.vpcIds(vpc)).vpcs().getFirst()
.ipv6CidrBlockAssociationSet().getFirst().ipv6CidrBlock();
String network = block.substring(0, block.indexOf('/'));
String subnet = client.createSubnet(request -> request.vpcId(vpc).cidrBlock("10.234.0.0/24")
.ipv6CidrBlock(network + "/" + prefixLength)).subnet().subnetId();
cleanup.register(() -> client.deleteSubnet(request -> request.subnetId(subnet)));
return new Fixture(client, subnet, network);
}
private record Fixture(Ec2Client client, String subnet, String network) { }
}
@@ -0,0 +1,181 @@
package io.floci.aws.services.ec2;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.InstanceNetworkInterface;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.Filter;
import software.amazon.awssdk.services.ec2.model.NetworkInterface;
import software.amazon.awssdk.services.ec2.model.ResourceType;
import software.amazon.awssdk.services.ec2.model.Tag;
import software.amazon.awssdk.services.ec2.model.TagSpecification;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
@QuarkusTest
class Ec2LaunchIpv6MetadataIntegrationTest {
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Inject
Ec2Service service;
@Test
void implicitLaunchMacIdentifiesTheSameIpv6MetadataAfterDescribe() throws Exception {
Fixture fixture = fixture("555566668101", true, 64);
List<String> ids = launch(fixture, 2);
Instance first = service.findInstanceById(fixture.account(), ids.getFirst());
Instance second = service.findInstanceById(fixture.account(), ids.get(1));
String mac = first.getNetworkInterfaces().getFirst().getMacAddress();
assertNotNull(mac);
assertNotEquals(mac, second.getNetworkInterfaces().getFirst().getMacAddress());
String describedMac = fixture.client().describeInstances(request -> request.instanceIds(ids.getFirst()))
.reservations().getFirst().instances().getFirst().networkInterfaces().getFirst().macAddress();
assertEquals(mac, describedMac);
assertEquals(mac + "/", Ec2MetadataServer.macListing(first));
assertMetadata(fixture, first, mac);
assertNotEquals(Ec2MetadataServer.primaryIpv6(first), Ec2MetadataServer.primaryIpv6(second));
}
@Test
void aLaterAssignmentHasSubnetAndVpcBlocksWithoutAutomaticAssignment() throws Exception {
Fixture fixture = fixture("555566668102", false, 64);
String id = launch(fixture, 1).getFirst();
Instance before = service.findInstanceById(fixture.account(), id);
InstanceNetworkInterface eni = before.getNetworkInterfaces().getFirst();
assertTrue(eni.getIpv6Addresses().isEmpty());
// The stored blocks are independent of a MAC, so this catches the block gap on its own.
assertEquals(List.of(fixture.subnetBlock()), eni.getSubnetIpv6CidrBlocks());
assertEquals(List.of(fixture.vpcBlock()), eni.getVpcIpv6CidrBlocks());
fixture.client().assignIpv6Addresses(request -> request.networkInterfaceId(eni.getNetworkInterfaceId())
.ipv6AddressCount(1));
Instance after = service.findInstanceById(fixture.account(), id);
assertMetadata(fixture, after, after.getNetworkInterfaces().getFirst().getMacAddress());
}
@Test
void exhaustedMultiInstanceLaunchLeavesNoResourcesOrIpv4Leases() {
Fixture fixture = fixture("555566668103", true, 124);
hold(fixture, 10);
int available = availableIpv4(fixture);
Ec2Exception failure = assertThrows(Ec2Exception.class, () -> launch(fixture, 2));
assertEquals("InsufficientFreeAddressesInSubnet", failure.awsErrorDetails().errorCode());
assertTrue(fixture.client().describeInstances().reservations().stream()
.flatMap(reservation -> reservation.instances().stream()).findAny().isEmpty());
assertTrue(fixture.client().describeVolumes().volumes().isEmpty());
assertTrue(fixture.client().describeTags(request -> request.filters(Filter.builder()
.name("key").values("ipv6-launch-review").build())).tags().isEmpty());
assertEquals(1, fixture.client().describeNetworkInterfaces().networkInterfaces().size());
assertEquals(available, availableIpv4(fixture));
String id = launch(fixture, 1).getFirst();
assertEquals(1, service.findInstanceById(fixture.account(), id).getNetworkInterfaces()
.getFirst().getIpv6Addresses().size());
}
@Test
void aBatchCanConsumeTheLastTwoDistinctIpv6Addresses() {
Fixture fixture = fixture("555566668104", true, 124);
hold(fixture, 9);
List<String> ids = launch(fixture, 2);
String first = Ec2MetadataServer.primaryIpv6(service.findInstanceById(fixture.account(), ids.getFirst()));
String second = Ec2MetadataServer.primaryIpv6(service.findInstanceById(fixture.account(), ids.get(1)));
assertNotNull(first);
assertNotNull(second);
assertNotEquals(first, second);
Ec2Exception exhausted = assertThrows(Ec2Exception.class, () -> launch(fixture, 1));
assertEquals("InsufficientFreeAddressesInSubnet", exhausted.awsErrorDetails().errorCode());
}
private void assertMetadata(Fixture fixture, Instance instance, String mac) throws Exception {
assertEquals(Ec2MetadataServer.primaryIpv6(instance), Ec2MetadataServer.interfaceValues(
instance, mac, InstanceNetworkInterface::getIpv6Addresses).orElseThrow());
assertEquals(fixture.subnetBlock(), Ec2MetadataServer.interfaceValues(
instance, mac, InstanceNetworkInterface::getSubnetIpv6CidrBlocks).orElseThrow());
assertEquals(fixture.vpcBlock(), Ec2MetadataServer.interfaceValues(
instance, mac, InstanceNetworkInterface::getVpcIpv6CidrBlocks).orElseThrow());
try (Ec2MetadataTestFixture metadata = new Ec2MetadataTestFixture()) {
metadata.start(null, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), instance);
HttpResponse<String> token = metadata.putToken("60");
assertEquals(200, token.statusCode());
String prefix = "/latest/meta-data/network/interfaces/macs/";
for (Map.Entry<String, String> expected : Map.of(
"/latest/meta-data/mac", mac,
prefix, mac + "/",
prefix + mac + "/ipv6s", Ec2MetadataServer.primaryIpv6(instance),
prefix + mac + "/subnet-ipv6-cidr-blocks", fixture.subnetBlock(),
prefix + mac + "/vpc-ipv6-cidr-blocks", fixture.vpcBlock()).entrySet()) {
HttpResponse<String> response = metadata.get(expected.getKey(), token.body());
assertEquals(200, response.statusCode(), expected.getKey());
assertEquals(expected.getValue(), response.body(), expected.getKey());
}
}
}
private List<String> launch(Fixture fixture, int count) {
return fixture.client().runInstances(request -> request.imageId("ami-ipv6-review")
.instanceType("t3.micro").minCount(count).maxCount(count).subnetId(fixture.subnet())
.tagSpecifications(TagSpecification.builder().resourceType(ResourceType.INSTANCE)
.tags(Tag.builder().key("ipv6-launch-review").value("owned").build()).build()))
.instances().stream().map(instance -> instance.instanceId()).toList();
}
private int availableIpv4(Fixture fixture) {
return fixture.client().describeSubnets(request -> request.subnetIds(fixture.subnet()))
.subnets().getFirst().availableIpAddressCount();
}
private void hold(Fixture fixture, int count) {
NetworkInterface held = fixture.client().createNetworkInterface(request -> request
.subnetId(fixture.subnet()).ipv6AddressCount(count)).networkInterface();
cleanup.register(() -> fixture.client().deleteNetworkInterface(request -> request
.networkInterfaceId(held.networkInterfaceId())));
}
private Fixture fixture(String account, boolean automatic, int prefix) {
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), account, Region.US_WEST_2);
cleanup.register(client::close);
String vpc = client.createVpc(request -> request.cidrBlock("10.235.0.0/16")
.amazonProvidedIpv6CidrBlock(true)).vpc().vpcId();
cleanup.register(() -> client.deleteVpc(request -> request.vpcId(vpc)));
String block = client.describeVpcs(request -> request.vpcIds(vpc)).vpcs().getFirst()
.ipv6CidrBlockAssociationSet().getFirst().ipv6CidrBlock();
String subnetBlock = block.substring(0, block.indexOf('/')) + "/" + prefix;
String subnet = client.createSubnet(request -> request.vpcId(vpc).cidrBlock("10.235.0.0/28")
.ipv6CidrBlock(subnetBlock)).subnet().subnetId();
cleanup.register(() -> client.deleteSubnet(request -> request.subnetId(subnet)));
// Include resources an old failed launch might have stored without returning their IDs.
cleanup.register(() -> {
List<String> ids = client.describeInstances().reservations().stream()
.flatMap(reservation -> reservation.instances().stream()).map(instance -> instance.instanceId()).toList();
if (!ids.isEmpty()) {
client.terminateInstances(request -> request.instanceIds(ids));
}
client.describeVolumes().volumes().forEach(volume -> client.deleteVolume(request ->
request.volumeId(volume.volumeId())));
});
client.modifySubnetAttribute(request -> request.subnetId(subnet)
.assignIpv6AddressOnCreation(value -> value.value(automatic)));
return new Fixture(client, account, subnet, subnetBlock, block);
}
private record Fixture(Ec2Client client, String account, String subnet, String subnetBlock, String vpcBlock) { }
}
@@ -1,11 +1,13 @@
package io.floci.aws.services.ec2;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.InstanceNetworkInterface;
import io.floci.aws.services.ec2.model.Placement;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@@ -116,6 +118,37 @@ class Ec2MetadataServerTest {
server.registeredContainer("192.168.215.7").orElseThrow());
}
@Test
void ipv6KeysAnswerTheInterfaceByMacAndNothingForAnIpv4OnlyInterface() {
InstanceNetworkInterface primary = new InstanceNetworkInterface();
primary.setMacAddress("02:aa:bb:cc:dd:ee");
primary.setIpv6Addresses(List.of("2600:1f18:abcd:ef01::1234"));
primary.setSubnetIpv6CidrBlocks(List.of("2600:1f18:abcd:ef01::/64"));
primary.setVpcIpv6CidrBlocks(List.of("2600:1f18:abcd:ef00::/56"));
InstanceNetworkInterface ipv4Only = new InstanceNetworkInterface();
ipv4Only.setMacAddress("02:11:22:33:44:55");
ipv4Only.setDeviceIndex(1);
Instance instance = new Instance();
instance.setNetworkInterfaces(new ArrayList<>(List.of(primary, ipv4Only)));
assertEquals("2600:1f18:abcd:ef01::1234", Ec2MetadataServer.primaryIpv6(instance));
assertEquals("02:aa:bb:cc:dd:ee/\n02:11:22:33:44:55/", Ec2MetadataServer.macListing(instance));
assertEquals("2600:1f18:abcd:ef01::1234", Ec2MetadataServer.interfaceValues(
instance, "02:AA:BB:CC:DD:EE", InstanceNetworkInterface::getIpv6Addresses).orElseThrow());
assertEquals("2600:1f18:abcd:ef01::/64", Ec2MetadataServer.interfaceValues(
instance, "02:aa:bb:cc:dd:ee", InstanceNetworkInterface::getSubnetIpv6CidrBlocks).orElseThrow());
assertEquals("2600:1f18:abcd:ef00::/56", Ec2MetadataServer.interfaceValues(
instance, "02:aa:bb:cc:dd:ee", InstanceNetworkInterface::getVpcIpv6CidrBlocks).orElseThrow());
assertTrue(Ec2MetadataServer.interfaceValues(
instance, "02:11:22:33:44:55", InstanceNetworkInterface::getIpv6Addresses).isEmpty());
assertTrue(Ec2MetadataServer.interfaceValues(
instance, "02:00:00:00:00:00", InstanceNetworkInterface::getIpv6Addresses).isEmpty());
Instance noIpv6 = new Instance();
noIpv6.setNetworkInterfaces(new ArrayList<>(List.of(ipv4Only)));
assertEquals(null, Ec2MetadataServer.primaryIpv6(noIpv6));
}
@Test
void unregisteredContainerMessageExplainsMissingEc2Record() {
String message = Ec2MetadataServer.unregisteredContainerMessage("172.17.0.9");
@@ -0,0 +1,220 @@
package io.floci.aws.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Per https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateNetworkInterface.html,
* {@code Ipv6AddressCount} is "the number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically
* selects the IPv6 addresses from the subnet range", it cannot be combined with specific IPv6 addresses, specific IPv6
* prefixes or a count of IPv6 prefixes, and "if your subnet has the AssignIpv6AddressOnCreation attribute set, you can
* override that setting by specifying 0 as the IPv6 address count". The interface reports its addresses in
* {@code ipv6AddressesSet}, DescribeNetworkInterfaces' {@code ipv6-addresses.ipv6-address} filter finds it by one, and
* an attached interface carries them onto the instance.
*/
@QuarkusTest
class Ec2NetworkInterfaceIpv6AddressCountIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static final String ADDRESSES = "CreateNetworkInterfaceResponse.networkInterface.ipv6AddressesSet.item";
private String[] dualStackSubnet(String ipv4Cidr, String subnetCidr, boolean assign) throws Exception {
Response vpc = given()
.formParam("Action", "CreateVpc").formParam("CidrBlock", ipv4Cidr)
.formParam("AmazonProvidedIpv6CidrBlock", "true").header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract().response();
String vpcId = vpc.path("CreateVpcResponse.vpc.vpcId");
String vpcCidr = vpc.path("CreateVpcResponse.vpc.ipv6CidrBlockAssociationSet.item.ipv6CidrBlock");
byte[] address = InetAddress.getByName(vpcCidr.split("/")[0]).getAddress();
address[7] = 1;
String prefix = String.join(":", Arrays.copyOf(
InetAddress.getByAddress(address).getHostAddress().split(":"), 4));
String ipv6Block = prefix + "::/64";
String subnetId = given()
.formParam("Action", "CreateSubnet").formParam("VpcId", vpcId).formParam("CidrBlock", subnetCidr)
.formParam("Ipv6CidrBlock", ipv6Block).header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
if (assign) {
given()
.formParam("Action", "ModifySubnetAttribute").formParam("SubnetId", subnetId)
.formParam("AssignIpv6AddressOnCreation.Value", "true").header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200);
}
return new String[] {subnetId, ipv6Block};
}
private Response create(String subnetId, String... params) {
RequestSpecification request = given().formParam("Action", "CreateNetworkInterface").formParam("SubnetId", subnetId)
.header("Authorization", AUTH_HEADER);
for (int i = 0; i + 1 < params.length; i += 2) {
request = request.formParam(params[i], params[i + 1]);
}
return request.when().post("/").then().extract().response();
}
private static List<String> addresses(Response response, String path) {
return XmlPath.from(response.asString()).getList(path + ".ipv6Address");
}
private static void assertInBlock(String block, String address) throws Exception {
BigInteger network = new BigInteger(1, InetAddress.getByName(block.split("/")[0]).getAddress());
BigInteger value = new BigInteger(1, InetAddress.getByName(address).getAddress());
assertEquals(network, value.shiftRight(64).shiftLeft(64), address + " is outside " + block);
// AWS reserves the first four addresses of a subnet's block.
assertTrue(value.subtract(network).compareTo(BigInteger.valueOf(4)) >= 0, address + " is reserved");
}
@Test
void theCountAssignsThatManyDistinctAddressesFromTheSubnetsBlock() throws Exception {
String[] subnet = dualStackSubnet("10.110.0.0/16", "10.110.1.0/24", false);
Response created = create(subnet[0], "Ipv6AddressCount", "3");
assertEquals(200, created.statusCode(), created.asString());
List<String> assigned = addresses(created, ADDRESSES);
assertEquals(3, assigned.size(), created.asString());
assertEquals(3, new HashSet<>(assigned).size(), "addresses repeat: " + assigned);
for (String address : assigned) {
assertInBlock(subnet[1], address);
}
assertEquals(List.of("false", "false", "false"),
XmlPath.from(created.asString()).getList(ADDRESSES + ".isPrimaryIpv6"));
String eniId = created.path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
Response described = given()
.formParam("Action", "DescribeNetworkInterfaces").formParam("NetworkInterfaceId.1", eniId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract().response();
assertEquals(assigned, addresses(described,
"DescribeNetworkInterfacesResponse.networkInterfaceSet.item.ipv6AddressesSet.item"));
}
@Test
void theIpv6AddressFilterFindsTheInterfaceByOneOfItsAddresses() throws Exception {
String[] subnet = dualStackSubnet("10.111.0.0/16", "10.111.1.0/24", false);
Response created = create(subnet[0], "Ipv6AddressCount", "2");
String eniId = created.path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
String second = addresses(created, ADDRESSES).get(1);
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("Filter.1.Name", "ipv6-addresses.ipv6-address").formParam("Filter.1.Value.1", second)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()", equalTo(1))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.networkInterfaceId", equalTo(eniId));
String absent = subnet[1].replace("::/64", "::ffff:1");
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("Filter.1.Name", "ipv6-addresses.ipv6-address").formParam("Filter.1.Value.1", absent)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()", equalTo(0));
}
@Test
void aSubnetThatAssignsIpv6GivesOneAddressUnlessTheCountIsZero() throws Exception {
String[] subnet = dualStackSubnet("10.112.0.0/16", "10.112.1.0/24", true);
Response defaulted = create(subnet[0]);
assertEquals(200, defaulted.statusCode(), defaulted.asString());
List<String> one = addresses(defaulted, ADDRESSES);
assertEquals(1, one.size(), defaulted.asString());
assertInBlock(subnet[1], one.get(0));
Response overridden = create(subnet[0], "Ipv6AddressCount", "0");
assertEquals(200, overridden.statusCode(), overridden.asString());
assertFalse(overridden.asString().contains("ipv6Address"), overridden.asString());
String[] noAttribute = dualStackSubnet("10.113.0.0/16", "10.113.1.0/24", false);
Response plain = create(noAttribute[0]);
assertEquals(200, plain.statusCode(), plain.asString());
assertFalse(plain.asString().contains("ipv6Address"), plain.asString());
}
@Test
void aCountOnASubnetWithoutAnIpv6BlockIsRefusedAndCreatesNothing() {
String vpcId = given()
.formParam("Action", "CreateVpc").formParam("CidrBlock", "10.114.0.0/16").header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
String ipv4Only = given()
.formParam("Action", "CreateSubnet").formParam("VpcId", vpcId).formParam("CidrBlock", "10.114.1.0/24")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
Response refused = create(ipv4Only, "Ipv6AddressCount", "1", "Description", "ipv4-only-count");
assertEquals(400, refused.statusCode(), refused.asString());
assertEquals("InvalidParameterValue", refused.path("Response.Errors.Error.Code"));
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("Filter.1.Name", "description").formParam("Filter.1.Value.1", "ipv4-only-count")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()", equalTo(0));
}
@Test
void aNegativeCountOrACountWithSpecificAddressesOrPrefixesIsRefused() throws Exception {
String[] subnet = dualStackSubnet("10.115.0.0/16", "10.115.1.0/24", false);
Response negative = create(subnet[0], "Ipv6AddressCount", "-1");
assertEquals(400, negative.statusCode(), negative.asString());
assertEquals("InvalidParameterValue", negative.path("Response.Errors.Error.Code"));
String specific = subnet[1].replace("::/64", "::10");
for (String[] combined : new String[][] {
{"Ipv6Addresses.1.Ipv6Address", specific},
{"Ipv6PrefixCount", "1"},
{"Ipv6Prefix.1.Ipv6Prefix", subnet[1].replace("::/64", "::/80")}}) {
Response refused = create(subnet[0], "Ipv6AddressCount", "1", combined[0], combined[1]);
assertEquals(400, refused.statusCode(), combined[0] + ": " + refused.asString());
assertEquals("InvalidParameterCombination", refused.path("Response.Errors.Error.Code"), combined[0]);
}
}
@Test
void anAttachedInterfaceCarriesItsAddressesOntoTheInstance() throws Exception {
String[] subnet = dualStackSubnet("10.116.0.0/16", "10.116.1.0/24", false);
Response created = create(subnet[0], "Ipv6AddressCount", "1");
String eniId = created.path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
String address = addresses(created, ADDRESSES).get(0);
String instanceId = given()
.formParam("Action", "RunInstances").formParam("ImageId", "ami-ipv6-eni")
.formParam("InstanceType", "t3.micro").formParam("MinCount", "1").formParam("MaxCount", "1")
.formParam("SubnetId", subnet[0]).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; an attach needs running or 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"));
given()
.formParam("Action", "AttachNetworkInterface").formParam("NetworkInterfaceId", eniId)
.formParam("InstanceId", instanceId).formParam("DeviceIndex", "1").header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200);
Response described = given()
.formParam("Action", "DescribeInstances").formParam("InstanceId.1", instanceId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract().response();
List<String> interfaceIds = XmlPath.from(described.asString()).getList(
"DescribeInstancesResponse.reservationSet.item.instancesSet.item.networkInterfaceSet.item"
+ ".networkInterfaceId");
List<String> carried = XmlPath.from(described.asString()).getList(
"DescribeInstancesResponse.reservationSet.item.instancesSet.item.networkInterfaceSet.item"
.concat(".find { it.networkInterfaceId == '" + eniId + "' }.ipv6AddressesSet.item.ipv6Address"));
assertTrue(interfaceIds.contains(eniId), described.asString());
assertEquals(List.of(address), carried, described.asString());
}
}
@@ -0,0 +1,106 @@
package io.floci.aws.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.net.InetAddress;
import java.util.Arrays;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Per https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifySubnetAttribute.html an instance launched
* into a subnet with AssignIpv6AddressOnCreation receives an IPv6 address from the subnet's block; DescribeInstances
* reports it on the instance (ipv6Address) and on its interface (ipv6AddressesSet). A subnet without the attribute
* or without an IPv6 block gives none.
*/
@QuarkusTest
class Ec2RunInstancesIpv6IntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private String[] dualStackSubnet(String ipv4Cidr, String subnetCidr, boolean assign) throws Exception {
Response vpc = given()
.formParam("Action", "CreateVpc").formParam("CidrBlock", ipv4Cidr)
.formParam("AmazonProvidedIpv6CidrBlock", "true").header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract().response();
String vpcId = vpc.path("CreateVpcResponse.vpc.vpcId");
String vpcCidr = vpc.path("CreateVpcResponse.vpc.ipv6CidrBlockAssociationSet.item.ipv6CidrBlock");
byte[] address = InetAddress.getByName(vpcCidr.split("/")[0]).getAddress();
address[7] = 1;
String prefix = String.join(":", Arrays.copyOf(
InetAddress.getByAddress(address).getHostAddress().split(":"), 4));
String ipv6Block = prefix + "::/64";
String subnetId = given()
.formParam("Action", "CreateSubnet").formParam("VpcId", vpcId).formParam("CidrBlock", subnetCidr)
.formParam("Ipv6CidrBlock", ipv6Block).header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
if (assign) {
given()
.formParam("Action", "ModifySubnetAttribute").formParam("SubnetId", subnetId)
.formParam("AssignIpv6AddressOnCreation.Value", "true").header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200);
}
return new String[] {subnetId, ipv6Block};
}
private Response launchAndDescribe(String subnetId) {
String instanceId = given()
.formParam("Action", "RunInstances").formParam("ImageId", "ami-ipv6-launch")
.formParam("InstanceType", "t3.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");
return given()
.formParam("Action", "DescribeInstances").formParam("InstanceId.1", instanceId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract().response();
}
@Test
void aSubnetThatAssignsIpv6GivesTheInstanceOneAddressInsideItsBlock() throws Exception {
String[] subnet = dualStackSubnet("10.96.0.0/16", "10.96.1.0/24", true);
Response described = launchAndDescribe(subnet[0]);
String instanceAddress = described.path("DescribeInstancesResponse.reservationSet.item.instancesSet.item.ipv6Address");
String interfaceAddress = described.path(
"DescribeInstancesResponse.reservationSet.item.instancesSet.item.networkInterfaceSet.item.ipv6AddressesSet.item.ipv6Address");
assertEquals(instanceAddress, interfaceAddress);
BigInteger network = new BigInteger(1, InetAddress.getByName(subnet[1].split("/")[0]).getAddress());
BigInteger value = new BigInteger(1, InetAddress.getByName(instanceAddress).getAddress());
assertEquals(network, value.shiftRight(64).shiftLeft(64));
assertTrue(value.subtract(network).compareTo(BigInteger.valueOf(4)) >= 0);
given()
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", (String) described.path(
"DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId"))
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.networkInterfaceSet.item"
+ ".ipv6AddressesSet.item.isPrimaryIpv6", equalTo("false"));
}
@Test
void aSubnetWithoutTheAttributeOrWithoutIpv6GivesNoAddress() throws Exception {
String[] noAttribute = dualStackSubnet("10.97.0.0/16", "10.97.1.0/24", false);
assertFalse(launchAndDescribe(noAttribute[0]).asString().contains("ipv6Address"));
String vpcId = given()
.formParam("Action", "CreateVpc").formParam("CidrBlock", "10.98.0.0/16").header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
String ipv4Only = given()
.formParam("Action", "CreateSubnet").formParam("VpcId", vpcId).formParam("CidrBlock", "10.98.1.0/24")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
given()
.formParam("Action", "ModifySubnetAttribute").formParam("SubnetId", ipv4Only)
.formParam("AssignIpv6AddressOnCreation.Value", "true").header("Authorization", AUTH_HEADER)
.when().post("/");
assertFalse(launchAndDescribe(ipv4Only).asString().contains("ipv6Address"));
}
}