mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
@@ -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