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

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