fix(ec2): an interface VPC endpoint reports its network interfaces, and they resolve (#4598)

* fix(ec2): report an interface VPC endpoint's network interfaces

DescribeVpcEndpoints never emitted networkInterfaceIdSet, so an interface (PrivateLink)
endpoint came back with no interfaces at all. Terraform's aws_vpc_endpoint surfaces that
element as network_interface_ids, and modules feed the output downstream to
security-group rules, flow-log filters and DNS, so the empty list does not merely differ
from AWS: it propagates into whatever consumes it.

The interfaces already existed. Ec2Service.endpointNetworkInterfaces derives one per
subnet deterministically, with a stable id, the subnet's availability zone and
interfaceType vpc_endpoint, so flow-log generation can attribute AWS-service traffic to a
stable endpoint address. Nothing reported them on the wire.

So this adds a reader rather than a new resource. endpointNetworkInterfaceIds returns the
same ids that endpointNetworkInterfaces synthesizes, reusing endpointEniId, deliberately
derived instead of stored: a second, stored copy could disagree with the one flow-log
attribution reads, and then two answers would exist for one question. It mirrors the
existing endpointDnsEntries accessor, which the same XML writer already calls.

A Gateway endpoint is a route-table entry and owns no interfaces. AWS reports none for
one, and so does this: the element is omitted rather than emitted empty.

Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest covers one interface per subnet with
distinct ids, the ids being stable across two DescribeVpcEndpoints calls (Terraform reads
them between plan and apply), a single-subnet endpoint reporting exactly one, and a
gateway endpoint reporting none. That last case is what stops a change that simply
emitted the set unconditionally from passing.

Verified by reverting the emission alone: 2 of the 3 tests fail, and the gateway case
correctly still passes. Restored, all 3 pass.

Ec2*Test is 1246 tests with 2 failures, both in Ec2VolumeBlockDeviceDockerIntegrationTest
(Docker block devices, mke2fs). Measured on a clean checkout of upstream/main with these
changes removed: the same 2 fail. Pre-existing and environment-specific, not from this
change.

* fix(ec2): reattach the DnsEntries javadoc to its own method

The previous commit inserted endpointNetworkInterfaceIds and its javadoc between the
endpointDnsEntries javadoc and endpointDnsEntries itself. Java binds a doc comment to the
next declaration, so that left two consecutive blocks on the new method -- the first
dangling, the second the real one -- and endpointDnsEntries documented by nothing.

Moving the new method above the DnsEntries javadoc restores that binding and puts the
accessor next to endpointEniId, the helper whose ids it returns. Comment placement only;
no behaviour changes.

Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest: 3 tests, 0 failures.

* refactor(ec2): derive endpoint ENI ids from the interfaces, not beside them

Review found that the javadoc on endpointNetworkInterfaceIds asserted an invariant the
code did not have. It said the ids were derived from endpointNetworkInterfaces so a
second copy could not disagree with what flow-log attribution reads. They were not
derived from it: both called endpointEniId independently, and they filtered differently.
endpointNetworkInterfaces skips a subnet whose record has gone; the id method emitted one
for every entry of getSubnetIds() unconditionally.

The gap is reachable. deleteSubnet checks only for transit-gateway attachments, so
nothing stops a subnet being deleted out from under a live endpoint, and the two were
then measured reporting different sets -- two answers to one question, with flow-log
attribution reading the shorter. Real AWS answers DependencyViolation to that delete and
Terraform's graph destroys the endpoint first, so the state is reachable only in an
emulator. That is the argument for the emulator staying self-consistent in it, not
against.

Extracts endpointNetworkInterfacesOf(VpcEndpoint). The region-wide
endpointNetworkInterfaces(String) is now that method looped, and the id list is mapped
over it, so one copy of the subnet-existence filter serves both and congruence holds by
construction rather than by inspection.

A distinct NAME rather than an overload: endpointNetworkInterfaces(VpcEndpoint) beside
endpointNetworkInterfaces(String) makes a Mockito any() ambiguous, and
FlowLogServiceTest:31 already uses one. Caught by the compiler; a new method should not
make an existing test stop compiling.

Incidental saving: vpcEndpointXml called the region-wide scan once per endpoint in a
response, so DescribeVpcEndpoints was quadratic in subnet lookups. It no longer is.

THE TEST WAS DECORATIVE UNTIL IT WAS MEASURED. Its first draft compared the wire ids to
the service's list for an endpoint whose subnets all still existed -- a case where both
derivations trivially agree, and it passed against the buggy version. It now deletes a
subnet out from under the endpoint first. Verified both ways: it FAILS on the old
independent derivation and PASSES on this one.

Ec2VpcEndpoint*, FlowLogServiceTest, Ec2ServiceTest and Ec2NetworkInterfaceIntegrationTest:
1251 tests, the only failures being Ec2VolumeBlockDeviceDockerIntegrationTest's known 2
of 8 (Docker block devices, mke2fs), measured identically on a clean upstream/main
checkout.

Not addressed here, filed separately: the ids this publishes do not resolve through
DescribeNetworkInterfaces, which never consults endpointNetworkInterfaces. Real AWS
returns endpoint ENIs there as requester-managed with interfaceType vpc_endpoint. That
gap predates this branch; publishing ids makes it visible rather than creating it, and no
corpus module looks one up today.

* docs(ec2): narrow the congruence claim to what the code actually guarantees

Three findings from review of #21, none behavioural.

The javadoc said the wire ids are BY CONSTRUCTION "the interfaces flow-log attribution
reads". Within one account that is exact -- vpcEndpoints.scan and subnets.get share a
prefix and both stores are account-wrapped. But FlowLogService runs on a scheduler with
no request context, so it 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 the refactor established and the one worth
claiming. Both seeing the same endpoints is not, and the absolute phrasing claimed it.
Restated as shared derivation rather than shared view.

endpointNetworkInterfacesOf was public with no caller outside the class -- not in
Ec2QueryHandler, which calls endpointNetworkInterfaceIds, and not in any test. Every
sibling helper in the same block is private (endpointEniId, endpointDnsDiscriminator,
endpointServiceToken, endpointPrivateIp), so public was the outlier. Now private. The
javadoc's argument for the distinct NAME stands untouched; that was about the Mockito
ambiguity, not the visibility.

The same javadoc cited FlowLogServiceTest:31 for that ambiguity. The line is 44 on this
base, and a comment carrying a line number is wrong again at the next rebase, so it now
names the stub instead.

Also drops a stray backslash in "method\'s" that survived from the heredoc the comment
was written in.

* test(ec2): say what the gateway case actually catches, which is less than claimed

The class javadoc and the PR description both said the gateway assertion is "what stops a
change that simply emitted the set unconditionally from passing". It is not. The emission
is guarded by `if (!endpointEniIds.isEmpty())`; remove that guard and a gateway endpoint
gets an empty `<networkInterfaceIdSet/>`, whose `item` list is empty, so
`eniIdsOf(...).isEmpty()` still holds and the test still passes.

Found by review of #21. Third claim on this branch that asserted more than the code
delivered -- after the javadoc that claimed a congruence invariant the code lacked, and
the one that claimed both sides see the same endpoints across accounts.

Not fixed by tightening the assertion to pin absence, which was the obvious move and the
wrong one: real AWS emits the empty element where this omits it. Absent and empty are
indistinguishable to any ec2query SDK, and Terraform's TypeSet lands both as an empty set,
so the behaviour is fine -- but an assertion pinning absence would pin the side of that
choice further from AWS, and make a later move toward AWS look like a regression.

So the comment now states the limit instead. The case still earns its place as a
regression guard: a gateway endpoint must never report interface ids.

Also orders the new test's imports like the sibling SubnetConfiguration suite.

* fix(ec2): an endpoint on a subnet whose CIDR is not dotted IPv4 must still answer

Both findings from the Greptile review of #4598.

P1. endpointPrivateIp splits the subnet's CidrBlock on dots and reads parts[1] and
parts[2]. CreateSubnet calls setCidrBlock with whatever it was given and never validates
the address family, so the value is not guaranteed to be dotted IPv4 -- "2001:db8::/56"
splits to one element and parts[1] throws.

This PR is what makes that reachable from a request. Deriving an endpoint's interfaces
used to happen only on the flow-log scheduler, where a throw was contained; it now also
happens while rendering CreateVpcEndpoint and DescribeVpcEndpoints, so the same odd subnet
turns into a failed EC2 response rather than a degraded address. Measured, with the guard
removed:

  Unhandled error dispatching Query action CreateVpcEndpoint for service ec2:
  java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1

Falls back to the same default the existing null-CidrBlock branch already uses, so "no
usable IPv4" has one behaviour instead of two. Deliberately NOT fixed by validating in
CreateSubnet: rejecting a non-IPv4 CidrBlock is what AWS does and is probably right, but
it is a behaviour change with a wider blast radius than this PR should carry, and it would
not help an IPv6-only subnet, which legitimately has no IPv4 CIDR at all.

anEndpointOnASubnetWithoutIpv4StillAnswers is a regression guard and states so. Measured
both ways: it FAILS at CreateVpcEndpoint without the guard and PASSES with it. Reviewer
found the defect by reading; the test is what keeps it found.

P2. Import order -- io.restassured sorts before jakarta. I reordered the first two imports
in an earlier commit and did not notice the same rule applied further down the block.

Ec2VpcEndpoint* and FlowLogServiceTest: 52 tests, 0 failures.

* fix(ec2): the non-IPv4 fallback gave every subnet on an endpoint the same address

Second Greptile round on #4598, and a defect introduced by the fix for the first.

The crash fix fell back to a CONSTANT network, 172.31.0.0. The host octet is derived from
the ENDPOINT, so it is identical across that endpoint's interfaces; on the IPv4 path the
only thing making them distinct is each subnet supplying its own network. Collapsing the
network to a constant threw that away, so every non-IPv4 subnet on one endpoint got the
same private address -- a crash traded for a silent collision. Measured:

  got [172.31.0.249, 172.31.0.249]

The third octet now comes from the subnet id, restoring the property the IPv4 path has by
construction rather than by luck. The ENI ids were never affected -- endpointEniId already
mixes the subnet in -- and the new test asserts both, so a later change cannot fix one and
break the other.

twoSubnetsWithoutIpv4GetDistinctAddresses measured both ways: it FAILS on the constant
fallback with the collision above and PASSES with the subnet-derived one. The existing
non-IPv4 test could not have caught this: it uses a single subnet, where a collision has
nothing to collide with.

Ec2VpcEndpoint*, FlowLogServiceTest, Ec2ServiceTest, Ec2NetworkInterfaceIntegrationTest:
264 tests, 0 failures.

* test(compat): validate the endpoint's network interface ids through the Java SDK

Greptile's P2 on #4598. The integration test asserts the wire element over RestAssured,
which is deliberate -- an absent networkInterfaceIdSet and an empty one are different
things and only raw XML can tell them apart. But AGENTS.md's "Management APIs should be
validated with AWS SDK clients, not only handcrafted HTTP requests" sits under AWS Protocol
Rules, not under Compatibility Project, so it is general and "not only" is the operative
phrase. Both, not either.

src/test cannot host it: the main module has no AWS SDK dependency at all. sdk-test-java is
where the repo keeps SDK validation and already had 60 EC2 tests, covering
DescribeVpcEndpointServices but not an endpoint's own interfaces.

What this proves that the XML assertions cannot: that the real Java SDK DESERIALIZES the
element into networkInterfaceIds(). A response can be well-formed XML and still not populate
the model -- a wrong element name or nesting fails silently and leaves an empty list rather
than raising, which is the exact symptom this PR fixes.

Asserted on CreateVpcEndpoint and again on DescribeVpcEndpoints, and that the two agree,
because Terraform reads from one and re-reads from the other between plan and apply.

DeleteVpc moves from @Order(50) to @Order(51) so this runs while the shared VPC still
exists.

* fix(ec2): an endpoint's published interface ids have to resolve too

Blocking finding from hectorvent on #4598, and the gap it names is one this branch
filed as separate work (floci-5wby) on reasoning that turns out to be wrong.

DescribeVpcEndpoints publishes one ENI id per subnet in networkInterfaceIdSet.
describeNetworkInterfaces enumerated instance-attached interfaces and the standalone
CreateNetworkInterface store only, never endpointNetworkInterfaces, so asking about a
published id got InvalidNetworkInterfaceID.NotFound from the same emulator that had
just handed it over.

WHY IT CANNOT SHIP SEPARATELY. The bead argued no corpus module writes
data "aws_network_interface", so nothing resolves one. The corpus check was right and
the conclusion was wrong: the provider does the lookup ITSELF, inside its own read of
aws_vpc_endpoint. resourceVPCEndpointFlatten calls
findSubnetConfigurationsByNetworkInterfaceIDs over every id in network_interface_ids to
build subnet_configuration, and returns the lookup error rather than tolerating a
NotFound -- it handles retry.NotFound for the prefix list a few lines above and
pointedly does not here. So the blast radius is not "modules that look up an ENI", it is
every interface endpoint read. Publishing the ids without this turns an empty list on
main into a hard read failure, which is a regression against main rather than a
pre-existing gap left unfixed.

Endpoint interfaces now answer describeNetworkInterfaces: listed unfiltered, resolvable
by id, and selectable by interface-type, subnet-id and vpc-id. interface-type had no arm
at all, so it matched everything through the default; requester-managed is new alongside
it.

WIRE SHAPE. interfaceType vpc_endpoint and requesterManaged true, which is what AWS
reports for an interface it creates on the customer's behalf, and requesterManaged is now
emitted for every interface, false included, as the documented sample response does.
requesterId is left unset on purpose: real AWS reports an internal service account there,
which floci cannot know, and an invented twelve-digit id would be a wrong answer rather
than a missing one. No attachment block, for the same reason -- AWS reports one carrying
an AWS-side owner alias that would have to be fabricated, and the provider reads none of
it.

The new arm is deliberately NOT account-scoped, unlike the two above it. describeVpcEndpoints
is not account-scoped either, so scoping here would leave an id that IS published to a
caller unresolvable BY that caller -- the exact defect being closed. Its ids are added to
foundIds before the filter check, matching the other arms, so an id asked for by name and
then excluded by a filter is absent from the answer rather than NotFound.

Measured both ways at 1608dc7. Before: 5 of the new class's 6 tests fail, the id lookup
answering

  <Code>InvalidNetworkInterfaceID.NotFound</Code>
  <Message>The network interface ID 'eni-787c7b66a5503789b' does not exist</Message>

for an id DescribeVpcEndpoints had just published. After: 6 of 6 pass. The sixth is the
guard that an id which was never published still does not exist, and it passes both ways --
a store that resolves everything would satisfy the other five.

Ec2VpcEndpoint*, Ec2NetworkInterfaceIntegrationTest, FlowLogServiceTest, Ec2ServiceTest,
Ec2IntegrationTest, plus the two internal describeNetworkInterfaces callers
(EcsFargateTaskIntegrationTest, EksVpcRouteProgrammingTest) and CloudControlIntegrationTest:
504 tests, 2 failures, both in Ec2VolumeBlockDeviceDockerIntegrationTest and both measured
failing identically on this head with the change reverted -- a loopback mount inside the
container returning EINVAL on this machine, which no ENI path reaches.

* docs(ec2): drop the private tracker ids from shipped source

Second point on #4598: floci-5vs is an id in a private tracker, so an upstream reader
cannot resolve it. The sentence it sat in stands on its own -- the parenthetical was
the only part carrying the dangling pointer.

Two more of the same kind, both introduced by the previous commit on this branch rather
than pre-existing: floci-5wby on the new describeNetworkInterfaces arm, and the same id
in the new test class's javadoc. The test keeps its floci-io/floci#4598 reference, which
is this PR and resolves for anyone reading it.

The PR's diff now adds no tracker-shaped id at all. Note that upstream main already
carries several on lines this branch does not touch -- floci-kt9 appears eleven times in
Ec2Service alone, plus floci-k41 and the floci-3wz the review cites -- so this is the
convention changing, not a slip being corrected, and the rest is left where it is rather
than widened into this fix.

Deliberately NOT the javadoc trimming the review asks for in the same breath. That was
sequenced as a separate follow-up PR and the branch-history lines it targets are a
different problem from an unresolvable id.

Comment-only. Ec2VpcEndpoint*, Ec2NetworkInterfaceIntegrationTest, FlowLogServiceTest:
89 tests, 0 failures.

* fix(ec2): an endpoint's interfaces carry its security groups, and own their owner

Third review round on #4598. One finding is real, one rests on a misreading I had
written into the code myself, and the correction runs the other way from what was asked.

SECURITY GROUPS -- the real one. An interface endpoint's security groups are enforced ON
its interfaces; that is the entire mechanism by which a PrivateLink endpoint is
firewalled, and AWS reports them in each interface's groupSet. Floci reported an empty
groupSet, so a group-id filter excluded the very interfaces the group is attached to.
The group 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 one.

ACCOUNT SCOPING -- the misreading, and it was mine. The previous commit justified leaving
this arm unscoped by asserting that describeVpcEndpoints is not account-scoped either,
citing its vpcEndpoints.scan(k -> true). That is wrong. Plain scan on an
AccountAwareStorageBackend filters to the caller's partition before the predicate runs:
k -> true selects every KEY within one account, not every account. The endpoint side was
scoped all along, and so is the subnet lookup inside endpointNetworkInterfacesOf, which
would yield no interfaces for a foreign endpoint even if one were reached. Two
independent layers, neither visible at the call site.

So the review's conclusion -- that this arm exposed other accounts' interfaces -- does
not hold, and neither did my stated reason for writing it that way. Measured rather than
argued: deleting an account filter from the describe arm changes no observable behaviour,
because the scoping is not there to begin with. The arm is therefore left as it was and
the COMMENT is corrected, since the comment was the defect.

ownerId is the part of that finding with a real kernel, and it is fixed: it now comes
from callerAccountId(), the account these interfaces were actually read under, instead of
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.

Also: the not-found matcher is statically imported rather than inline-qualified, per
AGENTS.md.

TESTS. anEndpointInterfaceCarriesTheEndpointsSecurityGroups measured both ways -- it
FAILS with the group loop removed ("expected: <[sg-13d37d8313c325d98]> but was: <[]>")
and passes with it, and it asserts the group-id filter as well as the groupSet, since the
empty-groupSet bug satisfies neither. anotherAccountsEndpointInterfacesAreInvisible is
labelled in the source as what it is: a characterization test that passes with and
without an account filter, kept because it pins the behaviour a reviewer doubted rather
than the mechanism, and positioned to fail if either scoping layer changes.

Ec2VpcEndpoint*, Ec2NetworkInterfaceIntegrationTest, FlowLogServiceTest, Ec2ServiceTest,
Ec2IntegrationTest, EcsFargateTaskIntegrationTest, EksVpcRouteProgrammingTest,
CloudControlIntegrationTest: 499 tests, 0 failures.

* test(compat): the endpoint SDK test creates the fixtures it needs

The ordered suite shares mutable fixtures, so what exists at a given point is a function
of position. @Order(44) deletes the shared subnet and sets subnetId to null and
@Order(45) deletes the shared security group, both before this @Order(50) test ran: it
was passing a null subnet id to CreateVpcEndpoint and asserting groups() was non-empty
while supplying no group at all.

It now creates its own subnet and security group, uses them, and deletes them in the
same finally block that already removed the endpoint.

Worth noting why neither half failed loudly enough to catch earlier: compatibility-tests
is not a module of the root pom, so `./mvnw test` never compiles or runs it. Verified
here by building the module directly.

Authored by Allen; committed from the branch worktree alongside the review round.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-29 22:28:01 -04:00
1 parent c0ec98b43e
commit 6b7d17698c
6 files changed
+886 -16

No files matched your search

@@ -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());
@@ -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<String> endpointEniIds = service.endpointNetworkInterfaceIds(endpoint);
if (!endpointEniIds.isEmpty()) {
xml.start("networkInterfaceIdSet");
for (String eniId : endpointEniIds) {
xml.elem("item", eniId);
}
xml.end("networkInterfaceIdSet");
}
List<VpcEndpointDnsEntry> dnsEntries = service.endpointDnsEntries(endpoint);
if (!dnsEntries.isEmpty()) {
xml.start("dnsEntrySet");
@@ -4725,25 +4725,72 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
public List<NetworkInterface> endpointNetworkInterfaces(String region) {
List<NetworkInterface> 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.
*
* <p>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.
*
* <p>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.
*
* <p>A Gateway endpoint owns no interfaces and gets an empty list.
*/
private List<NetworkInterface> endpointNetworkInterfacesOf(VpcEndpoint endpoint) {
if (!"Interface".equalsIgnoreCase(endpoint.getVpcEndpointType())) {
return List.of();
}
String region = endpoint.getRegion();
List<NetworkInterface> 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.
*
* <p>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.
*
* <p>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.
*
* <p>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<String> endpointNetworkInterfaceIds(VpcEndpoint endpoint) {
List<String> 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)) {
@@ -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<GroupIdentifier> groups = new ArrayList<>();
private NetworkInterfaceAttachment attachment;
private List<Tag> 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; }
@@ -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.
*
* <p>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.
*
* <p>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.
*
* <p>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 <networkInterfaceIdSet/>}, 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 <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVpcEndpoints.html">DescribeVpcEndpoints</a>
*/
@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<String> 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<String> 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<String> 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<String> 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<String> 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());
}
}
@@ -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.
*
* <p>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.
*
* <p>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.
*
* <p>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 <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeNetworkInterfaces.html">DescribeNetworkInterfaces</a>
* @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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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);
}
}