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

+12 -10
View File
@@ -93,9 +93,7 @@ Floci supports the EKS Pod Identity association management plane. You can map a
### Credential injection at admission
Injection is off by default. Set `FLOCI_SERVICES_EKS_POD_IDENTITY_WEBHOOK=true` to turn it on, and read the warning at the end of this section first: nothing answers the injected URI yet, so an injected pod is worse off than an uninjected one.
With it on, Floci registers a `MutatingWebhookConfiguration` in every real-mode cluster, scoped to pod `CREATE`. When a pod is created, Floci looks up an association matching the pod's namespace and its `spec.serviceAccountName`. A pod that matches nothing is admitted unchanged.
Floci registers a `MutatingWebhookConfiguration` in every real-mode cluster, scoped to pod `CREATE`. When a pod is created, Floci looks up an association matching the pod's namespace and its `spec.serviceAccountName`. A pod that matches nothing is admitted unchanged.
Injection happens only when the `eks-pod-identity-agent` addon is installed on the cluster, which is what real EKS requires too. Install it with `CreateAddon` before expecting pods to be mutated.
@@ -109,7 +107,16 @@ A matching pod is patched exactly the way real EKS patches it. Every init contai
The volume is a projected service account token with audience `pods.eks.amazonaws.com`, `expirationSeconds: 86400` and path `eks-pod-identity-token`. A name the pod already carries (a volume, a mount, or either environment variable) is left as the workload set it.
**Nothing answers `169.254.170.23` yet, which is why this is off by default.** An injected pod has the token and the environment variables, so the AWS SDK credential chain takes the container credentials path, and that path fails: the request to the URI goes nowhere. A workload that was picking up credentials earlier in the chain loses them. Leave the setting off until the credential endpoint lands, unless you are working on that endpoint.
### Credential endpoint
Floci serves pod identity credentials through a link-local relay bound to `169.254.170.23:80` inside the cluster container, forwarding requests to Floci's credentials endpoint (`GET /v1/credentials`). Workloads reach this endpoint using the injected `AWS_CONTAINER_CREDENTIALS_FULL_URI` environment variable, passing their projected token in the `Authorization` header (`Authorization: <token>` or `Authorization: Bearer <token>`).
The credentials endpoint performs the following validations:
1. Validates token format and extracts the issuer URL without verifying signatures yet.
2. Identifies the matching EKS cluster by comparing the token issuer URL to cluster OIDC issuer URLs.
3. Validates the token signature against the cluster OIDC public key, confirming the token is unexpired and carries audience `pods.eks.amazonaws.com`.
4. Extracts the subject claim (`system:serviceaccount:<namespace>:<serviceAccount>`) and looks up the pod identity association for the cluster, namespace, and service account.
5. Issues temporary session credentials (`ASIA...`) for the associated IAM role and returns them in standard AWS container credentials format (`AccessKeyId`, `SecretAccessKey`, `Token`, `AccountId`, `Expiration`).
#### TLS is required
@@ -121,11 +128,6 @@ The webhook carries `failurePolicy: Ignore`, and Floci admits the pod unchanged
The manifest is written into the cluster's k3s server manifests directory (`/var/lib/rancher/k3s/server/manifests`) before the container starts, so k3s applies it as the API server comes up.
### Limitations and Scope
- The link-local credential endpoint (`169.254.170.23`) that answers the injected URI is not implemented, so injected pods cannot yet obtain credentials.
- Token validation, association-to-role resolution and STS credential issuance belong to that endpoint and do not exist yet.
## Addon management
Floci supports the EKS cluster addon management plane for AWS SDKs and Terraform (`aws_eks_addon` resource).
@@ -369,7 +371,7 @@ back (for example Docker is unavailable), the cluster is marked `FAILED` instead
| `FLOCI_SERVICES_EKS_IAM_AUTH_WEBHOOK` | `true` | Wire a token-auth webhook into k3s so `aws eks get-token` works |
| `FLOCI_SERVICES_EKS_ECR_REGISTRY_MIRROR` | `true` | Inject a containerd `registries.yaml` so pods can pull images pushed to [Floci ECR](ecr.md) |
| `FLOCI_SERVICES_EKS_IRSA_SIGNING_KEY` | `true` | Pass the cluster OIDC signing key to k3s so in-cluster projected service account tokens can assume IAM roles via Floci STS |
| `FLOCI_SERVICES_EKS_POD_IDENTITY_WEBHOOK` | `false` | Register a mutating admission webhook that injects pod identity credentials. Needs `FLOCI_TLS_ENABLED=true`. Off until the credential endpoint exists |
| `FLOCI_SERVICES_EKS_POD_IDENTITY_WEBHOOK` | `true` | Register a mutating admission webhook that injects pod identity credentials. Needs `FLOCI_TLS_ENABLED=true` |
| `FLOCI_SERVICES_EKS_IMDS` | `false` | Enable link-local IMDS (`169.254.169.254`) proxy in cluster containers |
### Kubernetes versions and network configuration
@@ -2896,16 +2896,11 @@ public interface EmulatorConfig {
* whose service account has an EKS Pod Identity association are mutated at admission with a
* projected pod identity token and the container credentials environment variables.
*
* <p>Off by default until the credential endpoint on {@code 169.254.170.23} exists. An
* injected pod points its SDK at that endpoint, and nothing answers it yet, so turning this
* on today takes a workload off whatever credentials it was using and gives it a container
* credentials path that fails.
*
* <p>Requires {@link EmulatorConfig#tls()} to be enabled: Kubernetes rejects an admission
* webhook URL that is not {@code https}. With TLS off the webhook is skipped with a warning
* and pods start unmutated.
*/
@WithDefault("false")
@WithDefault("true")
boolean podIdentityWebhook();
}
@@ -42,19 +42,33 @@ public final class Ec2MetadataProxy {
}
public static String[] startCommand(String flociHost, int imdsPort) {
return startCommand("imds", "169.254.169.254", 80, flociHost, imdsPort,
"curl -fsS --max-time 1 http://169.254.169.254/latest/meta-data/instance-id >/dev/null && exit 0");
}
public static String[] podIdentityStartCommand(String flociHost, int flociPort) {
return startCommand("pod-identity", "169.254.170.23", 80, flociHost, flociPort,
"[ \"$(curl -s -o /dev/null -w '%{http_code}' --max-time 1 http://169.254.170.23/v1/credentials)\" != \"000\" ] && exit 0");
}
public static String[] startCommand(String name, String bindIp, int bindPort,
String targetHost, int targetPort, String probeCommand) {
String pidFile = "/tmp/floci-" + name + "-proxy.pid";
String logFile = "/tmp/floci-" + name + "-proxy.log";
return new String[]{"sh", "-c", String.join("\n",
"set -eu",
"ip addr show dev lo | grep -q '169.254.169.254/32' || ip addr add 169.254.169.254/32 dev lo",
"if [ -f /tmp/floci-imds-proxy.pid ] && kill -0 \"$(cat /tmp/floci-imds-proxy.pid)\" 2>/dev/null; then",
"ip addr show dev lo | grep -q '" + bindIp + "/32' || ip addr add " + bindIp + "/32 dev lo",
"if [ -f " + pidFile + " ] && kill -0 \"$(cat " + pidFile + ")\" 2>/dev/null; then",
" exit 0",
"fi",
"nohup socat TCP-LISTEN:80,bind=169.254.169.254,fork,reuseaddr TCP:" + flociHost + ":" + imdsPort + " >/tmp/floci-imds-proxy.log 2>&1 &",
"echo $! > /tmp/floci-imds-proxy.pid",
"nohup socat TCP-LISTEN:" + bindPort + ",bind=" + bindIp + ",fork,reuseaddr TCP:"
+ targetHost + ":" + targetPort + " >" + logFile + " 2>&1 &",
"echo $! > " + pidFile,
"for i in 1 2 3 4 5 6 7 8 9 10 11 12; do",
" curl -fsS --max-time 1 http://169.254.169.254/latest/meta-data/instance-id >/dev/null && exit 0",
" " + probeCommand,
" sleep 1",
"done",
"cat /tmp/floci-imds-proxy.log >&2 || true",
"cat " + logFile + " >&2 || true",
"exit 1")};
}
@@ -393,6 +393,7 @@ public class EksClusterManager {
applyEndpoints(cluster, containerName, hostPort, info);
configureLinkLocalMetadataEndpoint(cluster, containerId);
configurePodIdentityRelay(cluster, containerId);
attachClusterLogs(cluster);
LOG.infov("k3s container {0} started for cluster {1} on port {2} (internal: {3})",
@@ -449,6 +450,7 @@ public class EksClusterManager {
cluster.setHostPort(hostPort);
applyEndpoints(cluster, containerName, hostPort, info);
configureLinkLocalMetadataEndpoint(cluster, info.containerId());
configurePodIdentityRelay(cluster, info.containerId());
attachClusterLogsFromNow(cluster);
LOG.infov("Adopted surviving k3s container {0} for EKS cluster {1} on port {2} (internal: {3})",
@@ -1317,6 +1319,39 @@ public class EksClusterManager {
}
}
void configurePodIdentityRelay(Cluster cluster, String containerId) {
if (!config.services().eks().podIdentityWebhook() || !config.tls().enabled()) {
return;
}
try {
ContainerExecResult install = execInContainerForResult(containerId,
Ec2MetadataProxy.installCommand(), 180);
if (install.exitCode() != 0) {
LOG.warnv("Could not install Pod Identity relay dependencies for EKS cluster {0}: {1}",
cluster.getName(), install.summary());
return;
}
String flociHost = dockerHostResolver.resolve();
int flociPort = config.port();
ContainerExecResult start = execInContainerForResult(containerId,
Ec2MetadataProxy.podIdentityStartCommand(flociHost, flociPort), 30);
if (start.exitCode() != 0) {
LOG.warnv("Could not start link-local Pod Identity relay for EKS cluster {0}: {1}",
cluster.getName(), start.summary());
return;
}
configurePodNetworkRouting(cluster, containerId, List.of(EksPodNetworkRouting.POD_IDENTITY_ENDPOINT));
LOG.infov("Configured link-local Pod Identity relay for EKS cluster {0}", cluster.getName());
} catch (Exception e) {
LOG.warnv("Could not configure link-local Pod Identity relay for EKS cluster {0}: {1}",
cluster.getName(), e.getMessage());
}
}
void configurePodNetworkRouting(Cluster cluster, String containerId) {
configurePodNetworkRouting(cluster, containerId, EksPodNetworkRouting.DEFAULT_ENDPOINTS);
}
@@ -23,6 +23,7 @@ import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
/**
@@ -117,9 +118,19 @@ public class EksPodIdentityAssociationService {
}
String associationId = generateAssociationId();
String[] clusterArn = cluster.getArn().split(":", 6);
String associationArn = "arn:" + clusterArn[1] + ":eks:" + clusterArn[3] + ":"
+ clusterArn[4] + ":podidentityassociation/" + cluster.getName() + "/" + associationId;
String partition = "aws";
String region = "us-east-1";
String accountId = cluster.getAccountId() != null ? cluster.getAccountId() : "000000000000";
if (cluster.getArn() != null) {
String[] clusterArn = cluster.getArn().split(":", 6);
if (clusterArn.length == 6) {
partition = clusterArn[1];
region = clusterArn[3];
accountId = clusterArn[4];
}
}
String associationArn = "arn:" + partition + ":eks:" + region + ":"
+ accountId + ":podidentityassociation/" + cluster.getName() + "/" + associationId;
double now = Instant.now().toEpochMilli() / 1000.0;
String externalId = UUID.randomUUID().toString();
@@ -277,8 +288,22 @@ public class EksPodIdentityAssociationService {
}
}
public synchronized Optional<PodIdentityAssociation> findAssociation(Cluster cluster,
String namespace,
String serviceAccount) {
if (cluster == null || cluster.getStatus() != ClusterStatus.ACTIVE) {
return Optional.empty();
}
String prefix = prefix(cluster);
return associations.scan(key -> key.startsWith(prefix)).stream()
.map(StoredAssociation::association)
.filter(a -> a.namespace().equals(namespace) && a.serviceAccount().equals(serviceAccount))
.findFirst();
}
private static String prefix(Cluster cluster) {
return cluster.getArn() + "/" + Objects.toString(cluster.getCreatedAt()) + "/";
String base = cluster.getArn() != null ? cluster.getArn() : cluster.getName();
return base + "/" + Objects.toString(cluster.getCreatedAt()) + "/";
}
private static void requireActiveCluster(Cluster cluster) {
@@ -292,8 +317,14 @@ public class EksPodIdentityAssociationService {
private void validateRoleArn(Cluster cluster, String roleArn, String fieldName) {
String[] arn = roleArn.split(":", 6);
String[] clusterArn = cluster.getArn().split(":", 6);
if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(clusterArn[1])
String expectedPartition = "aws";
if (cluster != null && cluster.getArn() != null) {
String[] clusterArn = cluster.getArn().split(":", 6);
if (clusterArn.length > 1) {
expectedPartition = clusterArn[1];
}
}
if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(expectedPartition)
|| !"iam".equals(arn[2]) || !arn[3].isEmpty() || !arn[4].matches("[0-9]{12}")
|| !arn[5].startsWith("role/") || arn[5].startsWith("role/aws-service-role/")
|| roleArn.endsWith("/")) {
@@ -307,8 +338,14 @@ public class EksPodIdentityAssociationService {
private static void validateTargetRoleArn(Cluster cluster, String targetRoleArn) {
String[] arn = targetRoleArn.split(":", 6);
String[] clusterArn = cluster.getArn().split(":", 6);
if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(clusterArn[1])
String expectedPartition = "aws";
if (cluster != null && cluster.getArn() != null) {
String[] clusterArn = cluster.getArn().split(":", 6);
if (clusterArn.length > 1) {
expectedPartition = clusterArn[1];
}
}
if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(expectedPartition)
|| !"iam".equals(arn[2]) || !arn[3].isEmpty() || !arn[4].matches("[0-9]{12}")
|| !arn[5].startsWith("role/") || targetRoleArn.endsWith("/")) {
throw invalid("targetRoleArn must identify an IAM role");
@@ -0,0 +1,172 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.WebIdentityToken;
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier.ExpiredTokenException;
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier.InvalidTokenException;
import io.github.hectorvent.floci.services.eks.model.Cluster;
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.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.security.SecureRandom;
import java.security.interfaces.RSAPublicKey;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
/**
* Serves the link-local EKS Pod Identity credentials endpoint (169.254.170.23:80).
* <p>
* Pods running with projected service account tokens call this endpoint to exchange
* their token for temporary AWS IAM role credentials associated with the pod's service account.
*/
@ApplicationScoped
@Path("/v1/credentials")
public class EksPodIdentityCredentialsController {
private static final String POD_IDENTITY_AUDIENCE = "pods.eks.amazonaws.com";
private static final String SERVICE_ACCOUNT_PREFIX = "system:serviceaccount:";
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
private static final String ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/** CSPRNG for session secret keys and session tokens; ordinary IDs keep using {@link ThreadLocalRandom}. */
private final SecureRandom secureRandom = new SecureRandom();
private final EksService eksService;
private final EksOidcService oidcService;
private final EksPodIdentityAssociationService associationService;
private final IamService iamService;
private final WebIdentityTokenVerifier tokenVerifier;
@Inject
public EksPodIdentityCredentialsController(EksService eksService,
EksOidcService oidcService,
EksPodIdentityAssociationService associationService,
IamService iamService,
WebIdentityTokenVerifier tokenVerifier) {
this.eksService = eksService;
this.oidcService = oidcService;
this.associationService = associationService;
this.iamService = iamService;
this.tokenVerifier = tokenVerifier;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getCredentials(@HeaderParam("Authorization") String authHeader) {
if (authHeader == null || authHeader.isBlank()) {
return error(400, "Service account token cannot be empty\n");
}
String token = authHeader.trim();
if (token.regionMatches(true, 0, "Bearer", 0, 6)) {
token = token.substring(6).trim();
}
if (token.isEmpty()) {
return error(400, "Service account token cannot be empty\n");
}
Optional<String> maybeIssuer = tokenVerifier.peekIssuer(token);
if (maybeIssuer.isEmpty()) {
return error(400, "Service account token cannot be parsed\n");
}
String issuer = maybeIssuer.get();
Optional<Cluster> maybeCluster = eksService.findClusterByIssuer(issuer);
Optional<RSAPublicKey> maybeKey = oidcService.findVerificationKey(issuer);
if (maybeCluster.isEmpty() || maybeKey.isEmpty()) {
return error(400, "The web identity token issuer is not recognized\n");
}
Cluster cluster = maybeCluster.get();
RSAPublicKey publicKey = maybeKey.get();
WebIdentityToken verified;
try {
verified = tokenVerifier.verify(token, publicKey, issuer, POD_IDENTITY_AUDIENCE);
} catch (ExpiredTokenException e) {
return error(400, "The web identity token that was passed is expired\n");
} catch (InvalidTokenException e) {
return error(400, "InvalidToken: " + e.getMessage() + "\n");
} catch (Exception e) {
return error(400, "Service account token cannot be parsed: " + e.getMessage() + "\n");
}
String sub = verified.subject();
if (sub == null || !sub.startsWith(SERVICE_ACCOUNT_PREFIX)) {
return error(400, "Service account token subject is invalid\n");
}
String rest = sub.substring(SERVICE_ACCOUNT_PREFIX.length());
int colon = rest.indexOf(':');
if (colon <= 0 || colon == rest.length() - 1) {
return error(400, "Service account token subject is invalid\n");
}
String namespace = rest.substring(0, colon);
String serviceAccount = rest.substring(colon + 1);
Optional<PodIdentityAssociation> maybeAssociation = associationService.findAssociation(
cluster, namespace, serviceAccount);
if (maybeAssociation.isEmpty()) {
return error(404, "ResourceNotFoundException: No association found for service account: "
+ serviceAccount + "\n");
}
PodIdentityAssociation association = maybeAssociation.get();
String roleArn = association.roleArn();
String callerAccountId = cluster.getAccountId();
String roleAccountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
String accessKeyId = "ASIA" + randomId(16);
String secretAccessKey = randomSecret(40);
String sessionToken = randomSecret(200);
Instant expiration = Instant.now().plus(Duration.ofHours(1));
iamService.registerSession(accessKeyId, secretAccessKey, sessionToken, roleArn,
expiration, association.policy(), callerAccountId);
EksPodIdentityCredentialsResponse response = new EksPodIdentityCredentialsResponse(
accessKeyId,
secretAccessKey,
sessionToken,
roleAccountId,
DateTimeFormatter.ISO_INSTANT.format(expiration)
);
return Response.ok(response, MediaType.APPLICATION_JSON).build();
}
private Response error(int status, String message) {
return Response.status(status)
.entity(message)
.type(MediaType.TEXT_PLAIN)
.build();
}
private String randomId(int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(ALPHANUMERIC.charAt(ThreadLocalRandom.current().nextInt(ALPHANUMERIC.length())));
}
return sb.toString();
}
private String randomSecret(int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(CHARS.charAt(secureRandom.nextInt(CHARS.length())));
}
return sb.toString();
}
}
@@ -16,6 +16,7 @@ public final class EksPodNetworkRouting {
public static final String DEFAULT_POD_CIDR = "10.42.0.0/16";
public static final String CHAIN_NAME = "FLOCI-LINK-LOCAL";
public static final LinkLocalEndpoint IMDS_ENDPOINT = new LinkLocalEndpoint("169.254.169.254", 80);
public static final LinkLocalEndpoint POD_IDENTITY_ENDPOINT = new LinkLocalEndpoint("169.254.170.23", 80);
public static final List<LinkLocalEndpoint> DEFAULT_ENDPOINTS = List.of(IMDS_ENDPOINT);
private EksPodNetworkRouting() {}
@@ -1079,6 +1079,16 @@ public class EksService implements TagHandler, ResourceProvider {
}, 2, 3, TimeUnit.SECONDS);
}
public Optional<Cluster> findClusterByIssuer(String issuer) {
if (issuer == null || issuer.isBlank()) {
return Optional.empty();
}
return allClusters().stream()
.filter(c -> c.getIdentity() != null && c.getIdentity().getOidc() != null
&& issuer.equals(c.getIdentity().getOidc().getIssuer()))
.findFirst();
}
private List<Cluster> allClusters() {
if (storage instanceof AccountAwareStorageBackend<Cluster> aware) {
return aware.scanAllAccounts();
@@ -0,0 +1,15 @@
package io.github.hectorvent.floci.services.eks.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public record EksPodIdentityCredentialsResponse(
@JsonProperty("AccessKeyId") String accessKeyId,
@JsonProperty("SecretAccessKey") String secretAccessKey,
@JsonProperty("Token") String token,
@JsonProperty("AccountId") String accountId,
@JsonProperty("Expiration") String expiration
) {}
+1 -1
View File
@@ -604,7 +604,7 @@ floci:
imds: false # expose link-local IMDS (169.254.169.254) inside the cluster container
imds-pod-network: false # route link-local IMDS traffic from ordinary pod network namespaces (requires imds: true)
irsa-signing-key: true # sign k3s service account tokens with the cluster OIDC key
pod-identity-webhook: false # register a mutating webhook that injects pod identity credentials (needs floci.tls.enabled; nothing answers the injected URI yet)
pod-identity-webhook: true # register a mutating webhook that injects pod identity credentials (needs floci.tls.enabled)
mwaa:
enabled: true
mock: false
@@ -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();
}
}