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

+6
View File
@@ -1852,3 +1852,9 @@ Under `none` the rule still runs, but a mock instance has only the Elastic IP, i
Otherwise a mock instance's address appears whether DescribeInstances or DescribeInstanceStatus
observes the launch first. A terminated mock instance has no public address, and stopping it does not bring it
back.
### IPv6 launch metadata and interface creation
An implicit primary interface launched into a subnet with `AssignIpv6AddressOnCreation` and an associated IPv6 block receives one address through the shared collision-aware allocator. `DescribeInstances` and IMDS report the primary address and per-interface IPv6 addresses, subnet blocks and VPC blocks. These metadata changes do not enable guest IPv6 routing.
`CreateNetworkInterface` rejects `Ipv6AddressCount` combined with explicit IPv6 addresses or prefixes. `DescribeNetworkInterfaces` supports the `ipv6-addresses.ipv6-address` filter. Attached and supplied primary interfaces retain their subnet and VPC IPv6 metadata.
@@ -5,6 +5,7 @@ import io.floci.aws.core.common.AvailabilityZoneIds;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.services.ec2.model.GroupIdentifier;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.InstanceNetworkInterface;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
import io.floci.aws.services.iam.IamService;
@@ -30,6 +31,7 @@ import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@@ -38,6 +40,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* IMDS-compatible HTTP server bound to port 9169 on the Floci host.
@@ -200,6 +203,19 @@ public class Ec2MetadataServer {
router.get("/latest/meta-data/hostname").handler(ctx -> handleText(ctx, inst -> inst.getPrivateDnsName()));
router.get("/latest/meta-data/mac").handler(ctx -> handleMac(ctx));
router.get("/latest/meta-data/security-groups").handler(ctx -> handleSecurityGroups(ctx));
// IPv6: the primary interface's address, and per interface (keyed by MAC) its addresses and the IPv6
// blocks of its subnet and VPC. Each answers 404 for an interface without IPv6.
router.get("/latest/meta-data/ipv6")
.handler(ctx -> handleText(ctx, Ec2MetadataServer::primaryIpv6));
router.get("/latest/meta-data/network/interfaces/macs").handler(this::handleMacListing);
router.get("/latest/meta-data/network/interfaces/macs/").handler(this::handleMacListing);
router.get("/latest/meta-data/network/interfaces/macs/:mac/ipv6s")
.handler(ctx -> handleInterfaceIpv6(ctx, InstanceNetworkInterface::getIpv6Addresses));
router.get("/latest/meta-data/network/interfaces/macs/:mac/subnet-ipv6-cidr-blocks")
.handler(ctx -> handleInterfaceIpv6(ctx, InstanceNetworkInterface::getSubnetIpv6CidrBlocks));
router.get("/latest/meta-data/network/interfaces/macs/:mac/vpc-ipv6-cidr-blocks")
.handler(ctx -> handleInterfaceIpv6(ctx, InstanceNetworkInterface::getVpcIpv6CidrBlocks));
router.get("/latest/meta-data/placement/availability-zone").handler(ctx -> handleText(ctx,
this::availabilityZone));
router.get("/latest/meta-data/placement/availability-zone-id").handler(ctx -> handleText(ctx, inst ->
@@ -369,6 +385,61 @@ public class Ec2MetadataServer {
.end(mac != null ? mac : "02:42:ac:11:00:02");
}
private void handleMacListing(RoutingContext ctx) {
Instance inst = resolveInstance(ctx);
if (inst == null) {
return;
}
ctx.response().setStatusCode(200).putHeader("content-type", "text/plain").end(macListing(inst));
}
private void handleInterfaceIpv6(RoutingContext ctx,
Function<InstanceNetworkInterface, List<String>> values) {
Instance inst = resolveInstance(ctx);
if (inst == null) {
return;
}
Optional<String> answer = interfaceValues(inst, ctx.pathParam("mac"), values);
if (answer.isEmpty()) {
ctx.response().setStatusCode(404).end("not-available");
return;
}
ctx.response().setStatusCode(200).putHeader("content-type", "text/plain").end(answer.get());
}
/** The primary interface's first IPv6 address, the {@code meta-data/ipv6} answer; null without one. */
static String primaryIpv6(Instance inst) {
for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
if (eni.getDeviceIndex() == 0 && !eni.getIpv6Addresses().isEmpty()) {
return eni.getIpv6Addresses().get(0);
}
}
return null;
}
/** {@code network/interfaces/macs/}: one {@code <mac>/} line per interface. */
static String macListing(Instance inst) {
StringBuilder sb = new StringBuilder();
for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
if (eni.getMacAddress() != null) {
sb.append(sb.isEmpty() ? "" : "\n").append(eni.getMacAddress()).append('/');
}
}
return sb.toString();
}
/** One line per value of the interface with this MAC, or empty (404) when it has none, as IMDS answers. */
static Optional<String> interfaceValues(Instance inst, String mac,
Function<InstanceNetworkInterface, List<String>> values) {
for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
if (mac != null && mac.equalsIgnoreCase(eni.getMacAddress())) {
List<String> found = values.apply(eni);
return found.isEmpty() ? Optional.empty() : Optional.of(String.join("\n", found));
}
}
return Optional.empty();
}
private void handleSecurityGroups(RoutingContext ctx) {
Instance inst = resolveInstance(ctx);
if (inst == null) {
@@ -5604,6 +5604,14 @@ public class Ec2QueryHandler {
ipv6Addresses.add(p.getFirst("Ipv6Addresses." + i + ".Ipv6Address"));
}
Integer ipv6AddressCount = parseOptionalInt(p.getFirst("Ipv6AddressCount"), "Ipv6AddressCount");
if (ipv6AddressCount != null) {
for (String other : List.of("Ipv6Addresses.1.Ipv6Address", "Ipv6Prefix.1.Ipv6Prefix", "Ipv6PrefixCount")) {
if (p.getFirst(other) != null) {
throw new AwsException("InvalidParameterCombination",
"Ipv6AddressCount cannot be combined with " + other.split("\\.", 2)[0] + ".", 400);
}
}
}
NetworkInterface ni = service.createNetworkInterface(region, subnetId, description,
privateIpAddress, privateIpAddresses, ipv6Addresses, ipv6AddressCount, securityGroupIds, tagList,
@@ -5860,6 +5868,12 @@ public class Ec2QueryHandler {
.end("item");
}
xml.end("networkInterfaceSet");
for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
if (eni.getDeviceIndex() == 0 && !eni.getIpv6Addresses().isEmpty()) {
xml.elem("ipv6Address", eni.getIpv6Addresses().get(0));
break;
}
}
xml.elem("clientToken", inst.getClientToken());
if (inst.getStateReasonCode() != null || inst.getStateReasonMessage() != null) {
xml.start("stateReason")
@@ -4605,6 +4605,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// since the unlocked check above.
validateHostPlacement(getRequiredAvailableHost(region, hostId), az, effectiveInstanceType, tenancy);
}
List<String> launchIpv6 = allocateLaunchIpv6(region, finalSubnetId, suppliedEni, admitted);
List<String> privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni,
privateIpAddress, admitted);
for (int i = 0; i < admitted; i++) {
@@ -4672,13 +4673,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
eni.setVpcId(vpcId);
eni.setOwnerId(callerAccountId());
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : randomMac());
eni.setPrivateIpAddress(privateIp);
eni.setPrivateDnsName(inst.getPrivateDnsName());
eni.setGroups(new ArrayList<>(sgIdentifiers));
if (suppliedEni != null) {
eni.setIpv6Addresses(new ArrayList<>(suppliedEni.getIpv6Addresses()));
} else if (!launchIpv6.isEmpty()) {
eni.setIpv6Addresses(new ArrayList<>(List.of(launchIpv6.get(i))));
}
carrySubnetIpv6Blocks(region, finalSubnetId, eni);
eni.setAttachmentId("eni-attach-" + randomHex(17));
eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0);
if (inst.getLaunchTime() != null) {
@@ -15839,6 +15843,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// every interface instead and the filter would read as doing nothing.
case "interface-type" -> matchesValue(values, ni.getInterfaceType());
case "requester-managed" -> matchesValue(values, String.valueOf(ni.isRequesterManaged()));
case "ipv6-addresses.ipv6-address" -> ni.getIpv6Addresses().stream()
.anyMatch(address -> matchesValue(values, address));
case "attachment.instance-id" -> ni.getAttachment() != null
&& matchesValue(values, ni.getAttachment().getInstanceId());
case "association.ip-owner-id" -> ni.getPrivateIpAddresses().stream()
@@ -17516,6 +17522,31 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
/** Plans all implicit interfaces' IPv6 addresses before the launch claims IPv4 leases or stores resources. */
private List<String> allocateLaunchIpv6(String region, String subnetId, NetworkInterface suppliedEni, int count) {
Subnet subnet = subnetId == null ? null : subnets.get(key(region, subnetId)).orElse(null);
if (suppliedEni != null || subnet == null || !subnet.isAssignIpv6AddressOnCreation()
|| associatedIpv6Blocks(subnet).isEmpty()) {
return List.of();
}
return allocateIpv6(region, subnet, count);
}
private void carrySubnetIpv6Blocks(String region, String subnetId, InstanceNetworkInterface eni) {
Subnet subnet = subnetId == null ? null : subnets.get(key(region, subnetId)).orElse(null);
if (subnet == null) {
return;
}
eni.setSubnetIpv6CidrBlocks(new ArrayList<>(associatedIpv6Blocks(subnet)));
Vpc vpc = vpcs.get(key(region, subnet.getVpcId())).orElse(null);
if (vpc != null) {
eni.setVpcIpv6CidrBlocks(new ArrayList<>(vpc.getIpv6CidrBlockAssociationSet().stream()
.filter(assoc -> "associated".equalsIgnoreCase(assoc.getIpv6CidrBlockState()))
.map(VpcIpv6CidrBlockAssociation::getIpv6CidrBlock)
.toList()));
}
}
private static List<String> associatedIpv6Blocks(Subnet subnet) {
if (subnet.getIpv6CidrBlockAssociationSet() == null) {
return List.of();
@@ -17777,6 +17808,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
attached.setPrivateDnsName(ni.getPrivateDnsName());
attached.setGroups(new ArrayList<>(ni.getGroups()));
attached.setIpv6Addresses(new ArrayList<>(ni.getIpv6Addresses()));
carrySubnetIpv6Blocks(region, ni.getSubnetId(), attached);
attached.setAttachmentId(attachment.getAttachmentId());
attached.setDeviceIndex(deviceIndex);
attached.setAttachTime(attachment.getAttachTime());
@@ -23,6 +23,8 @@ public class InstanceNetworkInterface {
private List<GroupIdentifier> groups = new ArrayList<>();
private List<String> ipv6Addresses = new ArrayList<>();
private List<String> ipv4Prefixes = new ArrayList<>();
private List<String> subnetIpv6CidrBlocks = new ArrayList<>();
private List<String> vpcIpv6CidrBlocks = new ArrayList<>();
private String attachmentId;
private int deviceIndex;
private String attachTime;
@@ -76,11 +78,23 @@ public class InstanceNetworkInterface {
public void setDeleteOnTermination(boolean deleteOnTermination) { this.deleteOnTermination = deleteOnTermination; }
public List<String> getIpv6Addresses() { return ipv6Addresses; }
public void setIpv6Addresses(List<String> ipv6Addresses) { this.ipv6Addresses = ipv6Addresses; }
public void setIpv6Addresses(List<String> ipv6Addresses) {
this.ipv6Addresses = ipv6Addresses != null ? ipv6Addresses : new ArrayList<>();
}
public List<String> getIpv4Prefixes() { return ipv4Prefixes; }
public void setIpv4Prefixes(List<String> ipv4Prefixes) { this.ipv4Prefixes = ipv4Prefixes; }
public List<String> getSubnetIpv6CidrBlocks() { return subnetIpv6CidrBlocks; }
public void setSubnetIpv6CidrBlocks(List<String> subnetIpv6CidrBlocks) {
this.subnetIpv6CidrBlocks = subnetIpv6CidrBlocks != null ? subnetIpv6CidrBlocks : new ArrayList<>();
}
public List<String> getVpcIpv6CidrBlocks() { return vpcIpv6CidrBlocks; }
public void setVpcIpv6CidrBlocks(List<String> vpcIpv6CidrBlocks) {
this.vpcIpv6CidrBlocks = vpcIpv6CidrBlocks != null ? vpcIpv6CidrBlocks : new ArrayList<>();
}
/** A copy with lists of its own, so a change to the copy does not reach this interface. */
public InstanceNetworkInterface copy() {
InstanceNetworkInterface copy = new InstanceNetworkInterface();
@@ -97,6 +111,8 @@ public class InstanceNetworkInterface {
copy.groups = new ArrayList<>(groups);
copy.ipv6Addresses = new ArrayList<>(ipv6Addresses);
copy.ipv4Prefixes = new ArrayList<>(ipv4Prefixes);
copy.subnetIpv6CidrBlocks = new ArrayList<>(subnetIpv6CidrBlocks);
copy.vpcIpv6CidrBlocks = new ArrayList<>(vpcIpv6CidrBlocks);
copy.attachmentId = attachmentId;
copy.deviceIndex = deviceIndex;
copy.attachTime = attachTime;
@@ -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"));
}
}