diff --git a/docs/services/eks.md b/docs/services/eks.md index 6e85d15901..d7a3286bb7 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -148,6 +148,23 @@ The volume is a projected service account token with audience `pods.eks.amazonaw Real EKS sets neither endpoint variable. Floci adds them so the credentials it hands out are used against Floci, as every container Floci launches already is, instead of being sent to AWS, which rejects them. `AWS_ENDPOINT_URL_STS` is set beside the global variable because the AWS SDK for Go v2 builds the STS client of its web identity provider before it reads `AWS_ENDPOINT_URL`. A pod cannot resolve the Docker host name (`host.docker.internal` lives only in the cluster container's `/etc/hosts`) or, unless the cluster's pods resolve through Floci's embedded DNS (see [DNS resolution](#dns-resolution-and-route-53-private-hosted-zones)), Floci's hostname (k3s replaces a custom Docker network's loopback resolver `127.0.0.11` with a public one, so `localhost.floci.io` answers `127.0.0.1`), so the endpoint is the Docker host address and is injected only when that is an IP address, as it is when Floci runs in a container. A container that sets `AWS_ENDPOINT_URL` itself gets no `AWS_ENDPOINT_URL_STS`, which would override its choice for STS. A container with any `envFrom` source gets no endpoint variable, because its values are unknown at admission and an injected `env` entry would take precedence over them; it still gets the credentials variables. +#### IAM roles for service accounts + +The same webhook also makes the IAM roles for service accounts (IRSA) mutation, as the Amazon EKS pod identity webhook does. A pod that gets no Pod Identity mutation, because no association matches it or the agent addon is not installed, is checked for a service account annotated with `eks.amazonaws.com/role-arn`. The webhook is handed only the pod, so Floci reads the service account with `kubectl` in the cluster container, within two seconds of the webhook's three, even when Docker is slow. A read is reused for 10 seconds, so a burst of pods, and the cluster's own pods of service accounts with no role, cost one read each. So a change to a service account reaches pods created up to 10 seconds later. A failed read is not reused. A service account that is missing, unannotated or unreadable leaves the pod unchanged, and a failed read is logged as a warning. Pod Identity takes precedence, as the upstream webhook's container credentials do, and the two mutations are never made together. + +Every init container and container gets: + +| What | Value | +|---|---| +| `AWS_ROLE_ARN` | The service account's `eks.amazonaws.com/role-arn` | +| `AWS_WEB_IDENTITY_TOKEN_FILE` | `/var/run/secrets/eks.amazonaws.com/serviceaccount/token` | +| `AWS_STS_REGIONAL_ENDPOINTS` | `regional`, unless the service account sets `eks.amazonaws.com/sts-regional-endpoints: "false"` | +| `AWS_DEFAULT_REGION`, `AWS_REGION` | The cluster's Region | +| Volume mount | `/var/run/secrets/eks.amazonaws.com/serviceaccount`, read-only, from volume `aws-iam-token` | +| `AWS_ENDPOINT_URL`, `AWS_ENDPOINT_URL_STS` | Floci's endpoint, under the rules above (Floci only) | + +The volume is a projected service account token with path `token`, audience `sts.amazonaws.com`, and `expirationSeconds` 86400. Floci's STS exchanges a cluster's tokens for `sts.amazonaws.com` alone, so a service account whose `eks.amazonaws.com/audience` names another gets no mutation, with a warning, rather than a token it could not exchange. The service account's `eks.amazonaws.com/token-expiration` overrides the expiry and the pod's overrides that. A value that is not a whole number is ignored, and a shorter one than 600 seconds is raised to 600, the shortest the API server issues. Containers the pod names in its `eks.amazonaws.com/skip-containers` annotation, comma-separated, are left as they are. As upstream, a container that sets either `AWS_ROLE_ARN` or `AWS_WEB_IDENTITY_TOKEN_FILE` gets neither, one that sets either Region variable gets neither, and a volume or mount the pod already has under the name is kept. When that volume is not a projected service account token at path `token`, or a container mounts it elsewhere, the container gets no `AWS_ROLE_ARN` or `AWS_WEB_IDENTITY_TOKEN_FILE`, which would name a token it does not have. Like upstream, the webhook reads only `env` for values the container sets, so its entries take precedence over the same names an `envFrom` source holds. The region variables are what the SDK needs to call STS; the token is exchanged at Floci's STS as described under [IRSA](#irsa-iam-roles-for-service-accounts). + ### Credential endpoint On EKS the Pod Identity Agent answers on `169.254.170.23:80` on every node while the `eks-pod-identity-agent` add-on is installed. Floci makes that address answer in the cluster container while the add-on is stored, with NAT rules that send requests for it straight to Floci's credentials endpoint (`GET /v1/credentials`), so nothing is installed or run in the node. A `PREROUTING` rule takes the pod network's requests (the cluster's pod CIDR) and an `OUTPUT` rule the node's own, which is where `hostNetwork` pods' come from. The node's masquerade rule (flannel's) carries the answers back. Workloads reach this endpoint using the injected `AWS_CONTAINER_CREDENTIALS_FULL_URI` environment variable, passing their projected token in the `Authorization` header (`Authorization: ` or `Authorization: Bearer `). @@ -1070,7 +1087,7 @@ The k3s API server is configured with: - `--kube-apiserver-arg=service-account-issuer=https://kubernetes.default.svc.cluster.local` - `--kube-apiserver-arg=api-audiences=https://kubernetes.default.svc.cluster.local,sts.amazonaws.com` -This enables in-cluster pods to project service account tokens directly using Kubernetes standard projected volumes: +With `floci.services.eks.pod-identity-webhook` and TLS on, annotating the service account with `eks.amazonaws.com/role-arn` is enough: the admission webhook injects the token and the variables, as described under [IAM roles for service accounts](#iam-roles-for-service-accounts). A pod can also project the token itself, using Kubernetes standard projected volumes: ```yaml apiVersion: v1 diff --git a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java index c811806ee4..6258c9e8ef 100644 --- a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java +++ b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java @@ -3589,6 +3589,58 @@ public class EksClusterManager } } + /** + * What a read of a service account found: the service account as {@code kubectl get --output json} prints it, + * null for one that does not exist; or that the read failed, which says nothing about the service account. + */ + record ServiceAccountRead(boolean succeeded, String json) { + + static ServiceAccountRead found(String json) { + return new ServiceAccountRead(true, json); + } + + static ServiceAccountRead absent() { + return new ServiceAccountRead(true, null); + } + + static ServiceAccountRead failed() { + return new ServiceAccountRead(false, null); + } + } + + /** + * Reads the service account {@code name} in {@code namespace} with kubectl in the cluster's server container, + * for the pod identity webhook, which is handed only the pod. A cluster with no container has none to read. A + * failed read is logged as a warning, and a service account that does not exist at debug level. + */ + ServiceAccountRead serviceAccount(Cluster cluster, String namespace, String name, int timeoutSeconds) { + String containerId = cluster.getContainerId(); + if (containerId == null) { + return ServiceAccountRead.absent(); + } + try { + ContainerExec.Result result = execInContainerSeparatingStderr(containerId, + new String[]{"kubectl", "--request-timeout=" + timeoutSeconds + "s", "get", "serviceaccount", name, + "--namespace", namespace, "--output", "json"}, timeoutSeconds); + if (!result.timedOut() && result.exitCode() == 0) { + return ServiceAccountRead.found(result.stdout()); + } + if (!result.timedOut() && result.stderr() != null && result.stderr().contains("(NotFound)")) { + LOG.debugv("Service account {0}/{1} does not exist in cluster {2}", namespace, name, + cluster.getName()); + return ServiceAccountRead.absent(); + } + LOG.warnv("Could not read service account {0}/{1} in cluster {2}, so its pods get no IAM role " + + "injected: {3}", namespace, name, cluster.getName(), + result.timedOut() ? "kubectl did not answer in " + timeoutSeconds + "s" : result.summary()); + return ServiceAccountRead.failed(); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not read service account {0}/{1} in cluster {2}, so its pods get no IAM role " + + "injected", namespace, name, cluster.getName()); + return ServiceAccountRead.failed(); + } + } + String clusterRegion(Cluster cluster) { String region = cluster == null ? null : AwsArnUtils.regionOrDefault(cluster.getArn(), null); if (region != null && !region.isBlank()) { @@ -4257,6 +4309,11 @@ public class EksClusterManager return ContainerExec.runMerged(lifecycleManager.getDockerClient(), containerId, cmd, timeoutSeconds); } + /** {@link #execInContainerForResult} keeping stderr out of stdout, for output that is parsed. */ + ContainerExec.Result execInContainerSeparatingStderr(String containerId, String[] cmd, int timeoutSeconds) { + return ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, timeoutSeconds); + } + /** * Executes launch template UserData script(s) inside the running cluster container. * diff --git a/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java b/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java index b3541fcd41..325992a945 100644 --- a/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java +++ b/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java @@ -1,6 +1,7 @@ package io.floci.aws.services.eks; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RequestScopes; @@ -11,16 +12,30 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.net.URI; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.Base64; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Function; import java.util.function.Supplier; /** - * Admission logic behind the EKS Pod Identity mutating webhook. + * Admission logic behind the EKS Pod Identity mutating webhook, which, as the Amazon EKS pod identity webhook does, + * makes both mutations: EKS Pod Identity's and IAM roles for service accounts'. * *

