feat(ec2): expose synthesized cluster node instances to the EC2 service (#4262)

* feat(ec2): expose synthesized cluster node instances to the EC2 service

* fix(ec2): enforce account isolation and tag persistence for cluster node instances

* fix(ec2): scope findInstanceById to caller account for external instances

Scope findInstanceById to the caller account when falling back to
external instances instead of matching across all accounts. Thread
the account identifier into SSM direct command execution, ELBv2 target
resolution, and classic ELB health checking so external cluster nodes
remain strictly account-isolated across all instance lookup paths.

* fix(ssm,eks): update test stubs for account-scoped direct execution and harden cluster provider
This commit is contained in:
Simone Primarosa authored and GitHub committed 2026-09-24 08:27:52 -04:00
1 parent bf894376e4
commit 876ddc7422
18 files changed
+1060 -57

No files matched your search

@@ -3,8 +3,10 @@ package io.github.hectorvent.floci.services.ec2;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import java.util.ArrayList;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import io.github.hectorvent.floci.services.ec2.model.Address;
import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
@@ -29,6 +31,7 @@ import io.github.hectorvent.floci.services.ec2.model.IpPermission;
import io.github.hectorvent.floci.services.ec2.model.IpRange;
import io.github.hectorvent.floci.services.ec2.model.PrefixListEntry;
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
import io.github.hectorvent.floci.services.ec2.model.Placement;
import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.Snapshot;
@@ -4303,14 +4306,25 @@ class Ec2ServiceTest {
private static final class InMemoryStorageFactory extends StorageFactory {
private final Map<String, AccountAwareStorageBackend<?>> overrides;
private final jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance;
private InMemoryStorageFactory() {
this(Map.of());
this(Map.of(), null);
}
private InMemoryStorageFactory(jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance) {
this(Map.of(), requestContextInstance);
}
private InMemoryStorageFactory(Map<String, AccountAwareStorageBackend<?>> overrides) {
this(overrides, null);
}
private InMemoryStorageFactory(Map<String, AccountAwareStorageBackend<?>> overrides,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance) {
super(null, null);
this.overrides = overrides;
this.requestContextInstance = requestContextInstance;
}
@Override
@@ -4321,6 +4335,10 @@ class Ec2ServiceTest {
if (override != null) {
return (AccountAwareStorageBackend<V>) override;
}
if (requestContextInstance != null) {
return new AccountAwareStorageBackend<>(new io.github.hectorvent.floci.core.storage.InMemoryStorage<>(),
requestContextInstance, "000000000000");
}
return AccountAwareStorageBackend.inMemory("000000000000");
}
}
@@ -4386,4 +4404,353 @@ class Ec2ServiceTest {
return copy;
}
}
@Test
void attachVolumeResolvesClusterNodeInstance() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
Instance nodeInstance = new Instance();
nodeInstance.setInstanceId("i-node1234567890abc");
nodeInstance.setRegion("us-east-1");
nodeInstance.setPlacement(new Placement("us-east-1a"));
nodeInstance.setState(InstanceState.running());
nodeInstance.setInstanceType("m5.large");
nodeInstance.setTags(List.of(new Tag("Name", "test-cluster-node")));
service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() {
@Override
public Optional<Instance> findInstance(String accountId, String region, String instanceId) {
return "i-node1234567890abc".equals(instanceId) && ("us-east-1".equals(region) || region == null)
? Optional.of(nodeInstance) : Optional.empty();
}
@Override
public List<Instance> listInstances(String accountId, String region) {
return "us-east-1".equals(region) || region == null ? List.of(nodeInstance) : List.of();
}
});
Volume vol = service.createVolume("us-east-1", "us-east-1a", "gp3", 10, false, 3000, null, null, List.of());
VolumeAttachment att = service.attachVolume("us-east-1", vol.getVolumeId(), nodeInstance.getInstanceId(), "/dev/xvdf");
assertEquals(vol.getVolumeId(), att.getVolumeId());
assertEquals(nodeInstance.getInstanceId(), att.getInstanceId());
assertEquals("attached", att.getState());
VolumeAttachment detached = service.detachVolume("us-east-1", vol.getVolumeId(), nodeInstance.getInstanceId(), "/dev/xvdf", false);
assertEquals("detached", detached.getState());
}
@Test
void describeInstancesIncludesClusterNodeInstancesWithPlacementTypeAndFilters() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
Instance nodeInstance = new Instance();
nodeInstance.setInstanceId("i-node1234567890abc");
nodeInstance.setRegion("us-east-1");
nodeInstance.setPlacement(new Placement("us-east-1a"));
nodeInstance.setState(InstanceState.running());
nodeInstance.setInstanceType("m5.large");
nodeInstance.setTags(List.of(new Tag("Name", "test-cluster-node")));
service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() {
@Override
public Optional<Instance> findInstance(String accountId, String region, String instanceId) {
return "i-node1234567890abc".equals(instanceId) && ("us-east-1".equals(region) || region == null)
? Optional.of(nodeInstance) : Optional.empty();
}
@Override
public List<Instance> listInstances(String accountId, String region) {
return "us-east-1".equals(region) || region == null ? List.of(nodeInstance) : List.of();
}
});
List<Reservation> reservations = service.describeInstances("us-east-1", List.of(), Map.of());
assertEquals(1, reservations.size());
Instance inst = reservations.getFirst().getInstances().getFirst();
assertEquals("i-node1234567890abc", inst.getInstanceId());
assertEquals("m5.large", inst.getInstanceType());
assertEquals("us-east-1a", inst.getPlacement().getAvailabilityZone());
List<Reservation> byId = service.describeInstances("us-east-1", List.of("i-node1234567890abc"), Map.of());
assertEquals(1, byId.size());
List<Reservation> filtered = service.describeInstances("us-east-1", List.of(), Map.of("instance-type", List.of("m5.large")));
assertEquals(1, filtered.size());
List<Reservation> nonMatching = service.describeInstances("us-east-1", List.of(), Map.of("instance-type", List.of("c5.large")));
assertTrue(nonMatching.isEmpty());
List<Instance> statuses = service.describeInstanceStatus("us-east-1", List.of());
assertEquals(1, statuses.size());
assertEquals("i-node1234567890abc", statuses.getFirst().getInstanceId());
Instance foundById = service.findInstanceById("i-node1234567890abc");
assertNotNull(foundById);
assertEquals("i-node1234567890abc", foundById.getInstanceId());
}
@Test
void clusterNodeInstanceLifecycleActionsRejected() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
Instance nodeInstance = new Instance();
nodeInstance.setInstanceId("i-node1234567890abc");
nodeInstance.setRegion("us-east-1");
nodeInstance.setPlacement(new Placement("us-east-1a"));
nodeInstance.setState(InstanceState.running());
nodeInstance.setInstanceType("m5.large");
service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() {
@Override
public Optional<Instance> findInstance(String accountId, String region, String instanceId) {
return "i-node1234567890abc".equals(instanceId) && ("us-east-1".equals(region) || region == null)
? Optional.of(nodeInstance) : Optional.empty();
}
@Override
public List<Instance> listInstances(String accountId, String region) {
return "us-east-1".equals(region) || region == null ? List.of(nodeInstance) : List.of();
}
});
AwsException terminateEx = assertThrows(AwsException.class, () ->
service.terminateInstances("us-east-1", List.of("i-node1234567890abc")));
assertEquals("OperationNotPermitted", terminateEx.getErrorCode());
assertEquals(400, terminateEx.getHttpStatus());
AwsException stopEx = assertThrows(AwsException.class, () ->
service.stopInstances("us-east-1", List.of("i-node1234567890abc")));
assertEquals("OperationNotPermitted", stopEx.getErrorCode());
assertEquals(400, stopEx.getHttpStatus());
AwsException startEx = assertThrows(AwsException.class, () ->
service.startInstances("us-east-1", List.of("i-node1234567890abc")));
assertEquals("OperationNotPermitted", startEx.getErrorCode());
assertEquals(400, startEx.getHttpStatus());
AwsException rebootEx = assertThrows(AwsException.class, () ->
service.rebootInstances("us-east-1", List.of("i-node1234567890abc")));
assertEquals("OperationNotPermitted", rebootEx.getErrorCode());
assertEquals(400, rebootEx.getHttpStatus());
}
@Test
void ordinaryEc2InstancesUnaffectedByClusterNodeInstanceProvider() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
Instance nodeInstance = new Instance();
nodeInstance.setInstanceId("i-node1234567890abc");
nodeInstance.setRegion("us-east-1");
nodeInstance.setPlacement(new Placement("us-east-1a"));
nodeInstance.setState(InstanceState.running());
service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() {
@Override
public Optional<Instance> findInstance(String accountId, String region, String instanceId) {
return "i-node1234567890abc".equals(instanceId) ? Optional.of(nodeInstance) : Optional.empty();
}
@Override
public List<Instance> listInstances(String accountId, String region) {
return List.of(nodeInstance);
}
});
Reservation reservation = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), null, null, List.of(), null, null);
String ordinaryId = reservation.getInstances().getFirst().getInstanceId();
List<Map<String, String>> stopped = service.stopInstances("us-east-1", List.of(ordinaryId));
assertEquals("stopping", stopped.getFirst().get("currentState"));
List<Map<String, String>> started = service.startInstances("us-east-1", List.of(ordinaryId));
assertEquals("pending", started.getFirst().get("currentState"));
List<Map<String, String>> terminated = service.terminateInstances("us-east-1", List.of(ordinaryId));
assertEquals("shutting-down", terminated.getFirst().get("currentState"));
}
@Test
void clusterNodeInstanceGoneWhenProviderClearsIt() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
Instance nodeInstance = new Instance();
nodeInstance.setInstanceId("i-node1234567890abc");
nodeInstance.setRegion("us-east-1");
nodeInstance.setPlacement(new Placement("us-east-1a"));
nodeInstance.setState(InstanceState.running());
service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() {
@Override
public Optional<Instance> findInstance(String accountId, String region, String instanceId) {
return "i-node1234567890abc".equals(instanceId) ? Optional.of(nodeInstance) : Optional.empty();
}
@Override
public List<Instance> listInstances(String accountId, String region) {
return List.of(nodeInstance);
}
});
assertEquals(1, service.describeInstances("us-east-1", List.of(), Map.of()).size());
service.setClusterNodeInstanceProvider(null);
assertTrue(service.describeInstances("us-east-1", List.of(), Map.of()).isEmpty());
AwsException error = assertThrows(AwsException.class, () ->
service.describeInstances("us-east-1", List.of("i-node1234567890abc"), Map.of()));
assertEquals("InvalidInstanceID.NotFound", error.getErrorCode());
}
@Test
void clusterNodeInstancesIsolatedByAccount() {
String accountA = "111122223333";
String accountB = "444455556666";
Instance nodeInstance = new Instance();
nodeInstance.setInstanceId("i-node1234567890abc");
nodeInstance.setRegion("us-east-1");
nodeInstance.setPlacement(new Placement("us-east-1a"));
nodeInstance.setState(InstanceState.running());
nodeInstance.setInstanceType("m5.large");
ClusterNodeInstanceProvider provider = new ClusterNodeInstanceProvider() {
@Override
public Optional<Instance> findInstance(String accountId, String region, String instanceId) {
if (accountA.equals(accountId) && "i-node1234567890abc".equals(instanceId)) {
return Optional.of(nodeInstance);
}
return Optional.empty();
}
@Override
public List<Instance> listInstances(String accountId, String region) {
if (accountA.equals(accountId)) {
return List.of(nodeInstance);
}
return List.of();
}
};
@SuppressWarnings("unchecked")
jakarta.enterprise.inject.Instance<RequestContext> reqCtxInstance = mock(jakarta.enterprise.inject.Instance.class);
RequestContext reqCtx = new RequestContext();
when(reqCtxInstance.isResolvable()).thenReturn(true);
when(reqCtxInstance.get()).thenReturn(reqCtx);
InMemoryStorageFactory storageFactory = new InMemoryStorageFactory(reqCtxInstance);
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), storageFactory, reqCtxInstance);
service.setClusterNodeInstanceProvider(provider);
// Under account A, instance is visible
reqCtx.setAccountId(accountA);
List<Reservation> resA = service.describeInstances("us-east-1", List.of(), Map.of());
assertEquals(1, resA.size());
assertEquals("i-node1234567890abc", resA.getFirst().getInstances().getFirst().getInstanceId());
// Under account B, instance is not visible
reqCtx.setAccountId(accountB);
List<Reservation> resB = service.describeInstances("us-east-1", List.of(), Map.of());
assertTrue(resB.isEmpty());
AwsException notFoundB = assertThrows(AwsException.class, () ->
service.describeInstances("us-east-1", List.of("i-node1234567890abc"), Map.of()));
assertEquals("InvalidInstanceID.NotFound", notFoundB.getErrorCode());
// findInstanceForAccount respects account argument
assertTrue(service.findInstanceForAccount(accountA, "us-east-1", "i-node1234567890abc").isPresent());
assertTrue(service.findInstanceForAccount(accountB, "us-east-1", "i-node1234567890abc").isEmpty());
// findInstanceById respects callerAccountId and explicit account argument
assertNull(service.findInstanceById("i-node1234567890abc"));
assertNull(service.findInstanceById(accountB, "i-node1234567890abc"));
assertNotNull(service.findInstanceById(accountA, "i-node1234567890abc"));
reqCtx.setAccountId(accountA);
assertNotNull(service.findInstanceById("i-node1234567890abc"));
}
@Test
void clusterNodeInstanceTaggingIsolatedAndDoesNotMutateProvider() {
String accountA = "111122223333";
Instance nodeInstance = new Instance();
nodeInstance.setInstanceId("i-node1234567890abc");
nodeInstance.setRegion("us-east-1");
nodeInstance.setPlacement(new Placement("us-east-1a"));
nodeInstance.setState(InstanceState.running());
nodeInstance.setInstanceType("m5.large");
List<Tag> originalTags = new ArrayList<>(List.of(new Tag("Name", "test-cluster-node")));
nodeInstance.setTags(originalTags);
ClusterNodeInstanceProvider provider = new ClusterNodeInstanceProvider() {
@Override
public Optional<Instance> findInstance(String accountId, String region, String instanceId) {
if (accountA.equals(accountId) && "i-node1234567890abc".equals(instanceId)) {
return Optional.of(nodeInstance);
}
return Optional.empty();
}
@Override
public List<Instance> listInstances(String accountId, String region) {
if (accountA.equals(accountId)) {
return List.of(nodeInstance);
}
return List.of();
}
};
@SuppressWarnings("unchecked")
jakarta.enterprise.inject.Instance<RequestContext> reqCtxInstance = mock(jakarta.enterprise.inject.Instance.class);
RequestContext reqCtx = new RequestContext();
reqCtx.setAccountId(accountA);
when(reqCtxInstance.isResolvable()).thenReturn(true);
when(reqCtxInstance.get()).thenReturn(reqCtx);
InMemoryStorageFactory storageFactory = new InMemoryStorageFactory(reqCtxInstance);
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), storageFactory, reqCtxInstance);
service.setClusterNodeInstanceProvider(provider);
// Before any custom tags are added, describeTags includes default tags
List<Map<String, String>> initialTags = service.describeTags("us-east-1", Map.of("resource-id", List.of("i-node1234567890abc")));
assertEquals(1, initialTags.size());
assertEquals("Name", initialTags.getFirst().get("key"));
assertEquals("test-cluster-node", initialTags.getFirst().get("value"));
// Create tags on the node instance
service.createTags("us-east-1", List.of("i-node1234567890abc"), List.of(new Tag("Environment", "production")));
// Provider's underlying object must NOT be mutated
assertEquals(1, nodeInstance.getTags().size());
assertEquals("Name", nodeInstance.getTags().getFirst().getKey());
// EC2 service returns defensive copy with new tag merged
List<Reservation> reservations = service.describeInstances("us-east-1", List.of("i-node1234567890abc"), Map.of());
Instance queried = reservations.getFirst().getInstances().getFirst();
assertTrue(queried.getTags().stream().anyMatch(t -> "Environment".equals(t.getKey()) && "production".equals(t.getValue())));
assertTrue(queried.getTags().stream().anyMatch(t -> "Name".equals(t.getKey()) && "test-cluster-node".equals(t.getValue())));
// DescribeTags now returns both tags
List<Map<String, String>> updatedTags = service.describeTags("us-east-1", Map.of("resource-id", List.of("i-node1234567890abc")));
assertEquals(2, updatedTags.size());
// Delete tag
service.deleteTags("us-east-1", List.of("i-node1234567890abc"), List.of(new Tag("Environment", "production")));
List<Map<String, String>> finalTags = service.describeTags("us-east-1", Map.of("resource-id", List.of("i-node1234567890abc")));
assertEquals(1, finalTags.size());
assertEquals("Name", finalTags.getFirst().get("key"));
// Provider remains untouched
assertEquals(1, nodeInstance.getTags().size());
}
}
@@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey;
import io.github.hectorvent.floci.services.eks.model.LogSetup;
import io.github.hectorvent.floci.services.eks.model.Logging;
import io.github.hectorvent.floci.services.eks.model.OidcIdentity;
import io.github.hectorvent.floci.services.eks.model.ResourcesVpcConfig;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -933,6 +934,54 @@ class EksClusterManagerTest {
assertNull(manager.getRegisteredClusterNodeInstance(cluster));
}
@Test
void registerClusterNodeInstanceRegistersWithoutImds() {
Cluster cluster = new Cluster();
cluster.setName("no-imds-cluster");
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
vpcConfig.setVpcId("vpc-12345678");
vpcConfig.setSubnetIds(List.of("subnet-87654321"));
cluster.setResourcesVpcConfig(vpcConfig);
manager.registerClusterNodeInstance(cluster, "container-no-imds");
Instance instance = manager.getRegisteredClusterNodeInstance(cluster);
assertNotNull(instance);
assertEquals("vpc-12345678", instance.getVpcId());
assertEquals("subnet-87654321", instance.getSubnetId());
assertNotNull(instance.getLaunchTime());
assertTrue(instance.getTags().stream().anyMatch(t -> "Name".equals(t.getKey()) && "no-imds-cluster-node".equals(t.getValue())));
assertTrue(instance.getTags().stream().anyMatch(t -> "kubernetes.io/cluster/no-imds-cluster".equals(t.getKey()) && "owned".equals(t.getValue())));
assertTrue(instance.getTags().stream().anyMatch(t -> "eks:cluster-name".equals(t.getKey()) && "no-imds-cluster".equals(t.getValue())));
}
@Test
void clusterNodeInstanceProviderFindsAndListsRegisteredInstances() {
Cluster cluster = new Cluster();
cluster.setName("prov-cluster");
cluster.setArn("arn:aws:eks:us-east-1:123456789012:cluster/prov-cluster");
manager.registerClusterNodeInstance(cluster, "container-prov");
Instance registered = manager.getRegisteredClusterNodeInstance(cluster);
assertNotNull(registered);
assertTrue(manager.findInstance("123456789012", "us-east-1", registered.getInstanceId()).isPresent());
assertEquals(registered.getInstanceId(), manager.findInstance("123456789012", "us-east-1", registered.getInstanceId()).get().getInstanceId());
assertTrue(manager.findInstance(null, null, registered.getInstanceId()).isEmpty());
assertTrue(manager.findInstance("123456789012", null, registered.getInstanceId()).isPresent());
assertTrue(manager.findInstance("999999999999", "us-east-1", registered.getInstanceId()).isEmpty());
assertTrue(manager.findInstance("123456789012", "eu-central-1", registered.getInstanceId()).isEmpty());
List<Instance> eastInstances = manager.listInstances("123456789012", "us-east-1");
assertTrue(eastInstances.stream().anyMatch(i -> registered.getInstanceId().equals(i.getInstanceId())));
assertTrue(manager.listInstances(null, "us-east-1").isEmpty());
assertTrue(manager.listInstances("999999999999", "us-east-1").isEmpty());
assertTrue(manager.listInstances("123456789012", "eu-central-1").isEmpty());
manager.unregisterMetadataEndpoint(cluster);
assertTrue(manager.findInstance("123456789012", "us-east-1", registered.getInstanceId()).isEmpty());
assertTrue(manager.listInstances("123456789012", "us-east-1").isEmpty());
}
@Test
void failureToWireLogsAndDoesNotAbort() {
when(dockerClient.execCreateCmd(anyString())).thenThrow(new RuntimeException("docker exec failed"));
@@ -1240,7 +1289,7 @@ class EksClusterManagerTest {
assertFalse(cmd.stream().anyMatch(a -> a.contains("service-account-issuer")));
assertFalse(cmd.stream().anyMatch(a -> a.contains("api-audiences")));
verifyNoInteractions(dockerClient);
verify(dockerClient, never()).copyArchiveToContainerCmd(anyString());
assertFalse(Files.exists(tempDir.resolve("keys")));
}
@@ -0,0 +1,188 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
@QuarkusTest
class EksClusterNodeInstanceIntegrationTest {
@Inject
EksClusterManager eksClusterManager;
@Test
void clusterNodeInstancesAreExposedThroughEc2QueryApi() {
String account = "123456789012";
String clusterName = "node-exp-" + UUID.randomUUID().toString().substring(0, 8);
Cluster cluster = new Cluster();
cluster.setName(clusterName);
cluster.setArn("arn:aws:eks:us-east-1:" + account + ":cluster/" + clusterName);
eksClusterManager.registerClusterNodeInstance(cluster, "mock-container-id");
Instance nodeInstance = eksClusterManager.getRegisteredClusterNodeInstance(cluster);
String nodeId = nodeInstance.getInstanceId();
try {
// DescribeInstances resolves external cluster node instance
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "DescribeInstances")
.post("/")
.then()
.statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId",
equalTo(nodeId))
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name",
equalTo("running"))
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceType",
equalTo("m5.large"));
// DescribeInstances with InstanceId filter
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", nodeId)
.post("/")
.then()
.statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId",
equalTo(nodeId));
// DescribeInstanceStatus includes running cluster node instance
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "DescribeInstanceStatus")
.formParam("InstanceId.1", nodeId)
.post("/")
.then()
.statusCode(200)
.body("DescribeInstanceStatusResponse.instanceStatusSet.item.instanceId",
equalTo(nodeId));
// AttachVolume succeeds against cluster node instance
String volumeId = given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "CreateVolume")
.formParam("AvailabilityZone", "us-east-1a")
.formParam("Size", "10")
.formParam("VolumeType", "gp3")
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVolumeResponse.volumeId");
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "AttachVolume")
.formParam("VolumeId", volumeId)
.formParam("InstanceId", nodeId)
.formParam("Device", "/dev/xvdf")
.post("/")
.then()
.statusCode(200)
.body("AttachVolumeResponse.status", equalTo("attaching"));
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "DetachVolume")
.formParam("VolumeId", volumeId)
.formParam("InstanceId", nodeId)
.formParam("Device", "/dev/xvdf")
.post("/")
.then()
.statusCode(200)
.body("DetachVolumeResponse.status", equalTo("detaching"));
// Lifecycle actions are rejected with OperationNotPermitted
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "TerminateInstances")
.formParam("InstanceId.1", nodeId)
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("OperationNotPermitted"));
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "StopInstances")
.formParam("InstanceId.1", nodeId)
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("OperationNotPermitted"));
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "StartInstances")
.formParam("InstanceId.1", nodeId)
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("OperationNotPermitted"));
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "RebootInstances")
.formParam("InstanceId.1", nodeId)
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("OperationNotPermitted"));
// Cross-account isolation: another account cannot see or query the instance
String otherAccount = "999999999999";
given().header("Authorization", auth(otherAccount, "ec2"))
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", nodeId)
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound"));
// Tagging the node instance works through EC2 and is visible in DescribeTags
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "CreateTags")
.formParam("ResourceId.1", nodeId)
.formParam("Tag.1.Key", "Environment")
.formParam("Tag.1.Value", "stage")
.post("/")
.then()
.statusCode(200);
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "DescribeTags")
.formParam("Filter.1.Name", "resource-id")
.formParam("Filter.1.Value.1", nodeId)
.post("/")
.then()
.statusCode(200)
.body("DescribeTagsResponse.tagSet.item.key", hasItem("Environment"))
.body("DescribeTagsResponse.tagSet.item.key", hasItem("eks:cluster-name"));
// Other account does not see the instance's tags in DescribeTags
given().header("Authorization", auth(otherAccount, "ec2"))
.formParam("Action", "DescribeTags")
.formParam("Filter.1.Name", "resource-id")
.formParam("Filter.1.Value.1", nodeId)
.post("/")
.then()
.statusCode(200)
.body("DescribeTagsResponse.tagSet", equalTo(""));
} finally {
eksClusterManager.unregisterMetadataEndpoint(cluster);
}
// After unregistering, node instance disappears from EC2
given().header("Authorization", auth(account, "ec2"))
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", nodeId)
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound"));
}
private static String auth(String account, String service) {
return "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260917/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc";
}
}
@@ -33,6 +33,23 @@ class ElbV2TargetResolverTest {
assertEquals("172.18.0.42", ElbV2TargetResolver.resolveHost(ec2Service, targetGroup, target));
}
@Test
void instanceTargetPassesTargetGroupAccountIdToEc2Service() {
Ec2Service ec2Service = mock(Ec2Service.class);
Instance instance = new Instance();
instance.setInstanceId("i-1234567890abcdef0");
instance.setContainerBridgeIp("172.18.0.42");
when(ec2Service.findInstanceById("111122223333", "i-1234567890abcdef0")).thenReturn(instance);
TargetGroup targetGroup = new TargetGroup();
targetGroup.setTargetGroupArn("arn:aws:elasticloadbalancing:us-east-1:111122223333:targetgroup/tg/123456");
targetGroup.setTargetType("instance");
TargetDescription target = new TargetDescription();
target.setId("i-1234567890abcdef0");
assertEquals("172.18.0.42", ElbV2TargetResolver.resolveHost(ec2Service, targetGroup, target));
}
@Test
void ipTargetKeepsRegisteredAddress() {
Ec2Service ec2Service = mock(Ec2Service.class);
@@ -72,8 +72,8 @@ class SsmCommandServiceDirectExecutionTest {
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
Instant start = Instant.parse("2026-06-07T00:00:00Z");
Instant end = Instant.parse("2026-06-07T00:00:01Z");
when(executor.supports(eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
"Success", "hello\n", "", 0, start, end)));
@@ -111,7 +111,7 @@ class SsmCommandServiceDirectExecutionTest {
@Test
void unsupportedDirectExecutionFallsBackToAgentQueue() throws Exception {
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
when(executor.supports(eq("i-agent"), eq("AWS-RunShellScript"))).thenReturn(false);
when(executor.supports(any(), eq("i-agent"), eq("AWS-RunShellScript"))).thenReturn(false);
SsmCommandService service = new SsmCommandService(
new InMemoryStorageFactory(),
@@ -140,7 +140,7 @@ class SsmCommandServiceDirectExecutionTest {
@Test
void unavailableInstanceFailsQueuedCommandInvocation() throws Exception {
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
when(executor.supports(eq("i-stale"), eq("AWS-RunShellScript"))).thenReturn(false);
when(executor.supports(any(), eq("i-stale"), eq("AWS-RunShellScript"))).thenReturn(false);
SsmCommandService service = new SsmCommandService(
new InMemoryStorageFactory(),
@@ -172,7 +172,7 @@ class SsmCommandServiceDirectExecutionTest {
@Test
void unavailableInstancesFailQueuedCommandInvocationsInBulk() throws Exception {
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
when(executor.supports(any(), eq("AWS-RunShellScript"))).thenReturn(false);
when(executor.supports(any(), any(), eq("AWS-RunShellScript"))).thenReturn(false);
SsmCommandService service = new SsmCommandService(
new InMemoryStorageFactory(),
@@ -207,8 +207,8 @@ class SsmCommandServiceDirectExecutionTest {
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
Instant start = Instant.parse("2026-06-07T00:00:00Z");
Instant end = Instant.parse("2026-06-07T00:00:30Z");
when(executor.supports(eq("i-timeout"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(eq("i-timeout"), eq("AWS-RunShellScript"), any(), eq(30)))
when(executor.supports(any(), eq("i-timeout"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(any(), eq("i-timeout"), eq("AWS-RunShellScript"), any(), eq(30)))
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
"TimedOut", "", "Timed out after 30s", -1, start, end)));
@@ -259,8 +259,8 @@ class SsmCommandServiceDirectExecutionTest {
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
Instant start = Instant.parse("2026-06-07T00:00:00Z");
Instant end = Instant.parse("2026-06-07T00:00:01Z");
when(executor.supports(eq("i-race"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(eq("i-race"), eq("AWS-RunShellScript"), any(), eq(60)))
when(executor.supports(any(), eq("i-race"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(any(), eq("i-race"), eq("AWS-RunShellScript"), any(), eq(60)))
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
"Success", "done\n", "", 0, start, end)));
@@ -335,8 +335,8 @@ class SsmCommandServiceDirectExecutionTest {
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
Instant start = Instant.parse("2026-06-07T00:00:00Z");
Instant end = Instant.parse("2026-06-07T00:00:01Z");
when(executor.supports(eq("i-race"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(eq("i-race"), eq("AWS-RunShellScript"), any(), eq(60)))
when(executor.supports(any(), eq("i-race"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(any(), eq("i-race"), eq("AWS-RunShellScript"), any(), eq(60)))
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
"Success", "done\n", "", 0, start, end)));
@@ -426,8 +426,8 @@ class SsmCommandServiceDirectExecutionTest {
for (int i = 0; i < instanceCount; i++) {
String instanceId = "i-" + i;
instanceIds.add(instanceId);
when(executor.supports(eq(instanceId), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(eq(instanceId), eq("AWS-RunShellScript"), any(), eq(60)))
when(executor.supports(any(), eq(instanceId), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(any(), eq(instanceId), eq("AWS-RunShellScript"), any(), eq(60)))
.thenAnswer(invocation -> {
barrier.await(5, TimeUnit.SECONDS);
return Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
@@ -460,9 +460,9 @@ class SsmCommandServiceDirectExecutionTest {
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
Instant start = Instant.parse("2026-06-07T00:00:00Z");
Instant end = Instant.parse("2026-06-07T00:00:01Z");
when(executor.supports(eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.supports(eq("i-agent"), eq("AWS-RunShellScript"))).thenReturn(false);
when(executor.executeIfSupported(eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.supports(any(), eq("i-agent"), eq("AWS-RunShellScript"))).thenReturn(false);
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
"Success", "done\n", "", 0, start, end)));
@@ -503,8 +503,8 @@ class SsmCommandServiceDirectExecutionTest {
CountDownLatch release = new CountDownLatch(1);
Instant start = Instant.parse("2026-06-07T00:00:00Z");
Instant end = Instant.parse("2026-06-07T00:00:01Z");
when(executor.supports(eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
.thenAnswer(invocation -> {
started.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
@@ -543,8 +543,8 @@ class SsmCommandServiceDirectExecutionTest {
@Test
void directExecutionThatBecomesUnsupportedFallsBackToAgentQueue() throws Exception {
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
when(executor.supports(eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
.thenReturn(Optional.empty());
SsmCommandService service = new SsmCommandService(
@@ -576,8 +576,8 @@ class SsmCommandServiceDirectExecutionTest {
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
String stdout = "o".repeat(24_010) + "tail";
String stderr = "e".repeat(8_010) + "tail";
when(executor.supports(eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
"Failed", stdout, stderr, 1, Instant.parse("2026-06-07T00:00:00Z"), Instant.parse("2026-06-07T00:00:01Z"))));
@@ -404,6 +404,19 @@ class SsmDirectCommandExecutorTest {
assertEquals("E".repeat(8_000), result.get().standardError());
}
@Test
void supportsPassesAccountIdToEc2Service() {
DockerClient dockerClient = mock(DockerClient.class);
Ec2Service ec2Service = mock(Ec2Service.class);
Instance instance = instance("i-container", "container-1");
when(ec2Service.findInstanceById("111122223333", "i-container")).thenReturn(instance);
when(ec2Service.isInstanceContainerRunning("111122223333", "i-container")).thenReturn(true);
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
assertTrue(executor.supports("111122223333", "i-container", "AWS-RunShellScript"));
assertFalse(executor.supports("444455556666", "i-container", "AWS-RunShellScript"));
}
private static Instance instance(String instanceId, String containerId) {
Instance instance = new Instance();
instance.setInstanceId(instanceId);
@@ -43,6 +43,8 @@ class SsmSendCommandIntegrationTest {
@BeforeEach
void resetDirectExecution() {
reset(directCommandExecutor);
when(directCommandExecutor.executeIfSupported(any(), anyString(), anyString(), any(), anyInt()))
.thenReturn(Optional.empty());
when(directCommandExecutor.executeIfSupported(anyString(), anyString(), any(), anyInt()))
.thenReturn(Optional.empty());
}
@@ -408,9 +410,10 @@ class SsmSendCommandIntegrationTest {
void sendCommandDirectlyExecutesForContainerBackedInstance() {
Instant start = Instant.parse("2026-06-07T00:00:00Z");
Instant end = Instant.parse("2026-06-07T00:00:01Z");
when(directCommandExecutor.supports(eq("i-direct-container"), eq("AWS-RunShellScript")))
when(directCommandExecutor.supports(any(), eq("i-direct-container"), eq("AWS-RunShellScript")))
.thenReturn(true);
when(directCommandExecutor.executeIfSupported(
any(),
eq("i-direct-container"),
eq("AWS-RunShellScript"),
any(),