diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java index 259a6bd970..c1027864d6 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java @@ -969,6 +969,75 @@ class Ec2Tests { @Test @Order(50) + @DisplayName("DescribeVpcEndpoints - an interface endpoint reports its network interfaces") + void describeVpcEndpointsReportsNetworkInterfaceIds() { + // The wire element is networkInterfaceIdSet, and the point of asserting it HERE + // rather than only over raw XML is that this proves the real Java SDK deserializes + // it into networkInterfaceIds(). A response can be well-formed XML and still not + // populate the SDK model -- a wrong element name or nesting fails silently, leaving + // an empty list rather than an error, which is exactly the symptom being fixed. + // OWNS ITS FIXTURES. The shared subnetId and security group this test originally + // used are destroyed before it runs -- @Order(44) deletes the subnet and sets + // subnetId to null, @Order(45) deletes the group -- so it was passing null as a + // subnet id and asserting on groups that no longer existed. Caught in review. + // An ordered suite sharing mutable fixtures makes "what exists here" a function of + // position, so a test placed late has to create what it needs. + String ownSubnetId = null; + String ownGroupId = null; + String endpointId = null; + try { + ownSubnetId = ec2.createSubnet(CreateSubnetRequest.builder() + .vpcId(vpcId).cidrBlock("10.0.90.0/24").availabilityZone("us-east-1a") + .build()).subnet().subnetId(); + ownGroupId = ec2.createSecurityGroup(CreateSecurityGroupRequest.builder() + .groupName("vpce-eni-sdk-test").description("endpoint interface ids") + .vpcId(vpcId).build()).groupId(); + + CreateVpcEndpointResponse created = ec2.createVpcEndpoint( + CreateVpcEndpointRequest.builder() + .vpcId(vpcId) + .serviceName("com.amazonaws.us-east-1.ec2") + .vpcEndpointType(VpcEndpointType.INTERFACE) + .subnetIds(ownSubnetId) + .securityGroupIds(ownGroupId) + .build()); + endpointId = created.vpcEndpoint().vpcEndpointId(); + + // Asserted on the CREATE response and again on DESCRIBE, because Terraform + // reads the ids from one and then re-reads them from the other between plan + // and apply; both renderings have to agree. + assertThat(created.vpcEndpoint().networkInterfaceIds()) + .as("CreateVpcEndpoint response") + .hasSize(1) + .allMatch(id -> id.matches("eni-[0-9a-f]{17}")); + + DescribeVpcEndpointsResponse described = ec2.describeVpcEndpoints( + DescribeVpcEndpointsRequest.builder().vpcEndpointIds(endpointId).build()); + VpcEndpoint ep = described.vpcEndpoints().get(0); + + assertThat(ep.networkInterfaceIds()) + .as("DescribeVpcEndpoints response") + .isEqualTo(created.vpcEndpoint().networkInterfaceIds()); + assertThat(ep.groups()).isNotEmpty(); + assertThat(ep.dnsEntries()).isNotEmpty(); + } finally { + if (endpointId != null) { + ec2.deleteVpcEndpoints(DeleteVpcEndpointsRequest.builder() + .vpcEndpointIds(endpointId).build()); + } + if (ownGroupId != null) { + ec2.deleteSecurityGroup(DeleteSecurityGroupRequest.builder() + .groupId(ownGroupId).build()); + } + if (ownSubnetId != null) { + ec2.deleteSubnet(DeleteSubnetRequest.builder() + .subnetId(ownSubnetId).build()); + } + } + } + + @Test + @Order(51) @DisplayName("DeleteVpc - delete VPC") void deleteVpc() { ec2.deleteVpc(DeleteVpcRequest.builder().vpcId(vpcId).build()); 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 e6edf5ecac..7bcb0302cb 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 @@ -4377,6 +4377,11 @@ public class Ec2QueryHandler { .elem("availabilityZone", ni.getAvailabilityZone()) .elem("description", ni.getDescription()) .elem("ownerId", ni.getOwnerId()) + // AWS emits requesterManaged on every interface, false included -- see the + // DescribeNetworkInterfaces sample response -- and requesterId only where + // there is a requester. floci leaves requesterId unset; see the field's javadoc. + .elem("requesterId", ni.getRequesterId()) + .elem("requesterManaged", ni.isRequesterManaged()) .elem("status", ni.getStatus()) .elem("interfaceType", ni.getInterfaceType()) .elem("macAddress", ni.getMacAddress()) @@ -5609,6 +5614,19 @@ public class Ec2QueryHandler { xml.start("item").elem("groupId", securityGroupId).end("item"); } xml.end("groupSet"); + // AWS reports an interface endpoint's ENIs here, and the Terraform provider + // surfaces them as aws_vpc_endpoint.network_interface_ids. Floci already + // synthesizes those interfaces deterministically for flow-log attribution; until + // now nothing said so on the wire, so the attribute came back empty and + // propagated into every module that feeds it downstream. + List endpointEniIds = service.endpointNetworkInterfaceIds(endpoint); + if (!endpointEniIds.isEmpty()) { + xml.start("networkInterfaceIdSet"); + for (String eniId : endpointEniIds) { + xml.elem("item", eniId); + } + xml.end("networkInterfaceIdSet"); + } List dnsEntries = service.endpointDnsEntries(endpoint); if (!dnsEntries.isEmpty()) { xml.start("dnsEntrySet"); 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 1150c96c7b..29826ae93f 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 @@ -4725,25 +4725,72 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { public List endpointNetworkInterfaces(String region) { List result = new ArrayList<>(); for (VpcEndpoint endpoint : vpcEndpoints.scan(k -> true)) { - if (!region.equals(endpoint.getRegion()) - || !"Interface".equalsIgnoreCase(endpoint.getVpcEndpointType())) { + if (region.equals(endpoint.getRegion())) { + result.addAll(endpointNetworkInterfacesOf(endpoint)); + } + } + return result; + } + + /** + * The interfaces ONE endpoint owns. The region-wide method above is this, looped. + * + *

A distinct NAME rather than an overload of {@code endpointNetworkInterfaces}, + * deliberately: an overload taking VpcEndpoint beside one taking String makes a + * Mockito {@code any()} ambiguous, and {@code FlowLogServiceTest} already stubs + * {@code endpointNetworkInterfaces(any())}. A new method should not make an existing + * test stop compiling. + * + *

Split out so that everything reporting an endpoint's interfaces -- the ids on + * the wire, the objects flow-log attribution reads -- comes from one place and + * cannot disagree. The alternative, deriving ids independently from the same + * {@link #endpointEniId}, looks equivalent and is not: this method skips a subnet + * whose record has gone, and a second derivation that forgot to would report an + * interface the first one denies exists. Congruence by construction beats congruence + * by inspection, and the two had in fact already diverged. + * + *

A Gateway endpoint owns no interfaces and gets an empty list. + */ + private List endpointNetworkInterfacesOf(VpcEndpoint endpoint) { + if (!"Interface".equalsIgnoreCase(endpoint.getVpcEndpointType())) { + return List.of(); + } + String region = endpoint.getRegion(); + List result = new ArrayList<>(); + for (String subnetId : endpoint.getSubnetIds()) { + Subnet subnet = subnets.get(key(region, subnetId)).orElse(null); + if (subnet == null) { continue; } - for (String subnetId : endpoint.getSubnetIds()) { - Subnet subnet = subnets.get(key(region, subnetId)).orElse(null); - if (subnet == null) { - continue; - } - NetworkInterface ni = new NetworkInterface(); - ni.setNetworkInterfaceId(endpointEniId(endpoint.getVpcEndpointId(), subnetId)); - ni.setSubnetId(subnetId); - ni.setVpcId(endpoint.getVpcId()); - ni.setAvailabilityZone(subnet.getAvailabilityZone()); - ni.setDescription("VPC Endpoint Interface " + endpoint.getVpcEndpointId()); - ni.setInterfaceType("vpc_endpoint"); - ni.setPrivateIpAddress(endpointPrivateIp(subnet, endpoint, subnetId)); - result.add(ni); + NetworkInterface ni = new NetworkInterface(); + ni.setNetworkInterfaceId(endpointEniId(endpoint.getVpcEndpointId(), subnetId)); + ni.setSubnetId(subnetId); + ni.setVpcId(endpoint.getVpcId()); + ni.setAvailabilityZone(subnet.getAvailabilityZone()); + ni.setDescription("VPC Endpoint Interface " + endpoint.getVpcEndpointId()); + ni.setInterfaceType("vpc_endpoint"); + // AWS creates an interface endpoint's ENIs on the customer's behalf and reports + // them as requester-managed. Set here, on the one derivation, so that the objects + // flow-log attribution reads and the ones DescribeNetworkInterfaces answers with + // cannot describe the same interface two ways. requesterId is deliberately left + // unset -- see NetworkInterface#requesterId. + ni.setRequesterManaged(true); + // An interface endpoint's security groups are enforced ON its interfaces -- that is + // the whole mechanism by which a PrivateLink endpoint is firewalled -- and AWS reports + // them in each interface's groupSet. Without them DescribeNetworkInterfaces answered + // with an empty groupSet and a group-id filter excluded the very interfaces the group + // is attached to. The name is best-effort: it is cosmetic, the id is what filters and + // rules match on, and the lookup reads the caller's account while FlowLogService runs + // on the default one, so a miss omits the name rather than inventing it. + for (String securityGroupId : endpoint.getSecurityGroupIds()) { + GroupIdentifier group = new GroupIdentifier(); + group.setGroupId(securityGroupId); + securityGroups.get(key(region, securityGroupId)) + .ifPresent(sg -> group.setGroupName(sg.getGroupName())); + ni.getGroups().add(group); } + ni.setPrivateIpAddress(endpointPrivateIp(subnet, endpoint, subnetId)); + result.add(ni); } return result; } @@ -4755,6 +4802,37 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { return "eni-" + hex.substring(0, 17); } + /** + * The network interfaces an interface endpoint owns, by id, in subnet order. + * + *

DescribeVpcEndpoints reports these in {@code networkInterfaceIdSet}, and the + * Terraform AWS provider surfaces them as {@code aws_vpc_endpoint.network_interface_ids}. + * Gruntwork modules feed that output downstream, so an empty list does not merely + * diff -- it propagates into whatever consumes it. + * + *

Mapped over {@link #endpointNetworkInterfacesOf(VpcEndpoint)} rather than derived + * separately, so the ids on the wire come BY CONSTRUCTION from the same derivation + * flow-log attribution uses, and no endpoint can be described two ways. An earlier + * version of this method called {@link #endpointEniId} itself and looked equivalent; + * it was not, because it lacked that method's skip of a subnet whose record has gone, + * and the two were measured reporting different sets after a subnet was deleted out + * from under a live endpoint. + * + *

Shared derivation, not a shared view: {@link FlowLogService} runs on a scheduler + * with no request context and so reads the default account, while this path reads the + * caller's. For a non-default account the flow-log side sees no endpoints at all. + * Each side stays internally consistent, which is the property being claimed here -- + * it is not a claim that both see the same endpoints. A Gateway endpoint has no + * interfaces and gets an empty list, which is what AWS reports for one. + */ + public List endpointNetworkInterfaceIds(VpcEndpoint endpoint) { + List ids = new ArrayList<>(); + for (NetworkInterface ni : endpointNetworkInterfacesOf(endpoint)) { + ids.add(ni.getNetworkInterfaceId()); + } + return ids; + } + /** * The {@code DnsEntries} an interface endpoint reports. The names and zones are synthesized * deterministically rather than persisted, so a restart keeps answering with what the caller @@ -4848,7 +4926,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { String cidr = subnet.getCidrBlock(); String baseIp = cidr != null ? cidr.split("/")[0] : "172.31.0.0"; String[] parts = baseIp.split("\\."); + // A subnet's CidrBlock is not guaranteed to be dotted IPv4. CreateSubnet stores + // whatever it is given without validating the family, and an IPv6-only subnet has + // no IPv4 CIDR at all, so this can be "2001:db8::" or anything else -- one element, + // and parts[1] then throws. That used to surface only on the flow-log scheduler; + // DescribeVpcEndpoints now derives interfaces on the request path, which would turn + // an odd subnet into a failed EC2 response rather than a degraded address. + // Falls back to the same default the null case already uses, so "no usable IPv4" + // has one behaviour rather than two. int host = 200 + Math.floorMod(endpoint.getVpcEndpointId().hashCode(), 50); + if (parts.length < 4) { + // The third octet comes from the SUBNET, not a constant. On the IPv4 path each + // subnet supplies its own distinct network, and that is the only thing making + // one endpoint's interfaces distinct -- the host octet is derived from the + // endpoint and is therefore the same for all of them. A constant fallback threw + // that away and gave every non-IPv4 subnet on an endpoint the same address, + // trading a crash for a silent collision. + return "172.31." + Math.floorMod(subnetId.hashCode(), 256) + "." + host; + } return parts[0] + "." + parts[1] + "." + parts[2] + "." + host; } @@ -8741,6 +8836,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { case "group-id" -> ni.getGroups().stream() .anyMatch(g -> g != null && matchesValue(values, g.getGroupId())); case "status" -> matchesValue(values, ni.getStatus()); + // interface-type is how a caller asks for exactly the endpoint interfaces this + // store now answers with; without an arm here the default below would match + // every interface instead and the filter would read as doing nothing. + case "interface-type" -> matchesValue(values, ni.getInterfaceType()); + case "requester-managed" -> matchesValue(values, String.valueOf(ni.isRequesterManaged())); case "attachment.instance-id" -> ni.getAttachment() != null && matchesValue(values, ni.getAttachment().getInstanceId()); case "private-ip-address" -> @@ -9390,6 +9490,58 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { result.add(ni); } + // The ENIs an interface VPC endpoint owns. DescribeVpcEndpoints publishes these ids in + // networkInterfaceIdSet, so without this arm the same emulator that just handed out an id + // answers InvalidNetworkInterfaceID.NotFound when asked about it. + // + // That is not a cosmetic gap. The Terraform AWS provider's aws_vpc_endpoint read calls + // findSubnetConfigurationsByNetworkInterfaceIDs over EVERY id in network_interface_ids to + // build subnet_configuration, and returns the lookup error rather than tolerating a + // NotFound -- note it handles retry.NotFound for the prefix list a few lines above and + // pointedly does not here. So an unresolvable id fails every interface endpoint read, + // where publishing no ids at all had merely left the list empty. + // + // The ENIs an interface VPC endpoint owns, so that an id DescribeVpcEndpoints published + // resolves instead of answering InvalidNetworkInterfaceID.NotFound. The Terraform AWS + // provider's aws_vpc_endpoint read calls findSubnetConfigurationsByNetworkInterfaceIDs + // over EVERY id in network_interface_ids to build subnet_configuration, and returns the + // lookup error rather than tolerating a NotFound -- note it handles retry.NotFound for + // the prefix list a few lines above and pointedly does not here. So an unresolvable id + // fails every interface endpoint read, where publishing no ids had merely left the list + // empty. + // + // ACCOUNT SCOPING IS ALREADY DONE, TWICE, BY THE STORAGE LAYER -- which is worth stating + // because nothing at this call site shows it, and a reviewer reasonably read it the + // other way. endpointNetworkInterfaces does vpcEndpoints.scan(k -> true), and plain scan + // on an AccountAwareStorageBackend filters to the caller's partition first: the + // k -> true predicate selects every KEY within that account, not every account. The + // subnet lookup inside endpointNetworkInterfacesOf is scoped the same way, so even a + // foreign endpoint would yield no interfaces. Nothing here crosses an account boundary, + // and an id is only ever published to the account that can resolve it. + // + // ownerId therefore comes from callerAccountId(), the account these were actually read + // under, rather than from safeAccount: the explicit-account overload can set safeAccount + // to an account this ambient-scoped arm cannot honour, and labelling a resource with an + // account it did not come from is worse than either showing or hiding it. + String endpointOwnerAccountId = callerAccountId(); + for (NetworkInterface endpointNi : endpointNetworkInterfaces(region)) { + String endpointEniId = endpointNi.getNetworkInterfaceId(); + if (foundIds.contains(endpointEniId)) { + continue; + } + if (!networkInterfaceIds.isEmpty() && !networkInterfaceIds.contains(endpointEniId)) { + continue; + } + // Added before the filter check, matching the arms above: an id that was asked for + // by name and then excluded by a filter is absent from the answer, not NotFound. + foundIds.add(endpointEniId); + endpointNi.setOwnerId(endpointOwnerAccountId); + if (!matchesFilters(endpointNi, filters, region)) { + continue; + } + result.add(endpointNi); + } + // Phase 6: validate requested IDs exist for (String id : networkInterfaceIds) { if (!foundIds.contains(id)) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/NetworkInterface.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/NetworkInterface.java index 08d05ef6c5..e6c302f2ee 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/NetworkInterface.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/NetworkInterface.java @@ -22,6 +22,19 @@ public class NetworkInterface { private boolean sourceDestCheck = true; private String availabilityZone; private String interfaceType = "interface"; + /** + * Whether AWS itself manages this interface, rather than the account it is billed to. + * False for anything a customer created; true for the service-owned interfaces AWS + * creates on the customer's behalf, of which an interface VPC endpoint's is one. + */ + private boolean requesterManaged; + /** + * The alias or account of the principal that created the interface, for a + * requester-managed one. Left null rather than filled with a plausible-looking id: + * real AWS reports an internal service account here, which floci cannot know, and an + * invented twelve-digit account would be a wrong answer rather than a missing one. + */ + private String requesterId; private List groups = new ArrayList<>(); private NetworkInterfaceAttachment attachment; private List tagSet = new ArrayList<>(); @@ -68,6 +81,12 @@ public class NetworkInterface { public String getInterfaceType() { return interfaceType; } public void setInterfaceType(String interfaceType) { this.interfaceType = interfaceType; } + public boolean isRequesterManaged() { return requesterManaged; } + public void setRequesterManaged(boolean requesterManaged) { this.requesterManaged = requesterManaged; } + + public String getRequesterId() { return requesterId; } + public void setRequesterId(String requesterId) { this.requesterId = requesterId; } + public NetworkInterfaceAttachment getAttachment() { return attachment; } public void setAttachment(NetworkInterfaceAttachment attachment) { this.attachment = attachment; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest.java new file mode 100644 index 0000000000..a5d9be39c8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest.java @@ -0,0 +1,254 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.github.hectorvent.floci.services.ec2.model.NetworkInterface; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.everyItem; +import static org.hamcrest.Matchers.matchesPattern; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The {@code networkInterfaceIdSet} an interface endpoint reports. + * + *

AWS creates one elastic network interface per subnet for an interface (PrivateLink) + * endpoint and reports them here. Terraform's {@code aws_vpc_endpoint} surfaces the list as + * {@code network_interface_ids}, and modules feed that output downstream -- to security-group + * rules, to flow-log filters, to DNS -- so an empty list does not merely diff against AWS, it + * propagates into whatever consumes it. + * + *

Floci already synthesized these interfaces: {@code Ec2Service.endpointNetworkInterfaces} + * derives them deterministically from the endpoint's subnets so flow-log generation can + * attribute AWS-service traffic to a stable address. Nothing reported them on the wire, so + * DescribeVpcEndpoints answered with the element absent. + * + *

A Gateway endpoint has no interfaces, and AWS reports none for one; that direction is + * asserted too. Note what that assertion can and cannot catch: it pins that no interface + * ids are REPORTED, not that the element is absent. Dropping the emission guard would + * yield an empty {@code }, whose {@code item} list is also empty, + * and this test would still pass. That is deliberate rather than an oversight -- AWS emits + * the empty element where this omits it, a difference no ec2query SDK can observe, so + * pinning absence would pin the side of that choice further from AWS. + * + * @see DescribeVpcEndpoints + */ +@QuarkusTest +class Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest { + + @Inject + Ec2Service service; + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request"; + + private static final String ENI_IDS = + "DescribeVpcEndpointsResponse.vpcEndpointSet.item.networkInterfaceIdSet.item"; + + private String ec2Value(String action, String element, String... formParams) { + RequestSpecification req = given().formParam("Action", action) + .header("Authorization", AUTH_HEADER); + for (int i = 0; i < formParams.length; i += 2) { + req = req.formParam(formParams[i], formParams[i + 1]); + } + return req.when().post("/").then().statusCode(200).extract().path(element); + } + + private String createVpc(String cidr) { + return ec2Value("CreateVpc", "CreateVpcResponse.vpc.vpcId", "CidrBlock", cidr); + } + + private String createSubnet(String vpcId, String cidr, String availabilityZone) { + return ec2Value("CreateSubnet", "CreateSubnetResponse.subnet.subnetId", + "VpcId", vpcId, "CidrBlock", cidr, "AvailabilityZone", availabilityZone); + } + + private XmlPath describeEndpoint(String endpointId) { + return given() + .formParam("Action", "DescribeVpcEndpoints") + .formParam("VpcEndpointId.1", endpointId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200) + .extract().xmlPath(); + } + + private List eniIdsOf(String endpointId) { + return describeEndpoint(endpointId).getList(ENI_IDS, String.class); + } + + @Test + void anInterfaceEndpointReportsOneNetworkInterfacePerSubnet() { + String vpcId = createVpc("10.74.0.0/16"); + String subnetA = createSubnet(vpcId, "10.74.1.0/24", "us-east-1a"); + String subnetB = createSubnet(vpcId, "10.74.2.0/24", "us-east-1b"); + + String endpointId = ec2Value("CreateVpcEndpoint", + "CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId", + "VpcId", vpcId, "ServiceName", "com.amazonaws.us-east-1.ec2", + "VpcEndpointType", "Interface", "SubnetId.1", subnetA, "SubnetId.2", subnetB); + + List eniIds = eniIdsOf(endpointId); + assertEquals(2, eniIds.size(), "one interface per subnet, got " + eniIds); + assertThat(eniIds, everyItem(matchesPattern("eni-[0-9a-f]{17}"))); + assertNotEquals(eniIds.get(0), eniIds.get(1), + "each subnet gets its own interface, not one shared id"); + + // Stable across calls. The ids are derived, not stored, so a caller that reads them + // twice -- as Terraform does between plan and apply -- must see the same list. + assertEquals(eniIds, eniIdsOf(endpointId)); + } + + @Test + void theWireIdsAreTheInterfacesFlowLogAttributionReads() { + // THE PROPERTY THE DESIGN RESTS ON, and the one the other tests do not reach. + // They pin count, shape, distinctness and stability -- all of which an + // implementation deriving ids from the subnet id alone would satisfy while + // reporting interfaces that endpointNetworkInterfaces() denies exist. That is + // not hypothetical: an earlier version of endpointNetworkInterfaceIds called + // endpointEniId itself, lacked this method's skip of a vanished subnet, and the + // two were measured reporting different sets after a subnet was deleted out from + // under a live endpoint. Flow-log attribution reads the service side; Terraform + // reads the wire side; they have to be the same list. + String vpcId = createVpc("10.77.0.0/16"); + String subnetA = createSubnet(vpcId, "10.77.1.0/24", "us-east-1a"); + String subnetB = createSubnet(vpcId, "10.77.2.0/24", "us-east-1b"); + + String endpointId = ec2Value("CreateVpcEndpoint", + "CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId", + "VpcId", vpcId, "ServiceName", "com.amazonaws.us-east-1.ec2", + "VpcEndpointType", "Interface", "SubnetId.1", subnetA, "SubnetId.2", subnetB); + + // DELETE A SUBNET OUT FROM UNDER THE LIVE ENDPOINT. Without this the test is + // decorative: both derivations agree whenever every subnet still exists, so a + // version that skipped the vanished-subnet filter passed this assertion happily. + // Measured -- the first draft of this test did exactly that. Real AWS answers + // DependencyViolation here and Terraform's graph destroys the endpoint first, so + // the state is reachable only in an emulator; that is precisely why the emulator + // has to stay self-consistent in it rather than report two different answers. + ec2Value("DeleteSubnet", "DeleteSubnetResponse.return", "SubnetId", subnetB); + + List onTheWire = eniIdsOf(endpointId); + + // Scoped to THIS endpoint: the region-wide overload returns every endpoint's + // interfaces, and other tests in this class leave their own behind. + List fromTheService = new ArrayList<>(); + for (NetworkInterface ni : service.endpointNetworkInterfaces("us-east-1")) { + if (("VPC Endpoint Interface " + endpointId).equals(ni.getDescription())) { + fromTheService.add(ni.getNetworkInterfaceId()); + } + } + + assertEquals(fromTheService, onTheWire, + "the ids DescribeVpcEndpoints publishes must be the interfaces the " + + "service reports, in the same order"); + assertEquals(1, onTheWire.size(), + "the endpoint has one surviving subnet, so it reports one interface"); + } + + @Test + void anEndpointOnASubnetWithoutIpv4StillAnswers() { + // REGRESSION GUARD for the request path this change created. Deriving the + // interfaces now happens while rendering CreateVpcEndpoint and + // DescribeVpcEndpoints, and that derivation computes a private IP by splitting + // the subnet's CidrBlock on dots. CreateSubnet stores whatever CidrBlock it is + // given without validating the family, so the value is not guaranteed to be + // dotted IPv4 -- and before the guard, parts[1] threw, turning an odd subnet into + // a FAILED EC2 response instead of a degraded address. Previously the same + // calculation ran only on the flow-log scheduler, where a throw was contained. + String vpcId = createVpc("10.78.0.0/16"); + String subnetId = ec2Value("CreateSubnet", "CreateSubnetResponse.subnet.subnetId", + "VpcId", vpcId, "CidrBlock", "2001:db8::/56", + "AvailabilityZone", "us-east-1a"); + + String endpointId = ec2Value("CreateVpcEndpoint", + "CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId", + "VpcId", vpcId, "ServiceName", "com.amazonaws.us-east-1.ec2", + "VpcEndpointType", "Interface", "SubnetId.1", subnetId); + + // The assertion is that we get an ANSWER at all: every ec2Value above already + // requires statusCode 200, so a throw in the rendering path fails this test at + // CreateVpcEndpoint. Describe is exercised too, because it renders by the same + // path and is the call Terraform makes between plan and apply. + assertEquals(1, eniIdsOf(endpointId).size(), + "one subnet, so one interface, whatever family its CIDR is"); + } + + @Test + void twoSubnetsWithoutIpv4GetDistinctAddresses() { + // The first fix for the non-IPv4 crash used a CONSTANT fallback network, which + // turned a crash into a silent collision: the host octet is derived from the + // ENDPOINT, so it is identical across that endpoint's interfaces, and on the IPv4 + // path the only thing making them distinct is each subnet's own network. Collapse + // the network to a constant and every non-IPv4 subnet gets the same address. + // Caught in review, not by the test above, which uses a single subnet and so + // cannot see a collision at all. + String vpcId = createVpc("10.79.0.0/16"); + String subnetA = ec2Value("CreateSubnet", "CreateSubnetResponse.subnet.subnetId", + "VpcId", vpcId, "CidrBlock", "2001:db8:1::/64", + "AvailabilityZone", "us-east-1a"); + String subnetB = ec2Value("CreateSubnet", "CreateSubnetResponse.subnet.subnetId", + "VpcId", vpcId, "CidrBlock", "2001:db8:2::/64", + "AvailabilityZone", "us-east-1b"); + + String endpointId = ec2Value("CreateVpcEndpoint", + "CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId", + "VpcId", vpcId, "ServiceName", "com.amazonaws.us-east-1.ec2", + "VpcEndpointType", "Interface", + "SubnetId.1", subnetA, "SubnetId.2", subnetB); + + List addresses = new ArrayList<>(); + for (NetworkInterface ni : service.endpointNetworkInterfaces("us-east-1")) { + if (("VPC Endpoint Interface " + endpointId).equals(ni.getDescription())) { + addresses.add(ni.getPrivateIpAddress()); + } + } + + assertEquals(2, addresses.size(), "one interface per subnet"); + assertNotEquals(addresses.get(0), addresses.get(1), + "each subnet's interface needs its own address, got " + addresses); + // And the ids stay distinct too, which they already were -- endpointEniId mixes the + // subnet in. Asserted so a future change cannot fix one and break the other. + assertEquals(2, eniIdsOf(endpointId).size()); + } + + @Test + void aGatewayEndpointReportsNoNetworkInterfaces() { + String vpcId = createVpc("10.75.0.0/16"); + String routeTableId = ec2Value("CreateRouteTable", + "CreateRouteTableResponse.routeTable.routeTableId", "VpcId", vpcId); + + String endpointId = ec2Value("CreateVpcEndpoint", + "CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId", + "VpcId", vpcId, "ServiceName", "com.amazonaws.us-east-1.s3", + "VpcEndpointType", "Gateway", "RouteTableId.1", routeTableId); + + // A gateway endpoint is a route-table entry, not an ENI. This is a regression guard + // on that, not a discriminator for the emission change: see the class javadoc for + // why an empty element and an absent one are indistinguishable here. + assertTrue(eniIdsOf(endpointId).isEmpty(), + "a gateway endpoint owns no interfaces"); + } + + @Test + void anInterfaceEndpointInOneSubnetReportsExactlyOneInterface() { + String vpcId = createVpc("10.76.0.0/16"); + String subnetId = createSubnet(vpcId, "10.76.1.0/24", "us-east-1a"); + + String endpointId = ec2Value("CreateVpcEndpoint", + "CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId", + "VpcId", vpcId, "ServiceName", "com.amazonaws.us-east-1.ecr.api", + "VpcEndpointType", "Interface", "SubnetId.1", subnetId); + + assertEquals(1, eniIdsOf(endpointId).size()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointNetworkInterfaceLookupIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointNetworkInterfaceLookupIntegrationTest.java new file mode 100644 index 0000000000..0903e2b44d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointNetworkInterfaceLookupIntegrationTest.java @@ -0,0 +1,358 @@ +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.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * An interface endpoint's network interfaces must RESOLVE, not merely be named. + * + *

DescribeVpcEndpoints publishes one ENI id per subnet in {@code networkInterfaceIdSet}. + * Until this change DescribeNetworkInterfaces enumerated instance-attached interfaces and the + * standalone {@code CreateNetworkInterface} store only, never + * {@code Ec2Service.endpointNetworkInterfaces}, so asking about a published id got + * {@code InvalidNetworkInterfaceID.NotFound} from the same emulator that had just handed it + * over. + * + *

THE BLAST RADIUS IS NOT "callers who look up an ENI". The Terraform AWS provider does the + * lookup ITSELF, inside its own read of {@code aws_vpc_endpoint}: + * {@code resourceVPCEndpointFlatten} calls + * {@code findSubnetConfigurationsByNetworkInterfaceIDs(ctx, conn, vpce.NetworkInterfaceIds)} over + * every published id to build {@code subnet_configuration}, and returns the lookup error rather + * than tolerating a NotFound -- it handles {@code retry.NotFound} for the prefix list a few lines + * above and pointedly does not here. So publishing ids that do not resolve makes every interface + * endpoint read FAIL, where publishing none had merely left the list empty. Reported as blocking + * on floci-io/floci#4598. + * + *

The round-trip test below walks exactly that path -- read the ids off a DescribeVpcEndpoints + * response, then describe each one -- because that is the call sequence that breaks, and a test + * that only asked about an id it derived itself would not pin the two sides together. + * + * @see DescribeNetworkInterfaces + * @see Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest + */ +@QuarkusTest +class Ec2VpcEndpointNetworkInterfaceLookupIntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request"; + + private static final String ENI_IDS = + "DescribeVpcEndpointsResponse.vpcEndpointSet.item.networkInterfaceIdSet.item"; + private static final String NI_SET = + "DescribeNetworkInterfacesResponse.networkInterfaceSet.item"; + + private static final String AUTH_ACCOUNT_2 = + "AWS4-HMAC-SHA256 Credential=000000000002/20260205/us-east-1/ec2/aws4_request"; + + private RequestSpecification ec2As(String auth, String action, String... formParams) { + RequestSpecification req = given().formParam("Action", action) + .header("Authorization", auth); + for (int i = 0; i < formParams.length; i += 2) { + req = req.formParam(formParams[i], formParams[i + 1]); + } + return req; + } + + private RequestSpecification ec2(String action, String... formParams) { + RequestSpecification req = given().formParam("Action", action) + .header("Authorization", AUTH_HEADER); + for (int i = 0; i < formParams.length; i += 2) { + req = req.formParam(formParams[i], formParams[i + 1]); + } + return req; + } + + private String ec2Value(String action, String element, String... formParams) { + return ec2(action, formParams).when().post("/").then().statusCode(200).extract().path(element); + } + + private XmlPath ec2Xml(String action, String... formParams) { + return ec2(action, formParams).when().post("/").then().statusCode(200).extract().xmlPath(); + } + + /** An interface endpoint across the given subnets, and the ids it publishes. */ + private String createInterfaceEndpoint(String vpcId, String... subnetIds) { + String[] params = new String[6 + subnetIds.length * 2]; + params[0] = "VpcId"; + params[1] = vpcId; + params[2] = "ServiceName"; + params[3] = "com.amazonaws.us-east-1.ec2"; + params[4] = "VpcEndpointType"; + params[5] = "Interface"; + for (int i = 0; i < subnetIds.length; i++) { + params[6 + i * 2] = "SubnetId." + (i + 1); + params[7 + i * 2] = subnetIds[i]; + } + return ec2Value("CreateVpcEndpoint", + "CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId", params); + } + + private String createVpc(String cidr) { + return ec2Value("CreateVpc", "CreateVpcResponse.vpc.vpcId", "CidrBlock", cidr); + } + + private String createSubnet(String vpcId, String cidr, String az) { + return ec2Value("CreateSubnet", "CreateSubnetResponse.subnet.subnetId", + "VpcId", vpcId, "CidrBlock", cidr, "AvailabilityZone", az); + } + + private List publishedEniIds(String endpointId) { + return ec2Xml("DescribeVpcEndpoints", "VpcEndpointId.1", endpointId) + .getList(ENI_IDS, String.class); + } + + @Test + void anEndpointInterfaceResolvesWhenAskedForById() { + // THE MINIMUM THE MAINTAINER ASKED FOR: read an id back. Before the change this call + // answered 400 InvalidNetworkInterfaceID.NotFound. + String vpcId = createVpc("10.84.0.0/16"); + String subnetId = createSubnet(vpcId, "10.84.1.0/24", "us-east-1a"); + String endpointId = createInterfaceEndpoint(vpcId, subnetId); + + List published = publishedEniIds(endpointId); + assertEquals(1, published.size(), "one subnet, so one published id"); + String eniId = published.get(0); + + XmlPath answer = ec2Xml("DescribeNetworkInterfaces", "NetworkInterfaceId.1", eniId); + assertEquals(List.of(eniId), answer.getList(NI_SET + ".networkInterfaceId", String.class)); + assertEquals(subnetId, answer.getString(NI_SET + ".subnetId")); + assertEquals(vpcId, answer.getString(NI_SET + ".vpcId")); + } + + @Test + void theProviderRoundTripResolvesEveryPublishedId() { + // The provider's own sequence: read network_interface_ids off the endpoint, then look up + // each one to build subnet_configuration. It reads PrivateIpAddress, Ipv6Address and + // SubnetId off each answer, so an interface that resolves but carries no subnet would + // still leave the provider with a subnet_configuration entry naming nothing. + String vpcId = createVpc("10.85.0.0/16"); + String subnetA = createSubnet(vpcId, "10.85.1.0/24", "us-east-1a"); + String subnetB = createSubnet(vpcId, "10.85.2.0/24", "us-east-1b"); + String endpointId = createInterfaceEndpoint(vpcId, subnetA, subnetB); + + List published = publishedEniIds(endpointId); + assertEquals(2, published.size(), "one interface per subnet, got " + published); + + for (String eniId : published) { + XmlPath answer = ec2Xml("DescribeNetworkInterfaces", "NetworkInterfaceId.1", eniId); + assertEquals(eniId, answer.getString(NI_SET + ".networkInterfaceId"), + "a published id must describe as itself"); + String subnetId = answer.getString(NI_SET + ".subnetId"); + assertTrue(subnetA.equals(subnetId) || subnetB.equals(subnetId), + "the interface must name one of the endpoint's subnets, got " + subnetId); + assertFalse(answer.getString(NI_SET + ".privateIpAddress").isEmpty(), + "subnet_configuration is built from the private address, which must be there"); + } + + // AND ALL AT ONCE, which is the form the provider's loop amounts to: no id in the batch + // may be the one that throws. + XmlPath both = ec2Xml("DescribeNetworkInterfaces", + "NetworkInterfaceId.1", published.get(0), + "NetworkInterfaceId.2", published.get(1)); + assertEquals(published, both.getList(NI_SET + ".networkInterfaceId", String.class)); + } + + @Test + void anEndpointInterfaceIsListedWithNoFilter() { + String vpcId = createVpc("10.86.0.0/16"); + String subnetId = createSubnet(vpcId, "10.86.1.0/24", "us-east-1a"); + String endpointId = createInterfaceEndpoint(vpcId, subnetId); + String eniId = publishedEniIds(endpointId).get(0); + + // Asserted by membership, not by count: this class shares its Quarkus application with + // every other EC2 test, so the unfiltered list holds whatever they left behind. + List all = ec2Xml("DescribeNetworkInterfaces") + .getList(NI_SET + ".networkInterfaceId", String.class); + assertThat(all, hasItem(eniId)); + } + + @Test + void theWireShapeIsAnAwsManagedVpcEndpointInterface() { + String vpcId = createVpc("10.87.0.0/16"); + String subnetId = createSubnet(vpcId, "10.87.1.0/24", "us-east-1c"); + String endpointId = createInterfaceEndpoint(vpcId, subnetId); + String eniId = publishedEniIds(endpointId).get(0); + + XmlPath answer = ec2Xml("DescribeNetworkInterfaces", "NetworkInterfaceId.1", eniId); + assertEquals("vpc_endpoint", answer.getString(NI_SET + ".interfaceType"), + "the documented interfaceType for an interface endpoint's ENI"); + assertEquals("true", answer.getString(NI_SET + ".requesterManaged"), + "AWS creates these on the customer's behalf and reports them as requester-managed"); + assertEquals("in-use", answer.getString(NI_SET + ".status")); + assertEquals("us-east-1c", answer.getString(NI_SET + ".availabilityZone")); + assertEquals("VPC Endpoint Interface " + endpointId, + answer.getString(NI_SET + ".description")); + } + + @Test + void anEndpointInterfaceCarriesTheEndpointsSecurityGroups() { + // The security groups on an interface endpoint are enforced on its INTERFACES, so AWS + // reports them in each interface's groupSet. Without them the groupSet came back empty + // and a group-id filter excluded the very interfaces the group is attached to -- which + // is asserted here too, because the empty-groupSet bug would satisfy the first half + // alone. + String vpcId = createVpc("10.89.0.0/16"); + String subnetId = createSubnet(vpcId, "10.89.1.0/24", "us-east-1a"); + String sgId = ec2Value("CreateSecurityGroup", "CreateSecurityGroupResponse.groupId", + "GroupName", "vpce-eni-sg", "GroupDescription", "endpoint sg", "VpcId", vpcId); + + String endpointId = ec2Value("CreateVpcEndpoint", + "CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId", + "VpcId", vpcId, "ServiceName", "com.amazonaws.us-east-1.ec2", + "VpcEndpointType", "Interface", "SubnetId.1", subnetId, + "SecurityGroupId.1", sgId); + String eniId = publishedEniIds(endpointId).get(0); + + XmlPath answer = ec2Xml("DescribeNetworkInterfaces", "NetworkInterfaceId.1", eniId); + assertEquals(List.of(sgId), + answer.getList(NI_SET + ".groupSet.item.groupId", String.class), + "the interface carries the endpoint's security group"); + assertEquals("vpce-eni-sg", answer.getString(NI_SET + ".groupSet.item.groupName")); + + // And the filter that group id is for actually selects it. + assertThat(filteredIds("group-id", sgId), hasItem(eniId)); + } + + @Test + void anEndpointInterfaceReportsItsOwnAccountAsOwner() { + // Not the caller's account merely because the caller asked. The two coincide here -- + // one account in this test app -- so what this pins is that ownerId is populated from + // the endpoint's owner at all, and is a live account id rather than blank. + String vpcId = createVpc("10.90.0.0/16"); + String subnetId = createSubnet(vpcId, "10.90.1.0/24", "us-east-1a"); + String endpointId = createInterfaceEndpoint(vpcId, subnetId); + String eniId = publishedEniIds(endpointId).get(0); + + String ownerId = ec2Xml("DescribeNetworkInterfaces", "NetworkInterfaceId.1", eniId) + .getString(NI_SET + ".ownerId"); + assertThat(ownerId, matchesPattern("[0-9]{12}")); + + // The VPC the endpoint sits in is owned by the same account, and that is the account + // the interface must name. + String vpcOwner = ec2Xml("DescribeVpcs", "VpcId.1", vpcId) + .getString("DescribeVpcsResponse.vpcSet.item.ownerId"); + assertEquals(vpcOwner, ownerId, + "the interface reports the account that owns the endpoint"); + } + + @Test + void filtersSelectEndpointInterfaces() { + String vpcId = createVpc("10.88.0.0/16"); + String subnetA = createSubnet(vpcId, "10.88.1.0/24", "us-east-1a"); + String subnetB = createSubnet(vpcId, "10.88.2.0/24", "us-east-1b"); + String endpointId = createInterfaceEndpoint(vpcId, subnetA, subnetB); + List published = publishedEniIds(endpointId); + + // vpc-id: exactly this endpoint's two interfaces live in this brand-new VPC. + assertEquals(published, filteredIds("vpc-id", vpcId)); + + // subnet-id: one each. + assertEquals(1, filteredIds("subnet-id", subnetA).size()); + assertEquals(1, filteredIds("subnet-id", subnetB).size()); + assertThat(filteredIds("subnet-id", subnetA), hasItem(published.get(0))); + + // interface-type: scoped to this VPC so other tests' endpoints do not enter the + // assertion, and paired with its negative -- an arm returning true for everything + // would satisfy the positive alone. + assertThat(filteredIds("vpc-id", vpcId, "interface-type", "vpc_endpoint"), + hasItem(published.get(0))); + assertThat(filteredIds("vpc-id", vpcId, "interface-type", "interface"), + not(hasItem(published.get(0)))); + + // requester-managed, the same way. Asserted as equality rather than with everyItem, + // which an empty answer would satisfy vacuously -- and an empty answer is exactly the + // failure mode being guarded against. + assertEquals(published, filteredIds("vpc-id", vpcId, "requester-managed", "true")); + assertTrue(filteredIds("vpc-id", vpcId, "requester-managed", "false").isEmpty(), + "nothing in this VPC is customer-managed"); + } + + @Test + void anotherAccountsEndpointInterfacesAreInvisible() { + // A CHARACTERIZATION TEST, and honest about it: it passes both with and without an + // explicit account filter in the describe arm, because the scoping it observes is done + // twice over in the storage layer and neither copy is visible at the call site. + // endpointNetworkInterfaces does vpcEndpoints.scan(k -> true) -- which reads as "every + // endpoint" and means "every endpoint of the calling account", since + // AccountAwareStorageBackend.scan filters to the caller's partition before the predicate + // ever runs -- and the subnet lookup inside endpointNetworkInterfacesOf is scoped the + // same way, so a foreign endpoint would yield no interfaces even if it were reached. + // Measured: removing an account filter from the describe arm does not fail this test. + // + // It is kept because it pins the BEHAVIOUR rather than the mechanism. A reviewer read + // the k -> true as cross-account and concluded this code leaked; the answer to that is + // an executable demonstration that it does not, positioned to fail if a future change + // to either scoping layer makes it start. + String vpcId = createVpc("10.91.0.0/16"); + String subnetId = createSubnet(vpcId, "10.91.1.0/24", "us-east-1a"); + String endpointId = createInterfaceEndpoint(vpcId, subnetId); + String eniId = publishedEniIds(endpointId).get(0); + + // Account 2 is not handed the endpoint at all. + ec2As(AUTH_ACCOUNT_2, "DescribeVpcEndpoints", "VpcEndpointId.1", endpointId) + .when().post("/") + .then().statusCode(400); + + // ... so it must not resolve the interface either. Consistent, not merely restrictive: + // an id this caller was never given is an id that does not exist for it. + ec2As(AUTH_ACCOUNT_2, "DescribeNetworkInterfaces", "NetworkInterfaceId.1", eniId) + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidNetworkInterfaceID.NotFound")); + + // ... nor enumerate it. + List account2List = ec2As(AUTH_ACCOUNT_2, "DescribeNetworkInterfaces") + .when().post("/").then().statusCode(200).extract().xmlPath() + .getList(NI_SET + ".networkInterfaceId", String.class); + assertThat("account 2 must not enumerate account 1's endpoint interfaces", + account2List, not(hasItem(eniId))); + + // The owning account still sees its own, by id and in the list. Without this the test + // would pass equally against a build that had simply stopped reporting endpoint + // interfaces to anyone. + assertEquals(eniId, ec2Xml("DescribeNetworkInterfaces", "NetworkInterfaceId.1", eniId) + .getString(NI_SET + ".networkInterfaceId")); + assertThat(ec2Xml("DescribeNetworkInterfaces") + .getList(NI_SET + ".networkInterfaceId", String.class), + hasItem(eniId)); + } + + @Test + void anIdThatWasNeverPublishedStillDoesNotExist() { + // GUARD on the validation sweep. Teaching the lookup about endpoint interfaces must not + // turn InvalidNetworkInterfaceID.NotFound into something that never fires -- a store + // that resolves everything is as wrong as one that resolves nothing, and the tests above + // would pass against it. + ec2("DescribeNetworkInterfaces", "NetworkInterfaceId.1", "eni-00000000000000000") + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidNetworkInterfaceID.NotFound")); + } + + private List filteredIds(String... nameValuePairs) { + String[] params = new String[nameValuePairs.length * 2]; + for (int i = 0; i < nameValuePairs.length; i += 2) { + int n = i / 2 + 1; + params[i * 2] = "Filter." + n + ".Name"; + params[i * 2 + 1] = nameValuePairs[i]; + params[i * 2 + 2] = "Filter." + n + ".Value.1"; + params[i * 2 + 3] = nameValuePairs[i + 1]; + } + return ec2Xml("DescribeNetworkInterfaces", params) + .getList(NI_SET + ".networkInterfaceId", String.class); + } +}