mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eks): expose IMDS on 169.254.169.254 inside cluster containers (#3693)
* feat(eks): expose IMDS on 169.254.169.254 inside cluster containers When applications or agents run on Kubernetes nodes or use hostNetwork: true, they expect the AWS Instance Metadata Service (IMDS) at the standard link-local address 169.254.169.254:80. In Floci, EKS k3s cluster containers lacked access to IMDS at this link-local address, preventing workloads from discovering instance identities, node IAM roles, or dynamic cluster credentials without custom endpoint overrides. This change exposes IMDS on 169.254.169.254:80 inside EKS cluster containers when floci.services.eks.imds is enabled. It configures a background TCP relay via socat pointing to the host's EC2 metadata port, registers a synthesized EC2 node instance with the cluster's IAM role and container IP in Ec2MetadataServer, extracts reusable metadata proxy logic into Ec2MetadataProxy, and documents node network namespace reachability and hop limit handling. * fix(eks): address review feedback on lifecycle check, default flag, and instance seed * fix(eks): synthesize distinct node instance profile and import CompletableFuture * test(eks): enable IMDS profile and provide curl in docker test fixture
This commit is contained in:
1 parent
f48bc2aa40
commit
a2fddaf08d
13 files changed
+838
-72
No files matched your search
@@ -39,6 +39,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -59,6 +60,7 @@ class EmulatorLifecycleTest {
|
||||
@Mock private EmulatorConfig.StorageConfig storageConfig;
|
||||
@Mock private EmulatorConfig.ServicesConfig servicesConfig;
|
||||
@Mock private EmulatorConfig.Ec2ServiceConfig ec2ServiceConfig;
|
||||
@Mock private EmulatorConfig.EksServiceConfig eksServiceConfig;
|
||||
@Mock private EmulatorConfig.ElbV2ServiceConfig elbv2ServiceConfig;
|
||||
@Mock private EmulatorConfig.ElbServiceConfig elbServiceConfig;
|
||||
@Mock private IamService iamService;
|
||||
@@ -107,6 +109,8 @@ class EmulatorLifecycleTest {
|
||||
Mockito.lenient().when(elastiCacheServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(servicesConfig.elb()).thenReturn(elbServiceConfig);
|
||||
Mockito.lenient().when(elbServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(servicesConfig.eks()).thenReturn(eksServiceConfig);
|
||||
Mockito.lenient().when(eksServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(config.tls()).thenReturn(tlsConfig);
|
||||
Mockito.lenient().when(tlsConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(config.port()).thenReturn(4566);
|
||||
@@ -574,4 +578,36 @@ class EmulatorLifecycleTest {
|
||||
assertEquals(1, messages.stream().filter("Ready."::equals).count(),
|
||||
"Exactly one parity \"Ready.\" line must be emitted on the hook path");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should start and stop EC2 metadata server when EKS IMDS is enabled")
|
||||
void shouldStartAndStopMetadataServerWhenEksImdsEnabled() {
|
||||
stubStorageConfig();
|
||||
when(eksServiceConfig.enabled()).thenReturn(true);
|
||||
when(eksServiceConfig.mock()).thenReturn(false);
|
||||
when(eksServiceConfig.imds()).thenReturn(true);
|
||||
when(ec2MetadataServer.start()).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
verify(ec2MetadataServer).start();
|
||||
|
||||
emulatorLifecycle.onStop(Mockito.mock(ShutdownEvent.class));
|
||||
verify(ec2MetadataServer).stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not start EC2 metadata server when EKS IMDS is disabled")
|
||||
void shouldNotStartMetadataServerWhenEksImdsDisabled() {
|
||||
stubStorageConfig();
|
||||
when(eksServiceConfig.enabled()).thenReturn(true);
|
||||
when(eksServiceConfig.mock()).thenReturn(false);
|
||||
when(eksServiceConfig.imds()).thenReturn(false);
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
verify(ec2MetadataServer, never()).start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class Ec2MetadataProxyTest {
|
||||
|
||||
@Test
|
||||
void installCommandContainsSupportedPackageManagers() {
|
||||
String[] command = Ec2MetadataProxy.installCommand();
|
||||
assertEquals(3, command.length);
|
||||
assertEquals("sh", command[0]);
|
||||
assertEquals("-c", command[1]);
|
||||
|
||||
String script = command[2];
|
||||
assertTrue(script.contains("command -v ip >/dev/null 2>&1 && command -v socat >/dev/null 2>&1 && command -v curl >/dev/null 2>&1; then exit 0; fi"));
|
||||
assertTrue(script.contains("apt-get install -y --no-install-recommends iproute2 socat curl ca-certificates"));
|
||||
assertTrue(script.contains("dnf install -y --allowerasing iproute socat curl ca-certificates"));
|
||||
assertTrue(script.contains("yum install -y iproute socat curl ca-certificates"));
|
||||
assertTrue(script.contains("apk add --no-cache iproute2 socat curl ca-certificates"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startCommandAttachesAddressIdempotentlyAndTargetsHostAndPort() {
|
||||
String[] command = Ec2MetadataProxy.startCommand("10.0.0.1", 9169);
|
||||
assertEquals(3, command.length);
|
||||
assertEquals("sh", command[0]);
|
||||
assertEquals("-c", command[1]);
|
||||
|
||||
String script = command[2];
|
||||
// Attaches address if missing
|
||||
assertTrue(script.contains("ip addr show dev lo | grep -q '169.254.169.254/32' || ip addr add 169.254.169.254/32 dev lo"));
|
||||
// Idempotent when pid file exists and process is alive
|
||||
assertTrue(script.contains("if [ -f /tmp/floci-imds-proxy.pid ] && kill -0 \"$(cat /tmp/floci-imds-proxy.pid)\" 2>/dev/null; then\n exit 0\nfi"));
|
||||
// Targets configured Floci host and IMDS port
|
||||
assertTrue(script.contains("nohup socat TCP-LISTEN:80,bind=169.254.169.254,fork,reuseaddr TCP:10.0.0.1:9169 >/tmp/floci-imds-proxy.log 2>&1 &"));
|
||||
// Verifies via link-local curl
|
||||
assertTrue(script.contains("curl -fsS --max-time 1 http://169.254.169.254/latest/meta-data/instance-id >/dev/null && exit 0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preferredMetadataSourceIpPrefersConfiguredNetworkOverBridge() {
|
||||
ContainerNetwork bridge = new ContainerNetwork();
|
||||
bridge.withIpv4Address("172.17.0.2");
|
||||
ContainerNetwork vpc = new ContainerNetwork();
|
||||
vpc.withIpv4Address("10.0.0.2");
|
||||
|
||||
Optional<String> ip = Ec2MetadataProxy.preferredMetadataSourceIp(Map.of("bridge", bridge, "custom-net", vpc));
|
||||
assertTrue(ip.isPresent());
|
||||
assertEquals("10.0.0.2", ip.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void preferredMetadataSourceIpFallsBackToBridge() {
|
||||
ContainerNetwork bridge = new ContainerNetwork();
|
||||
bridge.withIpv4Address("172.17.0.2");
|
||||
|
||||
Optional<String> ip = Ec2MetadataProxy.preferredMetadataSourceIp(Map.of("bridge", bridge));
|
||||
assertTrue(ip.isPresent());
|
||||
assertEquals("172.17.0.2", ip.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void preferredMetadataSourceIpReturnsEmptyWhenNoNetworks() {
|
||||
assertTrue(Ec2MetadataProxy.preferredMetadataSourceIp(null).isEmpty());
|
||||
assertTrue(Ec2MetadataProxy.preferredMetadataSourceIp(Map.of()).isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,21 @@ import io.github.hectorvent.floci.services.eks.model.Cluster;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmd;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
|
||||
import com.github.dockerjava.api.command.ExecStartCmd;
|
||||
import com.github.dockerjava.api.command.InspectContainerCmd;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.command.InspectExecCmd;
|
||||
import com.github.dockerjava.api.command.InspectExecResponse;
|
||||
import com.github.dockerjava.api.command.InspectVolumeCmd;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.NetworkSettings;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -26,12 +38,17 @@ import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -598,4 +615,180 @@ class EksClusterManagerTest {
|
||||
verify(copyCmd).exec();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConfigureLinkLocalMetadataEndpoint {
|
||||
|
||||
private EmulatorConfig config;
|
||||
private EmulatorConfig.EksServiceConfig eks;
|
||||
private EmulatorConfig.Ec2ServiceConfig ec2;
|
||||
private ContainerLifecycleManager lifecycleManager;
|
||||
private DockerClient dockerClient;
|
||||
private Ec2MetadataServer metadataServer;
|
||||
private DockerHostResolver dockerHostResolver;
|
||||
private RegionResolver regionResolver;
|
||||
private EksClusterManager manager;
|
||||
private ExecCreateCmd execCreate;
|
||||
private List<String[]> capturedCmds;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
config = Mockito.mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
eks = Mockito.mock(EmulatorConfig.EksServiceConfig.class);
|
||||
ec2 = Mockito.mock(EmulatorConfig.Ec2ServiceConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
when(services.eks()).thenReturn(eks);
|
||||
when(services.ec2()).thenReturn(ec2);
|
||||
when(ec2.imdsPort()).thenReturn(9169);
|
||||
when(eks.imds()).thenReturn(true);
|
||||
|
||||
lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
|
||||
dockerClient = Mockito.mock(DockerClient.class);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
|
||||
metadataServer = Mockito.mock(Ec2MetadataServer.class);
|
||||
dockerHostResolver = Mockito.mock(DockerHostResolver.class);
|
||||
when(dockerHostResolver.resolve()).thenReturn("floci-host");
|
||||
|
||||
regionResolver = Mockito.mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
|
||||
capturedCmds = new ArrayList<>();
|
||||
execCreate = Mockito.mock(ExecCreateCmd.class, Mockito.withSettings().defaultAnswer(Mockito.RETURNS_SELF));
|
||||
ExecCreateCmdResponse execResponse = Mockito.mock(ExecCreateCmdResponse.class);
|
||||
when(execResponse.getId()).thenReturn("exec-123");
|
||||
when(dockerClient.execCreateCmd(anyString())).thenReturn(execCreate);
|
||||
when(execCreate.withCmd(any(String[].class))).thenAnswer(inv -> {
|
||||
Object[] args = inv.getArguments();
|
||||
if (args.length == 1 && args[0] instanceof String[] command) {
|
||||
capturedCmds.add(command);
|
||||
} else {
|
||||
capturedCmds.add(Arrays.copyOf(args, args.length, String[].class));
|
||||
}
|
||||
return execCreate;
|
||||
});
|
||||
when(execCreate.exec()).thenReturn(execResponse);
|
||||
|
||||
ExecStartCmd execStart = Mockito.mock(ExecStartCmd.class);
|
||||
when(dockerClient.execStartCmd(anyString())).thenReturn(execStart);
|
||||
when(execStart.exec(any())).thenAnswer(inv -> {
|
||||
ResultCallback<Frame> cb = inv.getArgument(0);
|
||||
cb.onComplete();
|
||||
return cb;
|
||||
});
|
||||
|
||||
InspectExecCmd inspectExec = Mockito.mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectResponse = Mockito.mock(InspectExecResponse.class);
|
||||
when(inspectResponse.getExitCodeLong()).thenReturn(0L);
|
||||
when(inspectExec.exec()).thenReturn(inspectResponse);
|
||||
when(dockerClient.inspectExecCmd(anyString())).thenReturn(inspectExec);
|
||||
|
||||
InspectContainerCmd inspectContainer = Mockito.mock(InspectContainerCmd.class);
|
||||
InspectContainerResponse containerResponse = Mockito.mock(InspectContainerResponse.class);
|
||||
NetworkSettings netSettings = Mockito.mock(NetworkSettings.class);
|
||||
when(inspectContainer.exec()).thenReturn(containerResponse);
|
||||
when(dockerClient.inspectContainerCmd(anyString())).thenReturn(inspectContainer);
|
||||
when(containerResponse.getNetworkSettings()).thenReturn(netSettings);
|
||||
when(netSettings.getIpAddress()).thenReturn("172.17.0.2");
|
||||
|
||||
manager = new EksClusterManager(
|
||||
Mockito.mock(ContainerBuilder.class), lifecycleManager,
|
||||
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
|
||||
dockerHostResolver, Mockito.mock(EcrRegistryManager.class),
|
||||
config, regionResolver, metadataServer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void synthesizesClusterNodeInstance() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("prod-cluster");
|
||||
cluster.setRoleArn("arn:aws:iam::123456789012:role/eks-node-role");
|
||||
|
||||
Instance instance = manager.synthesizeClusterNodeInstance(cluster, "172.17.0.2", "us-west-2", "123456789012");
|
||||
assertNotNull(instance);
|
||||
assertTrue(instance.getInstanceId().startsWith("i-"));
|
||||
assertTrue(instance.getInstanceId().length() >= 19);
|
||||
assertEquals("ami-eks-k3s", instance.getImageId());
|
||||
assertEquals("m5.large", instance.getInstanceType());
|
||||
assertEquals("us-west-2a", instance.getPlacement().getAvailabilityZone());
|
||||
assertEquals("us-west-2", instance.getRegion());
|
||||
assertEquals("172.17.0.2", instance.getPrivateIpAddress());
|
||||
assertEquals("ip-172-17-0-2.us-west-2.compute.internal", instance.getPrivateDnsName());
|
||||
assertEquals("arn:aws:iam::123456789012:instance-profile/prod-cluster-node-profile", instance.getIamInstanceProfileArn());
|
||||
assertNotEquals(cluster.getRoleArn(), instance.getIamInstanceProfileArn());
|
||||
assertEquals("running", instance.getState().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameNameClustersInDifferentRegionsGetDistinctInstanceIds() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("prod-cluster");
|
||||
|
||||
Instance inst1 = manager.synthesizeClusterNodeInstance(cluster, "172.17.0.2", "us-east-1", "123456789012");
|
||||
Instance inst2 = manager.synthesizeClusterNodeInstance(cluster, "172.17.0.2", "us-west-2", "123456789012");
|
||||
|
||||
assertNotNull(inst1);
|
||||
assertNotNull(inst2);
|
||||
assertNotEquals(inst1.getInstanceId(), inst2.getInstanceId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void configuresMetadataProxyWhenEnabled() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("test-cluster");
|
||||
|
||||
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
|
||||
|
||||
verify(metadataServer).reconcileContainerAddresses(any(), any());
|
||||
assertEquals(2, capturedCmds.size());
|
||||
// First command: install probe
|
||||
assertTrue(capturedCmds.get(0)[2].contains("command -v socat"));
|
||||
// Second command: start command with 169.254.169.254
|
||||
assertTrue(capturedCmds.get(1)[2].contains("169.254.169.254"));
|
||||
assertTrue(capturedCmds.get(1)[2].contains("TCP:floci-host:9169"));
|
||||
|
||||
assertNotNull(manager.getRegisteredClusterNodeInstance(cluster));
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsWhenImdsIsDisabled() {
|
||||
when(eks.imds()).thenReturn(false);
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("test-cluster");
|
||||
|
||||
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
|
||||
|
||||
verifyNoInteractions(metadataServer);
|
||||
verifyNoInteractions(dockerClient);
|
||||
assertNull(manager.getRegisteredClusterNodeInstance(cluster));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failureToWireLogsAndDoesNotAbort() {
|
||||
when(dockerClient.execCreateCmd(anyString())).thenThrow(new RuntimeException("docker exec failed"));
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("test-cluster");
|
||||
|
||||
// Failure to wire proxy should log warning and continue without throwing
|
||||
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unregisterMetadataEndpointRemovesInstance() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("test-cluster");
|
||||
|
||||
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
|
||||
assertNotNull(manager.getRegisteredClusterNodeInstance(cluster));
|
||||
|
||||
manager.unregisterMetadataEndpoint(cluster);
|
||||
verify(metadataServer).unregisterInstance(any());
|
||||
assertNull(manager.getRegisteredClusterNodeInstance(cluster));
|
||||
}
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer;
|
||||
import io.github.hectorvent.floci.services.eks.model.Cluster;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(EksImdsDockerIntegrationTest.Profile.class)
|
||||
class EksImdsDockerIntegrationTest {
|
||||
|
||||
public static final class Profile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.eks.imds", "true");
|
||||
}
|
||||
}
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EksImdsDockerIntegrationTest.class);
|
||||
private static final String TEST_IMAGE = "alpine:3.21";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
ContainerBuilder containerBuilder;
|
||||
|
||||
@Inject
|
||||
ContainerLifecycleManager lifecycleManager;
|
||||
|
||||
@Inject
|
||||
EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
Ec2MetadataServer metadataServer;
|
||||
|
||||
@Inject
|
||||
EksClusterManager eksClusterManager;
|
||||
|
||||
private String containerId;
|
||||
private Cluster cluster;
|
||||
|
||||
@BeforeEach
|
||||
void requireDockerAndStartMetadataServer() {
|
||||
boolean dockerAvailable = isDockerAvailable();
|
||||
if (!dockerAvailable) {
|
||||
LOG.warn("Docker daemon is not available; skipping EksImdsDockerIntegrationTest");
|
||||
}
|
||||
Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for EKS IMDS integration test");
|
||||
metadataServer.start().join();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (cluster != null) {
|
||||
eksClusterManager.unregisterMetadataEndpoint(cluster);
|
||||
}
|
||||
if (containerId != null) {
|
||||
try {
|
||||
lifecycleManager.stopAndRemove(containerId, null);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void linkLocalImdsEndpointAnswersInsideClusterContainer() throws Exception {
|
||||
String clusterName = "imds-it-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
cluster = new Cluster();
|
||||
cluster.setName(clusterName);
|
||||
cluster.setRoleArn("arn:aws:iam::000000000000:role/eks-it-role");
|
||||
|
||||
ContainerSpec spec = containerBuilder.newContainer(TEST_IMAGE)
|
||||
.withName("floci-eks-imds-test-" + clusterName)
|
||||
.withPrivileged(true)
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withCmd(List.of("sleep", "300"))
|
||||
.build();
|
||||
|
||||
containerId = lifecycleManager.createAndStart(spec).containerId();
|
||||
assertNotNull(containerId, "Container ID must not be null");
|
||||
|
||||
// Ensure curl dependency is installed in the test fixture if absent
|
||||
execInContainer(containerId, new String[]{"sh", "-c",
|
||||
"command -v curl >/dev/null 2>&1 || apk add --no-cache curl"});
|
||||
|
||||
eksClusterManager.configureLinkLocalMetadataEndpoint(cluster, containerId);
|
||||
|
||||
// IMDSv2 token test
|
||||
String tokenCmd = "curl -s -f -X PUT http://169.254.169.254/latest/api/token -H 'x-aws-ec2-metadata-token-ttl-seconds: 21600'";
|
||||
String token = execInContainer(containerId, new String[]{"sh", "-c", tokenCmd});
|
||||
assertNotNull(token, "IMDSv2 token response should not be null");
|
||||
assertTrue(!token.isBlank(), "IMDSv2 token should not be blank");
|
||||
|
||||
// IMDSv2 instance-id metadata test
|
||||
String instanceIdCmd = "curl -s -f -H 'x-aws-ec2-metadata-token: " + token.trim() + "' http://169.254.169.254/latest/meta-data/instance-id";
|
||||
String instanceId = execInContainer(containerId, new String[]{"sh", "-c", instanceIdCmd});
|
||||
assertNotNull(instanceId, "instance-id response should not be null");
|
||||
assertTrue(instanceId.trim().startsWith("i-"), "Instance ID should start with 'i-': " + instanceId);
|
||||
|
||||
// IMDSv1 fallback test using wget (tool guaranteed by alpine:3.21 image)
|
||||
String imdsv1Cmd = "wget -q -O - http://169.254.169.254/latest/meta-data/instance-id";
|
||||
String v1InstanceId = execInContainer(containerId, new String[]{"sh", "-c", imdsv1Cmd});
|
||||
assertEquals(instanceId.trim(), v1InstanceId.trim(), "IMDSv1 and IMDSv2 instance IDs should match");
|
||||
|
||||
// Pod-isolation test: ordinary pods in their own network namespace cannot reach link-local IMDS
|
||||
// Tested using wget (tool guaranteed by alpine:3.21 image)
|
||||
String podIsolationCmd = """
|
||||
if command -v unshare >/dev/null 2>&1; then
|
||||
unshare -n wget -q -O - -T 2 http://169.254.169.254/latest/meta-data/instance-id
|
||||
else
|
||||
ip netns add pod-test 2>/dev/null || true
|
||||
ip netns exec pod-test wget -q -O - -T 2 http://169.254.169.254/latest/meta-data/instance-id
|
||||
ret=$?
|
||||
ip netns del pod-test 2>/dev/null || true
|
||||
exit $ret
|
||||
fi
|
||||
""";
|
||||
ExecResult podResult = execInContainerWithExitCode(containerId, new String[]{"sh", "-c", podIsolationCmd});
|
||||
assertNotEquals(0L, podResult.exitCode(), "IMDS should not be reachable from an isolated pod network namespace");
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
record ExecResult(long exitCode, String stdout, String stderr) {}
|
||||
|
||||
private ExecResult execInContainerWithExitCode(String containerId, String[] cmd) throws Exception {
|
||||
ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerId)
|
||||
.withCmd(cmd)
|
||||
.withAttachStdout(true)
|
||||
.withAttachStderr(true)
|
||||
.exec();
|
||||
|
||||
StringBuilder stdout = new StringBuilder();
|
||||
StringBuilder stderr = new StringBuilder();
|
||||
boolean completed = dockerClient.execStartCmd(exec.getId())
|
||||
.exec(new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
if (frame != null && frame.getPayload() != null) {
|
||||
String text = new String(frame.getPayload(), StandardCharsets.UTF_8);
|
||||
if (frame.getStreamType() == com.github.dockerjava.api.model.StreamType.STDERR) {
|
||||
stderr.append(text);
|
||||
} else {
|
||||
stdout.append(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.awaitCompletion(30, TimeUnit.SECONDS);
|
||||
|
||||
if (!completed) {
|
||||
throw new RuntimeException("exec timed out in container " + containerId);
|
||||
}
|
||||
Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();
|
||||
return new ExecResult(exitCode != null ? exitCode : -1L, stdout.toString(), stderr.toString());
|
||||
}
|
||||
|
||||
private String execInContainer(String containerId, String[] cmd) throws Exception {
|
||||
ExecResult result = execInContainerWithExitCode(containerId, cmd);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new RuntimeException("exec failed with code " + result.exitCode() + ": " + result.stderr());
|
||||
}
|
||||
return result.stdout();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user