mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(eks): inject pod identity credentials through a mutating webhook (#4110)
* feat(eks): inject pod identity credentials through a mutating webhook Each real-mode cluster gets a MutatingWebhookConfiguration in its k3s server manifests directory, scoped to pod CREATE and pointing at a per-cluster, per-account Floci endpoint. On a pod create Floci looks up an association matching the pod's namespace and service account name and, when the eks-pod-identity-agent addon is installed, returns a JSONPatch carrying the projected token volume, the mount and the two container credentials environment variables, the same shape real EKS injects. A pod that matches nothing is admitted unchanged. The webhook carries failurePolicy: Ignore and every path through the admission handler admits the pod, including a malformed review and an internal error, so it can never block a pod from being created. Kubernetes only accepts an https webhook URL with a caBundle it trusts, so registration needs floci.tls.enabled; with TLS off the cluster starts with a warning and pods are not mutated. A failed registration logs and leaves the cluster running. Nothing answers http://169.254.170.23/v1/credentials yet, so an injected pod still cannot obtain credentials. * fix(eks): default the pod identity webhook off until the credential endpoint exists Injecting AWS_CONTAINER_CREDENTIALS_FULL_URI sends the SDK down the container credentials path, and nothing answers that URI yet, so a workload that was picking up credentials earlier in the chain loses them. On by default that is a regression for anyone already recording associations, in exchange for a capability that cannot work. Turning it off also takes the per-cluster warning off a default install. The webhook timeout drops from the Kubernetes default of 10 seconds to 3. Floci is a local process, so a healthy call takes milliseconds and the timeout only runs down when Floci is unreachable, which every pod creation in the cluster pays for.
This commit is contained in:
1 parent
14d13ee798
commit
d8239b3e66
8 files changed
+875
-15
No files matched your search
+33
-5
@@ -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
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <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")
|
||||
boolean podIdentityWebhook();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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<String, Instance> 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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>{@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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>Nothing answers {@link #CREDENTIALS_FULL_URI} yet: this class injects the plumbing only, so an
|
||||
* injected pod still cannot obtain credentials.
|
||||
*
|
||||
* <p>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<String, Object> review(String clusterName, String accountId, Map<String, Object> admissionReview) {
|
||||
String apiVersion = admissionReview != null && admissionReview.get("apiVersion") instanceof String version
|
||||
? version : DEFAULT_API_VERSION;
|
||||
Map<String, Object> 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<Map<String, Object>> decide(String clusterName, String accountId,
|
||||
Map<String, Object> request) {
|
||||
if (request == null) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, Object> pod = asMap(request.get("object"));
|
||||
if (pod == null) {
|
||||
return List.of();
|
||||
}
|
||||
String namespace = namespaceOf(request, pod);
|
||||
if (namespace == null) {
|
||||
return List.of();
|
||||
}
|
||||
Optional<Cluster> cluster = eks.findAuthenticationCluster(accountId, clusterName);
|
||||
if (cluster.isEmpty() || !podIdentityAgentInstalled(cluster.get())) {
|
||||
return List.of();
|
||||
}
|
||||
if (!hasAssociation(cluster.get(), namespace, serviceAccountOf(pod))) {
|
||||
return List.of();
|
||||
}
|
||||
return buildPatch(pod);
|
||||
}
|
||||
|
||||
private boolean podIdentityAgentInstalled(Cluster cluster) {
|
||||
try {
|
||||
addons.describe(cluster, POD_IDENTITY_ADDON);
|
||||
return true;
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv("EKS pod-identity-webhook: cluster {0} has no {1} addon, admitting pods unchanged ({2})",
|
||||
cluster.getName(), POD_IDENTITY_ADDON, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasAssociation(Cluster cluster, String namespace, String serviceAccount) {
|
||||
try {
|
||||
return !associations.list(cluster, namespace, serviceAccount, 1, null).associations().isEmpty();
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv("EKS pod-identity-webhook: could not list associations for {0}/{1} on cluster {2} ({3})",
|
||||
namespace, serviceAccount, cluster.getName(), e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The JSONPatch that turns a pod into an injected pod: one projected token volume, then a mount
|
||||
* and the two credentials environment variables on every init container and container. An entry
|
||||
* the pod already carries under the same name is left alone, matching the real webhook, which
|
||||
* never overrides a value the workload set itself.
|
||||
*/
|
||||
static List<Map<String, Object>> buildPatch(Map<String, Object> pod) {
|
||||
Map<String, Object> spec = asMap(pod.get("spec"));
|
||||
if (spec == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<Map<String, Object>> patch = new ArrayList<>();
|
||||
List<Object> volumes = asList(spec.get("volumes"));
|
||||
if (volumes == null) {
|
||||
patch.add(operation("/spec/volumes", List.of(tokenVolume())));
|
||||
} else if (!containsNamed(volumes, TOKEN_VOLUME_NAME)) {
|
||||
patch.add(operation("/spec/volumes/-", tokenVolume()));
|
||||
}
|
||||
patchContainers(patch, spec, "initContainers");
|
||||
patchContainers(patch, spec, "containers");
|
||||
return patch;
|
||||
}
|
||||
|
||||
private static void patchContainers(List<Map<String, Object>> patch, Map<String, Object> spec, String field) {
|
||||
List<Object> containers = asList(spec.get(field));
|
||||
if (containers == null) {
|
||||
return;
|
||||
}
|
||||
for (int index = 0; index < containers.size(); index++) {
|
||||
Map<String, Object> container = asMap(containers.get(index));
|
||||
if (container == null) {
|
||||
continue;
|
||||
}
|
||||
String path = "/spec/" + field + "/" + index;
|
||||
List<Object> 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<Object> env = asList(container.get("env"));
|
||||
List<Map<String, Object>> missing = new ArrayList<>();
|
||||
for (Map<String, Object> variable : credentialsEnv()) {
|
||||
if (env == null || !containsNamed(env, String.valueOf(variable.get("name")))) {
|
||||
missing.add(variable);
|
||||
}
|
||||
}
|
||||
if (missing.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (env == null) {
|
||||
patch.add(operation(path + "/env", missing));
|
||||
} else {
|
||||
for (Map<String, Object> variable : missing) {
|
||||
patch.add(operation(path + "/env/-", variable));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static Map<String, Object> tokenVolume() {
|
||||
return Map.of(
|
||||
"name", TOKEN_VOLUME_NAME,
|
||||
"projected", Map.of(
|
||||
"defaultMode", TOKEN_DEFAULT_MODE,
|
||||
"sources", List.of(Map.of("serviceAccountToken", Map.of(
|
||||
"audience", TOKEN_AUDIENCE,
|
||||
"expirationSeconds", TOKEN_EXPIRATION_SECONDS,
|
||||
"path", TOKEN_FILE_NAME)))));
|
||||
}
|
||||
|
||||
static Map<String, Object> tokenMount() {
|
||||
return Map.of("name", TOKEN_VOLUME_NAME, "mountPath", TOKEN_MOUNT_PATH, "readOnly", true);
|
||||
}
|
||||
|
||||
static List<Map<String, Object>> credentialsEnv() {
|
||||
return List.of(
|
||||
Map.of("name", ENV_CREDENTIALS_FULL_URI, "value", CREDENTIALS_FULL_URI),
|
||||
Map.of("name", ENV_AUTHORIZATION_TOKEN_FILE, "value", TOKEN_FILE_PATH));
|
||||
}
|
||||
|
||||
private static Map<String, Object> operation(String path, Object value) {
|
||||
return Map.of("op", "add", "path", path, "value", value);
|
||||
}
|
||||
|
||||
private static Map<String, Object> admissionReview(String apiVersion, String uid,
|
||||
List<Map<String, Object>> patch) {
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
response.put("uid", uid);
|
||||
response.put("allowed", true);
|
||||
if (!patch.isEmpty()) {
|
||||
response.put("patchType", "JSONPatch");
|
||||
response.put("patch", encodePatch(patch));
|
||||
}
|
||||
return Map.of("apiVersion", apiVersion, "kind", "AdmissionReview", "response", response);
|
||||
}
|
||||
|
||||
private static String encodePatch(List<Map<String, Object>> patch) {
|
||||
try {
|
||||
return Base64.getEncoder().encodeToString(MAPPER.writeValueAsBytes(patch));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Could not serialize the pod identity JSONPatch", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The namespace the admission decision is made against: the API server always sets it on the
|
||||
* request, and the pod's own metadata is the fallback for a hand-made review.
|
||||
*/
|
||||
private static String namespaceOf(Map<String, Object> request, Map<String, Object> pod) {
|
||||
if (request.get("namespace") instanceof String namespace && !namespace.isBlank()) {
|
||||
return namespace;
|
||||
}
|
||||
Map<String, Object> metadata = asMap(pod.get("metadata"));
|
||||
if (metadata != null && metadata.get("namespace") instanceof String namespace && !namespace.isBlank()) {
|
||||
return namespace;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Kubernetes defaults an omitted service account to {@code default} before webhooks run. */
|
||||
private static String serviceAccountOf(Map<String, Object> pod) {
|
||||
Map<String, Object> spec = asMap(pod.get("spec"));
|
||||
if (spec != null && spec.get("serviceAccountName") instanceof String name && !name.isBlank()) {
|
||||
return name;
|
||||
}
|
||||
return DEFAULT_SERVICE_ACCOUNT;
|
||||
}
|
||||
|
||||
private static boolean containsNamed(List<Object> entries, String name) {
|
||||
for (Object entry : entries) {
|
||||
Map<String, Object> map = asMap(entry);
|
||||
if (map != null && name.equals(map.get("name"))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> asMap(Object value) {
|
||||
return value instanceof Map<?, ?> map ? (Map<String, Object>) map : null;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static List<Object> asList(Object value) {
|
||||
return value instanceof List<?> list ? (List<Object>) list : null;
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Kubernetes mutating admission webhook for EKS Pod Identity on k3s-backed clusters.
|
||||
*
|
||||
* <p>The {@code MutatingWebhookConfiguration} that {@code EksClusterManager} drops into the
|
||||
* cluster's k3s manifests directory points here, scoped per cluster and account in the style of the
|
||||
* token webhook. The API server calls Floci with no AWS credentials, so the account has to come
|
||||
* from the URL.
|
||||
*
|
||||
* <p>Unlike the token webhook, which is configured through a kubeconfig and may be plain HTTP,
|
||||
* Kubernetes requires an {@code https} URL here, so the route is only registered when
|
||||
* {@code floci.tls.enabled} is on.
|
||||
*
|
||||
* <p>This is Floci plumbing under the {@code _floci/...} namespace, not an AWS API.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
@Path("_floci/eks/clusters/{clusterName}/pod-identity-webhook")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class EksPodIdentityWebhookController {
|
||||
|
||||
private final EksPodIdentityWebhook webhook;
|
||||
|
||||
@Inject
|
||||
public EksPodIdentityWebhookController(EksPodIdentityWebhook webhook) {
|
||||
this.webhook = webhook;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("scope/{accountId}")
|
||||
public Response review(@PathParam("clusterName") String clusterName,
|
||||
@PathParam("accountId") String accountId,
|
||||
Map<String, Object> admissionReview) {
|
||||
return Response.ok(webhook.review(clusterName, accountId, admissionReview)).build();
|
||||
}
|
||||
}
|
||||
@@ -604,6 +604,7 @@ floci:
|
||||
imds: false # expose link-local IMDS (169.254.169.254) inside the cluster container
|
||||
imds-pod-network: false # route link-local IMDS traffic from ordinary pod network namespaces (requires imds: true)
|
||||
irsa-signing-key: true # sign k3s service account tokens with the cluster OIDC key
|
||||
pod-identity-webhook: false # register a mutating webhook that injects pod identity credentials (needs floci.tls.enabled; nothing answers the injected URI yet)
|
||||
mwaa:
|
||||
enabled: true
|
||||
mock: false
|
||||
|
||||
@@ -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;
|
||||
@@ -42,6 +43,7 @@ import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
@@ -49,6 +51,7 @@ import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -1375,4 +1378,134 @@ class EksClusterManagerTest {
|
||||
verify(lifecycleManager, Mockito.times(2)).removeIfExists("floci-eks-fail-cluster");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class RegisterPodIdentityWebhook {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private static final String CA_PEM = "-----BEGIN CERTIFICATE-----\nfloci-root-ca\n-----END CERTIFICATE-----\n";
|
||||
|
||||
private EmulatorConfig config;
|
||||
private EmulatorConfig.EksServiceConfig eks;
|
||||
private EmulatorConfig.TlsConfig tls;
|
||||
private ContainerLifecycleManager lifecycleManager;
|
||||
private CopyArchiveToContainerCmd copyCmd;
|
||||
private EksClusterManager manager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
config = Mockito.mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
eks = Mockito.mock(EmulatorConfig.EksServiceConfig.class);
|
||||
tls = Mockito.mock(EmulatorConfig.TlsConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.eks()).thenReturn(eks);
|
||||
when(config.tls()).thenReturn(tls);
|
||||
when(config.port()).thenReturn(4566);
|
||||
when(eks.podIdentityWebhook()).thenReturn(true);
|
||||
when(eks.dataPath()).thenReturn(tempDir.toString());
|
||||
when(eks.defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1");
|
||||
when(eks.dockerNetwork()).thenReturn(Optional.empty());
|
||||
when(eks.endpointMode()).thenReturn("host");
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
when(tls.enabled()).thenReturn(true);
|
||||
|
||||
lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
|
||||
DockerClient dockerClient = Mockito.mock(DockerClient.class);
|
||||
copyCmd = Mockito.mock(CopyArchiveToContainerCmd.class, Mockito.RETURNS_SELF);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
when(dockerClient.copyArchiveToContainerCmd(anyString())).thenReturn(copyCmd);
|
||||
when(lifecycleManager.create(any())).thenReturn("container-1");
|
||||
when(lifecycleManager.startCreated(any(), any()))
|
||||
.thenReturn(new ContainerInfo("container-1", Map.of()));
|
||||
|
||||
ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
|
||||
when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class));
|
||||
|
||||
DockerHostResolver dockerHostResolver = Mockito.mock(DockerHostResolver.class);
|
||||
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
|
||||
|
||||
RegionResolver regionResolver = Mockito.mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
|
||||
FlociCertificateAuthority certificateAuthority = Mockito.mock(FlociCertificateAuthority.class);
|
||||
when(certificateAuthority.caPem()).thenReturn(CA_PEM);
|
||||
|
||||
manager = new EksClusterManager(
|
||||
containerBuilder, lifecycleManager,
|
||||
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
|
||||
dockerHostResolver, Mockito.mock(EcrRegistryManager.class), config,
|
||||
regionResolver, null, null, certificateAuthority);
|
||||
}
|
||||
|
||||
private Cluster cluster() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("demo");
|
||||
cluster.setAccountId("000000000000");
|
||||
return cluster;
|
||||
}
|
||||
|
||||
@Test
|
||||
void configurationCarriesTheCaBundleAndAnHttpsUrl() {
|
||||
String manifest = EksClusterManager.buildPodIdentityWebhookConfiguration(
|
||||
"https://host.docker.internal:4566/_floci/eks/clusters/demo/pod-identity-webhook/scope/000000000000", CA_PEM);
|
||||
|
||||
assertTrue(manifest.contains("kind: MutatingWebhookConfiguration"));
|
||||
assertTrue(manifest.contains("url: \"https://host.docker.internal:4566"
|
||||
+ "/_floci/eks/clusters/demo/pod-identity-webhook/scope/000000000000\""));
|
||||
assertTrue(manifest.contains("caBundle: \""
|
||||
+ Base64.getEncoder().encodeToString(CA_PEM.getBytes(StandardCharsets.UTF_8)) + "\""));
|
||||
assertTrue(manifest.contains("failurePolicy: Ignore"));
|
||||
assertTrue(manifest.contains("operations: [\"CREATE\"]"));
|
||||
assertTrue(manifest.contains("resources: [\"pods\"]"));
|
||||
assertFalse(manifest.contains("url: \"http://"), "Kubernetes rejects a non-https webhook URL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesTheManifestIntoTheK3sManifestsDirectory() throws Exception {
|
||||
manager.registerPodIdentityWebhook("container-1", cluster());
|
||||
|
||||
verify(copyCmd).withRemotePath("/var/lib/rancher/k3s");
|
||||
verify(copyCmd).exec();
|
||||
String written = Files.readString(tempDir.resolve("webhook").resolve("demo")
|
||||
.resolve("floci-eks-pod-identity.yaml"));
|
||||
assertTrue(written.contains("https://host.docker.internal:4566"
|
||||
+ "/_floci/eks/clusters/demo/pod-identity-webhook/scope/000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsWithAWarningWhenTlsIsDisabled() {
|
||||
when(tls.enabled()).thenReturn(false);
|
||||
|
||||
manager.registerPodIdentityWebhook("container-1", cluster());
|
||||
|
||||
verify(lifecycleManager, never()).getDockerClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsWhenTheKnobIsOff() {
|
||||
when(eks.podIdentityWebhook()).thenReturn(false);
|
||||
|
||||
manager.registerPodIdentityWebhook("container-1", cluster());
|
||||
|
||||
verify(lifecycleManager, never()).getDockerClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
void registrationFailureLeavesTheClusterRunning() {
|
||||
when(copyCmd.exec()).thenThrow(new RuntimeException("no such container"));
|
||||
Cluster cluster = cluster();
|
||||
|
||||
manager.startCluster(cluster);
|
||||
|
||||
verify(copyCmd).exec();
|
||||
verify(lifecycleManager).startCreated(any(), any());
|
||||
assertEquals("container-1", cluster.getContainerId());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.eks.model.Addon;
|
||||
import io.github.hectorvent.floci.services.eks.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.eks.model.PodIdentityAssociationSummary;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
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 static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class EksPodIdentityWebhookTest {
|
||||
|
||||
private static final String CLUSTER_NAME = "demo";
|
||||
private static final String ACCOUNT_ID = "123456789012";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private EksService eks;
|
||||
private EksAddonService addons;
|
||||
private EksPodIdentityAssociationService associations;
|
||||
private EksPodIdentityWebhook webhook;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
eks = Mockito.mock(EksService.class);
|
||||
addons = Mockito.mock(EksAddonService.class);
|
||||
associations = Mockito.mock(EksPodIdentityAssociationService.class);
|
||||
webhook = new EksPodIdentityWebhook(eks, addons, associations);
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName(CLUSTER_NAME);
|
||||
when(eks.findAuthenticationCluster(ACCOUNT_ID, CLUSTER_NAME)).thenReturn(Optional.of(cluster));
|
||||
when(addons.describe(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON)))
|
||||
.thenReturn(Mockito.mock(Addon.class));
|
||||
when(associations.list(any(), anyString(), anyString(), any(), any()))
|
||||
.thenReturn(new EksPodIdentityAssociationService.Page(
|
||||
List.of(Mockito.mock(PodIdentityAssociationSummary.class)), null));
|
||||
}
|
||||
|
||||
private Map<String, Object> admissionReview(Map<String, Object> pod) {
|
||||
return Map.of(
|
||||
"apiVersion", "admission.k8s.io/v1",
|
||||
"kind", "AdmissionReview",
|
||||
"request", Map.of("uid", "req-1", "namespace", "payments", "object", pod));
|
||||
}
|
||||
|
||||
private Map<String, Object> pod(String serviceAccount, List<Object> containers) {
|
||||
Map<String, Object> spec = new LinkedHashMap<>();
|
||||
spec.put("serviceAccountName", serviceAccount);
|
||||
spec.put("containers", containers);
|
||||
return Map.of("kind", "Pod", "metadata", Map.of("name", "api"), "spec", spec);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> response(Map<String, Object> review) {
|
||||
return (Map<String, Object>) review.get("response");
|
||||
}
|
||||
|
||||
private JsonNode patchOf(Map<String, Object> review) throws Exception {
|
||||
Object patch = response(review).get("patch");
|
||||
return patch == null ? null
|
||||
: MAPPER.readTree(Base64.getDecoder().decode((String) patch));
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchingServiceAccountIsPatched() throws Exception {
|
||||
Map<String, Object> review = webhook.review(CLUSTER_NAME, ACCOUNT_ID,
|
||||
admissionReview(pod("checkout", List.of(Map.of("name", "app")))));
|
||||
|
||||
assertEquals(Boolean.TRUE, response(review).get("allowed"));
|
||||
assertEquals("req-1", response(review).get("uid"));
|
||||
assertEquals("JSONPatch", response(review).get("patchType"));
|
||||
assertEquals(3, patchOf(review).size());
|
||||
Mockito.verify(associations).list(any(), eq("payments"), eq("checkout"), any(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
* The exact shape an AWS SDK matches on: the environment variable names and values, the mount
|
||||
* path and the token audience. A near-miss silently does nothing, so this asserts the whole
|
||||
* patch rather than probing it. Init containers get the same treatment as containers.
|
||||
*/
|
||||
@Test
|
||||
void patchMatchesTheAwsPodIdentityInjectionExactly() throws Exception {
|
||||
Map<String, Object> spec = new LinkedHashMap<>();
|
||||
spec.put("serviceAccountName", "checkout");
|
||||
spec.put("initContainers", List.of(Map.of("name", "migrate")));
|
||||
spec.put("containers", List.of(Map.of("name", "app")));
|
||||
Map<String, Object> pod = Map.of("kind", "Pod", "spec", spec);
|
||||
|
||||
JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, admissionReview(pod)));
|
||||
|
||||
assertEquals(MAPPER.readTree("""
|
||||
[
|
||||
{"op":"add","path":"/spec/volumes","value":[
|
||||
{"name":"eks-pod-identity-token","projected":{"defaultMode":420,"sources":[
|
||||
{"serviceAccountToken":{"audience":"pods.eks.amazonaws.com",
|
||||
"expirationSeconds":86400,"path":"eks-pod-identity-token"}}]}}]},
|
||||
{"op":"add","path":"/spec/initContainers/0/volumeMounts","value":[
|
||||
{"name":"eks-pod-identity-token",
|
||||
"mountPath":"/var/run/secrets/pods.eks.amazonaws.com/serviceaccount",
|
||||
"readOnly":true}]},
|
||||
{"op":"add","path":"/spec/initContainers/0/env","value":[
|
||||
{"name":"AWS_CONTAINER_CREDENTIALS_FULL_URI",
|
||||
"value":"http://169.254.170.23/v1/credentials"},
|
||||
{"name":"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
|
||||
"value":"/var/run/secrets/pods.eks.amazonaws.com/serviceaccount/eks-pod-identity-token"}]},
|
||||
{"op":"add","path":"/spec/containers/0/volumeMounts","value":[
|
||||
{"name":"eks-pod-identity-token",
|
||||
"mountPath":"/var/run/secrets/pods.eks.amazonaws.com/serviceaccount",
|
||||
"readOnly":true}]},
|
||||
{"op":"add","path":"/spec/containers/0/env","value":[
|
||||
{"name":"AWS_CONTAINER_CREDENTIALS_FULL_URI",
|
||||
"value":"http://169.254.170.23/v1/credentials"},
|
||||
{"name":"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
|
||||
"value":"/var/run/secrets/pods.eks.amazonaws.com/serviceaccount/eks-pod-identity-token"}]}
|
||||
]"""), patch);
|
||||
}
|
||||
|
||||
@Test
|
||||
void podMatchingNoAssociationIsAdmittedUnchanged() throws Exception {
|
||||
when(associations.list(any(), anyString(), anyString(), any(), any()))
|
||||
.thenReturn(new EksPodIdentityAssociationService.Page(List.of(), null));
|
||||
|
||||
Map<String, Object> review = webhook.review(CLUSTER_NAME, ACCOUNT_ID,
|
||||
admissionReview(pod("unassociated", List.of(Map.of("name", "app")))));
|
||||
|
||||
assertEquals(Boolean.TRUE, response(review).get("allowed"));
|
||||
assertNull(patchOf(review));
|
||||
assertFalse(response(review).containsKey("patchType"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterWithoutThePodIdentityAgentAddonIsNotPatched() throws Exception {
|
||||
when(addons.describe(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON)))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "No addon", 404));
|
||||
|
||||
Map<String, Object> review = webhook.review(CLUSTER_NAME, ACCOUNT_ID,
|
||||
admissionReview(pod("checkout", List.of(Map.of("name", "app")))));
|
||||
|
||||
assertEquals(Boolean.TRUE, response(review).get("allowed"));
|
||||
assertNull(patchOf(review));
|
||||
Mockito.verifyNoInteractions(associations);
|
||||
}
|
||||
|
||||
/** The account is in the webhook URL because the API server calls Floci with no credentials. */
|
||||
@Test
|
||||
void clusterOwnedByAnotherAccountIsNotPatched() throws Exception {
|
||||
Map<String, Object> review = webhook.review(CLUSTER_NAME, "000000000000",
|
||||
admissionReview(pod("checkout", List.of(Map.of("name", "app")))));
|
||||
|
||||
assertEquals(Boolean.TRUE, response(review).get("allowed"));
|
||||
assertNull(patchOf(review));
|
||||
Mockito.verifyNoInteractions(addons, associations);
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedReviewIsAdmittedRatherThanRejected() throws Exception {
|
||||
for (Map<String, Object> malformed : malformedReviews()) {
|
||||
Map<String, Object> review = webhook.review(CLUSTER_NAME, ACCOUNT_ID, malformed);
|
||||
assertEquals(Boolean.TRUE, response(review).get("allowed"), () -> "rejected " + malformed);
|
||||
assertEquals("AdmissionReview", review.get("kind"));
|
||||
assertNull(patchOf(review));
|
||||
}
|
||||
assertEquals(Boolean.TRUE, response(webhook.review(CLUSTER_NAME, ACCOUNT_ID, null)).get("allowed"));
|
||||
}
|
||||
|
||||
private static List<Map<String, Object>> malformedReviews() {
|
||||
List<Map<String, Object>> reviews = new ArrayList<>();
|
||||
reviews.add(Map.of());
|
||||
reviews.add(Map.of("request", "not-an-object"));
|
||||
reviews.add(Map.of("request", Map.of("uid", "req-1")));
|
||||
reviews.add(Map.of("request", Map.of("uid", "req-1", "namespace", "payments",
|
||||
"object", Map.of("kind", "Pod"))));
|
||||
return reviews;
|
||||
}
|
||||
|
||||
@Test
|
||||
void internalErrorStillAdmitsThePod() throws Exception {
|
||||
when(eks.findAuthenticationCluster(ACCOUNT_ID, CLUSTER_NAME))
|
||||
.thenThrow(new IllegalStateException("storage is gone"));
|
||||
|
||||
Map<String, Object> review = webhook.review(CLUSTER_NAME, ACCOUNT_ID,
|
||||
admissionReview(pod("checkout", List.of(Map.of("name", "app")))));
|
||||
|
||||
assertEquals(Boolean.TRUE, response(review).get("allowed"));
|
||||
assertNull(patchOf(review));
|
||||
}
|
||||
|
||||
/** The real webhook never overrides what the workload set itself. */
|
||||
@Test
|
||||
void entriesThePodAlreadyCarriesAreLeftAlone() throws Exception {
|
||||
Map<String, Object> spec = new LinkedHashMap<>();
|
||||
spec.put("serviceAccountName", "checkout");
|
||||
spec.put("volumes", List.of(Map.of("name", "eks-pod-identity-token")));
|
||||
spec.put("containers", List.of(Map.of(
|
||||
"name", "app",
|
||||
"volumeMounts", List.of(Map.of("name", "eks-pod-identity-token", "mountPath", "/elsewhere")),
|
||||
"env", List.of(Map.of("name", "AWS_CONTAINER_CREDENTIALS_FULL_URI", "value", "http://127.0.0.1/x")))));
|
||||
|
||||
JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID,
|
||||
admissionReview(Map.of("kind", "Pod", "spec", spec))));
|
||||
|
||||
assertEquals(1, patch.size());
|
||||
assertEquals("/spec/containers/0/env/-", patch.get(0).get("path").asText());
|
||||
assertEquals("AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE", patch.get(0).get("value").get("name").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void responseEchoesTheRequestApiVersion() {
|
||||
Map<String, Object> review = webhook.review(CLUSTER_NAME, ACCOUNT_ID, Map.of(
|
||||
"apiVersion", "admission.k8s.io/v1beta1",
|
||||
"request", Map.of("uid", "req-9")));
|
||||
|
||||
assertEquals("admission.k8s.io/v1beta1", review.get("apiVersion"));
|
||||
assertTrue(response(review).containsKey("uid"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user