From 1d8499e8373fb99138f4c985a3d42c6a939e67bc Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:51:14 -0400 Subject: [PATCH] fix(eks): resolve pod names through Floci's embedded DNS (#8924) Pods resolve through CoreDNS, which forwards to the resolver file k3s hands them. k3s takes the node's /etc/resolv.conf, and on a user-defined Docker network that names only Docker's loopback 127.0.0.11, which k3s refuses; it then writes a file naming a public resolver. So Route 53 private zones, Cloud Map names and the other names only Floci answers never resolved from a pod. When embedded DNS is on and running, and the cluster's Docker network can reach it, Floci now copies a resolver file naming only its DNS server into the cluster container before it starts, and passes it to k3s with --resolv-conf. With Floci in a container that means the cluster is on Floci's own network: Docker isolates user-defined networks, and pods given only an unreachable resolver would lose the public one too. The public fallback resolvers stay out of it, because CoreDNS picks among its upstreams at random. A cluster that sets the kubelet's resolv-conf through its tags keeps its own file. A file that cannot be copied fails the start, as a container that cannot start does, since k3s would hand its pods a missing file. --- docs/services/eks.md | 4 +- .../core/common/docker/ContainerBuilder.java | 20 ++ .../aws/services/eks/EksClusterArgs.java | 22 +- .../aws/services/eks/EksClusterManager.java | 33 +++ .../services/eks/EksPodIdentityWebhook.java | 10 +- .../common/docker/ContainerBuilderTest.java | 27 +++ .../aws/services/eks/EksClusterArgsTest.java | 23 ++ .../eks/EksClusterPodResolvConfTest.java | 204 ++++++++++++++++++ .../EksRoute53DnsDockerIntegrationTest.java | 85 ++++++-- 9 files changed, 407 insertions(+), 21 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/eks/EksClusterPodResolvConfTest.java diff --git a/docs/services/eks.md b/docs/services/eks.md index 338879068c..264ff7c780 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -146,7 +146,7 @@ A matching pod is patched exactly the way real EKS patches it. Every init contai 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. +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, unless the cluster's pods resolve through Floci's embedded DNS (see [DNS resolution](#dns-resolution-and-route-53-private-hosted-zones)), Floci's hostname (k3s replaces a custom Docker network's 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 @@ -803,6 +803,8 @@ Requirements and limits: By default, Floci injects its embedded DNS server into each cluster container (`FLOCI_SERVICES_EKS_EMBEDDED_DNS=true`). Cluster containers and CoreDNS forward to Floci's embedded resolver on port 53, enabling resolution of Route 53 private hosted zone records, internal hostnames, and records managed by `external-dns`. Set `FLOCI_SERVICES_EKS_EMBEDDED_DNS=false` to use standard Docker network DNS instead. +Pods resolve through CoreDNS, which forwards to the resolver file k3s hands its pods. Floci writes that file to `/etc/rancher/k3s/floci-resolv.conf` in the cluster container, naming only its embedded DNS server, and starts k3s with `--resolv-conf` pointing at it. With Floci in a container, it does so only when the cluster joins Floci's own Docker network, the default when neither `FLOCI_SERVICES_EKS_DOCKER_NETWORK` nor `FLOCI_SERVICES_DOCKER_NETWORK` names another: Docker isolates user-defined networks from each other, so on another network the pods keep k3s's resolver rather than one they cannot reach. Otherwise k3s reads the container's `/etc/resolv.conf`, which on a user-defined Docker network names only Docker's `127.0.0.11`; k3s refuses that loopback address and writes a file naming a public resolver, which never sees Floci's names. The public fallback resolvers (`FLOCI_DNS_CONTAINER_FALLBACK_SERVERS`) stay out of the file, because CoreDNS picks among its upstreams at random and a public one would answer some lookups of Floci's names; Floci forwards every name it does not hold itself. A cluster that sets the kubelet's resolver file itself, with the `floci:kubelet-arg:resolv-conf` tag, keeps its own file. + ### Registry host configuration (pull-through caches and custom mirrors) On standard EKS (such as AL2023), node registry host configuration is provided through the node diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java b/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java index 03dc2d75b3..a03ca38920 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java @@ -98,6 +98,26 @@ public class ContainerBuilder { return resolveDockerNetwork(serviceNetwork, config, currentContainerNetworkResolver); } + /** + * The address {@link Builder#withEmbeddedDns} hands a container as its first resolver, when a + * container on the network {@link Builder#withDockerNetwork} picks for {@code serviceNetwork} can + * reach it; empty when it cannot or the embedded DNS server is not running. Exposed for a container + * that must name that resolver alone in a file of its own, as a k3s node does for its pods, where an + * unreachable one leaves no resolver at all. Floci in a container listens on its own address on its + * own network, which Docker isolates from every other user-defined network. Floci running natively + * listens on the Docker bridge address, which every container already gets as its resolver. + */ + public Optional embeddedDnsServerIpReachableOn(Optional serviceNetwork) { + Optional dnsServerIp = embeddedDnsServer != null ? embeddedDnsServer.getServerIp() : Optional.empty(); + Optional flociNetwork = currentContainerNetworkResolver != null + ? currentContainerNetworkResolver.resolveNetworkName() + : Optional.empty(); + if (dnsServerIp.isEmpty() || flociNetwork.isEmpty()) { + return dnsServerIp; + } + return resolveDockerNetwork(serviceNetwork).equals(flociNetwork) ? dnsServerIp : Optional.empty(); + } + private static Optional resolveDockerNetwork(Optional serviceNetwork, EmulatorConfig config, CurrentContainerNetworkResolver currentContainerNetworkResolver) { return serviceNetwork diff --git a/src/main/java/io/floci/aws/services/eks/EksClusterArgs.java b/src/main/java/io/floci/aws/services/eks/EksClusterArgs.java index 5f3876ed23..f50d4077ad 100644 --- a/src/main/java/io/floci/aws/services/eks/EksClusterArgs.java +++ b/src/main/java/io/floci/aws/services/eks/EksClusterArgs.java @@ -181,6 +181,21 @@ public final class EksClusterArgs { } } + /** Whether {@code clusterArgs} set the kubelet's resolv-conf, the resolver file its pods get. */ + public static boolean setsKubeletResolvConf(List clusterArgs) { + if (clusterArgs == null) { + return false; + } + String prefix = Component.KUBELET.flagPrefix(); + for (String arg : clusterArgs) { + if (arg != null && arg.startsWith(prefix) + && "resolvconf".equals(normalizedFlagName(extractFlagName(arg.substring(prefix.length()))))) { + return true; + } + } + return false; + } + private record ParsedTag(Component component, TagKind kind, String prefixMatched) {} private enum TagKind { @@ -280,7 +295,7 @@ public final class EksClusterArgs { private static void validateCollision(Component component, String flag) { String rawName = extractFlagName(flag); - String flagName = rawName.replace("-", "").toLowerCase(Locale.ROOT); + String flagName = normalizedFlagName(rawName); if (component == Component.KUBELET) { if (FLOCI_MANAGED_KUBELET_FLAGS.contains(flagName)) { @@ -301,6 +316,11 @@ public final class EksClusterArgs { } } + /** A flag name without its hyphens, lower-cased, so spellings that differ only in those match. */ + private static String normalizedFlagName(String flagName) { + return flagName.replace("-", "").toLowerCase(Locale.ROOT); + } + private static String extractFlagName(String flag) { int eqIndex = flag.indexOf('='); String name = (eqIndex >= 0) ? flag.substring(0, eqIndex).trim() : flag.trim(); 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 ec8e667851..bcf2d51b4d 100644 --- a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java +++ b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java @@ -137,6 +137,9 @@ 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"; + // The resolv.conf k3s hands its pods (--resolv-conf), extracted at /etc as registries.yaml is. + static final String POD_RESOLV_CONF_TAR_ENTRY = "rancher/k3s/floci-resolv.conf"; + static final String POD_RESOLV_CONF_PATH = "/etc/" + POD_RESOLV_CONF_TAR_ENTRY; // 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 @@ -834,6 +837,7 @@ public class EksClusterManager String webhookLocalFile = null; SigningKeyFiles signingKeyFiles = null; String auditPolicyLocalFile = null; + String podResolvConf = null; ContainerSpec spec; String containerId; try { @@ -970,6 +974,10 @@ public class EksClusterManager } List callerArgs = resolveCallerArgs(cluster); + podResolvConf = podResolvConf(callerArgs); + if (podResolvConf != null) { + serverArgs.add("--resolv-conf=" + POD_RESOLV_CONF_PATH); + } if (!callerArgs.isEmpty()) { serverArgs.addAll(callerArgs); } @@ -1044,6 +1052,12 @@ public class EksClusterManager deferGuestSetup(containerId, false); ContainerInfo info; try { + if (podResolvConf != null) { + // Part of the start: k3s would hand its pods a resolver file that is not there, and no pod could start. + RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, "/etc", + POD_RESOLV_CONF_TAR_ENTRY, podResolvConf.getBytes(StandardCharsets.UTF_8), 0644, + RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, archiveRetryBackoffMillis); + } info = lifecycleManager.startCreated(containerId, spec); } catch (Exception e) { abandonGuestSetup(containerId, "its container could not be started"); @@ -2042,6 +2056,25 @@ public class EksClusterManager return wrappedCmd; } + /** + * The resolv.conf k3s hands its pods, naming only Floci's embedded DNS server, or null when k3s keeps + * its own choice: embedded DNS is off, not running or not reachable from the cluster's Docker network, + * or the caller set the kubelet's resolv-conf. + * k3s otherwise reads the node's /etc/resolv.conf, which on a user-defined Docker network names only + * Docker's loopback resolver 127.0.0.11. k3s refuses a loopback-only file and writes one naming a + * public resolver instead, so CoreDNS never asks Floci and names only Floci holds do not resolve. + * Floci's public fallback resolvers stay out of the file: CoreDNS picks among its upstreams at random, + * so one of them would answer some lookups of Floci's names. Floci forwards every other name itself. + */ + private String podResolvConf(List callerArgs) { + if (!config.services().eks().embeddedDns() || EksClusterArgs.setsKubeletResolvConf(callerArgs)) { + return null; + } + return containerBuilder.embeddedDnsServerIpReachableOn(config.services().eks().dockerNetwork()) + .map(dnsServerIp -> "nameserver " + dnsServerIp + "\n") + .orElse(null); + } + /** * Resolves caller-supplied k3s arguments configured on the cluster or in its creation tags. */ 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 e655d669b9..b3541fcd41 100644 --- a/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java +++ b/src/main/java/io/floci/aws/services/eks/EksPodIdentityWebhook.java @@ -150,11 +150,11 @@ public class EksPodIdentityWebhook { /** * 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 + * {@code /etc/hosts}, where {@code host.docker.internal} lives on Linux. Floci's hostname resolves + * in a pod only when the cluster hands its pods Floci's embedded DNS server: without it, a custom + * Docker network's resolver is {@code 127.0.0.11}, which k3s rejects as loopback and replaces with + * a public resolver, so the name resolves to {@code 127.0.0.1}. An IP address is reachable either + * way, 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) { diff --git a/src/test/java/io/floci/aws/core/common/docker/ContainerBuilderTest.java b/src/test/java/io/floci/aws/core/common/docker/ContainerBuilderTest.java index 9c92fead0d..7fe9427fa8 100644 --- a/src/test/java/io/floci/aws/core/common/docker/ContainerBuilderTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerBuilderTest.java @@ -273,6 +273,33 @@ class ContainerBuilderTest { assertEquals(List.of(), spec.dnsServers()); } + @Test + void embeddedDnsServerIpReachableOnIsTheResolverWithEmbeddedDnsHandsFirst() { + TestFixture fixture = new TestFixture(); + assertEquals(Optional.empty(), fixture.builder.embeddedDnsServerIpReachableOn(Optional.empty())); + + when(fixture.embeddedDnsServer.getServerIp()).thenReturn(Optional.of("172.17.0.1")); + ContainerSpec spec = fixture.builder.newContainer("alpine") + .withEmbeddedDns() + .build(); + + // Floci running natively listens on the Docker bridge, which every network routes to. + assertEquals(Optional.of(spec.dnsServers().getFirst()), + fixture.builder.embeddedDnsServerIpReachableOn(Optional.of("app-network"))); + } + + @Test + void embeddedDnsServerIpReachableOnNeedsFlocisOwnNetworkWhenFlociRunsInAContainer() { + TestFixture fixture = new TestFixture(); + when(fixture.embeddedDnsServer.getServerIp()).thenReturn(Optional.of("172.18.0.4")); + when(fixture.currentContainerNetworkResolver.resolveNetworkName()).thenReturn(Optional.of("floci-net")); + + assertEquals(Optional.of("172.18.0.4"), fixture.builder.embeddedDnsServerIpReachableOn(Optional.empty())); + assertEquals(Optional.of("172.18.0.4"), + fixture.builder.embeddedDnsServerIpReachableOn(Optional.of("floci-net"))); + assertEquals(Optional.empty(), fixture.builder.embeddedDnsServerIpReachableOn(Optional.of("app-network"))); + } + @Test void withEmbeddedDns_preservesExplicitResolversWithoutAddingFallbacks() { TestFixture fixture = new TestFixture(); diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterArgsTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterArgsTest.java index b2ddc507a2..979260ff5e 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterArgsTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterArgsTest.java @@ -2,12 +2,14 @@ package io.floci.aws.services.eks; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -224,4 +226,25 @@ class EksClusterArgsTest { List args = EksClusterArgs.parseAndValidateClusterArgs(tags, "demo"); assertEquals(List.of("--kubelet-arg=max-pods=250"), args); } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "floci:kubelet-arg:resolv-conf|/etc/own-resolv.conf", + "floci:kubelet-arg|--resolv-conf=/etc/own-resolv.conf", + "floci:kubelet-args|[\"max-pods=250\", \"resolv-conf=/etc/own-resolv.conf\"]"}) + void aKubeletResolvConfTagSetsThePodsResolverFile(String key, String value) { + List args = EksClusterArgs.parseAndValidateClusterArgs(Map.of(key, value), "demo"); + + assertTrue(EksClusterArgs.setsKubeletResolvConf(args), args.toString()); + } + + @Test + void otherArgumentsLeaveThePodsResolverFileToFloci() { + assertFalse(EksClusterArgs.setsKubeletResolvConf(null)); + assertFalse(EksClusterArgs.setsKubeletResolvConf(List.of())); + assertFalse(EksClusterArgs.setsKubeletResolvConf(List.of( + "--kubelet-arg=max-pods=250", + "--kubelet-arg=resolv-conf-extra=x", + "--kube-apiserver-arg=resolv-conf=/etc/own-resolv.conf"))); + } } diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterPodResolvConfTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterPodResolvConfTest.java new file mode 100644 index 0000000000..55ad495d34 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eks/EksClusterPodResolvConfTest.java @@ -0,0 +1,204 @@ +package io.floci.aws.services.eks; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CopyArchiveToContainerCmd; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerDetector; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo; +import io.floci.aws.core.common.docker.ContainerSpec; +import io.floci.aws.core.common.docker.DockerHostResolver; +import io.floci.aws.core.common.docker.PortAllocator; +import io.floci.aws.services.ecr.registry.EcrRegistryManager; +import io.floci.aws.services.eks.model.Cluster; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The resolver file a cluster's k3s node hands its pods: Floci's embedded DNS server alone, so CoreDNS + * forwards to Floci rather than to the public resolver k3s picks when the node's own resolv.conf names + * only Docker's loopback resolver. + */ +class EksClusterPodResolvConfTest { + + private static final String FLOCI_DNS = "172.18.0.2"; + private static final String RESOLV_CONF_ARG = "--resolv-conf=" + EksClusterManager.POD_RESOLV_CONF_PATH; + + private EmulatorConfig config; + private ContainerBuilder containerBuilder; + private ContainerBuilder.Builder builder; + private ContainerLifecycleManager lifecycleManager; + private CopyArchiveToContainerCmd copyCmd; + private EksClusterManager manager; + + /** Each file copied into the container, by its path there, and the ones copied after it started. */ + private final Map copiedFiles = new LinkedHashMap<>(); + private final Set copiedAfterStart = new HashSet<>(); + private String remotePath; + private String copiedEntry; + private boolean started; + + @BeforeEach + void setUp() { + config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS); + when(config.services().eks().defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1"); + when(config.services().eks().embeddedDns()).thenReturn(true); + + containerBuilder = Mockito.mock(ContainerBuilder.class); + builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); + when(containerBuilder.newContainer(anyString())).thenReturn(builder); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); + when(containerBuilder.embeddedDnsServerIpReachableOn(any())).thenReturn(Optional.of(FLOCI_DNS)); + + 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(lifecycleManager.create(any())).thenReturn("container-id"); + when(lifecycleManager.startCreated(any(), any())).thenAnswer(invocation -> { + started = true; + return new ContainerInfo("container-id", Map.of()); + }); + when(dockerClient.copyArchiveToContainerCmd(anyString())).thenAnswer(invocation -> { + remotePath = null; + copiedEntry = null; + return copyCmd; + }); + when(copyCmd.withRemotePath(anyString())).thenAnswer(invocation -> { + remotePath = invocation.getArgument(0); + return copyCmd; + }); + when(copyCmd.withTarInputStream(any())).thenAnswer(invocation -> { + recordFiles(invocation.getArgument(0)); + return copyCmd; + }); + + manager = new EksClusterManager(containerBuilder, lifecycleManager, + Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), + Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), + config, new RegionResolver("us-east-1", "000000000000"), null, null, null, null, null, 0L); + } + + @Test + void podsGetAResolverFileNamingOnlyFlocisDnsServer() { + manager.startCluster(cluster(Map.of())); + + assertTrue(serverArgs().contains(RESOLV_CONF_ARG), serverArgs().toString()); + assertEquals("nameserver " + FLOCI_DNS + "\n", copiedFiles.get(EksClusterManager.POD_RESOLV_CONF_PATH)); + assertFalse(copiedAfterStart.contains(EksClusterManager.POD_RESOLV_CONF_PATH), + "k3s reads the file as it starts, so it must be there first"); + } + + @Test + void podsKeepK3sResolverWhenEmbeddedDnsIsNotRunning() { + when(containerBuilder.embeddedDnsServerIpReachableOn(any())).thenReturn(Optional.empty()); + + manager.startCluster(cluster(Map.of())); + + assertNoResolverFile(); + } + + @Test + void podsKeepK3sResolverWhenTheClustersNetworkCannotReachFlocisDns() { + // A pod given only a resolver it cannot reach would lose the public one k3s picks as well. + when(config.services().eks().dockerNetwork()).thenReturn(Optional.of("cluster-net")); + when(containerBuilder.embeddedDnsServerIpReachableOn(Optional.of("cluster-net"))).thenReturn(Optional.empty()); + + manager.startCluster(cluster(Map.of())); + + assertNoResolverFile(); + } + + @Test + void podsKeepK3sResolverWhenEmbeddedDnsIsOff() { + when(config.services().eks().embeddedDns()).thenReturn(false); + + manager.startCluster(cluster(Map.of())); + + verify(builder, never()).withEmbeddedDns(); + assertNoResolverFile(); + } + + @Test + void aClusterThatSetsTheKubeletsResolverFileKeepsItsOwn() { + manager.startCluster(cluster(Map.of("floci:kubelet-arg:resolv-conf", "/etc/own-resolv.conf"))); + + assertTrue(serverArgs().contains("--kubelet-arg=resolv-conf=/etc/own-resolv.conf"), serverArgs().toString()); + assertNoResolverFile(); + } + + @Test + void aResolverFileThatCannotBeCopiedFailsTheStartAndRemovesTheContainer() { + when(copyCmd.exec()).thenAnswer(invocation -> { + if (EksClusterManager.POD_RESOLV_CONF_TAR_ENTRY.equals(copiedEntry)) { + throw new IllegalStateException("copy refused"); + } + return null; + }); + Cluster cluster = cluster(Map.of()); + + assertThrows(RuntimeException.class, () -> manager.startCluster(cluster)); + + verify(lifecycleManager, never()).startCreated(any(), any()); + verify(lifecycleManager).removeIfExistsStrict(cluster.getDockerName(), true); + } + + private void assertNoResolverFile() { + assertFalse(serverArgs().stream().anyMatch(arg -> arg.startsWith("--resolv-conf")), serverArgs().toString()); + assertFalse(copiedFiles.containsKey(EksClusterManager.POD_RESOLV_CONF_PATH), copiedFiles.keySet().toString()); + } + + private List serverArgs() { + @SuppressWarnings("unchecked") + ArgumentCaptor> cmd = ArgumentCaptor.forClass(List.class); + verify(builder).withCmd(cmd.capture()); + return cmd.getValue(); + } + + private void recordFiles(InputStream archive) throws Exception { + try (TarArchiveInputStream tar = new TarArchiveInputStream(archive)) { + for (TarArchiveEntry entry = tar.getNextEntry(); entry != null; entry = tar.getNextEntry()) { + copiedEntry = entry.getName(); + if (entry.isFile()) { + String path = remotePath + "/" + entry.getName(); + copiedFiles.put(path, new String(tar.readAllBytes(), StandardCharsets.UTF_8)); + if (started) { + copiedAfterStart.add(path); + } + } + } + } + } + + private static Cluster cluster(Map tags) { + Cluster cluster = new Cluster(); + cluster.setName("my-cluster"); + cluster.setTags(tags); + return cluster; + } +} diff --git a/src/test/java/io/floci/aws/services/eks/EksRoute53DnsDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksRoute53DnsDockerIntegrationTest.java index cf619b5adc..2277fbb4ed 100644 --- a/src/test/java/io/floci/aws/services/eks/EksRoute53DnsDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksRoute53DnsDockerIntegrationTest.java @@ -6,10 +6,12 @@ import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerExec; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerSpec; +import io.floci.aws.services.eks.model.Cluster; import io.floci.aws.services.route53.Route53Service; import io.floci.aws.services.route53.model.ResourceRecord; import io.floci.aws.services.route53.model.ResourceRecordSet; import io.floci.aws.services.route53.model.VpcAssociation; +import io.floci.aws.testing.EksTestNode; import io.quarkus.test.junit.QuarkusTest; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -18,12 +20,14 @@ import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -31,13 +35,16 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * Enables embedded DNS on the container it starts itself, so it needs no profile and runs on the * default one alongside the other EKS Docker classes. It needs Docker and a bound embedded DNS * server, and that server only binds when Floci itself runs in a container, so anywhere else the - * class skips. + * class skips. The pod check starts a cluster through {@link EksClusterManager}, which runs a k3s + * container whether or not EKS is mocked, and its pods resolve through CoreDNS. */ @QuarkusTest class EksRoute53DnsDockerIntegrationTest { private static final Logger LOG = Logger.getLogger(EksRoute53DnsDockerIntegrationTest.class); private static final String TEST_IMAGE = "alpine:3.21"; + private static final String ACCOUNT = "000000000000"; + private static final String POD = "dns-lookup-pod"; @Inject DockerClient dockerClient; @@ -54,8 +61,12 @@ class EksRoute53DnsDockerIntegrationTest { @Inject Route53Service route53Service; + @Inject + EksClusterManager eksClusterManager; + private String containerId; private String zoneId; + private Cluster cluster; @BeforeEach void requireDockerAndEmbeddedDns() { @@ -74,6 +85,13 @@ class EksRoute53DnsDockerIntegrationTest { @AfterEach void tearDown() { + if (cluster != null) { + try { + eksClusterManager.stopCluster(cluster); + } catch (Exception e) { + LOG.warnv("Failed to stop test cluster: {0}", e.getMessage()); + } + } if (containerId != null) { try { lifecycleManager.stopAndRemove(containerId, null); @@ -99,19 +117,7 @@ class EksRoute53DnsDockerIntegrationTest { @Test void clusterContainerResolvesRoute53PrivateHostedZoneRecords() throws Exception { - String testDomain = "corp-it-" + UUID.randomUUID().toString().substring(0, 8) + ".internal."; - zoneId = route53Service.createHostedZone( - testDomain, - UUID.randomUUID().toString(), - "EKS IT private zone", - new VpcAssociation("vpc-12345", "us-east-1")).zone().getId(); - - ResourceRecordSet aRrs = new ResourceRecordSet(); - aRrs.setName("db." + testDomain); - aRrs.setType("A"); - aRrs.setTtl(60L); - aRrs.setRecords(List.of(new ResourceRecord("10.0.1.200"))); - route53Service.changeResourceRecordSets(zoneId, List.of(Map.of("action", "CREATE", "rrs", aRrs)), null); + String testDomain = privateZoneWithRecord("10.0.1.200"); ContainerSpec spec = containerBuilder.newContainer(TEST_IMAGE) .withName("floci-eks-dns-test-" + UUID.randomUUID().toString().substring(0, 8)) @@ -135,6 +141,57 @@ class EksRoute53DnsDockerIntegrationTest { assertTrue(output.contains("10.0.1.200"), "Lookup output must contain record IP: " + output); } + @Test + void podsResolveRoute53PrivateHostedZoneRecordsThroughCoreDns() { + String testDomain = privateZoneWithRecord("10.0.1.201"); + cluster = EksTestNode.cluster(ACCOUNT, "dns-pod-" + UUID.randomUUID().toString().substring(0, 8)); + EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(90)); + + // On a user-defined Docker network the node's own resolv.conf names only 127.0.0.11; without the + // resolver file Floci hands k3s, CoreDNS would forward to a public resolver instead of to Floci. + assertTrue(node.execOutput("cat", EksClusterManager.POD_RESOLV_CONF_PATH) + .contains(embeddedDnsServer.getServerIp().orElseThrow()), + "the pods' resolver file must name Floci's DNS server"); + await("CoreDNS rolled out").atMost(Duration.ofSeconds(90)).pollInterval(Duration.ofSeconds(2)) + .until(() -> node.kubectl("rollout", "status", "deployment/coredns", "-n", "kube-system", + "--timeout=10s").exitCode() == 0); + node.apply(""" + apiVersion: v1 + kind: Pod + metadata: + name: %s + namespace: default + spec: + containers: + - name: lookup + image: %s + command: ["sleep", "3600"] + """.formatted(POD, TEST_IMAGE)); + node.awaitPodRunning(POD, Duration.ofSeconds(90)); + + String name = "db." + testDomain.substring(0, testDomain.length() - 1); + String answer = node.kubectlOutput("exec", POD, "--", "nslookup", name); + assertTrue(answer.contains("10.0.1.201"), "a pod must resolve the private record through CoreDNS: " + answer); + } + + /** Creates a private hosted zone with an A record {@code db.} answering {@code address}; returns the zone. */ + private String privateZoneWithRecord(String address) { + String testDomain = "corp-it-" + UUID.randomUUID().toString().substring(0, 8) + ".internal."; + zoneId = route53Service.createHostedZone( + testDomain, + UUID.randomUUID().toString(), + "EKS IT private zone", + new VpcAssociation("vpc-12345", "us-east-1")).zone().getId(); + + ResourceRecordSet aRrs = new ResourceRecordSet(); + aRrs.setName("db." + testDomain); + aRrs.setType("A"); + aRrs.setTtl(60L); + aRrs.setRecords(List.of(new ResourceRecord(address))); + route53Service.changeResourceRecordSets(zoneId, List.of(Map.of("action", "CREATE", "rrs", aRrs)), null); + return testDomain; + } + private boolean isDockerAvailable() { try { dockerClient.pingCmd().exec();