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

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