Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Simone Primarosa876ddc74223d
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
index a582e2e428..3bf0bf836e 100644
--- a/docs/services/ec2.md
+++ b/docs/services/ec2.md
@@ -164,6 +164,14 @@ Registering a container with SSM is independent of this: an SSM agent that calls
To get a container that both answers IMDS (including instance profile credentials) and executes `SendCommand` directly, launch it with `RunInstances` first, then register that same container's SSM agent as a managed instance. Do not register an arbitrary or pre-existing container directly with SSM and expect IMDS to work. See [SSM](ssm.md#run-command-execution) for the SendCommand side of this.
+### Cluster Node Instances
+
+When an EKS cluster is running, its synthesized node instance is registered and visible through the EC2 service:
+
+- **Visibility**: Exposed via `DescribeInstances` and `DescribeInstanceStatus` with its synthesized instance ID (`i-...`), type (`m5.large`), running state, VPC, subnet, launch time, and cluster tags (`Name`, `kubernetes.io/cluster/<cluster-name>=owned`, `eks:cluster-name=<cluster-name>`). It can be queried by ID, filtered, or listed with other instances.
+- **Operations**: Supports volume attachments (`AttachVolume`, `DetachVolume`), instance attribute inspection and modification, and resource tagging (`CreateTags`, `DeleteTags`, `DescribeTags`).
+- **Lifecycle protection**: Lifecycle actions that would mutate or delete the node through EC2 (`TerminateInstances`, `StopInstances`, `StartInstances`, `RebootInstances`) are rejected with `OperationNotPermitted` (HTTP 400) as a Floci emulation limitation because the instance directly represents the underlying k3s cluster container. In real AWS, cluster node instances in an Auto Scaling group can be terminated or stopped and are subsequently replaced by the ASG. In Floci, the node instance lifecycle is managed solely through the EKS cluster lifecycle.
+
## Default Resources
Floci seeds the following resources on first use in each region so Terraform, the AWS CLI, and SDK clients work out of the box without any setup:
diff --git a/docs/services/eks.md b/docs/services/eks.md
index f18ff060db..bd8d7325c2 100644
--- a/docs/services/eks.md
+++ b/docs/services/eks.md
@@ -487,10 +487,11 @@ services:
```
## Instance Metadata Service (IMDS)
+The cluster container is registered as a synthesized EC2 instance node (type `m5.large`, image `ami-eks-k3s`) regardless of whether IMDS is enabled, making it visible to the EC2 service (`DescribeInstances`, `DescribeInstanceStatus`, volume attachments, tagging).
-When enabled (`FLOCI_SERVICES_EKS_IMDS=true`), each k3s cluster container exposes the AWS Instance Metadata Service on the link-local address `169.254.169.254:80`. Inside the container, Floci adds `169.254.169.254/32` to the loopback interface (`lo`) and runs a lightweight `socat` TCP relay forwarding metadata requests to Floci's IMDS server.
+When IMDS is enabled (`FLOCI_SERVICES_EKS_IMDS=true`), each k3s cluster container exposes the AWS Instance Metadata Service on the link-local address `169.254.169.254:80`. Inside the container, Floci adds `169.254.169.254/32` to the loopback interface (`lo`) and runs a lightweight `socat` TCP relay forwarding metadata requests to Floci's IMDS server.
-Both IMDSv1 and IMDSv2 (`PUT /latest/api/token`) are supported. The cluster container is registered as a synthesized EC2 instance node (type `m5.large`, image `ami-eks-k3s`) associated with the cluster's IAM role:
+Both IMDSv1 and IMDSv2 (`PUT /latest/api/token`) are supported. The cluster container is registered as a synthesized EC2 instance node associated with the cluster's IAM role:
```bash
# IMDSv2: obtain token
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/ClusterNodeInstanceProvider.java b/src/main/java/io/github/hectorvent/floci/services/ec2/ClusterNodeInstanceProvider.java
new file mode 100644
index 0000000000..6de169d789
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/ClusterNodeInstanceProvider.java
@@ -0,0 +1,35 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import io.github.hectorvent.floci.services.ec2.model.Instance;
+
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Supplies EC2 instances synthesized by external cluster management services (such as EKS cluster nodes).
+ *
+ * <p>Implemented by cluster management services; consumed lazily by {@code Ec2Service}
+ * via CDI {@code Instance<ClusterNodeInstanceProvider>} so EC2 never depends directly
+ * on EKS or other cluster management packages.</p>
+ */
+public interface ClusterNodeInstanceProvider {
+
+ /**
+ * Finds an external cluster node instance by account, region, and instance ID.
+ *
+ * @param accountId the AWS account ID (must not be {@code null})
+ * @param region the AWS region (or {@code null} to match any region)
+ * @param instanceId the EC2 instance ID
+ * @return the matching instance, or empty if not found
+ */
+ Optional<Instance> findInstance(String accountId, String region, String instanceId);
+
+ /**
+ * Lists external cluster node instances for the given account and region.
+ *
+ * @param accountId the AWS account ID (must not be {@code null})
+ * @param region the AWS region (or {@code null} for all regions)
+ * @return list of cluster node instances
+ */
+ List<Instance> listInstances(String accountId, String region);
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
index f8cf62e777..dacdef5648 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
@@ -227,8 +227,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
* delegating.
*/
private VpcNetworkManager vpcNetworkManager;
+ private jakarta.enterprise.inject.Instance<ClusterNodeInstanceProvider> clusterNodeInstanceProviders;
+ private ClusterNodeInstanceProvider testClusterNodeInstanceProvider;
- // Public, no request context — for callers (and tests) that construct this service directly
+ void setClusterNodeInstanceProvider(ClusterNodeInstanceProvider provider) {
+ this.testClusterNodeInstanceProvider = provider;
+ }
+
+ // Public, no request context - for callers (and tests) that construct this service directly
// without CDI. Caller-identity resolution falls back to the configured default account.
public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
Ec2PortForwardManager portForwardManager,
@@ -255,10 +261,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog, StorageFactory storageFactory,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,
- VpcNetworkManager vpcNetworkManager, IamService iamService) {
+ VpcNetworkManager vpcNetworkManager, IamService iamService,
+ jakarta.enterprise.inject.Instance<ClusterNodeInstanceProvider> clusterNodeInstanceProviders) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,
instanceTypeCatalog, storageFactory, requestContextInstance, iamService);
this.vpcNetworkManager = vpcNetworkManager;
+ this.clusterNodeInstanceProviders = clusterNodeInstanceProviders;
}
public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
@@ -3102,7 +3110,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
instances.put(key(i.getRegion(), i.getInstanceId()), i);
});
}
- List<Instance> matched = instances.scan(k -> true).stream()
+ List<Instance> all = new ArrayList<>(instances.scan(k -> true));
+ Set<String> seenIds = all.stream().map(Instance::getInstanceId).collect(Collectors.toSet());
+ for (Instance external : listExternalInstances(callerAccountId(), region)) {
+ if (seenIds.add(external.getInstanceId())) {
+ all.add(external);
+ }
+ }
+ List<Instance> matched = all.stream()
.filter(i -> i.getRegion().equals(region))
.filter(i -> instanceIds.isEmpty() || instanceIds.contains(i.getInstanceId()))
.filter(i -> matchesFilters(i, filters, region))
@@ -3134,6 +3149,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String owner = callerAccountId();
for (String id : instanceIds) {
Instance inst = getRequiredInstance(region, id);
+ if (isExternalInstance(region, id)) {
+ throw new AwsException("OperationNotPermitted",
+ "The instance '" + id + "' is a cluster node and cannot be terminated through EC2", 400);
+ }
if (config.services().ec2().mock() && "pending".equals(inst.getState().getName())) {
inst.setState(InstanceState.running());
@@ -3231,6 +3250,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
List<Map<String, String>> result = new ArrayList<>();
for (String id : instanceIds) {
Instance inst = getRequiredInstance(region, id);
+ if (isExternalInstance(region, id)) {
+ throw new AwsException("OperationNotPermitted",
+ "The instance '" + id + "' is a cluster node and cannot be stopped through EC2", 400);
+ }
if (config.services().ec2().mock() && "pending".equals(inst.getState().getName())) {
inst.setState(InstanceState.running());
@@ -3258,6 +3281,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
List<Map<String, String>> result = new ArrayList<>();
for (String id : instanceIds) {
Instance inst = getRequiredInstance(region, id);
+ if (isExternalInstance(region, id)) {
+ throw new AwsException("OperationNotPermitted",
+ "The instance '" + id + "' is a cluster node and cannot be started through EC2", 400);
+ }
if ("terminated".equals(inst.getState().getName())) {
throw new AwsException("IncorrectInstanceState",
@@ -3286,6 +3313,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
ensureDefaultResources(region);
for (String id : instanceIds) {
Instance inst = getRequiredInstance(region, id);
+ if (isExternalInstance(region, id)) {
+ throw new AwsException("OperationNotPermitted",
+ "The instance '" + id + "' is a cluster node and cannot be rebooted through EC2", 400);
+ }
if (!config.services().ec2().mock()) {
containerManager.reboot(inst);
@@ -3318,7 +3349,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
instances.put(key(i.getRegion(), i.getInstanceId()), i);
});
}
- return instances.scan(k -> true).stream()
+ List<Instance> all = new ArrayList<>(instances.scan(k -> true));
+ Set<String> seenIds = all.stream().map(Instance::getInstanceId).collect(Collectors.toSet());
+ for (Instance external : listExternalInstances(callerAccountId(), region)) {
+ if (seenIds.add(external.getInstanceId())) {
+ all.add(external);
+ }
+ }
+ return all.stream()
.filter(i -> i.getRegion().equals(region))
.filter(i -> instanceIds.isEmpty() || instanceIds.contains(i.getInstanceId()))
.filter(i -> "running".equals(i.getState().getName()))
@@ -3668,10 +3706,118 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
+ "Valid values are: standard, unlimited.", 400);
}
+ private List<Tag> getTagsForAccount(String accountId, String resourceId, List<Tag> fallback) {
+ String safeAccount = accountId != null ? accountId : callerAccountId();
+ Optional<List<Tag>> stored = tags instanceof AccountAwareStorageBackend<List<Tag>> aware
+ ? aware.getForAccount(safeAccount, resourceId)
+ : tags.get(resourceId);
+ return stored.orElse(fallback);
+ }
+
+ private Instance copyExternalInstance(String accountId, Instance source) {
+ if (source == null) {
+ return null;
+ }
+ Instance copy = new Instance();
+ copy.setInstanceId(source.getInstanceId());
+ copy.setImageId(source.getImageId());
+ copy.setState(source.getState());
+ copy.setStateTransitionReason(source.getStateTransitionReason());
+ copy.setInstanceType(source.getInstanceType());
+ copy.setPlacement(source.getPlacement());
+ copy.setSubnetId(source.getSubnetId());
+ copy.setVpcId(source.getVpcId());
+ copy.setPrivateIpAddress(source.getPrivateIpAddress());
+ copy.setLogicalPrivateIpAddress(source.getLogicalPrivateIpAddress());
+ copy.setPublicIpAddress(source.getPublicIpAddress());
+ copy.setPrivateDnsName(source.getPrivateDnsName());
+ copy.setPublicDnsName(source.getPublicDnsName());
+ copy.setAssociatePublicIp(source.isAssociatePublicIp());
+ copy.setKeyName(source.getKeyName());
+ copy.setArchitecture(source.getArchitecture());
+ copy.setHypervisor(source.getHypervisor());
+ copy.setVirtualizationType(source.getVirtualizationType());
+ copy.setRootDeviceName(source.getRootDeviceName());
+ copy.setRootDeviceType(source.getRootDeviceType());
+ copy.setLaunchTime(source.getLaunchTime());
+ copy.setAmiLaunchIndex(source.getAmiLaunchIndex());
+ copy.setClientToken(source.getClientToken());
+ copy.setMonitoring(source.getMonitoring());
+ copy.setSourceDestCheck(source.isSourceDestCheck());
+ copy.setEbsOptimized(source.isEbsOptimized());
+ copy.setEnaSupport(source.isEnaSupport());
+ copy.setIamInstanceProfileArn(source.getIamInstanceProfileArn());
+ copy.setIamInstanceProfileAssociationTime(source.getIamInstanceProfileAssociationTime());
+ copy.setStateReasonCode(source.getStateReasonCode());
+ copy.setStateReasonMessage(source.getStateReasonMessage());
+ copy.setRegion(source.getRegion());
+ copy.setRootVolumeId(source.getRootVolumeId());
+ copy.setDisableApiStop(source.isDisableApiStop());
+ copy.setDisableApiTermination(source.isDisableApiTermination());
+ copy.setMetadataOptions(source.getMetadataOptions());
+ copy.setCreditSpecificationCpuCredits(source.getCreditSpecificationCpuCredits());
+ if (source.getSecurityGroups() != null) {
+ copy.setSecurityGroups(new ArrayList<>(source.getSecurityGroups()));
+ }
+ if (source.getNetworkInterfaces() != null) {
+ copy.setNetworkInterfaces(new ArrayList<>(source.getNetworkInterfaces()));
+ }
+ List<Tag> effectiveTags = getTagsForAccount(accountId, source.getInstanceId(), source.getTags());
+ copy.setTags(effectiveTags != null ? new ArrayList<>(effectiveTags) : new ArrayList<>());
+ return copy;
+ }
+
+ private Optional<Instance> findExternalInstance(String accountId, String region, String instanceId) {
+ if (testClusterNodeInstanceProvider != null) {
+ return testClusterNodeInstanceProvider.findInstance(accountId, region, instanceId)
+ .map(inst -> copyExternalInstance(accountId, inst));
+ }
+ if (clusterNodeInstanceProviders == null || clusterNodeInstanceProviders.isUnsatisfied()) {
+ return Optional.empty();
+ }
+ for (ClusterNodeInstanceProvider provider : clusterNodeInstanceProviders) {
+ Optional<Instance> inst = provider.findInstance(accountId, region, instanceId);
+ if (inst.isPresent()) {
+ return inst.map(i -> copyExternalInstance(accountId, i));
+ }
+ }
+ return Optional.empty();
+ }
+
+ private List<Instance> listExternalInstances(String accountId, String region) {
+ if (testClusterNodeInstanceProvider != null) {
+ return testClusterNodeInstanceProvider.listInstances(accountId, region).stream()
+ .map(inst -> copyExternalInstance(accountId, inst))
+ .toList();
+ }
+ if (clusterNodeInstanceProviders == null || clusterNodeInstanceProviders.isUnsatisfied()) {
+ return List.of();
+ }
+ List<Instance> result = new ArrayList<>();
+ for (ClusterNodeInstanceProvider provider : clusterNodeInstanceProviders) {
+ List<Instance> list = provider.listInstances(accountId, region);
+ if (list != null && !list.isEmpty()) {
+ for (Instance inst : list) {
+ result.add(copyExternalInstance(accountId, inst));
+ }
+ }
+ }
+ return result;
+ }
+
+ private boolean isExternalInstance(String region, String instanceId) {
+ return instances.get(key(region, instanceId)).isEmpty()
+ && findExternalInstance(callerAccountId(), region, instanceId).isPresent();
+ }
+
private Instance getRequiredInstance(String region, String instanceId) {
Instance inst = instances.get(key(region, instanceId)).orElse(null);
- if (inst == null)
+ if (inst == null) {
+ inst = findExternalInstance(callerAccountId(), region, instanceId).orElse(null);
+ }
+ if (inst == null) {
throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + instanceId + "' does not exist", 400);
+ }
return inst;
}
@@ -5061,19 +5207,39 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
}
public Optional<Instance> findInstanceForAccount(String accountId, String region, String instanceId) {
- return instances instanceof AccountAwareStorageBackend<Instance> aware
+ Optional<Instance> found = instances instanceof AccountAwareStorageBackend<Instance> aware
? aware.getForAccount(accountId, key(region, instanceId)) : instances.get(key(region, instanceId));
+ if (found.isPresent()) {
+ return found;
+ }
+ return findExternalInstance(accountId, region, instanceId);
}
public Instance findInstanceById(String instanceId) {
- return instances.scan(k -> true).stream()
+ return findInstanceById(callerAccountId(), instanceId);
+ }
+
+ public Instance findInstanceById(String accountId, String instanceId) {
+ String safeAccount = accountId != null ? accountId : callerAccountId();
+ List<Instance> accountInstances = instances instanceof AccountAwareStorageBackend<Instance> aware
+ ? aware.scanForAccount(safeAccount, k -> true)
+ : instances.scan(k -> true);
+ Instance inst = accountInstances.stream()
.filter(i -> instanceId.equals(i.getInstanceId()))
.findFirst()
.orElse(null);
+ if (inst != null) {
+ return inst;
+ }
+ return findExternalInstance(safeAccount, null, instanceId).orElse(null);
}
public boolean isInstanceContainerRunning(String instanceId) {
- Instance instance = findInstanceById(instanceId);
+ return isInstanceContainerRunning(callerAccountId(), instanceId);
+ }
+
+ public boolean isInstanceContainerRunning(String accountId, String instanceId) {
+ Instance instance = findInstanceById(accountId, instanceId);
if (instance == null) {
return false;
}
@@ -6340,7 +6506,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
for (String resourceId : resourceIds) {
withTopologyLockIfNeeded(region, resourceId, () -> {
synchronized (lockFor(key(region, resourceId))) {
- List<Tag> existing = new ArrayList<>(tags.get(resourceId).orElse(List.of()));
+ List<Tag> existing = new ArrayList<>(tags.get(resourceId).orElseGet(() -> {
+ Instance ext = findExternalInstance(callerAccountId(), region, resourceId).orElse(null);
+ return ext != null && ext.getTags() != null ? ext.getTags() : List.of();
+ }));
for (Tag tag : tagList) {
existing.removeIf(t -> t.getKey().equals(tag.getKey()));
existing.add(tag);
@@ -6374,7 +6543,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
for (String resourceId : resourceIds) {
withTopologyLockIfNeeded(region, resourceId, () -> {
synchronized (lockFor(key(region, resourceId))) {
- List<Tag> stored = tags.get(resourceId).orElse(null);
+ List<Tag> stored = tags.get(resourceId).orElseGet(() -> {
+ Instance ext = findExternalInstance(callerAccountId(), region, resourceId).orElse(null);
+ return ext != null && ext.getTags() != null ? ext.getTags() : null;
+ });
if (stored != null) {
List<Tag> existing = new ArrayList<>(stored);
for (Tag tag : tagList) {
@@ -6393,6 +6565,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String storeKey = key(region, resourceId);
Instance inst = instances.get(storeKey).orElse(null);
if (inst != null) { inst.setTags(new ArrayList<>(tagList)); instances.put(storeKey, inst); return; }
+ if (findExternalInstance(callerAccountId(), region, resourceId).isPresent()) {
+ return;
+ }
Vpc vpc = vpcs.get(storeKey).orElse(null);
if (vpc != null) { vpc.setTags(new ArrayList<>(tagList)); vpcs.put(storeKey, vpc); return; }
CapacityReservation cr = capacityReservations.get(storeKey).orElse(null);
@@ -6461,7 +6636,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
List<String> filterValues = filters != null ? filters.get("value") : null;
List<Map<String, String>> result = new ArrayList<>();
+ Set<String> processedResourceIds = new LinkedHashSet<>();
for (String resourceId : new ArrayList<>(tags.keys())) {
+ processedResourceIds.add(resourceId);
String resourceType = inferResourceType(resourceId);
if (filterResourceIds != null && !filterResourceIds.contains(resourceId)) {
@@ -6485,6 +6662,34 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
result.add(item);
}
}
+
+ for (Instance ext : listExternalInstances(callerAccountId(), region)) {
+ String resourceId = ext.getInstanceId();
+ if (processedResourceIds.contains(resourceId)) {
+ continue;
+ }
+ String resourceType = inferResourceType(resourceId);
+ if (filterResourceIds != null && !filterResourceIds.contains(resourceId)) {
+ continue;
+ }
+ if (filterResourceTypes != null && !filterResourceTypes.contains(resourceType)) {
+ continue;
+ }
+ for (Tag tag : ext.getTags() != null ? ext.getTags() : List.<Tag>of()) {
+ if (filterKeys != null && !filterKeys.contains(tag.getKey())) {
+ continue;
+ }
+ if (filterValues != null && !filterValues.contains(tag.getValue())) {
+ continue;
+ }
+ Map<String, String> item = new LinkedHashMap<>();
+ item.put("resourceId", resourceId);
+ item.put("resourceType", resourceType);
+ item.put("key", tag.getKey());
+ item.put("value", tag.getValue());
+ result.add(item);
+ }
+ }
return result;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
index 4a838ea09c..c5fb51f5fb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
@@ -27,11 +27,13 @@ import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.Frame;
+import io.github.hectorvent.floci.services.ec2.ClusterNodeInstanceProvider;
import io.github.hectorvent.floci.services.ec2.Ec2MetadataProxy;
import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
import io.github.hectorvent.floci.services.ec2.model.Placement;
+import io.github.hectorvent.floci.services.ec2.model.Tag;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
@@ -70,7 +72,7 @@ import java.util.concurrent.TimeUnit;
* Not used when {@code floci.services.eks.mock=true}.
*/
@ApplicationScoped
-public class EksClusterManager {
+public class EksClusterManager implements ClusterNodeInstanceProvider {
private static final Logger LOG = Logger.getLogger(EksClusterManager.class);
private static final int K3S_API_SERVER_PORT = 6443;
@@ -129,9 +131,11 @@ public class EksClusterManager {
private final EksOidcService oidcService;
private final FlociCertificateAuthority certificateAuthority;
private final ContainerLogStreamer logStreamer;
- private final Map<String, Instance> clusterNodeInstances = new ConcurrentHashMap<>();
+ private final Map<String, ClusterNodeRecord> clusterNodeInstances = new ConcurrentHashMap<>();
private final Map<String, Closeable> clusterLogHandles = new ConcurrentHashMap<>();
+ record ClusterNodeRecord(String accountId, String region, Instance instance) {}
+
public EksClusterManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerDetector containerDetector,
@@ -426,6 +430,7 @@ public class EksClusterManager {
}
applyEndpoints(cluster, containerName, hostPort, info);
+ registerClusterNodeInstance(cluster, containerId);
configureLinkLocalMetadataEndpoint(cluster, containerId);
configurePodIdentityRelay(cluster, containerId);
attachClusterLogs(cluster);
@@ -483,6 +488,7 @@ public class EksClusterManager {
cluster.setContainerId(info.containerId());
cluster.setHostPort(hostPort);
applyEndpoints(cluster, containerName, hostPort, info);
+ registerClusterNodeInstance(cluster, info.containerId());
configureLinkLocalMetadataEndpoint(cluster, info.containerId());
configurePodIdentityRelay(cluster, info.containerId());
attachClusterLogsFromNow(cluster);
@@ -1621,17 +1627,33 @@ public class EksClusterManager {
""".formatted(serverUrl);
}
+ void registerClusterNodeInstance(Cluster cluster, String containerId) {
+ try {
+ String accountId = resolveClusterAccountId(cluster);
+ String region = clusterRegion(cluster);
+ ContainerIps containerIps = resolveContainerIps(containerId);
+ Instance nodeInstance = synthesizeClusterNodeInstance(cluster, containerIps.primaryIp(), region, accountId);
+ clusterNodeInstances.put(clusterResourceName(cluster), new ClusterNodeRecord(accountId, region, nodeInstance));
+ } catch (Exception e) {
+ LOG.warnv("Could not register cluster node instance for EKS cluster {0}: {1}",
+ cluster.getName(), e.getMessage());
+ }
+ }
+
void configureLinkLocalMetadataEndpoint(Cluster cluster, String containerId) {
if (!config.services().eks().imds()) {
return;
}
try {
- String accountId = resolveClusterAccountId(cluster);
- String region = clusterRegion(cluster);
-
+ ClusterNodeRecord record = clusterNodeInstances.get(clusterResourceName(cluster));
+ Instance nodeInstance = record != null ? record.instance() : null;
ContainerIps containerIps = resolveContainerIps(containerId);
- Instance nodeInstance = synthesizeClusterNodeInstance(cluster, containerIps.primaryIp(), region, accountId);
- clusterNodeInstances.put(clusterResourceName(cluster), nodeInstance);
+ if (nodeInstance == null) {
+ String accountId = resolveClusterAccountId(cluster);
+ String region = clusterRegion(cluster);
+ nodeInstance = synthesizeClusterNodeInstance(cluster, containerIps.primaryIp(), region, accountId);
+ clusterNodeInstances.put(clusterResourceName(cluster), new ClusterNodeRecord(accountId, region, nodeInstance));
+ }
if (metadataServer != null) {
metadataServer.reconcileContainerAddresses(containerIps.allIps(), nodeInstance);
@@ -1721,7 +1743,8 @@ public class EksClusterManager {
}
void unregisterMetadataEndpoint(Cluster cluster) {
- Instance nodeInstance = clusterNodeInstances.remove(clusterResourceName(cluster));
+ ClusterNodeRecord record = clusterNodeInstances.remove(clusterResourceName(cluster));
+ Instance nodeInstance = record != null ? record.instance() : null;
if (metadataServer != null && nodeInstance != null) {
metadataServer.unregisterInstance(nodeInstance);
}
@@ -1807,9 +1830,47 @@ public class EksClusterManager {
// node instance profile identity so /latest/meta-data/iam/info returns a valid profile ARN.
String nodeProfileName = safeClusterName + "-node-profile";
inst.setIamInstanceProfileArn("arn:aws:iam::" + safeAccountId + ":instance-profile/" + nodeProfileName);
+
+ if (cluster.getResourcesVpcConfig() != null) {
+ inst.setVpcId(cluster.getResourcesVpcConfig().getVpcId());
+ if (cluster.getResourcesVpcConfig().getSubnetIds() != null && !cluster.getResourcesVpcConfig().getSubnetIds().isEmpty()) {
+ inst.setSubnetId(cluster.getResourcesVpcConfig().getSubnetIds().getFirst());
+ }
+ }
+ inst.setLaunchTime(cluster.getCreatedAt() != null ? cluster.getCreatedAt() : Instant.now());
+ List<Tag> tags = new ArrayList<>();
+ tags.add(new Tag("Name", safeClusterName + "-node"));
+ tags.add(new Tag("kubernetes.io/cluster/" + safeClusterName, "owned"));
+ tags.add(new Tag("eks:cluster-name", safeClusterName));
+ inst.setTags(tags);
return inst;
}
+ @Override
+ public Optional<Instance> findInstance(String accountId, String region, String instanceId) {
+ if (accountId == null || accountId.isBlank() || instanceId == null || instanceId.isBlank()) {
+ return Optional.empty();
+ }
+ return clusterNodeInstances.values().stream()
+ .filter(rec -> accountId.equals(rec.accountId()))
+ .filter(rec -> region == null || region.equals(rec.region()))
+ .map(ClusterNodeRecord::instance)
+ .filter(i -> instanceId.equals(i.getInstanceId()))
+ .findFirst();
+ }
+
+ @Override
+ public List<Instance> listInstances(String accountId, String region) {
+ if (accountId == null || accountId.isBlank()) {
+ return List.of();
+ }
+ return clusterNodeInstances.values().stream()
+ .filter(rec -> accountId.equals(rec.accountId()))
+ .filter(rec -> region == null || region.equals(rec.region()))
+ .map(ClusterNodeRecord::instance)
+ .toList();
+ }
+
record ContainerIps(String primaryIp, Set<String> allIps) {}
ContainerIps resolveContainerIps(String containerId) {
@@ -1842,7 +1903,8 @@ public class EksClusterManager {
}
Instance getRegisteredClusterNodeInstance(Cluster cluster) {
- return clusterNodeInstances.get(clusterResourceName(cluster));
+ ClusterNodeRecord record = clusterNodeInstances.get(clusterResourceName(cluster));
+ return record != null ? record.instance() : null;
}
ContainerExecResult execInContainerForResult(String containerId, String[] cmd, int timeoutSeconds) throws Exception {
diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthChecker.java b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthChecker.java
index 87246d59af..2daec43fa8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthChecker.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicHealthChecker.java
@@ -176,7 +176,7 @@ public class ElbClassicHealthChecker implements Resettable {
for (Map.Entry<String, InstanceState> entry : lbStates.entrySet()) {
String instanceId = entry.getKey();
InstanceState state = entry.getValue();
- String host = resolveHost(instanceId);
+ String host = resolveHost(lb.getAccountId(), instanceId);
vertx.executeBlocking(() -> probe(host, target, timeout))
.onSuccess(ok -> {
if (Boolean.TRUE.equals(ok)) {
@@ -206,10 +206,16 @@ public class ElbClassicHealthChecker implements Resettable {
}
private String resolveHost(String instanceId) {
+ return resolveHost(null, instanceId);
+ }
+
+ private String resolveHost(String accountId, String instanceId) {
if (ec2Service == null) {
return instanceId;
}
- Instance instance = ec2Service.findInstanceById(instanceId);
+ Instance instance = accountId != null
+ ? ec2Service.findInstanceById(accountId, instanceId)
+ : ec2Service.findInstanceById(instanceId);
if (instance == null) {
return instanceId;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java
index 7efeccecb4..9fac65c070 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java
@@ -143,6 +143,9 @@ public class ElbClassicService {
ClassicLoadBalancer lb = new ClassicLoadBalancer();
lb.setLoadBalancerName(name);
lb.setRegion(region);
+ if (regionResolver != null && regionResolver.getAccountId() != null) {
+ lb.setAccountId(regionResolver.getAccountId());
+ }
lb.setDnsName(dnsName);
lb.setCanonicalHostedZoneName(dnsName);
lb.setCanonicalHostedZoneNameId(CANONICAL_HOSTED_ZONE_ID);
diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicLoadBalancer.java b/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicLoadBalancer.java
index fecb5e5e6b..702c0e6868 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicLoadBalancer.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elb/model/ClassicLoadBalancer.java
@@ -27,6 +27,7 @@ public class ClassicLoadBalancer {
private String scheme;
private String vpcId;
private String region;
+ private String accountId;
private Instant createdTime;
private List<ClassicListener> listeners = new ArrayList<>();
@@ -65,6 +66,9 @@ public class ClassicLoadBalancer {
public String getRegion() { return region; }
public void setRegion(String v) { this.region = v; }
+ public String getAccountId() { return accountId; }
+ public void setAccountId(String v) { this.accountId = v; }
+
public Instant getCreatedTime() { return createdTime; }
public void setCreatedTime(Instant v) { this.createdTime = v; }
diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolver.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolver.java
index 5c2044104c..55efa163ba 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolver.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolver.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.elbv2;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.SsrfProtection;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Instance;
@@ -25,7 +26,10 @@ final class ElbV2TargetResolver {
return targetId;
}
- Instance instance = ec2Service.findInstanceById(targetId);
+ String accountId = extractAccountId(targetGroup.getTargetGroupArn());
+ Instance instance = accountId != null
+ ? ec2Service.findInstanceById(accountId, targetId)
+ : ec2Service.findInstanceById(targetId);
if (instance == null) {
return targetId;
}
@@ -46,4 +50,15 @@ final class ElbV2TargetResolver {
static boolean isIpLiteral(String host) {
return host != null && (host.contains(":") || host.matches("[0-9.]+"));
}
+
+ private static String extractAccountId(String targetGroupArn) {
+ if (targetGroupArn == null || !targetGroupArn.startsWith("arn:")) {
+ return null;
+ }
+ try {
+ return AwsArnUtils.parse(targetGroupArn).accountId();
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmCommandService.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmCommandService.java
index 0dbc31ed1e..f1df6d4dc6 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmCommandService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmCommandService.java
@@ -199,11 +199,12 @@ public class SsmCommandService implements Resettable {
inv.setStatusDetails(statusDetails("Pending"));
inv.setRegion(region);
- if (directCommandExecutor.supports(instanceId, documentName)) {
+ String callerAccountId = regionResolver != null ? regionResolver.getAccountId() : null;
+ if (directCommandExecutor.supports(callerAccountId, instanceId, documentName)) {
inv.setStatus("InProgress");
inv.setStatusDetails(statusDetails("InProgress"));
invocationStore.put(invocationKey(region, commandId, instanceId), inv);
- directExecutionRequests.add(new DirectExecutionRequest(instanceId, documentName, parameters));
+ directExecutionRequests.add(new DirectExecutionRequest(callerAccountId, instanceId, documentName, parameters));
}
else {
invocationStore.put(invocationKey(region, commandId, instanceId), inv);
@@ -215,6 +216,7 @@ public class SsmCommandService implements Resettable {
Command response = copyCommand(command);
for (DirectExecutionRequest directExecutionRequest : directExecutionRequests) {
runDirectCommandAsync(
+ directExecutionRequest.accountId(),
commandId,
directExecutionRequest.instanceId(),
directExecutionRequest.documentName(),
@@ -545,6 +547,7 @@ public class SsmCommandService implements Resettable {
// ── Internal helpers ────────────────────────────────────────────────────
private void runDirectCommandAsync(
+ String accountId,
String commandId,
String instanceId,
String documentName,
@@ -559,7 +562,7 @@ public class SsmCommandService implements Resettable {
}
SsmDirectCommandExecutor.ExecutionResult result = directCommandExecutor
- .executeIfSupported(instanceId, documentName, parameters, timeoutSeconds)
+ .executeIfSupported(accountId, instanceId, documentName, parameters, timeoutSeconds)
.orElse(null);
if (result == null) {
synchronized (invocation) {
@@ -801,6 +804,7 @@ public class SsmCommandService implements Resettable {
}
private record DirectExecutionRequest(
+ String accountId,
String instanceId,
String documentName,
Map<String, List<String>> parameters) {}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmDirectCommandExecutor.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmDirectCommandExecutor.java
index 309922bc52..c98aa7787b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmDirectCommandExecutor.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmDirectCommandExecutor.java
@@ -39,11 +39,22 @@ public class SsmDirectCommandExecutor {
String documentName,
Map<String, List<String>> parameters,
int timeoutSeconds) {
- if (!supports(instanceId, documentName)) {
+ return executeIfSupported(null, instanceId, documentName, parameters, timeoutSeconds);
+ }
+
+ public Optional<ExecutionResult> executeIfSupported(
+ String accountId,
+ String instanceId,
+ String documentName,
+ Map<String, List<String>> parameters,
+ int timeoutSeconds) {
+ if (!supports(accountId, instanceId, documentName)) {
return Optional.empty();
}
- Instance instance = ec2Service.findInstanceById(instanceId);
+ Instance instance = accountId != null
+ ? ec2Service.findInstanceById(accountId, instanceId)
+ : ec2Service.findInstanceById(instanceId);
String script = String.join("\n", parameters.getOrDefault("commands", List.of()));
if (script.isBlank()) {
return Optional.of(ExecutionResult.success("", "", 0));
@@ -65,10 +76,14 @@ public class SsmDirectCommandExecutor {
}
public boolean supports(String instanceId, String documentName) {
+ return supports(null, instanceId, documentName);
+ }
+
+ public boolean supports(String accountId, String instanceId, String documentName) {
if (!"AWS-RunShellScript".equals(documentName)) {
return false;
}
- return isContainerBacked(instanceId);
+ return isContainerBacked(accountId, instanceId);
}
/**
@@ -77,11 +92,19 @@ public class SsmDirectCommandExecutor {
* managed instance is served through the SSM agent polling flow.
*/
public boolean isContainerBacked(String instanceId) {
- Instance instance = ec2Service.findInstanceById(instanceId);
+ return isContainerBacked(null, instanceId);
+ }
+
+ public boolean isContainerBacked(String accountId, String instanceId) {
+ Instance instance = accountId != null
+ ? ec2Service.findInstanceById(accountId, instanceId)
+ : ec2Service.findInstanceById(instanceId);
if (instance == null || instance.getDockerContainerId() == null || instance.getDockerContainerId().isBlank()) {
return false;
}
- return ec2Service.isInstanceContainerRunning(instanceId);
+ return accountId != null
+ ? ec2Service.isInstanceContainerRunning(accountId, instanceId)
+ : ec2Service.isInstanceContainerRunning(instanceId);
}
private ExecutionResult executeInContainer(String containerId, String script, String workingDirectory, int timeoutSeconds)
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
index d289df535e..ff168bf3ae 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
@@ -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());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java
index 15b7efb902..4ce8cd7fab 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java
@@ -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")));
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterNodeInstanceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterNodeInstanceIntegrationTest.java
new file mode 100644
index 0000000000..ff7c72ae29
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterNodeInstanceIntegrationTest.java
@@ -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";
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolverTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolverTest.java
index f5ce289266..74ffdb6b47 100644
--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolverTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TargetResolverTest.java
@@ -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);
diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmCommandServiceDirectExecutionTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmCommandServiceDirectExecutionTest.java
index d2f5d5255f..7628658061 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmCommandServiceDirectExecutionTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmCommandServiceDirectExecutionTest.java
@@ -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"))));
diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmDirectCommandExecutorTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmDirectCommandExecutorTest.java
index b22172dcf0..56ef8a9ed1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmDirectCommandExecutorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmDirectCommandExecutorTest.java
@@ -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);
diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmSendCommandIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmSendCommandIntegrationTest.java
index 2cc5d51750..98c5a3c6b8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmSendCommandIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmSendCommandIntegrationTest.java
@@ -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(),