diff --git a/docs/services/eks.md b/docs/services/eks.md index 2349a69f44..0ce881866d 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -111,8 +111,12 @@ A matching pod is patched exactly the way real EKS patches it. Every init contai | `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` | +| `AWS_ENDPOINT_URL` | Floci's endpoint, as a cluster container reaches it (Floci only) | +| `AWS_ENDPOINT_URL_STS` | The same endpoint (Floci only) | -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. +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 any of the environment variables) is left as the workload set it. + +Real EKS sets neither endpoint variable. Floci adds them so the credentials it hands out are used against Floci, as every container Floci launches already is, instead of being sent to AWS, which rejects them. `AWS_ENDPOINT_URL_STS` is set beside the global variable because the AWS SDK for Go v2 builds the STS client of its web identity provider before it reads `AWS_ENDPOINT_URL`. A pod cannot resolve the Docker host name (`host.docker.internal` lives only in the cluster container's `/etc/hosts`) or Floci's hostname (on a custom Docker network k3s replaces the loopback resolver `127.0.0.11` with a public one, so `localhost.floci.io` answers `127.0.0.1`), so the endpoint is the Docker host address and is injected only when that is an IP address, as it is when Floci runs in a container. A container that sets `AWS_ENDPOINT_URL` itself gets no `AWS_ENDPOINT_URL_STS`, which would override its choice for STS. A container with any `envFrom` source gets no endpoint variable, because its values are unknown at admission and an injected `env` entry would take precedence over them; it still gets the credentials variables. ### Credential endpoint diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerReachableEndpoint.java b/src/main/java/io/floci/aws/core/common/docker/ContainerReachableEndpoint.java index 75e188dabf..d39ef1cd98 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerReachableEndpoint.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerReachableEndpoint.java @@ -23,10 +23,12 @@ import org.eclipse.microprofile.config.inject.ConfigProperty; *
  • {@code CustomResourceCfnProvisioner}, for the {@code ResponseURL} a custom resource * Lambda PUTs its result to
  • *
  • {@code FlociDuckClient}, for the S3 endpoint the DuckDB sidecar calls
  • + *
  • {@code EksPodIdentityWebhook}, for the {@code AWS_ENDPOINT_URL} of EKS pods, through + * {@link #baseUrl(boolean)} without the embedded DNS server, which a pod cannot use
  • * * - *

    Kubernetes pods do not use it: {@code KubernetesFlociAddressResolver} builds their endpoint - * without the embedded DNS server. + *

    Lambda pods on Kubernetes do not use it: {@code KubernetesFlociAddressResolver} builds their + * endpoint without the embedded DNS server. */ @ApplicationScoped public class ContainerReachableEndpoint { diff --git a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java index f70d75bbbf..df5cf8e57b 100644 --- a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java +++ b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java @@ -1671,7 +1671,7 @@ public class EksClusterManager return labels == null ? "localhost" : labels.getOrDefault(ENDPOINT_HOST_LABEL, "localhost"); } - private static boolean isIpv4Literal(String host) { + static boolean isIpv4Literal(String host) { // ofLiteral also takes BSD shorthand such as 1.2.3, which no URL or certificate means. if (host.split("\\.", -1).length != 4) { return false; diff --git a/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java b/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java index 5863f4b877..e023583d2f 100644 --- a/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java +++ b/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java @@ -4,17 +4,20 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.core.common.docker.ContainerReachableEndpoint; import io.floci.aws.services.eks.model.Cluster; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.net.URI; import java.util.ArrayList; import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.function.Supplier; /** * Admission logic behind the EKS Pod Identity mutating webhook. @@ -23,7 +26,9 @@ import java.util.Optional; * 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. + * provider instead of falling through. Floci reproduces exactly that mutation, and also points the + * SDK at Floci with {@code AWS_ENDPOINT_URL} and {@code AWS_ENDPOINT_URL_STS}, as it does for every + * container it launches itself: otherwise the pod's calls, signed with Floci credentials, go to AWS. * *

    Nothing answers {@link #CREDENTIALS_FULL_URI} yet: this class injects the plumbing only, so an * injected pod still cannot obtain credentials. @@ -52,6 +57,12 @@ public class EksPodIdentityWebhook { 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"; + static final String ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; + /** + * Set beside the global variable because the AWS SDK for Go v2 builds the STS client of its web + * identity provider before it reads {@code AWS_ENDPOINT_URL}. + */ + static final String ENV_ENDPOINT_URL_STS = "AWS_ENDPOINT_URL_STS"; private static final String DEFAULT_API_VERSION = "admission.k8s.io/v1"; private static final String DEFAULT_SERVICE_ACCOUNT = "default"; @@ -59,13 +70,22 @@ public class EksPodIdentityWebhook { private final EksService eks; private final EksAddonService addons; private final EksPodIdentityAssociationService associations; + private final Supplier flociEndpoint; + /** The endpoint is the Docker host address a launched container gets, when a pod can reach it. */ @Inject public EksPodIdentityWebhook(EksService eks, EksAddonService addons, - EksPodIdentityAssociationService associations) { + EksPodIdentityAssociationService associations, + ContainerReachableEndpoint endpoint) { + this(eks, addons, associations, () -> podReachableEndpoint(endpoint.baseUrl(false))); + } + + EksPodIdentityWebhook(EksService eks, EksAddonService addons, + EksPodIdentityAssociationService associations, Supplier flociEndpoint) { this.eks = eks; this.addons = addons; this.associations = associations; + this.flociEndpoint = flociEndpoint; } /** @@ -109,10 +129,27 @@ public class EksPodIdentityWebhook { || !hasAssociation(cluster.get(), namespace, serviceAccountOf(pod))) { return List.of(); } - return buildPatch(pod); + return buildPatch(pod, flociEndpoint.get()); }); } + /** + * A pod resolves names through CoreDNS, which never sees the cluster container's + * {@code /etc/hosts}, where {@code host.docker.internal} lives on Linux. Floci's DNS server does + * not reach it either: on a custom Docker network the container's resolver is {@code 127.0.0.11}, + * which k3s rejects as loopback and replaces with a public resolver, so Floci's hostname resolves + * to {@code 127.0.0.1} inside the pod. Only an IP address is reachable, and that is what + * {@code baseUrl(false)} returns whenever Floci runs in a container. No endpoint is injected + * otherwise, which leaves the SDK default. + */ + static String podReachableEndpoint(String baseUrl) { + if (EksClusterManager.isIpv4Literal(URI.create(baseUrl).getHost())) { + return baseUrl; + } + LOG.debugv("EKS pod-identity-webhook: pods cannot resolve {0}, injecting no endpoint", baseUrl); + return null; + } + private boolean podIdentityAgentInstalled(Cluster cluster) { try { addons.describe(cluster, POD_IDENTITY_ADDON); @@ -135,12 +172,14 @@ public class EksPodIdentityWebhook { } /** - * 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. + * The JSONPatch that turns a pod into an injected pod: one projected token volume, then a mount, + * the two credentials environment variables and the two endpoint 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. A container + * that sets {@code AWS_ENDPOINT_URL} gets no {@code AWS_ENDPOINT_URL_STS} either, since the + * service-specific variable would take its STS calls away from the endpoint it chose. */ - static List> buildPatch(Map pod) { + static List> buildPatch(Map pod, String endpointUrl) { Map spec = asMap(pod.get("spec")); if (spec == null) { return List.of(); @@ -152,12 +191,14 @@ public class EksPodIdentityWebhook { } else if (!containsNamed(volumes, TOKEN_VOLUME_NAME)) { patch.add(operation("/spec/volumes/-", tokenVolume())); } - patchContainers(patch, spec, "initContainers"); - patchContainers(patch, spec, "containers"); + List> injectedEnv = injectedEnv(endpointUrl); + patchContainers(patch, spec, "initContainers", injectedEnv); + patchContainers(patch, spec, "containers", injectedEnv); return patch; } - private static void patchContainers(List> patch, Map spec, String field) { + private static void patchContainers(List> patch, Map spec, String field, + List> injectedEnv) { List containers = asList(spec.get(field)); if (containers == null) { return; @@ -175,9 +216,19 @@ public class EksPodIdentityWebhook { patch.add(operation(path + "/volumeMounts/-", tokenMount())); } List env = asList(container.get("env")); + List envFrom = asList(container.get("envFrom")); + boolean mayDefineEndpoint = envFrom != null && !envFrom.isEmpty(); + boolean setsGlobalEndpoint = env != null && containsNamed(env, ENV_ENDPOINT_URL); List> missing = new ArrayList<>(); - for (Map variable : credentialsEnv()) { - if (env == null || !containsNamed(env, String.valueOf(variable.get("name")))) { + for (Map variable : injectedEnv) { + String name = String.valueOf(variable.get("name")); + if (mayDefineEndpoint && isEndpointVariable(name)) { + continue; + } + if (setsGlobalEndpoint && ENV_ENDPOINT_URL_STS.equals(name)) { + continue; + } + if (env == null || !containsNamed(env, name)) { missing.add(variable); } } @@ -215,6 +266,23 @@ public class EksPodIdentityWebhook { Map.of("name", ENV_AUTHORIZATION_TOKEN_FILE, "value", TOKEN_FILE_PATH)); } + /** + * The values {@code envFrom} brings in are not known at admission, and an {@code env} entry would + * take precedence over them, so a container that has any gets no endpoint variable. + */ + private static boolean isEndpointVariable(String name) { + return ENV_ENDPOINT_URL.equals(name) || ENV_ENDPOINT_URL_STS.equals(name); + } + + static List> injectedEnv(String endpointUrl) { + List> env = new ArrayList<>(credentialsEnv()); + if (endpointUrl != null && !endpointUrl.isBlank()) { + env.add(Map.of("name", ENV_ENDPOINT_URL, "value", endpointUrl)); + env.add(Map.of("name", ENV_ENDPOINT_URL_STS, "value", endpointUrl)); + } + return env; + } + private static Map operation(String path, Object value) { return Map.of("op", "add", "path", path, "value", value); } diff --git a/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java b/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java index 3158867ae9..568bf16db9 100644 --- a/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksPodIdentityWebhookTest.java @@ -32,6 +32,7 @@ class EksPodIdentityWebhookTest { private static final String CLUSTER_NAME = "demo"; private static final String ACCOUNT_ID = "123456789012"; private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String FLOCI_ENDPOINT = "http://floci.local:4566"; private EksService eks; private EksAddonService addons; @@ -43,7 +44,7 @@ class EksPodIdentityWebhookTest { eks = Mockito.mock(EksService.class); addons = Mockito.mock(EksAddonService.class); associations = Mockito.mock(EksPodIdentityAssociationService.class); - webhook = new EksPodIdentityWebhook(eks, addons, associations); + webhook = new EksPodIdentityWebhook(eks, addons, associations, () -> FLOCI_ENDPOINT); Cluster cluster = new Cluster(); cluster.setName(CLUSTER_NAME); @@ -121,7 +122,9 @@ class EksPodIdentityWebhookTest { {"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"}]}, + "value":"/var/run/secrets/pods.eks.amazonaws.com/serviceaccount/eks-pod-identity-token"}, + {"name":"AWS_ENDPOINT_URL","value":"http://floci.local:4566"}, + {"name":"AWS_ENDPOINT_URL_STS","value":"http://floci.local:4566"}]}, {"op":"add","path":"/spec/containers/0/volumeMounts","value":[ {"name":"eks-pod-identity-token", "mountPath":"/var/run/secrets/pods.eks.amazonaws.com/serviceaccount", @@ -130,7 +133,9 @@ class EksPodIdentityWebhookTest { {"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"}]} + "value":"/var/run/secrets/pods.eks.amazonaws.com/serviceaccount/eks-pod-identity-token"}, + {"name":"AWS_ENDPOINT_URL","value":"http://floci.local:4566"}, + {"name":"AWS_ENDPOINT_URL_STS","value":"http://floci.local:4566"}]} ]"""), patch); } @@ -218,11 +223,67 @@ class EksPodIdentityWebhookTest { JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, admissionReview(Map.of("kind", "Pod", "spec", spec)))); - assertEquals(1, patch.size()); + assertEquals(3, 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()); } + /** A workload that points its SDK somewhere itself keeps that choice, for STS too. */ + @Test + void endpointTheContainerSetsItselfIsKept() throws Exception { + Map container = Map.of( + "name", "app", + "env", List.of(Map.of("name", "AWS_ENDPOINT_URL", "value", "http://proxy:8080"))); + + JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(pod("checkout", List.of(container))))); + + List added = new ArrayList<>(); + for (JsonNode operation : patch) { + if (operation.get("path").asText().equals("/spec/containers/0/env/-")) { + added.add(operation.get("value").get("name").asText() + "=" + operation.get("value").get("value").asText()); + } + } + assertEquals(List.of( + "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"), added); + } + + /** What {@code envFrom} brings in is unknown at admission, and an injected env entry would win over it. */ + @Test + void containerWithEnvFromGetsCredentialsButNoEndpoint() throws Exception { + Map container = Map.of( + "name", "app", + "envFrom", List.of(Map.of("configMapRef", Map.of("name", "aws-endpoints")))); + + JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(pod("checkout", List.of(container))))); + + JsonNode env = patch.get(patch.size() - 1); + assertEquals("/spec/containers/0/env", env.get("path").asText()); + assertEquals(MAPPER.readTree(""" + [{"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"}]"""), + env.get("value")); + } + + /** A pod resolves neither the cluster container's /etc/hosts nor Floci's DNS, so only an IP works. */ + @Test + void endpointIsOnlyInjectedWhereAPodCanResolveIt() throws Exception { + assertEquals("http://172.18.0.5:4566", + EksPodIdentityWebhook.podReachableEndpoint("http://172.18.0.5:4566")); + assertNull(EksPodIdentityWebhook.podReachableEndpoint("http://localhost.floci.io:4566")); + assertNull(EksPodIdentityWebhook.podReachableEndpoint("http://host.docker.internal:4566")); + + webhook = new EksPodIdentityWebhook(eks, addons, associations, () -> null); + JsonNode patch = patchOf(webhook.review(CLUSTER_NAME, ACCOUNT_ID, + admissionReview(pod("checkout", List.of(Map.of("name", "app")))))); + + assertEquals(2, patch.get(patch.size() - 1).get("value").size(), "credentials only"); + } + @Test void responseEchoesTheRequestApiVersion() { Map review = webhook.review(CLUSTER_NAME, ACCOUNT_ID, Map.of(