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

@@ -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; }