feat(eks): serve pod identity credentials on 169.254.170.23 (#4124)

* feat(eks): serve pod identity credentials on 169.254.170.23

* fix(eks): safely handle cluster arn and initialize test cluster in pod identity integration test

* test(eks): configure fixed test port for pod identity docker integration test

* fix(eks): isolate pod routing and restore webhook timeout
This commit is contained in:
Simone Primarosa authored and GitHub committed 2026-09-21 22:07:50 -04:00
1 parent 30c89986bd
commit 8dcdf7b911
16 files changed
+954 -31

No files matched your search

@@ -44,6 +44,20 @@ class Ec2MetadataProxyTest {
assertTrue(script.contains("curl -fsS --max-time 1 http://169.254.169.254/latest/meta-data/instance-id >/dev/null && exit 0"));
}
@Test
void podIdentityStartCommandAttachesAddressIdempotentlyAndTargetsHostAndPort() {
String[] command = Ec2MetadataProxy.podIdentityStartCommand("10.0.0.1", 4566);
assertEquals(3, command.length);
assertEquals("sh", command[0]);
assertEquals("-c", command[1]);
String script = command[2];
assertTrue(script.contains("ip addr show dev lo | grep -q '169.254.170.23/32' || ip addr add 169.254.170.23/32 dev lo"));
assertTrue(script.contains("if [ -f /tmp/floci-pod-identity-proxy.pid ] && kill -0 \"$(cat /tmp/floci-pod-identity-proxy.pid)\" 2>/dev/null; then\n exit 0\nfi"));
assertTrue(script.contains("nohup socat TCP-LISTEN:80,bind=169.254.170.23,fork,reuseaddr TCP:10.0.0.1:4566 >/tmp/floci-pod-identity-proxy.log 2>&1 &"));
assertTrue(script.contains("http://169.254.170.23/v1/credentials"));
}
@Test
void preferredMetadataSourceIpPrefersConfiguredNetworkOverBridge() {
ContainerNetwork bridge = new ContainerNetwork();
@@ -61,6 +61,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -814,6 +815,8 @@ class EksClusterManagerTest {
assertTrue(capturedCmds.get(2)[2].contains("FLOCI-LINK-LOCAL"));
assertTrue(capturedCmds.get(2)[2].contains("10.42.0.0/16"));
assertTrue(capturedCmds.get(2)[2].contains("169.254.169.254"));
assertFalse(capturedCmds.get(2)[2].contains("169.254.170.23"),
"IMDS pod routing must not route Pod Identity traffic");
assertNotNull(manager.getRegisteredClusterNodeInstance(cluster));
}
@@ -879,6 +882,132 @@ class EksClusterManagerTest {
}
}
@Nested
class ConfigurePodIdentityRelay {
private EmulatorConfig config;
private EmulatorConfig.EksServiceConfig eks;
private EmulatorConfig.TlsConfig tls;
private ContainerLifecycleManager lifecycleManager;
private DockerClient dockerClient;
private DockerHostResolver dockerHostResolver;
private EksClusterManager manager;
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);
tls = Mockito.mock(EmulatorConfig.TlsConfig.class);
when(config.services()).thenReturn(services);
when(services.eks()).thenReturn(eks);
when(eks.podIdentityWebhook()).thenReturn(true);
when(config.tls()).thenReturn(tls);
when(tls.enabled()).thenReturn(true);
when(config.port()).thenReturn(4566);
lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
dockerClient = Mockito.mock(DockerClient.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
dockerHostResolver = Mockito.mock(DockerHostResolver.class);
when(dockerHostResolver.resolve()).thenReturn("floci-host");
capturedCmds = new ArrayList<>();
ExecCreateCmd 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);
manager = new EksClusterManager(
Mockito.mock(ContainerBuilder.class), lifecycleManager,
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
dockerHostResolver, Mockito.mock(EcrRegistryManager.class),
config, Mockito.mock(RegionResolver.class), null);
}
@Test
void configuresRelayWhenPodIdentityEnabled() {
Cluster cluster = new Cluster();
cluster.setName("test-cluster");
manager.configurePodIdentityRelay(cluster, "cid-1");
assertEquals(3, capturedCmds.size());
assertTrue(capturedCmds.get(0)[2].contains("command -v socat"));
assertTrue(capturedCmds.get(1)[2].contains("169.254.170.23"));
assertTrue(capturedCmds.get(1)[2].contains("TCP:floci-host:4566"));
assertTrue(capturedCmds.get(1)[2].contains("floci-pod-identity-proxy.pid"));
assertTrue(capturedCmds.get(2)[2].contains("FLOCI-LINK-LOCAL"));
assertTrue(capturedCmds.get(2)[2].contains("169.254.170.23"));
assertFalse(capturedCmds.get(2)[2].contains("169.254.169.254"),
"Pod identity relay must not route IMDS traffic");
}
@Test
void skipsRelayWhenPodIdentityDisabled() {
when(eks.podIdentityWebhook()).thenReturn(false);
Cluster cluster = new Cluster();
cluster.setName("test-cluster");
manager.configurePodIdentityRelay(cluster, "cid-1");
assertTrue(capturedCmds.isEmpty());
}
@Test
void skipsRelayWhenTlsDisabled() {
when(tls.enabled()).thenReturn(false);
Cluster cluster = new Cluster();
cluster.setName("test-cluster");
manager.configurePodIdentityRelay(cluster, "cid-1");
assertTrue(capturedCmds.isEmpty());
}
@Test
void failsGracefullyWhenExecFails() {
InspectExecCmd inspectExec = Mockito.mock(InspectExecCmd.class);
InspectExecResponse inspectResponse = Mockito.mock(InspectExecResponse.class);
when(inspectResponse.getExitCodeLong()).thenReturn(1L);
when(inspectExec.exec()).thenReturn(inspectResponse);
when(dockerClient.inspectExecCmd(anyString())).thenReturn(inspectExec);
Cluster cluster = new Cluster();
cluster.setName("test-cluster");
assertDoesNotThrow(() -> manager.configurePodIdentityRelay(cluster, "cid-1"));
}
}
@Nested
class IrsaSigningKey {
@@ -1466,6 +1595,7 @@ class EksClusterManagerTest {
assertTrue(manifest.contains("caBundle: \""
+ Base64.getEncoder().encodeToString(CA_PEM.getBytes(StandardCharsets.UTF_8)) + "\""));
assertTrue(manifest.contains("failurePolicy: Ignore"));
assertTrue(manifest.contains("timeoutSeconds: 3"));
assertTrue(manifest.contains("operations: [\"CREATE\"]"));
assertTrue(manifest.contains("resources: [\"pods\"]"));
assertFalse(manifest.contains("url: \"http://"), "Kubernetes rejects a non-https webhook URL");
@@ -247,6 +247,24 @@ class EksPodIdentityAssociationServiceTest {
assertThrows(AwsException.class, () -> fixture.service.list(fixture.cluster, null, null, null, null));
}
@Test
void clusterWithNullArnDoesNotThrowNpe() {
Fixture fixture = fixture();
fixture.cluster.setArn(null);
fixture.cluster.setCreatedAt(null);
CreatePodIdentityAssociationRequest request = new CreatePodIdentityAssociationRequest(
fixture.cluster.getName(), NAMESPACE, SERVICE_ACCOUNT, ROLE, null, Map.of(), null, null, null);
PodIdentityAssociation created = fixture.service.create(fixture.cluster, request);
assertNotNull(created);
assertEquals("test-cluster", created.clusterName());
assertTrue(created.associationArn().contains(":podidentityassociation/test-cluster/"));
Optional<PodIdentityAssociation> found = fixture.service.findAssociation(fixture.cluster, NAMESPACE, SERVICE_ACCOUNT);
assertTrue(found.isPresent());
assertEquals(created.associationId(), found.get().associationId());
}
private static Fixture fixture() {
Cluster cluster = new Cluster();
cluster.setName("test-cluster");
@@ -0,0 +1,230 @@
package io.github.hectorvent.floci.services.eks;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
import io.github.hectorvent.floci.services.eks.model.EksPodIdentityCredentialsResponse;
import io.github.hectorvent.floci.services.eks.model.PodIdentityAssociation;
import io.github.hectorvent.floci.services.iam.IamService;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.time.Instant;
import java.util.Base64;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class EksPodIdentityCredentialsControllerTest {
private static final String ISSUER =
"https://oidc.eks.us-east-1.amazonaws.com/id/A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4";
private static final String CLUSTER_NAME = "demo-cluster";
private static final String ACCOUNT_ID = "123456789012";
private static final String NAMESPACE = "workloads";
private static final String SERVICE_ACCOUNT = "app-sa";
private static final String ROLE_ARN = "arn:aws:iam::123456789012:role/app-role";
private EksService eksService;
private EksOidcService oidcService;
private EksPodIdentityAssociationService associationService;
private IamService iamService;
private WebIdentityTokenVerifier tokenVerifier;
private EksPodIdentityCredentialsController controller;
private KeyPair keyPair;
private Cluster cluster;
@BeforeEach
void setUp() throws GeneralSecurityException {
keyPair = newKeyPair();
eksService = Mockito.mock(EksService.class);
oidcService = Mockito.mock(EksOidcService.class);
associationService = Mockito.mock(EksPodIdentityAssociationService.class);
iamService = Mockito.mock(IamService.class);
tokenVerifier = new WebIdentityTokenVerifier(new ObjectMapper());
controller = new EksPodIdentityCredentialsController(
eksService, oidcService, associationService, iamService, tokenVerifier
);
cluster = new Cluster();
cluster.setName(CLUSTER_NAME);
cluster.setAccountId(ACCOUNT_ID);
cluster.setStatus(ClusterStatus.ACTIVE);
when(eksService.findClusterByIssuer(ISSUER)).thenReturn(Optional.of(cluster));
when(oidcService.findVerificationKey(ISSUER)).thenReturn(Optional.of((RSAPublicKey) keyPair.getPublic()));
PodIdentityAssociation association = new PodIdentityAssociation(
CLUSTER_NAME,
NAMESPACE,
SERVICE_ACCOUNT,
ROLE_ARN,
"arn:aws:eks:us-east-1:" + ACCOUNT_ID + ":podidentityassociation/" + CLUSTER_NAME + "/assoc-1",
"assoc-1",
null,
1000.0,
1000.0,
null,
null,
false,
null,
null
);
when(associationService.findAssociation(cluster, NAMESPACE, SERVICE_ACCOUNT))
.thenReturn(Optional.of(association));
}
private static KeyPair newKeyPair() throws GeneralSecurityException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
return generator.generateKeyPair();
}
private static String signRs256(PrivateKey key, String claims) throws GeneralSecurityException {
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
String header = enc.encodeToString("{\"alg\":\"RS256\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8));
String payload = enc.encodeToString(claims.getBytes(StandardCharsets.UTF_8));
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(key);
sig.update((header + "." + payload).getBytes(StandardCharsets.UTF_8));
return header + "." + payload + "." + enc.encodeToString(sig.sign());
}
private String buildToken(PrivateKey key, String iss, String aud, String sub, long expOffset) throws GeneralSecurityException {
long now = Instant.now().getEpochSecond();
return signRs256(key, String.format(
"{\"iss\":\"%s\",\"aud\":[\"%s\"],\"sub\":\"%s\",\"iat\":%d,\"nbf\":%d,\"exp\":%d}",
iss, aud, sub, now - 10, now - 10, now + expOffset));
}
private String validToken() throws GeneralSecurityException {
return buildToken(keyPair.getPrivate(), ISSUER, "pods.eks.amazonaws.com",
"system:serviceaccount:" + NAMESPACE + ":" + SERVICE_ACCOUNT, 3600);
}
@Test
void returnsCredentialsForValidTokenWithBearerPrefix() throws Exception {
Response response = controller.getCredentials("Bearer " + validToken());
assertEquals(200, response.getStatus());
assertTrue(response.getEntity() instanceof EksPodIdentityCredentialsResponse);
EksPodIdentityCredentialsResponse creds = (EksPodIdentityCredentialsResponse) response.getEntity();
assertNotNull(creds.accessKeyId());
assertTrue(creds.accessKeyId().startsWith("ASIA"));
assertNotNull(creds.secretAccessKey());
assertNotNull(creds.token());
assertEquals(ACCOUNT_ID, creds.accountId());
assertNotNull(creds.expiration());
ArgumentCaptor<String> akidCaptor = ArgumentCaptor.forClass(String.class);
verify(iamService).registerSession(akidCaptor.capture(), eq(creds.secretAccessKey()),
eq(creds.token()), eq(ROLE_ARN), any(Instant.class), eq(null), eq(ACCOUNT_ID));
assertEquals(creds.accessKeyId(), akidCaptor.getValue());
}
@Test
void supportsRawTokenWithoutBearerPrefix() throws Exception {
Response response = controller.getCredentials(validToken());
assertEquals(200, response.getStatus());
assertTrue(response.getEntity() instanceof EksPodIdentityCredentialsResponse);
}
@Test
void rejectsMissingOrBlankAuthorizationHeader() {
for (String auth : new String[]{null, " ", "Bearer "}) {
Response response = controller.getCredentials(auth);
assertEquals(400, response.getStatus());
assertEquals("Service account token cannot be empty\n", response.getEntity());
}
verifyNoInteractions(iamService);
}
@Test
void rejectsMalformedToken() {
Response response = controller.getCredentials("not.a.valid.jwt");
assertEquals(400, response.getStatus());
assertEquals("Service account token cannot be parsed\n", response.getEntity());
verifyNoInteractions(iamService);
}
@Test
void rejectsTokenForUnknownCluster() throws Exception {
String token = buildToken(keyPair.getPrivate(), "https://oidc.eks.us-east-1.amazonaws.com/id/UNKNOWN",
"pods.eks.amazonaws.com", "system:serviceaccount:" + NAMESPACE + ":" + SERVICE_ACCOUNT, 3600);
Response response = controller.getCredentials(token);
assertEquals(400, response.getStatus());
assertEquals("The web identity token issuer is not recognized\n", response.getEntity());
verifyNoInteractions(iamService);
}
@Test
void rejectsExpiredToken() throws Exception {
String token = buildToken(keyPair.getPrivate(), ISSUER, "pods.eks.amazonaws.com",
"system:serviceaccount:" + NAMESPACE + ":" + SERVICE_ACCOUNT, -100);
Response response = controller.getCredentials(token);
assertEquals(400, response.getStatus());
assertEquals("The web identity token that was passed is expired\n", response.getEntity());
verifyNoInteractions(iamService);
}
@Test
void rejectsInvalidSignature() throws Exception {
String token = buildToken(newKeyPair().getPrivate(), ISSUER, "pods.eks.amazonaws.com",
"system:serviceaccount:" + NAMESPACE + ":" + SERVICE_ACCOUNT, 3600);
Response response = controller.getCredentials(token);
assertEquals(400, response.getStatus());
assertEquals("InvalidToken: The web identity token signature is invalid\n", response.getEntity());
verifyNoInteractions(iamService);
}
@Test
void rejectsWrongAudience() throws Exception {
String token = buildToken(keyPair.getPrivate(), ISSUER, "sts.amazonaws.com",
"system:serviceaccount:" + NAMESPACE + ":" + SERVICE_ACCOUNT, 3600);
Response response = controller.getCredentials(token);
assertEquals(400, response.getStatus());
assertEquals("InvalidToken: The web identity token audience does not include pods.eks.amazonaws.com\n", response.getEntity());
verifyNoInteractions(iamService);
}
@Test
void rejectsInvalidSubject() throws Exception {
String token = buildToken(keyPair.getPrivate(), ISSUER, "pods.eks.amazonaws.com", "system:node:worker-1", 3600);
Response response = controller.getCredentials(token);
assertEquals(400, response.getStatus());
assertEquals("Service account token subject is invalid\n", response.getEntity());
verifyNoInteractions(iamService);
}
@Test
void returns404WhenNoAssociationFound() throws Exception {
String sa = "other-sa";
String token = buildToken(keyPair.getPrivate(), ISSUER, "pods.eks.amazonaws.com",
"system:serviceaccount:" + NAMESPACE + ":" + sa, 3600);
when(associationService.findAssociation(cluster, NAMESPACE, sa)).thenReturn(Optional.empty());
Response response = controller.getCredentials(token);
assertEquals(404, response.getStatus());
assertEquals("ResourceNotFoundException: No association found for service account: " + sa + "\n", response.getEntity());
verifyNoInteractions(iamService);
}
}
@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.services.eks;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.eks.model.EksPodIdentityCredentialsResponse;
import org.junit.jupiter.api.Test;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.junit.jupiter.api.Assertions.assertEquals;
class EksPodIdentityCredentialsWireFormatTest {
private final ObjectMapper objectMapper = new ObjectMapper();
@Test
void credentialsResponseMatchesAwsContainerCredentialsSchema() throws Exception {
EksPodIdentityCredentialsResponse response = new EksPodIdentityCredentialsResponse(
"ASIAEXAMPLEKEYID123",
"secretAccessKey1234567890",
"sessionToken1234567890",
"123456789012",
"2026-09-21T21:00:00Z"
);
String json = objectMapper.writeValueAsString(response);
JsonNode node = objectMapper.readTree(json);
assertEquals("ASIAEXAMPLEKEYID123", node.path("AccessKeyId").asText());
assertEquals("secretAccessKey1234567890", node.path("SecretAccessKey").asText());
assertEquals("sessionToken1234567890", node.path("Token").asText());
assertEquals("123456789012", node.path("AccountId").asText());
assertEquals("2026-09-21T21:00:00Z", node.path("Expiration").asText());
Set<String> fieldNames = StreamSupport.stream(
((Iterable<String>) () -> node.fieldNames()).spliterator(), false
).collect(Collectors.toSet());
assertEquals(Set.of("AccessKeyId", "SecretAccessKey", "Token", "AccountId", "Expiration"), fieldNames);
}
}
@@ -0,0 +1,207 @@
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.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.github.hectorvent.floci.services.eks.model.ClusterIdentity;
import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey;
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
import io.github.hectorvent.floci.services.eks.model.CreatePodIdentityAssociationRequest;
import io.github.hectorvent.floci.services.eks.model.OidcIdentity;
import io.github.hectorvent.floci.services.iam.IamService;
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.time.Instant;
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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(EksPodIdentityDockerIntegrationTest.Profile.class)
class EksPodIdentityDockerIntegrationTest {
public static final class Profile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.services.eks.pod-identity-webhook", "true",
"floci.tls.enabled", "true",
"floci.tls.aws-https-port", "0",
"quarkus.http.test-port", "4510",
"quarkus.http.test-ssl-port", "4511",
"floci.port", "4595",
"floci.base-url", "http://localhost:4595");
}
}
private static final Logger LOG = Logger.getLogger(EksPodIdentityDockerIntegrationTest.class);
private static final String TEST_IMAGE = "alpine:3.21";
@Inject
DockerClient dockerClient;
@Inject
ContainerBuilder containerBuilder;
@Inject
ContainerLifecycleManager lifecycleManager;
@Inject
EmulatorConfig config;
@Inject
EksService eksService;
@Inject
EksOidcService oidcService;
@Inject
EksPodIdentityAssociationService associationService;
@Inject
IamService iamService;
@Inject
EksClusterManager eksClusterManager;
@Inject
DockerHostResolver dockerHostResolver;
private String containerId;
private Cluster cluster;
private String clusterName;
private String roleName;
@BeforeEach
void requireDocker() {
boolean dockerAvailable = isDockerAvailable();
if (!dockerAvailable) {
LOG.warn("Docker daemon is not available; skipping EksPodIdentityDockerIntegrationTest");
}
Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for EKS Pod Identity integration test");
Assumptions.assumeTrue(dockerHostResolver.isLinuxHost(),
"Link-local Pod Identity container test requires a Linux host; on macOS/Windows, container-to-host proxy traffic arrives from 127.0.0.1 which collides across clusters");
}
@AfterEach
void tearDown() {
if (clusterName != null) {
try {
eksService.deleteClusterForAccount("000000000000", clusterName);
} catch (Exception ignored) {
}
}
if (roleName != null) {
try {
iamService.deleteRole(roleName);
} catch (Exception ignored) {
}
}
if (containerId != null) {
try {
lifecycleManager.stopAndRemove(containerId, null);
} catch (Exception ignored) {
}
}
}
@Test
void linkLocalPodIdentityEndpointAnswersInsideClusterContainer() throws Exception {
clusterName = "pi-it-" + UUID.randomUUID().toString().substring(0, 8);
roleName = "pi-it-role-" + UUID.randomUUID().toString().substring(0, 8);
String roleArn = "arn:aws:iam::000000000000:role/" + roleName;
iamService.createRole(roleName, "/", "{\"Version\":\"2012-10-17\",\"Statement\":[]}", null, 3600, null);
cluster = new Cluster();
cluster.setName(clusterName);
cluster.setAccountId("000000000000");
cluster.setArn("arn:aws:eks:us-east-1:000000000000:cluster/" + clusterName);
cluster.setCreatedAt(Instant.now());
cluster.setStatus(ClusterStatus.ACTIVE);
String issuer = "https://oidc.eks.us-east-1.amazonaws.com/id/" + UUID.randomUUID().toString().replace("-", "").toUpperCase();
cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer)));
eksService.putClusterForAccount("000000000000", cluster);
ClusterOidcKey key = oidcService.ensureKeyForAccount("000000000000", clusterName, issuer);
assertNotNull(key);
associationService.create(cluster, new CreatePodIdentityAssociationRequest(
clusterName, "default", "workload-sa", roleArn, null, null, null, null, null
));
ContainerSpec spec = containerBuilder.newContainer(TEST_IMAGE)
.withName("floci-eks-pi-test-" + clusterName)
.withPrivileged(true)
.withHostDockerInternalOnLinux()
.withCmd(List.of("sleep", "300"))
.build();
containerId = lifecycleManager.createAndStart(spec).containerId();
assertNotNull(containerId, "Container ID must not be null");
execInContainer(containerId, "command -v curl >/dev/null 2>&1 && command -v iptables >/dev/null 2>&1 && command -v ip >/dev/null 2>&1 || apk add --no-cache curl iptables iproute2");
eksClusterManager.configurePodIdentityRelay(cluster, containerId);
String validToken = oidcService.mintServiceAccountToken(clusterName, issuer, "default", "workload-sa",
"pods.eks.amazonaws.com", 3600);
String credsJson = execInContainer(containerId, "curl -s -f -H 'Authorization: " + validToken + "' http://169.254.170.23/v1/credentials");
assertNotNull(credsJson);
assertTrue(credsJson.contains("\"AccessKeyId\""));
assertTrue(credsJson.contains("ASIA"));
String unassociatedToken = oidcService.mintServiceAccountToken(clusterName, issuer, "default", "other-sa",
"pods.eks.amazonaws.com", 3600);
String missingCode = execInContainer(containerId, "curl -s -o /dev/null -w '%{http_code}' -H 'Authorization: " + unassociatedToken + "' http://169.254.170.23/v1/credentials");
assertEquals("404", missingCode.trim());
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
return true;
} catch (Exception e) {
return false;
}
}
private String execInContainer(String containerId, String cmd) throws Exception {
ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerId)
.withCmd("sh", "-c", cmd)
.withAttachStdout(true)
.withAttachStderr(true)
.exec();
StringBuilder stdout = new StringBuilder();
dockerClient.execStartCmd(exec.getId()).exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
if (frame != null && frame.getPayload() != null) {
stdout.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
}
}
}).awaitCompletion(30, TimeUnit.SECONDS);
return stdout.toString();
}
}