mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -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
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user