feat(ec2): EC2 Instance Connect Endpoint control plane (#7359)

* feat(ec2): EC2 Instance Connect Endpoint control plane

CreateInstanceConnectEndpoint, DescribeInstanceConnectEndpoints and
DeleteInstanceConnectEndpoint answered UnknownOperation, so Terraform's
aws_ec2_instance_connect_endpoint failed at create and the AWS CLI's
`ec2-instance-connect ssh --connection-type eice` could not look an
endpoint up. They now carry the fields, filters and errors Terraform and
the CLI use. Endpoint DNS names are <id>.localhost.floci.io, which public
DNS resolves to 127.0.0.1, and each endpoint takes a private address in
its subnet.

As on AWS, a live endpoint makes DeleteSubnet and DeleteVpc fail with
DependencyViolation (a destroy ordered wrongly would otherwise pass here
and fail on AWS, and the endpoint's address reservation leaked), and a
replayed ClientToken returns the first endpoint instead of creating a
duplicate on an SDK or Terraform retry.

The tunnel the endpoint serves is a separate change.

* fix(ec2): create an EC2 Instance Connect Endpoint under the subnet topology lock

Two creates with one ClientToken could both miss the replay scan and make
two endpoints, and a DeleteSubnet could land between the subnet check and
the save, leaving an endpoint on a subnet that is gone. The create now
holds the lock DeleteSubnet holds. The endpoint store is final and comes
through the constructor chain like the other stores, and the service test
is named Ec2InstanceConnectEndpointServiceTest.

* test(ec2): name the exceptions the endpoint race test expects

* fix(ec2): return a copy from instance connect endpoint reads

Create, Describe and Delete handed back the stored endpoint itself, with
its tags written onto it, and Delete then set delete-in-progress on that
object. A caller changing a returned endpoint changed the stored one.
They now return a copy carrying the current tags.

* fix(ec2): scan one region's instance connect endpoints by key on describe

Describe read every region's endpoints and kept those whose region field
matched, while the ClientToken replay scan picks a region by store key.
Describe now uses the key prefix too, so the two agree on what is in a
region and describe no longer reads other regions' records.

* fix(ec2): compare every creation parameter on an instance connect endpoint ClientToken replay

A replayed ClientToken compared only SubnetId, so a retry with other
security groups, IpAddressType, PreserveClientIp or tags returned the
first endpoint as if it matched. Each is now compared after defaults are
applied and a difference is IdempotentParameterMismatch, as the egress-only
internet gateway create does. Tags are compared as the create request
carried them, so a later CreateTags does not turn a retry into a mismatch.

* test(ec2): drive instance connect endpoints over the EC2 Query wire

The service test called Ec2Service directly, so nothing covered the query
handler: SecurityGroupId.N and TagSpecification.N parsing, the ClientToken
echo, and the Create, Describe and Delete response envelopes. The
integration test creates, replays, describes and deletes an endpoint
through the HTTP endpoint and reads each result back with a separate
Describe.

* fix(ec2): validate instance connect endpoint requests before answering DryRun

CreateInstanceConnectEndpoint answered DryRunOperation before checking the
subnet, IpAddressType or security groups, and Describe and Delete ignored
DryRun and acted on the request. Create now validates and then answers
DryRunOperation, as RunInstances and ReplaceRoute do, and Describe and
Delete check the IDs and filters first, then answer DryRunOperation
without deleting anything.

* fix(ec2): page DescribeInstanceConnectEndpoints by MaxResults and NextToken

MaxResults and NextToken were ignored and every match came back on one
page. Describe now returns at most MaxResults endpoints in ID order with a
nextToken for the rest, using the shared opaque-cursor pagination, and an
unreadable NextToken is InvalidParameterValue as DescribeDhcpOptions
answers it. MaxResults is not range-checked against the model's 1-50.

* fix(ec2): range-check MaxResults on DescribeInstanceConnectEndpoints and compare replayed security groups as a set

The model's InstanceConnectEndpointMaxResults allows 1 to 50, but a sent
0, negative or larger value was served. It is now InvalidMaxResults, as
DescribeTags and DescribeEgressOnlyInternetGateways refuse values outside
their own ranges; an omitted MaxResults still returns every match.

A test now pins that a ClientToken replay naming the same security groups
in another order returns the first endpoint.

* docs(ec2): name instance connect endpoints among the private address holders

privateIpsInUse and privateIpsHeldOnVpcNetwork count the addresses EC2 Instance Connect Endpoints hold, but their comments listed only instances, network interfaces and NAT gateways.

* test(ec2): refuse a NAT gateway the private address an instance connect endpoint holds

CreateNatGateway with a PrivateIpAddress an EC2 Instance Connect Endpoint holds answers InvalidIPAddress.InUse, and the address is free again once the endpoint is deleted. Nothing covered the endpoint's share of the in-use scan before.

* fix(ec2): copy each creation tag of an instance connect endpoint

The copy constructor copied the creationTags list but shared its Tag
objects with the stored endpoint, and the create stored the request's
own Tag objects. Changing a tag on a returned endpoint, or on the list
passed to the create, changed the saved creation parameters, so a
retry with the same ClientToken and the original tags failed with
IdempotentParameterMismatch. Copy each Tag when saving and when
returning a copy.

* fix(ec2): reject an unknown DescribeInstanceConnectEndpoints filter before scanning

An unknown filter name was rejected only while testing it against an
endpoint, so with no endpoints, or when an earlier filter excluded them
all, the bad name succeeded silently. Check every name up front through
requireSupportedFilters, as DescribeVpcs and DescribeVpnGateways do,
with the same InvalidParameterValue.

* fix(ec2): resolve an instance connect endpoint's interface in DescribeNetworkInterfaces

CreateInstanceConnectEndpoint published an interface ID in
networkInterfaceIdSet that DescribeNetworkInterfaces answered with
InvalidNetworkInterfaceID.NotFound, so a client could not read the
endpoint's private address or security groups from it. Build the
interface from the endpoint in the describe path, as the NAT gateway
and interface VPC endpoint arms already do: a requester-managed
ec2_instance_connect_endpoint interface with the endpoint's subnet,
VPC, private address and security groups, present while the endpoint
exists. Its address is already counted from the endpoint record, so
subnet address accounting is unchanged. DeleteInstanceConnectEndpoint
also drops the interface's own tags, as DeleteNatGateway does.

* fix(ec2): name an instance connect endpoint interface's groups from the account it is read for

The explicit-account DescribeNetworkInterfaces overload scanned the
named account's endpoints but looked their security group names up
under the ambient request account, so a caller in another account got
the groups back without names. Read the group for the same account,
as natNetworkInterfacesOf reads its subnet.

* test(ec2): keep another account's instance connect endpoint interface out of DescribeNetworkInterfaces

An endpoint created in one account is NotFound by NetworkInterfaceId
and absent from an unfiltered list for another account, and still
visible to its own.

* fix(ec2): accept exactly AWS's DescribeInstanceConnectEndpoints filters

The DescribeInstanceConnectEndpoints reference lists instance-connect-endpoint-id,
state, subnet-id, tag:<key>, tag-key, tag-value and vpc-id. Implement tag-value
(any tag's value in the filter values, as the other EC2 describe calls match it)
and stop accepting availability-zone and owner-id, which the reference does not
list; they are now refused as InvalidParameterValue like any unknown filter.

* refactor(ec2): build NAT gateway and instance connect endpoint interfaces once

natNetworkInterfacesOf and instanceConnectEndpointNetworkInterfacesOf set up the
same requester-managed interface with one primary address; both now call
requesterManagedInterface. Their two DescribeNetworkInterfaces arms, identical
but for the interfaces they walk, become one arm over NAT interfaces then
endpoint interfaces, the order the two arms ran in. No behaviour change.

* test(ec2): share a mock-mode Ec2Service builder in the test fixtures

Ec2ServiceFixtures.mockModeService() in the shared testing package builds the
mock-mode Ec2Service over in-memory storage that Ec2InstanceConnectEndpointServiceTest
built privately, and that class now uses it. The other classes with their own copy
move to it separately.

* docs(ec2): count the three InstanceConnectEndpoint operations in the service matrix
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-11-03 23:25:57 -04:00
1 parent a98380b387
commit 196b672563
9 files changed
+1302 -52

No files matched your search

@@ -0,0 +1,240 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.Ec2Requests.ec2;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* CreateInstanceConnectEndpoint, DescribeInstanceConnectEndpoints and DeleteInstanceConnectEndpoint
* over the EC2 Query wire: SecurityGroupId.N and TagSpecification.N on the way in, the response
* envelopes on the way out. Every read is a separate Describe rather than the create's own response.
*/
@QuarkusTest
class Ec2InstanceConnectEndpointIntegrationTest {
private static final String ITEM = "DescribeInstanceConnectEndpointsResponse.instanceConnectEndpointSet.item";
private static final String CREATED = "CreateInstanceConnectEndpointResponse.instanceConnectEndpoint";
@Test
void createDescribeAndDeleteOverTheWire() {
String vpcId = createVpc("10.81.0.0/16");
String subnetId = createSubnet(vpcId, "10.81.1.0/24");
String groupA = createGroup(vpcId, "eice-a");
String groupB = createGroup(vpcId, "eice-b");
String name = "eice-" + UUID.randomUUID();
String token = UUID.randomUUID().toString();
String id = create(subnetId, groupA, groupB, name, token)
.post("/").then().statusCode(200)
.body("CreateInstanceConnectEndpointResponse.clientToken", equalTo(token))
.body(CREATED + ".instanceConnectEndpointId", matchesPattern("eice-[0-9a-f]{17}"))
.body(CREATED + ".state", equalTo("create-complete"))
.body(CREATED + ".subnetId", equalTo(subnetId))
.extract().path(CREATED + ".instanceConnectEndpointId");
// The replay answers with the same endpoint and makes no second one.
create(subnetId, groupA, groupB, name, token)
.post("/").then().statusCode(200)
.body(CREATED + ".instanceConnectEndpointId", equalTo(id));
ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1")
.formParam("Filter.1.Name", "tag:Name")
.formParam("Filter.1.Value.1", name)
.post("/").then().statusCode(200)
.body(ITEM + ".size()", equalTo(1))
.body(ITEM + ".instanceConnectEndpointId", equalTo(id))
.body(ITEM + ".instanceConnectEndpointArn",
equalTo("arn:aws:ec2:us-east-1:000000000000:instance-connect-endpoint/" + id))
.body(ITEM + ".vpcId", equalTo(vpcId))
.body(ITEM + ".subnetId", equalTo(subnetId))
.body(ITEM + ".ipAddressType", equalTo("ipv4"))
.body(ITEM + ".preserveClientIp", equalTo("false"))
.body(ITEM + ".dnsName", equalTo(id + ".localhost.floci.io"))
.body(ITEM + ".publicDnsNames.ipv4.dnsName", equalTo(id + ".localhost.floci.io"))
.body(ITEM + ".securityGroupIdSet.item", containsInAnyOrder(groupA, groupB))
.body(ITEM + ".tagSet.item.find { it.key == 'Name' }.value", equalTo(name));
// The interface the endpoint publishes resolves through DescribeNetworkInterfaces.
String eniId = ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1")
.formParam("InstanceConnectEndpointId.1", id)
.post("/").then().statusCode(200)
.extract().path(ITEM + ".networkInterfaceIdSet.item");
String eni = "DescribeNetworkInterfacesResponse.networkInterfaceSet.item";
ec2("DescribeNetworkInterfaces", "test", "us-east-1")
.formParam("NetworkInterfaceId.1", eniId)
.post("/").then().statusCode(200)
.body(eni + ".networkInterfaceId", equalTo(eniId))
.body(eni + ".subnetId", equalTo(subnetId))
.body(eni + ".vpcId", equalTo(vpcId))
.body(eni + ".interfaceType", equalTo("ec2_instance_connect_endpoint"))
.body(eni + ".requesterManaged", equalTo("true"))
.body(eni + ".description", equalTo("EC2 Instance Connect Endpoint " + id))
.body(eni + ".privateIpAddress", matchesPattern("10\\.81\\.1\\.\\d+"))
.body(eni + ".groupSet.item.groupId", containsInAnyOrder(groupA, groupB));
ec2("DeleteInstanceConnectEndpoint", "test", "us-east-1")
.formParam("InstanceConnectEndpointId", id)
.post("/").then().statusCode(200)
.body("DeleteInstanceConnectEndpointResponse.instanceConnectEndpoint.instanceConnectEndpointId",
equalTo(id))
.body("DeleteInstanceConnectEndpointResponse.instanceConnectEndpoint.state",
equalTo("delete-in-progress"));
ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1")
.formParam("InstanceConnectEndpointId.1", id)
.post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidInstanceConnectEndpointId.NotFound"));
ec2("DescribeNetworkInterfaces", "test", "us-east-1")
.formParam("NetworkInterfaceId.1", eniId)
.post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidNetworkInterfaceID.NotFound"));
deleteAll(List.of(groupA, groupB), subnetId, vpcId);
}
@Test
void dryRunValidatesFirstAndChangesNothing() {
String vpcId = createVpc("10.82.0.0/16");
String subnetId = createSubnet(vpcId, "10.82.1.0/24");
String missing = "eice-0123456789abcdef0";
// An invalid request fails on its own error, not DryRunOperation.
assertError(ec2("CreateInstanceConnectEndpoint", "test", "us-east-1")
.formParam("SubnetId", "subnet-0123456789abcdef0").formParam("DryRun", "true"),
400, "InvalidSubnetID.NotFound");
assertError(ec2("CreateInstanceConnectEndpoint", "test", "us-east-1")
.formParam("SubnetId", subnetId).formParam("IpAddressType", "bogus").formParam("DryRun", "true"),
400, "InvalidParameterValue");
assertError(ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1")
.formParam("InstanceConnectEndpointId.1", missing).formParam("DryRun", "true"),
400, "InvalidInstanceConnectEndpointId.NotFound");
assertError(ec2("DeleteInstanceConnectEndpoint", "test", "us-east-1")
.formParam("InstanceConnectEndpointId", missing).formParam("DryRun", "true"),
400, "InvalidInstanceConnectEndpointId.NotFound");
// A valid one answers DryRunOperation and creates or deletes nothing.
assertError(ec2("CreateInstanceConnectEndpoint", "test", "us-east-1")
.formParam("SubnetId", subnetId).formParam("DryRun", "true"), 412, "DryRunOperation");
ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1")
.formParam("Filter.1.Name", "subnet-id").formParam("Filter.1.Value.1", subnetId)
.post("/").then().statusCode(200)
.body(ITEM + ".size()", equalTo(0));
assertError(ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1").formParam("DryRun", "true"),
412, "DryRunOperation");
String id = ec2("CreateInstanceConnectEndpoint", "test", "us-east-1").formParam("SubnetId", subnetId)
.post("/").then().statusCode(200).extract().path(CREATED + ".instanceConnectEndpointId");
assertError(ec2("DeleteInstanceConnectEndpoint", "test", "us-east-1")
.formParam("InstanceConnectEndpointId", id).formParam("DryRun", "true"), 412, "DryRunOperation");
ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1")
.formParam("InstanceConnectEndpointId.1", id)
.post("/").then().statusCode(200)
.body(ITEM + ".state", equalTo("create-complete"));
ec2("DeleteInstanceConnectEndpoint", "test", "us-east-1").formParam("InstanceConnectEndpointId", id)
.post("/").then().statusCode(200);
deleteAll(List.of(), subnetId, vpcId);
}
@Test
void describePagesWithMaxResultsAndNextToken() {
String vpcId = createVpc("10.83.0.0/16");
String subnetId = createSubnet(vpcId, "10.83.1.0/24");
List<String> created = new ArrayList<>();
for (int i = 0; i < 3; i++) {
created.add(ec2("CreateInstanceConnectEndpoint", "test", "us-east-1").formParam("SubnetId", subnetId)
.post("/").then().statusCode(200).extract().path(CREATED + ".instanceConnectEndpointId"));
}
List<String> seen = new ArrayList<>();
String token = null;
int pages = 0;
do {
RequestSpecification request = ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1")
.formParam("Filter.1.Name", "subnet-id").formParam("Filter.1.Value.1", subnetId)
.formParam("MaxResults", "2");
if (token != null) {
request.formParam("NextToken", token);
}
XmlPath page = request.post("/").then().statusCode(200).extract().xmlPath();
List<String> ids = page.getList(ITEM + ".instanceConnectEndpointId", String.class);
assertTrue(ids.size() <= 2, ids.toString());
seen.addAll(ids);
token = page.getString("DescribeInstanceConnectEndpointsResponse.nextToken");
token = token == null || token.isEmpty() ? null : token;
pages++;
} while (token != null && pages < 5);
assertEquals(2, pages);
assertEquals(created.stream().sorted().toList(), seen);
assertError(ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1").formParam("NextToken", "bogus"),
400, "InvalidParameterValue");
for (String outOfRange : List.of("0", "-1", "51")) {
assertError(ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1")
.formParam("MaxResults", outOfRange), 400, "InvalidMaxResults");
}
for (String inRange : List.of("1", "50")) {
ec2("DescribeInstanceConnectEndpoints", "test", "us-east-1").formParam("MaxResults", inRange)
.post("/").then().statusCode(200);
}
for (String id : created) {
ec2("DeleteInstanceConnectEndpoint", "test", "us-east-1").formParam("InstanceConnectEndpointId", id)
.post("/").then().statusCode(200);
}
deleteAll(List.of(), subnetId, vpcId);
}
private static void assertError(RequestSpecification request, int status, String code) {
request.post("/").then().statusCode(status).body("Response.Errors.Error.Code", equalTo(code));
}
private static RequestSpecification create(String subnetId, String groupA, String groupB, String name,
String token) {
return ec2("CreateInstanceConnectEndpoint", "test", "us-east-1")
.formParam("SubnetId", subnetId)
.formParam("SecurityGroupId.1", groupA)
.formParam("SecurityGroupId.2", groupB)
.formParam("TagSpecification.1.ResourceType", "instance-connect-endpoint")
.formParam("TagSpecification.1.Tag.1.Key", "Name")
.formParam("TagSpecification.1.Tag.1.Value", name)
.formParam("ClientToken", token);
}
static String createVpc(String cidr) {
return ec2("CreateVpc", "test", "us-east-1").formParam("CidrBlock", cidr)
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
}
static String createSubnet(String vpcId, String cidr) {
return ec2("CreateSubnet", "test", "us-east-1").formParam("VpcId", vpcId).formParam("CidrBlock", cidr)
.post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
}
static String createGroup(String vpcId, String name) {
return ec2("CreateSecurityGroup", "test", "us-east-1").formParam("VpcId", vpcId)
.formParam("GroupName", name).formParam("GroupDescription", name)
.post("/").then().statusCode(200).extract().path("CreateSecurityGroupResponse.groupId");
}
static void deleteAll(List<String> groups, String subnetId, String vpcId) {
for (String group : groups) {
ec2("DeleteSecurityGroup", "test", "us-east-1").formParam("GroupId", group)
.post("/").then().statusCode(200);
}
ec2("DeleteSubnet", "test", "us-east-1").formParam("SubnetId", subnetId).post("/").then().statusCode(200);
ec2("DeleteVpc", "test", "us-east-1").formParam("VpcId", vpcId).post("/").then().statusCode(200);
}
}
@@ -0,0 +1,390 @@
package io.github.hectorvent.floci.services.ec2;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
import io.github.hectorvent.floci.services.ec2.model.InstanceConnectEndpoint;
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static io.github.hectorvent.floci.testing.Ec2ServiceFixtures.mockModeService;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** CreateInstanceConnectEndpoint, DescribeInstanceConnectEndpoints and DeleteInstanceConnectEndpoint. */
class Ec2InstanceConnectEndpointServiceTest {
private static final String REGION = "us-east-1";
@Test
void lifecycleFiltersAndDefaults() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.71.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.71.1.0/24", "us-east-1a").getSubnetId();
String otherVpc = service.createVpc(REGION, "10.72.0.0/16", false).getVpcId();
String foreignGroup = service.createSecurityGroup(REGION, "foreign", "x", otherVpc).getGroupId();
InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(),
null, null, List.of(new Tag("Name", "kthw")), null);
String id = endpoint.getInstanceConnectEndpointId();
assertTrue(id.startsWith("eice-"), id);
assertEquals("create-complete", endpoint.getState());
assertEquals(id + ".localhost.floci.io", endpoint.getDnsName());
assertEquals(vpcId, endpoint.getVpcId());
assertEquals("ipv4", endpoint.getIpAddressType());
assertFalse(endpoint.isPreserveClientIp(), "AWS's default");
assertEquals(1, endpoint.getSecurityGroupIds().size(), "the VPC's default group when none is given");
assertTrue(endpoint.getPrivateIpAddress().startsWith("10.71.1."), endpoint.getPrivateIpAddress());
assertEquals(List.of(id), service.describeInstanceConnectEndpoints(REGION, List.of(),
Map.of("vpc-id", List.of(vpcId), "state", List.of("create-complete"), "tag:Name", List.of("kthw")))
.stream().map(InstanceConnectEndpoint::getInstanceConnectEndpointId).toList());
assertTrue(service.describeInstanceConnectEndpoints(REGION, List.of(),
Map.of("vpc-id", List.of(otherVpc))).isEmpty());
assertEquals("InvalidParameterValue", assertThrows(AwsException.class, () -> service
.describeInstanceConnectEndpoints(REGION, List.of(), Map.of("bogus", List.of("x"))))
.getErrorCode());
assertEquals("InvalidParameter", assertThrows(AwsException.class, () -> service
.createInstanceConnectEndpoint(REGION, subnetId, List.of(foreignGroup), null, null, List.of(), null))
.getErrorCode());
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class, () -> service
.createInstanceConnectEndpoint(REGION, subnetId, List.of(), true, "dualstack", List.of(), null))
.getErrorCode());
assertEquals("InvalidSubnetID.NotFound", assertThrows(AwsException.class, () -> service
.createInstanceConnectEndpoint(REGION, "subnet-0000000000000000f", List.of(), null, null,
List.of(), null))
.getErrorCode());
assertEquals("delete-in-progress", service.deleteInstanceConnectEndpoint(REGION, id).getState());
assertEquals("InvalidInstanceConnectEndpointId.NotFound", assertThrows(AwsException.class, () -> service
.describeInstanceConnectEndpoints(REGION, List.of(id), Map.of())).getErrorCode());
}
@Test
void aLiveEndpointBlocksDeletingItsSubnetAndVpc() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.74.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.74.1.0/24", "us-east-1a").getSubnetId();
String id = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), null)
.getInstanceConnectEndpointId();
assertEquals("DependencyViolation", assertThrows(AwsException.class,
() -> service.deleteSubnet(REGION, subnetId)).getErrorCode());
assertEquals("DependencyViolation", assertThrows(AwsException.class,
() -> service.deleteVpc(REGION, vpcId)).getErrorCode());
service.deleteInstanceConnectEndpoint(REGION, id);
service.deleteSubnet(REGION, subnetId);
service.deleteVpc(REGION, vpcId);
}
@Test
void aNatGatewayCannotTakeTheAddressAnEndpointHolds() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.75.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.75.1.0/24", "us-east-1a").getSubnetId();
InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(),
null, null, List.of(), null);
String held = endpoint.getPrivateIpAddress();
assertEquals("InvalidIPAddress.InUse", assertThrows(AwsException.class, () -> service
.createNatGateway(REGION, subnetId, null, "private", held, List.of())).getErrorCode());
// Once the endpoint is gone the address is free again, so the refusal above was the endpoint's.
service.deleteInstanceConnectEndpoint(REGION, endpoint.getInstanceConnectEndpointId());
assertEquals(held, service.createNatGateway(REGION, subnetId, null, "private", held, List.of())
.getNatGatewayAddresses().get(0).getPrivateIp());
}
@Test
void aReplayedClientTokenReturnsTheFirstEndpoint() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.75.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.75.1.0/24", "us-east-1a").getSubnetId();
String otherSubnet = service.createSubnet(REGION, vpcId, "10.75.2.0/24", "us-east-1a").getSubnetId();
String first = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(),
"token-1").getInstanceConnectEndpointId();
assertEquals(first, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null,
List.of(), "token-1").getInstanceConnectEndpointId());
assertEquals(1, service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).size());
assertEquals("IdempotentParameterMismatch", assertThrows(AwsException.class, () -> service
.createInstanceConnectEndpoint(REGION, otherSubnet, List.of(), null, null, List.of(), "token-1"))
.getErrorCode());
}
@Test
void aReplayedClientTokenWithOtherParametersIsAMismatch() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.78.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.78.1.0/24", "us-east-1a").getSubnetId();
String group = service.createSecurityGroup(REGION, "eice", "x", vpcId).getGroupId();
List<Tag> tags = List.of(new Tag("Name", "kthw"));
String first = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group), false, "ipv4", tags,
"token-78").getInstanceConnectEndpointId();
// Defaults applied the same way match: omitted PreserveClientIp and IpAddressType are false and ipv4.
assertEquals(first, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group), null, null,
tags, "token-78").getInstanceConnectEndpointId());
// Security groups are a set: the same groups in another order are the same request.
String other = service.createSecurityGroup(REGION, "eice-2", "x", vpcId).getGroupId();
String ordered = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group, other), null, null,
tags, "token-78-sets").getInstanceConnectEndpointId();
assertEquals(ordered, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(other, group), null,
null, tags, "token-78-sets").getInstanceConnectEndpointId());
// A tag added after the create is not a creation parameter.
service.createTags(REGION, List.of(first), List.of(new Tag("Later", "x")));
assertEquals(first, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group), null, null,
tags, "token-78").getInstanceConnectEndpointId());
Map<String, Executable> retries = Map.of(
"security groups", () -> service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null,
null, tags, "token-78"),
"tags", () -> service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group), null, null,
List.of(new Tag("Name", "other")), "token-78"),
"ip address type", () -> service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group),
null, "dualstack", tags, "token-78"),
"preserve client ip", () -> service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group),
true, null, tags, "token-78"));
retries.forEach((what, retry) -> assertEquals("IdempotentParameterMismatch",
assertThrows(AwsException.class, retry, what).getErrorCode(), what));
assertEquals(2, service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).size());
}
@Test
void changingAReturnedEndpointLeavesTheStoredOneAlone() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.76.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.76.1.0/24", "us-east-1a").getSubnetId();
InstanceConnectEndpoint created = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null,
null, List.of(new Tag("Name", "kthw")), null);
created.setState("bogus");
created.getSecurityGroupIds().clear();
InstanceConnectEndpoint described = service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).get(0);
described.getTags().clear();
InstanceConnectEndpoint again = service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).get(0);
assertEquals("create-complete", again.getState());
assertEquals(1, again.getSecurityGroupIds().size());
assertEquals(List.of("Name"), again.getTags().stream().map(Tag::getKey).toList());
}
@Test
void describeListsWhatTheClientTokenReplaySees() {
InMemoryStorageFactory storage = new InMemoryStorageFactory("000000000000");
Ec2Service service = mockModeService(storage);
String vpcId = service.createVpc(REGION, "10.77.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.77.1.0/24", "us-east-1a").getSubnetId();
String id = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(),
"token-77").getInstanceConnectEndpointId();
// Both scans pick a region's endpoints by store key; a record whose region field is unset
// (written before the field existed, say) is still in the region its key names.
StorageBackend<String, InstanceConnectEndpoint> store = storage.create("ec2",
"ec2-instance-connect-endpoints.json", new TypeReference<Map<String, InstanceConnectEndpoint>>() {});
InstanceConnectEndpoint stored = store.get(REGION + "::" + id).orElseThrow();
stored.setRegion(null);
store.put(REGION + "::" + id, stored);
assertEquals(id, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(),
"token-77").getInstanceConnectEndpointId());
assertEquals(List.of(id), service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).stream()
.map(InstanceConnectEndpoint::getInstanceConnectEndpointId).toList());
}
@Test
void concurrentCreatesWithOneClientTokenMakeOneEndpoint() throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(8);
try {
for (int round = 0; round < 50; round++) {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.73.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.73.1.0/24", "us-east-1a").getSubnetId();
CountDownLatch go = new CountDownLatch(1);
List<Future<String>> ids = new ArrayList<>();
for (int i = 0; i < 8; i++) {
ids.add(pool.submit(() -> {
go.await();
return service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null,
List.of(), "token-" + subnetId).getInstanceConnectEndpointId();
}));
}
go.countDown();
Set<String> distinct = ConcurrentHashMap.newKeySet();
for (Future<String> id : ids) {
distinct.add(id.get());
}
assertEquals(1, distinct.size(), "round " + round + ": " + distinct);
assertEquals(1, service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).size());
}
} finally {
pool.shutdownNow();
}
}
@Test
void aSubnetDeletedDuringACreateNeverLeavesAnEndpointOnIt() throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
for (int round = 0; round < 200; round++) {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.74.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.74.1.0/24", "us-east-1a").getSubnetId();
CountDownLatch go = new CountDownLatch(1);
Future<?> create = pool.submit(() -> {
go.await();
try {
service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), null);
} catch (AwsException expected) {
// InvalidSubnetID.NotFound: the delete won.
}
return null;
});
Future<?> delete = pool.submit(() -> {
go.await();
try {
service.deleteSubnet(REGION, subnetId);
} catch (AwsException expected) {
// DependencyViolation: the create won.
}
return null;
});
go.countDown();
create.get();
delete.get();
boolean subnetGone = service.describeSubnets(REGION, List.of(), Map.of()).stream()
.noneMatch(subnet -> subnetId.equals(subnet.getSubnetId()));
boolean endpointOnIt = service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).stream()
.anyMatch(endpoint -> subnetId.equals(endpoint.getSubnetId()));
assertFalse(subnetGone && endpointOnIt, "round " + round + ": endpoint left on a deleted subnet");
}
} finally {
pool.shutdownNow();
}
}
@Test
void changingAReturnedOrRequestedTagLeavesTheCreationParametersAlone() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.81.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.81.1.0/24", "us-east-1a").getSubnetId();
Tag requested = new Tag("Name", "kthw");
String id = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null,
List.of(requested), "token-81").getInstanceConnectEndpointId();
requested.setValue("changed-after-create");
service.describeInstanceConnectEndpoints(REGION, List.of(), Map.of()).get(0)
.getCreationTags().get(0).setValue("changed-on-a-copy");
assertEquals(id, service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null,
List.of(new Tag("Name", "kthw")), "token-81").getInstanceConnectEndpointId());
}
@Test
void anUnknownFilterNameFailsWhenNoEndpointIsTestedAgainstIt() {
Ec2Service service = mockModeService();
assertEquals("InvalidParameterValue", assertThrows(AwsException.class, () -> service
.describeInstanceConnectEndpoints(REGION, List.of(), Map.of("bogus", List.of("x"))))
.getErrorCode());
String vpcId = service.createVpc(REGION, "10.80.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.80.1.0/24", "us-east-1a").getSubnetId();
service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), null);
// An earlier filter that excludes every endpoint does not hide the bad name after it.
List<Map.Entry<String, List<String>>> filters = List.of(
Map.entry("vpc-id", List.of("vpc-00000000000000000")), Map.entry("bogus", List.of("x")));
assertEquals("InvalidParameterValue", assertThrows(AwsException.class, () -> service
.describeInstanceConnectEndpoints(REGION, List.of(), filters)).getErrorCode());
}
@Test
void tagValueMatchesAnEndpointCarryingThatValueUnderAnyKey() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.81.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.81.1.0/24", "us-east-1a").getSubnetId();
String id = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null,
List.of(new Tag("Name", "kthw"), new Tag("Team", "infra")), null).getInstanceConnectEndpointId();
assertEquals(List.of(id), service.describeInstanceConnectEndpoints(REGION, List.of(),
Map.of("tag-value", List.of("nope", "infra")))
.stream().map(InstanceConnectEndpoint::getInstanceConnectEndpointId).toList());
assertTrue(service.describeInstanceConnectEndpoints(REGION, List.of(),
Map.of("tag-value", List.of("Team"))).isEmpty(), "a key is not a value");
}
@Test
void availabilityZoneAndOwnerIdAreRefusedLikeAnyFilterAwsDoesNotList() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.82.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.82.1.0/24", "us-east-1a").getSubnetId();
service.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), null);
AwsException unknown = assertThrows(AwsException.class, () -> service
.describeInstanceConnectEndpoints(REGION, List.of(), Map.of("bogus", List.of("x"))));
for (String name : List.of("availability-zone", "owner-id")) {
AwsException error = assertThrows(AwsException.class, () -> service
.describeInstanceConnectEndpoints(REGION, List.of(), Map.of(name, List.of("x"))), name);
assertEquals(unknown.getErrorCode(), error.getErrorCode(), name);
assertEquals(unknown.getHttpStatus(), error.getHttpStatus(), name);
assertEquals("The filter '" + name + "' is invalid", error.getMessage(), name);
}
}
@Test
void theEndpointsInterfaceResolvesInDescribeNetworkInterfacesUntilItIsDeleted() {
Ec2Service service = mockModeService();
String vpcId = service.createVpc(REGION, "10.79.0.0/16", false).getVpcId();
String subnetId = service.createSubnet(REGION, vpcId, "10.79.1.0/24", "us-east-1a").getSubnetId();
String otherSubnet = service.createSubnet(REGION, vpcId, "10.79.2.0/24", "us-east-1a").getSubnetId();
String group = service.createSecurityGroup(REGION, "eice-sg", "x", vpcId).getGroupId();
InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(REGION, subnetId, List.of(group),
null, null, List.of(), null);
String eniId = endpoint.getNetworkInterfaceIds().get(0);
NetworkInterface ni = service.describeNetworkInterfaces(REGION, List.of(eniId), Map.of())
.networkInterfaces().get(0);
assertEquals(eniId, ni.getNetworkInterfaceId());
assertEquals(subnetId, ni.getSubnetId());
assertEquals(vpcId, ni.getVpcId());
assertEquals("us-east-1a", ni.getAvailabilityZone());
assertEquals(endpoint.getPrivateIpAddress(), ni.getPrivateIpAddress());
assertEquals(List.of(group), ni.getGroups().stream().map(GroupIdentifier::getGroupId).toList());
assertEquals(List.of("eice-sg"), ni.getGroups().stream().map(GroupIdentifier::getGroupName).toList());
assertTrue(ni.isRequesterManaged());
assertEquals("ec2_instance_connect_endpoint", ni.getInterfaceType());
assertEquals("EC2 Instance Connect Endpoint " + endpoint.getInstanceConnectEndpointId(), ni.getDescription());
// Filters see it the way they see any other interface, and only once.
assertEquals(List.of(eniId), service.describeNetworkInterfaces(REGION, List.of(),
Map.of("subnet-id", List.of(subnetId))).networkInterfaces().stream()
.map(NetworkInterface::getNetworkInterfaceId).toList());
assertEquals(List.of(eniId), service.describeNetworkInterfaces(REGION, List.of(),
Map.of("interface-type", List.of("ec2_instance_connect_endpoint"), "group-id", List.of(group)))
.networkInterfaces().stream().map(NetworkInterface::getNetworkInterfaceId).toList());
assertTrue(service.describeNetworkInterfaces(REGION, List.of(), Map.of("subnet-id", List.of(otherSubnet)))
.networkInterfaces().isEmpty());
// A tag on the interface is the interface's own and goes with it.
service.createTags(REGION, List.of(eniId), List.of(new Tag("Role", "eice")));
assertEquals(List.of("Role"), service.describeNetworkInterfaces(REGION, List.of(eniId), Map.of())
.networkInterfaces().get(0).getTagSet().stream().map(Tag::getKey).toList());
service.deleteInstanceConnectEndpoint(REGION, endpoint.getInstanceConnectEndpointId());
assertTrue(service.describeTags(REGION, Map.of("resource-id", List.of(eniId))).isEmpty());
assertEquals("InvalidNetworkInterfaceID.NotFound", assertThrows(AwsException.class, () -> service
.describeNetworkInterfaces(REGION, List.of(eniId), Map.of())).getErrorCode());
}
}
@@ -4918,6 +4918,47 @@ class Ec2ServiceTest {
false, null, null, null, false, privateIp);
}
@Test
void anInstanceConnectEndpointInterfaceNamesItsGroupsForTheAccountItIsReadFor() {
// The explicit-account DescribeNetworkInterfaces overload runs under whatever account the
// ambient request carries; the group names must come from the account named, not that one.
RequestContext context = new RequestContext();
Ec2Service service = mockedVpcNetworkService(context, Map.of(), null);
context.setAccountId("111122223333");
String vpcId = service.createVpc("us-east-1", "10.82.0.0/16", false).getVpcId();
String subnetId = service.createSubnet("us-east-1", vpcId, "10.82.1.0/24", "us-east-1a").getSubnetId();
String group = service.createSecurityGroup("us-east-1", "eice-sg", "x", vpcId).getGroupId();
String eniId = service.createInstanceConnectEndpoint("us-east-1", subnetId, List.of(group), null, null,
List.of(), null).getNetworkInterfaceIds().getFirst();
context.setAccountId("000000000000");
NetworkInterface ni = service.describeNetworkInterfaces("111122223333", "us-east-1", List.of(eniId),
Map.of()).networkInterfaces().getFirst();
assertEquals(List.of(Map.entry(group, "eice-sg")), ni.getGroups().stream()
.map(g -> Map.entry(g.getGroupId(), String.valueOf(g.getGroupName()))).toList());
}
@Test
void anotherAccountDoesNotSeeAnInstanceConnectEndpointsInterface() {
RequestContext context = new RequestContext();
Ec2Service service = mockedVpcNetworkService(context, Map.of(), null);
context.setAccountId("111122223333");
String vpcId = service.createVpc("us-east-1", "10.83.0.0/16", false).getVpcId();
String subnetId = service.createSubnet("us-east-1", vpcId, "10.83.1.0/24", "us-east-1a").getSubnetId();
String eniId = service.createInstanceConnectEndpoint("us-east-1", subnetId, List.of(), null, null,
List.of(), null).getNetworkInterfaceIds().getFirst();
context.setAccountId("444455556666");
assertEquals("InvalidNetworkInterfaceID.NotFound", assertThrows(AwsException.class, () -> service
.describeNetworkInterfaces("us-east-1", List.of(eniId), Map.of())).getErrorCode());
assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(), Map.of()).networkInterfaces().stream()
.noneMatch(ni -> eniId.equals(ni.getNetworkInterfaceId())));
context.setAccountId("111122223333");
assertEquals(eniId, service.describeNetworkInterfaces("us-east-1", List.of(eniId), Map.of())
.networkInterfaces().getFirst().getNetworkInterfaceId());
}
private static Ec2Service realVpcNetworkService(RequestContext context) {
return realVpcNetworkService(context, Map.of());
}
@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.testing;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.ec2.AmiImageResolver;
import io.github.hectorvent.floci.services.ec2.Ec2ContainerManager;
import io.github.hectorvent.floci.services.ec2.Ec2ImageCatalog;
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* A mock-mode {@link Ec2Service} over in-memory storage for account 000000000000, for unit tests
* that drive the service directly: containers, port forwarding and images are mocks, so nothing
* leaves the JVM.
*/
public final class Ec2ServiceFixtures {
public static final String ACCOUNT = "000000000000";
private Ec2ServiceFixtures() {
}
public static Ec2Service mockModeService() {
return mockModeService(new InMemoryStorageFactory(ACCOUNT));
}
/** Over {@code storage}, for a test that builds a second service on the same stores. */
public static Ec2Service mockModeService(InMemoryStorageFactory storage) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.Ec2ServiceConfig ec2 = mock(EmulatorConfig.Ec2ServiceConfig.class);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
when(config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2);
when(ec2.mock()).thenReturn(true);
return new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
storage);
}
}