diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 3c244adda4..23eb0b6fe1 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -784,6 +784,16 @@ one, fails with `InvalidParameterCombination`, and a count outside 1 to 31 with keeps its id, a secondary the template still names keeps its address, a dropped Elastic IP is handed back, and a new address that is already held fails the update and leaves the gateway as it was. +### EC2 Instance Connect Endpoints + +| Action | Description | +|--------|-------------| +| CreateInstanceConnectEndpoint | Creates an endpoint in a subnet, `create-complete` at once, with a private address from the subnet. | +| DescribeInstanceConnectEndpoints | Lists endpoints; filters `instance-connect-endpoint-id`, `state`, `vpc-id`, `subnet-id`, `tag:`, `tag-key`, `tag-value`. | +| DeleteInstanceConnectEndpoint | Deletes an endpoint and answers with it in `delete-in-progress`. | + +A repeated `ClientToken` returns the endpoint the first call created (`IdempotentParameterMismatch` when reused with another subnet, security group set, `IpAddressType`, `PreserveClientIp` or tag set; tags added later with `CreateTags` do not count). While an endpoint exists, `DeleteSubnet` on its subnet and `DeleteVpc` on its VPC fail with `DependencyViolation`, as on AWS. The interface ID in an endpoint's `networkInterfaceIdSet` resolves in `DescribeNetworkInterfaces` while the endpoint exists: a requester-managed `ec2_instance_connect_endpoint` interface carrying the endpoint's private address, subnet, VPC and security groups. An unknown filter name is `InvalidParameterValue` even when no endpoint exists. `DescribeInstanceConnectEndpoints` pages by `MaxResults`/`NextToken` in endpoint ID order (`MaxResults` outside 1-50 is `InvalidMaxResults`), and `publicDnsNames` carries only the `ipv4` names. The endpoint's tunnel (`openTunnel`) is not served yet. + ### Capacity Reservations | Action | Description | diff --git a/docs/services/index.md b/docs/services/index.md index 5629fa3ace..6467c5af9a 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -86,7 +86,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 | 220 | +| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 223 | | [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 | | [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane proxied to `registry:2`) | JSON 1.1 + OCI Distribution | 34 | diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index 297b2d5bfd..bc2b002c47 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -303,6 +303,9 @@ public class Ec2QueryHandler { // NAT Gateways case "CreateNatGateway" -> handleCreateNatGateway(params, region); case "DescribeNatGateways" -> handleDescribeNatGateways(params, region); + case "CreateInstanceConnectEndpoint" -> handleCreateInstanceConnectEndpoint(params, region); + case "DescribeInstanceConnectEndpoints" -> handleDescribeInstanceConnectEndpoints(params, region); + case "DeleteInstanceConnectEndpoint" -> handleDeleteInstanceConnectEndpoint(params, region); case "DeleteNatGateway" -> handleDeleteNatGateway(params, region); // Capacity Reservations case "CreateCapacityReservation" -> handleCreateCapacityReservation(params, region); @@ -4512,6 +4515,96 @@ public class Ec2QueryHandler { return xmlResponse(xml.build()); } + // ─── EC2 Instance Connect Endpoint handlers ─────────────────────────────── + + private Response handleCreateInstanceConnectEndpoint(MultivaluedMap p, String region) { + String preserve = p.getFirst("PreserveClientIp"); + // The service validates the request before answering a DryRun, as AWS does. + InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(region, p.getFirst("SubnetId"), + getList(p, "SecurityGroupId"), preserve == null ? null : Boolean.parseBoolean(preserve), + p.getFirst("IpAddressType"), parseTagsForResource(p, "instance-connect-endpoint"), + p.getFirst("ClientToken"), Boolean.parseBoolean(p.getFirst("DryRun"))); + XmlBuilder xml = new XmlBuilder() + .start("CreateInstanceConnectEndpointResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("instanceConnectEndpoint").raw(instanceConnectEndpointXml(endpoint)).end("instanceConnectEndpoint") + .elem("clientToken", p.getFirst("ClientToken")) + .end("CreateInstanceConnectEndpointResponse"); + return xmlResponse(xml.build()); + } + + private Response handleDescribeInstanceConnectEndpoints(MultivaluedMap p, String region) { + String maxResults = p.getFirst("MaxResults"); + PaginatedResult page = service.describeInstanceConnectEndpoints(region, + getList(p, "InstanceConnectEndpointId"), getFiltersList(p), + maxResults == null || maxResults.isEmpty() ? null : parseIntParam(p, "MaxResults", 0), + p.getFirst("NextToken")); + // After the describe, so an unknown ID, filter or NextToken fails on its own error first. + checkDryRun(p); + XmlBuilder xml = new XmlBuilder() + .start("DescribeInstanceConnectEndpointsResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("instanceConnectEndpointSet"); + for (InstanceConnectEndpoint endpoint : page.items()) { + xml.start("item").raw(instanceConnectEndpointXml(endpoint)).end("item"); + } + xml.end("instanceConnectEndpointSet"); + if (page.nextToken() != null) { + xml.elem("nextToken", page.nextToken()); + } + xml.end("DescribeInstanceConnectEndpointsResponse"); + return xmlResponse(xml.build()); + } + + private Response handleDeleteInstanceConnectEndpoint(MultivaluedMap p, String region) { + String id = p.getFirst("InstanceConnectEndpointId"); + if (id == null || id.isBlank()) { + throw new AwsException("MissingParameter", + "The request must contain the parameter InstanceConnectEndpointId", 400); + } + service.describeInstanceConnectEndpoints(region, List.of(id), List.of()); + checkDryRun(p); + InstanceConnectEndpoint endpoint = service.deleteInstanceConnectEndpoint(region, id); + XmlBuilder xml = new XmlBuilder() + .start("DeleteInstanceConnectEndpointResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("instanceConnectEndpoint").raw(instanceConnectEndpointXml(endpoint)).end("instanceConnectEndpoint") + .end("DeleteInstanceConnectEndpointResponse"); + return xmlResponse(xml.build()); + } + + private String instanceConnectEndpointXml(InstanceConnectEndpoint endpoint) { + XmlBuilder xml = new XmlBuilder() + .elem("ownerId", endpoint.getOwnerId()) + .elem("instanceConnectEndpointId", endpoint.getInstanceConnectEndpointId()) + .elem("instanceConnectEndpointArn", endpoint.getInstanceConnectEndpointArn()) + .elem("state", endpoint.getState()) + .elem("stateMessage", "") + .elem("dnsName", endpoint.getDnsName()) + .elem("fipsDnsName", endpoint.getFipsDnsName()) + .start("networkInterfaceIdSet"); + endpoint.getNetworkInterfaceIds().forEach(id -> xml.elem("item", id)); + xml.end("networkInterfaceIdSet") + .elem("vpcId", endpoint.getVpcId()) + .elem("availabilityZone", endpoint.getAvailabilityZone()) + .elem("availabilityZoneId", endpoint.getAvailabilityZoneId()) + .elem("createdAt", endpoint.getCreatedAt() == null ? null : ISO_FMT.format(endpoint.getCreatedAt())) + .elem("subnetId", endpoint.getSubnetId()) + .elem("preserveClientIp", endpoint.isPreserveClientIp()) + .start("securityGroupIdSet"); + endpoint.getSecurityGroupIds().forEach(id -> xml.elem("item", id)); + xml.end("securityGroupIdSet") + .elem("ipAddressType", endpoint.getIpAddressType()) + .start("publicDnsNames") + .start("ipv4") + .elem("dnsName", endpoint.getDnsName()) + .elem("fipsDnsName", endpoint.getFipsDnsName()) + .end("ipv4") + .end("publicDnsNames"); + xml.raw(tagSetXml(endpoint.getTags())); + return xml.build(); + } + // ─── Capacity Reservation handlers ──────────────────────────────────────── private Response handleCreateCapacityReservation(MultivaluedMap p, String region) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index eed691cdb4..899bbe70ab 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -12,6 +12,7 @@ import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.CidrCanonicalizer; import io.github.hectorvent.floci.core.common.ContainerTeardown; import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.core.common.RequestScopes; import io.github.hectorvent.floci.core.common.Resettable; @@ -37,6 +38,7 @@ import io.github.hectorvent.floci.services.ec2.model.Host; import io.github.hectorvent.floci.services.ec2.model.IamInstanceProfileAssociation; import io.github.hectorvent.floci.services.ec2.model.Image; import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.ec2.model.InstanceConnectEndpoint; import io.github.hectorvent.floci.services.ec2.model.InstanceCreditSpecification; import io.github.hectorvent.floci.services.ec2.model.InstanceCreditSpecificationListResult; import io.github.hectorvent.floci.services.ec2.model.InstanceNetworkInterface; @@ -178,7 +180,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab private static final String TAGGABLE_RESOURCE_TYPES = "(cvpn-endpoint|subnet-cidr-assoc|vpc-cidr-assoc" + "|ipam-pool-alloc|ipam-scope|ipam-pool|ipam" + "|traf-mir-fil|traf-mir-tar|iip-assoc|eni-attach|tgw-attach|tgw-rtb|vpce-svc|aclassoc|eipassoc" - + "|eipalloc|rtbassoc|subnet|fleet|cagw|dopt|eigw|snap|vpce|acl|ami|cgw|eni|igw|key|nat|pcx|rtb|scr" + + "|eipalloc|rtbassoc|subnet|fleet|cagw|dopt|eice|eigw|snap|vpce|acl|ami|cgw|eni|igw|key|nat|pcx|rtb|scr" + "|sfr|sgr|sir|tgw|tms|vgw|vol|vpc|vpn|cr|fl|lt|pl|sg|h|i|r)-"; private static final Pattern TAGGABLE_RESOURCE_ID = Pattern.compile(TAGGABLE_RESOURCE_TYPES + "(?:[0-9a-f]{8,}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"); @@ -304,6 +306,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab private final StorageBackend launchTemplates; private final StorageBackend vpcEndpoints; private final StorageBackend natGateways; + private final StorageBackend instanceConnectEndpoints; private final StorageBackend spotInstanceRequests; private final StorageBackend networkAcls; private final StorageBackend managedPrefixLists; @@ -588,7 +591,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab storageFactory.create("ec2", "ec2-egress-only-internet-gateways.json", new TypeReference>() {}), storageFactory.create("ec2", "ec2-dhcp-options.json", - new TypeReference>() {})); + new TypeReference>() {}), + storageFactory.create("ec2", "ec2-instance-connect-endpoints.json", + new TypeReference>() {})); } // Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly). @@ -654,7 +659,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), null, null, null, new InMemoryStorage<>(), new InMemoryStorage<>(), - new InMemoryStorage<>(), dhcpOptions); + new InMemoryStorage<>(), dhcpOptions, AccountAwareStorageBackend.inMemory("000000000000")); } // Package-private for hermetic tests, transit-gateway-aware. The shorter overload above keeps its @@ -881,7 +886,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab transitGatewayPropagations, transitGatewayRoutes, vpcPeeringConnections, networkInterfaces, capacityReservations, volumeModifications, requestContextInstance, iamService, volumeBlockDeviceManager, hosts, - transitGatewayPeeringAttachments, egressOnlyInternetGateways, new InMemoryStorage<>()); + transitGatewayPeeringAttachments, egressOnlyInternetGateways, new InMemoryStorage<>(), + AccountAwareStorageBackend.inMemory("000000000000")); } Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager, @@ -922,7 +928,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab StorageBackend hosts, StorageBackend transitGatewayPeeringAttachments, StorageBackend egressOnlyInternetGateways, - StorageBackend dhcpOptions) { + StorageBackend dhcpOptions, + StorageBackend instanceConnectEndpoints) { + this.instanceConnectEndpoints = instanceConnectEndpoints; this.hosts = hosts; this.egressOnlyInternetGateways = egressOnlyInternetGateways; this.transitGatewayPeeringAttachments = transitGatewayPeeringAttachments; @@ -4704,14 +4712,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab String regionPrefix = region + "::"; return privateIpsBySubnet(valuesOfEveryAccount(networkInterfaces, regionPrefix), valuesOfEveryAccount(instances, regionPrefix), - valuesOfEveryAccount(natGateways, regionPrefix)) + valuesOfEveryAccount(natGateways, regionPrefix), + valuesOfEveryAccount(instanceConnectEndpoints, regionPrefix)) .getOrDefault(subnetId, Set.of()); } /** * Every address a stored resource holds in the subnet: {@link #privateIpsTaken}, plus what the - * instances, network interfaces and NAT gateways of every account hold there. Default subnet - * ids are the same in every account, so their Docker network, and its lease table, is shared. + * instances, network interfaces, NAT gateways and EC2 Instance Connect Endpoints of every + * account hold there. Default subnet ids are the same in every account, so their Docker + * network, and its lease table, is shared. */ private Set privateIpsHeldOnVpcNetwork(String region, String subnetId) { Set held = privateIpsTaken(region, subnetId); @@ -4732,7 +4742,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab 400); } - /** Every private address a live instance, network interface or NAT gateway holds in the subnet. */ + /** + * Every private address a live instance, network interface, NAT gateway or EC2 Instance Connect + * Endpoint holds in the subnet. + */ private Set privateIpsInUse(String region, String subnetId) { return new HashSet<>(privateIpsBySubnet(region).getOrDefault(subnetId, Set.of())); } @@ -4752,12 +4765,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab String regionPrefix = region + "::"; return privateIpsBySubnet(networkInterfaces.scan(k -> k.startsWith(regionPrefix)), instances.scan(k -> k.startsWith(regionPrefix)), - natGateways.scan(k -> k.startsWith(regionPrefix))); + natGateways.scan(k -> k.startsWith(regionPrefix)), + instanceConnectEndpoints.scan(k -> k.startsWith(regionPrefix))); } private static Map> privateIpsBySubnet(List regionInterfaces, List regionInstances, - List regionNatGateways) { + List regionNatGateways, + List regionInstanceConnectEndpoints) { Map> bySubnet = new HashMap<>(); for (NetworkInterface ni : regionInterfaces) { Set inUse = bySubnet.computeIfAbsent(ni.getSubnetId(), ignored -> new HashSet<>()); @@ -4778,6 +4793,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab ni.getPrivateIpAddress()); } } + for (InstanceConnectEndpoint endpoint : regionInstanceConnectEndpoints) { + addIfSet(bySubnet.computeIfAbsent(endpoint.getSubnetId(), ignored -> new HashSet<>()), + endpoint.getPrivateIpAddress()); + } for (NatGateway natGateway : regionNatGateways) { if ("deleted".equals(natGateway.getState())) { continue; @@ -6492,7 +6511,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab .anyMatch(ni -> subnetIds.contains(ni.getSubnetId())) || vpcEndpoints.scan(k -> k.startsWith(regionPrefix)).stream() .anyMatch(endpoint -> !"deleted".equals(endpoint.getState()) - && nullToEmpty(endpoint.getSubnetIds()).stream().anyMatch(subnetIds::contains)); + && nullToEmpty(endpoint.getSubnetIds()).stream().anyMatch(subnetIds::contains)) + || instanceConnectEndpoints.scan(k -> k.startsWith(regionPrefix)).stream() + .anyMatch(endpoint -> subnetIds.contains(endpoint.getSubnetId())); if (occupied) { throw new AwsException("DependencyViolation", message, 400); } @@ -10259,6 +10280,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab case "nat" -> getRequiredNatGateway(region, resourceId); case "eipalloc" -> getRequiredAddress(region, resourceId); case "vpce" -> getRequiredVpcEndpoint(region, resourceId); + case "eice" -> requireInstanceConnectEndpoint(region, resourceId); case "pl" -> getRequiredManagedPrefixList(region, resourceId); case "tgw" -> getRequiredTransitGateway(region, resourceId); case "tgw-rtb" -> getRequiredTransitGatewayRouteTable(region, resourceId); @@ -12614,9 +12636,23 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (address.getNetworkInterfaceId() == null) { continue; } - NetworkInterfacePrivateIpAddress ip = new NetworkInterfacePrivateIpAddress(); - ip.setPrivateIpAddress(address.getPrivateIp()); - ip.setPrimary(address.isPrimary()); + // A secondary address sits on the primary address's interface; the helper marks its one + // address primary, so a secondary is added to the interface it returned. + NetworkInterface ni = result.get(address.getNetworkInterfaceId()); + NetworkInterfacePrivateIpAddress ip; + if (ni == null) { + ni = requesterManagedInterface(address.getNetworkInterfaceId(), + natGateway.getSubnetId(), natGateway.getVpcId(), subnet.getAvailabilityZone(), + "Interface for NAT Gateway " + natGateway.getNatGatewayId(), "nat_gateway", ownerId, + address.getPrivateIp()); + ip = ni.getPrivateIpAddresses().getFirst(); + result.put(address.getNetworkInterfaceId(), ni); + } else { + ip = new NetworkInterfacePrivateIpAddress(); + ip.setPrivateIpAddress(address.getPrivateIp()); + ip.setPrimary(address.isPrimary()); + ni.getPrivateIpAddresses().add(ip); + } if (address.getPublicIp() != null) { NetworkInterfaceAssociation assoc = new NetworkInterfaceAssociation(); assoc.setPublicIp(address.getPublicIp()); @@ -12625,28 +12661,286 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab assoc.setIpOwnerId(ownerId); ip.setAssociation(assoc); } - // A secondary address sits on the primary address's interface. - NetworkInterface existing = result.get(address.getNetworkInterfaceId()); - if (existing != null) { - existing.getPrivateIpAddresses().add(ip); - continue; - } - NetworkInterface ni = new NetworkInterface(); - ni.setNetworkInterfaceId(address.getNetworkInterfaceId()); - ni.setSubnetId(natGateway.getSubnetId()); - ni.setVpcId(natGateway.getVpcId()); - ni.setAvailabilityZone(subnet.getAvailabilityZone()); - ni.setDescription("Interface for NAT Gateway " + natGateway.getNatGatewayId()); - ni.setInterfaceType("nat_gateway"); - ni.setRequesterManaged(true); - ni.setOwnerId(ownerId); - ni.setPrivateIpAddress(address.getPrivateIp()); - ni.getPrivateIpAddresses().add(ip); - result.put(address.getNetworkInterfaceId(), ni); } return new ArrayList<>(result.values()); } + /** + * A requester-managed interface with one primary private address: the shape a NAT gateway's + * and an instance connect endpoint's interface share. + */ + private static NetworkInterface requesterManagedInterface(String eniId, String subnetId, String vpcId, + String availabilityZone, String description, + String interfaceType, String ownerId, + String privateIp) { + NetworkInterface ni = new NetworkInterface(); + ni.setNetworkInterfaceId(eniId); + ni.setSubnetId(subnetId); + ni.setVpcId(vpcId); + ni.setAvailabilityZone(availabilityZone); + ni.setDescription(description); + ni.setInterfaceType(interfaceType); + ni.setRequesterManaged(true); + ni.setOwnerId(ownerId); + ni.setPrivateIpAddress(privateIp); + NetworkInterfacePrivateIpAddress primaryIp = new NetworkInterfacePrivateIpAddress(); + primaryIp.setPrivateIpAddress(privateIp); + primaryIp.setPrimary(true); + ni.getPrivateIpAddresses().add(primaryIp); + return ni; + } + + /** + * The interface an instance connect endpoint owns, built from the endpoint so the id + * DescribeInstanceConnectEndpoints publishes in networkInterfaceIdSet resolves in + * DescribeNetworkInterfaces for as long as the endpoint exists. Its address is the endpoint's + * own, already counted by privateIpsBySubnet from the endpoint record. + */ + private List instanceConnectEndpointNetworkInterfacesOf(InstanceConnectEndpoint endpoint, + String ownerId) { + List result = new ArrayList<>(); + for (String eniId : endpoint.getNetworkInterfaceIds()) { + NetworkInterface ni = requesterManagedInterface(eniId, endpoint.getSubnetId(), endpoint.getVpcId(), + endpoint.getAvailabilityZone(), + "EC2 Instance Connect Endpoint " + endpoint.getInstanceConnectEndpointId(), + "ec2_instance_connect_endpoint", ownerId, endpoint.getPrivateIpAddress()); + for (String securityGroupId : endpoint.getSecurityGroupIds()) { + GroupIdentifier group = new GroupIdentifier(); + group.setGroupId(securityGroupId); + // Read for the account the endpoint was read for, as natNetworkInterfacesOf reads + // its subnet: the explicit-account overload may run under another ambient account. + String groupKey = key(endpoint.getRegion(), securityGroupId); + (securityGroups instanceof AccountAwareStorageBackend aware + ? aware.getForAccount(ownerId, groupKey).or(() -> aware.getLegacyForAccount(ownerId, groupKey)) + : securityGroups.get(groupKey)) + .ifPresent(sg -> group.setGroupName(sg.getGroupName())); + ni.getGroups().add(group); + } + result.add(ni); + } + return result; + } + + // ─── EC2 Instance Connect Endpoints ───────────────────────────────────── + + /** The public suffix every endpoint DNS name ends in; it resolves to 127.0.0.1 in public DNS. */ + static final String INSTANCE_CONNECT_ENDPOINT_DNS_SUFFIX = "localhost.floci.io"; + private static final Set INSTANCE_CONNECT_ENDPOINT_IP_TYPES = Set.of("ipv4", "dualstack", "ipv6"); + /** + * The names matchesInstanceConnectEndpointFilter implements, exactly the DescribeInstanceConnectEndpoints + * reference's list; tag:<key> is admitted through tag-key. + */ + private static final Set INSTANCE_CONNECT_ENDPOINT_FILTERS = Set.of("instance-connect-endpoint-id", + "state", "vpc-id", "subnet-id", "tag-key", "tag-value"); + /** + * Creates an endpoint in {@code subnetId}. Creation is immediate ({@code create-complete}); on + * AWS it takes a few minutes. The DNS names live under {@link #INSTANCE_CONNECT_ENDPOINT_DNS_SUFFIX}, + * which resolves to the loopback address where Floci's HTTPS listener is published, and which + * Floci's wildcard server certificate covers. A replayed {@code clientToken} returns the endpoint + * the first call created; reused with another subnet, security group set, IP address type, + * PreserveClientIp or tag set it fails with {@code IdempotentParameterMismatch}. + */ + public InstanceConnectEndpoint createInstanceConnectEndpoint(String region, String subnetId, + List securityGroupIds, + Boolean preserveClientIp, String ipAddressType, + List tagList, String clientToken) { + return createInstanceConnectEndpoint(region, subnetId, securityGroupIds, preserveClientIp, ipAddressType, + tagList, clientToken, false); + } + + /** As above; with {@code dryRun} the request is validated and then answered with DryRunOperation. */ + public InstanceConnectEndpoint createInstanceConnectEndpoint(String region, String subnetId, + List securityGroupIds, + Boolean preserveClientIp, String ipAddressType, + List tagList, String clientToken, + boolean dryRun) { + // Held from the client-token replay scan to the save: two creates with one token then see + // each other, and deleteSubnet, which takes the same lock, cannot remove the subnet between + // requireSubnet and the save. + synchronized (attachmentTopologyLock(region)) { + return createInstanceConnectEndpointHeld(region, subnetId, securityGroupIds, preserveClientIp, + ipAddressType, tagList, clientToken, dryRun); + } + } + + private InstanceConnectEndpoint createInstanceConnectEndpointHeld(String region, String subnetId, + List securityGroupIds, + Boolean preserveClientIp, String ipAddressType, + List tagList, String clientToken, + boolean dryRun) { + if (subnetId == null || subnetId.isBlank()) { + throw new AwsException("MissingParameter", "The request must contain the parameter SubnetId", 400); + } + Subnet subnet = requireSubnet(region, subnetId); + String type = ipAddressType == null || ipAddressType.isBlank() ? "ipv4" : ipAddressType; + if (!INSTANCE_CONNECT_ENDPOINT_IP_TYPES.contains(type)) { + throw new AwsException("InvalidParameterValue", + "Value (" + type + ") for parameter IpAddressType is invalid.", 400); + } + if (Boolean.TRUE.equals(preserveClientIp) && !"ipv4".equals(type)) { + throw new AwsException("InvalidParameterCombination", + "PreserveClientIp is only supported on IPv4 EC2 Instance Connect Endpoints.", 400); + } + List groups = new ArrayList<>(); + if (securityGroupIds == null || securityGroupIds.isEmpty()) { + securityGroups.scan(k -> true).stream() + .filter(sg -> region.equals(sg.getRegion()) && subnet.getVpcId().equals(sg.getVpcId()) + && "default".equals(sg.getGroupName())) + .findFirst() + .ifPresent(sg -> groups.add(sg.getGroupId())); + } else { + for (String groupId : securityGroupIds) { + SecurityGroup sg = getRequiredSecurityGroup(region, groupId); + if (!subnet.getVpcId().equals(sg.getVpcId())) { + throw new AwsException("InvalidParameter", "Security group " + groupId + + " does not belong to VPC " + subnet.getVpcId() + ".", 400); + } + groups.add(groupId); + } + } + if (dryRun) { + throw new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412); + } + String token = clientToken != null && !clientToken.isBlank() ? clientToken : null; + if (token != null) { + // Compared after defaults are applied, so a retry that omits a defaulted parameter the + // first call also omitted still matches. + Optional replay = instanceConnectEndpoints.scan(k -> k.startsWith(region + "::")) + .stream().filter(existing -> token.equals(existing.getClientToken())).findFirst(); + if (replay.isPresent()) { + InstanceConnectEndpoint first = replay.get(); + if (!subnetId.equals(first.getSubnetId()) + || !new HashSet<>(groups).equals(new HashSet<>(first.getSecurityGroupIds())) + || !type.equals(first.getIpAddressType()) + || Boolean.TRUE.equals(preserveClientIp) != first.isPreserveClientIp() + || !tagMap(tagList).equals(tagMap(first.getCreationTags()))) { + throw new AwsException("IdempotentParameterMismatch", + "The client token '" + token + "' was already used with different parameters", 400); + } + return withTags(first); + } + } + + String id = "eice-" + randomHex(17); + InstanceConnectEndpoint endpoint = new InstanceConnectEndpoint(); + endpoint.setInstanceConnectEndpointId(id); + endpoint.setInstanceConnectEndpointArn(AwsArnUtils.Arn.of("ec2", region, callerAccountId(), + "instance-connect-endpoint/" + id).toString()); + endpoint.setOwnerId(callerAccountId()); + endpoint.setState("create-complete"); + endpoint.setDnsName(id + "." + INSTANCE_CONNECT_ENDPOINT_DNS_SUFFIX); + endpoint.setFipsDnsName(id + "-fips." + INSTANCE_CONNECT_ENDPOINT_DNS_SUFFIX); + endpoint.setNetworkInterfaceIds(new ArrayList<>(List.of("eni-" + randomHex(17)))); + endpoint.setVpcId(subnet.getVpcId()); + endpoint.setSubnetId(subnetId); + endpoint.setAvailabilityZone(subnet.getAvailabilityZone()); + endpoint.setAvailabilityZoneId(subnet.getAvailabilityZoneId()); + endpoint.setCreatedAt(Instant.now()); + endpoint.setPreserveClientIp(Boolean.TRUE.equals(preserveClientIp)); + endpoint.setSecurityGroupIds(groups); + endpoint.setIpAddressType(type); + endpoint.setRegion(region); + endpoint.setClientToken(token); + endpoint.setCreationTags(InstanceConnectEndpoint.copyTags(tagList == null ? List.of() : tagList)); + synchronized (privateIpAllocationLock) { + endpoint.setPrivateIpAddress(assignPrivateIp(region, subnetId)); + instanceConnectEndpoints.put(key(region, id), endpoint); + } + if (tagList != null && !tagList.isEmpty()) { + createTags(region, List.of(id), tagList); + } + return withTags(endpoint); + } + + public List describeInstanceConnectEndpoints(String region, List ids, + Map> filters) { + return describeInstanceConnectEndpoints(region, ids, filterList(filters)); + } + + public List describeInstanceConnectEndpoints(String region, List ids, + List>> filters) { + // Checked before the scan, so a bad name fails even when no endpoint is there to test it on. + if (filters != null) { + requireSupportedFilters(filters.stream().map(Map.Entry::getKey).toList(), + INSTANCE_CONNECT_ENDPOINT_FILTERS); + } + for (String id : ids) { + requireInstanceConnectEndpoint(region, id); + } + return instanceConnectEndpoints.scan(k -> k.startsWith(region + "::")).stream() + .filter(endpoint -> ids.isEmpty() || ids.contains(endpoint.getInstanceConnectEndpointId())) + .map(this::withTags) + .filter(endpoint -> filters == null || filters.stream() + .allMatch(filter -> matchesInstanceConnectEndpointFilter(endpoint, filter.getKey(), + filter.getValue()))) + .sorted(Comparator.comparing(InstanceConnectEndpoint::getInstanceConnectEndpointId)) + .collect(Collectors.toList()); + } + + /** + * One page of {@link #describeInstanceConnectEndpoints}, in endpoint ID order. A null + * {@code maxResults} (omitted) returns every match; a value sent outside the model's 1 to 50 + * (InstanceConnectEndpointMaxResults), zero and negatives included, is InvalidMaxResults, as + * DescribeTags refuses its own range. + */ + public PaginatedResult describeInstanceConnectEndpoints( + String region, List ids, List>> filters, + Integer maxResults, String nextToken) { + if (maxResults != null && (maxResults < 1 || maxResults > 50)) { + throw new AwsException("InvalidMaxResults", + "Value (" + maxResults + ") for parameter MaxResults is invalid. " + + "Expecting a value between 1 and 50.", 400); + } + return Pagination.paginate(describeInstanceConnectEndpoints(region, ids, filters), + InstanceConnectEndpoint::getInstanceConnectEndpointId, + maxResults == null ? Integer.MAX_VALUE : maxResults, nextToken, "eice", + token -> new AwsException("InvalidParameterValue", "Invalid NextToken", 400)); + } + + /** Deletes the endpoint and answers with it in {@code delete-in-progress}, as AWS does. */ + public InstanceConnectEndpoint deleteInstanceConnectEndpoint(String region, String id) { + InstanceConnectEndpoint endpoint = withTags(requireInstanceConnectEndpoint(region, id)); + synchronized (privateIpAllocationLock) { + instanceConnectEndpoints.delete(key(region, id)); + if (vpcNetworkManager != null) { + vpcNetworkManager.releasePrivateIp(region, endpoint.getSubnetId(), endpoint.getPrivateIpAddress()); + } + } + removeTags(region, id); + endpoint.getNetworkInterfaceIds().forEach(eniId -> removeTags(region, eniId)); + endpoint.setState("delete-in-progress"); + return endpoint; + } + + private InstanceConnectEndpoint requireInstanceConnectEndpoint(String region, String id) { + return instanceConnectEndpoints.get(key(region, id)).orElseThrow(() -> new AwsException( + "InvalidInstanceConnectEndpointId.NotFound", + "The instance connect endpoint ID '" + id + "' does not exist", 400)); + } + + /** A copy of the stored endpoint carrying its current tags; the stored object is never changed. */ + private InstanceConnectEndpoint withTags(InstanceConnectEndpoint stored) { + InstanceConnectEndpoint endpoint = new InstanceConnectEndpoint(stored); + endpoint.setTags(new ArrayList<>(resourceTags(stored.getRegion(), stored.getInstanceConnectEndpointId()))); + return endpoint; + } + + private boolean matchesInstanceConnectEndpointFilter(InstanceConnectEndpoint endpoint, String name, + List values) { + if (name.startsWith("tag:") || "tag-key".equals(name)) { + return matchesTagFilter(endpoint.getTags(), name, values, Ec2Service::matchesFilterValue); + } + return switch (name) { + case "instance-connect-endpoint-id" -> matchesFilterValue(values, endpoint.getInstanceConnectEndpointId()); + case "state" -> matchesFilterValue(values, endpoint.getState()); + case "vpc-id" -> matchesFilterValue(values, endpoint.getVpcId()); + case "subnet-id" -> matchesFilterValue(values, endpoint.getSubnetId()); + case "tag-value" -> endpoint.getTags().stream().anyMatch(tag -> matchesFilterValue(values, tag.getValue())); + default -> throw new AwsException("InvalidParameterValue", + "The filter '" + name + "' is invalid", 400); + }; + } + public List describeNatGateways(String region, List natGatewayIds, Map> filters) { return describeNatGateways(region, natGatewayIds, filterList(filters)); @@ -14713,27 +15007,34 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab result.add(endpointNi); } - // The ENI a NAT gateway owns. DescribeNatGateways publishes its id (aws_nat_gateway's - // network_interface_id), so it has to resolve here too. Unlike the endpoint arm above this - // one honours the explicit account: gateways and their subnets are read for safeAccount. + // The ENIs a NAT gateway and an instance connect endpoint own, NAT first. DescribeNatGateways + // publishes a gateway's id (aws_nat_gateway's network_interface_id) and an endpoint publishes + // its own in networkInterfaceIdSet, so both have to resolve here too. Unlike the VPC endpoint + // arm above this one honours the explicit account: gateways, endpoints and the records their + // interfaces are built from are read for safeAccount. + List managedInterfaces = new ArrayList<>(); for (NatGateway natGateway : natGatewaysOf(safeAccount)) { - if (!region.equals(natGateway.getRegion())) { + if (region.equals(natGateway.getRegion())) { + managedInterfaces.addAll(natNetworkInterfacesOf(natGateway, safeAccount)); + } + } + List regionEndpoints = + instanceConnectEndpoints instanceof AccountAwareStorageBackend aware + ? aware.scanForAccount(safeAccount, k -> k.startsWith(region + "::")) + : instanceConnectEndpoints.scan(k -> k.startsWith(region + "::")); + for (InstanceConnectEndpoint endpoint : regionEndpoints) { + managedInterfaces.addAll(instanceConnectEndpointNetworkInterfacesOf(endpoint, safeAccount)); + } + for (NetworkInterface managedNi : managedInterfaces) { + String managedEniId = managedNi.getNetworkInterfaceId(); + if (foundIds.contains(managedEniId) + || !networkInterfaceIds.isEmpty() && !networkInterfaceIds.contains(managedEniId)) { continue; } - for (NetworkInterface natNi : natNetworkInterfacesOf(natGateway, safeAccount)) { - String natEniId = natNi.getNetworkInterfaceId(); - if (foundIds.contains(natEniId)) { - continue; - } - if (!networkInterfaceIds.isEmpty() && !networkInterfaceIds.contains(natEniId)) { - continue; - } - foundIds.add(natEniId); - natNi.getTagSet().addAll(tagsOf(safeAccount, region, natEniId).orElse(List.of())); - if (!matchesFilters(natNi, filters, region)) { - continue; - } - result.add(natNi); + foundIds.add(managedEniId); + managedNi.getTagSet().addAll(tagsOf(safeAccount, region, managedEniId).orElse(List.of())); + if (matchesFilters(managedNi, filters, region)) { + result.add(managedNi); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/InstanceConnectEndpoint.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/InstanceConnectEndpoint.java new file mode 100644 index 0000000000..bbc6fb0992 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/InstanceConnectEndpoint.java @@ -0,0 +1,132 @@ +package io.github.hectorvent.floci.services.ec2.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/** An EC2 Instance Connect Endpoint: the tunnel entry point into one subnet's VPC. */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class InstanceConnectEndpoint { + + private String instanceConnectEndpointId; + private String instanceConnectEndpointArn; + private String ownerId; + private String state; + private String dnsName; + private String fipsDnsName; + private List networkInterfaceIds = new ArrayList<>(); + private String vpcId; + private String subnetId; + private String availabilityZone; + private String availabilityZoneId; + private Instant createdAt; + private boolean preserveClientIp; + private List securityGroupIds = new ArrayList<>(); + private String ipAddressType; + private String region; + /** The endpoint's interface address in its subnet: the source instances see when the client IP is not preserved. */ + private String privateIpAddress; + private String clientToken; + /** The tags the create request carried, compared on a ClientToken replay; later CreateTags calls do not change them. */ + private List creationTags = new ArrayList<>(); + private List tags = new ArrayList<>(); + + public InstanceConnectEndpoint() {} + + /** A copy whose lists are its own, so a caller can change it without touching the stored endpoint. */ + public InstanceConnectEndpoint(InstanceConnectEndpoint other) { + instanceConnectEndpointId = other.instanceConnectEndpointId; + instanceConnectEndpointArn = other.instanceConnectEndpointArn; + ownerId = other.ownerId; + state = other.state; + dnsName = other.dnsName; + fipsDnsName = other.fipsDnsName; + networkInterfaceIds = new ArrayList<>(other.networkInterfaceIds); + vpcId = other.vpcId; + subnetId = other.subnetId; + availabilityZone = other.availabilityZone; + availabilityZoneId = other.availabilityZoneId; + createdAt = other.createdAt; + preserveClientIp = other.preserveClientIp; + securityGroupIds = new ArrayList<>(other.securityGroupIds); + ipAddressType = other.ipAddressType; + region = other.region; + privateIpAddress = other.privateIpAddress; + clientToken = other.clientToken; + creationTags = copyTags(other.creationTags); + tags = copyTags(other.tags); + } + + /** A list of new Tag objects equal to {@code source}'s, so neither side can change the other's. */ + public static List copyTags(List source) { + List copy = new ArrayList<>(source.size()); + for (Tag tag : source) { + copy.add(new Tag(tag.getKey(), tag.getValue())); + } + return copy; + } + + public String getInstanceConnectEndpointId() { return instanceConnectEndpointId; } + public void setInstanceConnectEndpointId(String id) { this.instanceConnectEndpointId = id; } + + public String getInstanceConnectEndpointArn() { return instanceConnectEndpointArn; } + public void setInstanceConnectEndpointArn(String arn) { this.instanceConnectEndpointArn = arn; } + + public String getOwnerId() { return ownerId; } + public void setOwnerId(String ownerId) { this.ownerId = ownerId; } + + public String getState() { return state; } + public void setState(String state) { this.state = state; } + + public String getDnsName() { return dnsName; } + public void setDnsName(String dnsName) { this.dnsName = dnsName; } + + public String getFipsDnsName() { return fipsDnsName; } + public void setFipsDnsName(String fipsDnsName) { this.fipsDnsName = fipsDnsName; } + + public List getNetworkInterfaceIds() { return networkInterfaceIds; } + public void setNetworkInterfaceIds(List ids) { this.networkInterfaceIds = ids != null ? ids : new ArrayList<>(); } + + public String getVpcId() { return vpcId; } + public void setVpcId(String vpcId) { this.vpcId = vpcId; } + + public String getSubnetId() { return subnetId; } + public void setSubnetId(String subnetId) { this.subnetId = subnetId; } + + public String getAvailabilityZone() { return availabilityZone; } + public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; } + + public String getAvailabilityZoneId() { return availabilityZoneId; } + public void setAvailabilityZoneId(String availabilityZoneId) { this.availabilityZoneId = availabilityZoneId; } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + + public boolean isPreserveClientIp() { return preserveClientIp; } + public void setPreserveClientIp(boolean preserveClientIp) { this.preserveClientIp = preserveClientIp; } + + public List getSecurityGroupIds() { return securityGroupIds; } + public void setSecurityGroupIds(List ids) { this.securityGroupIds = ids != null ? ids : new ArrayList<>(); } + + public String getIpAddressType() { return ipAddressType; } + public void setIpAddressType(String ipAddressType) { this.ipAddressType = ipAddressType; } + + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } + + public String getPrivateIpAddress() { return privateIpAddress; } + public void setPrivateIpAddress(String privateIpAddress) { this.privateIpAddress = privateIpAddress; } + + public String getClientToken() { return clientToken; } + public void setClientToken(String clientToken) { this.clientToken = clientToken; } + + public List getCreationTags() { return creationTags; } + public void setCreationTags(List creationTags) { this.creationTags = creationTags != null ? creationTags : new ArrayList<>(); } + + public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags != null ? tags : new ArrayList<>(); } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceConnectEndpointIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceConnectEndpointIntegrationTest.java new file mode 100644 index 0000000000..ccd416b8b5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceConnectEndpointIntegrationTest.java @@ -0,0 +1,240 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.Ec2Requests.ec2; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.matchesPattern; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * CreateInstanceConnectEndpoint, DescribeInstanceConnectEndpoints and DeleteInstanceConnectEndpoint + * over the EC2 Query wire: SecurityGroupId.N and TagSpecification.N on the way in, the response + * envelopes on the way out. Every read is a separate Describe rather than the create's own response. + */ +@QuarkusTest +class Ec2InstanceConnectEndpointIntegrationTest { + + private static final String ITEM = "DescribeInstanceConnectEndpointsResponse.instanceConnectEndpointSet.item"; + private static final String CREATED = "CreateInstanceConnectEndpointResponse.instanceConnectEndpoint"; + + @Test + void createDescribeAndDeleteOverTheWire() { + String vpcId = createVpc("10.81.0.0/16"); + String subnetId = createSubnet(vpcId, "10.81.1.0/24"); + String groupA = createGroup(vpcId, "eice-a"); + String groupB = createGroup(vpcId, "eice-b"); + String name = "eice-" + UUID.randomUUID(); + String token = UUID.randomUUID().toString(); + + String id = create(subnetId, groupA, groupB, name, token) + .post("/").then().statusCode(200) + .body("CreateInstanceConnectEndpointResponse.clientToken", equalTo(token)) + .body(CREATED + ".instanceConnectEndpointId", matchesPattern("eice-[0-9a-f]{17}")) + .body(CREATED + ".state", equalTo("create-complete")) + .body(CREATED + ".subnetId", equalTo(subnetId)) + .extract().path(CREATED + ".instanceConnectEndpointId"); + + // The replay answers with the same endpoint and makes no second one. + create(subnetId, groupA, groupB, name, token) + .post("/").then().statusCode(200) + .body(CREATED + ".instanceConnectEndpointId", equalTo(id)); + + ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1") + .formParam("Filter.1.Name", "tag:Name") + .formParam("Filter.1.Value.1", name) + .post("/").then().statusCode(200) + .body(ITEM + ".size()", equalTo(1)) + .body(ITEM + ".instanceConnectEndpointId", equalTo(id)) + .body(ITEM + ".instanceConnectEndpointArn", + equalTo("arn:aws:ec2:us-east-1:000000000000:instance-connect-endpoint/" + id)) + .body(ITEM + ".vpcId", equalTo(vpcId)) + .body(ITEM + ".subnetId", equalTo(subnetId)) + .body(ITEM + ".ipAddressType", equalTo("ipv4")) + .body(ITEM + ".preserveClientIp", equalTo("false")) + .body(ITEM + ".dnsName", equalTo(id + ".localhost.floci.io")) + .body(ITEM + ".publicDnsNames.ipv4.dnsName", equalTo(id + ".localhost.floci.io")) + .body(ITEM + ".securityGroupIdSet.item", containsInAnyOrder(groupA, groupB)) + .body(ITEM + ".tagSet.item.find { it.key == 'Name' }.value", equalTo(name)); + + // The interface the endpoint publishes resolves through DescribeNetworkInterfaces. + String eniId = ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1") + .formParam("InstanceConnectEndpointId.1", id) + .post("/").then().statusCode(200) + .extract().path(ITEM + ".networkInterfaceIdSet.item"); + String eni = "DescribeNetworkInterfacesResponse.networkInterfaceSet.item"; + ec2("DescribeNetworkInterfaces", "test", "us-east-1") + .formParam("NetworkInterfaceId.1", eniId) + .post("/").then().statusCode(200) + .body(eni + ".networkInterfaceId", equalTo(eniId)) + .body(eni + ".subnetId", equalTo(subnetId)) + .body(eni + ".vpcId", equalTo(vpcId)) + .body(eni + ".interfaceType", equalTo("ec2_instance_connect_endpoint")) + .body(eni + ".requesterManaged", equalTo("true")) + .body(eni + ".description", equalTo("EC2 Instance Connect Endpoint " + id)) + .body(eni + ".privateIpAddress", matchesPattern("10\\.81\\.1\\.\\d+")) + .body(eni + ".groupSet.item.groupId", containsInAnyOrder(groupA, groupB)); + + ec2("DeleteInstanceConnectEndpoint", "test", "us-east-1") + .formParam("InstanceConnectEndpointId", id) + .post("/").then().statusCode(200) + .body("DeleteInstanceConnectEndpointResponse.instanceConnectEndpoint.instanceConnectEndpointId", + equalTo(id)) + .body("DeleteInstanceConnectEndpointResponse.instanceConnectEndpoint.state", + equalTo("delete-in-progress")); + + ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1") + .formParam("InstanceConnectEndpointId.1", id) + .post("/").then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidInstanceConnectEndpointId.NotFound")); + ec2("DescribeNetworkInterfaces", "test", "us-east-1") + .formParam("NetworkInterfaceId.1", eniId) + .post("/").then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidNetworkInterfaceID.NotFound")); + + deleteAll(List.of(groupA, groupB), subnetId, vpcId); + } + + @Test + void dryRunValidatesFirstAndChangesNothing() { + String vpcId = createVpc("10.82.0.0/16"); + String subnetId = createSubnet(vpcId, "10.82.1.0/24"); + String missing = "eice-0123456789abcdef0"; + + // An invalid request fails on its own error, not DryRunOperation. + assertError(ec2("CreateInstanceConnectEndpoint", "test", "us-east-1") + .formParam("SubnetId", "subnet-0123456789abcdef0").formParam("DryRun", "true"), + 400, "InvalidSubnetID.NotFound"); + assertError(ec2("CreateInstanceConnectEndpoint", "test", "us-east-1") + .formParam("SubnetId", subnetId).formParam("IpAddressType", "bogus").formParam("DryRun", "true"), + 400, "InvalidParameterValue"); + assertError(ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1") + .formParam("InstanceConnectEndpointId.1", missing).formParam("DryRun", "true"), + 400, "InvalidInstanceConnectEndpointId.NotFound"); + assertError(ec2("DeleteInstanceConnectEndpoint", "test", "us-east-1") + .formParam("InstanceConnectEndpointId", missing).formParam("DryRun", "true"), + 400, "InvalidInstanceConnectEndpointId.NotFound"); + + // A valid one answers DryRunOperation and creates or deletes nothing. + assertError(ec2("CreateInstanceConnectEndpoint", "test", "us-east-1") + .formParam("SubnetId", subnetId).formParam("DryRun", "true"), 412, "DryRunOperation"); + ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1") + .formParam("Filter.1.Name", "subnet-id").formParam("Filter.1.Value.1", subnetId) + .post("/").then().statusCode(200) + .body(ITEM + ".size()", equalTo(0)); + assertError(ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1").formParam("DryRun", "true"), + 412, "DryRunOperation"); + + String id = ec2("CreateInstanceConnectEndpoint", "test", "us-east-1").formParam("SubnetId", subnetId) + .post("/").then().statusCode(200).extract().path(CREATED + ".instanceConnectEndpointId"); + assertError(ec2("DeleteInstanceConnectEndpoint", "test", "us-east-1") + .formParam("InstanceConnectEndpointId", id).formParam("DryRun", "true"), 412, "DryRunOperation"); + ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1") + .formParam("InstanceConnectEndpointId.1", id) + .post("/").then().statusCode(200) + .body(ITEM + ".state", equalTo("create-complete")); + + ec2("DeleteInstanceConnectEndpoint", "test", "us-east-1").formParam("InstanceConnectEndpointId", id) + .post("/").then().statusCode(200); + deleteAll(List.of(), subnetId, vpcId); + } + + @Test + void describePagesWithMaxResultsAndNextToken() { + String vpcId = createVpc("10.83.0.0/16"); + String subnetId = createSubnet(vpcId, "10.83.1.0/24"); + List created = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + created.add(ec2("CreateInstanceConnectEndpoint", "test", "us-east-1").formParam("SubnetId", subnetId) + .post("/").then().statusCode(200).extract().path(CREATED + ".instanceConnectEndpointId")); + } + + List seen = new ArrayList<>(); + String token = null; + int pages = 0; + do { + RequestSpecification request = ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1") + .formParam("Filter.1.Name", "subnet-id").formParam("Filter.1.Value.1", subnetId) + .formParam("MaxResults", "2"); + if (token != null) { + request.formParam("NextToken", token); + } + XmlPath page = request.post("/").then().statusCode(200).extract().xmlPath(); + List ids = page.getList(ITEM + ".instanceConnectEndpointId", String.class); + assertTrue(ids.size() <= 2, ids.toString()); + seen.addAll(ids); + token = page.getString("DescribeInstanceConnectEndpointsResponse.nextToken"); + token = token == null || token.isEmpty() ? null : token; + pages++; + } while (token != null && pages < 5); + assertEquals(2, pages); + assertEquals(created.stream().sorted().toList(), seen); + + assertError(ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1").formParam("NextToken", "bogus"), + 400, "InvalidParameterValue"); + for (String outOfRange : List.of("0", "-1", "51")) { + assertError(ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1") + .formParam("MaxResults", outOfRange), 400, "InvalidMaxResults"); + } + for (String inRange : List.of("1", "50")) { + ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1").formParam("MaxResults", inRange) + .post("/").then().statusCode(200); + } + + for (String id : created) { + ec2("DeleteInstanceConnectEndpoint", "test", "us-east-1").formParam("InstanceConnectEndpointId", id) + .post("/").then().statusCode(200); + } + deleteAll(List.of(), subnetId, vpcId); + } + + private static void assertError(RequestSpecification request, int status, String code) { + request.post("/").then().statusCode(status).body("Response.Errors.Error.Code", equalTo(code)); + } + + private static RequestSpecification create(String subnetId, String groupA, String groupB, String name, + String token) { + return ec2("CreateInstanceConnectEndpoint", "test", "us-east-1") + .formParam("SubnetId", subnetId) + .formParam("SecurityGroupId.1", groupA) + .formParam("SecurityGroupId.2", groupB) + .formParam("TagSpecification.1.ResourceType", "instance-connect-endpoint") + .formParam("TagSpecification.1.Tag.1.Key", "Name") + .formParam("TagSpecification.1.Tag.1.Value", name) + .formParam("ClientToken", token); + } + + static String createVpc(String cidr) { + return ec2("CreateVpc", "test", "us-east-1").formParam("CidrBlock", cidr) + .post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId"); + } + + static String createSubnet(String vpcId, String cidr) { + return ec2("CreateSubnet", "test", "us-east-1").formParam("VpcId", vpcId).formParam("CidrBlock", cidr) + .post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId"); + } + + static String createGroup(String vpcId, String name) { + return ec2("CreateSecurityGroup", "test", "us-east-1").formParam("VpcId", vpcId) + .formParam("GroupName", name).formParam("GroupDescription", name) + .post("/").then().statusCode(200).extract().path("CreateSecurityGroupResponse.groupId"); + } + + static void deleteAll(List groups, String subnetId, String vpcId) { + for (String group : groups) { + ec2("DeleteSecurityGroup", "test", "us-east-1").formParam("GroupId", group) + .post("/").then().statusCode(200); + } + ec2("DeleteSubnet", "test", "us-east-1").formParam("SubnetId", subnetId).post("/").then().statusCode(200); + ec2("DeleteVpc", "test", "us-east-1").formParam("VpcId", vpcId).post("/").then().statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceConnectEndpointServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceConnectEndpointServiceTest.java new file mode 100644 index 0000000000..72fbc6977f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceConnectEndpointServiceTest.java @@ -0,0 +1,390 @@ +package io.github.hectorvent.floci.services.ec2; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier; +import io.github.hectorvent.floci.services.ec2.model.InstanceConnectEndpoint; +import io.github.hectorvent.floci.services.ec2.model.NetworkInterface; +import io.github.hectorvent.floci.services.ec2.model.Tag; +import io.github.hectorvent.floci.testing.InMemoryStorageFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static io.github.hectorvent.floci.testing.Ec2ServiceFixtures.mockModeService; +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; + +/** CreateInstanceConnectEndpoint, DescribeInstanceConnectEndpoints and DeleteInstanceConnectEndpoint. */ +class Ec2InstanceConnectEndpointServiceTest { + + private static final String REGION = "us-east-1"; + + @Test + void lifecycleFiltersAndDefaults() { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.71.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.71.1.0/24", "us-east-1a").getSubnetId(); + String otherVpc = service.createVpc(REGION, "10.72.0.0/16", false).getVpcId(); + String foreignGroup = service.createSecurityGroup(REGION, "foreign", "x", otherVpc).getGroupId(); + + InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), + null, null, List.of(new Tag("Name", "kthw")), null); + String id = endpoint.getInstanceConnectEndpointId(); + assertTrue(id.startsWith("eice-"), id); + assertEquals("create-complete", endpoint.getState()); + assertEquals(id + ".localhost.floci.io", endpoint.getDnsName()); + assertEquals(vpcId, endpoint.getVpcId()); + assertEquals("ipv4", endpoint.getIpAddressType()); + assertFalse(endpoint.isPreserveClientIp(), "AWS's default"); + assertEquals(1, endpoint.getSecurityGroupIds().size(), "the VPC's default group when none is given"); + assertTrue(endpoint.getPrivateIpAddress().startsWith("10.71.1."), endpoint.getPrivateIpAddress()); + + assertEquals(List.of(id), service.describeInstanceConnectEndpoints(REGION, List.of(), + Map.of("vpc-id", List.of(vpcId), "state", List.of("create-complete"), "tag:Name", List.of("kthw"))) + .stream().map(InstanceConnectEndpoint::getInstanceConnectEndpointId).toList()); + assertTrue(service.describeInstanceConnectEndpoints(REGION, List.of(), + Map.of("vpc-id", List.of(otherVpc))).isEmpty()); + assertEquals("InvalidParameterValue", assertThrows(AwsException.class, () -> service + .describeInstanceConnectEndpoints(REGION, List.of(), Map.of("bogus", List.of("x")))) + .getErrorCode()); + assertEquals("InvalidParameter", assertThrows(AwsException.class, () -> service + .createInstanceConnectEndpoint(REGION, subnetId, List.of(foreignGroup), null, null, List.of(), null)) + .getErrorCode()); + assertEquals("InvalidParameterCombination", assertThrows(AwsException.class, () -> service + .createInstanceConnectEndpoint(REGION, subnetId, List.of(), true, "dualstack", List.of(), null)) + .getErrorCode()); + assertEquals("InvalidSubnetID.NotFound", assertThrows(AwsException.class, () -> service + .createInstanceConnectEndpoint(REGION, "subnet-0000000000000000f", List.of(), null, null, + List.of(), null)) + .getErrorCode()); + + assertEquals("delete-in-progress", service.deleteInstanceConnectEndpoint(REGION, id).getState()); + assertEquals("InvalidInstanceConnectEndpointId.NotFound", assertThrows(AwsException.class, () -> service + .describeInstanceConnectEndpoints(REGION, List.of(id), Map.of())).getErrorCode()); + } + + @Test + void aLiveEndpointBlocksDeletingItsSubnetAndVpc() { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.74.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.74.1.0/24", "us-east-1a").getSubnetId(); + String id = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), null) + .getInstanceConnectEndpointId(); + + assertEquals("DependencyViolation", assertThrows(AwsException.class, + () -> service.deleteSubnet(REGION, subnetId)).getErrorCode()); + assertEquals("DependencyViolation", assertThrows(AwsException.class, + () -> service.deleteVpc(REGION, vpcId)).getErrorCode()); + + service.deleteInstanceConnectEndpoint(REGION, id); + service.deleteSubnet(REGION, subnetId); + service.deleteVpc(REGION, vpcId); + } + + @Test + void aNatGatewayCannotTakeTheAddressAnEndpointHolds() { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.75.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.75.1.0/24", "us-east-1a").getSubnetId(); + InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), + null, null, List.of(), null); + String held = endpoint.getPrivateIpAddress(); + + assertEquals("InvalidIPAddress.InUse", assertThrows(AwsException.class, () -> service + .createNatGateway(REGION, subnetId, null, "private", held, List.of())).getErrorCode()); + + // Once the endpoint is gone the address is free again, so the refusal above was the endpoint's. + service.deleteInstanceConnectEndpoint(REGION, endpoint.getInstanceConnectEndpointId()); + assertEquals(held, service.createNatGateway(REGION, subnetId, null, "private", held, List.of()) + .getNatGatewayAddresses().get(0).getPrivateIp()); + } + + @Test + void aReplayedClientTokenReturnsTheFirstEndpoint() { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.75.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.75.1.0/24", "us-east-1a").getSubnetId(); + String otherSubnet = service.createSubnet(REGION, vpcId, "10.75.2.0/24", "us-east-1a").getSubnetId(); + + String first = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), + "token-1").getInstanceConnectEndpointId(); + assertEquals(first, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, + List.of(), "token-1").getInstanceConnectEndpointId()); + assertEquals(1, service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).size()); + assertEquals("IdempotentParameterMismatch", assertThrows(AwsException.class, () -> service + .createInstanceConnectEndpoint(REGION, otherSubnet, List.of(), null, null, List.of(), "token-1")) + .getErrorCode()); + } + + @Test + void aReplayedClientTokenWithOtherParametersIsAMismatch() { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.78.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.78.1.0/24", "us-east-1a").getSubnetId(); + String group = service.createSecurityGroup(REGION, "eice", "x", vpcId).getGroupId(); + List tags = List.of(new Tag("Name", "kthw")); + String first = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group), false, "ipv4", tags, + "token-78").getInstanceConnectEndpointId(); + + // Defaults applied the same way match: omitted PreserveClientIp and IpAddressType are false and ipv4. + assertEquals(first, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group), null, null, + tags, "token-78").getInstanceConnectEndpointId()); + // Security groups are a set: the same groups in another order are the same request. + String other = service.createSecurityGroup(REGION, "eice-2", "x", vpcId).getGroupId(); + String ordered = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group, other), null, null, + tags, "token-78-sets").getInstanceConnectEndpointId(); + assertEquals(ordered, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(other, group), null, + null, tags, "token-78-sets").getInstanceConnectEndpointId()); + // A tag added after the create is not a creation parameter. + service.createTags(REGION, List.of(first), List.of(new Tag("Later", "x"))); + assertEquals(first, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group), null, null, + tags, "token-78").getInstanceConnectEndpointId()); + + Map retries = Map.of( + "security groups", () -> service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, + null, tags, "token-78"), + "tags", () -> service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group), null, null, + List.of(new Tag("Name", "other")), "token-78"), + "ip address type", () -> service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group), + null, "dualstack", tags, "token-78"), + "preserve client ip", () -> service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group), + true, null, tags, "token-78")); + retries.forEach((what, retry) -> assertEquals("IdempotentParameterMismatch", + assertThrows(AwsException.class, retry, what).getErrorCode(), what)); + assertEquals(2, service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).size()); + } + + @Test + void changingAReturnedEndpointLeavesTheStoredOneAlone() { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.76.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.76.1.0/24", "us-east-1a").getSubnetId(); + InstanceConnectEndpoint created = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, + null, List.of(new Tag("Name", "kthw")), null); + created.setState("bogus"); + created.getSecurityGroupIds().clear(); + InstanceConnectEndpoint described = service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).get(0); + described.getTags().clear(); + + InstanceConnectEndpoint again = service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).get(0); + assertEquals("create-complete", again.getState()); + assertEquals(1, again.getSecurityGroupIds().size()); + assertEquals(List.of("Name"), again.getTags().stream().map(Tag::getKey).toList()); + } + + @Test + void describeListsWhatTheClientTokenReplaySees() { + InMemoryStorageFactory storage = new InMemoryStorageFactory("000000000000"); + Ec2Service service = mockModeService(storage); + String vpcId = service.createVpc(REGION, "10.77.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.77.1.0/24", "us-east-1a").getSubnetId(); + String id = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), + "token-77").getInstanceConnectEndpointId(); + // Both scans pick a region's endpoints by store key; a record whose region field is unset + // (written before the field existed, say) is still in the region its key names. + StorageBackend store = storage.create("ec2", + "ec2-instance-connect-endpoints.json", new TypeReference>() {}); + InstanceConnectEndpoint stored = store.get(REGION + "::" + id).orElseThrow(); + stored.setRegion(null); + store.put(REGION + "::" + id, stored); + + assertEquals(id, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), + "token-77").getInstanceConnectEndpointId()); + assertEquals(List.of(id), service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).stream() + .map(InstanceConnectEndpoint::getInstanceConnectEndpointId).toList()); + } + + @Test + void concurrentCreatesWithOneClientTokenMakeOneEndpoint() throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(8); + try { + for (int round = 0; round < 50; round++) { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.73.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.73.1.0/24", "us-east-1a").getSubnetId(); + CountDownLatch go = new CountDownLatch(1); + List> ids = new ArrayList<>(); + for (int i = 0; i < 8; i++) { + ids.add(pool.submit(() -> { + go.await(); + return service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, + List.of(), "token-" + subnetId).getInstanceConnectEndpointId(); + })); + } + go.countDown(); + Set distinct = ConcurrentHashMap.newKeySet(); + for (Future id : ids) { + distinct.add(id.get()); + } + assertEquals(1, distinct.size(), "round " + round + ": " + distinct); + assertEquals(1, service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).size()); + } + } finally { + pool.shutdownNow(); + } + } + + @Test + void aSubnetDeletedDuringACreateNeverLeavesAnEndpointOnIt() throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + for (int round = 0; round < 200; round++) { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.74.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.74.1.0/24", "us-east-1a").getSubnetId(); + CountDownLatch go = new CountDownLatch(1); + Future create = pool.submit(() -> { + go.await(); + try { + service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), null); + } catch (AwsException expected) { + // InvalidSubnetID.NotFound: the delete won. + } + return null; + }); + Future delete = pool.submit(() -> { + go.await(); + try { + service.deleteSubnet(REGION, subnetId); + } catch (AwsException expected) { + // DependencyViolation: the create won. + } + return null; + }); + go.countDown(); + create.get(); + delete.get(); + boolean subnetGone = service.describeSubnets(REGION, List.of(), Map.of()).stream() + .noneMatch(subnet -> subnetId.equals(subnet.getSubnetId())); + boolean endpointOnIt = service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).stream() + .anyMatch(endpoint -> subnetId.equals(endpoint.getSubnetId())); + assertFalse(subnetGone && endpointOnIt, "round " + round + ": endpoint left on a deleted subnet"); + } + } finally { + pool.shutdownNow(); + } + } + + @Test + void changingAReturnedOrRequestedTagLeavesTheCreationParametersAlone() { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.81.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.81.1.0/24", "us-east-1a").getSubnetId(); + Tag requested = new Tag("Name", "kthw"); + String id = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, + List.of(requested), "token-81").getInstanceConnectEndpointId(); + requested.setValue("changed-after-create"); + service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).get(0) + .getCreationTags().get(0).setValue("changed-on-a-copy"); + + assertEquals(id, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, + List.of(new Tag("Name", "kthw")), "token-81").getInstanceConnectEndpointId()); + } + + @Test + void anUnknownFilterNameFailsWhenNoEndpointIsTestedAgainstIt() { + Ec2Service service = mockModeService(); + assertEquals("InvalidParameterValue", assertThrows(AwsException.class, () -> service + .describeInstanceConnectEndpoints(REGION, List.of(), Map.of("bogus", List.of("x")))) + .getErrorCode()); + + String vpcId = service.createVpc(REGION, "10.80.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.80.1.0/24", "us-east-1a").getSubnetId(); + service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), null); + // An earlier filter that excludes every endpoint does not hide the bad name after it. + List>> filters = List.of( + Map.entry("vpc-id", List.of("vpc-00000000000000000")), Map.entry("bogus", List.of("x"))); + assertEquals("InvalidParameterValue", assertThrows(AwsException.class, () -> service + .describeInstanceConnectEndpoints(REGION, List.of(), filters)).getErrorCode()); + } + + @Test + void tagValueMatchesAnEndpointCarryingThatValueUnderAnyKey() { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.81.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.81.1.0/24", "us-east-1a").getSubnetId(); + String id = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, + List.of(new Tag("Name", "kthw"), new Tag("Team", "infra")), null).getInstanceConnectEndpointId(); + + assertEquals(List.of(id), service.describeInstanceConnectEndpoints(REGION, List.of(), + Map.of("tag-value", List.of("nope", "infra"))) + .stream().map(InstanceConnectEndpoint::getInstanceConnectEndpointId).toList()); + assertTrue(service.describeInstanceConnectEndpoints(REGION, List.of(), + Map.of("tag-value", List.of("Team"))).isEmpty(), "a key is not a value"); + } + + @Test + void availabilityZoneAndOwnerIdAreRefusedLikeAnyFilterAwsDoesNotList() { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.82.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.82.1.0/24", "us-east-1a").getSubnetId(); + service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), null); + AwsException unknown = assertThrows(AwsException.class, () -> service + .describeInstanceConnectEndpoints(REGION, List.of(), Map.of("bogus", List.of("x")))); + for (String name : List.of("availability-zone", "owner-id")) { + AwsException error = assertThrows(AwsException.class, () -> service + .describeInstanceConnectEndpoints(REGION, List.of(), Map.of(name, List.of("x"))), name); + assertEquals(unknown.getErrorCode(), error.getErrorCode(), name); + assertEquals(unknown.getHttpStatus(), error.getHttpStatus(), name); + assertEquals("The filter '" + name + "' is invalid", error.getMessage(), name); + } + } + + @Test + void theEndpointsInterfaceResolvesInDescribeNetworkInterfacesUntilItIsDeleted() { + Ec2Service service = mockModeService(); + String vpcId = service.createVpc(REGION, "10.79.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet(REGION, vpcId, "10.79.1.0/24", "us-east-1a").getSubnetId(); + String otherSubnet = service.createSubnet(REGION, vpcId, "10.79.2.0/24", "us-east-1a").getSubnetId(); + String group = service.createSecurityGroup(REGION, "eice-sg", "x", vpcId).getGroupId(); + InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group), + null, null, List.of(), null); + String eniId = endpoint.getNetworkInterfaceIds().get(0); + + NetworkInterface ni = service.describeNetworkInterfaces(REGION, List.of(eniId), Map.of()) + .networkInterfaces().get(0); + assertEquals(eniId, ni.getNetworkInterfaceId()); + assertEquals(subnetId, ni.getSubnetId()); + assertEquals(vpcId, ni.getVpcId()); + assertEquals("us-east-1a", ni.getAvailabilityZone()); + assertEquals(endpoint.getPrivateIpAddress(), ni.getPrivateIpAddress()); + assertEquals(List.of(group), ni.getGroups().stream().map(GroupIdentifier::getGroupId).toList()); + assertEquals(List.of("eice-sg"), ni.getGroups().stream().map(GroupIdentifier::getGroupName).toList()); + assertTrue(ni.isRequesterManaged()); + assertEquals("ec2_instance_connect_endpoint", ni.getInterfaceType()); + assertEquals("EC2 Instance Connect Endpoint " + endpoint.getInstanceConnectEndpointId(), ni.getDescription()); + + // Filters see it the way they see any other interface, and only once. + assertEquals(List.of(eniId), service.describeNetworkInterfaces(REGION, List.of(), + Map.of("subnet-id", List.of(subnetId))).networkInterfaces().stream() + .map(NetworkInterface::getNetworkInterfaceId).toList()); + assertEquals(List.of(eniId), service.describeNetworkInterfaces(REGION, List.of(), + Map.of("interface-type", List.of("ec2_instance_connect_endpoint"), "group-id", List.of(group))) + .networkInterfaces().stream().map(NetworkInterface::getNetworkInterfaceId).toList()); + assertTrue(service.describeNetworkInterfaces(REGION, List.of(), Map.of("subnet-id", List.of(otherSubnet))) + .networkInterfaces().isEmpty()); + + // A tag on the interface is the interface's own and goes with it. + service.createTags(REGION, List.of(eniId), List.of(new Tag("Role", "eice"))); + assertEquals(List.of("Role"), service.describeNetworkInterfaces(REGION, List.of(eniId), Map.of()) + .networkInterfaces().get(0).getTagSet().stream().map(Tag::getKey).toList()); + + service.deleteInstanceConnectEndpoint(REGION, endpoint.getInstanceConnectEndpointId()); + assertTrue(service.describeTags(REGION, Map.of("resource-id", List.of(eniId))).isEmpty()); + assertEquals("InvalidNetworkInterfaceID.NotFound", assertThrows(AwsException.class, () -> service + .describeNetworkInterfaces(REGION, List.of(eniId), Map.of())).getErrorCode()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index 53f317b105..74a302c5d2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -4918,6 +4918,47 @@ class Ec2ServiceTest { false, null, null, null, false, privateIp); } + @Test + void anInstanceConnectEndpointInterfaceNamesItsGroupsForTheAccountItIsReadFor() { + // The explicit-account DescribeNetworkInterfaces overload runs under whatever account the + // ambient request carries; the group names must come from the account named, not that one. + RequestContext context = new RequestContext(); + Ec2Service service = mockedVpcNetworkService(context, Map.of(), null); + context.setAccountId("111122223333"); + String vpcId = service.createVpc("us-east-1", "10.82.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet("us-east-1", vpcId, "10.82.1.0/24", "us-east-1a").getSubnetId(); + String group = service.createSecurityGroup("us-east-1", "eice-sg", "x", vpcId).getGroupId(); + String eniId = service.createInstanceConnectEndpoint("us-east-1", subnetId, List.of(group), null, null, + List.of(), null).getNetworkInterfaceIds().getFirst(); + + context.setAccountId("000000000000"); + NetworkInterface ni = service.describeNetworkInterfaces("111122223333", "us-east-1", List.of(eniId), + Map.of()).networkInterfaces().getFirst(); + assertEquals(List.of(Map.entry(group, "eice-sg")), ni.getGroups().stream() + .map(g -> Map.entry(g.getGroupId(), String.valueOf(g.getGroupName()))).toList()); + } + + @Test + void anotherAccountDoesNotSeeAnInstanceConnectEndpointsInterface() { + RequestContext context = new RequestContext(); + Ec2Service service = mockedVpcNetworkService(context, Map.of(), null); + context.setAccountId("111122223333"); + String vpcId = service.createVpc("us-east-1", "10.83.0.0/16", false).getVpcId(); + String subnetId = service.createSubnet("us-east-1", vpcId, "10.83.1.0/24", "us-east-1a").getSubnetId(); + String eniId = service.createInstanceConnectEndpoint("us-east-1", subnetId, List.of(), null, null, + List.of(), null).getNetworkInterfaceIds().getFirst(); + + context.setAccountId("444455556666"); + assertEquals("InvalidNetworkInterfaceID.NotFound", assertThrows(AwsException.class, () -> service + .describeNetworkInterfaces("us-east-1", List.of(eniId), Map.of())).getErrorCode()); + assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(), Map.of()).networkInterfaces().stream() + .noneMatch(ni -> eniId.equals(ni.getNetworkInterfaceId()))); + + context.setAccountId("111122223333"); + assertEquals(eniId, service.describeNetworkInterfaces("us-east-1", List.of(eniId), Map.of()) + .networkInterfaces().getFirst().getNetworkInterfaceId()); + } + private static Ec2Service realVpcNetworkService(RequestContext context) { return realVpcNetworkService(context, Map.of()); } diff --git a/src/test/java/io/github/hectorvent/floci/testing/Ec2ServiceFixtures.java b/src/test/java/io/github/hectorvent/floci/testing/Ec2ServiceFixtures.java new file mode 100644 index 0000000000..3f1b2c8a50 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/Ec2ServiceFixtures.java @@ -0,0 +1,43 @@ +package io.github.hectorvent.floci.testing; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.ec2.AmiImageResolver; +import io.github.hectorvent.floci.services.ec2.Ec2ContainerManager; +import io.github.hectorvent.floci.services.ec2.Ec2ImageCatalog; +import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * A mock-mode {@link Ec2Service} over in-memory storage for account 000000000000, for unit tests + * that drive the service directly: containers, port forwarding and images are mocks, so nothing + * leaves the JVM. + */ +public final class Ec2ServiceFixtures { + + public static final String ACCOUNT = "000000000000"; + + private Ec2ServiceFixtures() { + } + + public static Ec2Service mockModeService() { + return mockModeService(new InMemoryStorageFactory(ACCOUNT)); + } + + /** Over {@code storage}, for a test that builds a second service on the same stores. */ + public static Ec2Service mockModeService(InMemoryStorageFactory storage) { + EmulatorConfig config = mock(EmulatorConfig.class); + EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); + EmulatorConfig.Ec2ServiceConfig ec2 = mock(EmulatorConfig.Ec2ServiceConfig.class); + when(config.defaultAccountId()).thenReturn(ACCOUNT); + when(config.services()).thenReturn(services); + when(services.ec2()).thenReturn(ec2); + when(ec2.mock()).thenReturn(true); + return new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class), + mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), + storage); + } +}