diff --git a/docs/services/ec2.md b/docs/services/ec2.md index ee67cfeffc..e28ec3dfb0 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -1256,10 +1256,12 @@ profile. | Action | Description | |--------|-------------| -| CreateNetworkInterface | Creates a standalone elastic network interface (ENI) in a subnet, unattached. | +| CreateNetworkInterface | Creates a standalone elastic network interface (ENI) in a subnet, unattached. `Ipv6Addresses` names IPv6 addresses inside one of the subnet's IPv6 blocks; `Ipv6AddressCount` draws that many from the subnet. Left out, the subnet's `AssignIpv6AddressOnCreation` gives the interface one address; an explicit `0` overrides it. | | 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`. | +| AssignIpv6Addresses | Gives a standalone ENI or an instance's launch-created interface the named IPv6 addresses (`Ipv6Addresses.N`) or a count drawn from its subnet (`Ipv6AddressCount`); one of the two is required. `assignedIpv6Addresses` lists only the addresses the call added. An address outside the subnet's IPv6 blocks answers `InvalidParameterValue`, one another interface holds `InvalidIPAddress.InUse`. Prefix delegation (`Ipv6Prefix`, `Ipv6PrefixCount`) answers `UnsupportedOperation`. | +| UnassignIpv6Addresses | Removes the named IPv6 addresses (`Ipv6Addresses.N`) from an interface; `unassignedIpv6Addresses` lists only the ones it held. `Ipv6Prefix` answers `UnsupportedOperation`. | | ModifyNetworkInterfaceAttribute | Changes a standalone ENI or an instance's launch-created interface: its security groups (`SecurityGroupId.N`), `Description`, `SourceDestCheck`, or its attachment's `DeleteOnTermination`. On an instance's primary interface the groups and the check are the instance's too. With security-group enforcement on, a group change reaches the interface's firewall before it is stored. The members Floci does not apply (`EnablePrimaryIpv6`, `EnaSrdSpecification`, `ConnectionTrackingSpecification`, `AssociatePublicIpAddress`, `AssociatedSubnetIds`, and the attachment's `DefaultEnaQueueCount` and `EnaQueueCount`) answer `UnsupportedOperation` rather than `true` with nothing changed. | | DeleteNetworkInterface | Deletes a standalone ENI. Fails while the ENI is still attached, matching AWS. | diff --git a/docs/services/index.md b/docs/services/index.md index cf0abff14b..a134eb26ca 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -90,7 +90,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 | | [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 59 | | [EFS](efs.md) | `/2015-02-01/...` | REST JSON | 26 | -| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 229 | +| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 231 | | [EC2 Instance Connect](ec2-instance-connect.md) | `POST /` + `X-Amz-Target: AWSEC2InstanceConnectService.*` | JSON 1.1 | 2 | | [Lightsail](lightsail.md) | `POST /` + `X-Amz-Target: Lightsail_20161128.*` | JSON 1.1 | 79 local responses; 161 recognized actions | | [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 16 | diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java index 707a7fc780..54098601ef 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java @@ -43,10 +43,7 @@ public class Ec2QueryHandler { .withZone(ZoneOffset.UTC); /** ReplaceRoute targets AWS accepts that a stored {@code Route} cannot represent here. */ - /** - * ModifyNetworkInterfaceAttribute members Floci does not apply, as their query names prefix them. Each is refused, - * as ReplaceRoute refuses a target it cannot store, rather than answering true with nothing changed. - */ + /** ModifyNetworkInterfaceAttribute members Floci does not apply, as their query names prefix them. */ private static final List UNAPPLIED_INTERFACE_ATTRIBUTES = List.of("EnablePrimaryIpv6", "EnaSrdSpecification", "ConnectionTrackingSpecification", "AssociatePublicIpAddress", "AssociatedSubnetId", "Attachment.DefaultEnaQueueCount", "Attachment.EnaQueueCount"); @@ -358,6 +355,8 @@ public class Ec2QueryHandler { case "AttachNetworkInterface" -> handleAttachNetworkInterface(params, region); case "DetachNetworkInterface" -> handleDetachNetworkInterface(params, region); case "ModifyNetworkInterfaceAttribute" -> handleModifyNetworkInterfaceAttribute(params, region); + case "AssignIpv6Addresses" -> handleAssignIpv6Addresses(params, region); + case "UnassignIpv6Addresses" -> handleUnassignIpv6Addresses(params, region); // Volumes case "CreateVolume" -> handleCreateVolume(params, region); case "DescribeVolumes" -> handleDescribeVolumes(params, region); @@ -5494,9 +5493,22 @@ public class Ec2QueryHandler { } xml.end("privateIpAddressesSet"); } + xml.raw(ipv6AddressesSetXml(ni.getIpv6Addresses())); return xml.build(); } + /** An interface's {@code ipv6AddressesSet}, left out when it holds no IPv6 address. */ + private static String ipv6AddressesSetXml(List addresses) { + if (addresses == null || addresses.isEmpty()) { + return ""; + } + XmlBuilder xml = new XmlBuilder().start("ipv6AddressesSet"); + for (String address : addresses) { + xml.start("item").elem("ipv6Address", address).elem("isPrimaryIpv6", "false").end("item"); + } + return xml.end("ipv6AddressesSet").build(); + } + private static String networkInterfaceAssociationXml(NetworkInterfaceAssociation association) { return new XmlBuilder().start("association") .elem("publicIp", association.getPublicIp()) @@ -5542,9 +5554,14 @@ public class Ec2QueryHandler { securityGroupIds = getList(p, "Groups.SecurityGroupId"); } List tagList = parseTagsForResource(p, "network-interface"); + List ipv6Addresses = new ArrayList<>(); + for (int i = 1; p.getFirst("Ipv6Addresses." + i + ".Ipv6Address") != null; i++) { + ipv6Addresses.add(p.getFirst("Ipv6Addresses." + i + ".Ipv6Address")); + } + Integer ipv6AddressCount = parseOptionalInt(p.getFirst("Ipv6AddressCount"), "Ipv6AddressCount"); NetworkInterface ni = service.createNetworkInterface(region, subnetId, description, - privateIpAddress, privateIpAddresses, securityGroupIds, tagList); + privateIpAddress, privateIpAddresses, ipv6Addresses, ipv6AddressCount, securityGroupIds, tagList); XmlBuilder xml = new XmlBuilder() .start("CreateNetworkInterfaceResponse", AwsNamespaces.EC2) @@ -5580,18 +5597,65 @@ public class Ec2QueryHandler { return booleanResponse("DetachNetworkInterface"); } - private Response handleModifyNetworkInterfaceAttribute(MultivaluedMap p, String region) { + private Response handleAssignIpv6Addresses(MultivaluedMap p, String region) { + String networkInterfaceId = requireNetworkInterfaceId(p); + refuseUnappliedMembers(p, "AssignIpv6Addresses", List.of("Ipv6Prefix", "Ipv6PrefixCount")); + // botocore's Ipv6Addresses member carries the locationName ipv6Addresses, which the EC2 protocol + // capitalizes into the query name the SDKs and the CLI send: Ipv6Addresses.N. + List assigned = service.assignIpv6Addresses(region, networkInterfaceId, + getList(p, "Ipv6Addresses"), parseOptionalInt(p.getFirst("Ipv6AddressCount"), "Ipv6AddressCount")); + return ipv6AddressesResponse("AssignIpv6Addresses", "assignedIpv6Addresses", networkInterfaceId, assigned); + } + + private Response handleUnassignIpv6Addresses(MultivaluedMap p, String region) { + String networkInterfaceId = requireNetworkInterfaceId(p); + refuseUnappliedMembers(p, "UnassignIpv6Addresses", List.of("Ipv6Prefix")); + List unassigned = service.unassignIpv6Addresses(region, networkInterfaceId, + getList(p, "Ipv6Addresses")); + return ipv6AddressesResponse("UnassignIpv6Addresses", "unassignedIpv6Addresses", networkInterfaceId, + unassigned); + } + + private static String requireNetworkInterfaceId(MultivaluedMap p) { String networkInterfaceId = p.getFirst("NetworkInterfaceId"); if (networkInterfaceId == null || networkInterfaceId.isBlank()) { throw new AwsException("MissingParameter", "The request must contain the parameter NetworkInterfaceId", 400); } - for (String member : UNAPPLIED_INTERFACE_ATTRIBUTES) { + return networkInterfaceId; + } + + /** + * Refuses a call naming a member Floci does not apply (prefix delegation among them), as ReplaceRoute refuses a + * target it cannot store, rather than answering as though it had been applied. {@code members} are query-name + * prefixes. + */ + private static void refuseUnappliedMembers(MultivaluedMap p, String action, List members) { + for (String member : members) { if (p.keySet().stream().anyMatch(name -> name.equals(member) || name.startsWith(member + "."))) { - throw new AwsException("UnsupportedOperation", - "ModifyNetworkInterfaceAttribute with " + member + " is not supported.", 400); + throw new AwsException("UnsupportedOperation", action + " with " + member + " is not supported.", + 400); } } + } + + private Response ipv6AddressesResponse(String action, String listName, String networkInterfaceId, + List addresses) { + XmlBuilder xml = new XmlBuilder() + .start(action + "Response", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .elem("networkInterfaceId", networkInterfaceId) + .start(listName); + for (String address : addresses) { + xml.elem("item", address); + } + xml.end(listName).end(action + "Response"); + return xmlResponse(xml.build()); + } + + private Response handleModifyNetworkInterfaceAttribute(MultivaluedMap p, String region) { + String networkInterfaceId = requireNetworkInterfaceId(p); + refuseUnappliedMembers(p, "ModifyNetworkInterfaceAttribute", UNAPPLIED_INTERFACE_ATTRIBUTES); // The SDKs and the CLI send the group list as SecurityGroupId.N: botocore's Groups member carries that // locationName, and the EC2 protocol serializes a list by it. Ec2Service.NetworkInterfaceAttributeChange change = new Ec2Service.NetworkInterfaceAttributeChange( @@ -5710,6 +5774,7 @@ public class Ec2QueryHandler { .raw(associationXml) .end("item") .end("privateIpAddressesSet") + .raw(ipv6AddressesSetXml(eni.getIpv6Addresses())) .end("item"); } xml.end("networkInterfaceSet"); diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 59682495e0..54f2382b51 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -119,7 +119,9 @@ import org.jboss.logging.Logger; import java.io.IOException; import java.io.InputStream; +import java.math.BigInteger; import java.net.InetAddress; +import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -151,6 +153,7 @@ import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiPredicate; @@ -4332,6 +4335,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab eni.setPrivateIpAddress(privateIp); eni.setPrivateDnsName(inst.getPrivateDnsName()); eni.setGroups(new ArrayList<>(sgIdentifiers)); + if (suppliedEni != null) { + eni.setIpv6Addresses(new ArrayList<>(suppliedEni.getIpv6Addresses())); + } eni.setAttachmentId("eni-attach-" + randomHex(17)); eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0); if (inst.getLaunchTime() != null) { @@ -16123,6 +16129,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab public NetworkInterface createNetworkInterface(String region, String subnetId, String description, String privateIpAddress, List privateIpAddresses, List securityGroupIds, List tagList) { + return createNetworkInterface(region, subnetId, description, privateIpAddress, privateIpAddresses, + List.of(), null, securityGroupIds, tagList); + } + + /** + * @param ipv6AddressCount null when the request leaves it out, which lets the subnet's + * {@code AssignIpv6AddressOnCreation} give the interface one address; an explicit 0 overrides that. + */ + public NetworkInterface createNetworkInterface(String region, String subnetId, String description, + String privateIpAddress, List privateIpAddresses, + List ipv6Addresses, Integer ipv6AddressCount, + List securityGroupIds, List tagList) { if (subnetId == null || subnetId.isBlank()) { throw new AwsException("MissingParameter", "The request must contain the parameter SubnetId", 400); @@ -16170,10 +16188,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab requireRequestedPrivateIpFree(region, subnetId, ip); } } + List ipv6 = ipv6AddressesForNewInterface(region, subnet, ipv6Addresses, ipv6AddressCount); String primaryIp = requestedIp != null ? requestedIp : assignPrivateIp(region, subnetId); String primaryDns = AwsRegions.ec2PrivateIpDnsName(primaryIp, region); NetworkInterface ni = new NetworkInterface(); + ni.setIpv6Addresses(new ArrayList<>(ipv6)); ni.setNetworkInterfaceId(eniId); ni.setSubnetId(subnetId); ni.setVpcId(subnet.getVpcId()); @@ -16231,6 +16251,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab ni.setPrivateDnsName(eni.getPrivateDnsName()); ni.setSourceDestCheck(eni.isSourceDestCheck()); ni.setGroups(new ArrayList<>(eni.getGroups())); + ni.setIpv6Addresses(new ArrayList<>(eni.getIpv6Addresses())); if (inst.getPlacement() != null) { ni.setAvailabilityZone(inst.getPlacement().getAvailabilityZone()); } @@ -16458,6 +16479,318 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return interfaceHost(region, networkInterfaceId).map(Instance::getInstanceId).orElse(null); } + /** + * AssignIpv6Addresses: the named addresses, or a count drawn from the subnet's IPv6 block. Returns only the + * addresses the call added, which is what {@code assignedIpv6Addresses} reports. + */ + public List assignIpv6Addresses(String region, String networkInterfaceId, List requested, + Integer count) { + boolean named = requested != null && !requested.isEmpty(); + if (!named && count == null) { + throw new AwsException("MissingParameter", + "The request must contain the parameter Ipv6Addresses or Ipv6AddressCount", 400); + } + requireIpv6Source(named, count); + ensureDefaultResources(region); + synchronized (attachmentTopologyLock(region)) { + synchronized (privateIpAllocationLock) { + Ipv6Holder holder = ipv6Holder(region, networkInterfaceId); + Subnet subnet = requireSubnet(region, holder.subnetId()); + List held = holder.addresses(); + long adding = named ? requested.stream().map(address -> canonicalIpv6(address).orElse(address)) + .filter(address -> !held.contains(address)).distinct().count() : count; + requireWithinIpv6Limit(held.size() + adding, maxIpv6AddressesPerInterface(holder.instanceType()), + "network interface " + networkInterfaceId); + List added = named + ? claimRequestedIpv6(region, subnet, requested, held).stream() + .filter(address -> !held.contains(address)).toList() + : allocateIpv6(region, subnet, count); + if (!added.isEmpty()) { + List updated = new ArrayList<>(held); + updated.addAll(added); + holder.store(updated); + } + return added; + } + } + } + + /** UnassignIpv6Addresses: returns only the named addresses the interface held, which it no longer does. */ + public List unassignIpv6Addresses(String region, String networkInterfaceId, List addresses) { + if (addresses == null || addresses.isEmpty()) { + throw new AwsException("MissingParameter", "The request must contain the parameter Ipv6Addresses", 400); + } + ensureDefaultResources(region); + synchronized (attachmentTopologyLock(region)) { + synchronized (privateIpAllocationLock) { + Ipv6Holder holder = ipv6Holder(region, networkInterfaceId); + List held = holder.addresses(); + List removed = addresses.stream().map(address -> canonicalIpv6(address).orElse(address)) + .filter(held::contains).distinct().toList(); + if (!removed.isEmpty()) { + List updated = new ArrayList<>(held); + updated.removeAll(removed); + holder.store(updated); + } + return removed; + } + } + } + + /** + * The IPv6 addresses a new interface takes: the ones named, or a count drawn from the subnet. A count left out + * lets the subnet's {@code AssignIpv6AddressOnCreation} give it one; an explicit 0 overrides that, as the + * CreateNetworkInterface reference says. Called under {@link #privateIpAllocationLock}. + */ + private List ipv6AddressesForNewInterface(String region, Subnet subnet, List requested, + Integer count) { + boolean named = requested != null && !requested.isEmpty(); + requireIpv6Source(named, count); + int wanted = named ? requested.size() : count != null ? count : subnet.isAssignIpv6AddressOnCreation() ? 1 : 0; + requireWithinIpv6Limit(wanted, maxIpv6AddressesPerInterface(null), "the new network interface"); + if (named) { + return claimRequestedIpv6(region, subnet, requested, List.of()); + } + return allocateIpv6(region, subnet, wanted); + } + + private static void requireIpv6Source(boolean named, Integer count) { + if (count != null && count < 0) { + throw new AwsException("InvalidParameterValue", "Ipv6AddressCount must not be negative", 400); + } + if (named && count != null) { + throw new AwsException("InvalidParameterCombination", + "Specify either Ipv6Addresses or Ipv6AddressCount, not both", 400); + } + } + + /** + * The named addresses in canonical form, each inside an IPv6 block associated with the subnet and held by no + * other interface; {@code heldBySelf} are the interface's own, which it may name again. + */ + private List claimRequestedIpv6(String region, Subnet subnet, List requested, + Collection heldBySelf) { + Set used = usedIpv6Addresses(region); + LinkedHashSet claimed = new LinkedHashSet<>(); + for (String address : requested) { + String canonical = canonicalIpv6(address).orElseThrow(() -> new AwsException("InvalidParameterValue", + "Invalid IPv6 address: " + address, 400)); + String block = associatedIpv6Blocks(subnet).stream() + .filter(candidate -> CidrCanonicalizer.contains(candidate, canonical)).findFirst() + .orElseThrow(() -> new AwsException("InvalidParameterValue", "Address " + canonical + + " does not fall within the subnet's address range", 400)); + if (ipv6Reserved(block, canonical)) { + throw new AwsException("InvalidParameterValue", "Address " + canonical + + " is reserved by AWS in subnet " + subnet.getSubnetId() + " and cannot be assigned", 400); + } + if (used.contains(canonical) && !heldBySelf.contains(canonical)) { + throw new AwsException("InvalidIPAddress.InUse", "Address " + canonical + " is in use.", 400); + } + claimed.add(canonical); + } + return new ArrayList<>(claimed); + } + + /** + * {@code count} addresses no interface holds, from the subnet's first associated IPv6 block, with a random host + * part as AWS assigns one. The first four addresses and the last are skipped, being AWS's reserved ones. + */ + private List allocateIpv6(String region, Subnet subnet, int count) { + if (count == 0) { + return List.of(); + } + String block = associatedIpv6Blocks(subnet).stream().findFirst().orElseThrow(() -> new AwsException( + "InvalidParameterValue", "Subnet " + subnet.getSubnetId() + " has no IPv6 CIDR block associated", 400)); + String[] parts = block.split("/", 2); + int hostBits = 128 - Integer.parseInt(parts[1]); + BigInteger network = new BigInteger(1, ipv6Bytes(parts[0])); + BigInteger last = BigInteger.ONE.shiftLeft(hostBits).subtract(BigInteger.ONE); + Set used = usedIpv6Addresses(region); + long usedInBlock = used.stream().filter(address -> CidrCanonicalizer.contains(block, address)).count(); + // Every host but the four first and the last, less those held. + BigInteger free = last.subtract(BigInteger.valueOf(4)).subtract(BigInteger.valueOf(usedInBlock)); + if (free.compareTo(BigInteger.valueOf(count)) < 0) { + throw new AwsException("InsufficientFreeAddressesInSubnet", "There are not enough free IPv6 addresses in" + + " subnet '" + subnet.getSubnetId() + "' to satisfy the requested number of addresses.", 400); + } + List allocated = new ArrayList<>(count); + if (hostBits <= SEQUENTIAL_IPV6_HOST_BITS) { + // A small block is walked in order, so a nearly full one still ends. + for (BigInteger host = BigInteger.valueOf(4); allocated.size() < count && host.compareTo(last) < 0; + host = host.add(BigInteger.ONE)) { + String candidate = ipv6Text(network.add(host)); + if (used.add(candidate)) { + allocated.add(candidate); + } + } + return allocated; + } + while (allocated.size() < count) { + BigInteger host = new BigInteger(hostBits, ThreadLocalRandom.current()); + if (ipv6ReservedHost(host, last)) { + continue; + } + String candidate = ipv6Text(network.add(host)); + if (used.add(candidate)) { + allocated.add(candidate); + } + } + return allocated; + } + + /** Below this many host bits a block is small enough to walk, where random draws could miss its last free hosts. */ + private static final int SEQUENTIAL_IPV6_HOST_BITS = 16; + + /** Whether {@code address}, inside {@code block}, is one AWS reserves: the four first and the last. */ + private static boolean ipv6Reserved(String block, String address) { + String[] parts = block.split("/", 2); + int hostBits = 128 - Integer.parseInt(parts[1]); + BigInteger host = new BigInteger(1, ipv6Bytes(address)).subtract(new BigInteger(1, ipv6Bytes(parts[0]))); + return ipv6ReservedHost(host, BigInteger.ONE.shiftLeft(hostBits).subtract(BigInteger.ONE)); + } + + private static boolean ipv6ReservedHost(BigInteger host, BigInteger last) { + return host.compareTo(BigInteger.valueOf(4)) < 0 || host.equals(last); + } + + /** + * The IPv6 addresses an interface may hold: as many as the private IPv4 addresses its instance type allows, as + * the AssignIpv6Addresses reference says, or for an interface no instance holds, the most any type allows. + */ + private int maxIpv6AddressesPerInterface(String instanceType) { + return Optional.ofNullable(instanceType).flatMap(instanceTypeCatalog::find) + .map(type -> type.ipv4AddressesPerInterface) + .orElseGet(() -> instanceTypeCatalog.instanceTypes().stream() + .map(type -> type.ipv4AddressesPerInterface).filter(Objects::nonNull) + .max(Integer::compare).orElse(50)); + } + + private static void requireWithinIpv6Limit(long total, int limit, String owner) { + if (total > limit) { + throw new AwsException("InvalidParameterValue", "Cannot assign " + total + " IPv6 addresses to " + + owner + ": a network interface can hold at most " + limit, 400); + } + } + + private static List associatedIpv6Blocks(Subnet subnet) { + if (subnet.getIpv6CidrBlockAssociationSet() == null) { + return List.of(); + } + return subnet.getIpv6CidrBlockAssociationSet().stream() + .filter(association -> "associated".equalsIgnoreCase(association.getIpv6CidrBlockState())) + .map(VpcIpv6CidrBlockAssociation::getIpv6CidrBlock) + .filter(block -> block != null && block.contains("/")) + .toList(); + } + + /** Every IPv6 address an interface of the caller's in {@code region} holds; a terminated instance holds none. */ + private Set usedIpv6Addresses(String region) { + String prefix = region + "::"; + Set used = new HashSet<>(); + networkInterfaces.scan(k -> k.startsWith(prefix)).forEach(ni -> used.addAll(ni.getIpv6Addresses())); + instances.scan(k -> k.startsWith(prefix)).stream() + .filter(inst -> inst.getState() == null || !"terminated".equals(inst.getState().getName())) + .filter(inst -> inst.getNetworkInterfaces() != null) + .flatMap(inst -> inst.getNetworkInterfaces().stream()) + .forEach(eni -> used.addAll(eni.getIpv6Addresses())); + return used; + } + + /** An IPv6 literal in the RFC 5952 form AWS reports, or empty when it is not one. */ + private static Optional canonicalIpv6(String address) { + if (address == null || !address.contains(":")) { + return Optional.empty(); + } + return CidrCanonicalizer.canonicalize(address.trim() + "/128").map(cidr -> cidr.substring(0, cidr.indexOf('/'))); + } + + private static byte[] ipv6Bytes(String literal) { + try { + return InetAddress.getByName(literal).getAddress(); + } catch (UnknownHostException e) { + throw new AwsException("InvalidParameterValue", "Invalid IPv6 block: " + literal, 400); + } + } + + private static String ipv6Text(BigInteger value) { + byte[] raw = value.toByteArray(); + byte[] address = new byte[16]; + int copy = Math.min(raw.length, 16); + System.arraycopy(raw, raw.length - copy, address, 16 - copy, copy); + try { + return canonicalIpv6(InetAddress.getByAddress(address).getHostAddress()).orElseThrow(); + } catch (UnknownHostException e) { + throw new IllegalStateException(e); + } + } + + /** + * Where an interface's IPv6 addresses live: its standalone record, the copy on the instance it is attached to, + * or both, kept equal. Resolved under the topology lock. + */ + private Ipv6Holder ipv6Holder(String region, String networkInterfaceId) { + NetworkInterface stored = networkInterfaces.get(key(region, networkInterfaceId)) + .map(ni -> releaseIfHostIsGone(region, ni)).orElse(null); + Instance host = interfaceHost(region, networkInterfaceId).orElse(null); + InstanceNetworkInterface copy = host == null ? null : instanceCopy(host, networkInterfaceId); + if (stored == null && copy == null) { + throw new AwsException("InvalidNetworkInterfaceID.NotFound", + "The network interface ID '" + networkInterfaceId + "' does not exist", 400); + } + return new Ipv6Holder(region, stored, host, copy); + } + + private final class Ipv6Holder { + private final String region; + private final NetworkInterface stored; + private final Instance host; + private final InstanceNetworkInterface copy; + + private Ipv6Holder(String region, NetworkInterface stored, Instance host, InstanceNetworkInterface copy) { + this.region = region; + this.stored = stored; + this.host = host; + this.copy = copy; + } + + String subnetId() { + return stored != null ? stored.getSubnetId() : copy.getSubnetId(); + } + + String instanceType() { + return host != null ? host.getInstanceType() : null; + } + + List addresses() { + return List.copyOf(stored != null ? stored.getIpv6Addresses() : copy.getIpv6Addresses()); + } + + /** + * Writes the addresses to what is stored now, read again under the topology lock: an interface termination + * deleted is not written back, and a terminating instance's copy is left alone. + */ + void store(List addresses) { + if (stored != null) { + networkInterfaces.get(key(region, stored.getNetworkInterfaceId())).ifPresent(current -> { + current.setIpv6Addresses(new ArrayList<>(addresses)); + networkInterfaces.put(key(region, current.getNetworkInterfaceId()), current); + }); + } + if (copy != null) { + instances.get(key(region, host.getInstanceId())) + .filter(current -> current.getState() == null || !Set.of("terminated", "shutting-down") + .contains(current.getState().getName())) + .ifPresent(current -> { + InstanceNetworkInterface currentCopy = instanceCopy(current, copy.getNetworkInterfaceId()); + if (currentCopy != null) { + currentCopy.setIpv6Addresses(new ArrayList<>(addresses)); + instances.put(key(region, current.getInstanceId()), current); + } + }); + } + } + } + /** The instance an interface is attached to: the one its standalone record names, or the one launched with it. */ private Optional interfaceHost(String region, String networkInterfaceId) { String attached = instanceAttachedTo(region, networkInterfaceId); @@ -16598,6 +16931,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab attached.setPrivateIpAddress(ni.getPrivateIpAddress()); attached.setPrivateDnsName(ni.getPrivateDnsName()); attached.setGroups(new ArrayList<>(ni.getGroups())); + attached.setIpv6Addresses(new ArrayList<>(ni.getIpv6Addresses())); attached.setAttachmentId(attachment.getAttachmentId()); attached.setDeviceIndex(deviceIndex); attached.setAttachTime(attachment.getAttachTime()); @@ -16665,21 +16999,29 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab */ private void releaseStandaloneInterfacesOnTermination(String region, Instance inst) { for (InstanceNetworkInterface e : List.copyOf(inst.getNetworkInterfaces())) { - NetworkInterface ni = networkInterfaces.get(key(region, e.getNetworkInterfaceId())).orElse(null); - NetworkInterfaceAttachment att = ni != null ? ni.getAttachment() : null; - boolean deleted = ni == null || (att != null && att.isDeleteOnTermination()); + boolean deleted; + synchronized (attachmentTopologyLock(region)) { + NetworkInterface ni = networkInterfaces.get(key(region, e.getNetworkInterfaceId())).orElse(null); + NetworkInterfaceAttachment att = ni != null ? ni.getAttachment() : null; + deleted = ni == null || (att != null && att.isDeleteOnTermination()); + } releaseInterfaceAddresses(region, e.getNetworkInterfaceId(), deleted); - inst.getNetworkInterfaces().remove(e); - if (ni == null) { - continue; + // Under the topology lock, as interface changes are, so one that resolved this interface before it + // was released cannot write it back afterwards. + synchronized (attachmentTopologyLock(region)) { + inst.getNetworkInterfaces().remove(e); + NetworkInterface ni = networkInterfaces.get(key(region, e.getNetworkInterfaceId())).orElse(null); + if (ni == null) { + continue; + } + if (deleted) { + networkInterfaces.delete(key(region, ni.getNetworkInterfaceId())); + continue; + } + ni.setAttachment(null); + ni.setStatus("available"); + networkInterfaces.put(key(region, ni.getNetworkInterfaceId()), ni); } - if (deleted) { - networkInterfaces.delete(key(region, ni.getNetworkInterfaceId())); - continue; - } - ni.setAttachment(null); - ni.setStatus("available"); - networkInterfaces.put(key(region, ni.getNetworkInterfaceId()), ni); } } diff --git a/src/main/java/io/floci/aws/services/ec2/model/InstanceNetworkInterface.java b/src/main/java/io/floci/aws/services/ec2/model/InstanceNetworkInterface.java index 046ce30bf3..7365b51d4f 100644 --- a/src/main/java/io/floci/aws/services/ec2/model/InstanceNetworkInterface.java +++ b/src/main/java/io/floci/aws/services/ec2/model/InstanceNetworkInterface.java @@ -21,6 +21,7 @@ public class InstanceNetworkInterface { private String privateDnsName; private boolean sourceDestCheck = true; private List groups = new ArrayList<>(); + private List ipv6Addresses = new ArrayList<>(); private String attachmentId; private int deviceIndex; private String attachTime; @@ -72,4 +73,7 @@ public class InstanceNetworkInterface { public boolean isDeleteOnTermination() { return deleteOnTermination; } public void setDeleteOnTermination(boolean deleteOnTermination) { this.deleteOnTermination = deleteOnTermination; } + + public List getIpv6Addresses() { return ipv6Addresses; } + public void setIpv6Addresses(List ipv6Addresses) { this.ipv6Addresses = ipv6Addresses; } } diff --git a/src/main/java/io/floci/aws/services/ec2/model/NetworkInterface.java b/src/main/java/io/floci/aws/services/ec2/model/NetworkInterface.java index 6435477a60..483cf8f9ea 100644 --- a/src/main/java/io/floci/aws/services/ec2/model/NetworkInterface.java +++ b/src/main/java/io/floci/aws/services/ec2/model/NetworkInterface.java @@ -39,6 +39,7 @@ public class NetworkInterface { private NetworkInterfaceAttachment attachment; private List tagSet = new ArrayList<>(); private List privateIpAddresses = new ArrayList<>(); + private List ipv6Addresses = new ArrayList<>(); public NetworkInterface() {} @@ -94,5 +95,7 @@ public class NetworkInterface { public void setTagSet(List tagSet) { this.tagSet = tagSet; } public List getPrivateIpAddresses() { return privateIpAddresses; } + public List getIpv6Addresses() { return ipv6Addresses; } + public void setIpv6Addresses(List ipv6Addresses) { this.ipv6Addresses = ipv6Addresses; } public void setPrivateIpAddresses(List privateIpAddresses) { this.privateIpAddresses = privateIpAddresses; } } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2NetworkInterfaceIpv6IntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2NetworkInterfaceIpv6IntegrationTest.java new file mode 100644 index 0000000000..9e85fa2e36 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2NetworkInterfaceIpv6IntegrationTest.java @@ -0,0 +1,289 @@ +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.AttributeBooleanValue; +import software.amazon.awssdk.services.ec2.model.CreateNetworkInterfaceRequest; +import software.amazon.awssdk.services.ec2.model.Ec2Exception; +import software.amazon.awssdk.services.ec2.model.Filter; +import software.amazon.awssdk.services.ec2.model.InstanceIpv6Address; +import software.amazon.awssdk.services.ec2.model.InstanceNetworkInterfaceSpecification; +import software.amazon.awssdk.services.ec2.model.NetworkInterface; +import software.amazon.awssdk.services.ec2.model.NetworkInterfaceIpv6Address; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** IPv6 addresses on network interfaces, driven through the SDK so the wire names are the SDK's own. */ +@QuarkusTest +class Ec2NetworkInterfaceIpv6IntegrationTest { + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + // Catches: an Ipv6AddressCount that assigns nothing, or addresses outside the subnet's IPv6 block. + @Test + void aCountDrawsDistinctAddressesFromTheSubnetBlock() throws UnknownHostException { + Fixture fixture = fixture(); + + NetworkInterface created = fixture.client().createNetworkInterface(request -> request + .subnetId(fixture.subnet()).ipv6AddressCount(2)).networkInterface(); + cleanup.register(() -> fixture.client().deleteNetworkInterface(request -> request + .networkInterfaceId(created.networkInterfaceId()))); + + List addresses = addresses(created); + assertEquals(2, addresses.size()); + assertNotEquals(addresses.get(0), addresses.get(1)); + for (String address : addresses) { + assertTrue(inSubnet(fixture, address), address); + } + assertEquals(addresses, addresses(describe(fixture, created.networkInterfaceId()))); + } + + // Catches: an explicit Ipv6AddressCount of 0 read as "not given", so the subnet's AssignIpv6AddressOnCreation + // still hands out an address, where the API reference says 0 overrides it. + @Test + void anExplicitZeroOverridesTheSubnetsAssignOnCreation() { + Fixture fixture = fixture(); + fixture.client().modifySubnetAttribute(request -> request.subnetId(fixture.subnet()) + .assignIpv6AddressOnCreation(AttributeBooleanValue.builder().value(true).build())); + + String defaulted = create(fixture, request -> { }); + String zero = create(fixture, request -> request.ipv6AddressCount(0)); + + assertEquals(1, addresses(describe(fixture, defaulted)).size()); + assertEquals(List.of(), addresses(describe(fixture, zero))); + } + + // Catches: AssignIpv6Addresses reporting addresses the interface already held, or UnassignIpv6Addresses + // reporting ones it never held; each reports only what the call changed. + @Test + void assignAndUnassignReportOnlyWhatTheyChanged() { + Fixture fixture = fixture(); + String eni = create(fixture, request -> { }); + String named = fixture.prefix() + "abcd"; + + assertEquals(List.of(named), fixture.client().assignIpv6Addresses(request -> request + .networkInterfaceId(eni).ipv6Addresses(named)).assignedIpv6Addresses()); + assertEquals(List.of(), fixture.client().assignIpv6Addresses(request -> request + .networkInterfaceId(eni).ipv6Addresses(named)).assignedIpv6Addresses()); + List drawn = fixture.client().assignIpv6Addresses(request -> request + .networkInterfaceId(eni).ipv6AddressCount(1)).assignedIpv6Addresses(); + assertEquals(1, drawn.size()); + assertEquals(List.of(named, drawn.getFirst()), addresses(describe(fixture, eni))); + + assertEquals(List.of(named), fixture.client().unassignIpv6Addresses(request -> request + .networkInterfaceId(eni).ipv6Addresses(named, fixture.prefix() + "ffff")).unassignedIpv6Addresses()); + assertEquals(drawn, addresses(describe(fixture, eni))); + } + + @Test + void assignNeedsEitherAListOrACount() { + Fixture fixture = fixture(); + String eni = create(fixture, request -> { }); + + Ec2Exception neither = assertThrows(Ec2Exception.class, () -> fixture.client() + .assignIpv6Addresses(request -> request.networkInterfaceId(eni))); + Ec2Exception both = assertThrows(Ec2Exception.class, () -> fixture.client() + .assignIpv6Addresses(request -> request.networkInterfaceId(eni) + .ipv6Addresses(fixture.prefix() + "1234").ipv6AddressCount(1))); + + Ec2Exception listAndZero = assertThrows(Ec2Exception.class, () -> fixture.client() + .assignIpv6Addresses(request -> request.networkInterfaceId(eni) + .ipv6Addresses(fixture.prefix() + "1234").ipv6AddressCount(0))); + Ec2Exception createListAndZero = assertThrows(Ec2Exception.class, () -> fixture.client() + .createNetworkInterface(request -> request.subnetId(fixture.subnet()).ipv6AddressCount(0) + .ipv6Addresses(InstanceIpv6Address.builder().ipv6Address(fixture.prefix() + "1234").build()))); + + assertEquals("MissingParameter", neither.awsErrorDetails().errorCode()); + for (Ec2Exception error : List.of(both, listAndZero, createListAndZero)) { + assertEquals("InvalidParameterCombination", error.awsErrorDetails().errorCode()); + } + assertEquals(List.of(), addresses(describe(fixture, eni))); + } + + // Catches: a count no interface could hold sizing a list or looping under the region's locks; an interface + // holds at most as many IPv6 addresses as private IPv4 ones. + @Test + void aCountBeyondWhatAnInterfaceHoldsIsRefused() { + Fixture fixture = fixture(); + String eni = create(fixture, request -> { }); + + Ec2Exception error = assertThrows(Ec2Exception.class, () -> fixture.client() + .assignIpv6Addresses(request -> request.networkInterfaceId(eni).ipv6AddressCount(100000))); + + assertEquals("InvalidParameterValue", error.awsErrorDetails().errorCode()); + assertEquals(List.of(), addresses(describe(fixture, eni))); + } + + // Catches: a count larger than a small block's free hosts looping forever, where it should be refused. + @Test + void aBlockWithoutEnoughFreeAddressesRefusesTheCount() { + Fixture fixture = fixture(124); + // A /124 has sixteen hosts, five of them reserved. + String full = create(fixture, request -> request.ipv6AddressCount(11)); + + Ec2Exception error = assertThrows(Ec2Exception.class, () -> fixture.client() + .createNetworkInterface(request -> request.subnetId(fixture.subnet()).ipv6AddressCount(1))); + + assertEquals(11, addresses(describe(fixture, full)).size()); + assertEquals("InsufficientFreeAddressesInSubnet", error.awsErrorDetails().errorCode()); + } + + // Catches: a named address the subnet reserves (its first four and its last) being assigned, where the + // allocator never hands one out. + @Test + void aReservedAddressIsRefused() { + Fixture fixture = fixture(); + String eni = create(fixture, request -> { }); + + for (String reserved : List.of(fixture.network(), fixture.prefix() + "1", fixture.prefix() + "3")) { + Ec2Exception error = assertThrows(Ec2Exception.class, () -> fixture.client() + .assignIpv6Addresses(request -> request.networkInterfaceId(eni).ipv6Addresses(reserved))); + assertEquals("InvalidParameterValue", error.awsErrorDetails().errorCode(), reserved); + } + assertEquals(List.of(), addresses(describe(fixture, eni))); + } + + // Catches: a supplied interface handed to RunInstances keeping its IPv6 addresses on its own record while the + // instance's copy, which DescribeInstances reports, has none. + @Test + void aSuppliedInterfaceKeepsItsAddressesOnTheInstance() { + Fixture fixture = fixture(); + String eni = create(fixture, request -> request.ipv6AddressCount(1)); + String token = UUID.randomUUID().toString(); + cleanup.register(() -> fixture.client().describeInstances(request -> request.filters( + Filter.builder().name("client-token").values(token).build())).reservations().forEach(reservation -> + reservation.instances().forEach(instance -> fixture.client().terminateInstances( + request -> request.instanceIds(instance.instanceId()))))); + + String instance = fixture.client().runInstances(request -> request.imageId("ami-amazonlinux2023") + .instanceType("t2.micro").minCount(1).maxCount(1).clientToken(token) + .networkInterfaces(InstanceNetworkInterfaceSpecification.builder().networkInterfaceId(eni) + .deviceIndex(0).build())).instances().getFirst().instanceId(); + + assertEquals(addresses(describe(fixture, eni)), fixture.client().describeInstances(request -> request + .instanceIds(instance)).reservations().getFirst().instances().getFirst().networkInterfaces() + .getFirst().ipv6Addresses().stream().map(InstanceIpv6Address::ipv6Address).toList()); + } + + @Test + void anAddressOutsideTheSubnetOrHeldElsewhereIsRefused() { + Fixture fixture = fixture(); + String first = create(fixture, request -> request.ipv6Addresses(InstanceIpv6Address.builder() + .ipv6Address(fixture.prefix() + "beef").build())); + String second = create(fixture, request -> { }); + + Ec2Exception outside = assertThrows(Ec2Exception.class, () -> fixture.client() + .assignIpv6Addresses(request -> request.networkInterfaceId(second).ipv6Addresses("2001:db8::1"))); + Ec2Exception inUse = assertThrows(Ec2Exception.class, () -> fixture.client() + .assignIpv6Addresses(request -> request.networkInterfaceId(second) + .ipv6Addresses(fixture.prefix() + "beef"))); + + assertEquals("InvalidParameterValue", outside.awsErrorDetails().errorCode()); + assertEquals("InvalidIPAddress.InUse", inUse.awsErrorDetails().errorCode()); + assertEquals(List.of(fixture.prefix() + "beef"), addresses(describe(fixture, first))); + assertEquals(List.of(), addresses(describe(fixture, second))); + } + + // Catches: an instance's launch-created primary interface, which has no standalone record, answering + // InvalidNetworkInterfaceID.NotFound, or taking addresses that DescribeInstances does not report. + @Test + void theLaunchCreatedPrimaryInterfaceTakesAddresses() { + Fixture fixture = fixture(); + String token = UUID.randomUUID().toString(); + cleanup.register(() -> fixture.client().describeInstances(request -> request.filters( + Filter.builder().name("client-token").values(token).build())).reservations().forEach(reservation -> + reservation.instances().forEach(instance -> fixture.client().terminateInstances( + request -> request.instanceIds(instance.instanceId()))))); + String instance = fixture.client().runInstances(request -> request.imageId("ami-amazonlinux2023") + .instanceType("t2.micro").minCount(1).maxCount(1).subnetId(fixture.subnet()).clientToken(token)) + .instances().getFirst().instanceId(); + String primary = fixture.client().describeInstances(request -> request.instanceIds(instance)) + .reservations().getFirst().instances().getFirst().networkInterfaces().getFirst().networkInterfaceId(); + + List assigned = fixture.client().assignIpv6Addresses(request -> request.networkInterfaceId(primary) + .ipv6AddressCount(1)).assignedIpv6Addresses(); + + assertEquals(assigned, addresses(describe(fixture, primary))); + assertEquals(assigned, fixture.client().describeInstances(request -> request.instanceIds(instance)) + .reservations().getFirst().instances().getFirst().networkInterfaces().getFirst().ipv6Addresses() + .stream().map(InstanceIpv6Address::ipv6Address).toList()); + } + + @Test + void prefixDelegationIsRefused() { + Fixture fixture = fixture(); + String eni = create(fixture, request -> { }); + + Ec2Exception error = assertThrows(Ec2Exception.class, () -> fixture.client() + .assignIpv6Addresses(request -> request.networkInterfaceId(eni).ipv6PrefixCount(1))); + + assertEquals("UnsupportedOperation", error.awsErrorDetails().errorCode()); + } + + private Fixture fixture() { + return fixture(64); + } + + private Fixture fixture(int ipv6PrefixLength) { + Ec2Client client = AwsTestClients.create(Ec2Client.builder(), "555566667790", Region.US_WEST_2); + cleanup.register(client::close); + String vpc = client.createVpc(request -> request.cidrBlock("10.233.0.0/16").amazonProvidedIpv6CidrBlock(true)) + .vpc().vpcId(); + cleanup.register(() -> client.deleteVpc(request -> request.vpcId(vpc))); + String vpcBlock = client.describeVpcs(request -> request.vpcIds(vpc)).vpcs().getFirst() + .ipv6CidrBlockAssociationSet().getFirst().ipv6CidrBlock(); + // The /56's network address is also the network address of its first smaller block. + String subnetBlock = vpcBlock.substring(0, vpcBlock.indexOf('/')) + "/" + ipv6PrefixLength; + String subnet = client.createSubnet(request -> request.vpcId(vpc).cidrBlock("10.233.0.0/24") + .ipv6CidrBlock(subnetBlock)).subnet().subnetId(); + cleanup.register(() -> client.deleteSubnet(request -> request.subnetId(subnet))); + String network = subnetBlock.substring(0, subnetBlock.indexOf('/')); + return new Fixture(client, subnet, network, network.substring(0, network.indexOf("::") + 2)); + } + + private String create(Fixture fixture, Consumer extra) { + String eni = fixture.client().createNetworkInterface(request -> { + request.subnetId(fixture.subnet()); + extra.accept(request); + }).networkInterface().networkInterfaceId(); + cleanup.register(() -> fixture.client().deleteNetworkInterface(request -> request.networkInterfaceId(eni))); + return eni; + } + + private static NetworkInterface describe(Fixture fixture, String eni) { + return fixture.client().describeNetworkInterfaces(request -> request.networkInterfaceIds(eni)) + .networkInterfaces().getFirst(); + } + + /** Whether {@code address} shares the subnet's /64 network part. */ + private static boolean inSubnet(Fixture fixture, String address) throws UnknownHostException { + byte[] candidate = InetAddress.getByName(address).getAddress(); + byte[] network = InetAddress.getByName(fixture.network()).getAddress(); + return Arrays.equals(candidate, 0, 8, network, 0, 8); + } + + private static List addresses(NetworkInterface ni) { + return ni.ipv6Addresses().stream().map(NetworkInterfaceIpv6Address::ipv6Address).toList(); + } + + /** + * {@code network} is the subnet's /64 network address; {@code prefix} is it written up to and including + * {@code ::}, so a short host part can follow it. + */ + private record Fixture(Ec2Client client, String subnet, String network, String prefix) { } +}