diff --git a/docs/services/eks.md b/docs/services/eks.md
index 73d447ae7e..9901f33023 100644
--- a/docs/services/eks.md
+++ b/docs/services/eks.md
@@ -91,13 +91,40 @@ Floci supports the EKS Pod Identity association management plane. You can map a
- **Updating**: `UpdatePodIdentityAssociation` modifies the associated `roleArn`, `targetRoleArn`, `disableSessionTags`, or `policy`.
- **Deletion**: `DeletePodIdentityAssociation` removes an association and returns its final metadata. Deleting an EKS cluster automatically purges all of its pod identity associations.
+### 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.
+
+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.
+
+A matching pod is patched exactly the way real EKS patches it. Every init container and container gets:
+
+| What | Value |
+|---|---|
+| `AWS_CONTAINER_CREDENTIALS_FULL_URI` | `http://169.254.170.23/v1/credentials` |
+| `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE` | `/var/run/secrets/pods.eks.amazonaws.com/serviceaccount/eks-pod-identity-token` |
+| Volume mount | `/var/run/secrets/pods.eks.amazonaws.com/serviceaccount`, read-only, from volume `eks-pod-identity-token` |
+
+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.
+
+#### TLS is required
+
+Kubernetes only accepts an `https` `clientConfig.url` on a `MutatingWebhookConfiguration`, together with a `caBundle` the API server trusts. Floci serves HTTP with the default `floci.tls.enabled=false`, so the webhook is skipped with a warning in that case and pods start unmutated. Set `FLOCI_TLS_ENABLED=true` to get injection; the `caBundle` is then Floci's local CA, the same one served at `GET /_floci/ca.pem`.
+
+The webhook URL uses the hostname containers reach Floci on. When Floci runs natively that is `host.docker.internal`, which the self-signed certificate covers. When Floci itself runs in a container the hostname is its container IP, and the self-signed certificate carries no SAN for it, so the API server rejects the handshake. Pods still start, unmutated. Point `FLOCI_SERVICES_LAMBDA_DOCKER_HOST_OVERRIDE` at a name the certificate covers (add it with `FLOCI_HOSTNAME`) to make the webhook reachable from that setup.
+
+The webhook carries `failurePolicy: Ignore`, and Floci admits the pod unchanged on any internal error, so a webhook that cannot be registered or cannot be reached never prevents a pod from being created. Registration failures log a warning and leave the cluster running.
+
+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
-Credentials delivery directly into pods is not yet supported:
-- Mutating webhook injection for pod environment variables (`AWS_CONTAINER_CREDENTIALS_FULL_URI`, `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE`) is not implemented.
-- The link-local metadata credential endpoint (`169.254.170.23`) is not implemented.
-
-Applications running inside pods cannot currently exchange tokens for temporary AWS credentials via the link-local endpoint. Use access entries, node credentials, or explicit credential configuration until the pod identity agent endpoint is added.
+- 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
@@ -340,6 +367,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_IMDS` | `false` | Enable link-local IMDS (`169.254.169.254`) proxy in cluster containers |
### Kubernetes versions and network configuration
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 7203da770a..4918ae3c7f 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -2890,6 +2890,23 @@ public interface EmulatorConfig {
*/
@WithDefault("true")
boolean irsaSigningKey();
+
+ /**
+ * When true, registers a {@code MutatingWebhookConfiguration} in each new cluster so pods
+ * 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.
+ *
+ *
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.
+ *
+ *
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")
+ boolean podIdentityWebhook();
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
index 94308e2adc..049a3ffabc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -49,6 +50,7 @@ import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.time.Instant;
import java.util.ArrayList;
+import java.util.Base64;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -74,6 +76,13 @@ public class EksClusterManager {
// Tar entry extracted at /etc; the archive path creates /etc/rancher/k3s, which does not
// exist yet in a created-but-not-started k3s container.
private static final String REGISTRIES_TAR_ENTRY = "rancher/k3s/registries.yaml";
+ // k3s applies every manifest in its server manifests directory at startup, and again whenever
+ // one changes on disk, so dropping the file in before the container starts is enough to get the
+ // MutatingWebhookConfiguration registered. The directory sits under the cluster's named data
+ // volume; the Docker copy resolves through the container's mounts, so the file lands there.
+ static final String K3S_DATA_DIR = "/var/lib/rancher/k3s";
+ static final String POD_IDENTITY_MANIFEST_FILE = "floci-eks-pod-identity.yaml";
+ static final String POD_IDENTITY_MANIFEST_TAR_ENTRY = "server/manifests/" + POD_IDENTITY_MANIFEST_FILE;
private static final String ENDPOINT_MODE_NETWORK = "network";
public static final String DEFAULT_POD_CIDR = "10.42.0.0/16";
@@ -105,6 +114,7 @@ public class EksClusterManager {
private final RegionResolver regionResolver;
private final Ec2MetadataServer metadataServer;
private final EksOidcService oidcService;
+ private final FlociCertificateAuthority certificateAuthority;
private final Map clusterNodeInstances = new ConcurrentHashMap<>();
public EksClusterManager(ContainerBuilder containerBuilder,
@@ -116,7 +126,7 @@ public class EksClusterManager {
EmulatorConfig config,
RegionResolver regionResolver) {
this(containerBuilder, lifecycleManager, containerDetector, portAllocator,
- dockerHostResolver, ecrRegistryManager, config, regionResolver, null, null);
+ dockerHostResolver, ecrRegistryManager, config, regionResolver, null, null, null);
}
public EksClusterManager(ContainerBuilder containerBuilder,
@@ -129,7 +139,21 @@ public class EksClusterManager {
RegionResolver regionResolver,
Ec2MetadataServer metadataServer) {
this(containerBuilder, lifecycleManager, containerDetector, portAllocator,
- dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, null);
+ dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, null, null);
+ }
+
+ public EksClusterManager(ContainerBuilder containerBuilder,
+ ContainerLifecycleManager lifecycleManager,
+ ContainerDetector containerDetector,
+ PortAllocator portAllocator,
+ DockerHostResolver dockerHostResolver,
+ EcrRegistryManager ecrRegistryManager,
+ EmulatorConfig config,
+ RegionResolver regionResolver,
+ Ec2MetadataServer metadataServer,
+ EksOidcService oidcService) {
+ this(containerBuilder, lifecycleManager, containerDetector, portAllocator, dockerHostResolver,
+ ecrRegistryManager, config, regionResolver, metadataServer, oidcService, null);
}
@Inject
@@ -142,7 +166,8 @@ public class EksClusterManager {
EmulatorConfig config,
RegionResolver regionResolver,
Ec2MetadataServer metadataServer,
- EksOidcService oidcService) {
+ EksOidcService oidcService,
+ FlociCertificateAuthority certificateAuthority) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.containerDetector = containerDetector;
@@ -153,6 +178,7 @@ public class EksClusterManager {
this.regionResolver = regionResolver;
this.metadataServer = metadataServer;
this.oidcService = oidcService;
+ this.certificateAuthority = certificateAuthority;
}
/**
@@ -247,7 +273,7 @@ public class EksClusterManager {
.withName(containerName)
.withEnv("K3S_KUBECONFIG_MODE", "644")
.withPortBinding(K3S_API_SERVER_PORT, hostPort)
- .withNamedVolume(volumeName, "/var/lib/rancher/k3s")
+ .withNamedVolume(volumeName, K3S_DATA_DIR)
.withDockerNetwork(config.services().eks().dockerNetwork())
.withPrivileged(true)
.withLogRotation()
@@ -314,6 +340,7 @@ public class EksClusterManager {
copyWebhookIntoContainer(containerId, webhookLocalFile, cluster.getName());
}
injectEcrRegistryMirror(containerId, cluster.getName());
+ registerPodIdentityWebhook(containerId, cluster);
if (signingKeyFiles != null) {
copySigningKeysIntoContainer(containerId, signingKeyFiles, cluster.getName());
}
@@ -906,7 +933,8 @@ public class EksClusterManager {
}
String endpoint = "http://" + dockerHostResolver.resolve() + ":" + config.port();
String content = buildRegistriesYaml(config.defaultAccountId(), regions, config.port(), endpoint);
- writeRegistriesYaml(clusterName, content);
+ writeLocalCopy(Paths.get(config.services().eks().dataPath(), "registries", clusterName,
+ "registries.yaml"), content, clusterName);
try {
lifecycleManager.getDockerClient()
.copyArchiveToContainerCmd(containerId)
@@ -920,16 +948,105 @@ public class EksClusterManager {
}
}
+ /**
+ * Drops the cluster's {@code MutatingWebhookConfiguration} into the k3s server manifests
+ * directory of the (created, not-yet-started) container, so the API server registers it as it
+ * comes up and starts sending pod CREATE admission reviews to Floci.
+ *
+ *
Kubernetes requires an {@code https} {@code clientConfig.url} and a {@code caBundle} it
+ * trusts, neither of which Floci can offer with TLS off, so the webhook is skipped with a
+ * warning in that case. A failure here leaves the cluster running without pod identity
+ * injection, matching the token webhook and the ECR mirror.
+ */
+ void registerPodIdentityWebhook(String containerId, Cluster cluster) {
+ if (!config.services().eks().podIdentityWebhook()) {
+ return;
+ }
+ String clusterName = cluster.getName();
+ if (!config.tls().enabled()) {
+ LOG.warnv("EKS Pod Identity injection is off for cluster {0}: Kubernetes only accepts an "
+ + "https admission webhook URL, and Floci serves HTTP with floci.tls.enabled=false. "
+ + "Set FLOCI_TLS_ENABLED=true to have pods mutated. Pods still start, without the "
+ + "pod identity token or credentials environment variables.", clusterName);
+ return;
+ }
+ if (certificateAuthority == null) {
+ LOG.warnv("EKS Pod Identity injection is off for cluster {0}: no local CA is available to "
+ + "put in the webhook caBundle", clusterName);
+ return;
+ }
+ String url = "https://" + dockerHostResolver.resolve() + ":" + config.port()
+ + podIdentityWebhookPath(clusterName, resolveClusterAccountId(cluster));
+ String manifest = buildPodIdentityWebhookConfiguration(url, certificateAuthority.caPem());
+ writeLocalCopy(Paths.get(config.services().eks().dataPath(), "webhook", clusterName,
+ POD_IDENTITY_MANIFEST_FILE), manifest, clusterName);
+ try {
+ lifecycleManager.getDockerClient()
+ .copyArchiveToContainerCmd(containerId)
+ .withTarInputStream(new ByteArrayInputStream(
+ tarSingleFile(POD_IDENTITY_MANIFEST_TAR_ENTRY, manifest)))
+ .withRemotePath(K3S_DATA_DIR)
+ .exec();
+ LOG.infov("Registered the EKS Pod Identity mutating webhook ({0}) for cluster {1}", url, clusterName);
+ } catch (Exception e) {
+ LOG.warnv("EKS cluster {0} gets no pod identity injection: could not copy {1} into the k3s "
+ + "container: {2}", clusterName, POD_IDENTITY_MANIFEST_FILE, e.getMessage());
+ }
+ }
+
+ /**
+ * The Floci pod identity admission route. The account is in the path for the same reason the
+ * token webhook puts its scope there: the API server calls Floci with no AWS credentials, so a
+ * cluster owned by a non-default account would otherwise never be found.
+ */
+ static String podIdentityWebhookPath(String clusterName, String accountId) {
+ return "/_floci/eks/clusters/" + clusterName + "/pod-identity-webhook/scope/" + accountId;
+ }
+
+ /**
+ * Builds the {@code MutatingWebhookConfiguration} k3s auto-applies. Scoped to pod {@code CREATE}
+ * alone, and {@code failurePolicy: Ignore} so an unreachable or failing Floci never blocks a pod
+ * from being created. The {@code caBundle} is Floci's local CA, base64 of the PEM as Kubernetes
+ * expects.
+ *
+ *
{@code timeoutSeconds} is 3, not the Kubernetes default of 10: Floci is a local process, so
+ * a healthy call takes milliseconds, and the timeout only ever runs down when Floci is
+ * unreachable. Every pod creation in the cluster pays it in that case, so it is kept short.
+ */
+ static String buildPodIdentityWebhookConfiguration(String url, String caPem) {
+ return """
+ apiVersion: admissionregistration.k8s.io/v1
+ kind: MutatingWebhookConfiguration
+ metadata:
+ name: floci-eks-pod-identity
+ webhooks:
+ - name: pod-identity.eks.floci.io
+ admissionReviewVersions: ["v1"]
+ sideEffects: None
+ failurePolicy: Ignore
+ reinvocationPolicy: Never
+ timeoutSeconds: 3
+ clientConfig:
+ url: "%s"
+ caBundle: "%s"
+ rules:
+ - operations: ["CREATE"]
+ apiGroups: [""]
+ apiVersions: ["v1"]
+ resources: ["pods"]
+ scope: "*"
+ """.formatted(url, Base64.getEncoder().encodeToString(caPem.getBytes(StandardCharsets.UTF_8)));
+ }
+
/** Best-effort local copy for inspection/debugging; the container copy streams from memory. */
- private void writeRegistriesYaml(String clusterName, String content) {
- Path localFile = Paths.get(config.services().eks().dataPath(), "registries", clusterName, "registries.yaml")
- .toAbsolutePath().normalize();
+ private void writeLocalCopy(Path file, String content, String clusterName) {
+ Path localFile = file.toAbsolutePath().normalize();
try {
Files.createDirectories(localFile.getParent());
Files.writeString(localFile, content);
} catch (IOException e) {
- LOG.debugv("Could not write local registries.yaml copy for cluster {0}: {1}",
- clusterName, e.getMessage());
+ LOG.debugv("Could not write local {0} copy for cluster {1}: {2}",
+ localFile.getFileName(), clusterName, e.getMessage());
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhook.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhook.java
new file mode 100644
index 0000000000..aa2a7e78a3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhook.java
@@ -0,0 +1,281 @@
+package io.github.hectorvent.floci.services.eks;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.eks.model.Cluster;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Admission logic behind the EKS Pod Identity mutating webhook.
+ *
+ *
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
+ * account token with the pod identity audience and sets the two container credentials environment
+ * variables the AWS SDKs read, so the SDK credential chain reaches the container credentials
+ * provider instead of falling through. Floci reproduces exactly that mutation.
+ *
+ *
Nothing answers {@link #CREDENTIALS_FULL_URI} yet: this class injects the plumbing only, so an
+ * injected pod still cannot obtain credentials.
+ *
+ *
Every path here admits the pod. A cluster that is gone, an addon that is not installed, a
+ * malformed review and an internal error all return {@code allowed: true} with no patch, which is
+ * what {@code failurePolicy: Ignore} promises on the k3s side.
+ */
+@ApplicationScoped
+public class EksPodIdentityWebhook {
+
+ private static final Logger LOG = Logger.getLogger(EksPodIdentityWebhook.class);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ /** Real EKS only injects when the pod identity agent is installed on the cluster. */
+ static final String POD_IDENTITY_ADDON = "eks-pod-identity-agent";
+
+ static final String TOKEN_VOLUME_NAME = "eks-pod-identity-token";
+ static final String TOKEN_AUDIENCE = "pods.eks.amazonaws.com";
+ static final String TOKEN_MOUNT_PATH = "/var/run/secrets/pods.eks.amazonaws.com/serviceaccount";
+ static final String TOKEN_FILE_NAME = "eks-pod-identity-token";
+ static final String TOKEN_FILE_PATH = TOKEN_MOUNT_PATH + "/" + TOKEN_FILE_NAME;
+ static final int TOKEN_EXPIRATION_SECONDS = 86400;
+ static final int TOKEN_DEFAULT_MODE = 420;
+
+ static final String ENV_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
+ static final String ENV_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE";
+ static final String CREDENTIALS_FULL_URI = "http://169.254.170.23/v1/credentials";
+
+ private static final String DEFAULT_API_VERSION = "admission.k8s.io/v1";
+ private static final String DEFAULT_SERVICE_ACCOUNT = "default";
+
+ private final EksService eks;
+ private final EksAddonService addons;
+ private final EksPodIdentityAssociationService associations;
+
+ @Inject
+ public EksPodIdentityWebhook(EksService eks, EksAddonService addons,
+ EksPodIdentityAssociationService associations) {
+ this.eks = eks;
+ this.addons = addons;
+ this.associations = associations;
+ }
+
+ /**
+ * Reviews one pod CREATE and returns the {@code AdmissionReview} to hand back to the API server.
+ * The account comes from the URL because the k3s API server calls this anonymously: without it
+ * the cluster would only ever be looked up in the default account.
+ */
+ public Map review(String clusterName, String accountId, Map admissionReview) {
+ String apiVersion = admissionReview != null && admissionReview.get("apiVersion") instanceof String version
+ ? version : DEFAULT_API_VERSION;
+ Map request = admissionReview == null ? null : asMap(admissionReview.get("request"));
+ String uid = request != null && request.get("uid") instanceof String value ? value : "";
+ try {
+ return admissionReview(apiVersion, uid, decide(clusterName, accountId, request));
+ } catch (RuntimeException e) {
+ LOG.warnv("EKS pod-identity-webhook: admitting pod unchanged for cluster {0} after an "
+ + "internal error: {1}", clusterName, e.toString());
+ return admissionReview(apiVersion, uid, List.of());
+ }
+ }
+
+ private List