Real EKS mutates a pod at admission when its service account has a pod identity association * and the {@code eks-pod-identity-agent} addon is installed. The mutation projects a service @@ -30,6 +45,13 @@ import java.util.function.Supplier; * SDK at Floci with {@code AWS_ENDPOINT_URL} and {@code AWS_ENDPOINT_URL_STS}, as it does for every * container it launches itself: otherwise the pod's calls, signed with Floci credentials, go to AWS. * + *

A pod that does not get that mutation gets the IAM roles for service accounts one when its service account + * carries {@value #ANNOTATION_ROLE_ARN}: a projected token for STS and the web identity environment variables, read + * from the service account's annotations and the pod's, as the upstream webhook reads them. The webhook is handed + * only the pod, so the service account is read from the cluster; the upstream webhook keeps a cache of them instead. + * Pod Identity takes precedence, as the upstream webhook's container credentials do, and the two are never injected + * together. + * *

This class injects the plumbing only. {@link #CREDENTIALS_FULL_URI} answers while the addon is * installed: {@link EksClusterManager} forwards its address in the node to * {@link EksPodIdentityCredentialsController}, which hands the pod its association's credentials. @@ -43,6 +65,7 @@ public class EksPodIdentityWebhook { private static final Logger LOG = Logger.getLogger(EksPodIdentityWebhook.class); private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final TypeReference> MAP_TYPE = new TypeReference<>() {}; /** Real EKS only injects when the pod identity agent is installed on the cluster. */ static final String POD_IDENTITY_ADDON = "eks-pod-identity-agent"; @@ -65,28 +88,89 @@ public class EksPodIdentityWebhook { */ static final String ENV_ENDPOINT_URL_STS = "AWS_ENDPOINT_URL_STS"; + /** The service account annotations and pod annotations of IAM roles for service accounts. */ + static final String ANNOTATION_PREFIX = "eks.amazonaws.com/"; // partition-literal: a Kubernetes annotation prefix, not a host; EKS uses it in every partition + static final String ANNOTATION_ROLE_ARN = ANNOTATION_PREFIX + "role-arn"; + static final String ANNOTATION_AUDIENCE = ANNOTATION_PREFIX + "audience"; + static final String ANNOTATION_STS_REGIONAL_ENDPOINTS = ANNOTATION_PREFIX + "sts-regional-endpoints"; + static final String ANNOTATION_TOKEN_EXPIRATION = ANNOTATION_PREFIX + "token-expiration"; + static final String ANNOTATION_SKIP_CONTAINERS = ANNOTATION_PREFIX + "skip-containers"; + + static final String IRSA_VOLUME_NAME = "aws-iam-token"; + static final String IRSA_MOUNT_PATH = "/var/run/secrets/" + ANNOTATION_PREFIX + "serviceaccount"; + static final String IRSA_TOKEN_FILE_NAME = "token"; + static final String IRSA_TOKEN_FILE = IRSA_MOUNT_PATH + "/" + IRSA_TOKEN_FILE_NAME; + static final long IRSA_DEFAULT_TOKEN_EXPIRATION = 86400; + /** The shortest service account token the API server issues, which the upstream webhook raises shorter ones to. */ + static final long IRSA_MIN_TOKEN_EXPIRATION = 600; + + static final String ENV_ROLE_ARN = "AWS_ROLE_ARN"; + static final String ENV_WEB_IDENTITY_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE"; + static final String ENV_STS_REGIONAL_ENDPOINTS = "AWS_STS_REGIONAL_ENDPOINTS"; + static final String ENV_REGION = "AWS_REGION"; + static final String ENV_DEFAULT_REGION = "AWS_DEFAULT_REGION"; + + /** How long the service account lookup may take, inside the webhook's own three-second timeout. */ + static final int SERVICE_ACCOUNT_LOOKUP_SECONDS = 2; + /** + * How long a service account read is reused, so a burst of pods, and the cluster's own pods of service accounts + * with no role, cost one read each: the upstream webhook's informer cache is current within moments instead. + */ + static final Duration SERVICE_ACCOUNT_CACHE_TTL = Duration.ofSeconds(10); + private static final String DEFAULT_API_VERSION = "admission.k8s.io/v1"; private static final String DEFAULT_SERVICE_ACCOUNT = "default"; + /** Reads a service account of a cluster. */ + @FunctionalInterface + interface ServiceAccountReader { + EksClusterManager.ServiceAccountRead read(Cluster cluster, String namespace, String name); + } + + private record ServiceAccountKey(String cluster, String namespace, String name) {} + + /** A read of a service account, in flight or done, which pods created before {@code expiresAt} reuse. */ + private record CachedRead(Instant expiresAt, CompletableFuture read) {} + + /** What the service account's and the pod's annotations ask of the IAM roles for service accounts mutation. */ + record WebIdentity(String roleArn, String audience, long tokenExpiration, boolean regionalSts) {} + private final EksService eks; private final EksAddonService addons; private final EksPodIdentityAssociationService associations; private final Supplier flociEndpoint; + private final ServiceAccountReader serviceAccounts; + private final Function regionOf; + private final Clock clock; + private final Duration lookupTimeout; + private final Map serviceAccountReads = new ConcurrentHashMap<>(); + // A read runs apart from the admission request, so a Docker call that hangs before kubectl even starts still + // leaves the webhook answering within lookupTimeout. + private final ExecutorService lookups = Executors.newVirtualThreadPerTaskExecutor(); /** The endpoint is the Docker host address a launched container gets, when a pod can reach it. */ @Inject public EksPodIdentityWebhook(EksService eks, EksAddonService addons, EksPodIdentityAssociationService associations, - ContainerReachableEndpoint endpoint) { - this(eks, addons, associations, () -> podReachableEndpoint(endpoint.baseUrl(false))); + ContainerReachableEndpoint endpoint, EksClusterManager clusterManager) { + this(eks, addons, associations, () -> podReachableEndpoint(endpoint.baseUrl(false)), + (cluster, namespace, name) -> clusterManager.serviceAccount(cluster, namespace, name, + SERVICE_ACCOUNT_LOOKUP_SECONDS), + clusterManager::clusterRegion, Clock.systemUTC(), Duration.ofSeconds(SERVICE_ACCOUNT_LOOKUP_SECONDS)); } EksPodIdentityWebhook(EksService eks, EksAddonService addons, - EksPodIdentityAssociationService associations, Supplier flociEndpoint) { + EksPodIdentityAssociationService associations, Supplier flociEndpoint, + ServiceAccountReader serviceAccounts, Function regionOf, Clock clock, + Duration lookupTimeout) { this.eks = eks; this.addons = addons; this.associations = associations; this.flociEndpoint = flociEndpoint; + this.serviceAccounts = serviceAccounts; + this.regionOf = regionOf; + this.clock = clock; + this.lookupTimeout = lookupTimeout; } /** @@ -139,15 +223,149 @@ public class EksPodIdentityWebhook { if (cluster.isEmpty()) { return List.of(); } + String serviceAccount = serviceAccountOf(pod); return RequestScopes.callAs(accountId, () -> { - if (!podIdentityAgentInstalled(cluster.get()) - || !hasAssociation(cluster.get(), namespace, serviceAccountOf(pod))) { - return List.of(); + if (podIdentityAgentInstalled(cluster.get()) && hasAssociation(cluster.get(), namespace, serviceAccount)) { + return buildPatch(pod, flociEndpoint.get()); } - return buildPatch(pod, flociEndpoint.get()); + Optional webIdentity = webIdentity(cluster.get(), namespace, serviceAccount, pod); + return webIdentity.isEmpty() ? List.>of() + : buildWebIdentityPatch(pod, webIdentity.get(), regionOf.apply(cluster.get()), flociEndpoint.get()); }); } + /** + * The IAM roles for service accounts mutation the pod asks for, from its service account's annotations and its + * own; empty when the service account carries no role ARN or cannot be read. A token for an audience other than + * {@code sts.amazonaws.com}, which Floci's STS takes no other audience for a cluster's tokens in place of, could + * never be exchanged, so its pod is left as it is, with a warning. + */ + private Optional webIdentity(Cluster cluster, String namespace, String serviceAccount, + Map pod) { + String json = readServiceAccount(cluster, namespace, serviceAccount); + Optional identity = webIdentity(json == null ? Map.of() : annotationsOf(json), annotationsOf(pod)); + if (identity.isPresent() && !EksOidcService.STS_AUDIENCE.equals(identity.get().audience())) { + LOG.warnv("EKS pod-identity-webhook: service account {0}/{1} of cluster {2} asks for audience {3}, which " + + "Floci''s STS does not exchange a cluster''s tokens for, so its pods get no IAM role injected", + namespace, serviceAccount, cluster.getName(), identity.get().audience()); + return Optional.empty(); + } + return identity; + } + + /** + * The service account as the cluster has it, null for none, read at most once per + * {@link #SERVICE_ACCOUNT_CACHE_TTL}: pods created meanwhile, a read still in flight included, share it. A read + * that fails is dropped from the cache once it ends, so the next pod reads again, and one that outlasts + * {@code lookupTimeout} leaves this pod unchanged while it goes on for later ones. + */ + private String readServiceAccount(Cluster cluster, String namespace, String name) { + ServiceAccountKey key = new ServiceAccountKey(cluster.getArn() != null ? cluster.getArn() : cluster.getName(), + namespace, name); + Instant now = clock.instant(); + serviceAccountReads.values().removeIf(read -> !read.expiresAt().isAfter(now) && read.read().isDone()); + CachedRead[] started = new CachedRead[1]; + CachedRead cached = serviceAccountReads.compute(key, (ignored, existing) -> { + if (existing != null && existing.expiresAt().isAfter(now)) { + return existing; + } + started[0] = new CachedRead(now.plus(SERVICE_ACCOUNT_CACHE_TTL), + CompletableFuture.supplyAsync(() -> serviceAccounts.read(cluster, namespace, name), lookups)); + return started[0]; + }); + if (cached == started[0]) { + cached.read().whenComplete((read, failure) -> { + if (failure != null || !read.succeeded()) { + serviceAccountReads.remove(key, cached); + } + }); + } + try { + EksClusterManager.ServiceAccountRead read = cached.read() + .get(lookupTimeout.toMillis(), TimeUnit.MILLISECONDS); + return read.json(); + } catch (TimeoutException e) { + LOG.warnv("EKS pod-identity-webhook: reading service account {0}/{1} of cluster {2} took over {3} ms, " + + "so this pod gets no IAM role injected", namespace, name, cluster.getName(), + lookupTimeout.toMillis()); + return null; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return null; + } catch (ExecutionException e) { + LOG.warnv(e.getCause(), "EKS pod-identity-webhook: could not read service account {0}/{1} of cluster {2}", + namespace, name, cluster.getName()); + return null; + } + } + + /** + * Reads the annotations as the upstream webhook does. The audience defaults to {@code sts.amazonaws.com}. The + * token lifetime is the service account's, then the pod's, in seconds, 86400 by default, a value that is not a + * whole number leaving the one before, and a shorter one than 600 raised to 600. Regional STS endpoints are on + * unless the service account turns them off, as EKS clusters default to them, and a value that is not a boolean + * leaves the default. + */ + static Optional webIdentity(Map serviceAccount, Map pod) { + String roleArn = serviceAccount.get(ANNOTATION_ROLE_ARN); + if (roleArn == null || roleArn.isBlank()) { + return Optional.empty(); + } + String audience = serviceAccount.get(ANNOTATION_AUDIENCE); + long expiration = tokenExpiration(pod.get(ANNOTATION_TOKEN_EXPIRATION), + tokenExpiration(serviceAccount.get(ANNOTATION_TOKEN_EXPIRATION), IRSA_DEFAULT_TOKEN_EXPIRATION)); + Boolean regional = parseBoolean(serviceAccount.get(ANNOTATION_STS_REGIONAL_ENDPOINTS)); + return Optional.of(new WebIdentity(roleArn, audience == null || audience.isBlank() + ? EksOidcService.STS_AUDIENCE : audience, expiration, regional == null || regional)); + } + + private static long tokenExpiration(String value, long otherwise) { + if (value == null) { + return otherwise; + } + try { + return Math.max(Long.parseLong(value), IRSA_MIN_TOKEN_EXPIRATION); + } catch (NumberFormatException e) { + return otherwise; + } + } + + /** The values Go's {@code strconv.ParseBool} takes, which the upstream webhook reads booleans with. */ + private static Boolean parseBoolean(String value) { + if (value == null) { + return null; + } + return switch (value) { + case "1", "t", "T", "TRUE", "true", "True" -> Boolean.TRUE; + case "0", "f", "F", "FALSE", "false", "False" -> Boolean.FALSE; + default -> null; + }; + } + + private static Map annotationsOf(String serviceAccountJson) { + try { + return annotationsOf(MAPPER.readValue(serviceAccountJson, MAP_TYPE)); + } catch (JsonProcessingException e) { + LOG.warnv(e, "EKS pod-identity-webhook: could not parse a service account, so its pods get no IAM role " + + "injected"); + return Map.of(); + } + } + + private static Map annotationsOf(Map object) { + Map metadata = asMap(object.get("metadata")); + Map annotations = metadata == null ? null : asMap(metadata.get("annotations")); + Map values = new LinkedHashMap<>(); + if (annotations != null) { + annotations.forEach((key, value) -> { + if (value instanceof String text) { + values.put(key, text); + } + }); + } + return values; + } + /** * A pod resolves names through CoreDNS, which never sees the cluster container's * {@code /etc/hosts}, where {@code host.docker.internal} lives on Linux. Floci's hostname resolves @@ -193,69 +411,188 @@ public class EksPodIdentityWebhook { * service-specific variable would take its STS calls away from the endpoint it chose. */ static List> buildPatch(Map pod, String endpointUrl) { + return patch(pod, tokenVolume(), tokenMount(), Set.of(), container -> { + List env = asList(container.get("env")); + List> missing = new ArrayList<>(); + for (Map variable : credentialsEnv()) { + if (env == null || !containsNamed(env, String.valueOf(variable.get("name")))) { + missing.add(variable); + } + } + missing.addAll(missingEndpointEnv(container, endpointUrl)); + return missing; + }); + } + + /** + * The JSONPatch of IAM roles for service accounts, as the upstream webhook makes it: a projected token for STS, + * mounted read-only in every init container and container not named in {@value #ANNOTATION_SKIP_CONTAINERS}, + * with {@code AWS_ROLE_ARN} and {@code AWS_WEB_IDENTITY_TOKEN_FILE}, {@code AWS_STS_REGIONAL_ENDPOINTS} while + * regional endpoints are on, and {@code AWS_REGION} and {@code AWS_DEFAULT_REGION} set to the cluster's Region, + * which the SDK needs for its STS call. A container setting either variable of a pair gets neither, as upstream, + * and Floci's endpoint variables follow {@link #buildPatch}'s rules. + */ + static List> buildWebIdentityPatch(Map pod, WebIdentity identity, + String region, String endpointUrl) { + boolean tokenVolumeUsable = tokenVolumeUsable(pod); + return patch(pod, webIdentityVolume(identity), webIdentityMount(), skippedContainers(pod), container -> { + List env = asList(container.get("env")); + List> missing = new ArrayList<>(); + if (tokenVolumeUsable && tokenMountUsable(container) + && !sets(env, ENV_ROLE_ARN) && !sets(env, ENV_WEB_IDENTITY_TOKEN_FILE)) { + missing.add(Map.of("name", ENV_ROLE_ARN, "value", identity.roleArn())); + missing.add(Map.of("name", ENV_WEB_IDENTITY_TOKEN_FILE, "value", IRSA_TOKEN_FILE)); + } + if (identity.regionalSts() && !sets(env, ENV_STS_REGIONAL_ENDPOINTS)) { + missing.add(Map.of("name", ENV_STS_REGIONAL_ENDPOINTS, "value", "regional")); + } + if (region != null && !sets(env, ENV_REGION) && !sets(env, ENV_DEFAULT_REGION)) { + missing.add(Map.of("name", ENV_DEFAULT_REGION, "value", region)); + missing.add(Map.of("name", ENV_REGION, "value", region)); + } + missing.addAll(missingEndpointEnv(container, endpointUrl)); + return missing; + }); + } + + /** + * The pod volume unless the pod has one of its name, then for every init container and container not in + * {@code skipped}, the mount unless it has one of its name and the environment variables {@code missingEnv} + * finds it lacks. + */ + private static List> patch(Map pod, Map volume, + Map mount, Set skipped, + Function, List>> missingEnv) { Map spec = asMap(pod.get("spec")); if (spec == null) { return List.of(); } List> patch = new ArrayList<>(); List volumes = asList(spec.get("volumes")); + String volumeName = String.valueOf(volume.get("name")); if (volumes == null) { - patch.add(operation("/spec/volumes", List.of(tokenVolume()))); - } else if (!containsNamed(volumes, TOKEN_VOLUME_NAME)) { - patch.add(operation("/spec/volumes/-", tokenVolume())); + patch.add(operation("/spec/volumes", List.of(volume))); + } else if (!containsNamed(volumes, volumeName)) { + patch.add(operation("/spec/volumes/-", volume)); + } + for (String field : List.of("initContainers", "containers")) { + List containers = asList(spec.get(field)); + if (containers == null) { + continue; + } + for (int index = 0; index < containers.size(); index++) { + Map container = asMap(containers.get(index)); + if (container == null || skipped.contains(String.valueOf(container.get("name")))) { + continue; + } + String path = "/spec/" + field + "/" + index; + List mounts = asList(container.get("volumeMounts")); + if (mounts == null) { + patch.add(operation(path + "/volumeMounts", List.of(mount))); + } else if (!containsNamed(mounts, volumeName)) { + patch.add(operation(path + "/volumeMounts/-", mount)); + } + List> missing = missingEnv.apply(container); + if (missing.isEmpty()) { + continue; + } + if (container.get("env") == null) { + patch.add(operation(path + "/env", missing)); + } else { + for (Map variable : missing) { + patch.add(operation(path + "/env/-", variable)); + } + } + } } - List> injectedEnv = injectedEnv(endpointUrl); - patchContainers(patch, spec, "initContainers", injectedEnv); - patchContainers(patch, spec, "containers", injectedEnv); return patch; } - private static void patchContainers(List> patch, Map spec, String field, - List> injectedEnv) { - List containers = asList(spec.get(field)); - if (containers == null) { - return; + /** + * Whether the pod's {@value #IRSA_VOLUME_NAME} volume, which the patch keeps when the pod has one, projects a + * service account token at {@value #IRSA_TOKEN_FILE_NAME}; true when it has none, as the patch adds it. A volume + * of that name holding anything else would leave {@code AWS_WEB_IDENTITY_TOKEN_FILE} naming no token, so the + * role pair is not injected then. + */ + private static boolean tokenVolumeUsable(Map pod) { + Map spec = asMap(pod.get("spec")); + List volumes = spec == null ? null : asList(spec.get("volumes")); + Map volume = volumes == null ? null : named(volumes, IRSA_VOLUME_NAME); + if (volume == null) { + return true; } - for (int index = 0; index < containers.size(); index++) { - Map container = asMap(containers.get(index)); - if (container == null) { - continue; + Map projected = asMap(volume.get("projected")); + List sources = projected == null ? null : asList(projected.get("sources")); + if (sources == null) { + return false; + } + for (Object source : sources) { + Map entry = asMap(source); + Map token = entry == null ? null : asMap(entry.get("serviceAccountToken")); + if (token != null && IRSA_TOKEN_FILE_NAME.equals(token.get("path"))) { + return true; } - String path = "/spec/" + field + "/" + index; - List mounts = asList(container.get("volumeMounts")); - if (mounts == null) { - patch.add(operation(path + "/volumeMounts", List.of(tokenMount()))); - } else if (!containsNamed(mounts, TOKEN_VOLUME_NAME)) { - patch.add(operation(path + "/volumeMounts/-", tokenMount())); - } - List env = asList(container.get("env")); - List envFrom = asList(container.get("envFrom")); - boolean mayDefineEndpoint = envFrom != null && !envFrom.isEmpty(); - boolean setsGlobalEndpoint = env != null && containsNamed(env, ENV_ENDPOINT_URL); - List> missing = new ArrayList<>(); - for (Map variable : injectedEnv) { - String name = String.valueOf(variable.get("name")); - if (mayDefineEndpoint && isEndpointVariable(name)) { - continue; - } - if (setsGlobalEndpoint && ENV_ENDPOINT_URL_STS.equals(name)) { - continue; - } - if (env == null || !containsNamed(env, name)) { - missing.add(variable); - } - } - if (missing.isEmpty()) { - continue; - } - if (env == null) { - patch.add(operation(path + "/env", missing)); - } else { - for (Map variable : missing) { - patch.add(operation(path + "/env/-", variable)); + } + return false; + } + + /** Whether the container's {@value #IRSA_VOLUME_NAME} mount, kept when it has one, is at the token's path. */ + private static boolean tokenMountUsable(Map container) { + List mounts = asList(container.get("volumeMounts")); + Map mount = mounts == null ? null : named(mounts, IRSA_VOLUME_NAME); + return mount == null || IRSA_MOUNT_PATH.equals(mount.get("mountPath")); + } + + /** The endpoint variables the container lacks, under the rules {@link #buildPatch} describes. */ + private static List> missingEndpointEnv(Map container, String endpointUrl) { + if (endpointUrl == null || endpointUrl.isBlank()) { + return List.of(); + } + List env = asList(container.get("env")); + List envFrom = asList(container.get("envFrom")); + if (envFrom != null && !envFrom.isEmpty()) { + return List.of(); + } + if (sets(env, ENV_ENDPOINT_URL)) { + return List.of(); + } + List> missing = new ArrayList<>(); + missing.add(Map.of("name", ENV_ENDPOINT_URL, "value", endpointUrl)); + if (!sets(env, ENV_ENDPOINT_URL_STS)) { + missing.add(Map.of("name", ENV_ENDPOINT_URL_STS, "value", endpointUrl)); + } + return missing; + } + + private static boolean sets(List env, String name) { + return env != null && containsNamed(env, name); + } + + /** The names {@value #ANNOTATION_SKIP_CONTAINERS} lists, comma-separated, in the pod's annotations. */ + private static Set skippedContainers(Map pod) { + String names = annotationsOf(pod).get(ANNOTATION_SKIP_CONTAINERS); + Set skipped = new HashSet<>(); + if (names != null) { + for (String name : names.split(",")) { + if (!name.isBlank()) { + skipped.add(name.trim()); } } } + return skipped; + } + + static Map webIdentityVolume(WebIdentity identity) { + return Map.of( + "name", IRSA_VOLUME_NAME, + "projected", Map.of("sources", List.of(Map.of("serviceAccountToken", Map.of( + "audience", identity.audience(), + "expirationSeconds", identity.tokenExpiration(), + "path", IRSA_TOKEN_FILE_NAME))))); + } + + static Map webIdentityMount() { + return Map.of("name", IRSA_VOLUME_NAME, "mountPath", IRSA_MOUNT_PATH, "readOnly", true); } static Map tokenVolume() { @@ -279,23 +616,6 @@ public class EksPodIdentityWebhook { Map.of("name", ENV_AUTHORIZATION_TOKEN_FILE, "value", TOKEN_FILE_PATH)); } - /** - * The values {@code envFrom} brings in are not known at admission, and an {@code env} entry would - * take precedence over them, so a container that has any gets no endpoint variable. - */ - private static boolean isEndpointVariable(String name) { - return ENV_ENDPOINT_URL.equals(name) || ENV_ENDPOINT_URL_STS.equals(name); - } - - static List> injectedEnv(String endpointUrl) { - List> env = new ArrayList<>(credentialsEnv()); - if (endpointUrl != null && !endpointUrl.isBlank()) { - env.add(Map.of("name", ENV_ENDPOINT_URL, "value", endpointUrl)); - env.add(Map.of("name", ENV_ENDPOINT_URL_STS, "value", endpointUrl)); - } - return env; - } - private static Map operation(String path, Object value) { return Map.of("op", "add", "path", path, "value", value); } @@ -345,13 +665,17 @@ public class EksPodIdentityWebhook { } private static boolean containsNamed(List entries, String name) { + return named(entries, name) != null; + } + + private static Map named(List entries, String name) { for (Object entry : entries) { Map map = asMap(entry); if (map != null && name.equals(map.get("name"))) { - return true; + return map; } } - return false; + return null; } @SuppressWarnings("unchecked") diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java index 3106fdb96a..db8fa94e6b 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java @@ -5172,6 +5172,82 @@ class EksClusterManagerTest { } } + /** The service account lookup the pod identity webhook makes, through kubectl in the server container. */ + @Nested + class ServiceAccountLookupTest { + + private EksClusterManager manager; + private final Cluster cluster = new Cluster(); + + @BeforeEach + void setUp() { + EmulatorConfig config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS); + manager = Mockito.spy(new EksClusterManager(Mockito.mock(ContainerBuilder.class), + Mockito.mock(ContainerLifecycleManager.class), Mockito.mock(ContainerDetector.class), + Mockito.mock(PortAllocator.class), Mockito.mock(DockerHostResolver.class), + Mockito.mock(EcrRegistryManager.class), config, new RegionResolver("us-east-1", "000000000000"), + Mockito.mock(Ec2MetadataServer.class), Mockito.mock(EksOidcService.class), + inlineMock(FlociCertificateAuthority.class), Mockito.mock(ContainerLogStreamer.class), + new InMemoryStorage<>(), 0, Mockito.mock(Ec2ImageCatalog.class), + EksTestEndpoints.dockerHostEndpoint())); + cluster.setName("demo"); + cluster.setContainerId("server-1"); + } + + @Test + void theServiceAccountIsReadAsKubectlPrintsIt() { + doReturn(new ContainerExec.Result(0L, "{\"kind\":\"ServiceAccount\"}", "a warning", false)).when(manager) + .execInContainerSeparatingStderr(anyString(), any(), anyInt()); + + assertEquals(EksClusterManager.ServiceAccountRead.found("{\"kind\":\"ServiceAccount\"}"), + manager.serviceAccount(cluster, "payments", "checkout", 2)); + verify(manager).execInContainerSeparatingStderr("server-1", new String[]{"kubectl", + "--request-timeout=2s", "get", "serviceaccount", "checkout", "--namespace", "payments", + "--output", "json"}, 2); + } + + @Test + void aServiceAccountThatDoesNotExistIsAbsent() { + doReturn(new ContainerExec.Result(1L, "", + "Error from server (NotFound): serviceaccounts \"checkout\" not found", false)).when(manager) + .execInContainerSeparatingStderr(anyString(), any(), anyInt()); + + assertEquals(EksClusterManager.ServiceAccountRead.absent(), + manager.serviceAccount(cluster, "payments", "checkout", 2)); + } + + /** A failed read says nothing about the service account, so it is not taken for an absent one. */ + @Test + void aReadThatFailsOrTimesOutFails() { + doReturn(new ContainerExec.Result(1L, "", "Unable to connect to the server", false), + new ContainerExec.Result(-1L, "{", "", true)).when(manager) + .execInContainerSeparatingStderr(anyString(), any(), anyInt()); + + assertEquals(EksClusterManager.ServiceAccountRead.failed(), + manager.serviceAccount(cluster, "payments", "checkout", 2)); + assertEquals(EksClusterManager.ServiceAccountRead.failed(), + manager.serviceAccount(cluster, "payments", "checkout", 2)); + } + + @Test + void aFailedExecFails() { + doThrow(new IllegalStateException("container gone")).when(manager) + .execInContainerSeparatingStderr(anyString(), any(), anyInt()); + + assertEquals(EksClusterManager.ServiceAccountRead.failed(), + manager.serviceAccount(cluster, "payments", "checkout", 2)); + } + + @Test + void aClusterWithNoContainerIsNotAsked() { + cluster.setContainerId(null); + + assertEquals(EksClusterManager.ServiceAccountRead.absent(), + manager.serviceAccount(cluster, "payments", "checkout", 2)); + verify(manager, never()).execInContainerSeparatingStderr(any(), any(), anyInt()); + } + } + @Nested class JoinedInstancesTest { diff --git a/src/test/java/io/floci/aws/services/eks/EksIrsaWebhookNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksIrsaWebhookNightlyIntegrationTest.java new file mode 100644 index 0000000000..8a09ae94da --- /dev/null +++ b/src/test/java/io/floci/aws/services/eks/EksIrsaWebhookNightlyIntegrationTest.java @@ -0,0 +1,200 @@ +package io.floci.aws.services.eks; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.config.SelfSignedTlsProfile; +import io.floci.aws.core.common.docker.DockerHostResolver; +import io.floci.aws.services.eks.model.Cluster; +import io.floci.aws.services.eks.model.ClusterIdentity; +import io.floci.aws.services.eks.model.ClusterStatus; +import io.floci.aws.services.eks.model.OidcIdentity; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.EksPodIdentityProfile; +import io.floci.aws.testing.EksTestNode; +import io.quarkus.test.junit.QuarkusTest; +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 org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * IAM roles for service accounts on a real k3s node, through Floci's admission webhook alone: a pod whose service + * account carries {@code eks.amazonaws.com/role-arn} is created with nothing of its own, the webhook injects the + * projected token and the web identity variables, and the token the pod reads exchanges for the role's credentials + * at Floci's STS. A pod of a service account without the annotation is left as it is. + * + *

A nightly check: it starts a k3s cluster. Its own profile serves the self-signed certificate + * {@link SelfSignedTlsProfile} writes before boot, which names {@code host.docker.internal}, where the API server + * calls the webhook: the certificate Floci generates itself only follows TLS settings in system properties or the + * environment, never a test profile's. On top go the EKS settings {@link EksPodIdentityProfile} holds, its ports + * included, which put Floci's TLS proxy on the port it routes to Quarkus from. + */ +@QuarkusTest +@TestProfile(EksIrsaWebhookNightlyIntegrationTest.Profile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +// Bounded waits: the k3s image's pull and the API server, then the webhook and two pods; the Nightly checks job's +// timeout counts the 10. +@Timeout(value = 10, unit = TimeUnit.MINUTES) +class EksIrsaWebhookNightlyIntegrationTest { + + /** The self-signed certificate of {@link SelfSignedTlsProfile} with the EKS settings of the admission webhook. */ + public static final class Profile extends SelfSignedTlsProfile { + @Override + public Map getConfigOverrides() { + Map overrides = new HashMap<>(super.getConfigOverrides()); + overrides.putAll(new EksPodIdentityProfile().getConfigOverrides()); + return overrides; + } + } + + private static final Logger LOG = Logger.getLogger(EksIrsaWebhookNightlyIntegrationTest.class); + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String SERVICE_ACCOUNT = "irsa-workload"; + private static final Duration API_SERVER_TIMEOUT = Duration.ofSeconds(120); + private static final Duration POD_TIMEOUT = Duration.ofSeconds(120); + + @Inject + DockerClient dockerClient; + + @Inject + DockerHostResolver dockerHostResolver; + + @Inject + EksClusterManager eksClusterManager; + + @Inject + EksService eksService; + + @Inject + EksOidcService oidcService; + + @Inject + IamService iamService; + + private Cluster cluster; + private String roleName; + + @BeforeEach + void requireDocker() { + Assumptions.assumeTrue(DockerAvailability.answers(dockerClient), + "Docker daemon must be available for the EKS IRSA webhook check"); + Assumptions.assumeTrue(dockerHostResolver.isLinuxHost(), + "The node reaches Floci through host.docker.internal, which this check expects on a Linux host"); + } + + @AfterEach + void tearDown() { + if (cluster != null) { + try { + eksClusterManager.stopCluster(cluster); + } catch (Exception e) { + LOG.warnv(e, "Failed to stop test cluster {0}", cluster.getName()); + } + try { + eksService.deleteClusterForAccount(ACCOUNT, cluster.getName()); + } catch (Exception e) { + LOG.warnv(e, "Failed to delete test cluster {0}", cluster.getName()); + } + } + if (roleName != null) { + try { + iamService.deleteRole(roleName); + } catch (Exception e) { + LOG.warnv(e, "Failed to delete test role {0}", roleName); + } + } + } + + @Test + void aPodOfAnAnnotatedServiceAccountGetsTheRoleThroughTheWebhook() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String clusterName = "irsa-webhook-" + suffix; + cluster = EksTestNode.cluster(ACCOUNT, clusterName); + cluster.setVersion(EksService.DEFAULT_K8S_VERSION); + String issuer = oidcService.newIssuerUrl(REGION); + cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer))); + oidcService.ensureKeyForAccount(ACCOUNT, EksService.clusterKey(REGION, clusterName), issuer); + EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, API_SERVER_TIMEOUT); + cluster.setStatus(ClusterStatus.ACTIVE); + eksService.putClusterForAccount(ACCOUNT, cluster); + await("the pod identity webhook").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2)) + .until(() -> node.kubectl("get", "mutatingwebhookconfiguration", "floci-eks-pod-identity") + .exitCode() == 0); + + String issuerHost = issuer.replaceFirst("^https://", ""); + roleName = "irsa-webhook-role-" + suffix; + String roleArn = iamService.createRole(roleName, "/", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{\ + "Federated":"arn:aws:iam::%1$s:oidc-provider/%2$s"},"Action":"sts:AssumeRoleWithWebIdentity",\ + "Condition":{"StringEquals":{"%2$s:sub":"system:serviceaccount:default:%3$s",\ + "%2$s:aud":"sts.amazonaws.com"}}}]}""".formatted(ACCOUNT, issuerHost, SERVICE_ACCOUNT), + null, 3600, null).getArn(); + node.apply(""" + apiVersion: v1 + kind: ServiceAccount + metadata: + name: %s + namespace: default + annotations: + eks.amazonaws.com/role-arn: %s + """.formatted(SERVICE_ACCOUNT, roleArn)); + runPod(node, "irsa-pod", SERVICE_ACCOUNT); + runPod(node, "plain-pod", "default"); + + assertEquals(roleArn, node.kubectlOutput("exec", "irsa-pod", "--", "printenv", "AWS_ROLE_ARN")); + assertEquals(REGION, node.kubectlOutput("exec", "irsa-pod", "--", "printenv", "AWS_REGION")); + String tokenFile = node.kubectlOutput("exec", "irsa-pod", "--", "printenv", "AWS_WEB_IDENTITY_TOKEN_FILE"); + assertEquals("/var/run/secrets/eks.amazonaws.com/serviceaccount/token", tokenFile); + String token = node.kubectlOutput("exec", "irsa-pod", "--", "cat", tokenFile); + assertFalse(token.isBlank()); + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "AssumeRoleWithWebIdentity") + .formParam("Version", "2011-06-15") + .formParam("RoleArn", roleArn) + .formParam("RoleSessionName", "irsa-webhook") + .formParam("WebIdentityToken", token) + .when().post("/") + .then().statusCode(200) + .body(containsString("ASIA")) + .body(containsString("system:serviceaccount:default:" + SERVICE_ACCOUNT + + "")); + + assertEquals("", node.kubectlOutput("get", "pod", "plain-pod", "-o", + "jsonpath={.spec.volumes[?(@.name==\"aws-iam-token\")].name}")); + } + + private static void runPod(EksTestNode node, String name, String serviceAccount) { + node.apply(""" + apiVersion: v1 + kind: Pod + metadata: + name: %s + namespace: default + spec: + serviceAccountName: %s + containers: + - name: workload + image: alpine:3.21 + command: ["sleep", "3600"] + """.formatted(name, serviceAccount)); + node.awaitPodRunning(name, POD_TIMEOUT); + } +} diff --git a/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java b/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java index 33adec8f71..72133905a7 100644 --- a/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java @@ -8,14 +8,25 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import static io.floci.aws.testing.InlineMocks.inlineMock; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; @@ -36,13 +47,51 @@ class EksPodIdentityWebhookTest { private EksAddonService addons; private EksPodIdentityAssociationService associations; private EksPodIdentityWebhook webhook; + private final Map serviceAccounts = new ConcurrentHashMap<>(); + private final List serviceAccountReads = new CopyOnWriteArrayList<>(); + private final AtomicReference now = new AtomicReference<>(Instant.parse("2026-11-24T00:00:00Z")); + private volatile CountDownLatch readGate; + + private EksPodIdentityWebhook webhook(String endpoint) { + Clock clock = new Clock() { + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now.get(); + } + }; + return new EksPodIdentityWebhook(eks, addons, associations, () -> endpoint, + (cluster, namespace, name) -> { + serviceAccountReads.add(namespace + "/" + name); + CountDownLatch gate = readGate; + if (gate != null) { + try { + gate.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + return serviceAccounts.getOrDefault(namespace + "/" + name, + EksClusterManager.ServiceAccountRead.absent()); + }, + cluster -> "eu-west-1", clock, Duration.ofMillis(500)); + } @BeforeEach void setUp() { eks = Mockito.mock(EksService.class); addons = Mockito.mock(EksAddonService.class); associations = Mockito.mock(EksPodIdentityAssociationService.class); - webhook = new EksPodIdentityWebhook(eks, addons, associations, () -> FLOCI_ENDPOINT); + webhook = webhook(FLOCI_ENDPOINT); Cluster cluster = new Cluster(); cluster.setName(CLUSTER_NAME); @@ -291,7 +340,7 @@ class EksPodIdentityWebhookTest { assertNull(EksPodIdentityWebhook.podReachableEndpoint("http://localhost.floci.io:4566")); assertNull(EksPodIdentityWebhook.podReachableEndpoint("http://host.docker.internal:4566")); - webhook = new EksPodIdentityWebhook(eks, addons, associations, () -> null); + webhook = webhook(null); JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, admissionReview(pod("checkout", List.of(Map.of("name", "app")))))); @@ -307,4 +356,302 @@ class EksPodIdentityWebhookTest { assertEquals("admission.k8s.io/v1beta1", review.get("apiVersion")); assertTrue(response(review).containsKey("uid")); } + + // ------------------------------------------------------------ + // IAM roles for service accounts + // ------------------------------------------------------------ + + private static final String ROLE_ARN = "arn:aws:iam::123456789012:role/payments"; + + private void noPodIdentity() { + when(associations.list(any(), anyString(), anyString(), any(), any())) + .thenReturn(new EksPodIdentityAssociationService.Page(List.of(), null)); + } + + private void serviceAccount(String name, Map annotations) throws Exception { + serviceAccounts.put("payments/" + name, EksClusterManager.ServiceAccountRead.found( + MAPPER.writeValueAsString(Map.of("apiVersion", "v1", "kind", "ServiceAccount", + "metadata", Map.of("name", name, "namespace", "payments", "annotations", annotations))))); + } + + private Map reviewOf(String serviceAccount) { + return webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(pod(serviceAccount, List.of(Map.of("name", "app"))))); + } + + private Map annotatedPod(String serviceAccount, Map annotations, + Map spec) { + Map withAccount = new LinkedHashMap<>(spec); + withAccount.put("serviceAccountName", serviceAccount); + return Map.of("kind", "Pod", "metadata", Map.of("name", "api", "annotations", annotations), + "spec", withAccount); + } + + /** + * The upstream webhook's mutation, value for value: the projected token for STS, its read-only mount, the role + * and token file, regional STS endpoints, and the cluster's Region, on init containers and containers alike. + */ + @Test + void aServiceAccountWithARoleArnGetsTheWebIdentityMutation() throws Exception { + noPodIdentity(); + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN)); + Map spec = new LinkedHashMap<>(); + spec.put("initContainers", List.of(Map.of("name", "migrate"))); + spec.put("containers", List.of(Map.of("name", "app"))); + + JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(annotatedPod("checkout", Map.of(), spec)))); + + String env = """ + [{"name":"AWS_ROLE_ARN","value":"arn:aws:iam::123456789012:role/payments"}, + {"name":"AWS_WEB_IDENTITY_TOKEN_FILE", + "value":"/var/run/secrets/eks.amazonaws.com/serviceaccount/token"}, + {"name":"AWS_STS_REGIONAL_ENDPOINTS","value":"regional"}, + {"name":"AWS_DEFAULT_REGION","value":"eu-west-1"}, + {"name":"AWS_REGION","value":"eu-west-1"}, + {"name":"AWS_ENDPOINT_URL","value":"http://floci.local:4566"}, + {"name":"AWS_ENDPOINT_URL_STS","value":"http://floci.local:4566"}]"""; + String mount = """ + [{"name":"aws-iam-token","mountPath":"/var/run/secrets/eks.amazonaws.com/serviceaccount", + "readOnly":true}]"""; + assertEquals(MAPPER.readTree(""" + [ + {"op":"add","path":"/spec/volumes","value":[ + {"name":"aws-iam-token","projected":{"sources":[{"serviceAccountToken": + {"audience":"sts.amazonaws.com","expirationSeconds":86400,"path":"token"}}]}}]}, + {"op":"add","path":"/spec/initContainers/0/volumeMounts","value":%1$s}, + {"op":"add","path":"/spec/initContainers/0/env","value":%2$s}, + {"op":"add","path":"/spec/containers/0/volumeMounts","value":%1$s}, + {"op":"add","path":"/spec/containers/0/env","value":%2$s} + ]""".formatted(mount, env)), patch); + assertEquals(List.of("payments/checkout"), serviceAccountReads); + } + + /** Pod Identity takes precedence, as the upstream webhook's container credentials do; one mutation, never both. */ + @Test + void podIdentityTakesPrecedenceOverARoleArn() throws Exception { + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN)); + + JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(pod("checkout", List.of(Map.of("name", "app")))))); + + assertEquals("eks-pod-identity-token", patch.get(0).get("value").get(0).get("name").asText()); + assertFalse(patch.toString().contains("AWS_ROLE_ARN"), patch.toString()); + assertEquals(List.of(), serviceAccountReads); + } + + /** Without the agent there is no Pod Identity mutation, so the role ARN applies. */ + @Test + void aRoleArnAppliesWhenThePodIdentityAgentIsNotInstalled() throws Exception { + when(addons.isInstalled(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON))).thenReturn(false); + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN)); + + JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(pod("checkout", List.of(Map.of("name", "app")))))); + + assertEquals("aws-iam-token", patch.get(0).get("value").get(0).get("name").asText()); + } + + @Test + void aServiceAccountWithoutARoleArnOrThatCannotBeReadLeavesThePodUnchanged() throws Exception { + noPodIdentity(); + serviceAccount("plain", Map.of("team", "payments")); + serviceAccounts.put("payments/broken", EksClusterManager.ServiceAccountRead.found("not json")); + serviceAccounts.put("payments/unreadable", EksClusterManager.ServiceAccountRead.failed()); + + for (String account : List.of("plain", "broken", "missing", "unreadable")) { + Map review = webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(pod(account, List.of(Map.of("name", "app"))))); + + assertEquals(Boolean.TRUE, response(review).get("allowed")); + assertNull(response(review).get("patch"), account); + } + } + + @Test + void theServiceAccountAndThePodAnnotationsShapeTheToken() throws Exception { + assertEquals(Optional.of(new EksPodIdentityWebhook.WebIdentity(ROLE_ARN, "custom", 3600, false)), + EksPodIdentityWebhook.webIdentity(Map.of("eks.amazonaws.com/role-arn", ROLE_ARN, + "eks.amazonaws.com/audience", "custom", "eks.amazonaws.com/token-expiration", "7200", + "eks.amazonaws.com/sts-regional-endpoints", "false"), + Map.of("eks.amazonaws.com/token-expiration", "3600"))); + assertEquals(Optional.of(new EksPodIdentityWebhook.WebIdentity(ROLE_ARN, "sts.amazonaws.com", 600, true)), + EksPodIdentityWebhook.webIdentity(Map.of("eks.amazonaws.com/role-arn", ROLE_ARN, + "eks.amazonaws.com/token-expiration", "60", "eks.amazonaws.com/sts-regional-endpoints", + "maybe"), Map.of())); + assertEquals(Optional.of(new EksPodIdentityWebhook.WebIdentity(ROLE_ARN, "sts.amazonaws.com", 7200, true)), + EksPodIdentityWebhook.webIdentity(Map.of("eks.amazonaws.com/role-arn", ROLE_ARN, + "eks.amazonaws.com/token-expiration", "7200"), + Map.of("eks.amazonaws.com/token-expiration", "soon"))); + assertEquals(Optional.of(new EksPodIdentityWebhook.WebIdentity(ROLE_ARN, "sts.amazonaws.com", 86400, true)), + EksPodIdentityWebhook.webIdentity(Map.of("eks.amazonaws.com/role-arn", ROLE_ARN, + "eks.amazonaws.com/token-expiration", "a day"), Map.of())); + assertEquals(Optional.empty(), EksPodIdentityWebhook.webIdentity( + Map.of("eks.amazonaws.com/role-arn", " "), Map.of())); + } + + @Test + void theTokenTakesTheAnnotatedLifetime() throws Exception { + noPodIdentity(); + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN, + "eks.amazonaws.com/audience", "sts.amazonaws.com", "eks.amazonaws.com/sts-regional-endpoints", "false")); + + JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, admissionReview(annotatedPod("checkout", + Map.of("eks.amazonaws.com/token-expiration", "3600"), Map.of("containers", + List.of(Map.of("name", "app"))))))); + + assertEquals(MAPPER.readTree(""" + {"audience":"sts.amazonaws.com","expirationSeconds":3600,"path":"token"}"""), + patch.get(0).get("value").get(0).get("projected").get("sources").get(0).get("serviceAccountToken")); + assertFalse(patch.toString().contains("AWS_STS_REGIONAL_ENDPOINTS"), patch.toString()); + } + + /** Floci's STS exchanges a cluster's tokens for sts.amazonaws.com alone, so another audience could never work. */ + @Test + void anAudienceFlociCannotExchangeLeavesThePodUnchanged() throws Exception { + noPodIdentity(); + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN, + "eks.amazonaws.com/audience", "custom")); + + assertNull(response(reviewOf("checkout")).get("patch")); + } + + /** A token volume or mount of the same name the pod brings, which would not hold the token, gets no role pair. */ + @Test + void aTokenVolumeOrMountThatWouldNotHoldTheTokenGetsNoRolePair() throws Exception { + noPodIdentity(); + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN)); + Map elsewhere = Map.of("name", "app", + "volumeMounts", List.of(Map.of("name", "aws-iam-token", "mountPath", "/elsewhere"))); + Map inPlace = Map.of("name", "sidecar", + "volumeMounts", List.of(Map.of("name", "aws-iam-token", + "mountPath", "/var/run/secrets/eks.amazonaws.com/serviceaccount"))); + Map spec = new LinkedHashMap<>(); + spec.put("containers", List.of(elsewhere, inPlace)); + + JsonNode mounted = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(annotatedPod("checkout", Map.of(), spec)))); + assertFalse(envOf(mounted, 0).contains("AWS_ROLE_ARN"), mounted.toString()); + assertTrue(envOf(mounted, 1).contains("AWS_ROLE_ARN"), mounted.toString()); + + spec.put("volumes", List.of(Map.of("name", "aws-iam-token", "emptyDir", Map.of()))); + spec.put("containers", List.of(Map.of("name", "app"))); + JsonNode other = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(annotatedPod("checkout", Map.of(), spec)))); + assertFalse(envOf(other, 0).contains("AWS_ROLE_ARN"), other.toString()); + assertTrue(envOf(other, 0).contains("AWS_REGION"), other.toString()); + } + + private static String envOf(JsonNode patch, int container) { + StringBuilder env = new StringBuilder(); + patch.forEach(operation -> { + if (operation.get("path").asText().startsWith("/spec/containers/" + container + "/env")) { + env.append(operation.get("value")); + } + }); + return env.toString(); + } + + /** A burst of pods, and the cluster's own pods of service accounts with no role, cost one read each. */ + @Test + void aServiceAccountIsReadOnceWhileItsReadIsFresh() throws Exception { + noPodIdentity(); + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN)); + + reviewOf("checkout"); + reviewOf("checkout"); + reviewOf("missing"); + reviewOf("missing"); + assertEquals(List.of("payments/checkout", "payments/missing"), serviceAccountReads); + + now.set(now.get().plus(EksPodIdentityWebhook.SERVICE_ACCOUNT_CACHE_TTL)); + assertTrue(response(reviewOf("checkout")).containsKey("patch")); + assertEquals(List.of("payments/checkout", "payments/missing", "payments/checkout"), serviceAccountReads); + } + + @Test + void aFailedReadIsNotReused() throws Exception { + noPodIdentity(); + serviceAccounts.put("payments/checkout", EksClusterManager.ServiceAccountRead.failed()); + reviewOf("checkout"); + await().atMost(Duration.ofSeconds(5)).until(() -> { + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN)); + return response(reviewOf("checkout")).containsKey("patch"); + }); + + assertEquals("payments/checkout", serviceAccountReads.get(1)); + } + + /** A read that hangs, in Docker before kubectl even starts, still leaves the webhook answering in time. */ + @Test + void aReadThatOutlastsTheLookupTimeoutLeavesThePodUnchangedAndServesLaterPods() throws Exception { + noPodIdentity(); + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN)); + readGate = new CountDownLatch(1); + + Map review = reviewOf("checkout"); + assertEquals(Boolean.TRUE, response(review).get("allowed")); + assertNull(response(review).get("patch")); + + readGate.countDown(); + await().atMost(Duration.ofSeconds(5)).until(() -> response(reviewOf("checkout")).containsKey("patch")); + assertEquals(List.of("payments/checkout"), serviceAccountReads); + } + + + @Test + void aSkippedContainerIsLeftAsItIs() throws Exception { + noPodIdentity(); + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN)); + Map spec = new LinkedHashMap<>(); + spec.put("initContainers", List.of(Map.of("name", "migrate"))); + spec.put("containers", List.of(Map.of("name", "app"), Map.of("name", "proxy"))); + + JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, admissionReview(annotatedPod("checkout", + Map.of("eks.amazonaws.com/skip-containers", "migrate, proxy"), spec)))); + + List paths = new ArrayList<>(); + patch.forEach(operation -> paths.add(operation.get("path").asText())); + assertEquals(List.of("/spec/volumes", "/spec/containers/0/volumeMounts", "/spec/containers/0/env"), paths); + } + + /** As upstream, a container setting either variable of a pair gets neither, and nothing it set is overwritten. */ + @Test + void variablesTheContainerSetsAreLeftAlone() throws Exception { + noPodIdentity(); + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN)); + Map container = Map.of("name", "app", + "env", List.of(Map.of("name", "AWS_WEB_IDENTITY_TOKEN_FILE", "value", "/mine"), + Map.of("name", "AWS_DEFAULT_REGION", "value", "us-west-2"), + Map.of("name", "AWS_STS_REGIONAL_ENDPOINTS", "value", "legacy"), + Map.of("name", "AWS_ENDPOINT_URL", "value", "http://mine")), + "volumeMounts", List.of(Map.of("name", "aws-iam-token", + "mountPath", "/var/run/secrets/eks.amazonaws.com/serviceaccount"))); + + JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(pod("checkout", List.of(container))))); + + assertEquals(1, patch.size(), patch.toString()); + assertEquals("/spec/volumes", patch.get(0).get("path").asText()); + } + + @Test + void anExistingEnvListIsAppendedTo() throws Exception { + noPodIdentity(); + serviceAccount("checkout", Map.of("eks.amazonaws.com/role-arn", ROLE_ARN)); + Map container = Map.of("name", "app", + "env", List.of(Map.of("name", "AWS_REGION", "value", "us-west-2"))); + + JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(pod("checkout", List.of(container))))); + + List appended = new ArrayList<>(); + patch.forEach(operation -> { + if (operation.get("path").asText().equals("/spec/containers/0/env/-")) { + appended.add(operation.get("value").get("name").asText()); + } + }); + assertEquals(List.of("AWS_ROLE_ARN", "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_STS_REGIONAL_ENDPOINTS", + "AWS_ENDPOINT_URL", "AWS_ENDPOINT_URL_STS"), appended); + } }